org.el: Exclude tables in src and example blocks.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blobfe435ace23c4ee6af58365d250a8da929946ac2a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
10 ;; Version: 7.8.08
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum))
78 (require 'calendar)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-pcomplete)
105 (require 'org-src)
106 (require 'org-footnote)
108 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
109 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
110 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
111 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
112 (declare-function org-at-clock-log-p "org-clock" ())
113 (declare-function org-clock-timestamps-up "org-clock" ())
114 (declare-function org-clock-timestamps-down "org-clock" ())
116 ;; babel
117 (require 'ob)
118 (require 'ob-table)
119 (require 'ob-lob)
120 (require 'ob-ref)
121 (require 'ob-tangle)
122 (require 'ob-comint)
123 (require 'ob-keys)
125 ;; load languages based on value of `org-babel-load-languages'
126 (defvar org-babel-load-languages)
127 ;;;###autoload
128 (defun org-babel-do-load-languages (sym value)
129 "Load the languages defined in `org-babel-load-languages'."
130 (set-default sym value)
131 (mapc (lambda (pair)
132 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
133 (if active
134 (progn
135 (require (intern (concat "ob-" lang))))
136 (progn
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-execute:" lang)))
139 (funcall 'fmakunbound
140 (intern (concat "org-babel-expand-body:" lang)))))))
141 org-babel-load-languages))
143 (defcustom org-babel-load-languages '((emacs-lisp . t))
144 "Languages which can be evaluated in Org-mode buffers.
145 This list can be used to load support for any of the languages
146 below, note that each language will depend on a different set of
147 system executables and/or Emacs modes. When a language is
148 \"loaded\", then code blocks in that language can be evaluated
149 with `org-babel-execute-src-block' bound by default to C-c
150 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
151 be set to remove code block evaluation from the C-c C-c
152 keybinding. By default only Emacs Lisp (which has no
153 requirements) is loaded."
154 :group 'org-babel
155 :set 'org-babel-do-load-languages
156 :version "24.1"
157 :type '(alist :tag "Babel Languages"
158 :key-type
159 (choice
160 (const :tag "Awk" awk)
161 (const :tag "C" C)
162 (const :tag "R" R)
163 (const :tag "Asymptote" asymptote)
164 (const :tag "Calc" calc)
165 (const :tag "Clojure" clojure)
166 (const :tag "CSS" css)
167 (const :tag "Ditaa" ditaa)
168 (const :tag "Dot" dot)
169 (const :tag "Emacs Lisp" emacs-lisp)
170 (const :tag "Fortran" fortran)
171 (const :tag "Gnuplot" gnuplot)
172 (const :tag "Haskell" haskell)
173 (const :tag "IO" io)
174 (const :tag "Java" java)
175 (const :tag "Javascript" js)
176 (const :tag "LaTeX" latex)
177 (const :tag "Ledger" ledger)
178 (const :tag "Lilypond" lilypond)
179 (const :tag "Maxima" maxima)
180 (const :tag "Matlab" matlab)
181 (const :tag "Mscgen" mscgen)
182 (const :tag "Ocaml" ocaml)
183 (const :tag "Octave" octave)
184 (const :tag "Org" org)
185 (const :tag "Perl" perl)
186 (const :tag "Pico Lisp" picolisp)
187 (const :tag "PlantUML" plantuml)
188 (const :tag "Python" python)
189 (const :tag "Ruby" ruby)
190 (const :tag "Sass" sass)
191 (const :tag "Scala" scala)
192 (const :tag "Scheme" scheme)
193 (const :tag "Screen" screen)
194 (const :tag "Shell Script" sh)
195 (const :tag "Shen" shen)
196 (const :tag "Sql" sql)
197 (const :tag "Sqlite" sqlite))
198 :value-type (boolean :tag "Activate" :value t)))
200 ;;;; Customization variables
201 (defcustom org-clone-delete-id nil
202 "Remove ID property of clones of a subtree.
203 When non-nil, clones of a subtree don't inherit the ID property.
204 Otherwise they inherit the ID property with a new unique
205 identifier."
206 :type 'boolean
207 :version "24.1"
208 :group 'org-id)
210 ;;; Version
212 (defconst org-version "7.8.08"
213 "The version number of the file org.el.")
215 ;;;###autoload
216 (defun org-version (&optional here)
217 "Show the org-mode version in the echo area.
218 With prefix arg HERE, insert it at point."
219 (interactive "P")
220 (let* ((origin default-directory)
221 (version org-version)
222 (git-version)
223 (dir (concat (file-name-directory (locate-library "org")) "../" )))
224 (when (and (file-exists-p (expand-file-name ".git" dir))
225 (executable-find "git"))
226 (unwind-protect
227 (progn
228 (cd dir)
229 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
230 (with-current-buffer "*Shell Command Output*"
231 (goto-char (point-min))
232 (setq git-version (buffer-substring (point) (point-at-eol))))
233 (subst-char-in-string ?- ?. git-version t)
234 (when (string-match "\\S-"
235 (shell-command-to-string
236 "git diff-index --name-only HEAD --"))
237 (setq git-version (concat git-version ".dirty")))
238 (setq version (concat version " (" git-version ")"))))
239 (cd origin)))
240 (setq version (format "Org-mode version %s" version))
241 (if here (insert version))
242 (message version)))
244 ;;; Compatibility constants
246 ;;; The custom variables
248 (defgroup org nil
249 "Outline-based notes management and organizer."
250 :tag "Org"
251 :group 'outlines
252 :group 'calendar)
254 (defcustom org-mode-hook nil
255 "Mode hook for Org-mode, run after the mode was turned on."
256 :group 'org
257 :type 'hook)
259 (defcustom org-load-hook nil
260 "Hook that is run after org.el has been loaded."
261 :group 'org
262 :type 'hook)
264 (defcustom org-log-buffer-setup-hook nil
265 "Hook that is run after an Org log buffer is created."
266 :group 'org
267 :version "24.1"
268 :type 'hook)
270 (defvar org-modules) ; defined below
271 (defvar org-modules-loaded nil
272 "Have the modules been loaded already?")
274 (defun org-load-modules-maybe (&optional force)
275 "Load all extensions listed in `org-modules'."
276 (when (or force (not org-modules-loaded))
277 (mapc (lambda (ext)
278 (condition-case nil (require ext)
279 (error (message "Problems while trying to load feature `%s'" ext))))
280 org-modules)
281 (setq org-modules-loaded t)))
283 (defun org-set-modules (var value)
284 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
285 (set var value)
286 (when (featurep 'org)
287 (org-load-modules-maybe 'force)))
289 (when (org-bound-and-true-p org-modules)
290 (let ((a (member 'org-infojs org-modules)))
291 (and a (setcar a 'org-jsinfo))))
293 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
294 "Modules that should always be loaded together with org.el.
295 If a description starts with <C>, the file is not part of Emacs
296 and loading it will require that you have downloaded and properly installed
297 the org-mode distribution.
299 You can also use this system to load external packages (i.e. neither Org
300 core modules, nor modules from the CONTRIB directory). Just add symbols
301 to the end of the list. If the package is called org-xyz.el, then you need
302 to add the symbol `xyz', and the package must have a call to
304 (provide 'org-xyz)"
305 :group 'org
306 :set 'org-set-modules
307 :type
308 '(set :greedy t
309 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
310 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
311 (const :tag " crypt: Encryption of subtrees" org-crypt)
312 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
313 (const :tag " docview: Links to doc-view buffers" org-docview)
314 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
315 (const :tag " id: Global IDs for identifying entries" org-id)
316 (const :tag " info: Links to Info nodes" org-info)
317 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
318 (const :tag " habit: Track your consistency with habits" org-habit)
319 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
320 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
321 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
322 (const :tag " mew Links to Mew folders/messages" org-mew)
323 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
324 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
325 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
326 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
327 (const :tag " vm: Links to VM folders/messages" org-vm)
328 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
329 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
330 (const :tag " mouse: Additional mouse support" org-mouse)
331 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
333 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
334 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
335 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
336 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
337 (const :tag "C collector: Collect properties into tables" org-collector)
338 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
339 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
340 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
341 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
342 (const :tag "C eval: Include command output as text" org-eval)
343 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
344 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
345 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
346 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
347 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
349 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
351 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
352 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
353 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
354 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
355 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
356 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
357 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
358 (const :tag "C mtags: Support for muse-like tags" org-mtags)
359 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
360 (const :tag "C registry: A registry for Org-mode links" org-registry)
361 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
362 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
363 (const :tag "C secretary: Team management with org-mode" org-secretary)
364 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
365 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
366 (const :tag "C track: Keep up with Org-mode development" org-track)
367 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
368 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
369 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
371 (defcustom org-support-shift-select nil
372 "Non-nil means make shift-cursor commands select text when possible.
374 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
375 start selecting a region, or enlarge regions started in this way.
376 In Org-mode, in special contexts, these same keys are used for
377 other purposes, important enough to compete with shift selection.
378 Org tries to balance these needs by supporting `shift-select-mode'
379 outside these special contexts, under control of this variable.
381 The default of this variable is nil, to avoid confusing behavior. Shifted
382 cursor keys will then execute Org commands in the following contexts:
383 - on a headline, changing TODO state (left/right) and priority (up/down)
384 - on a time stamp, changing the time
385 - in a plain list item, changing the bullet type
386 - in a property definition line, switching between allowed values
387 - in the BEGIN line of a clock table (changing the time block).
388 Outside these contexts, the commands will throw an error.
390 When this variable is t and the cursor is not in a special
391 context, Org-mode will support shift-selection for making and
392 enlarging regions. To make this more effective, the bullet
393 cycling will no longer happen anywhere in an item line, but only
394 if the cursor is exactly on the bullet.
396 If you set this variable to the symbol `always', then the keys
397 will not be special in headlines, property lines, and item lines,
398 to make shift selection work there as well. If this is what you
399 want, you can use the following alternative commands: `C-c C-t'
400 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
401 can be used to switch TODO sets, `C-c -' to cycle item bullet
402 types, and properties can be edited by hand or in column view.
404 However, when the cursor is on a timestamp, shift-cursor commands
405 will still edit the time stamp - this is just too good to give up.
407 XEmacs user should have this variable set to nil, because
408 `shift-select-mode' is in Emacs 23 or later only."
409 :group 'org
410 :type '(choice
411 (const :tag "Never" nil)
412 (const :tag "When outside special context" t)
413 (const :tag "Everywhere except timestamps" always)))
415 (defcustom org-loop-over-headlines-in-active-region nil
416 "Shall some commands act upon headlines in the active region?
418 When set to `t', some commands will be performed in all headlines
419 within the active region.
421 When set to `start-level', some commands will be performed in all
422 headlines within the active region, provided that these headlines
423 are of the same level than the first one.
425 When set to a string, those commands will be performed on the
426 matching headlines within the active region. Such string must be
427 a tags/property/todo match as it is used in the agenda tags view.
429 The list of commands is: `org-schedule', `org-deadline',
430 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
431 `org-archive-to-archive-sibling'. The archiving commands skip
432 already archived entries."
433 :type '(choice (const :tag "Don't loop" nil)
434 (const :tag "All headlines in active region" t)
435 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
436 (string :tag "Tags/Property/Todo matcher"))
437 :version "24.1"
438 :group 'org-todo
439 :group 'org-archive)
441 (defgroup org-startup nil
442 "Options concerning startup of Org-mode."
443 :tag "Org Startup"
444 :group 'org)
446 (defcustom org-startup-folded t
447 "Non-nil means entering Org-mode will switch to OVERVIEW.
448 This can also be configured on a per-file basis by adding one of
449 the following lines anywhere in the buffer:
451 #+STARTUP: fold (or `overview', this is equivalent)
452 #+STARTUP: nofold (or `showall', this is equivalent)
453 #+STARTUP: content
454 #+STARTUP: showeverything"
455 :group 'org-startup
456 :type '(choice
457 (const :tag "nofold: show all" nil)
458 (const :tag "fold: overview" t)
459 (const :tag "content: all headlines" content)
460 (const :tag "show everything, even drawers" showeverything)))
462 (defcustom org-startup-truncated t
463 "Non-nil means entering Org-mode will set `truncate-lines'.
464 This is useful since some lines containing links can be very long and
465 uninteresting. Also tables look terrible when wrapped."
466 :group 'org-startup
467 :type 'boolean)
469 (defcustom org-startup-indented nil
470 "Non-nil means turn on `org-indent-mode' on startup.
471 This can also be configured on a per-file basis by adding one of
472 the following lines anywhere in the buffer:
474 #+STARTUP: indent
475 #+STARTUP: noindent"
476 :group 'org-structure
477 :type '(choice
478 (const :tag "Not" nil)
479 (const :tag "Globally (slow on startup in large files)" t)))
481 (defcustom org-use-sub-superscripts t
482 "Non-nil means interpret \"_\" and \"^\" for export.
483 When this option is turned on, you can use TeX-like syntax for sub- and
484 superscripts. Several characters after \"_\" or \"^\" will be
485 considered as a single item - so grouping with {} is normally not
486 needed. For example, the following things will be parsed as single
487 sub- or superscripts.
489 10^24 or 10^tau several digits will be considered 1 item.
490 10^-12 or 10^-tau a leading sign with digits or a word
491 x^2-y^3 will be read as x^2 - y^3, because items are
492 terminated by almost any nonword/nondigit char.
493 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
495 Still, ambiguity is possible - so when in doubt use {} to enclose the
496 sub/superscript. If you set this variable to the symbol `{}',
497 the braces are *required* in order to trigger interpretations as
498 sub/superscript. This can be helpful in documents that need \"_\"
499 frequently in plain text.
501 Not all export backends support this, but HTML does.
503 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
504 :group 'org-startup
505 :group 'org-export-translation
506 :version "24.1"
507 :type '(choice
508 (const :tag "Always interpret" t)
509 (const :tag "Only with braces" {})
510 (const :tag "Never interpret" nil)))
512 (if (fboundp 'defvaralias)
513 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
516 (defcustom org-startup-with-beamer-mode nil
517 "Non-nil means turn on `org-beamer-mode' on startup.
518 This can also be configured on a per-file basis by adding one of
519 the following lines anywhere in the buffer:
521 #+STARTUP: beamer"
522 :group 'org-startup
523 :version "24.1"
524 :type 'boolean)
526 (defcustom org-startup-align-all-tables nil
527 "Non-nil means align all tables when visiting a file.
528 This is useful when the column width in tables is forced with <N> cookies
529 in table fields. Such tables will look correct only after the first re-align.
530 This can also be configured on a per-file basis by adding one of
531 the following lines anywhere in the buffer:
532 #+STARTUP: align
533 #+STARTUP: noalign"
534 :group 'org-startup
535 :type 'boolean)
537 (defcustom org-startup-with-inline-images nil
538 "Non-nil means show inline images when loading a new Org file.
539 This can also be configured on a per-file basis by adding one of
540 the following lines anywhere in the buffer:
541 #+STARTUP: inlineimages
542 #+STARTUP: noinlineimages"
543 :group 'org-startup
544 :version "24.1"
545 :type 'boolean)
547 (defcustom org-insert-mode-line-in-empty-file nil
548 "Non-nil means insert the first line setting Org-mode in empty files.
549 When the function `org-mode' is called interactively in an empty file, this
550 normally means that the file name does not automatically trigger Org-mode.
551 To ensure that the file will always be in Org-mode in the future, a
552 line enforcing Org-mode will be inserted into the buffer, if this option
553 has been set."
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-replace-disputed-keys nil
558 "Non-nil means use alternative key bindings for some keys.
559 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
560 These keys are also used by other packages like shift-selection-mode'
561 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
562 If you want to use Org-mode together with one of these other modes,
563 or more generally if you would like to move some Org-mode commands to
564 other keys, set this variable and configure the keys with the variable
565 `org-disputed-keys'.
567 This option is only relevant at load-time of Org-mode, and must be set
568 *before* org.el is loaded. Changing it requires a restart of Emacs to
569 become effective."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-use-extra-keys nil
574 "Non-nil means use extra key sequence definitions for certain commands.
575 This happens automatically if you run XEmacs or if `window-system'
576 is nil. This variable lets you do the same manually. You must
577 set it before loading org.
579 Example: on Carbon Emacs 22 running graphically, with an external
580 keyboard on a Powerbook, the default way of setting M-left might
581 not work for either Alt or ESC. Setting this variable will make
582 it work for ESC."
583 :group 'org-startup
584 :type 'boolean)
586 (if (fboundp 'defvaralias)
587 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
589 (defcustom org-disputed-keys
590 '(([(shift up)] . [(meta p)])
591 ([(shift down)] . [(meta n)])
592 ([(shift left)] . [(meta -)])
593 ([(shift right)] . [(meta +)])
594 ([(control shift right)] . [(meta shift +)])
595 ([(control shift left)] . [(meta shift -)]))
596 "Keys for which Org-mode and other modes compete.
597 This is an alist, cars are the default keys, second element specifies
598 the alternative to use when `org-replace-disputed-keys' is t.
600 Keys can be specified in any syntax supported by `define-key'.
601 The value of this option takes effect only at Org-mode's startup,
602 therefore you'll have to restart Emacs to apply it after changing."
603 :group 'org-startup
604 :type 'alist)
606 (defun org-key (key)
607 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
608 Or return the original if not disputed.
609 Also apply the translations defined in `org-xemacs-key-equivalents'."
610 (when org-replace-disputed-keys
611 (let* ((nkey (key-description key))
612 (x (org-find-if (lambda (x)
613 (equal (key-description (car x)) nkey))
614 org-disputed-keys)))
615 (setq key (if x (cdr x) key))))
616 (when (featurep 'xemacs)
617 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
618 key)
620 (defun org-find-if (predicate seq)
621 (catch 'exit
622 (while seq
623 (if (funcall predicate (car seq))
624 (throw 'exit (car seq))
625 (pop seq)))))
627 (defun org-defkey (keymap key def)
628 "Define a key, possibly translated, as returned by `org-key'."
629 (define-key keymap (org-key key) def))
631 (defcustom org-ellipsis nil
632 "The ellipsis to use in the Org-mode outline.
633 When nil, just use the standard three dots. When a string, use that instead,
634 When a face, use the standard 3 dots, but with the specified face.
635 The change affects only Org-mode (which will then use its own display table).
636 Changing this requires executing `M-x org-mode' in a buffer to become
637 effective."
638 :group 'org-startup
639 :type '(choice (const :tag "Default" nil)
640 (face :tag "Face" :value org-warning)
641 (string :tag "String" :value "...#")))
643 (defvar org-display-table nil
644 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
646 (defgroup org-keywords nil
647 "Keywords in Org-mode."
648 :tag "Org Keywords"
649 :group 'org)
651 (defcustom org-deadline-string "DEADLINE:"
652 "String to mark deadline entries.
653 A deadline is this string, followed by a time stamp. Should be a word,
654 terminated by a colon. You can insert a schedule keyword and
655 a timestamp with \\[org-deadline].
656 Changes become only effective after restarting Emacs."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-scheduled-string "SCHEDULED:"
661 "String to mark scheduled TODO entries.
662 A schedule is this string, followed by a time stamp. Should be a word,
663 terminated by a colon. You can insert a schedule keyword and
664 a timestamp with \\[org-schedule].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-closed-string "CLOSED:"
670 "String used as the prefix for timestamps logging closing a TODO entry."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-clock-string "CLOCK:"
675 "String used as prefix for timestamps clocking work hours on an item."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-comment-string "COMMENT"
680 "Entries starting with this keyword will never be exported.
681 An entry can be toggled between COMMENT and normal with
682 \\[org-toggle-comment].
683 Changes become only effective after restarting Emacs."
684 :group 'org-keywords
685 :type 'string)
687 (defcustom org-quote-string "QUOTE"
688 "Entries starting with this keyword will be exported in fixed-width font.
689 Quoting applies only to the text in the entry following the headline, and does
690 not extend beyond the next headline, even if that is lower level.
691 An entry can be toggled between QUOTE and normal with
692 \\[org-toggle-fixed-width-section]."
693 :group 'org-keywords
694 :type 'string)
696 (defconst org-repeat-re
697 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
698 "Regular expression for specifying repeated events.
699 After a match, group 1 contains the repeat expression.")
701 (defgroup org-structure nil
702 "Options concerning the general structure of Org-mode files."
703 :tag "Org Structure"
704 :group 'org)
706 (defgroup org-reveal-location nil
707 "Options about how to make context of a location visible."
708 :tag "Org Reveal Location"
709 :group 'org-structure)
711 (defconst org-context-choice
712 '(choice
713 (const :tag "Always" t)
714 (const :tag "Never" nil)
715 (repeat :greedy t :tag "Individual contexts"
716 (cons
717 (choice :tag "Context"
718 (const agenda)
719 (const org-goto)
720 (const occur-tree)
721 (const tags-tree)
722 (const link-search)
723 (const mark-goto)
724 (const bookmark-jump)
725 (const isearch)
726 (const default))
727 (boolean))))
728 "Contexts for the reveal options.")
730 (defcustom org-show-hierarchy-above '((default . t))
731 "Non-nil means show full hierarchy when revealing a location.
732 Org-mode often shows locations in an org-mode file which might have
733 been invisible before. When this is set, the hierarchy of headings
734 above the exposed location is shown.
735 Turning this off for example for sparse trees makes them very compact.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. Valid contexts are
738 agenda when exposing an entry from the agenda
739 org-goto when using the command `org-goto' on key C-c C-j
740 occur-tree when using the command `org-occur' on key C-c /
741 tags-tree when constructing a sparse tree based on tags matches
742 link-search when exposing search matches associated with a link
743 mark-goto when exposing the jump goal of a mark
744 bookmark-jump when exposing a bookmark location
745 isearch when exiting from an incremental search
746 default default for all contexts not set explicitly"
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-following-heading '((default . nil))
751 "Non-nil means show following heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the heading following the
754 match is shown.
755 Turning this off for example for sparse trees makes them very compact,
756 but makes it harder to edit the location of the match. In such a case,
757 use the command \\[org-reveal] to show more context.
758 Instead of t, this can also be an alist specifying this option for different
759 contexts. See `org-show-hierarchy-above' for valid contexts."
760 :group 'org-reveal-location
761 :type org-context-choice)
763 (defcustom org-show-siblings '((default . nil) (isearch t))
764 "Non-nil means show all sibling heading when revealing a location.
765 Org-mode often shows locations in an org-mode file which might have
766 been invisible before. When this is set, the sibling of the current entry
767 heading are all made visible. If `org-show-hierarchy-above' is t,
768 the same happens on each level of the hierarchy above the current entry.
770 By default this is on for the isearch context, off for all other contexts.
771 Turning this off for example for sparse trees makes them very compact,
772 but makes it harder to edit the location of the match. In such a case,
773 use the command \\[org-reveal] to show more context.
774 Instead of t, this can also be an alist specifying this option for different
775 contexts. See `org-show-hierarchy-above' for valid contexts."
776 :group 'org-reveal-location
777 :type org-context-choice)
779 (defcustom org-show-entry-below '((default . nil))
780 "Non-nil means show the entry below a headline when revealing a location.
781 Org-mode often shows locations in an org-mode file which might have
782 been invisible before. When this is set, the text below the headline that is
783 exposed is also shown.
785 By default this is off for all contexts.
786 Instead of t, this can also be an alist specifying this option for different
787 contexts. See `org-show-hierarchy-above' for valid contexts."
788 :group 'org-reveal-location
789 :type org-context-choice)
791 (defcustom org-indirect-buffer-display 'other-window
792 "How should indirect tree buffers be displayed?
793 This applies to indirect buffers created with the commands
794 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
795 Valid values are:
796 current-window Display in the current window
797 other-window Just display in another window.
798 dedicated-frame Create one new frame, and re-use it each time.
799 new-frame Make a new frame each time. Note that in this case
800 previously-made indirect buffers are kept, and you need to
801 kill these buffers yourself."
802 :group 'org-structure
803 :group 'org-agenda-windows
804 :type '(choice
805 (const :tag "In current window" current-window)
806 (const :tag "In current frame, other window" other-window)
807 (const :tag "Each time a new frame" new-frame)
808 (const :tag "One dedicated frame" dedicated-frame)))
810 (defcustom org-use-speed-commands nil
811 "Non-nil means activate single letter commands at beginning of a headline.
812 This may also be a function to test for appropriate locations where speed
813 commands should be active."
814 :group 'org-structure
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "At beginning of headline stars" t)
818 (function)))
820 (defcustom org-speed-commands-user nil
821 "Alist of additional speed commands.
822 This list will be checked before `org-speed-commands-default'
823 when the variable `org-use-speed-commands' is non-nil
824 and when the cursor is at the beginning of a headline.
825 The car if each entry is a string with a single letter, which must
826 be assigned to `self-insert-command' in the global map.
827 The cdr is either a command to be called interactively, a function
828 to be called, or a form to be evaluated.
829 An entry that is just a list with a single string will be interpreted
830 as a descriptive headline that will be added when listing the speed
831 commands in the Help buffer using the `?' speed command."
832 :group 'org-structure
833 :type '(repeat :value ("k" . ignore)
834 (choice :value ("k" . ignore)
835 (list :tag "Descriptive Headline" (string :tag "Headline"))
836 (cons :tag "Letter and Command"
837 (string :tag "Command letter")
838 (choice
839 (function)
840 (sexp))))))
842 (defgroup org-cycle nil
843 "Options concerning visibility cycling in Org-mode."
844 :tag "Org Cycle"
845 :group 'org-structure)
847 (defcustom org-cycle-skip-children-state-if-no-children t
848 "Non-nil means skip CHILDREN state in entries that don't have any."
849 :group 'org-cycle
850 :type 'boolean)
852 (defcustom org-cycle-max-level nil
853 "Maximum level which should still be subject to visibility cycling.
854 Levels higher than this will, for cycling, be treated as text, not a headline.
855 When `org-odd-levels-only' is set, a value of N in this variable actually
856 means 2N-1 stars as the limiting headline.
857 When nil, cycle all levels.
858 Note that the limiting level of cycling is also influenced by
859 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
860 `org-inlinetask-min-level' is, cycling will be limited to levels one less
861 than its value."
862 :group 'org-cycle
863 :type '(choice
864 (const :tag "No limit" nil)
865 (integer :tag "Maximum level")))
867 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
868 "Names of drawers. Drawers are not opened by cycling on the headline above.
869 Drawers only open with a TAB on the drawer line itself. A drawer looks like
870 this:
871 :DRAWERNAME:
872 .....
873 :END:
874 The drawer \"PROPERTIES\" is special for capturing properties through
875 the property API.
877 Drawers can be defined on the per-file basis with a line like:
879 #+DRAWERS: HIDDEN STATE PROPERTIES"
880 :group 'org-structure
881 :group 'org-cycle
882 :type '(repeat (string :tag "Drawer Name")))
884 (defcustom org-hide-block-startup nil
885 "Non-nil means entering Org-mode will fold all blocks.
886 This can also be set in on a per-file basis with
888 #+STARTUP: hideblocks
889 #+STARTUP: showblocks"
890 :group 'org-startup
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-global-at-bob nil
895 "Cycle globally if cursor is at beginning of buffer and not at a headline.
896 This makes it possible to do global cycling without having to use S-TAB or
897 \\[universal-argument] TAB. For this special case to work, the first line \
898 of the buffer
899 must not be a headline - it may be empty or some other text. When used in
900 this way, `org-cycle-hook' is disables temporarily, to make sure the
901 cursor stays at the beginning of the buffer.
902 When this option is nil, don't do anything special at the beginning
903 of the buffer."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-level-after-item/entry-creation t
908 "Non-nil means cycle entry level or item indentation in new empty entries.
910 When the cursor is at the end of an empty headline, i.e with only stars
911 and maybe a TODO keyword, TAB will then switch the entry to become a child,
912 and then all possible ancestor states, before returning to the original state.
913 This makes data entry extremely fast: M-RET to create a new headline,
914 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
916 When the cursor is at the end of an empty plain list item, one TAB will
917 make it a subitem, two or more tabs will back up to make this an item
918 higher up in the item hierarchy."
919 :group 'org-cycle
920 :type 'boolean)
922 (defcustom org-cycle-emulate-tab t
923 "Where should `org-cycle' emulate TAB.
924 nil Never
925 white Only in completely white lines
926 whitestart Only at the beginning of lines, before the first non-white char
927 t Everywhere except in headlines
928 exc-hl-bol Everywhere except at the start of a headline
929 If TAB is used in a place where it does not emulate TAB, the current subtree
930 visibility is cycled."
931 :group 'org-cycle
932 :type '(choice (const :tag "Never" nil)
933 (const :tag "Only in completely white lines" white)
934 (const :tag "Before first char in a line" whitestart)
935 (const :tag "Everywhere except in headlines" t)
936 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
939 (defcustom org-cycle-separator-lines 2
940 "Number of empty lines needed to keep an empty line between collapsed trees.
941 If you leave an empty line between the end of a subtree and the following
942 headline, this empty line is hidden when the subtree is folded.
943 Org-mode will leave (exactly) one empty line visible if the number of
944 empty lines is equal or larger to the number given in this variable.
945 So the default 2 means at least 2 empty lines after the end of a subtree
946 are needed to produce free space between a collapsed subtree and the
947 following headline.
949 If the number is negative, and the number of empty lines is at least -N,
950 all empty lines are shown.
952 Special case: when 0, never leave empty lines in collapsed view."
953 :group 'org-cycle
954 :type 'integer)
955 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
957 (defcustom org-pre-cycle-hook nil
958 "Hook that is run before visibility cycling is happening.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that will be set right after running this hook. The
961 argument is a symbol. Before a global state change, it can have the values
962 `overview', `content', or `all'. Before a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
968 org-cycle-hide-drawers
969 org-cycle-show-empty-lines
970 org-optimize-window-after-visibility-change)
971 "Hook that is run after `org-cycle' has changed the buffer visibility.
972 The function(s) in this hook must accept a single argument which indicates
973 the new state that was set by the most recent `org-cycle' command. The
974 argument is a symbol. After a global state change, it can have the values
975 `overview', `content', or `all'. After a local state change, it can have
976 the values `folded', `children', or `subtree'."
977 :group 'org-cycle
978 :type 'hook)
980 (defgroup org-edit-structure nil
981 "Options concerning structure editing in Org-mode."
982 :tag "Org Edit Structure"
983 :group 'org-structure)
985 (defcustom org-odd-levels-only nil
986 "Non-nil means skip even levels and only use odd levels for the outline.
987 This has the effect that two stars are being added/taken away in
988 promotion/demotion commands. It also influences how levels are
989 handled by the exporters.
990 Changing it requires restart of `font-lock-mode' to become effective
991 for fontification also in regions already fontified.
992 You may also set this on a per-file basis by adding one of the following
993 lines to the buffer:
995 #+STARTUP: odd
996 #+STARTUP: oddeven"
997 :group 'org-edit-structure
998 :group 'org-appearance
999 :type 'boolean)
1001 (defcustom org-adapt-indentation t
1002 "Non-nil means adapt indentation to outline node level.
1004 When this variable is set, Org assumes that you write outlines by
1005 indenting text in each node to align with the headline (after the stars).
1006 The following issues are influenced by this variable:
1008 - When this is set and the *entire* text in an entry is indented, the
1009 indentation is increased by one space in a demotion command, and
1010 decreased by one in a promotion command. If any line in the entry
1011 body starts with text at column 0, indentation is not changed at all.
1013 - Property drawers and planning information is inserted indented when
1014 this variable s set. When nil, they will not be indented.
1016 - TAB indents a line relative to context. The lines below a headline
1017 will be indented when this variable is set.
1019 Note that this is all about true indentation, by adding and removing
1020 space characters. See also `org-indent.el' which does level-dependent
1021 indentation in a virtual way, i.e. at display time in Emacs."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-special-ctrl-a/e nil
1026 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1028 When t, `C-a' will bring back the cursor to the beginning of the
1029 headline text, i.e. after the stars and after a possible TODO
1030 keyword. In an item, this will be the position after bullet and
1031 check-box, if any. When the cursor is already at that position,
1032 another `C-a' will bring it to the beginning of the line.
1034 `C-e' will jump to the end of the headline, ignoring the presence
1035 of tags in the headline. A second `C-e' will then jump to the
1036 true end of the line, after any tags. This also means that, when
1037 this variable is non-nil, `C-e' also will never jump beyond the
1038 end of the heading of a folded section, i.e. not after the
1039 ellipses.
1041 When set to the symbol `reversed', the first `C-a' or `C-e' works
1042 normally, going to the true line boundary first. Only a directly
1043 following, identical keypress will bring the cursor to the
1044 special positions.
1046 This may also be a cons cell where the behavior for `C-a' and
1047 `C-e' is set separately."
1048 :group 'org-edit-structure
1049 :type '(choice
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet and before tags first" t)
1052 (const :tag "reversed: true line boundary first" reversed)
1053 (cons :tag "Set C-a and C-e separately"
1054 (choice :tag "Special C-a"
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet first" t)
1057 (const :tag "reversed: before stars/bullet first" reversed))
1058 (choice :tag "Special C-e"
1059 (const :tag "off" nil)
1060 (const :tag "on: before tags first" t)
1061 (const :tag "reversed: after tags first" reversed)))))
1062 (if (fboundp 'defvaralias)
1063 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1065 (defcustom org-special-ctrl-k nil
1066 "Non-nil means `C-k' will behave specially in headlines.
1067 When nil, `C-k' will call the default `kill-line' command.
1068 When t, the following will happen while the cursor is in the headline:
1070 - When the cursor is at the beginning of a headline, kill the entire
1071 line and possible the folded subtree below the line.
1072 - When in the middle of the headline text, kill the headline up to the tags.
1073 - When after the headline text, kill the tags."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-ctrl-k-protect-subtree nil
1078 "Non-nil means, do not delete a hidden subtree with C-k.
1079 When set to the symbol `error', simply throw an error when C-k is
1080 used to kill (part-of) a headline that has hidden text behind it.
1081 Any other non-nil value will result in a query to the user, if it is
1082 OK to kill that hidden subtree. When nil, kill without remorse."
1083 :group 'org-edit-structure
1084 :version "24.1"
1085 :type '(choice
1086 (const :tag "Do not protect hidden subtrees" nil)
1087 (const :tag "Protect hidden subtrees with a security query" t)
1088 (const :tag "Never kill a hidden subtree with C-k" error)))
1090 (defcustom org-catch-invisible-edits nil
1091 "Check if in invisible region before inserting or deleting a character.
1092 Valid values are:
1094 nil Do not check, so just do invisible edits.
1095 error Throw an error and do nothing.
1096 show Make point visible, and do the requested edit.
1097 show-and-error Make point visible, then throw an error and abort the edit.
1098 smart Make point visible, and do insertion/deletion if it is
1099 adjacent to visible text and the change feels predictable.
1100 Never delete a previously invisible character or add in the
1101 middle or right after an invisible region. Basically, this
1102 allows insertion and backward-delete right before ellipses.
1103 FIXME: maybe in this case we should not even show?"
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not check" nil)
1108 (const :tag "Throw error when trying to edit" error)
1109 (const :tag "Unhide, but do not do the edit" show-and-error)
1110 (const :tag "Show invisible part and do the edit" show)
1111 (const :tag "Be smart and do the right thing" smart)))
1113 (defcustom org-yank-folded-subtrees t
1114 "Non-nil means when yanking subtrees, fold them.
1115 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1116 it starts with a heading and all other headings in it are either children
1117 or siblings, then fold all the subtrees. However, do this only if no
1118 text after the yank would be swallowed into a folded tree by this action."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-yank-adjusted-subtrees nil
1123 "Non-nil means when yanking subtrees, adjust the level.
1124 With this setting, `org-paste-subtree' is used to insert the subtree, see
1125 this function for details."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defcustom org-M-RET-may-split-line '((default . t))
1130 "Non-nil means M-RET will split the line at the cursor position.
1131 When nil, it will go to the end of the line before making a
1132 new line.
1133 You may also set this option in a different way for different
1134 contexts. Valid contexts are:
1136 headline when creating a new headline
1137 item when creating a new item
1138 table in a table field
1139 default the value to be used for all contexts not explicitly
1140 customized"
1141 :group 'org-structure
1142 :group 'org-table
1143 :type '(choice
1144 (const :tag "Always" t)
1145 (const :tag "Never" nil)
1146 (repeat :greedy t :tag "Individual contexts"
1147 (cons
1148 (choice :tag "Context"
1149 (const headline)
1150 (const item)
1151 (const table)
1152 (const default))
1153 (boolean)))))
1156 (defcustom org-insert-heading-respect-content nil
1157 "Non-nil means insert new headings after the current subtree.
1158 When nil, the new heading is created directly after the current line.
1159 The commands \\[org-insert-heading-respect-content] and
1160 \\[org-insert-todo-heading-respect-content] turn this variable on
1161 for the duration of the command."
1162 :group 'org-structure
1163 :type 'boolean)
1165 (defcustom org-blank-before-new-entry '((heading . auto)
1166 (plain-list-item . auto))
1167 "Should `org-insert-heading' leave a blank line before new heading/item?
1168 The value is an alist, with `heading' and `plain-list-item' as CAR,
1169 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1170 which case Org will look at the surrounding headings/items and try to
1171 make an intelligent decision whether to insert a blank line or not.
1173 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1174 set, the setting here is ignored and no empty line is inserted, to avoid
1175 breaking the list structure."
1176 :group 'org-edit-structure
1177 :type '(list
1178 (cons (const heading)
1179 (choice (const :tag "Never" nil)
1180 (const :tag "Always" t)
1181 (const :tag "Auto" auto)))
1182 (cons (const plain-list-item)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))))
1187 (defcustom org-insert-heading-hook nil
1188 "Hook being run after inserting a new heading."
1189 :group 'org-edit-structure
1190 :type 'hook)
1192 (defcustom org-enable-fixed-width-editor t
1193 "Non-nil means lines starting with \":\" are treated as fixed-width.
1194 This currently only means they are never auto-wrapped.
1195 When nil, such lines will be treated like ordinary lines.
1196 See also the QUOTE keyword."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defcustom org-goto-auto-isearch t
1201 "Non-nil means typing characters in `org-goto' starts incremental search."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defgroup org-sparse-trees nil
1206 "Options concerning sparse trees in Org-mode."
1207 :tag "Org Sparse Trees"
1208 :group 'org-structure)
1210 (defcustom org-highlight-sparse-tree-matches t
1211 "Non-nil means highlight all matches that define a sparse tree.
1212 The highlights will automatically disappear the next time the buffer is
1213 changed by an edit command."
1214 :group 'org-sparse-trees
1215 :type 'boolean)
1217 (defcustom org-remove-highlights-with-change t
1218 "Non-nil means any change to the buffer will remove temporary highlights.
1219 Such highlights are created by `org-occur' and `org-clock-display'.
1220 When nil, `C-c C-c needs to be used to get rid of the highlights.
1221 The highlights created by `org-preview-latex-fragment' always need
1222 `C-c C-c' to be removed."
1223 :group 'org-sparse-trees
1224 :group 'org-time
1225 :type 'boolean)
1228 (defcustom org-occur-hook '(org-first-headline-recenter)
1229 "Hook that is run after `org-occur' has constructed a sparse tree.
1230 This can be used to recenter the window to show as much of the structure
1231 as possible."
1232 :group 'org-sparse-trees
1233 :type 'hook)
1235 (defgroup org-imenu-and-speedbar nil
1236 "Options concerning imenu and speedbar in Org-mode."
1237 :tag "Org Imenu and Speedbar"
1238 :group 'org-structure)
1240 (defcustom org-imenu-depth 2
1241 "The maximum level for Imenu access to Org-mode headlines.
1242 This also applied for speedbar access."
1243 :group 'org-imenu-and-speedbar
1244 :type 'integer)
1246 (defgroup org-table nil
1247 "Options concerning tables in Org-mode."
1248 :tag "Org Table"
1249 :group 'org)
1251 (defcustom org-enable-table-editor 'optimized
1252 "Non-nil means lines starting with \"|\" are handled by the table editor.
1253 When nil, such lines will be treated like ordinary lines.
1255 When equal to the symbol `optimized', the table editor will be optimized to
1256 do the following:
1257 - Automatic overwrite mode in front of whitespace in table fields.
1258 This makes the structure of the table stay in tact as long as the edited
1259 field does not exceed the column width.
1260 - Minimize the number of realigns. Normally, the table is aligned each time
1261 TAB or RET are pressed to move to another field. With optimization this
1262 happens only if changes to a field might have changed the column width.
1263 Optimization requires replacing the functions `self-insert-command',
1264 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1265 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1266 very good at guessing when a re-align will be necessary, but you can always
1267 force one with \\[org-ctrl-c-ctrl-c].
1269 If you would like to use the optimized version in Org-mode, but the
1270 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1272 This variable can be used to turn on and off the table editor during a session,
1273 but in order to toggle optimization, a restart is required.
1275 See also the variable `org-table-auto-blank-field'."
1276 :group 'org-table
1277 :type '(choice
1278 (const :tag "off" nil)
1279 (const :tag "on" t)
1280 (const :tag "on, optimized" optimized)))
1282 (defcustom org-self-insert-cluster-for-undo t
1283 "Non-nil means cluster self-insert commands for undo when possible.
1284 If this is set, then, like in the Emacs command loop, 20 consecutive
1285 characters will be undone together.
1286 This is configurable, because there is some impact on typing performance."
1287 :group 'org-table
1288 :type 'boolean)
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1294 :group 'org-table-editing
1295 :type 'boolean)
1297 (defgroup org-link nil
1298 "Options concerning links in Org-mode."
1299 :tag "Org Link"
1300 :group 'org)
1302 (defvar org-link-abbrev-alist-local nil
1303 "Buffer-local version of `org-link-abbrev-alist', which see.
1304 The value of this is taken from the #+LINK lines.")
1305 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1307 (defcustom org-link-abbrev-alist nil
1308 "Alist of link abbreviations.
1309 The car of each element is a string, to be replaced at the start of a link.
1310 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1311 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1313 [[linkkey:tag][description]]
1315 The 'linkkey' must be a word word, starting with a letter, followed
1316 by letters, numbers, '-' or '_'.
1318 If REPLACE is a string, the tag will simply be appended to create the link.
1319 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1320 the placeholder \"%h\" will cause a url-encoded version of the tag to
1321 be inserted at that point (see the function `url-hexify-string').
1323 REPLACE may also be a function that will be called with the tag as the
1324 only argument to create the link, which should be returned as a string.
1326 See the manual for examples."
1327 :group 'org-link
1328 :type '(repeat
1329 (cons
1330 (string :tag "Protocol")
1331 (choice
1332 (string :tag "Format")
1333 (function)))))
1335 (defcustom org-descriptive-links t
1336 "Non-nil means Org will display descriptive links.
1337 E.g. [[http://orgmode.org][Org website]] will be displayed as
1338 \"Org Website\", hiding the link itself and just displaying its
1339 description. When set to `nil', Org will display the full links
1340 literally.
1342 You can interactively set the value of this variable by calling
1343 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1344 :group 'org-link
1345 :type 'boolean)
1347 (defcustom org-link-file-path-type 'adaptive
1348 "How the path name in file links should be stored.
1349 Valid values are:
1351 relative Relative to the current directory, i.e. the directory of the file
1352 into which the link is being inserted.
1353 absolute Absolute path, if possible with ~ for home directory.
1354 noabbrev Absolute path, no abbreviation of home directory.
1355 adaptive Use relative path for files in the current directory and sub-
1356 directories of it. For other files, use an absolute path."
1357 :group 'org-link
1358 :type '(choice
1359 (const relative)
1360 (const absolute)
1361 (const noabbrev)
1362 (const adaptive)))
1364 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1365 "Types of links that should be activated in Org-mode files.
1366 This is a list of symbols, each leading to the activation of a certain link
1367 type. In principle, it does not hurt to turn on most link types - there may
1368 be a small gain when turning off unused link types. The types are:
1370 bracket The recommended [[link][description]] or [[link]] links with hiding.
1371 angle Links in angular brackets that may contain whitespace like
1372 <bbdb:Carsten Dominik>.
1373 plain Plain links in normal text, no whitespace, like http://google.com.
1374 radio Text that is matched by a radio target, see manual for details.
1375 tag Tag settings in a headline (link to tag search).
1376 date Time stamps (link to calendar).
1377 footnote Footnote labels.
1379 Changing this variable requires a restart of Emacs to become effective."
1380 :group 'org-link
1381 :type '(set :greedy t
1382 (const :tag "Double bracket links" bracket)
1383 (const :tag "Angular bracket links" angle)
1384 (const :tag "Plain text links" plain)
1385 (const :tag "Radio target matches" radio)
1386 (const :tag "Tags" tag)
1387 (const :tag "Timestamps" date)
1388 (const :tag "Footnotes" footnote)))
1390 (defcustom org-make-link-description-function nil
1391 "Function to use to generate link descriptions from links.
1392 If nil the link location will be used. This function must take
1393 two parameters; the first is the link and the second the
1394 description `org-insert-link' has generated, and should return the
1395 description to use."
1396 :group 'org-link
1397 :type 'function)
1399 (defgroup org-link-store nil
1400 "Options concerning storing links in Org-mode."
1401 :tag "Org Store Link"
1402 :group 'org-link)
1404 (defcustom org-email-link-description-format "Email %c: %.30s"
1405 "Format of the description part of a link to an email or usenet message.
1406 The following %-escapes will be replaced by corresponding information:
1408 %F full \"From\" field
1409 %f name, taken from \"From\" field, address if no name
1410 %T full \"To\" field
1411 %t first name in \"To\" field, address if no name
1412 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1413 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1414 %s subject
1415 %d date
1416 %m message-id.
1418 You may use normal field width specification between the % and the letter.
1419 This is for example useful to limit the length of the subject.
1421 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1422 :group 'org-link-store
1423 :type 'string)
1425 (defcustom org-from-is-user-regexp
1426 (let (r1 r2)
1427 (when (and user-mail-address (not (string= user-mail-address "")))
1428 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1429 (when (and user-full-name (not (string= user-full-name "")))
1430 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1431 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1432 "Regexp matched against the \"From:\" header of an email or usenet message.
1433 It should match if the message is from the user him/herself."
1434 :group 'org-link-store
1435 :type 'regexp)
1437 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1438 "Non-nil means storing a link to an Org file will use entry IDs.
1440 Note that before this variable is even considered, org-id must be loaded,
1441 so please customize `org-modules' and turn it on.
1443 The variable can have the following values:
1445 t Create an ID if needed to make a link to the current entry.
1447 create-if-interactive
1448 If `org-store-link' is called directly (interactively, as a user
1449 command), do create an ID to support the link. But when doing the
1450 job for remember, only use the ID if it already exists. The
1451 purpose of this setting is to avoid proliferation of unwanted
1452 IDs, just because you happen to be in an Org file when you
1453 call `org-remember' that automatically and preemptively
1454 creates a link. If you do want to get an ID link in a remember
1455 template to an entry not having an ID, create it first by
1456 explicitly creating a link to it, using `C-c C-l' first.
1458 create-if-interactive-and-no-custom-id
1459 Like create-if-interactive, but do not create an ID if there is
1460 a CUSTOM_ID property defined in the entry. This is the default.
1462 use-existing
1463 Use existing ID, do not create one.
1465 nil Never use an ID to make a link, instead link using a text search for
1466 the headline text."
1467 :group 'org-link-store
1468 :type '(choice
1469 (const :tag "Create ID to make link" t)
1470 (const :tag "Create if storing link interactively"
1471 create-if-interactive)
1472 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1473 create-if-interactive-and-no-custom-id)
1474 (const :tag "Only use existing" use-existing)
1475 (const :tag "Do not use ID to create link" nil)))
1477 (defcustom org-context-in-file-links t
1478 "Non-nil means file links from `org-store-link' contain context.
1479 A search string will be added to the file name with :: as separator and
1480 used to find the context when the link is activated by the command
1481 `org-open-at-point'. When this option is t, the entire active region
1482 will be placed in the search string of the file link. If set to a
1483 positive integer, only the first n lines of context will be stored.
1485 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1486 negates this setting for the duration of the command."
1487 :group 'org-link-store
1488 :type '(choice boolean integer))
1490 (defcustom org-keep-stored-link-after-insertion nil
1491 "Non-nil means keep link in list for entire session.
1493 The command `org-store-link' adds a link pointing to the current
1494 location to an internal list. These links accumulate during a session.
1495 The command `org-insert-link' can be used to insert links into any
1496 Org-mode file (offering completion for all stored links). When this
1497 option is nil, every link which has been inserted once using \\[org-insert-link]
1498 will be removed from the list, to make completing the unused links
1499 more efficient."
1500 :group 'org-link-store
1501 :type 'boolean)
1503 (defgroup org-link-follow nil
1504 "Options concerning following links in Org-mode."
1505 :tag "Org Follow Link"
1506 :group 'org-link)
1508 (defcustom org-link-translation-function nil
1509 "Function to translate links with different syntax to Org syntax.
1510 This can be used to translate links created for example by the Planner
1511 or emacs-wiki packages to Org syntax.
1512 The function must accept two parameters, a TYPE containing the link
1513 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1514 which is everything after the link protocol. It should return a cons
1515 with possibly modified values of type and path.
1516 Org contains a function for this, so if you set this variable to
1517 `org-translate-link-from-planner', you should be able follow many
1518 links created by planner."
1519 :group 'org-link-follow
1520 :type 'function)
1522 (defcustom org-follow-link-hook nil
1523 "Hook that is run after a link has been followed."
1524 :group 'org-link-follow
1525 :type 'hook)
1527 (defcustom org-tab-follows-link nil
1528 "Non-nil means on links TAB will follow the link.
1529 Needs to be set before org.el is loaded.
1530 This really should not be used, it does not make sense, and the
1531 implementation is bad."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-return-follows-link nil
1536 "Non-nil means on links RET will follow the link."
1537 :group 'org-link-follow
1538 :type 'boolean)
1540 (defcustom org-mouse-1-follows-link
1541 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1542 "Non-nil means mouse-1 on a link will follow the link.
1543 A longer mouse click will still set point. Does not work on XEmacs.
1544 Needs to be set before org.el is loaded."
1545 :group 'org-link-follow
1546 :type 'boolean)
1548 (defcustom org-mark-ring-length 4
1549 "Number of different positions to be recorded in the ring.
1550 Changing this requires a restart of Emacs to work correctly."
1551 :group 'org-link-follow
1552 :type 'integer)
1554 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1555 "Non-nil means internal links in Org files must exactly match a headline.
1556 When nil, the link search tries to match a phrase with all words
1557 in the search text."
1558 :group 'org-link-follow
1559 :version "24.1"
1560 :type '(choice
1561 (const :tag "Use fuzzy text search" nil)
1562 (const :tag "Match only exact headline" t)
1563 (const :tag "Match exact headline or query to create it"
1564 query-to-create)))
1566 (defcustom org-link-frame-setup
1567 '((vm . vm-visit-folder-other-frame)
1568 (vm-imap . vm-visit-imap-folder-other-frame)
1569 (gnus . org-gnus-no-new-news)
1570 (file . find-file-other-window)
1571 (wl . wl-other-frame))
1572 "Setup the frame configuration for following links.
1573 When following a link with Emacs, it may often be useful to display
1574 this link in another window or frame. This variable can be used to
1575 set this up for the different types of links.
1576 For VM, use any of
1577 `vm-visit-folder'
1578 `vm-visit-folder-other-window'
1579 `vm-visit-folder-other-frame'
1580 For Gnus, use any of
1581 `gnus'
1582 `gnus-other-frame'
1583 `org-gnus-no-new-news'
1584 For FILE, use any of
1585 `find-file'
1586 `find-file-other-window'
1587 `find-file-other-frame'
1588 For Wanderlust use any of
1589 `wl'
1590 `wl-other-frame'
1591 For the calendar, use the variable `calendar-setup'.
1592 For BBDB, it is currently only possible to display the matches in
1593 another window."
1594 :group 'org-link-follow
1595 :type '(list
1596 (cons (const vm)
1597 (choice
1598 (const vm-visit-folder)
1599 (const vm-visit-folder-other-window)
1600 (const vm-visit-folder-other-frame)))
1601 (cons (const gnus)
1602 (choice
1603 (const gnus)
1604 (const gnus-other-frame)
1605 (const org-gnus-no-new-news)))
1606 (cons (const file)
1607 (choice
1608 (const find-file)
1609 (const find-file-other-window)
1610 (const find-file-other-frame)))
1611 (cons (const wl)
1612 (choice
1613 (const wl)
1614 (const wl-other-frame)))))
1616 (defcustom org-display-internal-link-with-indirect-buffer nil
1617 "Non-nil means use indirect buffer to display infile links.
1618 Activating internal links (from one location in a file to another location
1619 in the same file) normally just jumps to the location. When the link is
1620 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1621 is displayed in
1622 another window. When this option is set, the other window actually displays
1623 an indirect buffer clone of the current buffer, to avoid any visibility
1624 changes to the current buffer."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-non-existing-files nil
1629 "Non-nil means `org-open-file' will open non-existing files.
1630 When nil, an error will be generated.
1631 This variable applies only to external applications because they
1632 might choke on non-existing files. If the link is to a file that
1633 will be opened in Emacs, the variable is ignored."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-open-directory-means-index-dot-org nil
1638 "Non-nil means a link to a directory really means to index.org.
1639 When nil, following a directory link will run dired or open a finder/explorer
1640 window on that directory."
1641 :group 'org-link-follow
1642 :type 'boolean)
1644 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1645 "Function and arguments to call for following mailto links.
1646 This is a list with the first element being a Lisp function, and the
1647 remaining elements being arguments to the function. In string arguments,
1648 %a will be replaced by the address, and %s will be replaced by the subject
1649 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1650 :group 'org-link-follow
1651 :type '(choice
1652 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1653 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1654 (const :tag "message-mail" (message-mail "%a" "%s"))
1655 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1657 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1658 "Non-nil means ask for confirmation before executing shell links.
1659 Shell links can be dangerous: just think about a link
1661 [[shell:rm -rf ~/*][Google Search]]
1663 This link would show up in your Org-mode document as \"Google Search\",
1664 but really it would remove your entire home directory.
1665 Therefore we advise against setting this variable to nil.
1666 Just change it to `y-or-n-p' if you want to confirm with a
1667 single keystroke rather than having to type \"yes\"."
1668 :group 'org-link-follow
1669 :type '(choice
1670 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1671 (const :tag "with y-or-n (faster)" y-or-n-p)
1672 (const :tag "no confirmation (dangerous)" nil)))
1673 (put 'org-confirm-shell-link-function
1674 'safe-local-variable
1675 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1677 (defcustom org-confirm-shell-link-not-regexp ""
1678 "A regexp to skip confirmation for shell links."
1679 :group 'org-link-follow
1680 :version "24.1"
1681 :type 'regexp)
1683 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1684 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1685 Elisp links can be dangerous: just think about a link
1687 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1689 This link would show up in your Org-mode document as \"Google Search\",
1690 but really it would remove your entire home directory.
1691 Therefore we advise against setting this variable to nil.
1692 Just change it to `y-or-n-p' if you want to confirm with a
1693 single keystroke rather than having to type \"yes\"."
1694 :group 'org-link-follow
1695 :type '(choice
1696 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1697 (const :tag "with y-or-n (faster)" y-or-n-p)
1698 (const :tag "no confirmation (dangerous)" nil)))
1699 (put 'org-confirm-shell-link-function
1700 'safe-local-variable
1701 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1703 (defcustom org-confirm-elisp-link-not-regexp ""
1704 "A regexp to skip confirmation for Elisp links."
1705 :group 'org-link-follow
1706 :version "24.1"
1707 :type 'regexp)
1709 (defconst org-file-apps-defaults-gnu
1710 '((remote . emacs)
1711 (system . mailcap)
1712 (t . mailcap))
1713 "Default file applications on a UNIX or GNU/Linux system.
1714 See `org-file-apps'.")
1716 (defconst org-file-apps-defaults-macosx
1717 '((remote . emacs)
1718 (t . "open %s")
1719 (system . "open %s")
1720 ("ps.gz" . "gv %s")
1721 ("eps.gz" . "gv %s")
1722 ("dvi" . "xdvi %s")
1723 ("fig" . "xfig %s"))
1724 "Default file applications on a MacOS X system.
1725 The system \"open\" is known as a default, but we use X11 applications
1726 for some files for which the OS does not have a good default.
1727 See `org-file-apps'.")
1729 (defconst org-file-apps-defaults-windowsnt
1730 (list
1731 '(remote . emacs)
1732 (cons t
1733 (list (if (featurep 'xemacs)
1734 'mswindows-shell-execute
1735 'w32-shell-execute)
1736 "open" 'file))
1737 (cons 'system
1738 (list (if (featurep 'xemacs)
1739 'mswindows-shell-execute
1740 'w32-shell-execute)
1741 "open" 'file)))
1742 "Default file applications on a Windows NT system.
1743 The system \"open\" is used for most files.
1744 See `org-file-apps'.")
1746 (defcustom org-file-apps
1748 (auto-mode . emacs)
1749 ("\\.mm\\'" . default)
1750 ("\\.x?html?\\'" . default)
1751 ("\\.pdf\\'" . default)
1753 "External applications for opening `file:path' items in a document.
1754 Org-mode uses system defaults for different file types, but
1755 you can use this variable to set the application for a given file
1756 extension. The entries in this list are cons cells where the car identifies
1757 files and the cdr the corresponding command. Possible values for the
1758 file identifier are
1759 \"string\" A string as a file identifier can be interpreted in different
1760 ways, depending on its contents:
1762 - Alphanumeric characters only:
1763 Match links with this file extension.
1764 Example: (\"pdf\" . \"evince %s\")
1765 to open PDFs with evince.
1767 - Regular expression: Match links where the
1768 filename matches the regexp. If you want to
1769 use groups here, use shy groups.
1771 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1772 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1773 to open *.html and *.xhtml with firefox.
1775 - Regular expression which contains (non-shy) groups:
1776 Match links where the whole link, including \"::\", and
1777 anything after that, matches the regexp.
1778 In a custom command string, %1, %2, etc. are replaced with
1779 the parts of the link that were matched by the groups.
1780 For backwards compatibility, if a command string is given
1781 that does not use any of the group matches, this case is
1782 handled identically to the second one (i.e. match against
1783 file name only).
1784 In a custom lisp form, you can access the group matches with
1785 (match-string n link).
1787 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1788 to open [[file:document.pdf::5]] with evince at page 5.
1790 `directory' Matches a directory
1791 `remote' Matches a remote file, accessible through tramp or efs.
1792 Remote files most likely should be visited through Emacs
1793 because external applications cannot handle such paths.
1794 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1795 so all files Emacs knows how to handle. Using this with
1796 command `emacs' will open most files in Emacs. Beware that this
1797 will also open html files inside Emacs, unless you add
1798 (\"html\" . default) to the list as well.
1799 t Default for files not matched by any of the other options.
1800 `system' The system command to open files, like `open' on Windows
1801 and Mac OS X, and mailcap under GNU/Linux. This is the command
1802 that will be selected if you call `C-c C-o' with a double
1803 \\[universal-argument] \\[universal-argument] prefix.
1805 Possible values for the command are:
1806 `emacs' The file will be visited by the current Emacs process.
1807 `default' Use the default application for this file type, which is the
1808 association for t in the list, most likely in the system-specific
1809 part.
1810 This can be used to overrule an unwanted setting in the
1811 system-specific variable.
1812 `system' Use the system command for opening files, like \"open\".
1813 This command is specified by the entry whose car is `system'.
1814 Most likely, the system-specific version of this variable
1815 does define this command, but you can overrule/replace it
1816 here.
1817 string A command to be executed by a shell; %s will be replaced
1818 by the path to the file.
1819 sexp A Lisp form which will be evaluated. The file path will
1820 be available in the Lisp variable `file'.
1821 For more examples, see the system specific constants
1822 `org-file-apps-defaults-macosx'
1823 `org-file-apps-defaults-windowsnt'
1824 `org-file-apps-defaults-gnu'."
1825 :group 'org-link-follow
1826 :type '(repeat
1827 (cons (choice :value ""
1828 (string :tag "Extension")
1829 (const :tag "System command to open files" system)
1830 (const :tag "Default for unrecognized files" t)
1831 (const :tag "Remote file" remote)
1832 (const :tag "Links to a directory" directory)
1833 (const :tag "Any files that have Emacs modes"
1834 auto-mode))
1835 (choice :value ""
1836 (const :tag "Visit with Emacs" emacs)
1837 (const :tag "Use default" default)
1838 (const :tag "Use the system command" system)
1839 (string :tag "Command")
1840 (sexp :tag "Lisp form")))))
1844 (defgroup org-refile nil
1845 "Options concerning refiling entries in Org-mode."
1846 :tag "Org Refile"
1847 :group 'org)
1849 (defcustom org-directory "~/org"
1850 "Directory with org files.
1851 This is just a default location to look for Org files. There is no need
1852 at all to put your files into this directory. It is only used in the
1853 following situations:
1855 1. When a remember template specifies a target file that is not an
1856 absolute path. The path will then be interpreted relative to
1857 `org-directory'
1858 2. When a remember note is filed away in an interactive way (when exiting the
1859 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1860 with `org-directory' as the default path."
1861 :group 'org-refile
1862 :group 'org-remember
1863 :type 'directory)
1865 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1866 "Default target for storing notes.
1867 Used as a fall back file for org-remember.el and org-capture.el, for
1868 templates that do not specify a target file."
1869 :group 'org-refile
1870 :group 'org-remember
1871 :type '(choice
1872 (const :tag "Default from remember-data-file" nil)
1873 file))
1875 (defcustom org-goto-interface 'outline
1876 "The default interface to be used for `org-goto'.
1877 Allowed values are:
1878 outline The interface shows an outline of the relevant file
1879 and the correct heading is found by moving through
1880 the outline or by searching with incremental search.
1881 outline-path-completion Headlines in the current buffer are offered via
1882 completion. This is the interface also used by
1883 the refile command."
1884 :group 'org-refile
1885 :type '(choice
1886 (const :tag "Outline" outline)
1887 (const :tag "Outline-path-completion" outline-path-completion)))
1889 (defcustom org-goto-max-level 5
1890 "Maximum target level when running `org-goto' with refile interface."
1891 :group 'org-refile
1892 :type 'integer)
1894 (defcustom org-reverse-note-order nil
1895 "Non-nil means store new notes at the beginning of a file or entry.
1896 When nil, new notes will be filed to the end of a file or entry.
1897 This can also be a list with cons cells of regular expressions that
1898 are matched against file names, and values."
1899 :group 'org-remember
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Reverse always" t)
1903 (const :tag "Reverse never" nil)
1904 (repeat :tag "By file name regexp"
1905 (cons regexp boolean))))
1907 (defcustom org-log-refile nil
1908 "Information to record when a task is refiled.
1910 Possible values are:
1912 nil Don't add anything
1913 time Add a time stamp to the task
1914 note Prompt for a note and add it with template `org-log-note-headings'
1916 This option can also be set with on a per-file-basis with
1918 #+STARTUP: nologrefile
1919 #+STARTUP: logrefile
1920 #+STARTUP: lognoterefile
1922 You can have local logging settings for a subtree by setting the LOGGING
1923 property to one or more of these keywords.
1925 When bulk-refiling from the agenda, the value `note' is forbidden and
1926 will temporarily be changed to `time'."
1927 :group 'org-refile
1928 :group 'org-progress
1929 :version "24.1"
1930 :type '(choice
1931 (const :tag "No logging" nil)
1932 (const :tag "Record timestamp" time)
1933 (const :tag "Record timestamp with note." note)))
1935 (defcustom org-refile-targets nil
1936 "Targets for refiling entries with \\[org-refile].
1937 This is a list of cons cells. Each cell contains:
1938 - a specification of the files to be considered, either a list of files,
1939 or a symbol whose function or variable value will be used to retrieve
1940 a file name or a list of file names. If you use `org-agenda-files' for
1941 that, all agenda files will be scanned for targets. Nil means consider
1942 headings in the current buffer.
1943 - A specification of how to find candidate refile targets. This may be
1944 any of:
1945 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1946 This tag has to be present in all target headlines, inheritance will
1947 not be considered.
1948 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1949 todo keyword.
1950 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1951 headlines that are refiling targets.
1952 - a cons cell (:level . N). Any headline of level N is considered a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1955 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1956 Note that, when `org-odd-levels-only' is set, level corresponds to
1957 order in hierarchy, not to the number of stars.
1959 Each element of this list generates a set of possible targets.
1960 The union of these sets is presented (with completion) to
1961 the user by `org-refile'.
1963 You can set the variable `org-refile-target-verify-function' to a function
1964 to verify each headline found by the simple criteria above.
1966 When this variable is nil, all top-level headlines in the current buffer
1967 are used, equivalent to the value `((nil . (:level . 1))'."
1968 :group 'org-refile
1969 :type '(repeat
1970 (cons
1971 (choice :value org-agenda-files
1972 (const :tag "All agenda files" org-agenda-files)
1973 (const :tag "Current buffer" nil)
1974 (function) (variable) (file))
1975 (choice :tag "Identify target headline by"
1976 (cons :tag "Specific tag" (const :value :tag) (string))
1977 (cons :tag "TODO keyword" (const :value :todo) (string))
1978 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1979 (cons :tag "Level number" (const :value :level) (integer))
1980 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1982 (defcustom org-refile-target-verify-function nil
1983 "Function to verify if the headline at point should be a refile target.
1984 The function will be called without arguments, with point at the
1985 beginning of the headline. It should return t and leave point
1986 where it is if the headline is a valid target for refiling.
1988 If the target should not be selected, the function must return nil.
1989 In addition to this, it may move point to a place from where the search
1990 should be continued. For example, the function may decide that the entire
1991 subtree of the current entry should be excluded and move point to the end
1992 of the subtree."
1993 :group 'org-refile
1994 :type 'function)
1996 (defcustom org-refile-use-cache nil
1997 "Non-nil means cache refile targets to speed up the process.
1998 The cache for a particular file will be updated automatically when
1999 the buffer has been killed, or when any of the marker used for flagging
2000 refile targets no longer points at a live buffer.
2001 If you have added new entries to a buffer that might themselves be targets,
2002 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2003 find that easier, `C-u C-u C-u C-c C-w'."
2004 :group 'org-refile
2005 :version "24.1"
2006 :type 'boolean)
2008 (defcustom org-refile-use-outline-path nil
2009 "Non-nil means provide refile targets as paths.
2010 So a level 3 headline will be available as level1/level2/level3.
2012 When the value is `file', also include the file name (without directory)
2013 into the path. In this case, you can also stop the completion after
2014 the file name, to get entries inserted as top level in the file.
2016 When `full-file-path', include the full file path."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Not" nil)
2020 (const :tag "Yes" t)
2021 (const :tag "Start with file name" file)
2022 (const :tag "Start with full file path" full-file-path)))
2024 (defcustom org-outline-path-complete-in-steps t
2025 "Non-nil means complete the outline path in hierarchical steps.
2026 When Org-mode uses the refile interface to select an outline path
2027 \(see variable `org-refile-use-outline-path'), the completion of
2028 the path can be done is a single go, or if can be done in steps down
2029 the headline hierarchy. Going in steps is probably the best if you
2030 do not use a special completion package like `ido' or `icicles'.
2031 However, when using these packages, going in one step can be very
2032 fast, while still showing the whole path to the entry."
2033 :group 'org-refile
2034 :type 'boolean)
2036 (defcustom org-refile-allow-creating-parent-nodes nil
2037 "Non-nil means allow to create new nodes as refile targets.
2038 New nodes are then created by adding \"/new node name\" to the completion
2039 of an existing node. When the value of this variable is `confirm',
2040 new node creation must be confirmed by the user (recommended)
2041 When nil, the completion must match an existing entry.
2043 Note that, if the new heading is not seen by the criteria
2044 listed in `org-refile-targets', multiple instances of the same
2045 heading would be created by trying again to file under the new
2046 heading."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Never" nil)
2050 (const :tag "Always" t)
2051 (const :tag "Prompt for confirmation" confirm)))
2053 (defcustom org-refile-active-region-within-subtree nil
2054 "Non-nil means also refile active region within a subtree.
2056 By default `org-refile' doesn't allow refiling regions if they
2057 don't contain a set of subtrees, but it might be convenient to
2058 do so sometimes: in that case, the first line of the region is
2059 converted to a headline before refiling."
2060 :group 'org-refile
2061 :version "24.1"
2062 :type 'boolean)
2064 (defgroup org-todo nil
2065 "Options concerning TODO items in Org-mode."
2066 :tag "Org TODO"
2067 :group 'org)
2069 (defgroup org-progress nil
2070 "Options concerning Progress logging in Org-mode."
2071 :tag "Org Progress"
2072 :group 'org-time)
2074 (defvar org-todo-interpretation-widgets
2075 '((:tag "Sequence (cycling hits every state)" sequence)
2076 (:tag "Type (cycling directly to DONE)" type))
2077 "The available interpretation symbols for customizing `org-todo-keywords'.
2078 Interested libraries should add to this list.")
2080 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2081 "List of TODO entry keyword sequences and their interpretation.
2082 \\<org-mode-map>This is a list of sequences.
2084 Each sequence starts with a symbol, either `sequence' or `type',
2085 indicating if the keywords should be interpreted as a sequence of
2086 action steps, or as different types of TODO items. The first
2087 keywords are states requiring action - these states will select a headline
2088 for inclusion into the global TODO list Org-mode produces. If one of
2089 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2090 signify that no further action is necessary. If \"|\" is not found,
2091 the last keyword is treated as the only DONE state of the sequence.
2093 The command \\[org-todo] cycles an entry through these states, and one
2094 additional state where no keyword is present. For details about this
2095 cycling, see the manual.
2097 TODO keywords and interpretation can also be set on a per-file basis with
2098 the special #+SEQ_TODO and #+TYP_TODO lines.
2100 Each keyword can optionally specify a character for fast state selection
2101 \(in combination with the variable `org-use-fast-todo-selection')
2102 and specifiers for state change logging, using the same syntax
2103 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2104 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2105 indicates to record a time stamp each time this state is selected.
2107 Each keyword may also specify if a timestamp or a note should be
2108 recorded when entering or leaving the state, by adding additional
2109 characters in the parenthesis after the keyword. This looks like this:
2110 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2111 record only the time of the state change. With X and Y being either
2112 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2113 Y when leaving the state if and only if the *target* state does not
2114 define X. You may omit any of the fast-selection key or X or /Y,
2115 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2117 For backward compatibility, this variable may also be just a list
2118 of keywords - in this case the interpretation (sequence or type) will be
2119 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2120 :group 'org-todo
2121 :group 'org-keywords
2122 :type '(choice
2123 (repeat :tag "Old syntax, just keywords"
2124 (string :tag "Keyword"))
2125 (repeat :tag "New syntax"
2126 (cons
2127 (choice
2128 :tag "Interpretation"
2129 ;;Quick and dirty way to see
2130 ;;`org-todo-interpretations'. This takes the
2131 ;;place of item arguments
2132 :convert-widget
2133 (lambda (widget)
2134 (widget-put widget
2135 :args (mapcar
2136 #'(lambda (x)
2137 (widget-convert
2138 (cons 'const x)))
2139 org-todo-interpretation-widgets))
2140 widget))
2141 (repeat
2142 (string :tag "Keyword"))))))
2144 (defvar org-todo-keywords-1 nil
2145 "All TODO and DONE keywords active in a buffer.")
2146 (make-variable-buffer-local 'org-todo-keywords-1)
2147 (defvar org-todo-keywords-for-agenda nil)
2148 (defvar org-done-keywords-for-agenda nil)
2149 (defvar org-drawers-for-agenda nil)
2150 (defvar org-todo-keyword-alist-for-agenda nil)
2151 (defvar org-tag-alist-for-agenda nil)
2152 (defvar org-agenda-contributing-files nil)
2153 (defvar org-not-done-keywords nil)
2154 (make-variable-buffer-local 'org-not-done-keywords)
2155 (defvar org-done-keywords nil)
2156 (make-variable-buffer-local 'org-done-keywords)
2157 (defvar org-todo-heads nil)
2158 (make-variable-buffer-local 'org-todo-heads)
2159 (defvar org-todo-sets nil)
2160 (make-variable-buffer-local 'org-todo-sets)
2161 (defvar org-todo-log-states nil)
2162 (make-variable-buffer-local 'org-todo-log-states)
2163 (defvar org-todo-kwd-alist nil)
2164 (make-variable-buffer-local 'org-todo-kwd-alist)
2165 (defvar org-todo-key-alist nil)
2166 (make-variable-buffer-local 'org-todo-key-alist)
2167 (defvar org-todo-key-trigger nil)
2168 (make-variable-buffer-local 'org-todo-key-trigger)
2170 (defcustom org-todo-interpretation 'sequence
2171 "Controls how TODO keywords are interpreted.
2172 This variable is in principle obsolete and is only used for
2173 backward compatibility, if the interpretation of todo keywords is
2174 not given already in `org-todo-keywords'. See that variable for
2175 more information."
2176 :group 'org-todo
2177 :group 'org-keywords
2178 :type '(choice (const sequence)
2179 (const type)))
2181 (defcustom org-use-fast-todo-selection t
2182 "Non-nil means use the fast todo selection scheme with C-c C-t.
2183 This variable describes if and under what circumstances the cycling
2184 mechanism for TODO keywords will be replaced by a single-key, direct
2185 selection scheme.
2187 When nil, fast selection is never used.
2189 When the symbol `prefix', it will be used when `org-todo' is called with
2190 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2191 in an agenda buffer.
2193 When t, fast selection is used by default. In this case, the prefix
2194 argument forces cycling instead.
2196 In all cases, the special interface is only used if access keys have actually
2197 been assigned by the user, i.e. if keywords in the configuration are followed
2198 by a letter in parenthesis, like TODO(t)."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Never" nil)
2202 (const :tag "By default" t)
2203 (const :tag "Only with C-u C-c C-t" prefix)))
2205 (defcustom org-provide-todo-statistics t
2206 "Non-nil means update todo statistics after insert and toggle.
2207 ALL-HEADLINES means update todo statistics by including headlines
2208 with no TODO keyword as well, counting them as not done.
2209 A list of TODO keywords means the same, but skip keywords that are
2210 not in this list.
2212 When this is set, todo statistics is updated in the parent of the
2213 current entry each time a todo state is changed."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Yes, only for TODO entries" t)
2217 (const :tag "Yes, including all entries" 'all-headlines)
2218 (repeat :tag "Yes, for TODOs in this list"
2219 (string :tag "TODO keyword"))
2220 (other :tag "No TODO statistics" nil)))
2222 (defcustom org-hierarchical-todo-statistics t
2223 "Non-nil means TODO statistics covers just direct children.
2224 When nil, all entries in the subtree are considered.
2225 This has only an effect if `org-provide-todo-statistics' is set.
2226 To set this to nil for only a single subtree, use a COOKIE_DATA
2227 property and include the word \"recursive\" into the value."
2228 :group 'org-todo
2229 :type 'boolean)
2231 (defcustom org-after-todo-state-change-hook nil
2232 "Hook which is run after the state of a TODO item was changed.
2233 The new state (a string with a TODO keyword, or nil) is available in the
2234 Lisp variable `org-state'."
2235 :group 'org-todo
2236 :type 'hook)
2238 (defvar org-blocker-hook nil
2239 "Hook for functions that are allowed to block a state change.
2241 Each function gets as its single argument a property list, see
2242 `org-trigger-hook' for more information about this list.
2244 If any of the functions in this hook returns nil, the state change
2245 is blocked.")
2247 (defvar org-trigger-hook nil
2248 "Hook for functions that are triggered by a state change.
2250 Each function gets as its single argument a property list with at least
2251 the following elements:
2253 (:type type-of-change :position pos-at-entry-start
2254 :from old-state :to new-state)
2256 Depending on the type, more properties may be present.
2258 This mechanism is currently implemented for:
2260 TODO state changes
2261 ------------------
2262 :type todo-state-change
2263 :from previous state (keyword as a string), or nil, or a symbol
2264 'todo' or 'done', to indicate the general type of state.
2265 :to new state, like in :from")
2267 (defcustom org-enforce-todo-dependencies nil
2268 "Non-nil means undone TODO entries will block switching the parent to DONE.
2269 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2270 be blocked if any prior sibling is not yet done.
2271 Finally, if the parent is blocked because of ordered siblings of its own,
2272 the child will also be blocked."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-children-or-siblings-or-parent)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-enforce-todo-checkbox-dependencies nil
2284 "Non-nil means unchecked boxes will block switching the parent to DONE.
2285 When this is nil, checkboxes have no influence on switching TODO states.
2286 When non-nil, you first need to check off all check boxes before the TODO
2287 entry can be switched to DONE.
2288 This variable needs to be set before org.el is loaded, and you need to
2289 restart Emacs after a change to make the change effective. The only way
2290 to change is while Emacs is running is through the customize interface."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-checkboxes)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-treat-insert-todo-heading-as-state-change nil
2302 "Non-nil means inserting a TODO heading is treated as state change.
2303 So when the command \\[org-insert-todo-heading] is used, state change
2304 logging will apply if appropriate. When nil, the new TODO item will
2305 be inserted directly, and no logging will take place."
2306 :group 'org-todo
2307 :type 'boolean)
2309 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2310 "Non-nil means switching TODO states with S-cursor counts as state change.
2311 This is the default behavior. However, setting this to nil allows a
2312 convenient way to select a TODO state and bypass any logging associated
2313 with that."
2314 :group 'org-todo
2315 :type 'boolean)
2317 (defcustom org-todo-state-tags-triggers nil
2318 "Tag changes that should be triggered by TODO state changes.
2319 This is a list. Each entry is
2321 (state-change (tag . flag) .......)
2323 State-change can be a string with a state, and empty string to indicate the
2324 state that has no TODO keyword, or it can be one of the symbols `todo'
2325 or `done', meaning any not-done or done state, respectively."
2326 :group 'org-todo
2327 :group 'org-tags
2328 :type '(repeat
2329 (cons (choice :tag "When changing to"
2330 (const :tag "Not-done state" todo)
2331 (const :tag "Done state" done)
2332 (string :tag "State"))
2333 (repeat
2334 (cons :tag "Tag action"
2335 (string :tag "Tag")
2336 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2338 (defcustom org-log-done nil
2339 "Information to record when a task moves to the DONE state.
2341 Possible values are:
2343 nil Don't add anything, just change the keyword
2344 time Add a time stamp to the task
2345 note Prompt for a note and add it with template `org-log-note-headings'
2347 This option can also be set with on a per-file-basis with
2349 #+STARTUP: nologdone
2350 #+STARTUP: logdone
2351 #+STARTUP: lognotedone
2353 You can have local logging settings for a subtree by setting the LOGGING
2354 property to one or more of these keywords."
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record CLOSED timestamp" time)
2360 (const :tag "Record CLOSED timestamp with note." note)))
2362 ;; Normalize old uses of org-log-done.
2363 (cond
2364 ((eq org-log-done t) (setq org-log-done 'time))
2365 ((and (listp org-log-done) (memq 'done org-log-done))
2366 (setq org-log-done 'note)))
2368 (defcustom org-log-reschedule nil
2369 "Information to record when the scheduling date of a tasks is modified.
2371 Possible values are:
2373 nil Don't add anything, just change the date
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologreschedule
2380 #+STARTUP: logreschedule
2381 #+STARTUP: lognotereschedule"
2382 :group 'org-todo
2383 :group 'org-progress
2384 :type '(choice
2385 (const :tag "No logging" nil)
2386 (const :tag "Record timestamp" time)
2387 (const :tag "Record timestamp with note." note)))
2389 (defcustom org-log-redeadline nil
2390 "Information to record when the deadline date of a tasks is modified.
2392 Possible values are:
2394 nil Don't add anything, just change the date
2395 time Add a time stamp to the task
2396 note Prompt for a note and add it with template `org-log-note-headings'
2398 This option can also be set with on a per-file-basis with
2400 #+STARTUP: nologredeadline
2401 #+STARTUP: logredeadline
2402 #+STARTUP: lognoteredeadline
2404 You can have local logging settings for a subtree by setting the LOGGING
2405 property to one or more of these keywords."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(choice
2409 (const :tag "No logging" nil)
2410 (const :tag "Record timestamp" time)
2411 (const :tag "Record timestamp with note." note)))
2413 (defcustom org-log-note-clock-out nil
2414 "Non-nil means record a note when clocking out of an item.
2415 This can also be configured on a per-file basis by adding one of
2416 the following lines anywhere in the buffer:
2418 #+STARTUP: lognoteclock-out
2419 #+STARTUP: nolognoteclock-out"
2420 :group 'org-todo
2421 :group 'org-progress
2422 :type 'boolean)
2424 (defcustom org-log-done-with-time t
2425 "Non-nil means the CLOSED time stamp will contain date and time.
2426 When nil, only the date will be recorded."
2427 :group 'org-progress
2428 :type 'boolean)
2430 (defcustom org-log-note-headings
2431 '((done . "CLOSING NOTE %t")
2432 (state . "State %-12s from %-12S %t")
2433 (note . "Note taken on %t")
2434 (reschedule . "Rescheduled from %S on %t")
2435 (delschedule . "Not scheduled, was %S on %t")
2436 (redeadline . "New deadline from %S on %t")
2437 (deldeadline . "Removed deadline, was %S on %t")
2438 (refile . "Refiled on %t")
2439 (clock-out . ""))
2440 "Headings for notes added to entries.
2441 The value is an alist, with the car being a symbol indicating the note
2442 context, and the cdr is the heading to be used. The heading may also be the
2443 empty string.
2444 %t in the heading will be replaced by a time stamp.
2445 %T will be an active time stamp instead the default inactive one
2446 %d will be replaced by a short-format time stamp.
2447 %D will be replaced by an active short-format time stamp.
2448 %s will be replaced by the new TODO state, in double quotes.
2449 %S will be replaced by the old TODO state, in double quotes.
2450 %u will be replaced by the user name.
2451 %U will be replaced by the full user name.
2453 In fact, it is not a good idea to change the `state' entry, because
2454 agenda log mode depends on the format of these entries."
2455 :group 'org-todo
2456 :group 'org-progress
2457 :type '(list :greedy t
2458 (cons (const :tag "Heading when closing an item" done) string)
2459 (cons (const :tag
2460 "Heading when changing todo state (todo sequence only)"
2461 state) string)
2462 (cons (const :tag "Heading when just taking a note" note) string)
2463 (cons (const :tag "Heading when clocking out" clock-out) string)
2464 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2465 (cons (const :tag "Heading when rescheduling" reschedule) string)
2466 (cons (const :tag "Heading when changing deadline" redeadline) string)
2467 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2468 (cons (const :tag "Heading when refiling" refile) string)))
2470 (unless (assq 'note org-log-note-headings)
2471 (push '(note . "%t") org-log-note-headings))
2473 (defcustom org-log-into-drawer nil
2474 "Non-nil means insert state change notes and time stamps into a drawer.
2475 When nil, state changes notes will be inserted after the headline and
2476 any scheduling and clock lines, but not inside a drawer.
2478 The value of this variable should be the name of the drawer to use.
2479 LOGBOOK is proposed as the default drawer for this purpose, you can
2480 also set this to a string to define the drawer of your choice.
2482 A value of t is also allowed, representing \"LOGBOOK\".
2484 If this variable is set, `org-log-state-notes-insert-after-drawers'
2485 will be ignored.
2487 You can set the property LOG_INTO_DRAWER to overrule this setting for
2488 a subtree."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "Not into a drawer" nil)
2493 (const :tag "LOGBOOK" t)
2494 (string :tag "Other")))
2496 (if (fboundp 'defvaralias)
2497 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2499 (defun org-log-into-drawer ()
2500 "Return the value of `org-log-into-drawer', but let properties overrule.
2501 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2502 used instead of the default value."
2503 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2504 (cond
2505 ((or (not p) (equal p "nil")) org-log-into-drawer)
2506 ((equal p "t") "LOGBOOK")
2507 (t p))))
2509 (defcustom org-log-state-notes-insert-after-drawers nil
2510 "Non-nil means insert state change notes after any drawers in entry.
2511 Only the drawers that *immediately* follow the headline and the
2512 deadline/scheduled line are skipped.
2513 When nil, insert notes right after the heading and perhaps the line
2514 with deadline/scheduling if present.
2516 This variable will have no effect if `org-log-into-drawer' is
2517 set."
2518 :group 'org-todo
2519 :group 'org-progress
2520 :type 'boolean)
2522 (defcustom org-log-states-order-reversed t
2523 "Non-nil means the latest state note will be directly after heading.
2524 When nil, the state change notes will be ordered according to time."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-todo-repeat-to-state nil
2530 "The TODO state to which a repeater should return the repeating task.
2531 By default this is the first task in a TODO sequence, or the previous state
2532 in a TODO_TYP set. But you can specify another task here.
2533 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2534 :group 'org-todo
2535 :version "24.1"
2536 :type '(choice (const :tag "Head of sequence" nil)
2537 (string :tag "Specific state")))
2539 (defcustom org-log-repeat 'time
2540 "Non-nil means record moving through the DONE state when triggering repeat.
2541 An auto-repeating task is immediately switched back to TODO when
2542 marked DONE. If you are not logging state changes (by adding \"@\"
2543 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2544 record a closing note, there will be no record of the task moving
2545 through DONE. This variable forces taking a note anyway.
2547 nil Don't force a record
2548 time Record a time stamp
2549 note Record a note
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: logrepeat
2554 #+STARTUP: lognoterepeat
2555 #+STARTUP: nologrepeat
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "Don't force a record" nil)
2563 (const :tag "Force recording the DONE state" time)
2564 (const :tag "Force recording a note with the DONE state" note)))
2567 (defgroup org-priorities nil
2568 "Priorities in Org-mode."
2569 :tag "Org Priorities"
2570 :group 'org-todo)
2572 (defcustom org-enable-priority-commands t
2573 "Non-nil means priority commands are active.
2574 When nil, these commands will be disabled, so that you never accidentally
2575 set a priority."
2576 :group 'org-priorities
2577 :type 'boolean)
2579 (defcustom org-highest-priority ?A
2580 "The highest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a smaller ASCII number than `org-lowest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-lowest-priority ?C
2586 "The lowest priority of TODO items. A character like ?A, ?B etc.
2587 Must have a larger ASCII number than `org-highest-priority'."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-default-priority ?B
2592 "The default priority of TODO items.
2593 This is the priority an item gets if no explicit priority is given.
2594 When starting to cycle on an empty priority the first step in the cycle
2595 depends on `org-priority-start-cycle-with-default'. The resulting first
2596 step priority must not exceed the range from `org-highest-priority' to
2597 `org-lowest-priority' which means that `org-default-priority' has to be
2598 in this range exclusive or inclusive the range boundaries. Else the
2599 first step refuses to set the default and the second will fall back
2600 to (depending on the command used) the highest or lowest priority."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-priority-start-cycle-with-default t
2605 "Non-nil means start with default priority when starting to cycle.
2606 When this is nil, the first step in the cycle will be (depending on the
2607 command used) one higher or lower than the default priority.
2608 See also `org-default-priority'."
2609 :group 'org-priorities
2610 :type 'boolean)
2612 (defcustom org-get-priority-function nil
2613 "Function to extract the priority from a string.
2614 The string is normally the headline. If this is nil Org computes the
2615 priority from the priority cookie like [#A] in the headline. It returns
2616 an integer, increasing by 1000 for each priority level.
2617 The user can set a different function here, which should take a string
2618 as an argument and return the numeric priority."
2619 :group 'org-priorities
2620 :version "24.1"
2621 :type 'function)
2623 (defgroup org-time nil
2624 "Options concerning time stamps and deadlines in Org-mode."
2625 :tag "Org Time"
2626 :group 'org)
2628 (defcustom org-insert-labeled-timestamps-at-point nil
2629 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2630 When nil, these labeled time stamps are forces into the second line of an
2631 entry, just after the headline. When scheduling from the global TODO list,
2632 the time stamp will always be forced into the second line."
2633 :group 'org-time
2634 :type 'boolean)
2636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2637 "Formats for `format-time-string' which are used for time stamps.
2638 It is not recommended to change this constant.")
2640 (defcustom org-time-stamp-rounding-minutes '(0 5)
2641 "Number of minutes to round time stamps to.
2642 These are two values, the first applies when first creating a time stamp.
2643 The second applies when changing it with the commands `S-up' and `S-down'.
2644 When changing the time stamp, this means that it will change in steps
2645 of N minutes, as given by the second value.
2647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2648 numbers should be factors of 60, so for example 5, 10, 15.
2650 When this is larger than 1, you can still force an exact time stamp by using
2651 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2652 and by using a prefix arg to `S-up/down' to specify the exact number
2653 of minutes to shift."
2654 :group 'org-time
2655 :get #'(lambda (var) ; Make sure both elements are there
2656 (if (integerp (default-value var))
2657 (list (default-value var) 5)
2658 (default-value var)))
2659 :type '(list
2660 (integer :tag "when inserting times")
2661 (integer :tag "when modifying times")))
2663 ;; Normalize old customizations of this variable.
2664 (when (integerp org-time-stamp-rounding-minutes)
2665 (setq org-time-stamp-rounding-minutes
2666 (list org-time-stamp-rounding-minutes
2667 org-time-stamp-rounding-minutes)))
2669 (defcustom org-display-custom-times nil
2670 "Non-nil means overlay custom formats over all time stamps.
2671 The formats are defined through the variable `org-time-stamp-custom-formats'.
2672 To turn this on on a per-file basis, insert anywhere in the file:
2673 #+STARTUP: customtime"
2674 :group 'org-time
2675 :set 'set-default
2676 :type 'sexp)
2677 (make-variable-buffer-local 'org-display-custom-times)
2679 (defcustom org-time-stamp-custom-formats
2680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2681 "Custom formats for time stamps. See `format-time-string' for the syntax.
2682 These are overlaid over the default ISO format if the variable
2683 `org-display-custom-times' is set. Time like %H:%M should be at the
2684 end of the second format. The custom formats are also honored by export
2685 commands, if custom time display is turned on at the time of export."
2686 :group 'org-time
2687 :type 'sexp)
2689 (defun org-time-stamp-format (&optional long inactive)
2690 "Get the right format for a time string."
2691 (let ((f (if long (cdr org-time-stamp-formats)
2692 (car org-time-stamp-formats))))
2693 (if inactive
2694 (concat "[" (substring f 1 -1) "]")
2695 f)))
2697 (defcustom org-time-clocksum-format "%d:%02d"
2698 "The format string used when creating CLOCKSUM lines.
2699 This is also used when org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'string)
2703 (defcustom org-time-clocksum-use-fractional nil
2704 "If non-nil, \\[org-clock-display] uses fractional times.
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'boolean)
2709 (defcustom org-time-clocksum-fractional-format "%.2f"
2710 "The format string used when creating CLOCKSUM lines, or when
2711 org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-deadline-warning-days 14
2716 "No. of days before expiration during which a deadline becomes active.
2717 This variable governs the display in sparse trees and in the agenda.
2718 When 0 or negative, it means use this number (the absolute value of it)
2719 even if a deadline has a different individual lead time specified.
2721 Custom commands can set this variable in the options section."
2722 :group 'org-time
2723 :group 'org-agenda-daily/weekly
2724 :type 'integer)
2726 (defcustom org-read-date-prefer-future t
2727 "Non-nil means assume future for incomplete date input from user.
2728 This affects the following situations:
2729 1. The user gives a month but not a year.
2730 For example, if it is April and you enter \"feb 2\", this will be read
2731 as Feb 2, *next* year. \"May 5\", however, will be this year.
2732 2. The user gives a day, but no month.
2733 For example, if today is the 15th, and you enter \"3\", Org-mode will
2734 read this as the third of *next* month. However, if you enter \"17\",
2735 it will be considered as *this* month.
2737 If you set this variable to the symbol `time', then also the following
2738 will work:
2740 3. If the user gives a time, but no day. If the time is before now,
2741 to will be interpreted as tomorrow.
2743 Currently none of this works for ISO week specifications.
2745 When this option is nil, the current day, month and year will always be
2746 used as defaults.
2748 See also `org-agenda-jump-prefer-future'."
2749 :group 'org-time
2750 :type '(choice
2751 (const :tag "Never" nil)
2752 (const :tag "Check month and day" t)
2753 (const :tag "Check month, day, and time" time)))
2755 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2756 "Should the agenda jump command prefer the future for incomplete dates?
2757 The default is to do the same as configured in `org-read-date-prefer-future'.
2758 But you can also set a deviating value here.
2759 This may t or nil, or the symbol `org-read-date-prefer-future'."
2760 :group 'org-agenda
2761 :group 'org-time
2762 :version "24.1"
2763 :type '(choice
2764 (const :tag "Use org-read-date-prefer-future"
2765 org-read-date-prefer-future)
2766 (const :tag "Never" nil)
2767 (const :tag "Always" t)))
2769 (defcustom org-read-date-force-compatible-dates t
2770 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2772 Depending on the system Emacs is running on, certain dates cannot
2773 be represented with the type used internally to represent time.
2774 Dates between 1970-1-1 and 2038-1-1 can always be represented
2775 correctly. Some systems allow for earlier dates, some for later,
2776 some for both. One way to find out it to insert any date into an
2777 Org buffer, putting the cursor on the year and hitting S-up and
2778 S-down to test the range.
2780 When this variable is set to t, the date/time prompt will not let
2781 you specify dates outside the 1970-2037 range, so it is certain that
2782 these dates will work in whatever version of Emacs you are
2783 running, and also that you can move a file from one Emacs implementation
2784 to another. WHenever Org is forcing the year for you, it will display
2785 a message and beep.
2787 When this variable is nil, Org will check if the date is
2788 representable in the specific Emacs implementation you are using.
2789 If not, it will force a year, usually the current year, and beep
2790 to remind you. Currently this setting is not recommended because
2791 the likelihood that you will open your Org files in an Emacs that
2792 has limited date range is not negligible.
2794 A workaround for this problem is to use diary sexp dates for time
2795 stamps outside of this range."
2796 :group 'org-time
2797 :version "24.1"
2798 :type 'boolean)
2800 (defcustom org-read-date-display-live t
2801 "Non-nil means display current interpretation of date prompt live.
2802 This display will be in an overlay, in the minibuffer."
2803 :group 'org-time
2804 :type 'boolean)
2806 (defcustom org-read-date-popup-calendar t
2807 "Non-nil means pop up a calendar when prompting for a date.
2808 In the calendar, the date can be selected with mouse-1. However, the
2809 minibuffer will also be active, and you can simply enter the date as well.
2810 When nil, only the minibuffer will be available."
2811 :group 'org-time
2812 :type 'boolean)
2813 (if (fboundp 'defvaralias)
2814 (defvaralias 'org-popup-calendar-for-date-prompt
2815 'org-read-date-popup-calendar))
2817 (defcustom org-read-date-minibuffer-setup-hook nil
2818 "Hook to be used to set up keys for the date/time interface.
2819 Add key definitions to `minibuffer-local-map', which will be a temporary
2820 copy."
2821 :group 'org-time
2822 :type 'hook)
2824 (defcustom org-extend-today-until 0
2825 "The hour when your day really ends. Must be an integer.
2826 This has influence for the following applications:
2827 - When switching the agenda to \"today\". It it is still earlier than
2828 the time given here, the day recognized as TODAY is actually yesterday.
2829 - When a date is read from the user and it is still before the time given
2830 here, the current date and time will be assumed to be yesterday, 23:59.
2831 Also, timestamps inserted in remember templates follow this rule.
2833 IMPORTANT: This is a feature whose implementation is and likely will
2834 remain incomplete. Really, it is only here because past midnight seems to
2835 be the favorite working time of John Wiegley :-)"
2836 :group 'org-time
2837 :type 'integer)
2839 (defcustom org-use-effective-time nil
2840 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2841 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2842 \"effective time\" of any timestamps between midnight and 8am will be
2843 23:59 of the previous day."
2844 :group 'org-time
2845 :version "24.1"
2846 :type 'boolean)
2848 (defcustom org-edit-timestamp-down-means-later nil
2849 "Non-nil means S-down will increase the time in a time stamp.
2850 When nil, S-up will increase."
2851 :group 'org-time
2852 :type 'boolean)
2854 (defcustom org-calendar-follow-timestamp-change t
2855 "Non-nil means make the calendar window follow timestamp changes.
2856 When a timestamp is modified and the calendar window is visible, it will be
2857 moved to the new date."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defgroup org-tags nil
2862 "Options concerning tags in Org-mode."
2863 :tag "Org Tags"
2864 :group 'org)
2866 (defcustom org-tag-alist nil
2867 "List of tags allowed in Org-mode files.
2868 When this list is nil, Org-mode will base TAG input on what is already in the
2869 buffer.
2870 The value of this variable is an alist, the car of each entry must be a
2871 keyword as a string, the cdr may be a character that is used to select
2872 that tag through the fast-tag-selection interface.
2873 See the manual for details."
2874 :group 'org-tags
2875 :type '(repeat
2876 (choice
2877 (cons (string :tag "Tag name")
2878 (character :tag "Access char"))
2879 (list :tag "Start radio group"
2880 (const :startgroup)
2881 (option (string :tag "Group description")))
2882 (list :tag "End radio group"
2883 (const :endgroup)
2884 (option (string :tag "Group description")))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-tag-persistent-alist nil
2888 "List of tags that will always appear in all Org-mode files.
2889 This is in addition to any in buffer settings or customizations
2890 of `org-tag-alist'.
2891 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2892 The value of this variable is an alist, the car of each entry must be a
2893 keyword as a string, the cdr may be a character that is used to select
2894 that tag through the fast-tag-selection interface.
2895 See the manual for details.
2896 To disable these tags on a per-file basis, insert anywhere in the file:
2897 #+STARTUP: noptag"
2898 :group 'org-tags
2899 :type '(repeat
2900 (choice
2901 (cons (string :tag "Tag name")
2902 (character :tag "Access char"))
2903 (const :tag "Start radio group" (:startgroup))
2904 (const :tag "End radio group" (:endgroup))
2905 (const :tag "New line" (:newline)))))
2907 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2908 "If non-nil, always offer completion for all tags of all agenda files.
2909 Instead of customizing this variable directly, you might want to
2910 set it locally for capture buffers, because there no list of
2911 tags in that file can be created dynamically (there are none).
2913 (add-hook 'org-capture-mode-hook
2914 (lambda ()
2915 (set (make-local-variable
2916 'org-complete-tags-always-offer-all-agenda-tags)
2917 t)))"
2918 :group 'org-tags
2919 :version "24.1"
2920 :type 'boolean)
2922 (defvar org-file-tags nil
2923 "List of tags that can be inherited by all entries in the file.
2924 The tags will be inherited if the variable `org-use-tag-inheritance'
2925 says they should be.
2926 This variable is populated from #+FILETAGS lines.")
2928 (defcustom org-use-fast-tag-selection 'auto
2929 "Non-nil means use fast tag selection scheme.
2930 This is a special interface to select and deselect tags with single keys.
2931 When nil, fast selection is never used.
2932 When the symbol `auto', fast selection is used if and only if selection
2933 characters for tags have been configured, either through the variable
2934 `org-tag-alist' or through a #+TAGS line in the buffer.
2935 When t, fast selection is always used and selection keys are assigned
2936 automatically if necessary."
2937 :group 'org-tags
2938 :type '(choice
2939 (const :tag "Always" t)
2940 (const :tag "Never" nil)
2941 (const :tag "When selection characters are configured" 'auto)))
2943 (defcustom org-fast-tag-selection-single-key nil
2944 "Non-nil means fast tag selection exits after first change.
2945 When nil, you have to press RET to exit it.
2946 During fast tag selection, you can toggle this flag with `C-c'.
2947 This variable can also have the value `expert'. In this case, the window
2948 displaying the tags menu is not even shown, until you press C-c again."
2949 :group 'org-tags
2950 :type '(choice
2951 (const :tag "No" nil)
2952 (const :tag "Yes" t)
2953 (const :tag "Expert" expert)))
2955 (defvar org-fast-tag-selection-include-todo nil
2956 "Non-nil means fast tags selection interface will also offer TODO states.
2957 This is an undocumented feature, you should not rely on it.")
2959 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2960 "The column to which tags should be indented in a headline.
2961 If this number is positive, it specifies the column. If it is negative,
2962 it means that the tags should be flushright to that column. For example,
2963 -80 works well for a normal 80 character screen.
2964 When 0, place tags directly after headline text, with only one space in
2965 between."
2966 :group 'org-tags
2967 :type 'integer)
2969 (defcustom org-auto-align-tags t
2970 "Non-nil keeps tags aligned when modifying headlines.
2971 Some operations (i.e. demoting) change the length of a headline and
2972 therefore shift the tags around. With this option turned on, after
2973 each such operation the tags are again aligned to `org-tags-column'."
2974 :group 'org-tags
2975 :type 'boolean)
2977 (defcustom org-use-tag-inheritance t
2978 "Non-nil means tags in levels apply also for sublevels.
2979 When nil, only the tags directly given in a specific line apply there.
2980 This may also be a list of tags that should be inherited, or a regexp that
2981 matches tags that should be inherited. Additional control is possible
2982 with the variable `org-tags-exclude-from-inheritance' which gives an
2983 explicit list of tags to be excluded from inheritance., even if the value of
2984 `org-use-tag-inheritance' would select it for inheritance.
2986 If this option is t, a match early-on in a tree can lead to a large
2987 number of matches in the subtree when constructing the agenda or creating
2988 a sparse tree. If you only want to see the first match in a tree during
2989 a search, check out the variable `org-tags-match-list-sublevels'."
2990 :group 'org-tags
2991 :type '(choice
2992 (const :tag "Not" nil)
2993 (const :tag "Always" t)
2994 (repeat :tag "Specific tags" (string :tag "Tag"))
2995 (regexp :tag "Tags matched by regexp")))
2997 (defcustom org-tags-exclude-from-inheritance nil
2998 "List of tags that should never be inherited.
2999 This is a way to exclude a few tags from inheritance. For way to do
3000 the opposite, to actively allow inheritance for selected tags,
3001 see the variable `org-use-tag-inheritance'."
3002 :group 'org-tags
3003 :type '(repeat (string :tag "Tag")))
3005 (defun org-tag-inherit-p (tag)
3006 "Check if TAG is one that should be inherited."
3007 (cond
3008 ((member tag org-tags-exclude-from-inheritance) nil)
3009 ((eq org-use-tag-inheritance t) t)
3010 ((not org-use-tag-inheritance) nil)
3011 ((stringp org-use-tag-inheritance)
3012 (string-match org-use-tag-inheritance tag))
3013 ((listp org-use-tag-inheritance)
3014 (member tag org-use-tag-inheritance))
3015 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3017 (defcustom org-tags-match-list-sublevels t
3018 "Non-nil means list also sublevels of headlines matching a search.
3019 This variable applies to tags/property searches, and also to stuck
3020 projects because this search is based on a tags match as well.
3022 When set to the symbol `indented', sublevels are indented with
3023 leading dots.
3025 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3026 the sublevels of a headline matching a tag search often also match
3027 the same search. Listing all of them can create very long lists.
3028 Setting this variable to nil causes subtrees of a match to be skipped.
3030 This variable is semi-obsolete and probably should always be true. It
3031 is better to limit inheritance to certain tags using the variables
3032 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3033 :group 'org-tags
3034 :type '(choice
3035 (const :tag "No, don't list them" nil)
3036 (const :tag "Yes, do list them" t)
3037 (const :tag "List them, indented with leading dots" indented)))
3039 (defcustom org-tags-sort-function nil
3040 "When set, tags are sorted using this function as a comparator."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No sorting" nil)
3044 (const :tag "Alphabetical" string<)
3045 (const :tag "Reverse alphabetical" string>)
3046 (function :tag "Custom function" nil)))
3048 (defvar org-tags-history nil
3049 "History of minibuffer reads for tags.")
3050 (defvar org-last-tags-completion-table nil
3051 "The last used completion table for tags.")
3052 (defvar org-after-tags-change-hook nil
3053 "Hook that is run after the tags in a line have changed.")
3055 (defgroup org-properties nil
3056 "Options concerning properties in Org-mode."
3057 :tag "Org Properties"
3058 :group 'org)
3060 (defcustom org-property-format "%-10s %s"
3061 "How property key/value pairs should be formatted by `indent-line'.
3062 When `indent-line' hits a property definition, it will format the line
3063 according to this format, mainly to make sure that the values are
3064 lined-up with respect to each other."
3065 :group 'org-properties
3066 :type 'string)
3068 (defcustom org-properties-postprocess-alist nil
3069 "Alist of properties and functions to adjust inserted values.
3070 Elements of this alist must be of the form
3072 ([string] [function])
3074 where [string] must be a property name and [function] must be a
3075 lambda expression: this lambda expression must take one argument,
3076 the value to adjust, and return the new value as a string.
3078 For example, this element will allow the property \"Remaining\"
3079 to be updated wrt the relation between the \"Effort\" property
3080 and the clock summary:
3082 ((\"Remaining\" (lambda(value)
3083 (let ((clocksum (org-clock-sum-current-item))
3084 (effort (org-duration-string-to-minutes
3085 (org-entry-get (point) \"Effort\"))))
3086 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3087 :group 'org-properties
3088 :version "24.1"
3089 :type 'alist)
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-agenda-action-key [?k]
3287 "The key to be installed in `calendar-mode-map' for agenda-action.
3288 The command `org-agenda-action' will be bound to this key. The
3289 default is the character `k' because we use the same key in the agenda."
3290 :group 'org-agenda
3291 :type 'sexp)
3293 (defcustom org-calendar-insert-diary-entry-key [?i]
3294 "The key to be installed in `calendar-mode-map' for adding diary entries.
3295 This option is irrelevant until `org-agenda-diary-file' has been configured
3296 to point to an Org-mode file. When that is the case, the command
3297 `org-agenda-diary-entry' will be bound to the key given here, by default
3298 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3299 if you want to continue doing this, you need to change this to a different
3300 key."
3301 :group 'org-agenda
3302 :type 'sexp)
3304 (defcustom org-agenda-diary-file 'diary-file
3305 "File to which to add new entries with the `i' key in agenda and calendar.
3306 When this is the symbol `diary-file', the functionality in the Emacs
3307 calendar will be used to add entries to the `diary-file'. But when this
3308 points to a file, `org-agenda-diary-entry' will be used instead."
3309 :group 'org-agenda
3310 :type '(choice
3311 (const :tag "The standard Emacs diary file" diary-file)
3312 (file :tag "Special Org file diary entries")))
3314 (eval-after-load "calendar"
3315 '(progn
3316 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3317 'org-calendar-goto-agenda)
3318 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3319 'org-agenda-action)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defun org-format-latex-mathml-available-p ()
3394 "Return t if `org-latex-to-mathml-convert-command' is usable."
3395 (save-match-data
3396 (when (and (boundp 'org-latex-to-mathml-convert-command)
3397 org-latex-to-mathml-convert-command)
3398 (let ((executable (car (split-string
3399 org-latex-to-mathml-convert-command))))
3400 (when (executable-find executable)
3401 (if (string-match
3402 "%j" org-latex-to-mathml-convert-command)
3403 (file-readable-p org-latex-to-mathml-jar-file)
3404 t))))))
3406 (defcustom org-format-latex-header "\\documentclass{article}
3407 \\usepackage[usenames]{color}
3408 \\usepackage{amsmath}
3409 \\usepackage[mathscr]{eucal}
3410 \\pagestyle{empty} % do not remove
3411 \[PACKAGES]
3412 \[DEFAULT-PACKAGES]
3413 % The settings below are copied from fullpage.sty
3414 \\setlength{\\textwidth}{\\paperwidth}
3415 \\addtolength{\\textwidth}{-3cm}
3416 \\setlength{\\oddsidemargin}{1.5cm}
3417 \\addtolength{\\oddsidemargin}{-2.54cm}
3418 \\setlength{\\evensidemargin}{\\oddsidemargin}
3419 \\setlength{\\textheight}{\\paperheight}
3420 \\addtolength{\\textheight}{-\\headheight}
3421 \\addtolength{\\textheight}{-\\headsep}
3422 \\addtolength{\\textheight}{-\\footskip}
3423 \\addtolength{\\textheight}{-3cm}
3424 \\setlength{\\topmargin}{1.5cm}
3425 \\addtolength{\\topmargin}{-2.54cm}"
3426 "The document header used for processing LaTeX fragments.
3427 It is imperative that this header make sure that no page number
3428 appears on the page. The package defined in the variables
3429 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3430 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3431 will be appended."
3432 :group 'org-latex
3433 :type 'string)
3435 (defvar org-format-latex-header-extra nil)
3437 (defun org-set-packages-alist (var val)
3438 "Set the packages alist and make sure it has 3 elements per entry."
3439 (set var (mapcar (lambda (x)
3440 (if (and (consp x) (= (length x) 2))
3441 (list (car x) (nth 1 x) t)
3443 val)))
3445 (defun org-get-packages-alist (var)
3447 "Get the packages alist and make sure it has 3 elements per entry."
3448 (mapcar (lambda (x)
3449 (if (and (consp x) (= (length x) 2))
3450 (list (car x) (nth 1 x) t)
3452 (default-value var)))
3454 ;; The following variables are defined here because is it also used
3455 ;; when formatting latex fragments. Originally it was part of the
3456 ;; LaTeX exporter, which is why the name includes "export".
3457 (defcustom org-export-latex-default-packages-alist
3458 '(("AUTO" "inputenc" t)
3459 ("T1" "fontenc" t)
3460 ("" "fixltx2e" nil)
3461 ("" "graphicx" t)
3462 ("" "longtable" nil)
3463 ("" "float" nil)
3464 ("" "wrapfig" nil)
3465 ("" "soul" t)
3466 ("" "textcomp" t)
3467 ("" "marvosym" t)
3468 ("" "wasysym" t)
3469 ("" "latexsym" t)
3470 ("" "amssymb" t)
3471 ("" "hyperref" nil)
3472 "\\tolerance=1000"
3474 "Alist of default packages to be inserted in the header.
3475 Change this only if one of the packages here causes an incompatibility
3476 with another package you are using.
3477 The packages in this list are needed by one part or another of Org-mode
3478 to function properly.
3480 - inputenc, fontenc: for basic font and character selection
3481 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3482 for interpreting the entities in `org-entities'. You can skip some of these
3483 packages if you don't use any of the symbols in it.
3484 - graphicx: for including images
3485 - float, wrapfig: for figure placement
3486 - longtable: for long tables
3487 - hyperref: for cross references
3489 Therefore you should not modify this variable unless you know what you
3490 are doing. The one reason to change it anyway is that you might be loading
3491 some other package that conflicts with one of the default packages.
3492 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3493 If SNIPPET-FLAG is t, the package also needs to be included when
3494 compiling LaTeX snippets into images for inclusion into HTML."
3495 :group 'org-export-latex
3496 :set 'org-set-packages-alist
3497 :get 'org-get-packages-alist
3498 :version "24.1"
3499 :type '(repeat
3500 (choice
3501 (list :tag "options/package pair"
3502 (string :tag "options")
3503 (string :tag "package")
3504 (boolean :tag "Snippet"))
3505 (string :tag "A line of LaTeX"))))
3507 (defcustom org-export-latex-packages-alist nil
3508 "Alist of packages to be inserted in every LaTeX header.
3509 These will be inserted after `org-export-latex-default-packages-alist'.
3510 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3511 SNIPPET-FLAG, when t, indicates that this package is also needed when
3512 turning LaTeX snippets into images for inclusion into HTML.
3513 Make sure that you only list packages here which:
3514 - you want in every file
3515 - do not conflict with the default packages in
3516 `org-export-latex-default-packages-alist'
3517 - do not conflict with the setup in `org-format-latex-header'."
3518 :group 'org-export-latex
3519 :set 'org-set-packages-alist
3520 :get 'org-get-packages-alist
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3530 (defgroup org-appearance nil
3531 "Settings for Org-mode appearance."
3532 :tag "Org Appearance"
3533 :group 'org)
3535 (defcustom org-level-color-stars-only nil
3536 "Non-nil means fontify only the stars in each headline.
3537 When nil, the entire headline is fontified.
3538 Changing it requires restart of `font-lock-mode' to become effective
3539 also in regions already fontified."
3540 :group 'org-appearance
3541 :type 'boolean)
3543 (defcustom org-hide-leading-stars nil
3544 "Non-nil means hide the first N-1 stars in a headline.
3545 This works by using the face `org-hide' for these stars. This
3546 face is white for a light background, and black for a dark
3547 background. You may have to customize the face `org-hide' to
3548 make this work.
3549 Changing it requires restart of `font-lock-mode' to become effective
3550 also in regions already fontified.
3551 You may also set this on a per-file basis by adding one of the following
3552 lines to the buffer:
3554 #+STARTUP: hidestars
3555 #+STARTUP: showstars"
3556 :group 'org-appearance
3557 :type 'boolean)
3559 (defcustom org-hidden-keywords nil
3560 "List of symbols corresponding to keywords to be hidden the org buffer.
3561 For example, a value '(title) for this list will make the document's title
3562 appear in the buffer without the initial #+TITLE: keyword."
3563 :group 'org-appearance
3564 :version "24.1"
3565 :type '(set (const :tag "#+AUTHOR" author)
3566 (const :tag "#+DATE" date)
3567 (const :tag "#+EMAIL" email)
3568 (const :tag "#+TITLE" title)))
3570 (defcustom org-fontify-done-headline nil
3571 "Non-nil means change the face of a headline if it is marked DONE.
3572 Normally, only the TODO/DONE keyword indicates the state of a headline.
3573 When this is non-nil, the headline after the keyword is set to the
3574 `org-headline-done' as an additional indication."
3575 :group 'org-appearance
3576 :type 'boolean)
3578 (defcustom org-fontify-emphasized-text t
3579 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3580 Changing this variable requires a restart of Emacs to take effect."
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-fontify-whole-heading-line nil
3585 "Non-nil means fontify the whole line for headings.
3586 This is useful when setting a background color for the
3587 org-level-* faces."
3588 :group 'org-appearance
3589 :type 'boolean)
3591 (defcustom org-highlight-latex-fragments-and-specials nil
3592 "Non-nil means fontify what is treated specially by the exporters."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-hide-emphasis-markers nil
3597 "Non-nil mean font-lock should hide the emphasis marker characters."
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-pretty-entities nil
3602 "Non-nil means show entities as UTF8 characters.
3603 When nil, the \\name form remains in the buffer."
3604 :group 'org-appearance
3605 :version "24.1"
3606 :type 'boolean)
3608 (defcustom org-pretty-entities-include-sub-superscripts t
3609 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3610 :group 'org-appearance
3611 :version "24.1"
3612 :type 'boolean)
3614 (defvar org-emph-re nil
3615 "Regular expression for matching emphasis.
3616 After a match, the match groups contain these elements:
3617 0 The match of the full regular expression, including the characters
3618 before and after the proper match
3619 1 The character before the proper match, or empty at beginning of line
3620 2 The proper match, including the leading and trailing markers
3621 3 The leading marker like * or /, indicating the type of highlighting
3622 4 The text between the emphasis markers, not including the markers
3623 5 The character after the match, empty at the end of a line")
3624 (defvar org-verbatim-re nil
3625 "Regular expression for matching verbatim text.")
3626 (defvar org-emphasis-regexp-components) ; defined just below
3627 (defvar org-emphasis-alist) ; defined just below
3628 (defun org-set-emph-re (var val)
3629 "Set variable and compute the emphasis regular expression."
3630 (set var val)
3631 (when (and (boundp 'org-emphasis-alist)
3632 (boundp 'org-emphasis-regexp-components)
3633 org-emphasis-alist org-emphasis-regexp-components)
3634 (let* ((e org-emphasis-regexp-components)
3635 (pre (car e))
3636 (post (nth 1 e))
3637 (border (nth 2 e))
3638 (body (nth 3 e))
3639 (nl (nth 4 e))
3640 (body1 (concat body "*?"))
3641 (markers (mapconcat 'car org-emphasis-alist ""))
3642 (vmarkers (mapconcat
3643 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3644 org-emphasis-alist "")))
3645 ;; make sure special characters appear at the right position in the class
3646 (if (string-match "\\^" markers)
3647 (setq markers (concat (replace-match "" t t markers) "^")))
3648 (if (string-match "-" markers)
3649 (setq markers (concat (replace-match "" t t markers) "-")))
3650 (if (string-match "\\^" vmarkers)
3651 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3652 (if (string-match "-" vmarkers)
3653 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3654 (if (> nl 0)
3655 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3656 (int-to-string nl) "\\}")))
3657 ;; Make the regexp
3658 (setq org-emph-re
3659 (concat "\\([" pre "]\\|^\\)"
3660 "\\("
3661 "\\([" markers "]\\)"
3662 "\\("
3663 "[^" border "]\\|"
3664 "[^" border "]"
3665 body1
3666 "[^" border "]"
3667 "\\)"
3668 "\\3\\)"
3669 "\\([" post "]\\|$\\)"))
3670 (setq org-verbatim-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" vmarkers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)")))))
3683 (defcustom org-emphasis-regexp-components
3684 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3685 "Components used to build the regular expression for emphasis.
3686 This is a list with five entries. Terminology: In an emphasis string
3687 like \" *strong word* \", we call the initial space PREMATCH, the final
3688 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3689 and \"trong wor\" is the body. The different components in this variable
3690 specify what is allowed/forbidden in each part:
3692 pre Chars allowed as prematch. Beginning of line will be allowed too.
3693 post Chars allowed as postmatch. End of line will be allowed too.
3694 border The chars *forbidden* as border characters.
3695 body-regexp A regexp like \".\" to match a body character. Don't use
3696 non-shy groups here, and don't allow newline here.
3697 newline The maximum number of newlines allowed in an emphasis exp.
3699 Use customize to modify this, or restart Emacs after changing it."
3700 :group 'org-appearance
3701 :set 'org-set-emph-re
3702 :type '(list
3703 (sexp :tag "Allowed chars in pre ")
3704 (sexp :tag "Allowed chars in post ")
3705 (sexp :tag "Forbidden chars in border ")
3706 (sexp :tag "Regexp for body ")
3707 (integer :tag "number of newlines allowed")
3708 (option (boolean :tag "Please ignore this button"))))
3710 (defcustom org-emphasis-alist
3711 `(("*" bold "<b>" "</b>")
3712 ("/" italic "<i>" "</i>")
3713 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3714 ("=" org-code "<code>" "</code>" verbatim)
3715 ("~" org-verbatim "<code>" "</code>" verbatim)
3716 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3717 "<del>" "</del>")
3719 "Special syntax for emphasized text.
3720 Text starting and ending with a special character will be emphasized, for
3721 example *bold*, _underlined_ and /italic/. This variable sets the marker
3722 characters, the face to be used by font-lock for highlighting in Org-mode
3723 Emacs buffers, and the HTML tags to be used for this.
3724 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3725 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3726 Use customize to modify this, or restart Emacs after changing it."
3727 :group 'org-appearance
3728 :set 'org-set-emph-re
3729 :type '(repeat
3730 (list
3731 (string :tag "Marker character")
3732 (choice
3733 (face :tag "Font-lock-face")
3734 (plist :tag "Face property list"))
3735 (string :tag "HTML start tag")
3736 (string :tag "HTML end tag")
3737 (option (const verbatim)))))
3739 (defvar org-protecting-blocks
3740 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3741 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3742 This is needed for font-lock setup.")
3744 ;;; Miscellaneous options
3746 (defgroup org-completion nil
3747 "Completion in Org-mode."
3748 :tag "Org Completion"
3749 :group 'org)
3751 (defcustom org-completion-use-ido nil
3752 "Non-nil means use ido completion wherever possible.
3753 Note that `ido-mode' must be active for this variable to be relevant.
3754 If you decide to turn this variable on, you might well want to turn off
3755 `org-outline-path-complete-in-steps'.
3756 See also `org-completion-use-iswitchb'."
3757 :group 'org-completion
3758 :type 'boolean)
3760 (defcustom org-completion-use-iswitchb nil
3761 "Non-nil means use iswitchb completion wherever possible.
3762 Note that `iswitchb-mode' must be active for this variable to be relevant.
3763 If you decide to turn this variable on, you might well want to turn off
3764 `org-outline-path-complete-in-steps'.
3765 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3766 :group 'org-completion
3767 :type 'boolean)
3769 (defcustom org-completion-fallback-command 'hippie-expand
3770 "The expansion command called by \\[pcomplete] in normal context.
3771 Normal means, no org-mode-specific context."
3772 :group 'org-completion
3773 :type 'function)
3775 ;;; Functions and variables from their packages
3776 ;; Declared here to avoid compiler warnings
3778 ;; XEmacs only
3779 (defvar outline-mode-menu-heading)
3780 (defvar outline-mode-menu-show)
3781 (defvar outline-mode-menu-hide)
3782 (defvar zmacs-regions) ; XEmacs regions
3784 ;; Emacs only
3785 (defvar mark-active)
3787 ;; Various packages
3788 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3789 (declare-function calendar-forward-day "cal-move" (arg))
3790 (declare-function calendar-goto-date "cal-move" (date))
3791 (declare-function calendar-goto-today "cal-move" ())
3792 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3793 (defvar calc-embedded-close-formula)
3794 (defvar calc-embedded-open-formula)
3795 (declare-function cdlatex-tab "ext:cdlatex" ())
3796 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3797 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3798 (defvar font-lock-unfontify-region-function)
3799 (declare-function iswitchb-read-buffer "iswitchb"
3800 (prompt &optional default require-match start matches-set))
3801 (defvar iswitchb-temp-buflist)
3802 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3803 (defvar org-agenda-tags-todo-honor-ignore-options)
3804 (declare-function org-agenda-skip "org-agenda" ())
3805 (declare-function
3806 org-agenda-format-item "org-agenda"
3807 (extra txt &optional category tags dotime noprefix remove-re habitp))
3808 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3809 (declare-function org-agenda-change-all-lines "org-agenda"
3810 (newhead hdmarker &optional fixface just-this))
3811 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3812 (declare-function org-agenda-maybe-redo "org-agenda" ())
3813 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3814 (beg end))
3815 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3816 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3817 "org-agenda" (&optional end))
3818 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3819 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3820 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3821 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3822 (declare-function org-indent-mode "org-indent" (&optional arg))
3823 (declare-function parse-time-string "parse-time" (string))
3824 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3825 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3826 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3827 (defvar remember-data-file)
3828 (defvar texmathp-why)
3829 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3830 (declare-function table--at-cell-p "table" (position &optional object at-column))
3832 (defvar w3m-current-url)
3833 (defvar w3m-current-title)
3835 (defvar org-latex-regexps)
3837 ;;; Autoload and prepare some org modules
3839 ;; Some table stuff that needs to be defined here, because it is used
3840 ;; by the functions setting up org-mode or checking for table context.
3842 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3843 "Detect an org-type or table-type table.")
3844 (defconst org-table-line-regexp "^[ \t]*|"
3845 "Detect an org-type table line.")
3846 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3847 "Detect an org-type table line.")
3848 (defconst org-table-hline-regexp "^[ \t]*|-"
3849 "Detect an org-type table hline.")
3850 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3851 "Detect a table-type table hline.")
3852 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3853 "Detect the first line outside a table when searching from within it.
3854 This works for both table types.")
3856 ;; Autoload the functions in org-table.el that are needed by functions here.
3858 (eval-and-compile
3859 (org-autoload "org-table"
3860 '(org-table-align org-table-begin org-table-blank-field
3861 org-table-convert org-table-convert-region org-table-copy-down
3862 org-table-copy-region org-table-create
3863 org-table-create-or-convert-from-region
3864 org-table-create-with-table.el org-table-current-dline
3865 org-table-cut-region org-table-delete-column org-table-edit-field
3866 org-table-edit-formulas org-table-end org-table-eval-formula
3867 org-table-export org-table-field-info
3868 org-table-get-stored-formulas org-table-goto-column
3869 org-table-hline-and-move org-table-import org-table-insert-column
3870 org-table-insert-hline org-table-insert-row org-table-iterate
3871 org-table-justify-field-maybe org-table-kill-row
3872 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3873 org-table-move-column org-table-move-column-left
3874 org-table-move-column-right org-table-move-row
3875 org-table-move-row-down org-table-move-row-up
3876 org-table-next-field org-table-next-row org-table-paste-rectangle
3877 org-table-previous-field org-table-recalculate
3878 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3879 org-table-toggle-coordinate-overlays
3880 org-table-toggle-formula-debugger org-table-wrap-region
3881 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3882 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3883 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3885 (defun org-at-table-p (&optional table-type)
3886 "Return t if the cursor is inside an org-type table.
3887 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3888 (if org-enable-table-editor
3889 (save-excursion
3890 (beginning-of-line 1)
3891 (looking-at (if table-type org-table-any-line-regexp
3892 org-table-line-regexp)))
3893 nil))
3894 (defsubst org-table-p () (org-at-table-p))
3896 (defun org-at-table.el-p ()
3897 "Return t if and only if we are at a table.el table."
3898 (and (org-at-table-p 'any)
3899 (save-excursion
3900 (goto-char (org-table-begin 'any))
3901 (looking-at org-table1-hline-regexp))))
3902 (defun org-table-recognize-table.el ()
3903 "If there is a table.el table nearby, recognize it and move into it."
3904 (if org-table-tab-recognizes-table.el
3905 (if (org-at-table.el-p)
3906 (progn
3907 (beginning-of-line 1)
3908 (if (looking-at org-table-dataline-regexp)
3910 (if (looking-at org-table1-hline-regexp)
3911 (progn
3912 (beginning-of-line 2)
3913 (if (looking-at org-table-any-border-regexp)
3914 (beginning-of-line -1)))))
3915 (if (re-search-forward "|" (org-table-end t) t)
3916 (progn
3917 (require 'table)
3918 (if (table--at-cell-p (point))
3920 (message "recognizing table.el table...")
3921 (table-recognize-table)
3922 (message "recognizing table.el table...done")))
3923 (error "This should not happen"))
3925 nil)
3926 nil))
3928 (defun org-at-table-hline-p ()
3929 "Return t if the cursor is inside a hline in a table."
3930 (if org-enable-table-editor
3931 (save-excursion
3932 (beginning-of-line 1)
3933 (looking-at org-table-hline-regexp))
3934 nil))
3936 (defvar org-table-clean-did-remove-column nil)
3938 (defun org-table-map-tables (function &optional quietly)
3939 "Apply FUNCTION to the start of all tables in the buffer."
3940 (save-excursion
3941 (save-restriction
3942 (widen)
3943 (goto-char (point-min))
3944 (while (re-search-forward org-table-any-line-regexp nil t)
3945 (unless quietly
3946 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3947 (beginning-of-line 1)
3948 (when (and (looking-at org-table-line-regexp)
3949 ;; Exclude tables in src/example/verbatim/clocktable blocks
3950 (not (org-in-block-p '("src" "example"))))
3951 (save-excursion (funcall function))
3952 (or (looking-at org-table-line-regexp)
3953 (forward-char 1)))
3954 (re-search-forward org-table-any-border-regexp nil 1))))
3955 (unless quietly (message "Mapping tables: done")))
3957 ;; Declare and autoload functions from org-exp.el & Co
3959 (declare-function org-default-export-plist "org-exp")
3960 (declare-function org-infile-export-plist "org-exp")
3961 (declare-function org-get-current-options "org-exp")
3962 (eval-and-compile
3963 (org-autoload "org-exp"
3964 '(org-export org-export-visible
3965 org-insert-export-options-template
3966 org-table-clean-before-export))
3967 (org-autoload "org-ascii"
3968 '(org-export-as-ascii org-export-ascii-preprocess
3969 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3970 org-export-region-as-ascii))
3971 (org-autoload "org-latex"
3972 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3973 org-replace-region-by-latex org-export-region-as-latex
3974 org-export-as-latex org-export-as-pdf
3975 org-export-as-pdf-and-open))
3976 (org-autoload "org-html"
3977 '(org-export-as-html-and-open
3978 org-export-as-html-batch org-export-as-html-to-buffer
3979 org-replace-region-by-html org-export-region-as-html
3980 org-export-as-html))
3981 (org-autoload "org-docbook"
3982 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3983 org-replace-region-by-docbook org-export-region-as-docbook
3984 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3985 org-export-as-docbook))
3986 (org-autoload "org-icalendar"
3987 '(org-export-icalendar-this-file
3988 org-export-icalendar-all-agenda-files
3989 org-export-icalendar-combine-agenda-files))
3990 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3991 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3993 ;; Declare and autoload functions from org-agenda.el
3995 (eval-and-compile
3996 (org-autoload "org-agenda"
3997 '(org-agenda org-agenda-list org-search-view
3998 org-todo-list org-tags-view org-agenda-list-stuck-projects
3999 org-diary org-agenda-to-appt
4000 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4002 ;; Autoload org-remember
4004 (eval-and-compile
4005 (org-autoload "org-remember"
4006 '(org-remember-insinuate org-remember-annotation
4007 org-remember-apply-template org-remember org-remember-handler)))
4009 (eval-and-compile
4010 (org-autoload "org-capture"
4011 '(org-capture org-capture-insert-template-here
4012 org-capture-import-remember-templates)))
4014 ;; Autoload org-clock.el
4016 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4017 (beg end))
4018 (declare-function org-clock-update-mode-line "org-clock" ())
4019 (declare-function org-resolve-clocks "org-clock"
4020 (&optional also-non-dangling-p prompt last-valid))
4021 (defvar org-clock-start-time)
4022 (defvar org-clock-marker (make-marker)
4023 "Marker recording the last clock-in.")
4024 (defvar org-clock-hd-marker (make-marker)
4025 "Marker recording the last clock-in, but the headline position.")
4026 (defvar org-clock-heading ""
4027 "The heading of the current clock entry.")
4028 (defun org-clock-is-active ()
4029 "Return non-nil if clock is currently running.
4030 The return value is actually the clock marker."
4031 (marker-buffer org-clock-marker))
4033 (eval-and-compile
4034 (org-autoload
4035 "org-clock"
4036 '(org-clock-in org-clock-out org-clock-cancel
4037 org-clock-goto org-clock-sum org-clock-display
4038 org-clock-remove-overlays org-clock-report
4039 org-clocktable-shift org-dblock-write:clocktable
4040 org-get-clocktable org-resolve-clocks)))
4042 (defun org-clock-update-time-maybe ()
4043 "If this is a CLOCK line, update it and return t.
4044 Otherwise, return nil."
4045 (interactive)
4046 (save-excursion
4047 (beginning-of-line 1)
4048 (skip-chars-forward " \t")
4049 (when (looking-at org-clock-string)
4050 (let ((re (concat "[ \t]*" org-clock-string
4051 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4052 "\\([ \t]*=>.*\\)?\\)?"))
4053 ts te h m s neg)
4054 (cond
4055 ((not (looking-at re))
4056 nil)
4057 ((not (match-end 2))
4058 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4059 (> org-clock-marker (point))
4060 (<= org-clock-marker (point-at-eol)))
4061 ;; The clock is running here
4062 (setq org-clock-start-time
4063 (apply 'encode-time
4064 (org-parse-time-string (match-string 1))))
4065 (org-clock-update-mode-line)))
4067 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4068 (end-of-line 1)
4069 (setq ts (match-string 1)
4070 te (match-string 3))
4071 (setq s (- (org-float-time
4072 (apply 'encode-time (org-parse-time-string te)))
4073 (org-float-time
4074 (apply 'encode-time (org-parse-time-string ts))))
4075 neg (< s 0)
4076 s (abs s)
4077 h (floor (/ s 3600))
4078 s (- s (* 3600 h))
4079 m (floor (/ s 60))
4080 s (- s (* 60 s)))
4081 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4082 t))))))
4084 (defun org-check-running-clock ()
4085 "Check if the current buffer contains the running clock.
4086 If yes, offer to stop it and to save the buffer with the changes."
4087 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4088 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4089 (buffer-name))))
4090 (org-clock-out)
4091 (when (y-or-n-p "Save changed buffer?")
4092 (save-buffer))))
4094 (defun org-clocktable-try-shift (dir n)
4095 "Check if this line starts a clock table, if yes, shift the time block."
4096 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4097 (org-clocktable-shift dir n)))
4099 ;; Autoload org-timer.el
4101 (eval-and-compile
4102 (org-autoload
4103 "org-timer"
4104 '(org-timer-start org-timer org-timer-item
4105 org-timer-change-times-in-region
4106 org-timer-set-timer
4107 org-timer-reset-timers
4108 org-timer-show-remaining-time)))
4110 ;; Autoload org-feed.el
4112 (eval-and-compile
4113 (org-autoload
4114 "org-feed"
4115 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4118 ;; Autoload org-indent.el
4120 ;; Define the variable already here, to make sure we have it.
4121 (defvar org-indent-mode nil
4122 "Non-nil if Org-Indent mode is enabled.
4123 Use the command `org-indent-mode' to change this variable.")
4125 (eval-and-compile
4126 (org-autoload
4127 "org-indent"
4128 '(org-indent-mode)))
4130 ;; Autoload org-mobile.el
4132 (eval-and-compile
4133 (org-autoload
4134 "org-mobile"
4135 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4137 ;; Autoload archiving code
4138 ;; The stuff that is needed for cycling and tags has to be defined here.
4140 (defgroup org-archive nil
4141 "Options concerning archiving in Org-mode."
4142 :tag "Org Archive"
4143 :group 'org-structure)
4145 (defcustom org-archive-location "%s_archive::"
4146 "The location where subtrees should be archived.
4148 The value of this variable is a string, consisting of two parts,
4149 separated by a double-colon. The first part is a filename and
4150 the second part is a headline.
4152 When the filename is omitted, archiving happens in the same file.
4153 %s in the filename will be replaced by the current file
4154 name (without the directory part). Archiving to a different file
4155 is useful to keep archived entries from contributing to the
4156 Org-mode Agenda.
4158 The archived entries will be filed as subtrees of the specified
4159 headline. When the headline is omitted, the subtrees are simply
4160 filed away at the end of the file, as top-level entries. Also in
4161 the heading you can use %s to represent the file name, this can be
4162 useful when using the same archive for a number of different files.
4164 Here are a few examples:
4165 \"%s_archive::\"
4166 If the current file is Projects.org, archive in file
4167 Projects.org_archive, as top-level trees. This is the default.
4169 \"::* Archived Tasks\"
4170 Archive in the current file, under the top-level headline
4171 \"* Archived Tasks\".
4173 \"~/org/archive.org::\"
4174 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4176 \"~/org/archive.org::* From %s\"
4177 Archive in file ~/org/archive.org (absolute path), under headlines
4178 \"From FILENAME\" where file name is the current file name.
4180 \"basement::** Finished Tasks\"
4181 Archive in file ./basement (relative path), as level 3 trees
4182 below the level 2 heading \"** Finished Tasks\".
4184 You may set this option on a per-file basis by adding to the buffer a
4185 line like
4187 #+ARCHIVE: basement::** Finished Tasks
4189 You may also define it locally for a subtree by setting an ARCHIVE property
4190 in the entry. If such a property is found in an entry, or anywhere up
4191 the hierarchy, it will be used."
4192 :group 'org-archive
4193 :type 'string)
4195 (defcustom org-archive-tag "ARCHIVE"
4196 "The tag that marks a subtree as archived.
4197 An archived subtree does not open during visibility cycling, and does
4198 not contribute to the agenda listings.
4199 After changing this, font-lock must be restarted in the relevant buffers to
4200 get the proper fontification."
4201 :group 'org-archive
4202 :group 'org-keywords
4203 :type 'string)
4205 (defcustom org-agenda-skip-archived-trees t
4206 "Non-nil means the agenda will skip any items located in archived trees.
4207 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4208 variable is no longer recommended, you should leave it at the value t.
4209 Instead, use the key `v' to cycle the archives-mode in the agenda."
4210 :group 'org-archive
4211 :group 'org-agenda-skip
4212 :type 'boolean)
4214 (defcustom org-columns-skip-archived-trees t
4215 "Non-nil means ignore archived trees when creating column view."
4216 :group 'org-archive
4217 :group 'org-properties
4218 :type 'boolean)
4220 (defcustom org-cycle-open-archived-trees nil
4221 "Non-nil means `org-cycle' will open archived trees.
4222 An archived tree is a tree marked with the tag ARCHIVE.
4223 When nil, archived trees will stay folded. You can still open them with
4224 normal outline commands like `show-all', but not with the cycling commands."
4225 :group 'org-archive
4226 :group 'org-cycle
4227 :type 'boolean)
4229 (defcustom org-sparse-tree-open-archived-trees nil
4230 "Non-nil means sparse tree construction shows matches in archived trees.
4231 When nil, matches in these trees are highlighted, but the trees are kept in
4232 collapsed state."
4233 :group 'org-archive
4234 :group 'org-sparse-trees
4235 :type 'boolean)
4237 (defun org-cycle-hide-archived-subtrees (state)
4238 "Re-hide all archived subtrees after a visibility state change."
4239 (when (and (not org-cycle-open-archived-trees)
4240 (not (memq state '(overview folded))))
4241 (save-excursion
4242 (let* ((globalp (memq state '(contents all)))
4243 (beg (if globalp (point-min) (point)))
4244 (end (if globalp (point-max) (org-end-of-subtree t))))
4245 (org-hide-archived-subtrees beg end)
4246 (goto-char beg)
4247 (if (looking-at (concat ".*:" org-archive-tag ":"))
4248 (message "%s" (substitute-command-keys
4249 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4251 (defun org-force-cycle-archived ()
4252 "Cycle subtree even if it is archived."
4253 (interactive)
4254 (setq this-command 'org-cycle)
4255 (let ((org-cycle-open-archived-trees t))
4256 (call-interactively 'org-cycle)))
4258 (defun org-hide-archived-subtrees (beg end)
4259 "Re-hide all archived subtrees after a visibility state change."
4260 (save-excursion
4261 (let* ((re (concat ":" org-archive-tag ":")))
4262 (goto-char beg)
4263 (while (re-search-forward re end t)
4264 (when (org-at-heading-p)
4265 (org-flag-subtree t)
4266 (org-end-of-subtree t))))))
4268 (defun org-flag-subtree (flag)
4269 (save-excursion
4270 (org-back-to-heading t)
4271 (outline-end-of-heading)
4272 (outline-flag-region (point)
4273 (progn (org-end-of-subtree t) (point))
4274 flag)))
4276 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4278 (eval-and-compile
4279 (org-autoload "org-archive"
4280 '(org-add-archive-files org-archive-subtree
4281 org-archive-to-archive-sibling org-toggle-archive-tag
4282 org-archive-subtree-default
4283 org-archive-subtree-default-with-confirmation)))
4285 ;; Autoload Column View Code
4287 (declare-function org-columns-number-to-string "org-colview")
4288 (declare-function org-columns-get-format-and-top-level "org-colview")
4289 (declare-function org-columns-compute "org-colview")
4291 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4292 '(org-columns-number-to-string org-columns-get-format-and-top-level
4293 org-columns-compute org-agenda-columns org-columns-remove-overlays
4294 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4296 ;; Autoload ID code
4298 (declare-function org-id-store-link "org-id")
4299 (declare-function org-id-locations-load "org-id")
4300 (declare-function org-id-locations-save "org-id")
4301 (defvar org-id-track-globally)
4302 (org-autoload "org-id"
4303 '(org-id-get-create org-id-new org-id-copy org-id-get
4304 org-id-get-with-outline-path-completion
4305 org-id-get-with-outline-drilling org-id-store-link
4306 org-id-goto org-id-find org-id-store-link))
4308 ;; Autoload Plotting Code
4310 (org-autoload "org-plot"
4311 '(org-plot/gnuplot))
4313 ;;; Variables for pre-computed regular expressions, all buffer local
4315 (defvar org-drawer-regexp nil
4316 "Matches first line of a hidden block.")
4317 (make-variable-buffer-local 'org-drawer-regexp)
4318 (defvar org-todo-regexp nil
4319 "Matches any of the TODO state keywords.")
4320 (make-variable-buffer-local 'org-todo-regexp)
4321 (defvar org-not-done-regexp nil
4322 "Matches any of the TODO state keywords except the last one.")
4323 (make-variable-buffer-local 'org-not-done-regexp)
4324 (defvar org-not-done-heading-regexp nil
4325 "Matches a TODO headline that is not done.")
4326 (make-variable-buffer-local 'org-not-done-regexp)
4327 (defvar org-todo-line-regexp nil
4328 "Matches a headline and puts TODO state into group 2 if present.")
4329 (make-variable-buffer-local 'org-todo-line-regexp)
4330 (defvar org-complex-heading-regexp nil
4331 "Matches a headline and puts everything into groups:
4332 group 1: the stars
4333 group 2: The todo keyword, maybe
4334 group 3: Priority cookie
4335 group 4: True headline
4336 group 5: Tags")
4337 (make-variable-buffer-local 'org-complex-heading-regexp)
4338 (defvar org-complex-heading-regexp-format nil
4339 "Printf format to make regexp to match an exact headline.
4340 This regexp will match the headline of any node which has the
4341 exact headline text that is put into the format, but may have any
4342 TODO state, priority and tags.")
4343 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4344 (defvar org-todo-line-tags-regexp nil
4345 "Matches a headline and puts TODO state into group 2 if present.
4346 Also put tags into group 4 if tags are present.")
4347 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4348 (defvar org-ds-keyword-length 12
4349 "Maximum length of the Deadline and SCHEDULED keywords.")
4350 (make-variable-buffer-local 'org-ds-keyword-length)
4351 (defvar org-deadline-regexp nil
4352 "Matches the DEADLINE keyword.")
4353 (make-variable-buffer-local 'org-deadline-regexp)
4354 (defvar org-deadline-time-regexp nil
4355 "Matches the DEADLINE keyword together with a time stamp.")
4356 (make-variable-buffer-local 'org-deadline-time-regexp)
4357 (defvar org-deadline-line-regexp nil
4358 "Matches the DEADLINE keyword and the rest of the line.")
4359 (make-variable-buffer-local 'org-deadline-line-regexp)
4360 (defvar org-scheduled-regexp nil
4361 "Matches the SCHEDULED keyword.")
4362 (make-variable-buffer-local 'org-scheduled-regexp)
4363 (defvar org-scheduled-time-regexp nil
4364 "Matches the SCHEDULED keyword together with a time stamp.")
4365 (make-variable-buffer-local 'org-scheduled-time-regexp)
4366 (defvar org-closed-time-regexp nil
4367 "Matches the CLOSED keyword together with a time stamp.")
4368 (make-variable-buffer-local 'org-closed-time-regexp)
4370 (defvar org-keyword-time-regexp nil
4371 "Matches any of the 4 keywords, together with the time stamp.")
4372 (make-variable-buffer-local 'org-keyword-time-regexp)
4373 (defvar org-keyword-time-not-clock-regexp nil
4374 "Matches any of the 3 keywords, together with the time stamp.")
4375 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4376 (defvar org-maybe-keyword-time-regexp nil
4377 "Matches a timestamp, possibly preceded by a keyword.")
4378 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4379 (defvar org-planning-or-clock-line-re nil
4380 "Matches a line with planning or clock info.")
4381 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4382 (defvar org-all-time-keywords nil
4383 "List of time keywords.")
4384 (make-variable-buffer-local 'org-all-time-keywords)
4386 (defconst org-plain-time-of-day-regexp
4387 (concat
4388 "\\(\\<[012]?[0-9]"
4389 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4390 "\\(--?"
4391 "\\(\\<[012]?[0-9]"
4392 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4393 "\\)?")
4394 "Regular expression to match a plain time or time range.
4395 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4396 groups carry important information:
4397 0 the full match
4398 1 the first time, range or not
4399 8 the second time, if it is a range.")
4401 (defconst org-plain-time-extension-regexp
4402 (concat
4403 "\\(\\<[012]?[0-9]"
4404 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4405 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4406 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4407 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4408 groups carry important information:
4409 0 the full match
4410 7 hours of duration
4411 9 minutes of duration")
4413 (defconst org-stamp-time-of-day-regexp
4414 (concat
4415 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4416 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4417 "\\(--?"
4418 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4419 "Regular expression to match a timestamp time or time range.
4420 After a match, the following groups carry important information:
4421 0 the full match
4422 1 date plus weekday, for back referencing to make sure both times are on the same day
4423 2 the first time, range or not
4424 4 the second time, if it is a range.")
4426 (defconst org-startup-options
4427 '(("fold" org-startup-folded t)
4428 ("overview" org-startup-folded t)
4429 ("nofold" org-startup-folded nil)
4430 ("showall" org-startup-folded nil)
4431 ("showeverything" org-startup-folded showeverything)
4432 ("content" org-startup-folded content)
4433 ("indent" org-startup-indented t)
4434 ("noindent" org-startup-indented nil)
4435 ("hidestars" org-hide-leading-stars t)
4436 ("showstars" org-hide-leading-stars nil)
4437 ("odd" org-odd-levels-only t)
4438 ("oddeven" org-odd-levels-only nil)
4439 ("align" org-startup-align-all-tables t)
4440 ("noalign" org-startup-align-all-tables nil)
4441 ("inlineimages" org-startup-with-inline-images t)
4442 ("noinlineimages" org-startup-with-inline-images nil)
4443 ("customtime" org-display-custom-times t)
4444 ("logdone" org-log-done time)
4445 ("lognotedone" org-log-done note)
4446 ("nologdone" org-log-done nil)
4447 ("lognoteclock-out" org-log-note-clock-out t)
4448 ("nolognoteclock-out" org-log-note-clock-out nil)
4449 ("logrepeat" org-log-repeat state)
4450 ("lognoterepeat" org-log-repeat note)
4451 ("nologrepeat" org-log-repeat nil)
4452 ("logreschedule" org-log-reschedule time)
4453 ("lognotereschedule" org-log-reschedule note)
4454 ("nologreschedule" org-log-reschedule nil)
4455 ("logredeadline" org-log-redeadline time)
4456 ("lognoteredeadline" org-log-redeadline note)
4457 ("nologredeadline" org-log-redeadline nil)
4458 ("logrefile" org-log-refile time)
4459 ("lognoterefile" org-log-refile note)
4460 ("nologrefile" org-log-refile nil)
4461 ("fninline" org-footnote-define-inline t)
4462 ("nofninline" org-footnote-define-inline nil)
4463 ("fnlocal" org-footnote-section nil)
4464 ("fnauto" org-footnote-auto-label t)
4465 ("fnprompt" org-footnote-auto-label nil)
4466 ("fnconfirm" org-footnote-auto-label confirm)
4467 ("fnplain" org-footnote-auto-label plain)
4468 ("fnadjust" org-footnote-auto-adjust t)
4469 ("nofnadjust" org-footnote-auto-adjust nil)
4470 ("constcgs" constants-unit-system cgs)
4471 ("constSI" constants-unit-system SI)
4472 ("noptag" org-tag-persistent-alist nil)
4473 ("hideblocks" org-hide-block-startup t)
4474 ("nohideblocks" org-hide-block-startup nil)
4475 ("beamer" org-startup-with-beamer-mode t)
4476 ("entitiespretty" org-pretty-entities t)
4477 ("entitiesplain" org-pretty-entities nil))
4478 "Variable associated with STARTUP options for org-mode.
4479 Each element is a list of three items: The startup options as written
4480 in the #+STARTUP line, the corresponding variable, and the value to
4481 set this variable to if the option is found. An optional forth element PUSH
4482 means to push this value onto the list in the variable.")
4484 (defun org-update-property-plist (key val props)
4485 "Update PROPS with KEY and VAL."
4486 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4487 (key (if appending (substring key 0 (- (length key) 1)) key))
4488 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4489 (previous (cdr (assoc key props))))
4490 (if appending
4491 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4492 (cons (cons key val) remainder))))
4494 (defconst org-block-regexp
4495 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4496 "Regular expression for hiding blocks.")
4497 (defconst org-heading-keyword-regexp-format
4498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4499 "Printf format for a regexp matching an headline with some keyword.
4500 This regexp will match the headline of any node which has the
4501 exact keyword that is put into the format. The keyword isn't in
4502 any group by default, but the stars and the body are.")
4503 (defconst org-heading-keyword-maybe-regexp-format
4504 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4505 "Printf format for a regexp matching an headline, possibly with some keyword.
4506 This regexp can match any headline with the specified keyword, or
4507 without a keyword. The keyword isn't in any group by default,
4508 but the stars and the body are.")
4510 (defun org-set-regexps-and-options ()
4511 "Precompute regular expressions for current buffer."
4512 (when (eq major-mode 'org-mode)
4513 (org-set-local 'org-todo-kwd-alist nil)
4514 (org-set-local 'org-todo-key-alist nil)
4515 (org-set-local 'org-todo-key-trigger nil)
4516 (org-set-local 'org-todo-keywords-1 nil)
4517 (org-set-local 'org-done-keywords nil)
4518 (org-set-local 'org-todo-heads nil)
4519 (org-set-local 'org-todo-sets nil)
4520 (org-set-local 'org-todo-log-states nil)
4521 (org-set-local 'org-file-properties nil)
4522 (org-set-local 'org-file-tags nil)
4523 (let ((re (org-make-options-regexp
4524 '("CATEGORY" "TODO" "COLUMNS"
4525 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4526 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4527 "OPTIONS")
4528 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4529 (splitre "[ \t]+")
4530 (scripts org-use-sub-superscripts)
4531 kwds kws0 kwsa key log value cat arch tags const links hw dws
4532 tail sep kws1 prio props ftags drawers beamer-p
4533 ext-setup-or-nil setup-contents (start 0))
4534 (save-excursion
4535 (save-restriction
4536 (widen)
4537 (goto-char (point-min))
4538 (while (or (and ext-setup-or-nil
4539 (string-match re ext-setup-or-nil start)
4540 (setq start (match-end 0)))
4541 (and (setq ext-setup-or-nil nil start 0)
4542 (re-search-forward re nil t)))
4543 (setq key (upcase (match-string 1 ext-setup-or-nil))
4544 value (org-match-string-no-properties 2 ext-setup-or-nil))
4545 (if (stringp value) (setq value (org-trim value)))
4546 (cond
4547 ((equal key "CATEGORY")
4548 (setq cat value))
4549 ((member key '("SEQ_TODO" "TODO"))
4550 (push (cons 'sequence (org-split-string value splitre)) kwds))
4551 ((equal key "TYP_TODO")
4552 (push (cons 'type (org-split-string value splitre)) kwds))
4553 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4554 ;; general TODO-like setup
4555 (push (cons (intern (downcase (match-string 1 key)))
4556 (org-split-string value splitre)) kwds))
4557 ((equal key "TAGS")
4558 (setq tags (append tags (if tags '("\\n") nil)
4559 (org-split-string value splitre))))
4560 ((equal key "COLUMNS")
4561 (org-set-local 'org-columns-default-format value))
4562 ((equal key "LINK")
4563 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4564 (push (cons (match-string 1 value)
4565 (org-trim (match-string 2 value)))
4566 links)))
4567 ((equal key "PRIORITIES")
4568 (setq prio (org-split-string value " +")))
4569 ((equal key "PROPERTY")
4570 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4571 (setq props (org-update-property-plist (match-string 1 value)
4572 (match-string 2 value)
4573 props))))
4574 ((equal key "FILETAGS")
4575 (when (string-match "\\S-" value)
4576 (setq ftags
4577 (append
4578 ftags
4579 (apply 'append
4580 (mapcar (lambda (x) (org-split-string x ":"))
4581 (org-split-string value)))))))
4582 ((equal key "DRAWERS")
4583 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4584 ((equal key "CONSTANTS")
4585 (setq const (append const (org-split-string value splitre))))
4586 ((equal key "STARTUP")
4587 (let ((opts (org-split-string value splitre))
4588 l var val)
4589 (while (setq l (pop opts))
4590 (when (setq l (assoc l org-startup-options))
4591 (setq var (nth 1 l) val (nth 2 l))
4592 (if (not (nth 3 l))
4593 (set (make-local-variable var) val)
4594 (if (not (listp (symbol-value var)))
4595 (set (make-local-variable var) nil))
4596 (set (make-local-variable var) (symbol-value var))
4597 (add-to-list var val))))))
4598 ((equal key "ARCHIVE")
4599 (setq arch value)
4600 (remove-text-properties 0 (length arch)
4601 '(face t fontified t) arch))
4602 ((equal key "LATEX_CLASS")
4603 (setq beamer-p (equal value "beamer")))
4604 ((equal key "OPTIONS")
4605 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4606 (setq scripts (read (match-string 2 value)))))
4607 ((equal key "SETUPFILE")
4608 (setq setup-contents (org-file-contents
4609 (expand-file-name
4610 (org-remove-double-quotes value))
4611 'noerror))
4612 (if (not ext-setup-or-nil)
4613 (setq ext-setup-or-nil setup-contents start 0)
4614 (setq ext-setup-or-nil
4615 (concat (substring ext-setup-or-nil 0 start)
4616 "\n" setup-contents "\n"
4617 (substring ext-setup-or-nil start)))))))
4618 ;; search for property blocks
4619 (goto-char (point-min))
4620 (while (re-search-forward org-block-regexp nil t)
4621 (when (equal "PROPERTY" (upcase (match-string 1)))
4622 (setq value (replace-regexp-in-string
4623 "[\n\r]" " " (match-string 4)))
4624 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4625 (setq props (org-update-property-plist (match-string 1 value)
4626 (match-string 2 value)
4627 props)))))))
4628 (org-set-local 'org-use-sub-superscripts scripts)
4629 (when cat
4630 (org-set-local 'org-category (intern cat))
4631 (push (cons "CATEGORY" cat) props))
4632 (when prio
4633 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4634 (setq prio (mapcar 'string-to-char prio))
4635 (org-set-local 'org-highest-priority (nth 0 prio))
4636 (org-set-local 'org-lowest-priority (nth 1 prio))
4637 (org-set-local 'org-default-priority (nth 2 prio)))
4638 (and props (org-set-local 'org-file-properties (nreverse props)))
4639 (and ftags (org-set-local 'org-file-tags
4640 (mapcar 'org-add-prop-inherited ftags)))
4641 (and drawers (org-set-local 'org-drawers drawers))
4642 (and arch (org-set-local 'org-archive-location arch))
4643 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4644 ;; Process the TODO keywords
4645 (unless kwds
4646 ;; Use the global values as if they had been given locally.
4647 (setq kwds (default-value 'org-todo-keywords))
4648 (if (stringp (car kwds))
4649 (setq kwds (list (cons org-todo-interpretation
4650 (default-value 'org-todo-keywords)))))
4651 (setq kwds (reverse kwds)))
4652 (setq kwds (nreverse kwds))
4653 (let (inter kws kw)
4654 (while (setq kws (pop kwds))
4655 (let ((kws (or
4656 (run-hook-with-args-until-success
4657 'org-todo-setup-filter-hook kws)
4658 kws)))
4659 (setq inter (pop kws) sep (member "|" kws)
4660 kws0 (delete "|" (copy-sequence kws))
4661 kwsa nil
4662 kws1 (mapcar
4663 (lambda (x)
4664 ;; 1 2
4665 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4666 (progn
4667 (setq kw (match-string 1 x)
4668 key (and (match-end 2) (match-string 2 x))
4669 log (org-extract-log-state-settings x))
4670 (push (cons kw (and key (string-to-char key))) kwsa)
4671 (and log (push log org-todo-log-states))
4673 (error "Invalid TODO keyword %s" x)))
4674 kws0)
4675 kwsa (if kwsa (append '((:startgroup))
4676 (nreverse kwsa)
4677 '((:endgroup))))
4678 hw (car kws1)
4679 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4680 tail (list inter hw (car dws) (org-last dws))))
4681 (add-to-list 'org-todo-heads hw 'append)
4682 (push kws1 org-todo-sets)
4683 (setq org-done-keywords (append org-done-keywords dws nil))
4684 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4685 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4686 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4687 (setq org-todo-sets (nreverse org-todo-sets)
4688 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4689 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4690 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4691 ;; Process the constants
4692 (when const
4693 (let (e cst)
4694 (while (setq e (pop const))
4695 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4696 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4697 (setq org-table-formula-constants-local cst)))
4699 ;; Process the tags.
4700 (when tags
4701 (let (e tgs)
4702 (while (setq e (pop tags))
4703 (cond
4704 ((equal e "{") (push '(:startgroup) tgs))
4705 ((equal e "}") (push '(:endgroup) tgs))
4706 ((equal e "\\n") (push '(:newline) tgs))
4707 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4708 (push (cons (match-string 1 e)
4709 (string-to-char (match-string 2 e)))
4710 tgs))
4711 (t (push (list e) tgs))))
4712 (org-set-local 'org-tag-alist nil)
4713 (while (setq e (pop tgs))
4714 (or (and (stringp (car e))
4715 (assoc (car e) org-tag-alist))
4716 (push e org-tag-alist)))))
4718 ;; Compute the regular expressions and other local variables.
4719 ;; Using `org-outline-regexp-bol' would complicate them much,
4720 ;; because of the fixed white space at the end of that string.
4721 (if (not org-done-keywords)
4722 (setq org-done-keywords (and org-todo-keywords-1
4723 (list (org-last org-todo-keywords-1)))))
4724 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4725 (length org-scheduled-string)
4726 (length org-clock-string)
4727 (length org-closed-string)))
4728 org-drawer-regexp
4729 (concat "^[ \t]*:\\("
4730 (mapconcat 'regexp-quote org-drawers "\\|")
4731 "\\):[ \t]*$")
4732 org-not-done-keywords
4733 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4734 org-todo-regexp
4735 (concat "\\("
4736 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4737 "\\)")
4738 org-not-done-regexp
4739 (concat "\\("
4740 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4741 "\\)")
4742 org-not-done-heading-regexp
4743 (format org-heading-keyword-regexp-format org-not-done-regexp)
4744 org-todo-line-regexp
4745 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4746 org-complex-heading-regexp
4747 (concat "^\\(\\*+\\)"
4748 "\\(?: +" org-todo-regexp "\\)?"
4749 "\\(?: +\\(\\[#.\\]\\)\\)?"
4750 "\\(?: +\\(.*?\\)\\)?"
4751 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4752 "[ \t]*$")
4753 org-complex-heading-regexp-format
4754 (concat "^\\(\\*+\\)"
4755 "\\(?: +" org-todo-regexp "\\)?"
4756 "\\(?: +\\(\\[#.\\]\\)\\)?"
4757 "\\(?: +"
4758 ;; Stats cookies can be stuck to body.
4759 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4760 "\\(%s\\)"
4761 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4762 "\\)"
4763 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4764 "[ \t]*$")
4765 org-todo-line-tags-regexp
4766 (concat "^\\(\\*+\\)"
4767 "\\(?: +" org-todo-regexp "\\)?"
4768 "\\(?: +\\(.*?\\)\\)?"
4769 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4770 "[ \t]*$")
4771 org-deadline-regexp (concat "\\<" org-deadline-string)
4772 org-deadline-time-regexp
4773 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4774 org-deadline-line-regexp
4775 (concat "\\<\\(" org-deadline-string "\\).*")
4776 org-scheduled-regexp
4777 (concat "\\<" org-scheduled-string)
4778 org-scheduled-time-regexp
4779 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4780 org-closed-time-regexp
4781 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4782 org-keyword-time-regexp
4783 (concat "\\<\\(" org-scheduled-string
4784 "\\|" org-deadline-string
4785 "\\|" org-closed-string
4786 "\\|" org-clock-string "\\)"
4787 " *[[<]\\([^]>]+\\)[]>]")
4788 org-keyword-time-not-clock-regexp
4789 (concat "\\<\\(" org-scheduled-string
4790 "\\|" org-deadline-string
4791 "\\|" org-closed-string
4792 "\\)"
4793 " *[[<]\\([^]>]+\\)[]>]")
4794 org-maybe-keyword-time-regexp
4795 (concat "\\(\\<\\(" org-scheduled-string
4796 "\\|" org-deadline-string
4797 "\\|" org-closed-string
4798 "\\|" org-clock-string "\\)\\)?"
4799 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4800 org-planning-or-clock-line-re
4801 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4802 "\\|" org-deadline-string
4803 "\\|" org-closed-string "\\|" org-clock-string
4804 "\\)\\>\\)")
4805 org-all-time-keywords
4806 (mapcar (lambda (w) (substring w 0 -1))
4807 (list org-scheduled-string org-deadline-string
4808 org-clock-string org-closed-string))
4810 (org-compute-latex-and-specials-regexp)
4811 (org-set-font-lock-defaults))))
4813 (defun org-file-contents (file &optional noerror)
4814 "Return the contents of FILE, as a string."
4815 (if (or (not file)
4816 (not (file-readable-p file)))
4817 (if noerror
4818 (progn
4819 (message "Cannot read file \"%s\"" file)
4820 (ding) (sit-for 2)
4822 (error "Cannot read file \"%s\"" file))
4823 (with-temp-buffer
4824 (insert-file-contents file)
4825 (buffer-string))))
4827 (defun org-extract-log-state-settings (x)
4828 "Extract the log state setting from a TODO keyword string.
4829 This will extract info from a string like \"WAIT(w@/!)\"."
4830 (let (kw key log1 log2)
4831 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4832 (setq kw (match-string 1 x)
4833 key (and (match-end 2) (match-string 2 x))
4834 log1 (and (match-end 3) (match-string 3 x))
4835 log2 (and (match-end 4) (match-string 4 x)))
4836 (and (or log1 log2)
4837 (list kw
4838 (and log1 (if (equal log1 "!") 'time 'note))
4839 (and log2 (if (equal log2 "!") 'time 'note)))))))
4841 (defun org-remove-keyword-keys (list)
4842 "Remove a pair of parenthesis at the end of each string in LIST."
4843 (mapcar (lambda (x)
4844 (if (string-match "(.*)$" x)
4845 (substring x 0 (match-beginning 0))
4847 list))
4849 (defun org-assign-fast-keys (alist)
4850 "Assign fast keys to a keyword-key alist.
4851 Respect keys that are already there."
4852 (let (new e (alt ?0))
4853 (while (setq e (pop alist))
4854 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4855 (cdr e)) ;; Key already assigned.
4856 (push e new)
4857 (let ((clist (string-to-list (downcase (car e))))
4858 (used (append new alist)))
4859 (when (= (car clist) ?@)
4860 (pop clist))
4861 (while (and clist (rassoc (car clist) used))
4862 (pop clist))
4863 (unless clist
4864 (while (rassoc alt used)
4865 (incf alt)))
4866 (push (cons (car e) (or (car clist) alt)) new))))
4867 (nreverse new)))
4869 ;;; Some variables used in various places
4871 (defvar org-window-configuration nil
4872 "Used in various places to store a window configuration.")
4873 (defvar org-selected-window nil
4874 "Used in various places to store a window configuration.")
4875 (defvar org-finish-function nil
4876 "Function to be called when `C-c C-c' is used.
4877 This is for getting out of special buffers like remember.")
4880 ;; FIXME: Occasionally check by commenting these, to make sure
4881 ;; no other functions uses these, forgetting to let-bind them.
4882 (defvar entry)
4883 (defvar org-last-state)
4884 (defvar date)
4886 ;; Defined somewhere in this file, but used before definition.
4887 (defvar org-entities) ;; defined in org-entities.el
4888 (defvar org-struct-menu)
4889 (defvar org-org-menu)
4890 (defvar org-tbl-menu)
4892 ;;;; Define the Org-mode
4894 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4895 (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"))
4898 ;; We use a before-change function to check if a table might need
4899 ;; an update.
4900 (defvar org-table-may-need-update t
4901 "Indicates that a table might need an update.
4902 This variable is set by `org-before-change-function'.
4903 `org-table-align' sets it back to nil.")
4904 (defun org-before-change-function (beg end)
4905 "Every change indicates that a table might need an update."
4906 (setq org-table-may-need-update t))
4907 (defvar org-mode-map)
4908 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4909 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4910 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4911 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4912 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4913 (defvar org-table-buffer-is-an nil)
4915 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4916 ;; some places -- e.g. see the macro org-with-limited-levels.
4918 ;; In Org buffers, the value of `outline-regexp' is that of
4919 ;; `org-outline-regexp'. The only function still directly relying on
4920 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4921 ;; job when `orgstruct-mode' is active.
4922 (defvar org-outline-regexp "\\*+ "
4923 "Regexp to match Org headlines.")
4924 (defconst org-outline-regexp-bol "^\\*+ "
4925 "Regexp to match Org headlines.
4926 This is similar to `org-outline-regexp' but additionally makes
4927 sure that we are at the beginning of the line.")
4929 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4930 "Matches an headline, putting stars and text into groups.
4931 Stars are put in group 1 and the trimmed body in group 2.")
4933 (defvar bidi-paragraph-direction)
4934 (defvar buffer-face-mode-face)
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 (when (>= emacs-major-version 23)
5070 (set (make-local-variable 'buffer-face-mode-face) 'org-default)
5071 (buffer-face-mode))
5073 ;; If empty file that did not turn on org-mode automatically, make it to.
5074 (if (and org-insert-mode-line-in-empty-file
5075 (org-called-interactively-p 'any)
5076 (= (point-min) (point-max)))
5077 (insert "# -*- mode: org -*-\n\n"))
5078 (unless org-inhibit-startup
5079 (when org-startup-align-all-tables
5080 (let ((bmp (buffer-modified-p)))
5081 (org-table-map-tables 'org-table-align 'quietly)
5082 (set-buffer-modified-p bmp)))
5083 (when org-startup-with-inline-images
5084 (org-display-inline-images))
5085 (when org-startup-indented
5086 (require 'org-indent)
5087 (org-indent-mode 1))
5088 (unless org-inhibit-startup-visibility-stuff
5089 (org-set-startup-visibility))))
5091 (when (fboundp 'abbrev-table-put)
5092 (abbrev-table-put org-mode-abbrev-table
5093 :parents (list text-mode-abbrev-table)))
5095 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5097 (defun org-current-time ()
5098 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5099 (if (> (car org-time-stamp-rounding-minutes) 1)
5100 (let ((r (car org-time-stamp-rounding-minutes))
5101 (time (decode-time)))
5102 (apply 'encode-time
5103 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5104 (nthcdr 2 time))))
5105 (current-time)))
5107 (defun org-today ()
5108 "Return today date, considering `org-extend-today-until'."
5109 (time-to-days
5110 (time-subtract (current-time)
5111 (list 0 (* 3600 org-extend-today-until) 0))))
5113 ;;;; Font-Lock stuff, including the activators
5115 (defvar org-mouse-map (make-sparse-keymap))
5116 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5117 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5118 (when org-mouse-1-follows-link
5119 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5120 (when org-tab-follows-link
5121 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5122 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5124 (require 'font-lock)
5126 (defconst org-non-link-chars "]\t\n\r<>")
5127 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5128 "shell" "elisp" "doi" "message"))
5129 (defvar org-link-types-re nil
5130 "Matches a link that has a url-like prefix like \"http:\"")
5131 (defvar org-link-re-with-space nil
5132 "Matches a link with spaces, optional angular brackets around it.")
5133 (defvar org-link-re-with-space2 nil
5134 "Matches a link with spaces, optional angular brackets around it.")
5135 (defvar org-link-re-with-space3 nil
5136 "Matches a link with spaces, only for internal part in bracket links.")
5137 (defvar org-angle-link-re nil
5138 "Matches link with angular brackets, spaces are allowed.")
5139 (defvar org-plain-link-re nil
5140 "Matches plain link, without spaces.")
5141 (defvar org-bracket-link-regexp nil
5142 "Matches a link in double brackets.")
5143 (defvar org-bracket-link-analytic-regexp nil
5144 "Regular expression used to analyze links.
5145 Here is what the match groups contain after a match:
5146 1: http:
5147 2: http
5148 3: path
5149 4: [desc]
5150 5: desc")
5151 (defvar org-bracket-link-analytic-regexp++ nil
5152 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5153 (defvar org-any-link-re nil
5154 "Regular expression matching any link.")
5156 (defcustom org-match-sexp-depth 3
5157 "Number of stacked braces for sub/superscript matching.
5158 This has to be set before loading org.el to be effective."
5159 :group 'org-export-translation ; ??????????????????????????/
5160 :type 'integer)
5162 (defun org-create-multibrace-regexp (left right n)
5163 "Create a regular expression which will match a balanced sexp.
5164 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5165 as single character strings.
5166 The regexp returned will match the entire expression including the
5167 delimiters. It will also define a single group which contains the
5168 match except for the outermost delimiters. The maximum depth of
5169 stacked delimiters is N. Escaping delimiters is not possible."
5170 (let* ((nothing (concat "[^" left right "]*?"))
5171 (or "\\|")
5172 (re nothing)
5173 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5174 (while (> n 1)
5175 (setq n (1- n)
5176 re (concat re or next)
5177 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5178 (concat left "\\(" re "\\)" right)))
5180 (defvar org-match-substring-regexp
5181 (concat
5182 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5183 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5184 "\\|"
5185 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5186 "\\|"
5187 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5188 "The regular expression matching a sub- or superscript.")
5190 (defvar org-match-substring-with-braces-regexp
5191 (concat
5192 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5193 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5194 "\\)")
5195 "The regular expression matching a sub- or superscript, forcing braces.")
5197 (defun org-make-link-regexps ()
5198 "Update the link regular expressions.
5199 This should be called after the variable `org-link-types' has changed."
5200 (setq org-link-types-re
5201 (concat
5202 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5203 org-link-re-with-space
5204 (concat
5205 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5206 "\\([^" org-non-link-chars " ]"
5207 "[^" org-non-link-chars "]*"
5208 "[^" org-non-link-chars " ]\\)>?")
5209 org-link-re-with-space2
5210 (concat
5211 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5212 "\\([^" org-non-link-chars " ]"
5213 "[^\t\n\r]*"
5214 "[^" org-non-link-chars " ]\\)>?")
5215 org-link-re-with-space3
5216 (concat
5217 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5218 "\\([^" org-non-link-chars " ]"
5219 "[^\t\n\r]*\\)")
5220 org-angle-link-re
5221 (concat
5222 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5223 "\\([^" org-non-link-chars " ]"
5224 "[^" org-non-link-chars "]*"
5225 "\\)>")
5226 org-plain-link-re
5227 (concat
5228 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5229 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5230 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5231 org-bracket-link-regexp
5232 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5233 org-bracket-link-analytic-regexp
5234 (concat
5235 "\\[\\["
5236 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5237 "\\([^]]+\\)"
5238 "\\]"
5239 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5240 "\\]")
5241 org-bracket-link-analytic-regexp++
5242 (concat
5243 "\\[\\["
5244 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5245 "\\([^]]+\\)"
5246 "\\]"
5247 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5248 "\\]")
5249 org-any-link-re
5250 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5251 org-angle-link-re "\\)\\|\\("
5252 org-plain-link-re "\\)")))
5254 (org-make-link-regexps)
5256 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5257 "Regular expression for fast time stamp matching.")
5258 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5259 "Regular expression for fast time stamp matching.")
5260 (defconst org-ts-regexp0
5261 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5262 "Regular expression matching time strings for analysis.
5263 This one does not require the space after the date, so it can be used
5264 on a string that terminates immediately after the date.")
5265 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5266 "Regular expression matching time strings for analysis.")
5267 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5268 "Regular expression matching time stamps, with groups.")
5269 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5270 "Regular expression matching time stamps (also [..]), with groups.")
5271 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5272 "Regular expression matching a time stamp range.")
5273 (defconst org-tr-regexp-both
5274 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5275 "Regular expression matching a time stamp range.")
5276 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5277 org-ts-regexp "\\)?")
5278 "Regular expression matching a time stamp or time stamp range.")
5279 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5280 org-ts-regexp-both "\\)?")
5281 "Regular expression matching a time stamp or time stamp range.
5282 The time stamps may be either active or inactive.")
5284 (defvar org-emph-face nil)
5286 (defun org-do-emphasis-faces (limit)
5287 "Run through the buffer and add overlays to emphasized strings."
5288 (let (rtn a)
5289 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5290 (if (not (= (char-after (match-beginning 3))
5291 (char-after (match-beginning 4))))
5292 (progn
5293 (setq rtn t)
5294 (setq a (assoc (match-string 3) org-emphasis-alist))
5295 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5296 'face
5297 (nth 1 a))
5298 (and (nth 4 a)
5299 (org-remove-flyspell-overlays-in
5300 (match-beginning 0) (match-end 0)))
5301 (add-text-properties (match-beginning 2) (match-end 2)
5302 '(font-lock-multiline t org-emphasis t))
5303 (when org-hide-emphasis-markers
5304 (add-text-properties (match-end 4) (match-beginning 5)
5305 '(invisible org-link))
5306 (add-text-properties (match-beginning 3) (match-end 3)
5307 '(invisible org-link)))))
5308 (backward-char 1))
5309 rtn))
5311 (defun org-emphasize (&optional char)
5312 "Insert or change an emphasis, i.e. a font like bold or italic.
5313 If there is an active region, change that region to a new emphasis.
5314 If there is no region, just insert the marker characters and position
5315 the cursor between them.
5316 CHAR should be either the marker character, or the first character of the
5317 HTML tag associated with that emphasis. If CHAR is a space, the means
5318 to remove the emphasis of the selected region.
5319 If char is not given (for example in an interactive call) it
5320 will be prompted for."
5321 (interactive)
5322 (let ((eal org-emphasis-alist) e det
5323 (erc org-emphasis-regexp-components)
5324 (prompt "")
5325 (string "") beg end move tag c s)
5326 (if (org-region-active-p)
5327 (setq beg (region-beginning) end (region-end)
5328 string (buffer-substring beg end))
5329 (setq move t))
5331 (while (setq e (pop eal))
5332 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5333 c (aref tag 0))
5334 (push (cons c (string-to-char (car e))) det)
5335 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5336 (substring tag 1)))))
5337 (setq det (nreverse det))
5338 (unless char
5339 (message "%s" (concat "Emphasis marker or tag:" prompt))
5340 (setq char (read-char-exclusive)))
5341 (setq char (or (cdr (assoc char det)) char))
5342 (if (equal char ?\ )
5343 (setq s "" move nil)
5344 (unless (assoc (char-to-string char) org-emphasis-alist)
5345 (error "No such emphasis marker: \"%c\"" char))
5346 (setq s (char-to-string char)))
5347 (while (and (> (length string) 1)
5348 (equal (substring string 0 1) (substring string -1))
5349 (assoc (substring string 0 1) org-emphasis-alist))
5350 (setq string (substring string 1 -1)))
5351 (setq string (concat s string s))
5352 (if beg (delete-region beg end))
5353 (unless (or (bolp)
5354 (string-match (concat "[" (nth 0 erc) "\n]")
5355 (char-to-string (char-before (point)))))
5356 (insert " "))
5357 (unless (or (eobp)
5358 (string-match (concat "[" (nth 1 erc) "\n]")
5359 (char-to-string (char-after (point)))))
5360 (insert " ") (backward-char 1))
5361 (insert string)
5362 (and move (backward-char 1))))
5364 (defconst org-nonsticky-props
5365 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5367 (defsubst org-rear-nonsticky-at (pos)
5368 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5370 (defun org-activate-plain-links (limit)
5371 "Run through the buffer and add overlays to links."
5372 (catch 'exit
5373 (let (f)
5374 (if (re-search-forward org-plain-link-re limit t)
5375 (progn
5376 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5377 (setq f (get-text-property (match-beginning 0) 'face))
5378 (if (or (eq f 'org-tag)
5379 (and (listp f) (memq 'org-tag f)))
5381 (add-text-properties (match-beginning 0) (match-end 0)
5382 (list 'mouse-face 'highlight
5383 'face 'org-link
5384 'keymap org-mouse-map))
5385 (org-rear-nonsticky-at (match-end 0)))
5386 t)))))
5388 (defun org-activate-code (limit)
5389 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5390 (progn
5391 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5392 (remove-text-properties (match-beginning 0) (match-end 0)
5393 '(display t invisible t intangible t))
5394 t)))
5396 (defcustom org-src-fontify-natively nil
5397 "When non-nil, fontify code in code blocks."
5398 :type 'boolean
5399 :version "24.1"
5400 :group 'org-appearance
5401 :group 'org-babel)
5403 (defun org-fontify-meta-lines-and-blocks (limit)
5404 (condition-case nil
5405 (org-fontify-meta-lines-and-blocks-1 limit)
5406 (error (message "org-mode fontification error"))))
5408 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5409 "Fontify #+ lines and blocks, in the correct ways."
5410 (let ((case-fold-search t))
5411 (if (re-search-forward
5412 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5413 limit t)
5414 (let ((beg (match-beginning 0))
5415 (block-start (match-end 0))
5416 (block-end nil)
5417 (lang (match-string 7))
5418 (beg1 (line-beginning-position 2))
5419 (dc1 (downcase (match-string 2)))
5420 (dc3 (downcase (match-string 3)))
5421 end end1 quoting block-type ovl)
5422 (cond
5423 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5424 ;; a single line of backend-specific content
5425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5426 (remove-text-properties (match-beginning 0) (match-end 0)
5427 '(display t invisible t intangible t))
5428 (add-text-properties (match-beginning 1) (match-end 3)
5429 '(font-lock-fontified t face org-meta-line))
5430 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5431 '(font-lock-fontified t face org-block))
5432 ; for backend-specific code
5434 ((and (match-end 4) (equal dc3 "begin"))
5435 ;; Truly a block
5436 (setq block-type (downcase (match-string 5))
5437 quoting (member block-type org-protecting-blocks))
5438 (when (re-search-forward
5439 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5440 nil t) ;; on purpose, we look further than LIMIT
5441 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5442 (setq block-end (match-beginning 0))
5443 (when quoting
5444 (remove-text-properties beg end
5445 '(display t invisible t intangible t)))
5446 (add-text-properties
5447 beg end
5448 '(font-lock-fontified t font-lock-multiline t))
5449 (add-text-properties beg beg1 '(face org-meta-line))
5450 (add-text-properties end1 (min (point-max) (1+ end))
5451 '(face org-meta-line)) ; for end_src
5452 (cond
5453 ((and lang (not (string= lang "")) org-src-fontify-natively)
5454 (org-src-font-lock-fontify-block lang block-start block-end)
5455 ;; remove old background overlays
5456 (mapc (lambda (ov)
5457 (if (eq (overlay-get ov 'face) 'org-block-background)
5458 (delete-overlay ov)))
5459 (overlays-at (/ (+ beg1 block-end) 2)))
5460 ;; add a background overlay
5461 (setq ovl (make-overlay beg1 block-end))
5462 (overlay-put ovl 'face 'org-block-background)
5463 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5464 (quoting
5465 (add-text-properties beg1 (min (point-max) (1+ end1))
5466 '(face org-block))) ; end of source block
5467 ((not org-fontify-quote-and-verse-blocks))
5468 ((string= block-type "quote")
5469 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5470 ((string= block-type "verse")
5471 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5472 (add-text-properties beg beg1 '(face org-block-begin-line))
5473 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5475 ((member dc1 '("title:" "author:" "email:" "date:"))
5476 (add-text-properties
5477 beg (match-end 3)
5478 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5479 '(font-lock-fontified t invisible t)
5480 '(font-lock-fontified t face org-document-info-keyword)))
5481 (add-text-properties
5482 (match-beginning 6) (match-end 6)
5483 (if (string-equal dc1 "title:")
5484 '(font-lock-fontified t face org-document-title)
5485 '(font-lock-fontified t face org-document-info))))
5486 ((not (member (char-after beg) '(?\ ?\t)))
5487 ;; just any other in-buffer setting, but not indented
5488 (add-text-properties
5489 beg (match-end 0)
5490 '(font-lock-fontified t face org-meta-line))
5492 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5493 "orgtbl:" "tblfm:" "tblname:" "results:"
5494 "call:" "header:" "headers:" "name:"))
5495 (and (match-end 4) (equal dc3 "attr")))
5496 (add-text-properties
5497 beg (match-end 0)
5498 '(font-lock-fontified t face org-meta-line))
5500 ((member dc3 '(" " ""))
5501 (add-text-properties
5502 beg (match-end 0)
5503 '(font-lock-fontified t face font-lock-comment-face)))
5504 (t nil))))))
5506 (defun org-strip-protective-commas (beg end)
5507 "Strip protective commas between BEG and END in the current buffer."
5508 (interactive "r")
5509 (save-excursion
5510 (save-match-data
5511 (goto-char beg)
5512 (let ((front-line (save-excursion
5513 (re-search-forward
5514 "[^[:space:]]" end t)
5515 (goto-char (match-beginning 0))
5516 (current-column))))
5517 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5518 (goto-char (match-beginning 1))
5519 (when (= (current-column) front-line)
5520 (replace-match "" nil nil nil 1)))))))
5522 (defun org-activate-angle-links (limit)
5523 "Run through the buffer and add overlays to links."
5524 (if (re-search-forward org-angle-link-re limit t)
5525 (progn
5526 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5527 (add-text-properties (match-beginning 0) (match-end 0)
5528 (list 'mouse-face 'highlight
5529 'keymap org-mouse-map))
5530 (org-rear-nonsticky-at (match-end 0))
5531 t)))
5533 (defun org-activate-footnote-links (limit)
5534 "Run through the buffer and add overlays to footnotes."
5535 (let ((fn (org-footnote-next-reference-or-definition limit)))
5536 (when fn
5537 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5538 (org-remove-flyspell-overlays-in beg end)
5539 (add-text-properties beg end
5540 (list 'mouse-face 'highlight
5541 'keymap org-mouse-map
5542 'help-echo
5543 (if (= (point-at-bol) beg)
5544 "Footnote definition"
5545 "Footnote reference")
5546 'font-lock-fontified t
5547 'font-lock-multiline t
5548 'face 'org-footnote))))))
5550 (defun org-activate-bracket-links (limit)
5551 "Run through the buffer and add overlays to bracketed links."
5552 (if (re-search-forward org-bracket-link-regexp limit t)
5553 (let* ((help (concat "LINK: "
5554 (org-match-string-no-properties 1)))
5555 ;; FIXME: above we should remove the escapes.
5556 ;; but that requires another match, protecting match data,
5557 ;; a lot of overhead for font-lock.
5558 (ip (org-maybe-intangible
5559 (list 'invisible 'org-link
5560 'keymap org-mouse-map 'mouse-face 'highlight
5561 'font-lock-multiline t 'help-echo help)))
5562 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5563 'font-lock-multiline t 'help-echo help)))
5564 ;; We need to remove the invisible property here. Table narrowing
5565 ;; may have made some of this invisible.
5566 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5567 (remove-text-properties (match-beginning 0) (match-end 0)
5568 '(invisible nil))
5569 (if (match-end 3)
5570 (progn
5571 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5572 (org-rear-nonsticky-at (match-beginning 3))
5573 (add-text-properties (match-beginning 3) (match-end 3) vp)
5574 (org-rear-nonsticky-at (match-end 3))
5575 (add-text-properties (match-end 3) (match-end 0) ip)
5576 (org-rear-nonsticky-at (match-end 0)))
5577 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5578 (org-rear-nonsticky-at (match-beginning 1))
5579 (add-text-properties (match-beginning 1) (match-end 1) vp)
5580 (org-rear-nonsticky-at (match-end 1))
5581 (add-text-properties (match-end 1) (match-end 0) ip)
5582 (org-rear-nonsticky-at (match-end 0)))
5583 t)))
5585 (defun org-activate-dates (limit)
5586 "Run through the buffer and add overlays to dates."
5587 (if (re-search-forward org-tsr-regexp-both limit t)
5588 (progn
5589 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5590 (add-text-properties (match-beginning 0) (match-end 0)
5591 (list 'mouse-face 'highlight
5592 'keymap org-mouse-map))
5593 (org-rear-nonsticky-at (match-end 0))
5594 (when org-display-custom-times
5595 (if (match-end 3)
5596 (org-display-custom-time (match-beginning 3) (match-end 3)))
5597 (org-display-custom-time (match-beginning 1) (match-end 1)))
5598 t)))
5600 (defvar org-target-link-regexp nil
5601 "Regular expression matching radio targets in plain text.")
5602 (make-variable-buffer-local 'org-target-link-regexp)
5603 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5604 "Regular expression matching a link target.")
5605 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5606 "Regular expression matching a radio target.")
5607 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5608 "Regular expression matching any target.")
5610 (defun org-activate-target-links (limit)
5611 "Run through the buffer and add overlays to target matches."
5612 (when org-target-link-regexp
5613 (let ((case-fold-search t))
5614 (if (re-search-forward org-target-link-regexp limit t)
5615 (progn
5616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5617 (add-text-properties (match-beginning 0) (match-end 0)
5618 (list 'mouse-face 'highlight
5619 'keymap org-mouse-map
5620 'help-echo "Radio target link"
5621 'org-linked-text t))
5622 (org-rear-nonsticky-at (match-end 0))
5623 t)))))
5625 (defun org-update-radio-target-regexp ()
5626 "Find all radio targets in this file and update the regular expression."
5627 (interactive)
5628 (when (memq 'radio org-activate-links)
5629 (setq org-target-link-regexp
5630 (org-make-target-link-regexp (org-all-targets 'radio)))
5631 (org-restart-font-lock)))
5633 (defun org-hide-wide-columns (limit)
5634 (let (s e)
5635 (setq s (text-property-any (point) (or limit (point-max))
5636 'org-cwidth t))
5637 (when s
5638 (setq e (next-single-property-change s 'org-cwidth))
5639 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5640 (goto-char e)
5641 t)))
5643 (defvar org-latex-and-specials-regexp nil
5644 "Regular expression for highlighting export special stuff.")
5645 (defvar org-match-substring-regexp)
5646 (defvar org-match-substring-with-braces-regexp)
5648 ;; This should be with the exporter code, but we also use if for font-locking
5649 (defconst org-export-html-special-string-regexps
5650 '(("\\\\-" . "&shy;")
5651 ("---\\([^-]\\)" . "&mdash;\\1")
5652 ("--\\([^-]\\)" . "&ndash;\\1")
5653 ("\\.\\.\\." . "&hellip;"))
5654 "Regular expressions for special string conversion.")
5657 (defun org-compute-latex-and-specials-regexp ()
5658 "Compute regular expression for stuff treated specially by exporters."
5659 (if (not org-highlight-latex-fragments-and-specials)
5660 (org-set-local 'org-latex-and-specials-regexp nil)
5661 (require 'org-exp)
5662 (let*
5663 ((matchers (plist-get org-format-latex-options :matchers))
5664 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5665 org-latex-regexps)))
5666 (org-export-allow-BIND nil)
5667 (options (org-combine-plists (org-default-export-plist)
5668 (org-infile-export-plist)))
5669 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5670 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5671 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5672 (org-export-html-expand (plist-get options :expand-quoted-html))
5673 (org-export-with-special-strings (plist-get options :special-strings))
5674 (re-sub
5675 (cond
5676 ((equal org-export-with-sub-superscripts '{})
5677 (list org-match-substring-with-braces-regexp))
5678 (org-export-with-sub-superscripts
5679 (list org-match-substring-regexp))
5680 (t nil)))
5681 (re-latex
5682 (if org-export-with-LaTeX-fragments
5683 (mapcar (lambda (x) (nth 1 x)) latexs)))
5684 (re-macros
5685 (if org-export-with-TeX-macros
5686 (list (concat "\\\\"
5687 (regexp-opt
5688 (append
5690 (delq nil
5691 (mapcar 'car-safe
5692 (append org-entities-user
5693 org-entities)))
5694 (if (boundp 'org-latex-entities)
5695 (mapcar (lambda (x)
5696 (or (car-safe x) x))
5697 org-latex-entities)
5698 nil))
5699 'words))) ; FIXME
5701 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5702 (re-special (if org-export-with-special-strings
5703 (mapcar (lambda (x) (car x))
5704 org-export-html-special-string-regexps)))
5705 (re-rest
5706 (delq nil
5707 (list
5708 (if org-export-html-expand "@<[^>\n]+>")
5709 ))))
5710 (org-set-local
5711 'org-latex-and-specials-regexp
5712 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5713 re-rest) "\\|")))))
5715 (defun org-do-latex-and-special-faces (limit)
5716 "Run through the buffer and add overlays to links."
5717 (when org-latex-and-specials-regexp
5718 (let (rtn d)
5719 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5720 limit t))
5721 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5722 'face))
5723 '(org-code org-verbatim underline)))
5724 (progn
5725 (setq rtn t
5726 d (cond ((member (char-after (1+ (match-beginning 0)))
5727 '(?_ ?^)) 1)
5728 (t 0)))
5729 (font-lock-prepend-text-property
5730 (+ d (match-beginning 0)) (match-end 0)
5731 'face 'org-latex-and-export-specials)
5732 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5733 '(font-lock-multiline t)))))
5734 rtn)))
5736 (defun org-restart-font-lock ()
5737 "Restart `font-lock-mode', to force refontification."
5738 (when (and (boundp 'font-lock-mode) font-lock-mode)
5739 (font-lock-mode -1)
5740 (font-lock-mode 1)))
5742 (defun org-all-targets (&optional radio)
5743 "Return a list of all targets in this file.
5744 With optional argument RADIO, only find radio targets."
5745 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5746 rtn)
5747 (save-excursion
5748 (goto-char (point-min))
5749 (while (re-search-forward re nil t)
5750 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5751 rtn)))
5753 (defun org-make-target-link-regexp (targets)
5754 "Make regular expression matching all strings in TARGETS.
5755 The regular expression finds the targets also if there is a line break
5756 between words."
5757 (and targets
5758 (concat
5759 "\\<\\("
5760 (mapconcat
5761 (lambda (x)
5762 (setq x (regexp-quote x))
5763 (while (string-match " +" x)
5764 (setq x (replace-match "\\s-+" t t x)))
5766 targets
5767 "\\|")
5768 "\\)\\>")))
5770 (defun org-activate-tags (limit)
5771 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5772 (progn
5773 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5774 (add-text-properties (match-beginning 1) (match-end 1)
5775 (list 'mouse-face 'highlight
5776 'keymap org-mouse-map))
5777 (org-rear-nonsticky-at (match-end 1))
5778 t)))
5780 (defun org-outline-level ()
5781 "Compute the outline level of the heading at point.
5782 This function assumes that the cursor is at the beginning of a line matched
5783 by `outline-regexp'. Otherwise it returns garbage.
5784 If this is called at a normal headline, the level is the number of stars.
5785 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5786 (save-excursion
5787 (looking-at org-outline-regexp)
5788 (1- (- (match-end 0) (match-beginning 0)))))
5790 (defvar org-font-lock-keywords nil)
5792 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5793 "Regular expression matching a property line.")
5795 (defvar org-font-lock-hook nil
5796 "Functions to be called for special font lock stuff.")
5798 (defvar org-font-lock-set-keywords-hook nil
5799 "Functions that can manipulate `org-font-lock-extra-keywords'.
5800 This is called after `org-font-lock-extra-keywords' is defined, but before
5801 it is installed to be used by font lock. This can be useful if something
5802 needs to be inserted at a specific position in the font-lock sequence.")
5804 (defun org-font-lock-hook (limit)
5805 (run-hook-with-args 'org-font-lock-hook limit))
5807 (defun org-set-font-lock-defaults ()
5808 (let* ((em org-fontify-emphasized-text)
5809 (lk org-activate-links)
5810 (org-font-lock-extra-keywords
5811 (list
5812 ;; Call the hook
5813 '(org-font-lock-hook)
5814 ;; Headlines
5815 `(,(if org-fontify-whole-heading-line
5816 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5817 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5818 (1 (org-get-level-face 1))
5819 (2 (org-get-level-face 2))
5820 (3 (org-get-level-face 3)))
5821 ;; Table lines
5822 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5823 (1 'org-table t))
5824 ;; Table internals
5825 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5826 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5827 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5828 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5829 ;; Drawers
5830 (list org-drawer-regexp '(0 'org-special-keyword t))
5831 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5832 ;; Properties
5833 (list org-property-re
5834 '(1 'org-special-keyword t)
5835 '(3 'org-property-value t))
5836 ;; Links
5837 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5838 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5839 (if (memq 'plain lk) '(org-activate-plain-links))
5840 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5841 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5842 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5843 (if (memq 'footnote lk) '(org-activate-footnote-links))
5844 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5845 '(org-hide-wide-columns (0 nil append))
5846 ;; TODO keyword
5847 (list (format org-heading-keyword-regexp-format
5848 org-todo-regexp)
5849 '(2 (org-get-todo-face 2) t))
5850 ;; DONE
5851 (if org-fontify-done-headline
5852 (list (format org-heading-keyword-regexp-format
5853 (concat
5854 "\\(?:"
5855 (mapconcat 'regexp-quote org-done-keywords "\\|")
5856 "\\)"))
5857 '(2 'org-headline-done t))
5858 nil)
5859 ;; Priorities
5860 '(org-font-lock-add-priority-faces)
5861 ;; Tags
5862 '(org-font-lock-add-tag-faces)
5863 ;; Special keywords
5864 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5865 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5866 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5867 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5868 ;; Emphasis
5869 (if em
5870 (if (featurep 'xemacs)
5871 '(org-do-emphasis-faces (0 nil append))
5872 '(org-do-emphasis-faces)))
5873 ;; Checkboxes
5874 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5875 1 'org-checkbox prepend)
5876 (if (cdr (assq 'checkbox org-list-automatic-rules))
5877 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5878 (0 (org-get-checkbox-statistics-face) t)))
5879 ;; Description list items
5880 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5881 1 'bold prepend)
5882 ;; ARCHIVEd headings
5883 (list (concat
5884 org-outline-regexp-bol
5885 "\\(.*:" org-archive-tag ":.*\\)")
5886 '(1 'org-archived prepend))
5887 ;; Specials
5888 '(org-do-latex-and-special-faces)
5889 '(org-fontify-entities)
5890 '(org-raise-scripts)
5891 ;; Code
5892 '(org-activate-code (1 'org-code t))
5893 ;; COMMENT
5894 (list (format org-heading-keyword-regexp-format
5895 (concat "\\("
5896 org-comment-string "\\|" org-quote-string
5897 "\\)"))
5898 '(2 'org-special-keyword t))
5899 '("^#.*" (0 'font-lock-comment-face t))
5900 ;; Blocks and meta lines
5901 '(org-fontify-meta-lines-and-blocks)
5903 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5904 (run-hooks 'org-font-lock-set-keywords-hook)
5905 ;; Now set the full font-lock-keywords
5906 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5907 (org-set-local 'font-lock-defaults
5908 '(org-font-lock-keywords t nil nil backward-paragraph))
5909 (kill-local-variable 'font-lock-keywords) nil))
5911 (defun org-toggle-pretty-entities ()
5912 "Toggle the composition display of entities as UTF8 characters."
5913 (interactive)
5914 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5915 (org-restart-font-lock)
5916 (if org-pretty-entities
5917 (message "Entities are displayed as UTF8 characters")
5918 (save-restriction
5919 (widen)
5920 (org-decompose-region (point-min) (point-max))
5921 (message "Entities are displayed plain"))))
5923 (defun org-fontify-entities (limit)
5924 "Find an entity to fontify."
5925 (let (ee)
5926 (when org-pretty-entities
5927 (catch 'match
5928 (while (re-search-forward
5929 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5930 limit t)
5931 (if (and (not (org-in-indented-comment-line))
5932 (setq ee (org-entity-get (match-string 1)))
5933 (= (length (nth 6 ee)) 1))
5934 (progn
5935 (add-text-properties
5936 (match-beginning 0) (match-end 1)
5937 (list 'font-lock-fontified t))
5938 (compose-region (match-beginning 0) (match-end 1)
5939 (nth 6 ee) nil)
5940 (backward-char 1)
5941 (throw 'match t))))
5942 nil))))
5944 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5945 "Fontify string S like in Org-mode."
5946 (with-temp-buffer
5947 (insert s)
5948 (let ((org-odd-levels-only odd-levels))
5949 (org-mode)
5950 (font-lock-fontify-buffer)
5951 (buffer-string))))
5953 (defvar org-m nil)
5954 (defvar org-l nil)
5955 (defvar org-f nil)
5956 (defun org-get-level-face (n)
5957 "Get the right face for match N in font-lock matching of headlines."
5958 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5959 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5960 (if org-cycle-level-faces
5961 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5962 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5963 (cond
5964 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5965 ((eq n 2) org-f)
5966 (t (if org-level-color-stars-only nil org-f))))
5969 (defun org-get-todo-face (kwd)
5970 "Get the right face for a TODO keyword KWD.
5971 If KWD is a number, get the corresponding match group."
5972 (if (numberp kwd) (setq kwd (match-string kwd)))
5973 (or (org-face-from-face-or-color
5974 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5975 (and (member kwd org-done-keywords) 'org-done)
5976 'org-todo))
5978 (defun org-face-from-face-or-color (context inherit face-or-color)
5979 "Create a face list that inherits INHERIT, but sets the foreground color.
5980 When FACE-OR-COLOR is not a string, just return it."
5981 (if (stringp face-or-color)
5982 (list :inherit inherit
5983 (cdr (assoc context org-faces-easy-properties))
5984 face-or-color)
5985 face-or-color))
5987 (defun org-font-lock-add-tag-faces (limit)
5988 "Add the special tag faces."
5989 (when (and org-tag-faces org-tags-special-faces-re)
5990 (while (re-search-forward org-tags-special-faces-re limit t)
5991 (add-text-properties (match-beginning 1) (match-end 1)
5992 (list 'face (org-get-tag-face 1)
5993 'font-lock-fontified t))
5994 (backward-char 1))))
5996 (defun org-font-lock-add-priority-faces (limit)
5997 "Add the special priority faces."
5998 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5999 (add-text-properties
6000 (match-beginning 0) (match-end 0)
6001 (list 'face (or (org-face-from-face-or-color
6002 'priority 'org-special-keyword
6003 (cdr (assoc (char-after (match-beginning 1))
6004 org-priority-faces)))
6005 'org-special-keyword)
6006 'font-lock-fontified t))))
6008 (defun org-get-tag-face (kwd)
6009 "Get the right face for a TODO keyword KWD.
6010 If KWD is a number, get the corresponding match group."
6011 (if (numberp kwd) (setq kwd (match-string kwd)))
6012 (or (org-face-from-face-or-color
6013 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6014 'org-tag))
6016 (defun org-unfontify-region (beg end &optional maybe_loudly)
6017 "Remove fontification and activation overlays from links."
6018 (font-lock-default-unfontify-region beg end)
6019 (let* ((buffer-undo-list t)
6020 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6021 (inhibit-modification-hooks t)
6022 deactivate-mark buffer-file-name buffer-file-truename)
6023 (org-decompose-region beg end)
6024 (remove-text-properties beg end
6025 '(mouse-face t keymap t org-linked-text t
6026 invisible t intangible t
6027 org-no-flyspell t org-emphasis t))
6028 (org-remove-font-lock-display-properties beg end)))
6030 (defconst org-script-display '(((raise -0.3) (height 0.7))
6031 ((raise 0.3) (height 0.7))
6032 ((raise -0.5))
6033 ((raise 0.5)))
6034 "Display properties for showing superscripts and subscripts.")
6036 (defun org-remove-font-lock-display-properties (beg end)
6037 "Remove specific display properties that have been added by font lock.
6038 The will remove the raise properties that are used to show superscripts
6039 and subscripts."
6040 (let (next prop)
6041 (while (< beg end)
6042 (setq next (next-single-property-change beg 'display nil end)
6043 prop (get-text-property beg 'display))
6044 (if (member prop org-script-display)
6045 (put-text-property beg next 'display nil))
6046 (setq beg next))))
6048 (defun org-raise-scripts (limit)
6049 "Add raise properties to sub/superscripts."
6050 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6051 (if (re-search-forward
6052 (if (eq org-use-sub-superscripts t)
6053 org-match-substring-regexp
6054 org-match-substring-with-braces-regexp)
6055 limit t)
6056 (let* ((pos (point)) table-p comment-p
6057 (mpos (match-beginning 3))
6058 (emph-p (get-text-property mpos 'org-emphasis))
6059 (link-p (get-text-property mpos 'mouse-face))
6060 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6061 (goto-char (point-at-bol))
6062 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6063 comment-p (org-looking-at-p "[ \t]*#"))
6064 (goto-char pos)
6065 ;; FIXME: Should we go back one character here, for a_b^c
6066 ;; (goto-char (1- pos)) ;????????????????????
6067 (if (or comment-p emph-p link-p keyw-p)
6069 (put-text-property (match-beginning 3) (match-end 0)
6070 'display
6071 (if (equal (char-after (match-beginning 2)) ?^)
6072 (nth (if table-p 3 1) org-script-display)
6073 (nth (if table-p 2 0) org-script-display)))
6074 (add-text-properties (match-beginning 2) (match-end 2)
6075 (list 'invisible t
6076 'org-dwidth t 'org-dwidth-n 1))
6077 (if (and (eq (char-after (match-beginning 3)) ?{)
6078 (eq (char-before (match-end 3)) ?}))
6079 (progn
6080 (add-text-properties
6081 (match-beginning 3) (1+ (match-beginning 3))
6082 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6083 (add-text-properties
6084 (1- (match-end 3)) (match-end 3)
6085 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6086 t)))))
6088 ;;;; Visibility cycling, including org-goto and indirect buffer
6090 ;;; Cycling
6092 (defvar org-cycle-global-status nil)
6093 (make-variable-buffer-local 'org-cycle-global-status)
6094 (defvar org-cycle-subtree-status nil)
6095 (make-variable-buffer-local 'org-cycle-subtree-status)
6097 ;;;###autoload
6099 (defvar org-inlinetask-min-level)
6101 (defun org-cycle (&optional arg)
6102 "TAB-action and visibility cycling for Org-mode.
6104 This is the command invoked in Org-mode by the TAB key. Its main purpose
6105 is outline visibility cycling, but it also invokes other actions
6106 in special contexts.
6108 - When this function is called with a prefix argument, rotate the entire
6109 buffer through 3 states (global cycling)
6110 1. OVERVIEW: Show only top-level headlines.
6111 2. CONTENTS: Show all headlines of all levels, but no body text.
6112 3. SHOW ALL: Show everything.
6113 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6114 determined by the variable `org-startup-folded', and by any VISIBILITY
6115 properties in the buffer.
6116 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6117 including any drawers.
6119 - When inside a table, re-align the table and move to the next field.
6121 - When point is at the beginning of a headline, rotate the subtree started
6122 by this line through 3 different states (local cycling)
6123 1. FOLDED: Only the main headline is shown.
6124 2. CHILDREN: The main headline and the direct children are shown.
6125 From this state, you can move to one of the children
6126 and zoom in further.
6127 3. SUBTREE: Show the entire subtree, including body text.
6128 If there is no subtree, switch directly from CHILDREN to FOLDED.
6130 - When point is at the beginning of an empty headline and the variable
6131 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6132 of the headline by demoting and promoting it to likely levels. This
6133 speeds up creation document structure by pressing TAB once or several
6134 times right after creating a new headline.
6136 - When there is a numeric prefix, go up to a heading with level ARG, do
6137 a `show-subtree' and return to the previous cursor position. If ARG
6138 is negative, go up that many levels.
6140 - When point is not at the beginning of a headline, execute the global
6141 binding for TAB, which is re-indenting the line. See the option
6142 `org-cycle-emulate-tab' for details.
6144 - Special case: if point is at the beginning of the buffer and there is
6145 no headline in line 1, this function will act as if called with prefix arg
6146 (C-u TAB, same as S-TAB) also when called without prefix arg.
6147 But only if also the variable `org-cycle-global-at-bob' is t."
6148 (interactive "P")
6149 (org-load-modules-maybe)
6150 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6151 (and org-cycle-level-after-item/entry-creation
6152 (or (org-cycle-level)
6153 (org-cycle-item-indentation))))
6154 (let* ((limit-level
6155 (or org-cycle-max-level
6156 (and (boundp 'org-inlinetask-min-level)
6157 org-inlinetask-min-level
6158 (1- org-inlinetask-min-level))))
6159 (nstars (and limit-level
6160 (if org-odd-levels-only
6161 (and limit-level (1- (* limit-level 2)))
6162 limit-level)))
6163 (org-outline-regexp
6164 (if (not (eq major-mode 'org-mode))
6165 outline-regexp
6166 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6167 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6168 (not (looking-at org-outline-regexp))))
6169 (org-cycle-hook
6170 (if bob-special
6171 (delq 'org-optimize-window-after-visibility-change
6172 (copy-sequence org-cycle-hook))
6173 org-cycle-hook))
6174 (pos (point)))
6176 (if (or bob-special (equal arg '(4)))
6177 ;; special case: use global cycling
6178 (setq arg t))
6180 (cond
6182 ((equal arg '(16))
6183 (setq last-command 'dummy)
6184 (org-set-startup-visibility)
6185 (message "Startup visibility, plus VISIBILITY properties"))
6187 ((equal arg '(64))
6188 (show-all)
6189 (message "Entire buffer visible, including drawers"))
6191 ;; Table: enter it or move to the next field.
6192 ((org-at-table-p 'any)
6193 (if (org-at-table.el-p)
6194 (message "Use C-c ' to edit table.el tables")
6195 (if arg (org-table-edit-field t)
6196 (org-table-justify-field-maybe)
6197 (call-interactively 'org-table-next-field))))
6199 ((run-hook-with-args-until-success
6200 'org-tab-after-check-for-table-hook))
6202 ;; Global cycling: delegate to `org-cycle-internal-global'.
6203 ((eq arg t) (org-cycle-internal-global))
6205 ;; Drawers: delegate to `org-flag-drawer'.
6206 ((and org-drawers org-drawer-regexp
6207 (save-excursion
6208 (beginning-of-line 1)
6209 (looking-at org-drawer-regexp)))
6210 (org-flag-drawer ; toggle block visibility
6211 (not (get-char-property (match-end 0) 'invisible))))
6213 ;; Show-subtree, ARG levels up from here.
6214 ((integerp arg)
6215 (save-excursion
6216 (org-back-to-heading)
6217 (outline-up-heading (if (< arg 0) (- arg)
6218 (- (funcall outline-level) arg)))
6219 (org-show-subtree)))
6221 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6222 ((and (featurep 'org-inlinetask)
6223 (org-inlinetask-at-task-p)
6224 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6225 (org-inlinetask-toggle-visibility))
6227 ((org-try-cdlatex-tab))
6229 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6230 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6231 (save-excursion (beginning-of-line 1)
6232 (looking-at org-outline-regexp)))
6233 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6234 (org-cycle-internal-local))
6236 ;; From there: TAB emulation and template completion.
6237 (buffer-read-only (org-back-to-heading))
6239 ((run-hook-with-args-until-success
6240 'org-tab-after-check-for-cycling-hook))
6242 ((org-try-structure-completion))
6244 ((run-hook-with-args-until-success
6245 'org-tab-before-tab-emulation-hook))
6247 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6248 (or (not (bolp))
6249 (not (looking-at org-outline-regexp))))
6250 (call-interactively (global-key-binding "\t")))
6252 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6253 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6254 (or (and (eq org-cycle-emulate-tab 'white)
6255 (= (match-end 0) (point-at-eol)))
6256 (and (eq org-cycle-emulate-tab 'whitestart)
6257 (>= (match-end 0) pos))))
6259 (eq org-cycle-emulate-tab t))
6260 (call-interactively (global-key-binding "\t")))
6262 (t (save-excursion
6263 (org-back-to-heading)
6264 (org-cycle)))))))
6266 (defun org-cycle-internal-global ()
6267 "Do the global cycling action."
6268 ;; Hack to avoid display of messages for .org attachments in Gnus
6269 (let ((ga (string-match "\\*fontification" (buffer-name))))
6270 (cond
6271 ((and (eq last-command this-command)
6272 (eq org-cycle-global-status 'overview))
6273 ;; We just created the overview - now do table of contents
6274 ;; This can be slow in very large buffers, so indicate action
6275 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6276 (unless ga (message "CONTENTS..."))
6277 (org-content)
6278 (unless ga (message "CONTENTS...done"))
6279 (setq org-cycle-global-status 'contents)
6280 (run-hook-with-args 'org-cycle-hook 'contents))
6282 ((and (eq last-command this-command)
6283 (eq org-cycle-global-status 'contents))
6284 ;; We just showed the table of contents - now show everything
6285 (run-hook-with-args 'org-pre-cycle-hook 'all)
6286 (show-all)
6287 (unless ga (message "SHOW ALL"))
6288 (setq org-cycle-global-status 'all)
6289 (run-hook-with-args 'org-cycle-hook 'all))
6292 ;; Default action: go to overview
6293 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6294 (org-overview)
6295 (unless ga (message "OVERVIEW"))
6296 (setq org-cycle-global-status 'overview)
6297 (run-hook-with-args 'org-cycle-hook 'overview)))))
6299 (defun org-cycle-internal-local ()
6300 "Do the local cycling action."
6301 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6302 ;; First, determine end of headline (EOH), end of subtree or item
6303 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6304 (save-excursion
6305 (if (org-at-item-p)
6306 (progn
6307 (beginning-of-line)
6308 (setq struct (org-list-struct))
6309 (setq eoh (point-at-eol))
6310 (setq eos (org-list-get-item-end-before-blank (point) struct))
6311 (setq has-children (org-list-has-child-p (point) struct)))
6312 (org-back-to-heading)
6313 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6314 (setq eos (save-excursion
6315 (org-end-of-subtree t)
6316 (unless (eobp)
6317 (skip-chars-forward " \t\n"))
6318 (if (eobp) (point) (1- (point)))))
6319 (setq has-children
6320 (or (save-excursion
6321 (let ((level (funcall outline-level)))
6322 (outline-next-heading)
6323 (and (org-at-heading-p t)
6324 (> (funcall outline-level) level))))
6325 (save-excursion
6326 (org-list-search-forward (org-item-beginning-re) eos t)))))
6327 ;; Determine end invisible part of buffer (EOL)
6328 (beginning-of-line 2)
6329 ;; XEmacs doesn't have `next-single-char-property-change'
6330 (if (featurep 'xemacs)
6331 (while (and (not (eobp)) ;; this is like `next-line'
6332 (get-char-property (1- (point)) 'invisible))
6333 (beginning-of-line 2))
6334 (while (and (not (eobp)) ;; this is like `next-line'
6335 (get-char-property (1- (point)) 'invisible))
6336 (goto-char (next-single-char-property-change (point) 'invisible))
6337 (and (eolp) (beginning-of-line 2))))
6338 (setq eol (point)))
6339 ;; Find out what to do next and set `this-command'
6340 (cond
6341 ((= eos eoh)
6342 ;; Nothing is hidden behind this heading
6343 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6344 (message "EMPTY ENTRY")
6345 (setq org-cycle-subtree-status nil)
6346 (save-excursion
6347 (goto-char eos)
6348 (outline-next-heading)
6349 (if (outline-invisible-p) (org-flag-heading nil))))
6350 ((and (or (>= eol eos)
6351 (not (string-match "\\S-" (buffer-substring eol eos))))
6352 (or has-children
6353 (not (setq children-skipped
6354 org-cycle-skip-children-state-if-no-children))))
6355 ;; Entire subtree is hidden in one line: children view
6356 (run-hook-with-args 'org-pre-cycle-hook 'children)
6357 (if (org-at-item-p)
6358 (org-list-set-item-visibility (point-at-bol) struct 'children)
6359 (org-show-entry)
6360 (org-with-limited-levels (show-children))
6361 ;; FIXME: This slows down the func way too much.
6362 ;; How keep drawers hidden in subtree anyway?
6363 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6364 ;; (org-cycle-hide-drawers 'subtree))
6366 ;; Fold every list in subtree to top-level items.
6367 (when (eq org-cycle-include-plain-lists 'integrate)
6368 (save-excursion
6369 (org-back-to-heading)
6370 (while (org-list-search-forward (org-item-beginning-re) eos t)
6371 (beginning-of-line 1)
6372 (let* ((struct (org-list-struct))
6373 (prevs (org-list-prevs-alist struct))
6374 (end (org-list-get-bottom-point struct)))
6375 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6376 (org-list-get-all-items (point) struct prevs))
6377 (goto-char end))))))
6378 (message "CHILDREN")
6379 (save-excursion
6380 (goto-char eos)
6381 (outline-next-heading)
6382 (if (outline-invisible-p) (org-flag-heading nil)))
6383 (setq org-cycle-subtree-status 'children)
6384 (run-hook-with-args 'org-cycle-hook 'children))
6385 ((or children-skipped
6386 (and (eq last-command this-command)
6387 (eq org-cycle-subtree-status 'children)))
6388 ;; We just showed the children, or no children are there,
6389 ;; now show everything.
6390 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6391 (outline-flag-region eoh eos nil)
6392 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6393 (setq org-cycle-subtree-status 'subtree)
6394 (run-hook-with-args 'org-cycle-hook 'subtree))
6396 ;; Default action: hide the subtree.
6397 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6398 (outline-flag-region eoh eos t)
6399 (message "FOLDED")
6400 (setq org-cycle-subtree-status 'folded)
6401 (run-hook-with-args 'org-cycle-hook 'folded)))))
6403 ;;;###autoload
6404 (defun org-global-cycle (&optional arg)
6405 "Cycle the global visibility. For details see `org-cycle'.
6406 With \\[universal-argument] prefix arg, switch to startup visibility.
6407 With a numeric prefix, show all headlines up to that level."
6408 (interactive "P")
6409 (let ((org-cycle-include-plain-lists
6410 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6411 (cond
6412 ((integerp arg)
6413 (show-all)
6414 (hide-sublevels arg)
6415 (setq org-cycle-global-status 'contents))
6416 ((equal arg '(4))
6417 (org-set-startup-visibility)
6418 (message "Startup visibility, plus VISIBILITY properties."))
6420 (org-cycle '(4))))))
6422 (defun org-set-startup-visibility ()
6423 "Set the visibility required by startup options and properties."
6424 (cond
6425 ((eq org-startup-folded t)
6426 (org-cycle '(4)))
6427 ((eq org-startup-folded 'content)
6428 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6429 (org-cycle '(4)) (org-cycle '(4)))))
6430 (unless (eq org-startup-folded 'showeverything)
6431 (if org-hide-block-startup (org-hide-block-all))
6432 (org-set-visibility-according-to-property 'no-cleanup)
6433 (org-cycle-hide-archived-subtrees 'all)
6434 (org-cycle-hide-drawers 'all)
6435 (org-cycle-show-empty-lines t)))
6437 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6438 "Switch subtree visibilities according to :VISIBILITY: property."
6439 (interactive)
6440 (let (org-show-entry-below state)
6441 (save-excursion
6442 (goto-char (point-min))
6443 (while (re-search-forward
6444 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6445 nil t)
6446 (setq state (match-string 1))
6447 (save-excursion
6448 (org-back-to-heading t)
6449 (hide-subtree)
6450 (org-reveal)
6451 (cond
6452 ((equal state '("fold" "folded"))
6453 (hide-subtree))
6454 ((equal state "children")
6455 (org-show-hidden-entry)
6456 (show-children))
6457 ((equal state "content")
6458 (save-excursion
6459 (save-restriction
6460 (org-narrow-to-subtree)
6461 (org-content))))
6462 ((member state '("all" "showall"))
6463 (show-subtree)))))
6464 (unless no-cleanup
6465 (org-cycle-hide-archived-subtrees 'all)
6466 (org-cycle-hide-drawers 'all)
6467 (org-cycle-show-empty-lines 'all)))))
6469 ;; This function uses outline-regexp instead of the more fundamental
6470 ;; org-outline-regexp so that org-cycle-global works outside of Org
6471 ;; buffers, where outline-regexp is needed.
6472 (defun org-overview ()
6473 "Switch to overview mode, showing only top-level headlines.
6474 Really, this shows all headlines with level equal or greater than the level
6475 of the first headline in the buffer. This is important, because if the
6476 first headline is not level one, then (hide-sublevels 1) gives confusing
6477 results."
6478 (interactive)
6479 (let ((level (save-excursion
6480 (goto-char (point-min))
6481 (if (re-search-forward (concat "^" outline-regexp) nil t)
6482 (progn
6483 (goto-char (match-beginning 0))
6484 (funcall outline-level))))))
6485 (and level (hide-sublevels level))))
6487 (defun org-content (&optional arg)
6488 "Show all headlines in the buffer, like a table of contents.
6489 With numerical argument N, show content up to level N."
6490 (interactive "P")
6491 (save-excursion
6492 ;; Visit all headings and show their offspring
6493 (and (integerp arg) (org-overview))
6494 (goto-char (point-max))
6495 (catch 'exit
6496 (while (and (progn (condition-case nil
6497 (outline-previous-visible-heading 1)
6498 (error (goto-char (point-min))))
6500 (looking-at org-outline-regexp))
6501 (if (integerp arg)
6502 (show-children (1- arg))
6503 (show-branches))
6504 (if (bobp) (throw 'exit nil))))))
6507 (defun org-optimize-window-after-visibility-change (state)
6508 "Adjust the window after a change in outline visibility.
6509 This function is the default value of the hook `org-cycle-hook'."
6510 (when (get-buffer-window (current-buffer))
6511 (cond
6512 ((eq state 'content) nil)
6513 ((eq state 'all) nil)
6514 ((eq state 'folded) nil)
6515 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6516 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6518 (defun org-remove-empty-overlays-at (pos)
6519 "Remove outline overlays that do not contain non-white stuff."
6520 (mapc
6521 (lambda (o)
6522 (and (eq 'outline (overlay-get o 'invisible))
6523 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6524 (overlay-end o))))
6525 (delete-overlay o)))
6526 (overlays-at pos)))
6528 (defun org-clean-visibility-after-subtree-move ()
6529 "Fix visibility issues after moving a subtree."
6530 ;; First, find a reasonable region to look at:
6531 ;; Start two siblings above, end three below
6532 (let* ((beg (save-excursion
6533 (and (org-get-last-sibling)
6534 (org-get-last-sibling))
6535 (point)))
6536 (end (save-excursion
6537 (and (org-get-next-sibling)
6538 (org-get-next-sibling)
6539 (org-get-next-sibling))
6540 (if (org-at-heading-p)
6541 (point-at-eol)
6542 (point))))
6543 (level (looking-at "\\*+"))
6544 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6545 (save-excursion
6546 (save-restriction
6547 (narrow-to-region beg end)
6548 (when re
6549 ;; Properly fold already folded siblings
6550 (goto-char (point-min))
6551 (while (re-search-forward re nil t)
6552 (if (and (not (outline-invisible-p))
6553 (save-excursion
6554 (goto-char (point-at-eol)) (outline-invisible-p)))
6555 (hide-entry))))
6556 (org-cycle-show-empty-lines 'overview)
6557 (org-cycle-hide-drawers 'overview)))))
6559 (defun org-cycle-show-empty-lines (state)
6560 "Show empty lines above all visible headlines.
6561 The region to be covered depends on STATE when called through
6562 `org-cycle-hook'. Lisp program can use t for STATE to get the
6563 entire buffer covered. Note that an empty line is only shown if there
6564 are at least `org-cycle-separator-lines' empty lines before the headline."
6565 (when (not (= org-cycle-separator-lines 0))
6566 (save-excursion
6567 (let* ((n (abs org-cycle-separator-lines))
6568 (re (cond
6569 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6570 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6571 (t (let ((ns (number-to-string (- n 2))))
6572 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6573 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6574 beg end b e)
6575 (cond
6576 ((memq state '(overview contents t))
6577 (setq beg (point-min) end (point-max)))
6578 ((memq state '(children folded))
6579 (setq beg (point) end (progn (org-end-of-subtree t t)
6580 (beginning-of-line 2)
6581 (point)))))
6582 (when beg
6583 (goto-char beg)
6584 (while (re-search-forward re end t)
6585 (unless (get-char-property (match-end 1) 'invisible)
6586 (setq e (match-end 1))
6587 (if (< org-cycle-separator-lines 0)
6588 (setq b (save-excursion
6589 (goto-char (match-beginning 0))
6590 (org-back-over-empty-lines)
6591 (if (save-excursion
6592 (goto-char (max (point-min) (1- (point))))
6593 (org-at-heading-p))
6594 (1- (point))
6595 (point))))
6596 (setq b (match-beginning 1)))
6597 (outline-flag-region b e nil)))))))
6598 ;; Never hide empty lines at the end of the file.
6599 (save-excursion
6600 (goto-char (point-max))
6601 (outline-previous-heading)
6602 (outline-end-of-heading)
6603 (if (and (looking-at "[ \t\n]+")
6604 (= (match-end 0) (point-max)))
6605 (outline-flag-region (point) (match-end 0) nil))))
6607 (defun org-show-empty-lines-in-parent ()
6608 "Move to the parent and re-show empty lines before visible headlines."
6609 (save-excursion
6610 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6611 (org-cycle-show-empty-lines context))))
6613 (defun org-files-list ()
6614 "Return `org-agenda-files' list, plus all open org-mode files.
6615 This is useful for operations that need to scan all of a user's
6616 open and agenda-wise Org files."
6617 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6618 (dolist (buf (buffer-list))
6619 (with-current-buffer buf
6620 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6621 (let ((file (expand-file-name (buffer-file-name))))
6622 (unless (member file files)
6623 (push file files))))))
6624 files))
6626 (defsubst org-entry-beginning-position ()
6627 "Return the beginning position of the current entry."
6628 (save-excursion (outline-back-to-heading t) (point)))
6630 (defsubst org-entry-end-position ()
6631 "Return the end position of the current entry."
6632 (save-excursion (outline-next-heading) (point)))
6634 (defun org-cycle-hide-drawers (state)
6635 "Re-hide all drawers after a visibility state change."
6636 (when (and (eq major-mode 'org-mode)
6637 (not (memq state '(overview folded contents))))
6638 (save-excursion
6639 (let* ((globalp (memq state '(contents all)))
6640 (beg (if globalp (point-min) (point)))
6641 (end (if globalp (point-max)
6642 (if (eq state 'children)
6643 (save-excursion (outline-next-heading) (point))
6644 (org-end-of-subtree t)))))
6645 (goto-char beg)
6646 (while (re-search-forward org-drawer-regexp end t)
6647 (org-flag-drawer t))))))
6649 (defun org-flag-drawer (flag)
6650 (save-excursion
6651 (beginning-of-line 1)
6652 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6653 (let ((b (match-end 0)))
6654 (if (re-search-forward
6655 "^[ \t]*:END:"
6656 (save-excursion (outline-next-heading) (point)) t)
6657 (outline-flag-region b (point-at-eol) flag)
6658 (error ":END: line missing at position %s" b))))))
6660 (defun org-subtree-end-visible-p ()
6661 "Is the end of the current subtree visible?"
6662 (pos-visible-in-window-p
6663 (save-excursion (org-end-of-subtree t) (point))))
6665 (defun org-first-headline-recenter (&optional N)
6666 "Move cursor to the first headline and recenter the headline.
6667 Optional argument N means put the headline into the Nth line of the window."
6668 (goto-char (point-min))
6669 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6670 (beginning-of-line)
6671 (recenter (prefix-numeric-value N))))
6673 ;;; Saving and restoring visibility
6675 (defun org-outline-overlay-data (&optional use-markers)
6676 "Return a list of the locations of all outline overlays.
6677 These are overlays with the `invisible' property value `outline'.
6678 The return value is a list of cons cells, with start and stop
6679 positions for each overlay.
6680 If USE-MARKERS is set, return the positions as markers."
6681 (let (beg end)
6682 (save-excursion
6683 (save-restriction
6684 (widen)
6685 (delq nil
6686 (mapcar (lambda (o)
6687 (when (eq (overlay-get o 'invisible) 'outline)
6688 (setq beg (overlay-start o)
6689 end (overlay-end o))
6690 (and beg end (> end beg)
6691 (if use-markers
6692 (cons (move-marker (make-marker) beg)
6693 (move-marker (make-marker) end))
6694 (cons beg end)))))
6695 (overlays-in (point-min) (point-max))))))))
6697 (defun org-set-outline-overlay-data (data)
6698 "Create visibility overlays for all positions in DATA.
6699 DATA should have been made by `org-outline-overlay-data'."
6700 (let (o)
6701 (save-excursion
6702 (save-restriction
6703 (widen)
6704 (show-all)
6705 (mapc (lambda (c)
6706 (outline-flag-region (car c) (cdr c) t))
6707 data)))))
6709 ;;; Folding of blocks
6711 (defvar org-hide-block-overlays nil
6712 "Overlays hiding blocks.")
6713 (make-variable-buffer-local 'org-hide-block-overlays)
6715 (defun org-block-map (function &optional start end)
6716 "Call FUNCTION at the head of all source blocks in the current buffer.
6717 Optional arguments START and END can be used to limit the range."
6718 (let ((start (or start (point-min)))
6719 (end (or end (point-max))))
6720 (save-excursion
6721 (goto-char start)
6722 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6723 (save-excursion
6724 (save-match-data
6725 (goto-char (match-beginning 0))
6726 (funcall function)))))))
6728 (defun org-hide-block-toggle-all ()
6729 "Toggle the visibility of all blocks in the current buffer."
6730 (org-block-map #'org-hide-block-toggle))
6732 (defun org-hide-block-all ()
6733 "Fold all blocks in the current buffer."
6734 (interactive)
6735 (org-show-block-all)
6736 (org-block-map #'org-hide-block-toggle-maybe))
6738 (defun org-show-block-all ()
6739 "Unfold all blocks in the current buffer."
6740 (interactive)
6741 (mapc 'delete-overlay org-hide-block-overlays)
6742 (setq org-hide-block-overlays nil))
6744 (defun org-hide-block-toggle-maybe ()
6745 "Toggle visibility of block at point."
6746 (interactive)
6747 (let ((case-fold-search t))
6748 (if (save-excursion
6749 (beginning-of-line 1)
6750 (looking-at org-block-regexp))
6751 (progn (org-hide-block-toggle)
6752 t) ;; to signal that we took action
6753 nil))) ;; to signal that we did not
6755 (defun org-hide-block-toggle (&optional force)
6756 "Toggle the visibility of the current block."
6757 (interactive)
6758 (save-excursion
6759 (beginning-of-line)
6760 (if (re-search-forward org-block-regexp nil t)
6761 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6762 (end (match-end 0)) ;; end of entire body
6764 (if (memq t (mapcar (lambda (overlay)
6765 (eq (overlay-get overlay 'invisible)
6766 'org-hide-block))
6767 (overlays-at start)))
6768 (if (or (not force) (eq force 'off))
6769 (mapc (lambda (ov)
6770 (when (member ov org-hide-block-overlays)
6771 (setq org-hide-block-overlays
6772 (delq ov org-hide-block-overlays)))
6773 (when (eq (overlay-get ov 'invisible)
6774 'org-hide-block)
6775 (delete-overlay ov)))
6776 (overlays-at start)))
6777 (setq ov (make-overlay start end))
6778 (overlay-put ov 'invisible 'org-hide-block)
6779 ;; make the block accessible to isearch
6780 (overlay-put
6781 ov 'isearch-open-invisible
6782 (lambda (ov)
6783 (when (member ov org-hide-block-overlays)
6784 (setq org-hide-block-overlays
6785 (delq ov org-hide-block-overlays)))
6786 (when (eq (overlay-get ov 'invisible)
6787 'org-hide-block)
6788 (delete-overlay ov))))
6789 (push ov org-hide-block-overlays)))
6790 (error "Not looking at a source block"))))
6792 ;; org-tab-after-check-for-cycling-hook
6793 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6794 ;; Remove overlays when changing major mode
6795 (add-hook 'org-mode-hook
6796 (lambda () (org-add-hook 'change-major-mode-hook
6797 'org-show-block-all 'append 'local)))
6799 ;;; Org-goto
6801 (defvar org-goto-window-configuration nil)
6802 (defvar org-goto-marker nil)
6803 (defvar org-goto-map
6804 (let ((map (make-sparse-keymap)))
6805 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6806 (while (setq cmd (pop cmds))
6807 (substitute-key-definition cmd cmd map global-map)))
6808 (suppress-keymap map)
6809 (org-defkey map "\C-m" 'org-goto-ret)
6810 (org-defkey map [(return)] 'org-goto-ret)
6811 (org-defkey map [(left)] 'org-goto-left)
6812 (org-defkey map [(right)] 'org-goto-right)
6813 (org-defkey map [(control ?g)] 'org-goto-quit)
6814 (org-defkey map "\C-i" 'org-cycle)
6815 (org-defkey map [(tab)] 'org-cycle)
6816 (org-defkey map [(down)] 'outline-next-visible-heading)
6817 (org-defkey map [(up)] 'outline-previous-visible-heading)
6818 (if org-goto-auto-isearch
6819 (if (fboundp 'define-key-after)
6820 (define-key-after map [t] 'org-goto-local-auto-isearch)
6821 nil)
6822 (org-defkey map "q" 'org-goto-quit)
6823 (org-defkey map "n" 'outline-next-visible-heading)
6824 (org-defkey map "p" 'outline-previous-visible-heading)
6825 (org-defkey map "f" 'outline-forward-same-level)
6826 (org-defkey map "b" 'outline-backward-same-level)
6827 (org-defkey map "u" 'outline-up-heading))
6828 (org-defkey map "/" 'org-occur)
6829 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6830 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6831 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6832 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6833 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6834 map))
6836 (defconst org-goto-help
6837 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6838 RET=jump to location [Q]uit and return to previous location
6839 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6841 (defvar org-goto-start-pos) ; dynamically scoped parameter
6843 ;; FIXME: Docstring does not mention both interfaces
6844 (defun org-goto (&optional alternative-interface)
6845 "Look up a different location in the current file, keeping current visibility.
6847 When you want look-up or go to a different location in a document, the
6848 fastest way is often to fold the entire buffer and then dive into the tree.
6849 This method has the disadvantage, that the previous location will be folded,
6850 which may not be what you want.
6852 This command works around this by showing a copy of the current buffer
6853 in an indirect buffer, in overview mode. You can dive into the tree in
6854 that copy, use org-occur and incremental search to find a location.
6855 When pressing RET or `Q', the command returns to the original buffer in
6856 which the visibility is still unchanged. After RET it will also jump to
6857 the location selected in the indirect buffer and expose the headline
6858 hierarchy above."
6859 (interactive "P")
6860 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6861 (org-refile-use-outline-path t)
6862 (org-refile-target-verify-function nil)
6863 (interface
6864 (if (not alternative-interface)
6865 org-goto-interface
6866 (if (eq org-goto-interface 'outline)
6867 'outline-path-completion
6868 'outline)))
6869 (org-goto-start-pos (point))
6870 (selected-point
6871 (if (eq interface 'outline)
6872 (car (org-get-location (current-buffer) org-goto-help))
6873 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6874 (org-refile-check-position pa)
6875 (nth 3 pa)))))
6876 (if selected-point
6877 (progn
6878 (org-mark-ring-push org-goto-start-pos)
6879 (goto-char selected-point)
6880 (if (or (outline-invisible-p) (org-invisible-p2))
6881 (org-show-context 'org-goto)))
6882 (message "Quit"))))
6884 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6885 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6886 (defvar org-goto-local-auto-isearch-map) ; defined below
6888 (defun org-get-location (buf help)
6889 "Let the user select a location in the Org-mode buffer BUF.
6890 This function uses a recursive edit. It returns the selected position
6891 or nil."
6892 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6893 (isearch-hide-immediately nil)
6894 (isearch-search-fun-function
6895 (lambda () 'org-goto-local-search-headings))
6896 (org-goto-selected-point org-goto-exit-command)
6897 (pop-up-frames nil)
6898 (special-display-buffer-names nil)
6899 (special-display-regexps nil)
6900 (special-display-function nil))
6901 (save-excursion
6902 (save-window-excursion
6903 (delete-other-windows)
6904 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6905 (org-pop-to-buffer-same-window
6906 (condition-case nil
6907 (make-indirect-buffer (current-buffer) "*org-goto*")
6908 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6909 (with-output-to-temp-buffer "*Help*"
6910 (princ help))
6911 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6912 (setq buffer-read-only nil)
6913 (let ((org-startup-truncated t)
6914 (org-startup-folded nil)
6915 (org-startup-align-all-tables nil))
6916 (org-mode)
6917 (org-overview))
6918 (setq buffer-read-only t)
6919 (if (and (boundp 'org-goto-start-pos)
6920 (integer-or-marker-p org-goto-start-pos))
6921 (let ((org-show-hierarchy-above t)
6922 (org-show-siblings t)
6923 (org-show-following-heading t))
6924 (goto-char org-goto-start-pos)
6925 (and (outline-invisible-p) (org-show-context)))
6926 (goto-char (point-min)))
6927 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6928 (message "Select location and press RET")
6929 (use-local-map org-goto-map)
6930 (recursive-edit)
6932 (kill-buffer "*org-goto*")
6933 (cons org-goto-selected-point org-goto-exit-command)))
6935 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6936 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6937 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6938 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6940 (defun org-goto-local-search-headings (string bound noerror)
6941 "Search and make sure that any matches are in headlines."
6942 (catch 'return
6943 (while (if isearch-forward
6944 (search-forward string bound noerror)
6945 (search-backward string bound noerror))
6946 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6947 (and (member :headline context)
6948 (not (member :tags context))))
6949 (throw 'return (point))))))
6951 (defun org-goto-local-auto-isearch ()
6952 "Start isearch."
6953 (interactive)
6954 (goto-char (point-min))
6955 (let ((keys (this-command-keys)))
6956 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6957 (isearch-mode t)
6958 (isearch-process-search-char (string-to-char keys)))))
6960 (defun org-goto-ret (&optional arg)
6961 "Finish `org-goto' by going to the new location."
6962 (interactive "P")
6963 (setq org-goto-selected-point (point)
6964 org-goto-exit-command 'return)
6965 (throw 'exit nil))
6967 (defun org-goto-left ()
6968 "Finish `org-goto' by going to the new location."
6969 (interactive)
6970 (if (org-at-heading-p)
6971 (progn
6972 (beginning-of-line 1)
6973 (setq org-goto-selected-point (point)
6974 org-goto-exit-command 'left)
6975 (throw 'exit nil))
6976 (error "Not on a heading")))
6978 (defun org-goto-right ()
6979 "Finish `org-goto' by going to the new location."
6980 (interactive)
6981 (if (org-at-heading-p)
6982 (progn
6983 (setq org-goto-selected-point (point)
6984 org-goto-exit-command 'right)
6985 (throw 'exit nil))
6986 (error "Not on a heading")))
6988 (defun org-goto-quit ()
6989 "Finish `org-goto' without cursor motion."
6990 (interactive)
6991 (setq org-goto-selected-point nil)
6992 (setq org-goto-exit-command 'quit)
6993 (throw 'exit nil))
6995 ;;; Indirect buffer display of subtrees
6997 (defvar org-indirect-dedicated-frame nil
6998 "This is the frame being used for indirect tree display.")
6999 (defvar org-last-indirect-buffer nil)
7001 (defun org-tree-to-indirect-buffer (&optional arg)
7002 "Create indirect buffer and narrow it to current subtree.
7003 With numerical prefix ARG, go up to this level and then take that tree.
7004 If ARG is negative, go up that many levels.
7005 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7006 indirect buffer previously made with this command, to avoid proliferation of
7007 indirect buffers. However, when you call the command with a \
7008 \\[universal-argument] prefix, or
7009 when `org-indirect-buffer-display' is `new-frame', the last buffer
7010 is kept so that you can work with several indirect buffers at the same time.
7011 If `org-indirect-buffer-display' is `dedicated-frame', the \
7012 \\[universal-argument] prefix also
7013 requests that a new frame be made for the new buffer, so that the dedicated
7014 frame is not changed."
7015 (interactive "P")
7016 (let ((cbuf (current-buffer))
7017 (cwin (selected-window))
7018 (pos (point))
7019 beg end level heading ibuf)
7020 (save-excursion
7021 (org-back-to-heading t)
7022 (when (numberp arg)
7023 (setq level (org-outline-level))
7024 (if (< arg 0) (setq arg (+ level arg)))
7025 (while (> (setq level (org-outline-level)) arg)
7026 (outline-up-heading 1 t)))
7027 (setq beg (point)
7028 heading (org-get-heading))
7029 (org-end-of-subtree t t)
7030 (if (org-at-heading-p) (backward-char 1))
7031 (setq end (point)))
7032 (if (and (buffer-live-p org-last-indirect-buffer)
7033 (not (eq org-indirect-buffer-display 'new-frame))
7034 (not arg))
7035 (kill-buffer org-last-indirect-buffer))
7036 (setq ibuf (org-get-indirect-buffer cbuf)
7037 org-last-indirect-buffer ibuf)
7038 (cond
7039 ((or (eq org-indirect-buffer-display 'new-frame)
7040 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7041 (select-frame (make-frame))
7042 (delete-other-windows)
7043 (org-pop-to-buffer-same-window ibuf)
7044 (org-set-frame-title heading))
7045 ((eq org-indirect-buffer-display 'dedicated-frame)
7046 (raise-frame
7047 (select-frame (or (and org-indirect-dedicated-frame
7048 (frame-live-p org-indirect-dedicated-frame)
7049 org-indirect-dedicated-frame)
7050 (setq org-indirect-dedicated-frame (make-frame)))))
7051 (delete-other-windows)
7052 (org-pop-to-buffer-same-window ibuf)
7053 (org-set-frame-title (concat "Indirect: " heading)))
7054 ((eq org-indirect-buffer-display 'current-window)
7055 (org-pop-to-buffer-same-window ibuf))
7056 ((eq org-indirect-buffer-display 'other-window)
7057 (pop-to-buffer ibuf))
7058 (t (error "Invalid value")))
7059 (if (featurep 'xemacs)
7060 (save-excursion (org-mode) (turn-on-font-lock)))
7061 (narrow-to-region beg end)
7062 (show-all)
7063 (goto-char pos)
7064 (run-hook-with-args 'org-cycle-hook 'all)
7065 (and (window-live-p cwin) (select-window cwin))))
7067 (defun org-get-indirect-buffer (&optional buffer)
7068 (setq buffer (or buffer (current-buffer)))
7069 (let ((n 1) (base (buffer-name buffer)) bname)
7070 (while (buffer-live-p
7071 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7072 (setq n (1+ n)))
7073 (condition-case nil
7074 (make-indirect-buffer buffer bname 'clone)
7075 (error (make-indirect-buffer buffer bname)))))
7077 (defun org-set-frame-title (title)
7078 "Set the title of the current frame to the string TITLE."
7079 ;; FIXME: how to name a single frame in XEmacs???
7080 (unless (featurep 'xemacs)
7081 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7083 ;;;; Structure editing
7085 ;;; Inserting headlines
7087 (defun org-previous-line-empty-p ()
7088 (save-excursion
7089 (and (not (bobp))
7090 (or (beginning-of-line 0) t)
7091 (save-match-data
7092 (looking-at "[ \t]*$")))))
7094 (defun org-insert-heading (&optional force-heading invisible-ok)
7095 "Insert a new heading or item with same depth at point.
7096 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7097 If point is at the beginning of a headline, insert a sibling before the
7098 current headline. If point is not at the beginning, split the line,
7099 create the new headline with the text in the current line after point
7100 \(but see also the variable `org-M-RET-may-split-line').
7102 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7103 This is important for non-interactive uses of the command."
7104 (interactive "P")
7105 (if (or (= (buffer-size) 0)
7106 (and (not (save-excursion
7107 (and (ignore-errors (org-back-to-heading invisible-ok))
7108 (org-at-heading-p))))
7109 (or force-heading (not (org-in-item-p)))))
7110 (progn
7111 (insert "\n* ")
7112 (run-hooks 'org-insert-heading-hook))
7113 (when (or force-heading (not (org-insert-item)))
7114 (let* ((empty-line-p nil)
7115 (level nil)
7116 (on-heading (org-at-heading-p))
7117 (head (save-excursion
7118 (condition-case nil
7119 (progn
7120 (org-back-to-heading invisible-ok)
7121 (when (and (not on-heading)
7122 (featurep 'org-inlinetask)
7123 (integerp org-inlinetask-min-level)
7124 (>= (length (match-string 0))
7125 org-inlinetask-min-level))
7126 ;; Find a heading level before the inline task
7127 (while (and (setq level (org-up-heading-safe))
7128 (>= level org-inlinetask-min-level)))
7129 (if (org-at-heading-p)
7130 (org-back-to-heading invisible-ok)
7131 (error "This should not happen")))
7132 (setq empty-line-p (org-previous-line-empty-p))
7133 (match-string 0))
7134 (error "*"))))
7135 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7136 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7137 pos hide-previous previous-pos)
7138 (cond
7139 ((and (org-at-heading-p) (bolp)
7140 (or (bobp)
7141 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7142 ;; insert before the current line
7143 (open-line (if blank 2 1)))
7144 ((and (bolp)
7145 (not org-insert-heading-respect-content)
7146 (or (bobp)
7147 (save-excursion
7148 (backward-char 1) (not (outline-invisible-p)))))
7149 ;; insert right here
7150 nil)
7152 ;; somewhere in the line
7153 (save-excursion
7154 (setq previous-pos (point-at-bol))
7155 (end-of-line)
7156 (setq hide-previous (outline-invisible-p)))
7157 (and org-insert-heading-respect-content (org-show-subtree))
7158 (let ((split
7159 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7160 (save-excursion
7161 (let ((p (point)))
7162 (goto-char (point-at-bol))
7163 (and (looking-at org-complex-heading-regexp)
7164 (match-beginning 4)
7165 (> p (match-beginning 4)))))))
7166 tags pos)
7167 (cond
7168 (org-insert-heading-respect-content
7169 (org-end-of-subtree nil t)
7170 (when (featurep 'org-inlinetask)
7171 (while (and (not (eobp))
7172 (looking-at "\\(\\*+\\)[ \t]+")
7173 (>= (length (match-string 1))
7174 org-inlinetask-min-level))
7175 (org-end-of-subtree nil t)))
7176 (or (bolp) (newline))
7177 (or (org-previous-line-empty-p)
7178 (and blank (newline)))
7179 (open-line 1))
7180 ((org-at-heading-p)
7181 (when hide-previous
7182 (show-children)
7183 (org-show-entry))
7184 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7185 (setq tags (and (match-end 2) (match-string 2)))
7186 (and (match-end 1)
7187 (delete-region (match-beginning 1) (match-end 1)))
7188 (setq pos (point-at-bol))
7189 (or split (end-of-line 1))
7190 (delete-horizontal-space)
7191 (if (string-match "\\`\\*+\\'"
7192 (buffer-substring (point-at-bol) (point)))
7193 (insert " "))
7194 (newline (if blank 2 1))
7195 (when tags
7196 (save-excursion
7197 (goto-char pos)
7198 (end-of-line 1)
7199 (insert " " tags)
7200 (org-set-tags nil 'align))))
7202 (or split (end-of-line 1))
7203 (newline (if blank 2 1)))))))
7204 (insert head) (just-one-space)
7205 (setq pos (point))
7206 (end-of-line 1)
7207 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7208 (when (and org-insert-heading-respect-content hide-previous)
7209 (save-excursion
7210 (goto-char previous-pos)
7211 (hide-subtree)))
7212 (run-hooks 'org-insert-heading-hook)))))
7214 (defun org-get-heading (&optional no-tags no-todo)
7215 "Return the heading of the current entry, without the stars.
7216 When NO-TAGS is non-nil, don't include tags.
7217 When NO-TODO is non-nil, don't include TODO keywords."
7218 (save-excursion
7219 (org-back-to-heading t)
7220 (cond
7221 ((and no-tags no-todo)
7222 (looking-at org-complex-heading-regexp)
7223 (match-string 4))
7224 (no-tags
7225 (looking-at (concat org-outline-regexp
7226 "\\(.*?\\)"
7227 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7228 (match-string 1))
7229 (no-todo
7230 (looking-at org-todo-line-regexp)
7231 (match-string 3))
7232 (t (looking-at org-heading-regexp)
7233 (match-string 2)))))
7235 (defun org-heading-components ()
7236 "Return the components of the current heading.
7237 This is a list with the following elements:
7238 - the level as an integer
7239 - the reduced level, different if `org-odd-levels-only' is set.
7240 - the TODO keyword, or nil
7241 - the priority character, like ?A, or nil if no priority is given
7242 - the headline text itself, or the tags string if no headline text
7243 - the tags string, or nil."
7244 (save-excursion
7245 (org-back-to-heading t)
7246 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7247 (list (length (match-string 1))
7248 (org-reduced-level (length (match-string 1)))
7249 (org-match-string-no-properties 2)
7250 (and (match-end 3) (aref (match-string 3) 2))
7251 (org-match-string-no-properties 4)
7252 (org-match-string-no-properties 5)))))
7254 (defun org-get-entry ()
7255 "Get the entry text, after heading, entire subtree."
7256 (save-excursion
7257 (org-back-to-heading t)
7258 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7260 (defun org-insert-heading-after-current ()
7261 "Insert a new heading with same level as current, after current subtree."
7262 (interactive)
7263 (org-back-to-heading)
7264 (org-insert-heading)
7265 (org-move-subtree-down)
7266 (end-of-line 1))
7268 (defun org-insert-heading-respect-content ()
7269 (interactive)
7270 (let ((org-insert-heading-respect-content t))
7271 (org-insert-heading t)))
7273 (defun org-insert-todo-heading-respect-content (&optional force-state)
7274 (interactive "P")
7275 (let ((org-insert-heading-respect-content t))
7276 (org-insert-todo-heading force-state t)))
7278 (defun org-insert-todo-heading (arg &optional force-heading)
7279 "Insert a new heading with the same level and TODO state as current heading.
7280 If the heading has no TODO state, or if the state is DONE, use the first
7281 state (TODO by default). Also with prefix arg, force first state."
7282 (interactive "P")
7283 (when (or force-heading (not (org-insert-item 'checkbox)))
7284 (org-insert-heading force-heading)
7285 (save-excursion
7286 (org-back-to-heading)
7287 (outline-previous-heading)
7288 (looking-at org-todo-line-regexp))
7289 (let*
7290 ((new-mark-x
7291 (if (or arg
7292 (not (match-beginning 2))
7293 (member (match-string 2) org-done-keywords))
7294 (car org-todo-keywords-1)
7295 (match-string 2)))
7296 (new-mark
7298 (run-hook-with-args-until-success
7299 'org-todo-get-default-hook new-mark-x nil)
7300 new-mark-x)))
7301 (beginning-of-line 1)
7302 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7303 (if org-treat-insert-todo-heading-as-state-change
7304 (org-todo new-mark)
7305 (insert new-mark " "))))
7306 (when org-provide-todo-statistics
7307 (org-update-parent-todo-statistics))))
7309 (defun org-insert-subheading (arg)
7310 "Insert a new subheading and demote it.
7311 Works for outline headings and for plain lists alike."
7312 (interactive "P")
7313 (org-insert-heading arg)
7314 (cond
7315 ((org-at-heading-p) (org-do-demote))
7316 ((org-at-item-p) (org-indent-item))))
7318 (defun org-insert-todo-subheading (arg)
7319 "Insert a new subheading with TODO keyword or checkbox and demote it.
7320 Works for outline headings and for plain lists alike."
7321 (interactive "P")
7322 (org-insert-todo-heading arg)
7323 (cond
7324 ((org-at-heading-p) (org-do-demote))
7325 ((org-at-item-p) (org-indent-item))))
7327 ;;; Promotion and Demotion
7329 (defvar org-after-demote-entry-hook nil
7330 "Hook run after an entry has been demoted.
7331 The cursor will be at the beginning of the entry.
7332 When a subtree is being demoted, the hook will be called for each node.")
7334 (defvar org-after-promote-entry-hook nil
7335 "Hook run after an entry has been promoted.
7336 The cursor will be at the beginning of the entry.
7337 When a subtree is being promoted, the hook will be called for each node.")
7339 (defun org-promote-subtree ()
7340 "Promote the entire subtree.
7341 See also `org-promote'."
7342 (interactive)
7343 (save-excursion
7344 (org-with-limited-levels (org-map-tree 'org-promote)))
7345 (org-fix-position-after-promote))
7347 (defun org-demote-subtree ()
7348 "Demote the entire subtree. See `org-demote'.
7349 See also `org-promote'."
7350 (interactive)
7351 (save-excursion
7352 (org-with-limited-levels (org-map-tree 'org-demote)))
7353 (org-fix-position-after-promote))
7356 (defun org-do-promote ()
7357 "Promote the current heading higher up the tree.
7358 If the region is active in `transient-mark-mode', promote all headings
7359 in the region."
7360 (interactive)
7361 (save-excursion
7362 (if (org-region-active-p)
7363 (org-map-region 'org-promote (region-beginning) (region-end))
7364 (org-promote)))
7365 (org-fix-position-after-promote))
7367 (defun org-do-demote ()
7368 "Demote the current heading lower down the tree.
7369 If the region is active in `transient-mark-mode', demote all headings
7370 in the region."
7371 (interactive)
7372 (save-excursion
7373 (if (org-region-active-p)
7374 (org-map-region 'org-demote (region-beginning) (region-end))
7375 (org-demote)))
7376 (org-fix-position-after-promote))
7378 (defun org-fix-position-after-promote ()
7379 "Make sure that after pro/demotion cursor position is right."
7380 (let ((pos (point)))
7381 (when (save-excursion
7382 (beginning-of-line 1)
7383 (looking-at org-todo-line-regexp)
7384 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7385 (cond ((eobp) (insert " "))
7386 ((eolp) (insert " "))
7387 ((equal (char-after) ?\ ) (forward-char 1))))))
7389 (defun org-current-level ()
7390 "Return the level of the current entry, or nil if before the first headline.
7391 The level is the number of stars at the beginning of the headline."
7392 (save-excursion
7393 (org-with-limited-levels
7394 (if (ignore-errors (org-back-to-heading t))
7395 (funcall outline-level)))))
7397 (defun org-get-previous-line-level ()
7398 "Return the outline depth of the last headline before the current line.
7399 Returns 0 for the first headline in the buffer, and nil if before the
7400 first headline."
7401 (let ((current-level (org-current-level))
7402 (prev-level (when (> (line-number-at-pos) 1)
7403 (save-excursion
7404 (beginning-of-line 0)
7405 (org-current-level)))))
7406 (cond ((null current-level) nil) ; Before first headline
7407 ((null prev-level) 0) ; At first headline
7408 (prev-level))))
7410 (defun org-reduced-level (l)
7411 "Compute the effective level of a heading.
7412 This takes into account the setting of `org-odd-levels-only'."
7413 (cond
7414 ((zerop l) 0)
7415 (org-odd-levels-only (1+ (floor (/ l 2))))
7416 (t l)))
7418 (defun org-level-increment ()
7419 "Return the number of stars that will be added or removed at a
7420 time to headlines when structure editing, based on the value of
7421 `org-odd-levels-only'."
7422 (if org-odd-levels-only 2 1))
7424 (defun org-get-valid-level (level &optional change)
7425 "Rectify a level change under the influence of `org-odd-levels-only'
7426 LEVEL is a current level, CHANGE is by how much the level should be
7427 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7428 even level numbers will become the next higher odd number."
7429 (if org-odd-levels-only
7430 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7431 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7432 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7433 (max 1 (+ level (or change 0)))))
7435 (if (boundp 'define-obsolete-function-alias)
7436 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7437 (define-obsolete-function-alias 'org-get-legal-level
7438 'org-get-valid-level)
7439 (define-obsolete-function-alias 'org-get-legal-level
7440 'org-get-valid-level "23.1")))
7442 (defun org-promote ()
7443 "Promote the current heading higher up the tree.
7444 If the region is active in `transient-mark-mode', promote all headings
7445 in the region."
7446 (org-back-to-heading t)
7447 (let* ((level (save-match-data (funcall outline-level)))
7448 (after-change-functions (remove 'flyspell-after-change-function
7449 after-change-functions))
7450 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7451 (diff (abs (- level (length up-head) -1))))
7452 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7453 (replace-match up-head nil t)
7454 ;; Fixup tag positioning
7455 (and org-auto-align-tags (org-set-tags nil t))
7456 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7457 (run-hooks 'org-after-promote-entry-hook)))
7459 (defun org-demote ()
7460 "Demote the current heading lower down the tree.
7461 If the region is active in `transient-mark-mode', demote all headings
7462 in the region."
7463 (org-back-to-heading t)
7464 (let* ((level (save-match-data (funcall outline-level)))
7465 (after-change-functions (remove 'flyspell-after-change-function
7466 after-change-functions))
7467 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7468 (diff (abs (- level (length down-head) -1))))
7469 (replace-match down-head nil t)
7470 ;; Fixup tag positioning
7471 (and org-auto-align-tags (org-set-tags nil t))
7472 (if org-adapt-indentation (org-fixup-indentation diff))
7473 (run-hooks 'org-after-demote-entry-hook)))
7475 (defun org-cycle-level ()
7476 "Cycle the level of an empty headline through possible states.
7477 This goes first to child, then to parent, level, then up the hierarchy.
7478 After top level, it switches back to sibling level."
7479 (interactive)
7480 (let ((org-adapt-indentation nil))
7481 (when (org-point-at-end-of-empty-headline)
7482 (setq this-command 'org-cycle-level) ; Only needed for caching
7483 (let ((cur-level (org-current-level))
7484 (prev-level (org-get-previous-line-level)))
7485 (cond
7486 ;; If first headline in file, promote to top-level.
7487 ((= prev-level 0)
7488 (loop repeat (/ (- cur-level 1) (org-level-increment))
7489 do (org-do-promote)))
7490 ;; If same level as prev, demote one.
7491 ((= prev-level cur-level)
7492 (org-do-demote))
7493 ;; If parent is top-level, promote to top level if not already.
7494 ((= prev-level 1)
7495 (loop repeat (/ (- cur-level 1) (org-level-increment))
7496 do (org-do-promote)))
7497 ;; If top-level, return to prev-level.
7498 ((= cur-level 1)
7499 (loop repeat (/ (- prev-level 1) (org-level-increment))
7500 do (org-do-demote)))
7501 ;; If less than prev-level, promote one.
7502 ((< cur-level prev-level)
7503 (org-do-promote))
7504 ;; If deeper than prev-level, promote until higher than
7505 ;; prev-level.
7506 ((> cur-level prev-level)
7507 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7508 do (org-do-promote))))
7509 t))))
7511 (defun org-map-tree (fun)
7512 "Call FUN for every heading underneath the current one."
7513 (org-back-to-heading)
7514 (let ((level (funcall outline-level)))
7515 (save-excursion
7516 (funcall fun)
7517 (while (and (progn
7518 (outline-next-heading)
7519 (> (funcall outline-level) level))
7520 (not (eobp)))
7521 (funcall fun)))))
7523 (defun org-map-region (fun beg end)
7524 "Call FUN for every heading between BEG and END."
7525 (let ((org-ignore-region t))
7526 (save-excursion
7527 (setq end (copy-marker end))
7528 (goto-char beg)
7529 (if (and (re-search-forward org-outline-regexp-bol nil t)
7530 (< (point) end))
7531 (funcall fun))
7532 (while (and (progn
7533 (outline-next-heading)
7534 (< (point) end))
7535 (not (eobp)))
7536 (funcall fun)))))
7538 (defvar org-property-end-re) ; silence byte-compiler
7539 (defun org-fixup-indentation (diff)
7540 "Change the indentation in the current entry by DIFF.
7541 However, if any line in the current entry has no indentation, or if it
7542 would end up with no indentation after the change, nothing at all is done."
7543 (save-excursion
7544 (let ((end (save-excursion (outline-next-heading)
7545 (point-marker)))
7546 (prohibit (if (> diff 0)
7547 "^\\S-"
7548 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7549 col)
7550 (unless (save-excursion (end-of-line 1)
7551 (re-search-forward prohibit end t))
7552 (while (and (< (point) end)
7553 (re-search-forward "^[ \t]+" end t))
7554 (goto-char (match-end 0))
7555 (setq col (current-column))
7556 (if (< diff 0) (replace-match ""))
7557 (org-indent-to-column (+ diff col))))
7558 (move-marker end nil))))
7560 (defun org-convert-to-odd-levels ()
7561 "Convert an org-mode file with all levels allowed to one with odd levels.
7562 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7563 level 5 etc."
7564 (interactive)
7565 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7566 (let ((outline-level 'org-outline-level)
7567 (org-odd-levels-only nil) n)
7568 (save-excursion
7569 (goto-char (point-min))
7570 (while (re-search-forward "^\\*\\*+ " nil t)
7571 (setq n (- (length (match-string 0)) 2))
7572 (while (>= (setq n (1- n)) 0)
7573 (org-demote))
7574 (end-of-line 1))))))
7576 (defun org-convert-to-oddeven-levels ()
7577 "Convert an org-mode file with only odd levels to one with odd/even levels.
7578 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7579 file contains a section with an even level, conversion would
7580 destroy the structure of the file. An error is signaled in this
7581 case."
7582 (interactive)
7583 (goto-char (point-min))
7584 ;; First check if there are no even levels
7585 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7586 (org-show-context t)
7587 (error "Not all levels are odd in this file. Conversion not possible"))
7588 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7589 (let ((outline-regexp org-outline-regexp)
7590 (outline-level 'org-outline-level)
7591 (org-odd-levels-only nil) n)
7592 (save-excursion
7593 (goto-char (point-min))
7594 (while (re-search-forward "^\\*\\*+ " nil t)
7595 (setq n (/ (1- (length (match-string 0))) 2))
7596 (while (>= (setq n (1- n)) 0)
7597 (org-promote))
7598 (end-of-line 1))))))
7600 (defun org-tr-level (n)
7601 "Make N odd if required."
7602 (if org-odd-levels-only (1+ (/ n 2)) n))
7604 ;;; Vertical tree motion, cutting and pasting of subtrees
7606 (defun org-move-subtree-up (&optional arg)
7607 "Move the current subtree up past ARG headlines of the same level."
7608 (interactive "p")
7609 (org-move-subtree-down (- (prefix-numeric-value arg))))
7611 (defun org-move-subtree-down (&optional arg)
7612 "Move the current subtree down past ARG headlines of the same level."
7613 (interactive "p")
7614 (setq arg (prefix-numeric-value arg))
7615 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7616 'org-get-last-sibling))
7617 (ins-point (make-marker))
7618 (cnt (abs arg))
7619 (col (current-column))
7620 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7621 ;; Select the tree
7622 (org-back-to-heading)
7623 (setq beg0 (point))
7624 (save-excursion
7625 (setq ne-beg (org-back-over-empty-lines))
7626 (setq beg (point)))
7627 (save-match-data
7628 (save-excursion (outline-end-of-heading)
7629 (setq folded (outline-invisible-p)))
7630 (outline-end-of-subtree))
7631 (outline-next-heading)
7632 (setq ne-end (org-back-over-empty-lines))
7633 (setq end (point))
7634 (goto-char beg0)
7635 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7636 ;; include less whitespace
7637 (save-excursion
7638 (goto-char beg)
7639 (forward-line (- ne-beg ne-end))
7640 (setq beg (point))))
7641 ;; Find insertion point, with error handling
7642 (while (> cnt 0)
7643 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7644 (progn (goto-char beg0)
7645 (error "Cannot move past superior level or buffer limit")))
7646 (setq cnt (1- cnt)))
7647 (if (> arg 0)
7648 ;; Moving forward - still need to move over subtree
7649 (progn (org-end-of-subtree t t)
7650 (save-excursion
7651 (org-back-over-empty-lines)
7652 (or (bolp) (newline)))))
7653 (setq ne-ins (org-back-over-empty-lines))
7654 (move-marker ins-point (point))
7655 (setq txt (buffer-substring beg end))
7656 (org-save-markers-in-region beg end)
7657 (delete-region beg end)
7658 (org-remove-empty-overlays-at beg)
7659 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7660 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7661 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7662 (let ((bbb (point)))
7663 (insert-before-markers txt)
7664 (org-reinstall-markers-in-region bbb)
7665 (move-marker ins-point bbb))
7666 (or (bolp) (insert "\n"))
7667 (setq ins-end (point))
7668 (goto-char ins-point)
7669 (org-skip-whitespace)
7670 (when (and (< arg 0)
7671 (org-first-sibling-p)
7672 (> ne-ins ne-beg))
7673 ;; Move whitespace back to beginning
7674 (save-excursion
7675 (goto-char ins-end)
7676 (let ((kill-whole-line t))
7677 (kill-line (- ne-ins ne-beg)) (point)))
7678 (insert (make-string (- ne-ins ne-beg) ?\n)))
7679 (move-marker ins-point nil)
7680 (if folded
7681 (hide-subtree)
7682 (org-show-entry)
7683 (show-children)
7684 (org-cycle-hide-drawers 'children))
7685 (org-clean-visibility-after-subtree-move)
7686 ;; move back to the initial column we were at
7687 (move-to-column col)))
7689 (defvar org-subtree-clip ""
7690 "Clipboard for cut and paste of subtrees.
7691 This is actually only a copy of the kill, because we use the normal kill
7692 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7694 (defvar org-subtree-clip-folded nil
7695 "Was the last copied subtree folded?
7696 This is used to fold the tree back after pasting.")
7698 (defun org-cut-subtree (&optional n)
7699 "Cut the current subtree into the clipboard.
7700 With prefix arg N, cut this many sequential subtrees.
7701 This is a short-hand for marking the subtree and then cutting it."
7702 (interactive "p")
7703 (org-copy-subtree n 'cut))
7705 (defun org-copy-subtree (&optional n cut force-store-markers)
7706 "Cut the current subtree into the clipboard.
7707 With prefix arg N, cut this many sequential subtrees.
7708 This is a short-hand for marking the subtree and then copying it.
7709 If CUT is non-nil, actually cut the subtree.
7710 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7711 of some markers in the region, even if CUT is non-nil. This is
7712 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7713 (interactive "p")
7714 (let (beg end folded (beg0 (point)))
7715 (if (org-called-interactively-p 'any)
7716 (org-back-to-heading nil) ; take what looks like a subtree
7717 (org-back-to-heading t)) ; take what is really there
7718 (org-back-over-empty-lines)
7719 (setq beg (point))
7720 (skip-chars-forward " \t\r\n")
7721 (save-match-data
7722 (save-excursion (outline-end-of-heading)
7723 (setq folded (outline-invisible-p)))
7724 (condition-case nil
7725 (org-forward-same-level (1- n) t)
7726 (error nil))
7727 (org-end-of-subtree t t))
7728 (org-back-over-empty-lines)
7729 (setq end (point))
7730 (goto-char beg0)
7731 (when (> end beg)
7732 (setq org-subtree-clip-folded folded)
7733 (when (or cut force-store-markers)
7734 (org-save-markers-in-region beg end))
7735 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7736 (setq org-subtree-clip (current-kill 0))
7737 (message "%s: Subtree(s) with %d characters"
7738 (if cut "Cut" "Copied")
7739 (length org-subtree-clip)))))
7741 (defun org-paste-subtree (&optional level tree for-yank)
7742 "Paste the clipboard as a subtree, with modification of headline level.
7743 The entire subtree is promoted or demoted in order to match a new headline
7744 level.
7746 If the cursor is at the beginning of a headline, the same level as
7747 that headline is used to paste the tree
7749 If not, the new level is derived from the *visible* headings
7750 before and after the insertion point, and taken to be the inferior headline
7751 level of the two. So if the previous visible heading is level 3 and the
7752 next is level 4 (or vice versa), level 4 will be used for insertion.
7753 This makes sure that the subtree remains an independent subtree and does
7754 not swallow low level entries.
7756 You can also force a different level, either by using a numeric prefix
7757 argument, or by inserting the heading marker by hand. For example, if the
7758 cursor is after \"*****\", then the tree will be shifted to level 5.
7760 If optional TREE is given, use this text instead of the kill ring.
7762 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7763 move back over whitespace before inserting, and move point to the end of
7764 the inserted text when done."
7765 (interactive "P")
7766 (setq tree (or tree (and kill-ring (current-kill 0))))
7767 (unless (org-kill-is-subtree-p tree)
7768 (error "%s"
7769 (substitute-command-keys
7770 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7771 (org-with-limited-levels
7772 (let* ((visp (not (outline-invisible-p)))
7773 (txt tree)
7774 (^re_ "\\(\\*+\\)[ \t]*")
7775 (old-level (if (string-match org-outline-regexp-bol txt)
7776 (- (match-end 0) (match-beginning 0) 1)
7777 -1))
7778 (force-level (cond (level (prefix-numeric-value level))
7779 ((and (looking-at "[ \t]*$")
7780 (string-match
7781 "^\\*+$" (buffer-substring
7782 (point-at-bol) (point))))
7783 (- (match-end 1) (match-beginning 1)))
7784 ((and (bolp)
7785 (looking-at org-outline-regexp))
7786 (- (match-end 0) (point) 1))
7787 (t nil)))
7788 (previous-level (save-excursion
7789 (condition-case nil
7790 (progn
7791 (outline-previous-visible-heading 1)
7792 (if (looking-at ^re_)
7793 (- (match-end 0) (match-beginning 0) 1)
7795 (error 1))))
7796 (next-level (save-excursion
7797 (condition-case nil
7798 (progn
7799 (or (looking-at org-outline-regexp)
7800 (outline-next-visible-heading 1))
7801 (if (looking-at ^re_)
7802 (- (match-end 0) (match-beginning 0) 1)
7804 (error 1))))
7805 (new-level (or force-level (max previous-level next-level)))
7806 (shift (if (or (= old-level -1)
7807 (= new-level -1)
7808 (= old-level new-level))
7810 (- new-level old-level)))
7811 (delta (if (> shift 0) -1 1))
7812 (func (if (> shift 0) 'org-demote 'org-promote))
7813 (org-odd-levels-only nil)
7814 beg end newend)
7815 ;; Remove the forced level indicator
7816 (if force-level
7817 (delete-region (point-at-bol) (point)))
7818 ;; Paste
7819 (beginning-of-line (if (bolp) 1 2))
7820 (unless for-yank (org-back-over-empty-lines))
7821 (setq beg (point))
7822 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7823 (insert-before-markers txt)
7824 (unless (string-match "\n\\'" txt) (insert "\n"))
7825 (setq newend (point))
7826 (org-reinstall-markers-in-region beg)
7827 (setq end (point))
7828 (goto-char beg)
7829 (skip-chars-forward " \t\n\r")
7830 (setq beg (point))
7831 (if (and (outline-invisible-p) visp)
7832 (save-excursion (outline-show-heading)))
7833 ;; Shift if necessary
7834 (unless (= shift 0)
7835 (save-restriction
7836 (narrow-to-region beg end)
7837 (while (not (= shift 0))
7838 (org-map-region func (point-min) (point-max))
7839 (setq shift (+ delta shift)))
7840 (goto-char (point-min))
7841 (setq newend (point-max))))
7842 (when (or (org-called-interactively-p 'interactive) for-yank)
7843 (message "Clipboard pasted as level %d subtree" new-level))
7844 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7845 kill-ring
7846 (eq org-subtree-clip (current-kill 0))
7847 org-subtree-clip-folded)
7848 ;; The tree was folded before it was killed/copied
7849 (hide-subtree))
7850 (and for-yank (goto-char newend)))))
7852 (defun org-kill-is-subtree-p (&optional txt)
7853 "Check if the current kill is an outline subtree, or a set of trees.
7854 Returns nil if kill does not start with a headline, or if the first
7855 headline level is not the largest headline level in the tree.
7856 So this will actually accept several entries of equal levels as well,
7857 which is OK for `org-paste-subtree'.
7858 If optional TXT is given, check this string instead of the current kill."
7859 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7860 (re (org-get-limited-outline-regexp))
7861 (^re (concat "^" re))
7862 (start-level (and kill
7863 (string-match
7864 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7865 kill)
7866 (- (match-end 2) (match-beginning 2) 1)))
7867 (start (1+ (or (match-beginning 2) -1))))
7868 (if (not start-level)
7869 (progn
7870 nil) ;; does not even start with a heading
7871 (catch 'exit
7872 (while (setq start (string-match ^re kill (1+ start)))
7873 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7874 (throw 'exit nil)))
7875 t))))
7877 (defvar org-markers-to-move nil
7878 "Markers that should be moved with a cut-and-paste operation.
7879 Those markers are stored together with their positions relative to
7880 the start of the region.")
7882 (defun org-save-markers-in-region (beg end)
7883 "Check markers in region.
7884 If these markers are between BEG and END, record their position relative
7885 to BEG, so that after moving the block of text, we can put the markers back
7886 into place.
7887 This function gets called just before an entry or tree gets cut from the
7888 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7889 called immediately, to move the markers with the entries."
7890 (setq org-markers-to-move nil)
7891 (when (featurep 'org-clock)
7892 (org-clock-save-markers-for-cut-and-paste beg end))
7893 (when (featurep 'org-agenda)
7894 (org-agenda-save-markers-for-cut-and-paste beg end)))
7896 (defun org-check-and-save-marker (marker beg end)
7897 "Check if MARKER is between BEG and END.
7898 If yes, remember the marker and the distance to BEG."
7899 (when (and (marker-buffer marker)
7900 (equal (marker-buffer marker) (current-buffer)))
7901 (if (and (>= marker beg) (< marker end))
7902 (push (cons marker (- marker beg)) org-markers-to-move))))
7904 (defun org-reinstall-markers-in-region (beg)
7905 "Move all remembered markers to their position relative to BEG."
7906 (mapc (lambda (x)
7907 (move-marker (car x) (+ beg (cdr x))))
7908 org-markers-to-move)
7909 (setq org-markers-to-move nil))
7911 (defun org-narrow-to-subtree ()
7912 "Narrow buffer to the current subtree."
7913 (interactive)
7914 (save-excursion
7915 (save-match-data
7916 (org-with-limited-levels
7917 (narrow-to-region
7918 (progn (org-back-to-heading t) (point))
7919 (progn (org-end-of-subtree t t)
7920 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7921 (point)))))))
7923 (defun org-narrow-to-block ()
7924 "Narrow buffer to the current block."
7925 (interactive)
7926 (let* ((case-fold-search t)
7927 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7928 "^[ \t]*#\\+end_.*")))
7929 (if blockp
7930 (narrow-to-region (car blockp) (cdr blockp))
7931 (error "Not in a block"))))
7933 (eval-when-compile
7934 (defvar org-property-drawer-re))
7936 (defvar org-property-start-re) ;; defined below
7937 (defun org-clone-subtree-with-time-shift (n &optional shift)
7938 "Clone the task (subtree) at point N times.
7939 The clones will be inserted as siblings.
7941 In interactive use, the user will be prompted for the number of
7942 clones to be produced, and for a time SHIFT, which may be a
7943 repeater as used in time stamps, for example `+3d'.
7945 When a valid repeater is given and the entry contains any time
7946 stamps, the clones will become a sequence in time, with time
7947 stamps in the subtree shifted for each clone produced. If SHIFT
7948 is nil or the empty string, time stamps will be left alone. The
7949 ID property of the original subtree is removed.
7951 If the original subtree did contain time stamps with a repeater,
7952 the following will happen:
7953 - the repeater will be removed in each clone
7954 - an additional clone will be produced, with the current, unshifted
7955 date(s) in the entry.
7956 - the original entry will be placed *after* all the clones, with
7957 repeater intact.
7958 - the start days in the repeater in the original entry will be shifted
7959 to past the last clone.
7960 In this way you can spell out a number of instances of a repeating task,
7961 and still retain the repeater to cover future instances of the task."
7962 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7963 (let (beg end template task idprop
7964 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7965 (drawer-re org-drawer-regexp))
7966 (if (not (and (integerp n) (> n 0)))
7967 (error "Invalid number of replications %s" n))
7968 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7969 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7970 shift)))
7971 (error "Invalid shift specification %s" shift))
7972 (when doshift
7973 (setq shift-n (string-to-number (match-string 1 shift))
7974 shift-what (cdr (assoc (match-string 2 shift)
7975 '(("d" . day) ("w" . week)
7976 ("m" . month) ("y" . year))))))
7977 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7978 (setq nmin 1 nmax n)
7979 (org-back-to-heading t)
7980 (setq beg (point))
7981 (setq idprop (org-entry-get nil "ID"))
7982 (org-end-of-subtree t t)
7983 (or (bolp) (insert "\n"))
7984 (setq end (point))
7985 (setq template (buffer-substring beg end))
7986 (when (and doshift
7987 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7988 (delete-region beg end)
7989 (setq end beg)
7990 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7991 (goto-char end)
7992 (loop for n from nmin to nmax do
7993 ;; prepare clone
7994 (with-temp-buffer
7995 (insert template)
7996 (org-mode)
7997 (goto-char (point-min))
7998 (org-show-subtree)
7999 (and idprop (if org-clone-delete-id
8000 (org-entry-delete nil "ID")
8001 (org-id-get-create t)))
8002 (unless (= n 0)
8003 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8004 (kill-whole-line))
8005 (goto-char (point-min))
8006 (while (re-search-forward drawer-re nil t)
8007 (mapc (lambda (d)
8008 (org-remove-empty-drawer-at d (point))) org-drawers)))
8009 (goto-char (point-min))
8010 (when doshift
8011 (while (re-search-forward org-ts-regexp-both nil t)
8012 (org-timestamp-change (* n shift-n) shift-what))
8013 (unless (= n n-no-remove)
8014 (goto-char (point-min))
8015 (while (re-search-forward org-ts-regexp nil t)
8016 (save-excursion
8017 (goto-char (match-beginning 0))
8018 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8019 (delete-region (match-beginning 1) (match-end 1)))))))
8020 (setq task (buffer-string)))
8021 (insert task))
8022 (goto-char beg)))
8024 ;;; Outline Sorting
8026 (defun org-sort (with-case)
8027 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8028 Optional argument WITH-CASE means sort case-sensitively."
8029 (interactive "P")
8030 (cond
8031 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8032 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8034 (org-call-with-arg 'org-sort-entries with-case))))
8036 (defun org-sort-remove-invisible (s)
8037 (remove-text-properties 0 (length s) org-rm-props s)
8038 (while (string-match org-bracket-link-regexp s)
8039 (setq s (replace-match (if (match-end 2)
8040 (match-string 3 s)
8041 (match-string 1 s)) t t s)))
8044 (defvar org-priority-regexp) ; defined later in the file
8046 (defvar org-after-sorting-entries-or-items-hook nil
8047 "Hook that is run after a bunch of entries or items have been sorted.
8048 When children are sorted, the cursor is in the parent line when this
8049 hook gets called. When a region or a plain list is sorted, the cursor
8050 will be in the first entry of the sorted region/list.")
8052 (defun org-sort-entries
8053 (&optional with-case sorting-type getkey-func compare-func property)
8054 "Sort entries on a certain level of an outline tree.
8055 If there is an active region, the entries in the region are sorted.
8056 Else, if the cursor is before the first entry, sort the top-level items.
8057 Else, the children of the entry at point are sorted.
8059 Sorting can be alphabetically, numerically, by date/time as given by
8060 a time stamp, by a property or by priority.
8062 The command prompts for the sorting type unless it has been given to the
8063 function through the SORTING-TYPE argument, which needs to be a character,
8064 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8065 precise meaning of each character:
8067 n Numerically, by converting the beginning of the entry/item to a number.
8068 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8069 t By date/time, either the first active time stamp in the entry, or, if
8070 none exist, by the first inactive one.
8071 s By the scheduled date/time.
8072 d By deadline date/time.
8073 c By creation time, which is assumed to be the first inactive time stamp
8074 at the beginning of a line.
8075 p By priority according to the cookie.
8076 r By the value of a property.
8078 Capital letters will reverse the sort order.
8080 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8081 called with point at the beginning of the record. It must return either
8082 a string or a number that should serve as the sorting key for that record.
8084 Comparing entries ignores case by default. However, with an optional argument
8085 WITH-CASE, the sorting considers case as well."
8086 (interactive "P")
8087 (let ((case-func (if with-case 'identity 'downcase))
8088 start beg end stars re re2
8089 txt what tmp)
8090 ;; Find beginning and end of region to sort
8091 (cond
8092 ((org-region-active-p)
8093 ;; we will sort the region
8094 (setq end (region-end)
8095 what "region")
8096 (goto-char (region-beginning))
8097 (if (not (org-at-heading-p)) (outline-next-heading))
8098 (setq start (point)))
8099 ((or (org-at-heading-p)
8100 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8101 ;; we will sort the children of the current headline
8102 (org-back-to-heading)
8103 (setq start (point)
8104 end (progn (org-end-of-subtree t t)
8105 (or (bolp) (insert "\n"))
8106 (org-back-over-empty-lines)
8107 (point))
8108 what "children")
8109 (goto-char start)
8110 (show-subtree)
8111 (outline-next-heading))
8113 ;; we will sort the top-level entries in this file
8114 (goto-char (point-min))
8115 (or (org-at-heading-p) (outline-next-heading))
8116 (setq start (point))
8117 (goto-char (point-max))
8118 (beginning-of-line 1)
8119 (when (looking-at ".*?\\S-")
8120 ;; File ends in a non-white line
8121 (end-of-line 1)
8122 (insert "\n"))
8123 (setq end (point-max))
8124 (setq what "top-level")
8125 (goto-char start)
8126 (show-all)))
8128 (setq beg (point))
8129 (if (>= beg end) (error "Nothing to sort"))
8131 (looking-at "\\(\\*+\\)")
8132 (setq stars (match-string 1)
8133 re (concat "^" (regexp-quote stars) " +")
8134 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8135 txt (buffer-substring beg end))
8136 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8137 (if (and (not (equal stars "*")) (string-match re2 txt))
8138 (error "Region to sort contains a level above the first entry"))
8140 (unless sorting-type
8141 (message
8142 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8143 [t]ime [s]cheduled [d]eadline [c]reated
8144 A/N/T/S/D/C/P/O/F means reversed:"
8145 what)
8146 (setq sorting-type (read-char-exclusive))
8148 (and (= (downcase sorting-type) ?f)
8149 (setq getkey-func
8150 (org-icompleting-read "Sort using function: "
8151 obarray 'fboundp t nil nil))
8152 (setq getkey-func (intern getkey-func)))
8154 (and (= (downcase sorting-type) ?r)
8155 (setq property
8156 (org-icompleting-read "Property: "
8157 (mapcar 'list (org-buffer-property-keys t))
8158 nil t))))
8160 (message "Sorting entries...")
8162 (save-restriction
8163 (narrow-to-region start end)
8164 (let ((dcst (downcase sorting-type))
8165 (case-fold-search nil)
8166 (now (current-time)))
8167 (sort-subr
8168 (/= dcst sorting-type)
8169 ;; This function moves to the beginning character of the "record" to
8170 ;; be sorted.
8171 (lambda nil
8172 (if (re-search-forward re nil t)
8173 (goto-char (match-beginning 0))
8174 (goto-char (point-max))))
8175 ;; This function moves to the last character of the "record" being
8176 ;; sorted.
8177 (lambda nil
8178 (save-match-data
8179 (condition-case nil
8180 (outline-forward-same-level 1)
8181 (error
8182 (goto-char (point-max))))))
8183 ;; This function returns the value that gets sorted against.
8184 (lambda nil
8185 (cond
8186 ((= dcst ?n)
8187 (if (looking-at org-complex-heading-regexp)
8188 (string-to-number (match-string 4))
8189 nil))
8190 ((= dcst ?a)
8191 (if (looking-at org-complex-heading-regexp)
8192 (funcall case-func (match-string 4))
8193 nil))
8194 ((= dcst ?t)
8195 (let ((end (save-excursion (outline-next-heading) (point))))
8196 (if (or (re-search-forward org-ts-regexp end t)
8197 (re-search-forward org-ts-regexp-both end t))
8198 (org-time-string-to-seconds (match-string 0))
8199 (org-float-time now))))
8200 ((= dcst ?c)
8201 (let ((end (save-excursion (outline-next-heading) (point))))
8202 (if (re-search-forward
8203 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8204 end t)
8205 (org-time-string-to-seconds (match-string 0))
8206 (org-float-time now))))
8207 ((= dcst ?s)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (re-search-forward org-scheduled-time-regexp end t)
8210 (org-time-string-to-seconds (match-string 1))
8211 (org-float-time now))))
8212 ((= dcst ?d)
8213 (let ((end (save-excursion (outline-next-heading) (point))))
8214 (if (re-search-forward org-deadline-time-regexp end t)
8215 (org-time-string-to-seconds (match-string 1))
8216 (org-float-time now))))
8217 ((= dcst ?p)
8218 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8219 (string-to-char (match-string 2))
8220 org-default-priority))
8221 ((= dcst ?r)
8222 (or (org-entry-get nil property) ""))
8223 ((= dcst ?o)
8224 (if (looking-at org-complex-heading-regexp)
8225 (- 9999 (length (member (match-string 2)
8226 org-todo-keywords-1)))))
8227 ((= dcst ?f)
8228 (if getkey-func
8229 (progn
8230 (setq tmp (funcall getkey-func))
8231 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8232 tmp)
8233 (error "Invalid key function `%s'" getkey-func)))
8234 (t (error "Invalid sorting type `%c'" sorting-type))))
8236 (cond
8237 ((= dcst ?a) 'string<)
8238 ((= dcst ?f) compare-func)
8239 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8240 (t nil)))))
8241 (run-hooks 'org-after-sorting-entries-or-items-hook)
8242 (message "Sorting entries...done")))
8244 (defun org-do-sort (table what &optional with-case sorting-type)
8245 "Sort TABLE of WHAT according to SORTING-TYPE.
8246 The user will be prompted for the SORTING-TYPE if the call to this
8247 function does not specify it. WHAT is only for the prompt, to indicate
8248 what is being sorted. The sorting key will be extracted from
8249 the car of the elements of the table.
8250 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8251 (unless sorting-type
8252 (message
8253 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8254 what)
8255 (setq sorting-type (read-char-exclusive)))
8256 (let ((dcst (downcase sorting-type))
8257 extractfun comparefun)
8258 ;; Define the appropriate functions
8259 (cond
8260 ((= dcst ?n)
8261 (setq extractfun 'string-to-number
8262 comparefun (if (= dcst sorting-type) '< '>)))
8263 ((= dcst ?a)
8264 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8265 (lambda(x) (downcase (org-sort-remove-invisible x))))
8266 comparefun (if (= dcst sorting-type)
8267 'string<
8268 (lambda (a b) (and (not (string< a b))
8269 (not (string= a b)))))))
8270 ((= dcst ?t)
8271 (setq extractfun
8272 (lambda (x)
8273 (if (or (string-match org-ts-regexp x)
8274 (string-match org-ts-regexp-both x))
8275 (org-float-time
8276 (org-time-string-to-time (match-string 0 x)))
8278 comparefun (if (= dcst sorting-type) '< '>)))
8279 (t (error "Invalid sorting type `%c'" sorting-type)))
8281 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8282 table)
8283 (lambda (a b) (funcall comparefun (car a) (car b))))))
8286 ;;; The orgstruct minor mode
8288 ;; Define a minor mode which can be used in other modes in order to
8289 ;; integrate the org-mode structure editing commands.
8291 ;; This is really a hack, because the org-mode structure commands use
8292 ;; keys which normally belong to the major mode. Here is how it
8293 ;; works: The minor mode defines all the keys necessary to operate the
8294 ;; structure commands, but wraps the commands into a function which
8295 ;; tests if the cursor is currently at a headline or a plain list
8296 ;; item. If that is the case, the structure command is used,
8297 ;; temporarily setting many Org-mode variables like regular
8298 ;; expressions for filling etc. However, when any of those keys is
8299 ;; used at a different location, function uses `key-binding' to look
8300 ;; up if the key has an associated command in another currently active
8301 ;; keymap (minor modes, major mode, global), and executes that
8302 ;; command. There might be problems if any of the keys is otherwise
8303 ;; used as a prefix key.
8305 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8306 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8307 ;; addresses this by checking explicitly for both bindings.
8309 (defvar orgstruct-mode-map (make-sparse-keymap)
8310 "Keymap for the minor `orgstruct-mode'.")
8312 (defvar org-local-vars nil
8313 "List of local variables, for use by `orgstruct-mode'.")
8315 ;;;###autoload
8316 (define-minor-mode orgstruct-mode
8317 "Toggle the minor mode `orgstruct-mode'.
8318 This mode is for using Org-mode structure commands in other
8319 modes. The following keys behave as if Org-mode were active, if
8320 the cursor is on a headline, or on a plain list item (both as
8321 defined by Org-mode).
8323 M-up Move entry/item up
8324 M-down Move entry/item down
8325 M-left Promote
8326 M-right Demote
8327 M-S-up Move entry/item up
8328 M-S-down Move entry/item down
8329 M-S-left Promote subtree
8330 M-S-right Demote subtree
8331 M-q Fill paragraph and items like in Org-mode
8332 C-c ^ Sort entries
8333 C-c - Cycle list bullet
8334 TAB Cycle item visibility
8335 M-RET Insert new heading/item
8336 S-M-RET Insert new TODO heading / Checkbox item
8337 C-c C-c Set tags / toggle checkbox"
8338 nil " OrgStruct" nil
8339 (org-load-modules-maybe)
8340 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8342 ;;;###autoload
8343 (defun turn-on-orgstruct ()
8344 "Unconditionally turn on `orgstruct-mode'."
8345 (orgstruct-mode 1))
8347 (defun orgstruct++-mode (&optional arg)
8348 "Toggle `orgstruct-mode', the enhanced version of it.
8349 In addition to setting orgstruct-mode, this also exports all indentation
8350 and autofilling variables from org-mode into the buffer. It will also
8351 recognize item context in multiline items.
8352 Note that turning off orgstruct-mode will *not* remove the
8353 indentation/paragraph settings. This can only be done by refreshing the
8354 major mode, for example with \\[normal-mode]."
8355 (interactive "P")
8356 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8357 (if (< arg 1)
8358 (orgstruct-mode -1)
8359 (orgstruct-mode 1)
8360 (let (var val)
8361 (mapc
8362 (lambda (x)
8363 (when (string-match
8364 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8365 (symbol-name (car x)))
8366 (setq var (car x) val (nth 1 x))
8367 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8368 org-local-vars)
8369 (org-set-local 'orgstruct-is-++ t))))
8371 (defvar orgstruct-is-++ nil
8372 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8373 (make-variable-buffer-local 'orgstruct-is-++)
8375 ;;;###autoload
8376 (defun turn-on-orgstruct++ ()
8377 "Unconditionally turn on `orgstruct++-mode'."
8378 (orgstruct++-mode 1))
8380 (defun orgstruct-error ()
8381 "Error when there is no default binding for a structure key."
8382 (interactive)
8383 (error "This key has no function outside structure elements"))
8385 (defun orgstruct-setup ()
8386 "Setup orgstruct keymaps."
8387 (let ((nfunc 0)
8388 (bindings
8389 (list
8390 '([(meta up)] org-metaup)
8391 '([(meta down)] org-metadown)
8392 '([(meta left)] org-metaleft)
8393 '([(meta right)] org-metaright)
8394 '([(meta shift up)] org-shiftmetaup)
8395 '([(meta shift down)] org-shiftmetadown)
8396 '([(meta shift left)] org-shiftmetaleft)
8397 '([(meta shift right)] org-shiftmetaright)
8398 '([?\e (up)] org-metaup)
8399 '([?\e (down)] org-metadown)
8400 '([?\e (left)] org-metaleft)
8401 '([?\e (right)] org-metaright)
8402 '([?\e (shift up)] org-shiftmetaup)
8403 '([?\e (shift down)] org-shiftmetadown)
8404 '([?\e (shift left)] org-shiftmetaleft)
8405 '([?\e (shift right)] org-shiftmetaright)
8406 '([(shift up)] org-shiftup)
8407 '([(shift down)] org-shiftdown)
8408 '([(shift left)] org-shiftleft)
8409 '([(shift right)] org-shiftright)
8410 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8411 '("\M-q" fill-paragraph)
8412 '("\C-c^" org-sort)
8413 '("\C-c-" org-cycle-list-bullet)))
8414 elt key fun cmd)
8415 (while (setq elt (pop bindings))
8416 (setq nfunc (1+ nfunc))
8417 (setq key (org-key (car elt))
8418 fun (nth 1 elt)
8419 cmd (orgstruct-make-binding fun nfunc key))
8420 (org-defkey orgstruct-mode-map key cmd))
8422 ;; Special treatment needed for TAB and RET
8423 (org-defkey orgstruct-mode-map [(tab)]
8424 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8425 (org-defkey orgstruct-mode-map "\C-i"
8426 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8428 (org-defkey orgstruct-mode-map "\M-\C-m"
8429 (orgstruct-make-binding 'org-insert-heading 105
8430 "\M-\C-m" [(meta return)]))
8431 (org-defkey orgstruct-mode-map [(meta return)]
8432 (orgstruct-make-binding 'org-insert-heading 106
8433 [(meta return)] "\M-\C-m"))
8435 (org-defkey orgstruct-mode-map [(shift meta return)]
8436 (orgstruct-make-binding 'org-insert-todo-heading 107
8437 [(meta return)] "\M-\C-m"))
8439 (org-defkey orgstruct-mode-map "\e\C-m"
8440 (orgstruct-make-binding 'org-insert-heading 108
8441 "\e\C-m" [?\e (return)]))
8442 (org-defkey orgstruct-mode-map [?\e (return)]
8443 (orgstruct-make-binding 'org-insert-heading 109
8444 [?\e (return)] "\e\C-m"))
8445 (org-defkey orgstruct-mode-map [?\e (shift return)]
8446 (orgstruct-make-binding 'org-insert-todo-heading 110
8447 [?\e (return)] "\e\C-m"))
8449 (unless org-local-vars
8450 (setq org-local-vars (org-get-local-variables)))
8454 (defun orgstruct-make-binding (fun n &rest keys)
8455 "Create a function for binding in the structure minor mode.
8456 FUN is the command to call inside a table. N is used to create a unique
8457 command name. KEYS are keys that should be checked in for a command
8458 to execute outside of tables."
8459 (eval
8460 (list 'defun
8461 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8462 '(arg)
8463 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8464 "Outside of structure, run the binding of `"
8465 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8466 "'.")
8467 '(interactive "p")
8468 (list 'if
8469 `(org-context-p 'headline 'item
8470 (and orgstruct-is-++
8471 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8472 'item-body))
8473 (list 'org-run-like-in-org-mode (list 'quote fun))
8474 (list 'let '(orgstruct-mode)
8475 (list 'call-interactively
8476 (append '(or)
8477 (mapcar (lambda (k)
8478 (list 'key-binding k))
8479 keys)
8480 '('orgstruct-error))))))))
8482 (defun org-context-p (&rest contexts)
8483 "Check if local context is any of CONTEXTS.
8484 Possible values in the list of contexts are `table', `headline', and `item'."
8485 (let ((pos (point)))
8486 (goto-char (point-at-bol))
8487 (prog1 (or (and (memq 'table contexts)
8488 (looking-at "[ \t]*|"))
8489 (and (memq 'headline contexts)
8490 (looking-at org-outline-regexp))
8491 (and (memq 'item contexts)
8492 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8493 (and (memq 'item-body contexts)
8494 (org-in-item-p)))
8495 (goto-char pos))))
8497 (defun org-get-local-variables ()
8498 "Return a list of all local variables in an org-mode buffer."
8499 (let (varlist)
8500 (with-current-buffer (get-buffer-create "*Org tmp*")
8501 (erase-buffer)
8502 (org-mode)
8503 (setq varlist (buffer-local-variables)))
8504 (kill-buffer "*Org tmp*")
8505 (delq nil
8506 (mapcar
8507 (lambda (x)
8508 (setq x
8509 (if (symbolp x)
8510 (list x)
8511 (list (car x) (list 'quote (cdr x)))))
8512 (if (string-match
8513 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8514 (symbol-name (car x)))
8515 x nil))
8516 varlist))))
8518 (defun org-clone-local-variables (from-buffer &optional regexp)
8519 "Clone local variables from FROM-BUFFER.
8520 Optional argument REGEXP selects variables to clone."
8521 (mapc
8522 (lambda (pair)
8523 (and (symbolp (car pair))
8524 (or (null regexp)
8525 (string-match regexp (symbol-name (car pair))))
8526 (set (make-local-variable (car pair))
8527 (cdr pair))))
8528 (buffer-local-variables from-buffer)))
8530 ;;;###autoload
8531 (defun org-run-like-in-org-mode (cmd)
8532 "Run a command, pretending that the current buffer is in Org-mode.
8533 This will temporarily bind local variables that are typically bound in
8534 Org-mode to the values they have in Org-mode, and then interactively
8535 call CMD."
8536 (org-load-modules-maybe)
8537 (unless org-local-vars
8538 (setq org-local-vars (org-get-local-variables)))
8539 (eval (list 'let org-local-vars
8540 (list 'call-interactively (list 'quote cmd)))))
8542 ;;;; Archiving
8544 (defun org-get-category (&optional pos force-refresh)
8545 "Get the category applying to position POS."
8546 (save-match-data
8547 (if force-refresh (org-refresh-category-properties))
8548 (let ((pos (or pos (point))))
8549 (or (get-text-property pos 'org-category)
8550 (progn (org-refresh-category-properties)
8551 (get-text-property pos 'org-category))))))
8553 (defun org-refresh-category-properties ()
8554 "Refresh category text properties in the buffer."
8555 (let ((def-cat (cond
8556 ((null org-category)
8557 (if buffer-file-name
8558 (file-name-sans-extension
8559 (file-name-nondirectory buffer-file-name))
8560 "???"))
8561 ((symbolp org-category) (symbol-name org-category))
8562 (t org-category)))
8563 beg end cat pos optionp)
8564 (org-unmodified
8565 (save-excursion
8566 (save-restriction
8567 (widen)
8568 (goto-char (point-min))
8569 (put-text-property (point) (point-max) 'org-category def-cat)
8570 (while (re-search-forward
8571 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8572 (setq pos (match-end 0)
8573 optionp (equal (char-after (match-beginning 0)) ?#)
8574 cat (org-trim (match-string 2)))
8575 (if optionp
8576 (setq beg (point-at-bol) end (point-max))
8577 (org-back-to-heading t)
8578 (setq beg (point) end (org-end-of-subtree t t)))
8579 (put-text-property beg end 'org-category cat)
8580 (put-text-property beg end 'org-category-position beg)
8581 (goto-char pos)))))))
8584 ;;;; Link Stuff
8586 ;;; Link abbreviations
8588 (defun org-link-expand-abbrev (link)
8589 "Apply replacements as defined in `org-link-abbrev-alist."
8590 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8591 (let* ((key (match-string 1 link))
8592 (as (or (assoc key org-link-abbrev-alist-local)
8593 (assoc key org-link-abbrev-alist)))
8594 (tag (and (match-end 2) (match-string 3 link)))
8595 rpl)
8596 (if (not as)
8597 link
8598 (setq rpl (cdr as))
8599 (cond
8600 ((symbolp rpl) (funcall rpl tag))
8601 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8602 ((string-match "%h" rpl)
8603 (replace-match (url-hexify-string (or tag "")) t t rpl))
8604 (t (concat rpl tag)))))
8605 link))
8607 ;;; Storing and inserting links
8609 (defvar org-insert-link-history nil
8610 "Minibuffer history for links inserted with `org-insert-link'.")
8612 (defvar org-stored-links nil
8613 "Contains the links stored with `org-store-link'.")
8615 (defvar org-store-link-plist nil
8616 "Plist with info about the most recently link created with `org-store-link'.")
8618 (defvar org-link-protocols nil
8619 "Link protocols added to Org-mode using `org-add-link-type'.")
8621 (defvar org-store-link-functions nil
8622 "List of functions that are called to create and store a link.
8623 Each function will be called in turn until one returns a non-nil
8624 value. Each function should check if it is responsible for creating
8625 this link (for example by looking at the major mode).
8626 If not, it must exit and return nil.
8627 If yes, it should return a non-nil value after a calling
8628 `org-store-link-props' with a list of properties and values.
8629 Special properties are:
8631 :type The link prefix, like \"http\". This must be given.
8632 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8633 This is obligatory as well.
8634 :description Optional default description for the second pair
8635 of brackets in an Org-mode link. The user can still change
8636 this when inserting this link into an Org-mode buffer.
8638 In addition to these, any additional properties can be specified
8639 and then used in remember templates.")
8641 (defun org-add-link-type (type &optional follow export)
8642 "Add TYPE to the list of `org-link-types'.
8643 Re-compute all regular expressions depending on `org-link-types'
8645 FOLLOW and EXPORT are two functions.
8647 FOLLOW should take the link path as the single argument and do whatever
8648 is necessary to follow the link, for example find a file or display
8649 a mail message.
8651 EXPORT should format the link path for export to one of the export formats.
8652 It should be a function accepting three arguments:
8654 path the path of the link, the text after the prefix (like \"http:\")
8655 desc the description of the link, if any, or a description added by
8656 org-export-normalize-links if there is none
8657 format the export format, a symbol like `html' or `latex' or `ascii'..
8659 The function may use the FORMAT information to return different values
8660 depending on the format. The return value will be put literally into
8661 the exported file. If the return value is nil, this means Org should
8662 do what it normally does with links which do not have EXPORT defined.
8664 Org-mode has a built-in default for exporting links. If you are happy with
8665 this default, there is no need to define an export function for the link
8666 type. For a simple example of an export function, see `org-bbdb.el'."
8667 (add-to-list 'org-link-types type t)
8668 (org-make-link-regexps)
8669 (if (assoc type org-link-protocols)
8670 (setcdr (assoc type org-link-protocols) (list follow export))
8671 (push (list type follow export) org-link-protocols)))
8673 (defvar org-agenda-buffer-name)
8675 ;;;###autoload
8676 (defun org-store-link (arg)
8677 "\\<org-mode-map>Store an org-link to the current location.
8678 This link is added to `org-stored-links' and can later be inserted
8679 into an org-buffer with \\[org-insert-link].
8681 For some link types, a prefix arg is interpreted:
8682 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8683 For file links, arg negates `org-context-in-file-links'."
8684 (interactive "P")
8685 (org-load-modules-maybe)
8686 (setq org-store-link-plist nil) ; reset
8687 (org-with-limited-levels
8688 (let (link cpltxt desc description search txt custom-id agenda-link)
8689 (cond
8691 ((run-hook-with-args-until-success 'org-store-link-functions)
8692 (setq link (plist-get org-store-link-plist :link)
8693 desc (or (plist-get org-store-link-plist :description) link)))
8695 ((org-src-edit-buffer-p)
8696 (let (label gc)
8697 (while (or (not label)
8698 (save-excursion
8699 (save-restriction
8700 (widen)
8701 (goto-char (point-min))
8702 (re-search-forward
8703 (regexp-quote (format org-coderef-label-format label))
8704 nil t))))
8705 (when label (message "Label exists already") (sit-for 2))
8706 (setq label (read-string "Code line label: " label)))
8707 (end-of-line 1)
8708 (setq link (format org-coderef-label-format label))
8709 (setq gc (- 79 (length link)))
8710 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8711 (insert link)
8712 (setq link (concat "(" label ")") desc nil)))
8714 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8715 ;; We are in the agenda, link to referenced location
8716 (let ((m (or (get-text-property (point) 'org-hd-marker)
8717 (get-text-property (point) 'org-marker))))
8718 (when m
8719 (org-with-point-at m
8720 (setq agenda-link
8721 (if (org-called-interactively-p 'any)
8722 (call-interactively 'org-store-link)
8723 (org-store-link nil)))))))
8725 ((eq major-mode 'calendar-mode)
8726 (let ((cd (calendar-cursor-to-date)))
8727 (setq link
8728 (format-time-string
8729 (car org-time-stamp-formats)
8730 (apply 'encode-time
8731 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8732 nil nil nil))))
8733 (org-store-link-props :type "calendar" :date cd)))
8735 ((eq major-mode 'w3-mode)
8736 (setq cpltxt (if (and (buffer-name)
8737 (not (string-match "Untitled" (buffer-name))))
8738 (buffer-name)
8739 (url-view-url t))
8740 link (org-make-link (url-view-url t)))
8741 (org-store-link-props :type "w3" :url (url-view-url t)))
8743 ((eq major-mode 'w3m-mode)
8744 (setq cpltxt (or w3m-current-title w3m-current-url)
8745 link (org-make-link w3m-current-url))
8746 (org-store-link-props :type "w3m" :url (url-view-url t)))
8748 ((setq search (run-hook-with-args-until-success
8749 'org-create-file-search-functions))
8750 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8751 "::" search))
8752 (setq cpltxt (or description link)))
8754 ((eq major-mode 'image-mode)
8755 (setq cpltxt (concat "file:"
8756 (abbreviate-file-name buffer-file-name))
8757 link (org-make-link cpltxt))
8758 (org-store-link-props :type "image" :file buffer-file-name))
8760 ((eq major-mode 'dired-mode)
8761 ;; link to the file in the current line
8762 (let ((file (dired-get-filename nil t)))
8763 (setq file (if file
8764 (abbreviate-file-name
8765 (expand-file-name (dired-get-filename nil t)))
8766 ;; otherwise, no file so use current directory.
8767 default-directory))
8768 (setq cpltxt (concat "file:" file)
8769 link (org-make-link cpltxt))))
8771 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8772 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8773 (cond
8774 ((org-in-regexp "<<\\(.*?\\)>>")
8775 (setq cpltxt
8776 (concat "file:"
8777 (abbreviate-file-name
8778 (buffer-file-name (buffer-base-buffer)))
8779 "::" (match-string 1))
8780 link (org-make-link cpltxt)))
8781 ((and (featurep 'org-id)
8782 (or (eq org-link-to-org-use-id t)
8783 (and (eq org-link-to-org-use-id 'create-if-interactive)
8784 (org-called-interactively-p 'any))
8785 (and (eq org-link-to-org-use-id
8786 'create-if-interactive-and-no-custom-id)
8787 (org-called-interactively-p 'any)
8788 (not custom-id))
8789 (and org-link-to-org-use-id
8790 (org-entry-get nil "ID"))))
8791 ;; We can make a link using the ID.
8792 (setq link (condition-case nil
8793 (prog1 (org-id-store-link)
8794 (setq desc (plist-get org-store-link-plist
8795 :description)))
8796 (error
8797 ;; probably before first headline, link to file only
8798 (concat "file:"
8799 (abbreviate-file-name
8800 (buffer-file-name (buffer-base-buffer))))))))
8802 ;; Just link to current headline
8803 (setq cpltxt (concat "file:"
8804 (abbreviate-file-name
8805 (buffer-file-name (buffer-base-buffer)))))
8806 ;; Add a context search string
8807 (when (org-xor org-context-in-file-links arg)
8808 (setq txt (cond
8809 ((org-at-heading-p) nil)
8810 ((org-region-active-p)
8811 (buffer-substring (region-beginning) (region-end)))
8812 (t nil)))
8813 (when (or (null txt) (string-match "\\S-" txt))
8814 (setq cpltxt
8815 (concat cpltxt "::"
8816 (condition-case nil
8817 (org-make-org-heading-search-string txt)
8818 (error "")))
8819 desc (or (nth 4 (ignore-errors
8820 (org-heading-components))) "NONE"))))
8821 (if (string-match "::\\'" cpltxt)
8822 (setq cpltxt (substring cpltxt 0 -2)))
8823 (setq link (org-make-link cpltxt)))))
8825 ((buffer-file-name (buffer-base-buffer))
8826 ;; Just link to this file here.
8827 (setq cpltxt (concat "file:"
8828 (abbreviate-file-name
8829 (buffer-file-name (buffer-base-buffer)))))
8830 ;; Add a context string
8831 (when (org-xor org-context-in-file-links arg)
8832 (setq txt (if (org-region-active-p)
8833 (buffer-substring (region-beginning) (region-end))
8834 (buffer-substring (point-at-bol) (point-at-eol))))
8835 ;; Only use search option if there is some text.
8836 (when (string-match "\\S-" txt)
8837 (setq cpltxt
8838 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8839 desc "NONE")))
8840 (setq link (org-make-link cpltxt)))
8842 ((org-called-interactively-p 'interactive)
8843 (error "Cannot link to a buffer which is not visiting a file"))
8845 (t (setq link nil)))
8847 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8848 (setq link (or link cpltxt)
8849 desc (or desc cpltxt))
8850 (if (equal desc "NONE") (setq desc nil))
8852 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8853 (progn
8854 (setq org-stored-links
8855 (cons (list link desc) org-stored-links))
8856 (message "Stored: %s" (or desc link))
8857 (when custom-id
8858 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8859 "::#" custom-id))
8860 (setq org-stored-links
8861 (cons (list link desc) org-stored-links))))
8862 (or agenda-link (and link (org-make-link-string link desc)))))))
8864 (defun org-store-link-props (&rest plist)
8865 "Store link properties, extract names and addresses."
8866 (let (x adr)
8867 (when (setq x (plist-get plist :from))
8868 (setq adr (mail-extract-address-components x))
8869 (setq plist (plist-put plist :fromname (car adr)))
8870 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8871 (when (setq x (plist-get plist :to))
8872 (setq adr (mail-extract-address-components x))
8873 (setq plist (plist-put plist :toname (car adr)))
8874 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8875 (let ((from (plist-get plist :from))
8876 (to (plist-get plist :to)))
8877 (when (and from to org-from-is-user-regexp)
8878 (setq plist
8879 (plist-put plist :fromto
8880 (if (string-match org-from-is-user-regexp from)
8881 (concat "to %t")
8882 (concat "from %f"))))))
8883 (setq org-store-link-plist plist))
8885 (defun org-add-link-props (&rest plist)
8886 "Add these properties to the link property list."
8887 (let (key value)
8888 (while plist
8889 (setq key (pop plist) value (pop plist))
8890 (setq org-store-link-plist
8891 (plist-put org-store-link-plist key value)))))
8893 (defun org-email-link-description (&optional fmt)
8894 "Return the description part of an email link.
8895 This takes information from `org-store-link-plist' and formats it
8896 according to FMT (default from `org-email-link-description-format')."
8897 (setq fmt (or fmt org-email-link-description-format))
8898 (let* ((p org-store-link-plist)
8899 (to (plist-get p :toaddress))
8900 (from (plist-get p :fromaddress))
8901 (table
8902 (list
8903 (cons "%c" (plist-get p :fromto))
8904 (cons "%F" (plist-get p :from))
8905 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8906 (cons "%T" (plist-get p :to))
8907 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8908 (cons "%s" (plist-get p :subject))
8909 (cons "%d" (plist-get p :date))
8910 (cons "%m" (plist-get p :message-id)))))
8911 (when (string-match "%c" fmt)
8912 ;; Check if the user wrote this message
8913 (if (and org-from-is-user-regexp from to
8914 (save-match-data (string-match org-from-is-user-regexp from)))
8915 (setq fmt (replace-match "to %t" t t fmt))
8916 (setq fmt (replace-match "from %f" t t fmt))))
8917 (org-replace-escapes fmt table)))
8919 (defun org-make-org-heading-search-string (&optional string heading)
8920 "Make search string for STRING or current headline."
8921 (interactive)
8922 (let ((s (or string (org-get-heading)))
8923 (lines org-context-in-file-links))
8924 (unless (and string (not heading))
8925 ;; We are using a headline, clean up garbage in there.
8926 (if (string-match org-todo-regexp s)
8927 (setq s (replace-match "" t t s)))
8928 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8929 (setq s (replace-match "" t t s)))
8930 (setq s (org-trim s))
8931 (if (string-match (concat "^\\(" org-quote-string "\\|"
8932 org-comment-string "\\)") s)
8933 (setq s (replace-match "" t t s)))
8934 (while (string-match org-ts-regexp s)
8935 (setq s (replace-match "" t t s))))
8936 (or string (setq s (concat "*" s))) ; Add * for headlines
8937 (when (and string (integerp lines) (> lines 0))
8938 (let ((slines (org-split-string s "\n")))
8939 (when (< lines (length slines))
8940 (setq s (mapconcat
8941 'identity
8942 (reverse (nthcdr (- (length slines) lines)
8943 (reverse slines))) "\n")))))
8944 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8946 (defun org-make-link (&rest strings)
8947 "Concatenate STRINGS."
8948 (apply 'concat strings))
8950 (defun org-make-link-string (link &optional description)
8951 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8952 (unless (string-match "\\S-" link)
8953 (error "Empty link"))
8954 (when (and description
8955 (stringp description)
8956 (not (string-match "\\S-" description)))
8957 (setq description nil))
8958 (when (stringp description)
8959 ;; Remove brackets from the description, they are fatal.
8960 (while (string-match "\\[" description)
8961 (setq description (replace-match "{" t t description)))
8962 (while (string-match "\\]" description)
8963 (setq description (replace-match "}" t t description))))
8964 (when (equal link description)
8965 ;; No description needed, it is identical
8966 (setq description nil))
8967 (when (and (not description)
8968 (not (string-match (org-image-file-name-regexp) link))
8969 (not (equal link (org-link-escape link))))
8970 (setq description (org-extract-attributes link)))
8971 (setq link
8972 (cond ((string-match (org-image-file-name-regexp) link) link)
8973 ((string-match org-link-types-re link)
8974 (concat (match-string 1 link)
8975 (org-link-escape (substring link (match-end 1)))))
8976 (t (org-link-escape link))))
8977 (concat "[[" link "]"
8978 (if description (concat "[" description "]") "")
8979 "]"))
8981 (defconst org-link-escape-chars
8982 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8983 "List of characters that should be escaped in link.
8984 This is the list that is used for internal purposes.")
8986 (defvar org-url-encoding-use-url-hexify nil)
8988 (defconst org-link-escape-chars-browser
8989 '(?\ )
8990 "List of escapes for characters that are problematic in links.
8991 This is the list that is used before handing over to the browser.")
8993 (defun org-link-escape (text &optional table merge)
8994 "Return percent escaped representation of TEXT.
8995 TEXT is a string with the text to escape.
8996 Optional argument TABLE is a list with characters that should be
8997 escaped. When nil, `org-link-escape-chars' is used.
8998 If optional argument MERGE is set, merge TABLE into
8999 `org-link-escape-chars'."
9000 (if (and org-url-encoding-use-url-hexify (not table))
9001 (url-hexify-string text)
9002 (cond
9003 ((and table merge)
9004 (mapc (lambda (defchr)
9005 (unless (member defchr table)
9006 (setq table (cons defchr table)))) org-link-escape-chars))
9007 ((null table)
9008 (setq table org-link-escape-chars)))
9009 (mapconcat
9010 (lambda (char)
9011 (if (or (member char table)
9012 (< char 32) (= char 37) (> char 126))
9013 (mapconcat (lambda (sequence-element)
9014 (format "%%%.2X" sequence-element))
9015 (or (encode-coding-char char 'utf-8)
9016 (error "Unable to percent escape character: %s"
9017 (char-to-string char))) "")
9018 (char-to-string char))) text "")))
9020 (defun org-link-unescape (str)
9021 "Unhex hexified Unicode strings as returned from the JavaScript function
9022 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9023 (unless (and (null str) (string= "" str))
9024 (let ((pos 0) (case-fold-search t) unhexed)
9025 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9026 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9027 (setq str (replace-match unhexed t t str))
9028 (setq pos (+ pos (length unhexed))))))
9029 str)
9031 (defun org-link-unescape-compound (hex)
9032 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9033 Note: this function also decodes single byte encodings like
9034 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9035 (save-match-data
9036 (let* ((bytes (cdr (split-string hex "%")))
9037 (ret "")
9038 (eat 0)
9039 (sum 0))
9040 (while bytes
9041 (let* ((val (string-to-number (pop bytes) 16))
9042 (shift-xor
9043 (if (= 0 eat)
9044 (cond
9045 ((>= val 252) (cons 6 252))
9046 ((>= val 248) (cons 5 248))
9047 ((>= val 240) (cons 4 240))
9048 ((>= val 224) (cons 3 224))
9049 ((>= val 192) (cons 2 192))
9050 (t (cons 0 0)))
9051 (cons 6 128))))
9052 (if (>= val 192) (setq eat (car shift-xor)))
9053 (setq val (logxor val (cdr shift-xor)))
9054 (setq sum (+ (lsh sum (car shift-xor)) val))
9055 (if (> eat 0) (setq eat (- eat 1)))
9056 (cond
9057 ((= 0 eat) ;multi byte
9058 (setq ret (concat ret (org-char-to-string sum)))
9059 (setq sum 0))
9060 ((not bytes) ; single byte(s)
9061 (setq ret (org-link-unescape-single-byte-sequence hex))))
9062 )) ;; end (while bytes
9063 ret )))
9065 (defun org-link-unescape-single-byte-sequence (hex)
9066 "Unhexify hex-encoded single byte character sequences."
9067 (mapconcat (lambda (byte)
9068 (char-to-string (string-to-number byte 16)))
9069 (cdr (split-string hex "%")) ""))
9071 (defun org-xor (a b)
9072 "Exclusive or."
9073 (if a (not b) b))
9075 (defun org-fixup-message-id-for-http (s)
9076 "Replace special characters in a message id, so it can be used in an http query."
9077 (when (string-match "%" s)
9078 (setq s (mapconcat (lambda (c)
9079 (if (eq c ?%)
9080 "%25"
9081 (char-to-string c)))
9082 s "")))
9083 (while (string-match "<" s)
9084 (setq s (replace-match "%3C" t t s)))
9085 (while (string-match ">" s)
9086 (setq s (replace-match "%3E" t t s)))
9087 (while (string-match "@" s)
9088 (setq s (replace-match "%40" t t s)))
9091 ;;;###autoload
9092 (defun org-insert-link-global ()
9093 "Insert a link like Org-mode does.
9094 This command can be called in any mode to insert a link in Org-mode syntax."
9095 (interactive)
9096 (org-load-modules-maybe)
9097 (org-run-like-in-org-mode 'org-insert-link))
9099 (defun org-insert-link (&optional complete-file link-location default-description)
9100 "Insert a link. At the prompt, enter the link.
9102 Completion can be used to insert any of the link protocol prefixes like
9103 http or ftp in use.
9105 The history can be used to select a link previously stored with
9106 `org-store-link'. When the empty string is entered (i.e. if you just
9107 press RET at the prompt), the link defaults to the most recently
9108 stored link. As SPC triggers completion in the minibuffer, you need to
9109 use M-SPC or C-q SPC to force the insertion of a space character.
9111 You will also be prompted for a description, and if one is given, it will
9112 be displayed in the buffer instead of the link.
9114 If there is already a link at point, this command will allow you to edit link
9115 and description parts.
9117 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9118 be selected using completion. The path to the file will be relative to the
9119 current directory if the file is in the current directory or a subdirectory.
9120 Otherwise, the link will be the absolute path as completed in the minibuffer
9121 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9122 option `org-link-file-path-type'.
9124 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9125 the current directory or below.
9127 With three \\[universal-argument] prefixes, negate the meaning of
9128 `org-keep-stored-link-after-insertion'.
9130 If `org-make-link-description-function' is non-nil, this function will be
9131 called with the link target, and the result will be the default
9132 link description.
9134 If the LINK-LOCATION parameter is non-nil, this value will be
9135 used as the link location instead of reading one interactively.
9137 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9138 be used as the default description."
9139 (interactive "P")
9140 (let* ((wcf (current-window-configuration))
9141 (region (if (org-region-active-p)
9142 (buffer-substring (region-beginning) (region-end))))
9143 (remove (and region (list (region-beginning) (region-end))))
9144 (desc region)
9145 tmphist ; byte-compile incorrectly complains about this
9146 (link link-location)
9147 entry file all-prefixes)
9148 (cond
9149 (link-location) ; specified by arg, just use it.
9150 ((org-in-regexp org-bracket-link-regexp 1)
9151 ;; We do have a link at point, and we are going to edit it.
9152 (setq remove (list (match-beginning 0) (match-end 0)))
9153 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9154 (setq link (read-string "Link: "
9155 (org-link-unescape
9156 (org-match-string-no-properties 1)))))
9157 ((or (org-in-regexp org-angle-link-re)
9158 (org-in-regexp org-plain-link-re))
9159 ;; Convert to bracket link
9160 (setq remove (list (match-beginning 0) (match-end 0))
9161 link (read-string "Link: "
9162 (org-remove-angle-brackets (match-string 0)))))
9163 ((member complete-file '((4) (16)))
9164 ;; Completing read for file names.
9165 (setq link (org-file-complete-link complete-file)))
9167 ;; Read link, with completion for stored links.
9168 (with-output-to-temp-buffer "*Org Links*"
9169 (princ "Insert a link.
9170 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9171 (when org-stored-links
9172 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9173 (princ (mapconcat
9174 (lambda (x)
9175 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9176 (reverse org-stored-links) "\n"))))
9177 (let ((cw (selected-window)))
9178 (select-window (get-buffer-window "*Org Links*" 'visible))
9179 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9180 (unless (pos-visible-in-window-p (point-max))
9181 (org-fit-window-to-buffer))
9182 (and (window-live-p cw) (select-window cw)))
9183 ;; Fake a link history, containing the stored links.
9184 (setq tmphist (append (mapcar 'car org-stored-links)
9185 org-insert-link-history))
9186 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9187 (mapcar 'car org-link-abbrev-alist)
9188 org-link-types))
9189 (unwind-protect
9190 (progn
9191 (setq link
9192 (let ((org-completion-use-ido nil)
9193 (org-completion-use-iswitchb nil))
9194 (org-completing-read
9195 "Link: "
9196 (append
9197 (mapcar (lambda (x) (list (concat x ":")))
9198 all-prefixes)
9199 (mapcar 'car org-stored-links))
9200 nil nil nil
9201 'tmphist
9202 (car (car org-stored-links)))))
9203 (if (not (string-match "\\S-" link))
9204 (error "No link selected"))
9205 (if (or (member link all-prefixes)
9206 (and (equal ":" (substring link -1))
9207 (member (substring link 0 -1) all-prefixes)
9208 (setq link (substring link 0 -1))))
9209 (setq link (org-link-try-special-completion link))))
9210 (set-window-configuration wcf)
9211 (kill-buffer "*Org Links*"))
9212 (setq entry (assoc link org-stored-links))
9213 (or entry (push link org-insert-link-history))
9214 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9215 (not org-keep-stored-link-after-insertion))
9216 (setq org-stored-links (delq (assoc link org-stored-links)
9217 org-stored-links)))
9218 (setq desc (or desc (nth 1 entry)))))
9220 (if (string-match org-plain-link-re link)
9221 ;; URL-like link, normalize the use of angular brackets.
9222 (setq link (org-make-link (org-remove-angle-brackets link))))
9224 ;; Check if we are linking to the current file with a search option
9225 ;; If yes, simplify the link by using only the search option.
9226 (when (and buffer-file-name
9227 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9228 (let* ((path (match-string 1 link))
9229 (case-fold-search nil)
9230 (search (match-string 2 link)))
9231 (save-match-data
9232 (if (equal (file-truename buffer-file-name) (file-truename path))
9233 ;; We are linking to this same file, with a search option
9234 (setq link search)))))
9236 ;; Check if we can/should use a relative path. If yes, simplify the link
9237 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9238 (let* ((type (match-string 1 link))
9239 (path (match-string 2 link))
9240 (origpath path)
9241 (case-fold-search nil))
9242 (cond
9243 ((or (eq org-link-file-path-type 'absolute)
9244 (equal complete-file '(16)))
9245 (setq path (abbreviate-file-name (expand-file-name path))))
9246 ((eq org-link-file-path-type 'noabbrev)
9247 (setq path (expand-file-name path)))
9248 ((eq org-link-file-path-type 'relative)
9249 (setq path (file-relative-name path)))
9251 (save-match-data
9252 (if (string-match (concat "^" (regexp-quote
9253 (expand-file-name
9254 (file-name-as-directory
9255 default-directory))))
9256 (expand-file-name path))
9257 ;; We are linking a file with relative path name.
9258 (setq path (substring (expand-file-name path)
9259 (match-end 0)))
9260 (setq path (abbreviate-file-name (expand-file-name path)))))))
9261 (setq link (concat type path))
9262 (if (equal desc origpath)
9263 (setq desc path))))
9265 (if org-make-link-description-function
9266 (setq desc (funcall org-make-link-description-function link desc))
9267 (if default-description (setq desc default-description)))
9269 (setq desc (read-string "Description: " desc))
9270 (unless (string-match "\\S-" desc) (setq desc nil))
9271 (if remove (apply 'delete-region remove))
9272 (insert (org-make-link-string link desc))))
9274 (defun org-link-try-special-completion (type)
9275 "If there is completion support for link type TYPE, offer it."
9276 (let ((fun (intern (concat "org-" type "-complete-link"))))
9277 (if (functionp fun)
9278 (funcall fun)
9279 (read-string "Link (no completion support): " (concat type ":")))))
9281 (defun org-file-complete-link (&optional arg)
9282 "Create a file link using completion."
9283 (let (file link)
9284 (setq file (read-file-name "File: "))
9285 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9286 (pwd1 (file-name-as-directory (abbreviate-file-name
9287 (expand-file-name ".")))))
9288 (cond
9289 ((equal arg '(16))
9290 (setq link (org-make-link
9291 "file:"
9292 (abbreviate-file-name (expand-file-name file)))))
9293 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9294 (setq link (org-make-link "file:" (match-string 1 file))))
9295 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9296 (expand-file-name file))
9297 (setq link (org-make-link
9298 "file:" (match-string 1 (expand-file-name file)))))
9299 (t (setq link (org-make-link "file:" file)))))
9300 link))
9302 (defun org-completing-read (&rest args)
9303 "Completing-read with SPACE being a normal character."
9304 (let ((enable-recursive-minibuffers t)
9305 (minibuffer-local-completion-map
9306 (copy-keymap minibuffer-local-completion-map)))
9307 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9308 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9309 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9310 (apply 'org-icompleting-read args)))
9312 (defun org-completing-read-no-i (&rest args)
9313 (let (org-completion-use-ido org-completion-use-iswitchb)
9314 (apply 'org-completing-read args)))
9316 (defun org-iswitchb-completing-read (prompt choices &rest args)
9317 "Use iswitch as a completing-read replacement to choose from choices.
9318 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9319 from."
9320 (let* ((iswitchb-use-virtual-buffers nil)
9321 (iswitchb-make-buflist-hook
9322 (lambda ()
9323 (setq iswitchb-temp-buflist choices))))
9324 (iswitchb-read-buffer prompt)))
9326 (defun org-icompleting-read (&rest args)
9327 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9328 (org-without-partial-completion
9329 (if (and org-completion-use-ido
9330 (fboundp 'ido-completing-read)
9331 (boundp 'ido-mode) ido-mode
9332 (listp (second args)))
9333 (let ((ido-enter-matching-directory nil))
9334 (apply 'ido-completing-read (concat (car args))
9335 (if (consp (car (nth 1 args)))
9336 (mapcar 'car (nth 1 args))
9337 (nth 1 args))
9338 (cddr args)))
9339 (if (and org-completion-use-iswitchb
9340 (boundp 'iswitchb-mode) iswitchb-mode
9341 (listp (second args)))
9342 (apply 'org-iswitchb-completing-read (concat (car args))
9343 (if (consp (car (nth 1 args)))
9344 (mapcar 'car (nth 1 args))
9345 (nth 1 args))
9346 (cddr args))
9347 (apply 'completing-read args)))))
9349 (defun org-extract-attributes (s)
9350 "Extract the attributes cookie from a string and set as text property."
9351 (let (a attr (start 0) key value)
9352 (save-match-data
9353 (when (string-match "{{\\([^}]+\\)}}$" s)
9354 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9355 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9356 (setq key (match-string 1 a) value (match-string 2 a)
9357 start (match-end 0)
9358 attr (plist-put attr (intern key) value))))
9359 (org-add-props s nil 'org-attr attr))
9362 (defun org-extract-attributes-from-string (tag)
9363 (let (key value attr)
9364 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9365 (setq key (match-string 1 tag) value (match-string 2 tag)
9366 tag (replace-match "" t t tag)
9367 attr (plist-put attr (intern key) value)))
9368 (cons tag attr)))
9370 (defun org-attributes-to-string (plist)
9371 "Format a property list into an HTML attribute list."
9372 (let ((s "") key value)
9373 (while plist
9374 (setq key (pop plist) value (pop plist))
9375 (and value
9376 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9379 ;;; Opening/following a link
9381 (defvar org-link-search-failed nil)
9383 (defvar org-open-link-functions nil
9384 "Hook for functions finding a plain text link.
9385 These functions must take a single argument, the link content.
9386 They will be called for links that look like [[link text][description]]
9387 when LINK TEXT does not have a protocol like \"http:\" and does not look
9388 like a filename (e.g. \"./blue.png\").
9390 These functions will be called *before* Org attempts to resolve the
9391 link by doing text searches in the current buffer - so if you want a
9392 link \"[[target]]\" to still find \"<<target>>\", your function should
9393 handle this as a special case.
9395 When the function does handle the link, it must return a non-nil value.
9396 If it decides that it is not responsible for this link, it must return
9397 nil to indicate that that Org-mode can continue with other options
9398 like exact and fuzzy text search.")
9400 (defun org-next-link ()
9401 "Move forward to the next link.
9402 If the link is in hidden text, expose it."
9403 (interactive)
9404 (when (and org-link-search-failed (eq this-command last-command))
9405 (goto-char (point-min))
9406 (message "Link search wrapped back to beginning of buffer"))
9407 (setq org-link-search-failed nil)
9408 (let* ((pos (point))
9409 (ct (org-context))
9410 (a (assoc :link ct)))
9411 (if a (goto-char (nth 2 a)))
9412 (if (re-search-forward org-any-link-re nil t)
9413 (progn
9414 (goto-char (match-beginning 0))
9415 (if (outline-invisible-p) (org-show-context)))
9416 (goto-char pos)
9417 (setq org-link-search-failed t)
9418 (error "No further link found"))))
9420 (defun org-previous-link ()
9421 "Move backward to the previous link.
9422 If the link is in hidden text, expose it."
9423 (interactive)
9424 (when (and org-link-search-failed (eq this-command last-command))
9425 (goto-char (point-max))
9426 (message "Link search wrapped back to end of buffer"))
9427 (setq org-link-search-failed nil)
9428 (let* ((pos (point))
9429 (ct (org-context))
9430 (a (assoc :link ct)))
9431 (if a (goto-char (nth 1 a)))
9432 (if (re-search-backward org-any-link-re nil t)
9433 (progn
9434 (goto-char (match-beginning 0))
9435 (if (outline-invisible-p) (org-show-context)))
9436 (goto-char pos)
9437 (setq org-link-search-failed t)
9438 (error "No further link found"))))
9440 (defun org-translate-link (s)
9441 "Translate a link string if a translation function has been defined."
9442 (if (and org-link-translation-function
9443 (fboundp org-link-translation-function)
9444 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9445 (progn
9446 (setq s (funcall org-link-translation-function
9447 (match-string 1) (match-string 2)))
9448 (concat (car s) ":" (cdr s)))
9451 (defun org-translate-link-from-planner (type path)
9452 "Translate a link from Emacs Planner syntax so that Org can follow it.
9453 This is still an experimental function, your mileage may vary."
9454 (cond
9455 ((member type '("http" "https" "news" "ftp"))
9456 ;; standard Internet links are the same.
9457 nil)
9458 ((and (equal type "irc") (string-match "^//" path))
9459 ;; Planner has two / at the beginning of an irc link, we have 1.
9460 ;; We should have zero, actually....
9461 (setq path (substring path 1)))
9462 ((and (equal type "lisp") (string-match "^/" path))
9463 ;; Planner has a slash, we do not.
9464 (setq type "elisp" path (substring path 1)))
9465 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9466 ;; A typical message link. Planner has the id after the final slash,
9467 ;; we separate it with a hash mark
9468 (setq path (concat (match-string 1 path) "#"
9469 (org-remove-angle-brackets (match-string 2 path)))))
9471 (cons type path))
9473 (defun org-find-file-at-mouse (ev)
9474 "Open file link or URL at mouse."
9475 (interactive "e")
9476 (mouse-set-point ev)
9477 (org-open-at-point 'in-emacs))
9479 (defun org-open-at-mouse (ev)
9480 "Open file link or URL at mouse.
9481 See the docstring of `org-open-file' for details."
9482 (interactive "e")
9483 (mouse-set-point ev)
9484 (if (eq major-mode 'org-agenda-mode)
9485 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9486 (org-open-at-point))
9488 (defvar org-window-config-before-follow-link nil
9489 "The window configuration before following a link.
9490 This is saved in case the need arises to restore it.")
9492 (defvar org-open-link-marker (make-marker)
9493 "Marker pointing to the location where `org-open-at-point; was called.")
9495 ;;;###autoload
9496 (defun org-open-at-point-global ()
9497 "Follow a link like Org-mode does.
9498 This command can be called in any mode to follow a link that has
9499 Org-mode syntax."
9500 (interactive)
9501 (org-run-like-in-org-mode 'org-open-at-point))
9503 ;;;###autoload
9504 (defun org-open-link-from-string (s &optional arg reference-buffer)
9505 "Open a link in the string S, as if it was in Org-mode."
9506 (interactive "sLink: \nP")
9507 (let ((reference-buffer (or reference-buffer (current-buffer))))
9508 (with-temp-buffer
9509 (let ((org-inhibit-startup (not reference-buffer)))
9510 (org-mode)
9511 (insert s)
9512 (goto-char (point-min))
9513 (when reference-buffer
9514 (setq org-link-abbrev-alist-local
9515 (with-current-buffer reference-buffer
9516 org-link-abbrev-alist-local)))
9517 (org-open-at-point arg reference-buffer)))))
9519 (defvar org-open-at-point-functions nil
9520 "Hook that is run when following a link at point.
9522 Functions in this hook must return t if they identify and follow
9523 a link at point. If they don't find anything interesting at point,
9524 they must return nil.")
9526 (defun org-open-at-point (&optional arg reference-buffer)
9527 "Open link at or after point.
9528 If there is no link at point, this function will search forward up to
9529 the end of the current line.
9530 Normally, files will be opened by an appropriate application. If the
9531 optional prefix argument ARG is non-nil, Emacs will visit the file.
9532 With a double prefix argument, try to open outside of Emacs, in the
9533 application the system uses for this file type."
9534 (interactive "P")
9535 ;; if in a code block, then open the block's results
9536 (unless (call-interactively #'org-babel-open-src-block-result)
9537 (org-load-modules-maybe)
9538 (move-marker org-open-link-marker (point))
9539 (setq org-window-config-before-follow-link (current-window-configuration))
9540 (org-remove-occur-highlights nil nil t)
9541 (cond
9542 ((and (org-at-heading-p)
9543 (not (org-in-regexp
9544 (concat org-plain-link-re "\\|"
9545 org-bracket-link-regexp "\\|"
9546 org-angle-link-re "\\|"
9547 "[ \t]:[^ \t\n]+:[ \t]*$")))
9548 (not (get-text-property (point) 'org-linked-text)))
9549 (or (org-offer-links-in-entry arg)
9550 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9551 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9552 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9553 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9554 (not (org-in-regexp org-bracket-link-regexp)))
9555 (org-footnote-action))
9557 (let (type path link line search (pos (point)))
9558 (catch 'match
9559 (save-excursion
9560 (skip-chars-forward "^]\n\r")
9561 (when (org-in-regexp org-bracket-link-regexp 1)
9562 (setq link (org-extract-attributes
9563 (org-link-unescape (org-match-string-no-properties 1))))
9564 (while (string-match " *\n *" link)
9565 (setq link (replace-match " " t t link)))
9566 (setq link (org-link-expand-abbrev link))
9567 (cond
9568 ((or (file-name-absolute-p link)
9569 (string-match "^\\.\\.?/" link))
9570 (setq type "file" path link))
9571 ((string-match org-link-re-with-space3 link)
9572 (setq type (match-string 1 link) path (match-string 2 link)))
9573 (t (setq type "thisfile" path link)))
9574 (throw 'match t)))
9576 (when (get-text-property (point) 'org-linked-text)
9577 (setq type "thisfile"
9578 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9579 (1+ (point)) (point))
9580 path (buffer-substring
9581 (or (previous-single-property-change pos 'org-linked-text)
9582 (point-min))
9583 (or (next-single-property-change pos 'org-linked-text)
9584 (point-max))))
9585 (throw 'match t))
9587 (save-excursion
9588 (when (or (org-in-regexp org-angle-link-re)
9589 (org-in-regexp org-plain-link-re))
9590 (setq type (match-string 1)
9591 path (org-link-unescape (match-string 2)))
9592 (throw 'match t)))
9593 (save-excursion
9594 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9595 (setq type "tags"
9596 path (match-string 1))
9597 (while (string-match ":" path)
9598 (setq path (replace-match "+" t t path)))
9599 (throw 'match t)))
9600 (when (org-in-regexp "<\\([^><\n]+\\)>")
9601 (setq type "tree-match"
9602 path (match-string 1))
9603 (throw 'match t)))
9604 (unless path
9605 (error "No link found"))
9607 ;; switch back to reference buffer
9608 ;; needed when if called in a temporary buffer through
9609 ;; org-open-link-from-string
9610 (with-current-buffer (or reference-buffer (current-buffer))
9612 ;; Remove any trailing spaces in path
9613 (if (string-match " +\\'" path)
9614 (setq path (replace-match "" t t path)))
9615 (if (and org-link-translation-function
9616 (fboundp org-link-translation-function))
9617 ;; Check if we need to translate the link
9618 (let ((tmp (funcall org-link-translation-function type path)))
9619 (setq type (car tmp) path (cdr tmp))))
9621 (cond
9623 ((assoc type org-link-protocols)
9624 (funcall (nth 1 (assoc type org-link-protocols)) path))
9626 ((equal type "mailto")
9627 (let ((cmd (car org-link-mailto-program))
9628 (args (cdr org-link-mailto-program)) args1
9629 (address path) (subject "") a)
9630 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9631 (setq address (match-string 1 path)
9632 subject (org-link-escape (match-string 2 path))))
9633 (while args
9634 (cond
9635 ((not (stringp (car args))) (push (pop args) args1))
9636 (t (setq a (pop args))
9637 (if (string-match "%a" a)
9638 (setq a (replace-match address t t a)))
9639 (if (string-match "%s" a)
9640 (setq a (replace-match subject t t a)))
9641 (push a args1))))
9642 (apply cmd (nreverse args1))))
9644 ((member type '("http" "https" "ftp" "news"))
9645 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9646 (org-link-escape
9647 path org-link-escape-chars-browser)
9648 path))))
9650 ((string= type "doi")
9651 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9652 (org-link-escape
9653 path org-link-escape-chars-browser)
9654 path))))
9656 ((member type '("message"))
9657 (browse-url (concat type ":" path)))
9659 ((string= type "tags")
9660 (org-tags-view arg path))
9662 ((string= type "tree-match")
9663 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9665 ((string= type "file")
9666 (if (string-match "::\\([0-9]+\\)\\'" path)
9667 (setq line (string-to-number (match-string 1 path))
9668 path (substring path 0 (match-beginning 0)))
9669 (if (string-match "::\\(.+\\)\\'" path)
9670 (setq search (match-string 1 path)
9671 path (substring path 0 (match-beginning 0)))))
9672 (if (string-match "[*?{]" (file-name-nondirectory path))
9673 (dired path)
9674 (org-open-file path arg line search)))
9676 ((string= type "shell")
9677 (let ((cmd path))
9678 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9679 (string-match org-confirm-shell-link-not-regexp cmd))
9680 (not org-confirm-shell-link-function)
9681 (funcall org-confirm-shell-link-function
9682 (format "Execute \"%s\" in shell? "
9683 (org-add-props cmd nil
9684 'face 'org-warning))))
9685 (progn
9686 (message "Executing %s" cmd)
9687 (shell-command cmd))
9688 (error "Abort"))))
9690 ((string= type "elisp")
9691 (let ((cmd path))
9692 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9693 (string-match org-confirm-elisp-link-not-regexp cmd))
9694 (not org-confirm-elisp-link-function)
9695 (funcall org-confirm-elisp-link-function
9696 (format "Execute \"%s\" as elisp? "
9697 (org-add-props cmd nil
9698 'face 'org-warning))))
9699 (message "%s => %s" cmd
9700 (if (equal (string-to-char cmd) ?\()
9701 (eval (read cmd))
9702 (call-interactively (read cmd))))
9703 (error "Abort"))))
9705 ((and (string= type "thisfile")
9706 (run-hook-with-args-until-success
9707 'org-open-link-functions path)))
9709 ((string= type "thisfile")
9710 (if arg
9711 (switch-to-buffer-other-window
9712 (org-get-buffer-for-internal-link (current-buffer)))
9713 (org-mark-ring-push))
9714 (let ((cmd `(org-link-search
9715 ,path
9716 ,(cond ((equal arg '(4)) ''occur)
9717 ((equal arg '(16)) ''org-occur)
9718 (t nil))
9719 ,pos)))
9720 (condition-case nil (let ((org-link-search-inhibit-query t))
9721 (eval cmd))
9722 (error (progn (widen) (eval cmd))))))
9725 (browse-url-at-point)))))))
9726 (move-marker org-open-link-marker nil)
9727 (run-hook-with-args 'org-follow-link-hook)))
9729 (defun org-offer-links-in-entry (&optional nth zero)
9730 "Offer links in the current entry and follow the selected link.
9731 If there is only one link, follow it immediately as well.
9732 If NTH is an integer, immediately pick the NTH link found.
9733 If ZERO is a string, check also this string for a link, and if
9734 there is one, offer it as link number zero."
9735 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9736 "\\(" org-angle-link-re "\\)\\|"
9737 "\\(" org-plain-link-re "\\)"))
9738 (cnt ?0)
9739 (in-emacs (if (integerp nth) nil nth))
9740 have-zero end links link c)
9741 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9742 (push (match-string 0 zero) links)
9743 (setq cnt (1- cnt) have-zero t))
9744 (save-excursion
9745 (org-back-to-heading t)
9746 (setq end (save-excursion (outline-next-heading) (point)))
9747 (while (re-search-forward re end t)
9748 (push (match-string 0) links))
9749 (setq links (org-uniquify (reverse links))))
9751 (cond
9752 ((null links)
9753 (message "No links"))
9754 ((equal (length links) 1)
9755 (setq link (list (car links))))
9756 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9757 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9758 (t ; we have to select a link
9759 (save-excursion
9760 (save-window-excursion
9761 (delete-other-windows)
9762 (with-output-to-temp-buffer "*Select Link*"
9763 (mapc (lambda (l)
9764 (if (not (string-match org-bracket-link-regexp l))
9765 (princ (format "[%c] %s\n" (incf cnt)
9766 (org-remove-angle-brackets l)))
9767 (if (match-end 3)
9768 (princ (format "[%c] %s (%s)\n" (incf cnt)
9769 (match-string 3 l) (match-string 1 l)))
9770 (princ (format "[%c] %s\n" (incf cnt)
9771 (match-string 1 l))))))
9772 links))
9773 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9774 (message "Select link to open, RET to open all:")
9775 (setq c (read-char-exclusive))
9776 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9777 (when (equal c ?q) (error "Abort"))
9778 (if (equal c ?\C-m)
9779 (setq link links)
9780 (setq nth (- c ?0))
9781 (if have-zero (setq nth (1+ nth)))
9782 (unless (and (integerp nth) (>= (length links) nth))
9783 (error "Invalid link selection"))
9784 (setq link (list (nth (1- nth) links))))))
9785 (if link
9786 (let ((buf (current-buffer)))
9787 (dolist (l link)
9788 (org-open-link-from-string l in-emacs buf))
9790 nil)))
9792 ;; Add special file links that specify the way of opening
9794 (org-add-link-type "file+sys" 'org-open-file-with-system)
9795 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9796 (defun org-open-file-with-system (path)
9797 "Open file at PATH using the system way of opening it."
9798 (org-open-file path 'system))
9799 (defun org-open-file-with-emacs (path)
9800 "Open file at PATH in Emacs."
9801 (org-open-file path 'emacs))
9802 (defun org-remove-file-link-modifiers ()
9803 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9804 (goto-char (point-min))
9805 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9806 (org-if-unprotected
9807 (replace-match "file:" t t))))
9808 (eval-after-load "org-exp"
9809 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9810 'org-remove-file-link-modifiers))
9812 ;;;; Time estimates
9814 (defun org-get-effort (&optional pom)
9815 "Get the effort estimate for the current entry."
9816 (org-entry-get pom org-effort-property))
9818 ;;; File search
9820 (defvar org-create-file-search-functions nil
9821 "List of functions to construct the right search string for a file link.
9822 These functions are called in turn with point at the location to
9823 which the link should point.
9825 A function in the hook should first test if it would like to
9826 handle this file type, for example by checking the `major-mode'
9827 or the file extension. If it decides not to handle this file, it
9828 should just return nil to give other functions a chance. If it
9829 does handle the file, it must return the search string to be used
9830 when following the link. The search string will be part of the
9831 file link, given after a double colon, and `org-open-at-point'
9832 will automatically search for it. If special measures must be
9833 taken to make the search successful, another function should be
9834 added to the companion hook `org-execute-file-search-functions',
9835 which see.
9837 A function in this hook may also use `setq' to set the variable
9838 `description' to provide a suggestion for the descriptive text to
9839 be used for this link when it gets inserted into an Org-mode
9840 buffer with \\[org-insert-link].")
9842 (defvar org-execute-file-search-functions nil
9843 "List of functions to execute a file search triggered by a link.
9845 Functions added to this hook must accept a single argument, the
9846 search string that was part of the file link, the part after the
9847 double colon. The function must first check if it would like to
9848 handle this search, for example by checking the `major-mode' or
9849 the file extension. If it decides not to handle this search, it
9850 should just return nil to give other functions a chance. If it
9851 does handle the search, it must return a non-nil value to keep
9852 other functions from trying.
9854 Each function can access the current prefix argument through the
9855 variable `current-prefix-argument'. Note that a single prefix is
9856 used to force opening a link in Emacs, so it may be good to only
9857 use a numeric or double prefix to guide the search function.
9859 In case this is needed, a function in this hook can also restore
9860 the window configuration before `org-open-at-point' was called using:
9862 (set-window-configuration org-window-config-before-follow-link)")
9864 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9865 (defun org-link-search (s &optional type avoid-pos stealth)
9866 "Search for a link search option.
9867 If S is surrounded by forward slashes, it is interpreted as a
9868 regular expression. In org-mode files, this will create an `org-occur'
9869 sparse tree. In ordinary files, `occur' will be used to list matches.
9870 If the current buffer is in `dired-mode', grep will be used to search
9871 in all files. If AVOID-POS is given, ignore matches near that position.
9873 When optional argument STEALTH is non-nil, do not modify
9874 visibility around point, thus ignoring
9875 `org-show-hierarchy-above', `org-show-following-heading' and
9876 `org-show-siblings' variables."
9877 (let ((case-fold-search t)
9878 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9879 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9880 (append '(("") (" ") ("\t") ("\n"))
9881 org-emphasis-alist)
9882 "\\|") "\\)"))
9883 (pos (point))
9884 (pre nil) (post nil)
9885 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9886 (cond
9887 ;; First check if there are any special search functions
9888 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9889 ;; Now try the builtin stuff
9890 ((and (equal (string-to-char s0) ?#)
9891 (> (length s0) 1)
9892 (save-excursion
9893 (goto-char (point-min))
9894 (and
9895 (re-search-forward
9896 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9897 (setq type 'dedicated
9898 pos (match-beginning 0))))
9899 ;; There is an exact target for this
9900 (goto-char pos)
9901 (org-back-to-heading t)))
9902 ((save-excursion
9903 (goto-char (point-min))
9904 (and
9905 (re-search-forward
9906 (concat "<<" (regexp-quote s0) ">>") nil t)
9907 (setq type 'dedicated
9908 pos (match-beginning 0))))
9909 ;; There is an exact target for this
9910 (goto-char pos))
9911 ((save-excursion
9912 (goto-char (point-min))
9913 (and
9914 (re-search-forward
9915 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9916 (setq type 'dedicated pos (match-beginning 0))))
9917 ;; Found an invisible target.
9918 (goto-char pos))
9919 ((save-excursion
9920 (goto-char (point-min))
9921 (and
9922 (re-search-forward
9923 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9924 (setq type 'dedicated pos (match-beginning 0))))
9925 ;; Found an element with a matching #+name affiliated keyword.
9926 (goto-char pos))
9927 ((and (string-match "^(\\(.*\\))$" s0)
9928 (save-excursion
9929 (goto-char (point-min))
9930 (and
9931 (re-search-forward
9932 (concat "[^[]" (regexp-quote
9933 (format org-coderef-label-format
9934 (match-string 1 s0))))
9935 nil t)
9936 (setq type 'dedicated
9937 pos (1+ (match-beginning 0))))))
9938 ;; There is a coderef target for this
9939 (goto-char pos))
9940 ((string-match "^/\\(.*\\)/$" s)
9941 ;; A regular expression
9942 (cond
9943 ((eq major-mode 'org-mode)
9944 (org-occur (match-string 1 s)))
9945 ;;((eq major-mode 'dired-mode)
9946 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9947 (t (org-do-occur (match-string 1 s)))))
9948 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9949 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9950 (goto-char (point-min))
9951 (cond
9952 ((let (case-fold-search)
9953 (re-search-forward (format org-complex-heading-regexp-format
9954 (regexp-quote s))
9955 nil t))
9956 ;; OK, found a match
9957 (setq type 'dedicated)
9958 (goto-char (match-beginning 0)))
9959 ((and (not org-link-search-inhibit-query)
9960 (eq org-link-search-must-match-exact-headline 'query-to-create)
9961 (y-or-n-p "No match - create this as a new heading? "))
9962 (goto-char (point-max))
9963 (or (bolp) (newline))
9964 (insert "* " s "\n")
9965 (beginning-of-line 0))
9967 (goto-char pos)
9968 (error "No match"))))
9970 ;; A normal search string
9971 (when (equal (string-to-char s) ?*)
9972 ;; Anchor on headlines, post may include tags.
9973 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9974 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9975 s (substring s 1)))
9976 (remove-text-properties
9977 0 (length s)
9978 '(face nil mouse-face nil keymap nil fontified nil) s)
9979 ;; Make a series of regular expressions to find a match
9980 (setq words (org-split-string s "[ \n\r\t]+")
9982 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9983 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9984 "\\)" markers)
9985 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9986 re2a (concat "[ \t\r\n]" re2a_)
9987 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9988 re4 (concat "[^a-zA-Z_]" re4_)
9990 re1 (concat pre re2 post)
9991 re3 (concat pre (if pre re4_ re4) post)
9992 re5 (concat pre ".*" re4)
9993 re2 (concat pre re2)
9994 re2a (concat pre (if pre re2a_ re2a))
9995 re4 (concat pre (if pre re4_ re4))
9996 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9997 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9998 re5 "\\)"
10000 (cond
10001 ((eq type 'org-occur) (org-occur reall))
10002 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10003 (t (goto-char (point-min))
10004 (setq type 'fuzzy)
10005 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10006 (org-search-not-self 1 re1 nil t)
10007 (org-search-not-self 1 re2 nil t)
10008 (org-search-not-self 1 re2a nil t)
10009 (org-search-not-self 1 re3 nil t)
10010 (org-search-not-self 1 re4 nil t)
10011 (org-search-not-self 1 re5 nil t)
10013 (goto-char (match-beginning 1))
10014 (goto-char pos)
10015 (error "No match"))))))
10016 (and (eq major-mode 'org-mode)
10017 (not stealth)
10018 (org-show-context 'link-search))
10019 type))
10021 (defun org-search-not-self (group &rest args)
10022 "Execute `re-search-forward', but only accept matches that do not
10023 enclose the position of `org-open-link-marker'."
10024 (let ((m org-open-link-marker))
10025 (catch 'exit
10026 (while (apply 're-search-forward args)
10027 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10028 (goto-char (match-end group))
10029 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10030 (> (match-beginning 0) (marker-position m))
10031 (< (match-end 0) (marker-position m)))
10032 (save-match-data
10033 (or (not (org-in-regexp
10034 org-bracket-link-analytic-regexp 1))
10035 (not (match-end 4)) ; no description
10036 (and (<= (match-beginning 4) (point))
10037 (>= (match-end 4) (point))))))
10038 (throw 'exit (point))))))))
10040 (defun org-get-buffer-for-internal-link (buffer)
10041 "Return a buffer to be used for displaying the link target of internal links."
10042 (cond
10043 ((not org-display-internal-link-with-indirect-buffer)
10044 buffer)
10045 ((string-match "(Clone)$" (buffer-name buffer))
10046 (message "Buffer is already a clone, not making another one")
10047 ;; we also do not modify visibility in this case
10048 buffer)
10049 (t ; make a new indirect buffer for displaying the link
10050 (let* ((bn (buffer-name buffer))
10051 (ibn (concat bn "(Clone)"))
10052 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10053 (with-current-buffer ib (org-overview))
10054 ib))))
10056 (defun org-do-occur (regexp &optional cleanup)
10057 "Call the Emacs command `occur'.
10058 If CLEANUP is non-nil, remove the printout of the regular expression
10059 in the *Occur* buffer. This is useful if the regex is long and not useful
10060 to read."
10061 (occur regexp)
10062 (when cleanup
10063 (let ((cwin (selected-window)) win beg end)
10064 (when (setq win (get-buffer-window "*Occur*"))
10065 (select-window win))
10066 (goto-char (point-min))
10067 (when (re-search-forward "match[a-z]+" nil t)
10068 (setq beg (match-end 0))
10069 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10070 (setq end (1- (match-beginning 0)))))
10071 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10072 (goto-char (point-min))
10073 (select-window cwin))))
10075 ;;; The mark ring for links jumps
10077 (defvar org-mark-ring nil
10078 "Mark ring for positions before jumps in Org-mode.")
10079 (defvar org-mark-ring-last-goto nil
10080 "Last position in the mark ring used to go back.")
10081 ;; Fill and close the ring
10082 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10083 (loop for i from 1 to org-mark-ring-length do
10084 (push (make-marker) org-mark-ring))
10085 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10086 org-mark-ring)
10088 (defun org-mark-ring-push (&optional pos buffer)
10089 "Put the current position or POS into the mark ring and rotate it."
10090 (interactive)
10091 (setq pos (or pos (point)))
10092 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10093 (move-marker (car org-mark-ring)
10094 (or pos (point))
10095 (or buffer (current-buffer)))
10096 (message "%s"
10097 (substitute-command-keys
10098 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10100 (defun org-mark-ring-goto (&optional n)
10101 "Jump to the previous position in the mark ring.
10102 With prefix arg N, jump back that many stored positions. When
10103 called several times in succession, walk through the entire ring.
10104 Org-mode commands jumping to a different position in the current file,
10105 or to another Org-mode file, automatically push the old position
10106 onto the ring."
10107 (interactive "p")
10108 (let (p m)
10109 (if (eq last-command this-command)
10110 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10111 (setq p org-mark-ring))
10112 (setq org-mark-ring-last-goto p)
10113 (setq m (car p))
10114 (org-pop-to-buffer-same-window (marker-buffer m))
10115 (goto-char m)
10116 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10118 (defun org-remove-angle-brackets (s)
10119 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10120 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10122 (defun org-add-angle-brackets (s)
10123 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10124 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10126 (defun org-remove-double-quotes (s)
10127 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10128 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10131 ;;; Following specific links
10133 (defun org-follow-timestamp-link ()
10134 (cond
10135 ((org-at-date-range-p t)
10136 (let ((org-agenda-start-on-weekday)
10137 (t1 (match-string 1))
10138 (t2 (match-string 2)))
10139 (setq t1 (time-to-days (org-time-string-to-time t1))
10140 t2 (time-to-days (org-time-string-to-time t2)))
10141 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10142 ((org-at-timestamp-p t)
10143 (org-agenda-list nil (time-to-days (org-time-string-to-time
10144 (substring (match-string 1) 0 10)))
10146 (t (error "This should not happen"))))
10149 ;;; Following file links
10150 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10151 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10152 (declare-function mailcap-mime-info
10153 "mailcap" (string &optional request no-decode))
10154 (defvar org-wait nil)
10155 (defun org-open-file (path &optional in-emacs line search)
10156 "Open the file at PATH.
10157 First, this expands any special file name abbreviations. Then the
10158 configuration variable `org-file-apps' is checked if it contains an
10159 entry for this file type, and if yes, the corresponding command is launched.
10161 If no application is found, Emacs simply visits the file.
10163 With optional prefix argument IN-EMACS, Emacs will visit the file.
10164 With a double \\[universal-argument] \\[universal-argument] \
10165 prefix arg, Org tries to avoid opening in Emacs
10166 and to use an external application to visit the file.
10168 Optional LINE specifies a line to go to, optional SEARCH a string
10169 to search for. If LINE or SEARCH is given, the file will be
10170 opened in Emacs, unless an entry from org-file-apps that makes
10171 use of groups in a regexp matches.
10173 If you want to change the way frames are used when following a
10174 link, please customize `org-link-frame-setup'.
10176 If the file does not exist, an error is thrown."
10177 (let* ((file (if (equal path "")
10178 buffer-file-name
10179 (substitute-in-file-name (expand-file-name path))))
10180 (file-apps (append org-file-apps (org-default-apps)))
10181 (apps (org-remove-if
10182 'org-file-apps-entry-match-against-dlink-p file-apps))
10183 (apps-dlink (org-remove-if-not
10184 'org-file-apps-entry-match-against-dlink-p file-apps))
10185 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10186 (dirp (if remp nil (file-directory-p file)))
10187 (file (if (and dirp org-open-directory-means-index-dot-org)
10188 (concat (file-name-as-directory file) "index.org")
10189 file))
10190 (a-m-a-p (assq 'auto-mode apps))
10191 (dfile (downcase file))
10192 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10193 (link (cond ((and (eq line nil)
10194 (eq search nil))
10195 file)
10196 (line
10197 (concat file "::" (number-to-string line)))
10198 (search
10199 (concat file "::" search))))
10200 (dlink (downcase link))
10201 (old-buffer (current-buffer))
10202 (old-pos (point))
10203 (old-mode major-mode)
10204 ext cmd link-match-data)
10205 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10206 (setq ext (match-string 1 dfile))
10207 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10208 (setq ext (match-string 1 dfile))))
10209 (cond
10210 ((member in-emacs '((16) system))
10211 (setq cmd (cdr (assoc 'system apps))))
10212 (in-emacs (setq cmd 'emacs))
10214 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10215 (and dirp (cdr (assoc 'directory apps)))
10216 ; first, try matching against apps-dlink
10217 ; if we get a match here, store the match data for later
10218 (let ((match (assoc-default dlink apps-dlink
10219 'string-match)))
10220 (if match
10221 (progn (setq link-match-data (match-data))
10222 match)
10223 (progn (setq in-emacs (or in-emacs line search))
10224 nil))) ; if we have no match in apps-dlink,
10225 ; always open the file in emacs if line or search
10226 ; is given (for backwards compatibility)
10227 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10228 'string-match)
10229 (cdr (assoc ext apps))
10230 (cdr (assoc t apps))))))
10231 (when (eq cmd 'system)
10232 (setq cmd (cdr (assoc 'system apps))))
10233 (when (eq cmd 'default)
10234 (setq cmd (cdr (assoc t apps))))
10235 (when (eq cmd 'mailcap)
10236 (require 'mailcap)
10237 (mailcap-parse-mailcaps)
10238 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10239 (command (mailcap-mime-info mime-type)))
10240 (if (stringp command)
10241 (setq cmd command)
10242 (setq cmd 'emacs))))
10243 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10244 (not (file-exists-p file))
10245 (not org-open-non-existing-files))
10246 (error "No such file: %s" file))
10247 (cond
10248 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10249 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10250 (while (string-match "['\"]%s['\"]" cmd)
10251 (setq cmd (replace-match "%s" t t cmd)))
10252 (while (string-match "%s" cmd)
10253 (setq cmd (replace-match
10254 (save-match-data
10255 (shell-quote-argument
10256 (convert-standard-filename file)))
10257 t t cmd)))
10259 ;; Replace "%1", "%2" etc. in command with group matches from regex
10260 (save-match-data
10261 (let ((match-index 1)
10262 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10263 (set-match-data link-match-data)
10264 (while (<= match-index number-of-groups)
10265 (let ((regex (concat "%" (number-to-string match-index)))
10266 (replace-with (match-string match-index dlink)))
10267 (while (string-match regex cmd)
10268 (setq cmd (replace-match replace-with t t cmd))))
10269 (setq match-index (+ match-index 1)))))
10271 (save-window-excursion
10272 (start-process-shell-command cmd nil cmd)
10273 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10275 ((or (stringp cmd)
10276 (eq cmd 'emacs))
10277 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10278 (widen)
10279 (if line (org-goto-line line)
10280 (if search (org-link-search search))))
10281 ((consp cmd)
10282 (let ((file (convert-standard-filename file)))
10283 (save-match-data
10284 (set-match-data link-match-data)
10285 (eval cmd))))
10286 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10287 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10288 (or (not (equal old-buffer (current-buffer)))
10289 (not (equal old-pos (point))))
10290 (org-mark-ring-push old-pos old-buffer))))
10292 (defun org-file-apps-entry-match-against-dlink-p (entry)
10293 "This function returns non-nil if `entry' uses a regular
10294 expression which should be matched against the whole link by
10295 org-open-file.
10297 It assumes that is the case when the entry uses a regular
10298 expression which has at least one grouping construct and the
10299 action is either a lisp form or a command string containing
10300 '%1', i.e. using at least one subexpression match as a
10301 parameter."
10302 (let ((selector (car entry))
10303 (action (cdr entry)))
10304 (if (stringp selector)
10305 (and (> (regexp-opt-depth selector) 0)
10306 (or (and (stringp action)
10307 (string-match "%[0-9]" action))
10308 (consp action)))
10309 nil)))
10311 (defun org-default-apps ()
10312 "Return the default applications for this operating system."
10313 (cond
10314 ((eq system-type 'darwin)
10315 org-file-apps-defaults-macosx)
10316 ((eq system-type 'windows-nt)
10317 org-file-apps-defaults-windowsnt)
10318 (t org-file-apps-defaults-gnu)))
10320 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10321 "Convert extensions to regular expressions in the cars of LIST.
10322 Also, weed out any non-string entries, because the return value is used
10323 only for regexp matching.
10324 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10325 point to the symbol `emacs', indicating that the file should
10326 be opened in Emacs."
10327 (append
10328 (delq nil
10329 (mapcar (lambda (x)
10330 (if (not (stringp (car x)))
10332 (if (string-match "\\W" (car x))
10334 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10335 list))
10336 (if add-auto-mode
10337 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10339 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10340 (defun org-file-remote-p (file)
10341 "Test whether FILE specifies a location on a remote system.
10342 Return non-nil if the location is indeed remote.
10344 For example, the filename \"/user@host:/foo\" specifies a location
10345 on the system \"/user@host:\"."
10346 (cond ((fboundp 'file-remote-p)
10347 (file-remote-p file))
10348 ((fboundp 'tramp-handle-file-remote-p)
10349 (tramp-handle-file-remote-p file))
10350 ((and (boundp 'ange-ftp-name-format)
10351 (string-match (car ange-ftp-name-format) file))
10353 (t nil)))
10356 ;;;; Refiling
10358 (defun org-get-org-file ()
10359 "Read a filename, with default directory `org-directory'."
10360 (let ((default (or org-default-notes-file remember-data-file)))
10361 (read-file-name (format "File name [%s]: " default)
10362 (file-name-as-directory org-directory)
10363 default)))
10365 (defun org-notes-order-reversed-p ()
10366 "Check if the current file should receive notes in reversed order."
10367 (cond
10368 ((not org-reverse-note-order) nil)
10369 ((eq t org-reverse-note-order) t)
10370 ((not (listp org-reverse-note-order)) nil)
10371 (t (catch 'exit
10372 (let ((all org-reverse-note-order)
10373 entry)
10374 (while (setq entry (pop all))
10375 (if (string-match (car entry) buffer-file-name)
10376 (throw 'exit (cdr entry))))
10377 nil)))))
10379 (defvar org-refile-target-table nil
10380 "The list of refile targets, created by `org-refile'.")
10382 (defvar org-agenda-new-buffers nil
10383 "Buffers created to visit agenda files.")
10385 (defvar org-refile-cache nil
10386 "Cache for refile targets.")
10388 (defvar org-refile-markers nil
10389 "All the markers used for caching refile locations.")
10391 (defun org-refile-marker (pos)
10392 "Get a new refile marker, but only if caching is in use."
10393 (if (not org-refile-use-cache)
10395 (let ((m (make-marker)))
10396 (move-marker m pos)
10397 (push m org-refile-markers)
10398 m)))
10400 (defun org-refile-cache-clear ()
10401 "Clear the refile cache and disable all the markers."
10402 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10403 (setq org-refile-markers nil)
10404 (setq org-refile-cache nil)
10405 (message "Refile cache has been cleared"))
10407 (defun org-refile-cache-check-set (set)
10408 "Check if all the markers in the cache still have live buffers."
10409 (let (marker)
10410 (catch 'exit
10411 (while (and set (setq marker (nth 3 (pop set))))
10412 ;; if org-refile-use-outline-path is 'file, marker may be nil
10413 (when (and marker (null (marker-buffer marker)))
10414 (message "not found") (sit-for 3)
10415 (throw 'exit nil)))
10416 t)))
10418 (defun org-refile-cache-put (set &rest identifiers)
10419 "Push the refile targets SET into the cache, under IDENTIFIERS."
10420 (let* ((key (sha1 (prin1-to-string identifiers)))
10421 (entry (assoc key org-refile-cache)))
10422 (if entry
10423 (setcdr entry set)
10424 (push (cons key set) org-refile-cache))))
10426 (defun org-refile-cache-get (&rest identifiers)
10427 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10428 (cond
10429 ((not org-refile-cache) nil)
10430 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10432 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10433 org-refile-cache))))
10434 (and set (org-refile-cache-check-set set) set)))))
10436 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10437 "Produce a table with refile targets."
10438 (let ((case-fold-search nil)
10439 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10440 (entries (or org-refile-targets '((nil . (:level . 1)))))
10441 targets tgs txt re files f desc descre fast-path-p level pos0)
10442 (message "Getting targets...")
10443 (with-current-buffer (or default-buffer (current-buffer))
10444 (while (setq entry (pop entries))
10445 (setq files (car entry) desc (cdr entry))
10446 (setq fast-path-p nil)
10447 (cond
10448 ((null files) (setq files (list (current-buffer))))
10449 ((eq files 'org-agenda-files)
10450 (setq files (org-agenda-files 'unrestricted)))
10451 ((and (symbolp files) (fboundp files))
10452 (setq files (funcall files)))
10453 ((and (symbolp files) (boundp files))
10454 (setq files (symbol-value files))))
10455 (if (stringp files) (setq files (list files)))
10456 (cond
10457 ((eq (car desc) :tag)
10458 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10459 ((eq (car desc) :todo)
10460 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10461 ((eq (car desc) :regexp)
10462 (setq descre (cdr desc)))
10463 ((eq (car desc) :level)
10464 (setq descre (concat "^\\*\\{" (number-to-string
10465 (if org-odd-levels-only
10466 (1- (* 2 (cdr desc)))
10467 (cdr desc)))
10468 "\\}[ \t]")))
10469 ((eq (car desc) :maxlevel)
10470 (setq fast-path-p t)
10471 (setq descre (concat "^\\*\\{1," (number-to-string
10472 (if org-odd-levels-only
10473 (1- (* 2 (cdr desc)))
10474 (cdr desc)))
10475 "\\}[ \t]")))
10476 (t (error "Bad refiling target description %s" desc)))
10477 (while (setq f (pop files))
10478 (with-current-buffer
10479 (if (bufferp f) f (org-get-agenda-file-buffer f))
10481 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10482 (progn
10483 (if (bufferp f) (setq f (buffer-file-name
10484 (buffer-base-buffer f))))
10485 (setq f (and f (expand-file-name f)))
10486 (if (eq org-refile-use-outline-path 'file)
10487 (push (list (file-name-nondirectory f) f nil nil) tgs))
10488 (save-excursion
10489 (save-restriction
10490 (widen)
10491 (goto-char (point-min))
10492 (while (re-search-forward descre nil t)
10493 (goto-char (setq pos0 (point-at-bol)))
10494 (catch 'next
10495 (when org-refile-target-verify-function
10496 (save-match-data
10497 (or (funcall org-refile-target-verify-function)
10498 (throw 'next t))))
10499 (when (and (looking-at org-complex-heading-regexp)
10500 (not (member (match-string 4) excluded-entries))
10501 (match-string 4))
10502 (setq level (org-reduced-level
10503 (- (match-end 1) (match-beginning 1)))
10504 txt (org-link-display-format (match-string 4))
10505 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10506 re (format org-complex-heading-regexp-format
10507 (regexp-quote (match-string 4))))
10508 (when org-refile-use-outline-path
10509 (setq txt (mapconcat
10510 'org-protect-slash
10511 (append
10512 (if (eq org-refile-use-outline-path
10513 'file)
10514 (list (file-name-nondirectory
10515 (buffer-file-name
10516 (buffer-base-buffer))))
10517 (if (eq org-refile-use-outline-path
10518 'full-file-path)
10519 (list (buffer-file-name
10520 (buffer-base-buffer)))))
10521 (org-get-outline-path fast-path-p
10522 level txt)
10523 (list txt))
10524 "/")))
10525 (push (list txt f re (org-refile-marker (point)))
10526 tgs)))
10527 (when (= (point) pos0)
10528 ;; verification function has not moved point
10529 (goto-char (point-at-eol))))))))
10530 (when org-refile-use-cache
10531 (org-refile-cache-put tgs (buffer-file-name) descre))
10532 (setq targets (append tgs targets))
10533 ))))
10534 (message "Getting targets...done")
10535 (nreverse targets)))
10537 (defun org-protect-slash (s)
10538 (while (string-match "/" s)
10539 (setq s (replace-match "\\" t t s)))
10542 (defvar org-olpa (make-vector 20 nil))
10544 (defun org-get-outline-path (&optional fastp level heading)
10545 "Return the outline path to the current entry, as a list.
10547 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10548 routine which makes outline path derivations for an entire file,
10549 avoiding backtracing. Refile target collection makes use of that."
10550 (if fastp
10551 (progn
10552 (if (> level 19)
10553 (error "Outline path failure, more than 19 levels"))
10554 (loop for i from level upto 19 do
10555 (aset org-olpa i nil))
10556 (prog1
10557 (delq nil (append org-olpa nil))
10558 (aset org-olpa level heading)))
10559 (let (rtn case-fold-search)
10560 (save-excursion
10561 (save-restriction
10562 (widen)
10563 (while (org-up-heading-safe)
10564 (when (looking-at org-complex-heading-regexp)
10565 (push (org-match-string-no-properties 4) rtn)))
10566 rtn)))))
10568 (defun org-format-outline-path (path &optional width prefix)
10569 "Format the outline path PATH for display.
10570 Width is the maximum number of characters that is available.
10571 Prefix is a prefix to be included in the returned string,
10572 such as the file name."
10573 (setq width (or width 79))
10574 (if prefix (setq width (- width (length prefix))))
10575 (if (not path)
10576 (or prefix "")
10577 (let* ((nsteps (length path))
10578 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10579 (maxwidth (if (<= total-width width)
10580 10000 ;; everything fits
10581 ;; we need to shorten the level headings
10582 (/ (- width nsteps) nsteps)))
10583 (org-odd-levels-only nil)
10584 (n 0)
10585 (total (1+ (length prefix))))
10586 (setq maxwidth (max maxwidth 10))
10587 (concat prefix
10588 (mapconcat
10589 (lambda (h)
10590 (setq n (1+ n))
10591 (if (and (= n nsteps) (< maxwidth 10000))
10592 (setq maxwidth (- total-width total)))
10593 (if (< (length h) maxwidth)
10594 (progn (setq total (+ total (length h) 1)) h)
10595 (setq h (substring h 0 (- maxwidth 2))
10596 total (+ total maxwidth 1))
10597 (if (string-match "[ \t]+\\'" h)
10598 (setq h (substring h 0 (match-beginning 0))))
10599 (setq h (concat h "..")))
10600 (org-add-props h nil 'face
10601 (nth (% (1- n) org-n-level-faces)
10602 org-level-faces))
10604 path "/")))))
10606 (defun org-display-outline-path (&optional file current)
10607 "Display the current outline path in the echo area."
10608 (interactive "P")
10609 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10610 (case-fold-search nil)
10611 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10612 (if current (setq path (append path
10613 (save-excursion
10614 (org-back-to-heading t)
10615 (if (looking-at org-complex-heading-regexp)
10616 (list (match-string 4)))))))
10617 (message "%s"
10618 (org-format-outline-path
10619 path
10620 (1- (frame-width))
10621 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10623 (defvar org-refile-history nil
10624 "History for refiling operations.")
10626 (defvar org-after-refile-insert-hook nil
10627 "Hook run after `org-refile' has inserted its stuff at the new location.
10628 Note that this is still *before* the stuff will be removed from
10629 the *old* location.")
10631 (defvar org-capture-last-stored-marker)
10632 (defun org-refile (&optional goto default-buffer rfloc)
10633 "Move the entry or entries at point to another heading.
10634 The list of target headings is compiled using the information in
10635 `org-refile-targets', which see.
10637 At the target location, the entry is filed as a subitem of the target
10638 heading. Depending on `org-reverse-note-order', the new subitem will
10639 either be the first or the last subitem.
10641 If there is an active region, all entries in that region will be moved.
10642 However, the region must fulfill the requirement that the first heading
10643 is the first one sets the top-level of the moved text - at most siblings
10644 below it are allowed.
10646 With prefix arg GOTO, the command will only visit the target location
10647 and not actually move anything.
10649 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10650 go to the location where the last refiling operation has put the subtree.
10651 With a prefix argument of `2', refile to the running clock.
10653 RFLOC can be a refile location obtained in a different way.
10655 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10657 If you are using target caching (see `org-refile-use-cache'),
10658 You have to clear the target cache in order to find new targets.
10659 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10660 prefix argument (`C-u C-u C-u C-c C-w')."
10662 (interactive "P")
10663 (if (member goto '(0 (64)))
10664 (org-refile-cache-clear)
10665 (let* ((cbuf (current-buffer))
10666 (regionp (org-region-active-p))
10667 (region-start (and regionp (region-beginning)))
10668 (region-end (and regionp (region-end)))
10669 (region-length (and regionp (- region-end region-start)))
10670 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10671 pos it nbuf file re level reversed)
10672 (setq last-command nil)
10673 (when regionp
10674 (goto-char region-start)
10675 (or (bolp) (goto-char (point-at-bol)))
10676 (setq region-start (point))
10677 (unless (or (org-kill-is-subtree-p
10678 (buffer-substring region-start region-end))
10679 (prog1 org-refile-active-region-within-subtree
10680 (org-toggle-heading)))
10681 (error "The region is not a (sequence of) subtree(s)")))
10682 (if (equal goto '(16))
10683 (org-refile-goto-last-stored)
10684 (when (or
10685 (and (equal goto 2)
10686 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10687 (prog1
10688 (setq it (list (or org-clock-heading "running clock")
10689 (buffer-file-name
10690 (marker-buffer org-clock-hd-marker))
10692 (marker-position org-clock-hd-marker)))
10693 (setq goto nil)))
10694 (setq it (or rfloc
10695 (let (heading-text)
10696 (save-excursion
10697 (unless goto
10698 (org-back-to-heading t)
10699 (setq heading-text
10700 (nth 4 (org-heading-components))))
10701 (org-refile-get-location
10702 (cond (goto "Goto")
10703 (regionp "Refile region to")
10704 (t (concat "Refile subtree \""
10705 heading-text "\" to")))
10706 default-buffer
10707 (and (not (equal '(4) goto))
10708 org-refile-allow-creating-parent-nodes)
10709 goto))))))
10710 (setq file (nth 1 it)
10711 re (nth 2 it)
10712 pos (nth 3 it))
10713 (if (and (not goto)
10715 (equal (buffer-file-name) file)
10716 (if regionp
10717 (and (>= pos region-start)
10718 (<= pos region-end))
10719 (and (>= pos (point))
10720 (< pos (save-excursion
10721 (org-end-of-subtree t t))))))
10722 (error "Cannot refile to position inside the tree or region"))
10724 (setq nbuf (or (find-buffer-visiting file)
10725 (find-file-noselect file)))
10726 (if goto
10727 (progn
10728 (org-pop-to-buffer-same-window nbuf)
10729 (goto-char pos)
10730 (org-show-context 'org-goto))
10731 (if regionp
10732 (progn
10733 (org-kill-new (buffer-substring region-start region-end))
10734 (org-save-markers-in-region region-start region-end))
10735 (org-copy-subtree 1 nil t))
10736 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10737 (find-file-noselect file)))
10738 (setq reversed (org-notes-order-reversed-p))
10739 (save-excursion
10740 (save-restriction
10741 (widen)
10742 (if pos
10743 (progn
10744 (goto-char pos)
10745 (looking-at org-outline-regexp)
10746 (setq level (org-get-valid-level (funcall outline-level) 1))
10747 (goto-char
10748 (if reversed
10749 (or (outline-next-heading) (point-max))
10750 (or (save-excursion (org-get-next-sibling))
10751 (org-end-of-subtree t t)
10752 (point-max)))))
10753 (setq level 1)
10754 (if (not reversed)
10755 (goto-char (point-max))
10756 (goto-char (point-min))
10757 (or (outline-next-heading) (goto-char (point-max)))))
10758 (if (not (bolp)) (newline))
10759 (org-paste-subtree level)
10760 (when org-log-refile
10761 (org-add-log-setup 'refile nil nil 'findpos
10762 org-log-refile)
10763 (unless (eq org-log-refile 'note)
10764 (save-excursion (org-add-log-note))))
10765 (and org-auto-align-tags (org-set-tags nil t))
10766 (bookmark-set "org-refile-last-stored")
10767 ;; If we are refiling for capture, make sure that the
10768 ;; last-capture pointers point here
10769 (when (org-bound-and-true-p org-refile-for-capture)
10770 (bookmark-set "org-capture-last-stored-marker")
10771 (move-marker org-capture-last-stored-marker (point)))
10772 (if (fboundp 'deactivate-mark) (deactivate-mark))
10773 (run-hooks 'org-after-refile-insert-hook))))
10774 (if regionp
10775 (delete-region (point) (+ (point) region-length))
10776 (org-cut-subtree))
10777 (when (featurep 'org-inlinetask)
10778 (org-inlinetask-remove-END-maybe))
10779 (setq org-markers-to-move nil)
10780 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10782 (defun org-refile-goto-last-stored ()
10783 "Go to the location where the last refile was stored."
10784 (interactive)
10785 (bookmark-jump "org-refile-last-stored")
10786 (message "This is the location of the last refile"))
10788 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10789 no-exclude)
10790 "Prompt the user for a refile location, using PROMPT.
10791 PROMPT should not be suffixed with a colon and a space, because
10792 this function appends the default value from
10793 `org-refile-history' automatically, if that is not empty.
10794 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10795 this is used for the GOTO interface."
10796 (let ((org-refile-targets org-refile-targets)
10797 (org-refile-use-outline-path org-refile-use-outline-path)
10798 excluded-entries)
10799 (when (and (eq major-mode 'org-mode)
10800 (not org-refile-use-cache)
10801 (not no-exclude))
10802 (org-map-tree
10803 (lambda()
10804 (setq excluded-entries
10805 (append excluded-entries (list (org-get-heading t t)))))))
10806 (setq org-refile-target-table
10807 (org-refile-get-targets default-buffer excluded-entries)))
10808 (unless org-refile-target-table
10809 (error "No refile targets"))
10810 (let* ((prompt (concat prompt
10811 (and (car org-refile-history)
10812 (concat " (default " (car org-refile-history) ")"))
10813 ": "))
10814 (cbuf (current-buffer))
10815 (partial-completion-mode nil)
10816 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10817 (cfunc (if (and org-refile-use-outline-path
10818 org-outline-path-complete-in-steps)
10819 'org-olpath-completing-read
10820 'org-icompleting-read))
10821 (extra (if org-refile-use-outline-path "/" ""))
10822 (filename (and cfn (expand-file-name cfn)))
10823 (tbl (mapcar
10824 (lambda (x)
10825 (if (and (not (member org-refile-use-outline-path
10826 '(file full-file-path)))
10827 (not (equal filename (nth 1 x))))
10828 (cons (concat (car x) extra " ("
10829 (file-name-nondirectory (nth 1 x)) ")")
10830 (cdr x))
10831 (cons (concat (car x) extra) (cdr x))))
10832 org-refile-target-table))
10833 (completion-ignore-case t)
10834 pa answ parent-target child parent old-hist)
10835 (setq old-hist org-refile-history)
10836 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10837 nil 'org-refile-history (car org-refile-history)))
10838 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10839 (org-refile-check-position pa)
10840 (if pa
10841 (progn
10842 (when (or (not org-refile-history)
10843 (not (eq old-hist org-refile-history))
10844 (not (equal (car pa) (car org-refile-history))))
10845 (setq org-refile-history
10846 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10847 org-refile-history
10848 (cdr org-refile-history))))
10849 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10850 (pop org-refile-history)))
10852 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10853 (progn
10854 (setq parent (match-string 1 answ)
10855 child (match-string 2 answ))
10856 (setq parent-target (or (assoc parent tbl)
10857 (assoc (concat parent "/") tbl)))
10858 (when (and parent-target
10859 (or (eq new-nodes t)
10860 (and (eq new-nodes 'confirm)
10861 (y-or-n-p (format "Create new node \"%s\"? "
10862 child)))))
10863 (org-refile-new-child parent-target child)))
10864 (error "Invalid target location")))))
10866 (declare-function org-string-nw-p "org-macs.el" (s))
10867 (defun org-refile-check-position (refile-pointer)
10868 "Check if the refile pointer matches the readline to which it points."
10869 (let* ((file (nth 1 refile-pointer))
10870 (re (nth 2 refile-pointer))
10871 (pos (nth 3 refile-pointer))
10872 buffer)
10873 (when (org-string-nw-p re)
10874 (setq buffer (if (markerp pos)
10875 (marker-buffer pos)
10876 (or (find-buffer-visiting file)
10877 (find-file-noselect file))))
10878 (with-current-buffer buffer
10879 (save-excursion
10880 (save-restriction
10881 (widen)
10882 (goto-char pos)
10883 (beginning-of-line 1)
10884 (unless (org-looking-at-p re)
10885 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10887 (defun org-refile-new-child (parent-target child)
10888 "Use refile target PARENT-TARGET to add new CHILD below it."
10889 (unless parent-target
10890 (error "Cannot find parent for new node"))
10891 (let ((file (nth 1 parent-target))
10892 (pos (nth 3 parent-target))
10893 level)
10894 (with-current-buffer (or (find-buffer-visiting file)
10895 (find-file-noselect file))
10896 (save-excursion
10897 (save-restriction
10898 (widen)
10899 (if pos
10900 (goto-char pos)
10901 (goto-char (point-max))
10902 (if (not (bolp)) (newline)))
10903 (when (looking-at org-outline-regexp)
10904 (setq level (funcall outline-level))
10905 (org-end-of-subtree t t))
10906 (org-back-over-empty-lines)
10907 (insert "\n" (make-string
10908 (if pos (org-get-valid-level level 1) 1) ?*)
10909 " " child "\n")
10910 (beginning-of-line 0)
10911 (list (concat (car parent-target) "/" child) file "" (point)))))))
10913 (defun org-olpath-completing-read (prompt collection &rest args)
10914 "Read an outline path like a file name."
10915 (let ((thetable collection)
10916 (org-completion-use-ido nil) ; does not work with ido.
10917 (org-completion-use-iswitchb nil)) ; or iswitchb
10918 (apply
10919 'org-icompleting-read prompt
10920 (lambda (string predicate &optional flag)
10921 (let (rtn r f (l (length string)))
10922 (cond
10923 ((eq flag nil)
10924 ;; try completion
10925 (try-completion string thetable))
10926 ((eq flag t)
10927 ;; all-completions
10928 (setq rtn (all-completions string thetable predicate))
10929 (mapcar
10930 (lambda (x)
10931 (setq r (substring x l))
10932 (if (string-match " ([^)]*)$" x)
10933 (setq f (match-string 0 x))
10934 (setq f ""))
10935 (if (string-match "/" r)
10936 (concat string (substring r 0 (match-end 0)) f)
10938 rtn))
10939 ((eq flag 'lambda)
10940 ;; exact match?
10941 (assoc string thetable)))
10943 args)))
10945 ;;;; Dynamic blocks
10947 (defun org-find-dblock (name)
10948 "Find the first dynamic block with name NAME in the buffer.
10949 If not found, stay at current position and return nil."
10950 (let (pos)
10951 (save-excursion
10952 (goto-char (point-min))
10953 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10954 nil t)
10955 (match-beginning 0))))
10956 (if pos (goto-char pos))
10957 pos))
10959 (defconst org-dblock-start-re
10960 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10961 "Matches the start line of a dynamic block, with parameters.")
10963 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10964 "Matches the end of a dynamic block.")
10966 (defun org-create-dblock (plist)
10967 "Create a dynamic block section, with parameters taken from PLIST.
10968 PLIST must contain a :name entry which is used as name of the block."
10969 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10970 (end-of-line 1)
10971 (newline))
10972 (let ((col (current-column))
10973 (name (plist-get plist :name)))
10974 (insert "#+BEGIN: " name)
10975 (while plist
10976 (if (eq (car plist) :name)
10977 (setq plist (cddr plist))
10978 (insert " " (prin1-to-string (pop plist)))))
10979 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10980 (beginning-of-line -2)))
10982 (defun org-prepare-dblock ()
10983 "Prepare dynamic block for refresh.
10984 This empties the block, puts the cursor at the insert position and returns
10985 the property list including an extra property :name with the block name."
10986 (unless (looking-at org-dblock-start-re)
10987 (error "Not at a dynamic block"))
10988 (let* ((begdel (1+ (match-end 0)))
10989 (name (org-no-properties (match-string 1)))
10990 (params (append (list :name name)
10991 (read (concat "(" (match-string 3) ")")))))
10992 (save-excursion
10993 (beginning-of-line 1)
10994 (skip-chars-forward " \t")
10995 (setq params (plist-put params :indentation-column (current-column))))
10996 (unless (re-search-forward org-dblock-end-re nil t)
10997 (error "Dynamic block not terminated"))
10998 (setq params
10999 (append params
11000 (list :content (buffer-substring
11001 begdel (match-beginning 0)))))
11002 (delete-region begdel (match-beginning 0))
11003 (goto-char begdel)
11004 (open-line 1)
11005 params))
11007 (defun org-map-dblocks (&optional command)
11008 "Apply COMMAND to all dynamic blocks in the current buffer.
11009 If COMMAND is not given, use `org-update-dblock'."
11010 (let ((cmd (or command 'org-update-dblock)))
11011 (save-excursion
11012 (goto-char (point-min))
11013 (while (re-search-forward org-dblock-start-re nil t)
11014 (goto-char (match-beginning 0))
11015 (save-excursion
11016 (condition-case nil
11017 (funcall cmd)
11018 (error (message "Error during update of dynamic block"))))
11019 (unless (re-search-forward org-dblock-end-re nil t)
11020 (error "Dynamic block not terminated"))))))
11022 (defun org-dblock-update (&optional arg)
11023 "User command for updating dynamic blocks.
11024 Update the dynamic block at point. With prefix ARG, update all dynamic
11025 blocks in the buffer."
11026 (interactive "P")
11027 (if arg
11028 (org-update-all-dblocks)
11029 (or (looking-at org-dblock-start-re)
11030 (org-beginning-of-dblock))
11031 (org-update-dblock)))
11033 (defun org-update-dblock ()
11034 "Update the dynamic block at point.
11035 This means to empty the block, parse for parameters and then call
11036 the correct writing function."
11037 (interactive)
11038 (save-window-excursion
11039 (let* ((pos (point))
11040 (line (org-current-line))
11041 (params (org-prepare-dblock))
11042 (name (plist-get params :name))
11043 (indent (plist-get params :indentation-column))
11044 (cmd (intern (concat "org-dblock-write:" name))))
11045 (message "Updating dynamic block `%s' at line %d..." name line)
11046 (funcall cmd params)
11047 (message "Updating dynamic block `%s' at line %d...done" name line)
11048 (goto-char pos)
11049 (when (and indent (> indent 0))
11050 (setq indent (make-string indent ?\ ))
11051 (save-excursion
11052 (org-beginning-of-dblock)
11053 (forward-line 1)
11054 (while (not (looking-at org-dblock-end-re))
11055 (insert indent)
11056 (beginning-of-line 2))
11057 (when (looking-at org-dblock-end-re)
11058 (and (looking-at "[ \t]+")
11059 (replace-match ""))
11060 (insert indent)))))))
11062 (defun org-beginning-of-dblock ()
11063 "Find the beginning of the dynamic block at point.
11064 Error if there is no such block at point."
11065 (let ((pos (point))
11066 beg)
11067 (end-of-line 1)
11068 (if (and (re-search-backward org-dblock-start-re nil t)
11069 (setq beg (match-beginning 0))
11070 (re-search-forward org-dblock-end-re nil t)
11071 (> (match-end 0) pos))
11072 (goto-char beg)
11073 (goto-char pos)
11074 (error "Not in a dynamic block"))))
11076 (defun org-update-all-dblocks ()
11077 "Update all dynamic blocks in the buffer.
11078 This function can be used in a hook."
11079 (interactive)
11080 (when (eq major-mode 'org-mode)
11081 (org-map-dblocks 'org-update-dblock)))
11084 ;;;; Completion
11086 (defconst org-additional-option-like-keywords
11087 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11088 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11089 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11090 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11091 "BEGIN:" "END:"
11092 "ORGTBL" "TBLFM:" "TBLNAME:"
11093 "BEGIN_EXAMPLE" "END_EXAMPLE"
11094 "BEGIN_QUOTE" "END_QUOTE"
11095 "BEGIN_VERSE" "END_VERSE"
11096 "BEGIN_CENTER" "END_CENTER"
11097 "BEGIN_SRC" "END_SRC"
11098 "BEGIN_RESULT" "END_RESULT"
11099 "NAME:" "RESULTS:"
11100 "HEADER:" "HEADERS:"
11101 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11102 "CAPTION:" "LABEL:"
11103 "SETUPFILE:"
11104 "INCLUDE:"
11105 "BIND:"
11106 "MACRO:"))
11108 (defcustom org-structure-template-alist
11110 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11111 "<src lang=\"?\">\n\n</src>")
11112 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11113 "<example>\n?\n</example>")
11114 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11115 "<quote>\n?\n</quote>")
11116 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11117 "<verse>\n?\n</verse>")
11118 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11119 "<center>\n?\n</center>")
11120 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11121 "<literal style=\"latex\">\n?\n</literal>")
11122 ("L" "#+LaTeX: "
11123 "<literal style=\"latex\">?</literal>")
11124 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11125 "<literal style=\"html\">\n?\n</literal>")
11126 ("H" "#+HTML: "
11127 "<literal style=\"html\">?</literal>")
11128 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11129 ("A" "#+ASCII: ")
11130 ("i" "#+INDEX: ?"
11131 "#+INDEX: ?")
11132 ("I" "#+INCLUDE %file ?"
11133 "<include file=%file markup=\"?\">")
11135 "Structure completion elements.
11136 This is a list of abbreviation keys and values. The value gets inserted
11137 if you type `<' followed by the key and then press the completion key,
11138 usually `M-TAB'. %file will be replaced by a file name after prompting
11139 for the file using completion. The cursor will be placed at the position
11140 of the `?` in the template.
11141 There are two templates for each key, the first uses the original Org syntax,
11142 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11143 the default when the /org-mtags.el/ module has been loaded. See also the
11144 variable `org-mtags-prefer-muse-templates'."
11145 :group 'org-completion
11146 :type '(repeat
11147 (string :tag "Key")
11148 (string :tag "Template")
11149 (string :tag "Muse Template")))
11151 (defun org-try-structure-completion ()
11152 "Try to complete a structure template before point.
11153 This looks for strings like \"<e\" on an otherwise empty line and
11154 expands them."
11155 (let ((l (buffer-substring (point-at-bol) (point)))
11157 (when (and (looking-at "[ \t]*$")
11158 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11159 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11160 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11161 (match-beginning 1)) a)
11162 t)))
11164 (defun org-complete-expand-structure-template (start cell)
11165 "Expand a structure template."
11166 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11167 (rpl (nth (if musep 2 1) cell))
11168 (ind ""))
11169 (delete-region start (point))
11170 (when (string-match "\\`#\\+" rpl)
11171 (cond
11172 ((bolp))
11173 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11174 (setq ind (buffer-substring (point-at-bol) (point))))
11175 (t (newline))))
11176 (setq start (point))
11177 (if (string-match "%file" rpl)
11178 (setq rpl (replace-match
11179 (concat
11180 "\""
11181 (save-match-data
11182 (abbreviate-file-name (read-file-name "Include file: ")))
11183 "\"")
11184 t t rpl)))
11185 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11186 (concat "\n" ind)))
11187 (insert rpl)
11188 (if (re-search-backward "\\?" start t) (delete-char 1))))
11190 ;;;; TODO, DEADLINE, Comments
11192 (defun org-toggle-comment ()
11193 "Change the COMMENT state of an entry."
11194 (interactive)
11195 (save-excursion
11196 (org-back-to-heading)
11197 (let (case-fold-search)
11198 (cond
11199 ((looking-at (format org-heading-keyword-regexp-format
11200 org-comment-string))
11201 (goto-char (match-end 1))
11202 (looking-at (concat " +" org-comment-string))
11203 (replace-match "" t t)
11204 (when (eolp) (insert " ")))
11205 ((looking-at org-outline-regexp)
11206 (goto-char (match-end 0))
11207 (insert org-comment-string " "))))))
11209 (defvar org-last-todo-state-is-todo nil
11210 "This is non-nil when the last TODO state change led to a TODO state.
11211 If the last change removed the TODO tag or switched to DONE, then
11212 this is nil.")
11214 (defvar org-setting-tags nil) ; dynamically skipped
11216 (defvar org-todo-setup-filter-hook nil
11217 "Hook for functions that pre-filter todo specs.
11218 Each function takes a todo spec and returns either nil or the spec
11219 transformed into canonical form." )
11221 (defvar org-todo-get-default-hook nil
11222 "Hook for functions that get a default item for todo.
11223 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11224 nil or a string to be used for the todo mark." )
11226 (defvar org-agenda-headline-snapshot-before-repeat)
11228 (defun org-current-effective-time ()
11229 "Return current time adjusted for `org-extend-today-until' variable"
11230 (let* ((ct (org-current-time))
11231 (dct (decode-time ct))
11232 (ct1
11233 (if (and org-use-effective-time
11234 (< (nth 2 dct) org-extend-today-until))
11235 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11236 ct)))
11237 ct1))
11239 (defun org-todo-yesterday (&optional arg)
11240 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11241 (interactive "P")
11242 (if (eq major-mode 'org-agenda-mode)
11243 (apply 'org-agenda-todo-yesterday arg)
11244 (let* ((hour (third (decode-time
11245 (org-current-time))))
11246 (org-extend-today-until (1+ hour)))
11247 (org-todo arg))))
11249 (defun org-todo (&optional arg)
11250 "Change the TODO state of an item.
11251 The state of an item is given by a keyword at the start of the heading,
11252 like
11253 *** TODO Write paper
11254 *** DONE Call mom
11256 The different keywords are specified in the variable `org-todo-keywords'.
11257 By default the available states are \"TODO\" and \"DONE\".
11258 So for this example: when the item starts with TODO, it is changed to DONE.
11259 When it starts with DONE, the DONE is removed. And when neither TODO nor
11260 DONE are present, add TODO at the beginning of the heading.
11262 With \\[universal-argument] prefix arg, use completion to determine the new \
11263 state.
11264 With numeric prefix arg, switch to that state.
11265 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11266 keywords (nextset).
11267 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11268 With a numeric prefix arg of 0, inhibit note taking for the change.
11270 For calling through lisp, arg is also interpreted in the following way:
11271 'none -> empty state
11272 \"\"(empty string) -> switch to empty state
11273 'done -> switch to DONE
11274 'nextset -> switch to the next set of keywords
11275 'previousset -> switch to the previous set of keywords
11276 \"WAITING\" -> switch to the specified keyword, but only if it
11277 really is a member of `org-todo-keywords'."
11278 (interactive "P")
11279 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11280 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11281 'region-start-level 'region))
11282 org-loop-over-headlines-in-active-region)
11283 (org-map-entries
11284 `(org-todo ,arg)
11285 org-loop-over-headlines-in-active-region
11286 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11287 (if (equal arg '(16)) (setq arg 'nextset))
11288 (let ((org-blocker-hook org-blocker-hook)
11289 (case-fold-search nil))
11290 (when (equal arg '(64))
11291 (setq arg nil org-blocker-hook nil))
11292 (when (and org-blocker-hook
11293 (or org-inhibit-blocking
11294 (org-entry-get nil "NOBLOCKING")))
11295 (setq org-blocker-hook nil))
11296 (save-excursion
11297 (catch 'exit
11298 (org-back-to-heading t)
11299 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11300 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11301 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11302 (let* ((match-data (match-data))
11303 (startpos (point-at-bol))
11304 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11305 (org-log-done org-log-done)
11306 (org-log-repeat org-log-repeat)
11307 (org-todo-log-states org-todo-log-states)
11308 (org-inhibit-logging
11309 (if (equal arg 0)
11310 (progn (setq arg nil) 'note) org-inhibit-logging))
11311 (this (match-string 1))
11312 (hl-pos (match-beginning 0))
11313 (head (org-get-todo-sequence-head this))
11314 (ass (assoc head org-todo-kwd-alist))
11315 (interpret (nth 1 ass))
11316 (done-word (nth 3 ass))
11317 (final-done-word (nth 4 ass))
11318 (org-last-state (or this ""))
11319 (completion-ignore-case t)
11320 (member (member this org-todo-keywords-1))
11321 (tail (cdr member))
11322 (org-state (cond
11323 ((and org-todo-key-trigger
11324 (or (and (equal arg '(4))
11325 (eq org-use-fast-todo-selection 'prefix))
11326 (and (not arg) org-use-fast-todo-selection
11327 (not (eq org-use-fast-todo-selection
11328 'prefix)))))
11329 ;; Use fast selection
11330 (org-fast-todo-selection))
11331 ((and (equal arg '(4))
11332 (or (not org-use-fast-todo-selection)
11333 (not org-todo-key-trigger)))
11334 ;; Read a state with completion
11335 (org-icompleting-read
11336 "State: " (mapcar (lambda(x) (list x))
11337 org-todo-keywords-1)
11338 nil t))
11339 ((eq arg 'right)
11340 (if this
11341 (if tail (car tail) nil)
11342 (car org-todo-keywords-1)))
11343 ((eq arg 'left)
11344 (if (equal member org-todo-keywords-1)
11346 (if this
11347 (nth (- (length org-todo-keywords-1)
11348 (length tail) 2)
11349 org-todo-keywords-1)
11350 (org-last org-todo-keywords-1))))
11351 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11352 (setq arg nil))) ; hack to fall back to cycling
11353 (arg
11354 ;; user or caller requests a specific state
11355 (cond
11356 ((equal arg "") nil)
11357 ((eq arg 'none) nil)
11358 ((eq arg 'done) (or done-word (car org-done-keywords)))
11359 ((eq arg 'nextset)
11360 (or (car (cdr (member head org-todo-heads)))
11361 (car org-todo-heads)))
11362 ((eq arg 'previousset)
11363 (let ((org-todo-heads (reverse org-todo-heads)))
11364 (or (car (cdr (member head org-todo-heads)))
11365 (car org-todo-heads))))
11366 ((car (member arg org-todo-keywords-1)))
11367 ((stringp arg)
11368 (error "State `%s' not valid in this file" arg))
11369 ((nth (1- (prefix-numeric-value arg))
11370 org-todo-keywords-1))))
11371 ((null member) (or head (car org-todo-keywords-1)))
11372 ((equal this final-done-word) nil) ;; -> make empty
11373 ((null tail) nil) ;; -> first entry
11374 ((memq interpret '(type priority))
11375 (if (eq this-command last-command)
11376 (car tail)
11377 (if (> (length tail) 0)
11378 (or done-word (car org-done-keywords))
11379 nil)))
11381 (car tail))))
11382 (org-state (or
11383 (run-hook-with-args-until-success
11384 'org-todo-get-default-hook org-state org-last-state)
11385 org-state))
11386 (next (if org-state (concat " " org-state " ") " "))
11387 (change-plist (list :type 'todo-state-change :from this :to org-state
11388 :position startpos))
11389 dolog now-done-p)
11390 (when org-blocker-hook
11391 (setq org-last-todo-state-is-todo
11392 (not (member this org-done-keywords)))
11393 (unless (save-excursion
11394 (save-match-data
11395 (org-with-wide-buffer
11396 (run-hook-with-args-until-failure
11397 'org-blocker-hook change-plist))))
11398 (if (org-called-interactively-p 'interactive)
11399 (error "TODO state change from %s to %s blocked" this org-state)
11400 ;; fail silently
11401 (message "TODO state change from %s to %s blocked" this org-state)
11402 (throw 'exit nil))))
11403 (store-match-data match-data)
11404 (replace-match next t t)
11405 (unless (pos-visible-in-window-p hl-pos)
11406 (message "TODO state changed to %s" (org-trim next)))
11407 (unless head
11408 (setq head (org-get-todo-sequence-head org-state)
11409 ass (assoc head org-todo-kwd-alist)
11410 interpret (nth 1 ass)
11411 done-word (nth 3 ass)
11412 final-done-word (nth 4 ass)))
11413 (when (memq arg '(nextset previousset))
11414 (message "Keyword-Set %d/%d: %s"
11415 (- (length org-todo-sets) -1
11416 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11417 (length org-todo-sets)
11418 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11419 (setq org-last-todo-state-is-todo
11420 (not (member org-state org-done-keywords)))
11421 (setq now-done-p (and (member org-state org-done-keywords)
11422 (not (member this org-done-keywords))))
11423 (and logging (org-local-logging logging))
11424 (when (and (or org-todo-log-states org-log-done)
11425 (not (eq org-inhibit-logging t))
11426 (not (memq arg '(nextset previousset))))
11427 ;; we need to look at recording a time and note
11428 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11429 (nth 2 (assoc this org-todo-log-states))))
11430 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11431 (setq dolog 'time))
11432 (when (and org-state
11433 (member org-state org-not-done-keywords)
11434 (not (member this org-not-done-keywords)))
11435 ;; This is now a todo state and was not one before
11436 ;; If there was a CLOSED time stamp, get rid of it.
11437 (org-add-planning-info nil nil 'closed))
11438 (when (and now-done-p org-log-done)
11439 ;; It is now done, and it was not done before
11440 (org-add-planning-info 'closed (org-current-effective-time))
11441 (if (and (not dolog) (eq 'note org-log-done))
11442 (org-add-log-setup 'done org-state this 'findpos 'note)))
11443 (when (and org-state dolog)
11444 ;; This is a non-nil state, and we need to log it
11445 (org-add-log-setup 'state org-state this 'findpos dolog)))
11446 ;; Fixup tag positioning
11447 (org-todo-trigger-tag-changes org-state)
11448 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11449 (when org-provide-todo-statistics
11450 (org-update-parent-todo-statistics))
11451 (run-hooks 'org-after-todo-state-change-hook)
11452 (if (and arg (not (member org-state org-done-keywords)))
11453 (setq head (org-get-todo-sequence-head org-state)))
11454 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11455 ;; Do we need to trigger a repeat?
11456 (when now-done-p
11457 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11458 ;; This is for the agenda, take a snapshot of the headline.
11459 (save-match-data
11460 (setq org-agenda-headline-snapshot-before-repeat
11461 (org-get-heading))))
11462 (org-auto-repeat-maybe org-state))
11463 ;; Fixup cursor location if close to the keyword
11464 (if (and (outline-on-heading-p)
11465 (not (bolp))
11466 (save-excursion (beginning-of-line 1)
11467 (looking-at org-todo-line-regexp))
11468 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11469 (progn
11470 (goto-char (or (match-end 2) (match-end 1)))
11471 (and (looking-at " ") (just-one-space))))
11472 (when org-trigger-hook
11473 (save-excursion
11474 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11476 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11477 "Block turning an entry into a TODO, using the hierarchy.
11478 This checks whether the current task should be blocked from state
11479 changes. Such blocking occurs when:
11481 1. The task has children which are not all in a completed state.
11483 2. A task has a parent with the property :ORDERED:, and there
11484 are siblings prior to the current task with incomplete
11485 status.
11487 3. The parent of the task is blocked because it has siblings that should
11488 be done first, or is child of a block grandparent TODO entry."
11490 (if (not org-enforce-todo-dependencies)
11491 t ; if locally turned off don't block
11492 (catch 'dont-block
11493 ;; If this is not a todo state change, or if this entry is already DONE,
11494 ;; do not block
11495 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11496 (member (plist-get change-plist :from)
11497 (cons 'done org-done-keywords))
11498 (member (plist-get change-plist :to)
11499 (cons 'todo org-not-done-keywords))
11500 (not (plist-get change-plist :to)))
11501 (throw 'dont-block t))
11502 ;; If this task has children, and any are undone, it's blocked
11503 (save-excursion
11504 (org-back-to-heading t)
11505 (let ((this-level (funcall outline-level)))
11506 (outline-next-heading)
11507 (let ((child-level (funcall outline-level)))
11508 (while (and (not (eobp))
11509 (> child-level this-level))
11510 ;; this todo has children, check whether they are all
11511 ;; completed
11512 (if (and (not (org-entry-is-done-p))
11513 (org-entry-is-todo-p))
11514 (throw 'dont-block nil))
11515 (outline-next-heading)
11516 (setq child-level (funcall outline-level))))))
11517 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11518 ;; any previous siblings are undone, it's blocked
11519 (save-excursion
11520 (org-back-to-heading t)
11521 (let* ((pos (point))
11522 (parent-pos (and (org-up-heading-safe) (point))))
11523 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11524 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11525 (forward-line 1)
11526 (re-search-forward org-not-done-heading-regexp pos t))
11527 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11528 ;; Search further up the hierarchy, to see if an ancestor is blocked
11529 (while t
11530 (goto-char parent-pos)
11531 (if (not (looking-at org-not-done-heading-regexp))
11532 (throw 'dont-block t)) ; do not block, parent is not a TODO
11533 (setq pos (point))
11534 (setq parent-pos (and (org-up-heading-safe) (point)))
11535 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11536 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11537 (forward-line 1)
11538 (re-search-forward org-not-done-heading-regexp pos t))
11539 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11541 (defcustom org-track-ordered-property-with-tag nil
11542 "Should the ORDERED property also be shown as a tag?
11543 The ORDERED property decides if an entry should require subtasks to be
11544 completed in sequence. Since a property is not very visible, setting
11545 this option means that toggling the ORDERED property with the command
11546 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11547 not relevant for the behavior, but it makes things more visible.
11549 Note that toggling the tag with tags commands will not change the property
11550 and therefore not influence behavior!
11552 This can be t, meaning the tag ORDERED should be used, It can also be a
11553 string to select a different tag for this task."
11554 :group 'org-todo
11555 :type '(choice
11556 (const :tag "No tracking" nil)
11557 (const :tag "Track with ORDERED tag" t)
11558 (string :tag "Use other tag")))
11560 (defun org-toggle-ordered-property ()
11561 "Toggle the ORDERED property of the current entry.
11562 For better visibility, you can track the value of this property with a tag.
11563 See variable `org-track-ordered-property-with-tag'."
11564 (interactive)
11565 (let* ((t1 org-track-ordered-property-with-tag)
11566 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11567 (save-excursion
11568 (org-back-to-heading)
11569 (if (org-entry-get nil "ORDERED")
11570 (progn
11571 (org-delete-property "ORDERED")
11572 (and tag (org-toggle-tag tag 'off))
11573 (message "Subtasks can be completed in arbitrary order"))
11574 (org-entry-put nil "ORDERED" "t")
11575 (and tag (org-toggle-tag tag 'on))
11576 (message "Subtasks must be completed in sequence")))))
11578 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11579 (defun org-block-todo-from-checkboxes (change-plist)
11580 "Block turning an entry into a TODO, using checkboxes.
11581 This checks whether the current task should be blocked from state
11582 changes because there are unchecked boxes in this entry."
11583 (if (not org-enforce-todo-checkbox-dependencies)
11584 t ; if locally turned off don't block
11585 (catch 'dont-block
11586 ;; If this is not a todo state change, or if this entry is already DONE,
11587 ;; do not block
11588 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11589 (member (plist-get change-plist :from)
11590 (cons 'done org-done-keywords))
11591 (member (plist-get change-plist :to)
11592 (cons 'todo org-not-done-keywords))
11593 (not (plist-get change-plist :to)))
11594 (throw 'dont-block t))
11595 ;; If this task has checkboxes that are not checked, it's blocked
11596 (save-excursion
11597 (org-back-to-heading t)
11598 (let ((beg (point)) end)
11599 (outline-next-heading)
11600 (setq end (point))
11601 (goto-char beg)
11602 (if (org-list-search-forward
11603 (concat (org-item-beginning-re)
11604 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11605 "\\[[- ]\\]")
11606 end t)
11607 (progn
11608 (if (boundp 'org-blocked-by-checkboxes)
11609 (setq org-blocked-by-checkboxes t))
11610 (throw 'dont-block nil)))))
11611 t))) ; do not block
11613 (defun org-entry-blocked-p ()
11614 "Is the current entry blocked?"
11615 (if (org-entry-get nil "NOBLOCKING")
11616 nil ;; Never block this entry
11617 (not
11618 (run-hook-with-args-until-failure
11619 'org-blocker-hook
11620 (list :type 'todo-state-change
11621 :position (point)
11622 :from 'todo
11623 :to 'done)))))
11625 (defun org-update-statistics-cookies (all)
11626 "Update the statistics cookie, either from TODO or from checkboxes.
11627 This should be called with the cursor in a line with a statistics cookie."
11628 (interactive "P")
11629 (if all
11630 (progn
11631 (org-update-checkbox-count 'all)
11632 (org-map-entries 'org-update-parent-todo-statistics))
11633 (if (not (org-at-heading-p))
11634 (org-update-checkbox-count)
11635 (let ((pos (move-marker (make-marker) (point)))
11636 end l1 l2)
11637 (ignore-errors (org-back-to-heading t))
11638 (if (not (org-at-heading-p))
11639 (org-update-checkbox-count)
11640 (setq l1 (org-outline-level))
11641 (setq end (save-excursion
11642 (outline-next-heading)
11643 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11644 (point)))
11645 (if (and (save-excursion
11646 (re-search-forward
11647 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11648 (not (save-excursion (re-search-forward
11649 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11650 (org-update-checkbox-count)
11651 (if (and l2 (> l2 l1))
11652 (progn
11653 (goto-char end)
11654 (org-update-parent-todo-statistics))
11655 (goto-char pos)
11656 (beginning-of-line 1)
11657 (while (re-search-forward
11658 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11659 (point-at-eol) t)
11660 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11661 (goto-char pos)
11662 (move-marker pos nil)))))
11664 (defvar org-entry-property-inherited-from) ;; defined below
11665 (defun org-update-parent-todo-statistics ()
11666 "Update any statistics cookie in the parent of the current headline.
11667 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11668 the entire subtree and this will travel up the hierarchy and update
11669 statistics everywhere."
11670 (let* ((prop (save-excursion (org-up-heading-safe)
11671 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11672 (recursive (or (not org-hierarchical-todo-statistics)
11673 (and prop (string-match "\\<recursive\\>" prop))))
11674 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11676 (first t)
11677 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11678 level ltoggle l1 new ndel
11679 (cnt-all 0) (cnt-done 0) is-percent kwd
11680 checkbox-beg ov ovs ove cookie-present)
11681 (catch 'exit
11682 (save-excursion
11683 (beginning-of-line 1)
11684 (setq ltoggle (funcall outline-level))
11685 ;; Three situations are to consider:
11687 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11688 ;; to the top-level ancestor on the headline;
11690 ;; 2. If parent has "recursive" property, repeat up to the
11691 ;; headline setting that property, taking inheritance into
11692 ;; account;
11694 ;; 3. Else, move up to direct parent and proceed only once.
11695 (while (and (setq level (org-up-heading-safe))
11696 (or recursive first)
11697 (>= (point) lim))
11698 (setq first nil cookie-present nil)
11699 (unless (and level
11700 (not (string-match
11701 "\\<checkbox\\>"
11702 (downcase (or (org-entry-get nil "COOKIE_DATA")
11703 "")))))
11704 (throw 'exit nil))
11705 (while (re-search-forward box-re (point-at-eol) t)
11706 (setq cnt-all 0 cnt-done 0 cookie-present t)
11707 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11708 (save-match-data
11709 (unless (outline-next-heading) (throw 'exit nil))
11710 (while (and (looking-at org-complex-heading-regexp)
11711 (> (setq l1 (length (match-string 1))) level))
11712 (setq kwd (and (or recursive (= l1 ltoggle))
11713 (match-string 2)))
11714 (if (or (eq org-provide-todo-statistics 'all-headlines)
11715 (and (listp org-provide-todo-statistics)
11716 (or (member kwd org-provide-todo-statistics)
11717 (member kwd org-done-keywords))))
11718 (setq cnt-all (1+ cnt-all))
11719 (if (eq org-provide-todo-statistics t)
11720 (and kwd (setq cnt-all (1+ cnt-all)))))
11721 (and (member kwd org-done-keywords)
11722 (setq cnt-done (1+ cnt-done)))
11723 (outline-next-heading)))
11724 (setq new
11725 (if is-percent
11726 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11727 (format "[%d/%d]" cnt-done cnt-all))
11728 ndel (- (match-end 0) checkbox-beg))
11729 ;; handle overlays when updating cookie from column view
11730 (when (setq ov (car (overlays-at checkbox-beg)))
11731 (setq ovs (overlay-start ov) ove (overlay-end ov))
11732 (delete-overlay ov))
11733 (goto-char checkbox-beg)
11734 (insert new)
11735 (delete-region (point) (+ (point) ndel))
11736 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11737 (when ov (move-overlay ov ovs ove)))
11738 (when cookie-present
11739 (run-hook-with-args 'org-after-todo-statistics-hook
11740 cnt-done (- cnt-all cnt-done))))))
11741 (run-hooks 'org-todo-statistics-hook)))
11743 (defvar org-after-todo-statistics-hook nil
11744 "Hook that is called after a TODO statistics cookie has been updated.
11745 Each function is called with two arguments: the number of not-done entries
11746 and the number of done entries.
11748 For example, the following function, when added to this hook, will switch
11749 an entry to DONE when all children are done, and back to TODO when new
11750 entries are set to a TODO status. Note that this hook is only called
11751 when there is a statistics cookie in the headline!
11753 (defun org-summary-todo (n-done n-not-done)
11754 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11755 (let (org-log-done org-log-states) ; turn off logging
11756 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11759 (defvar org-todo-statistics-hook nil
11760 "Hook that is run whenever Org thinks TODO statistics should be updated.
11761 This hook runs even if there is no statistics cookie present, in which case
11762 `org-after-todo-statistics-hook' would not run.")
11764 (defun org-todo-trigger-tag-changes (state)
11765 "Apply the changes defined in `org-todo-state-tags-triggers'."
11766 (let ((l org-todo-state-tags-triggers)
11767 changes)
11768 (when (or (not state) (equal state ""))
11769 (setq changes (append changes (cdr (assoc "" l)))))
11770 (when (and (stringp state) (> (length state) 0))
11771 (setq changes (append changes (cdr (assoc state l)))))
11772 (when (member state org-not-done-keywords)
11773 (setq changes (append changes (cdr (assoc 'todo l)))))
11774 (when (member state org-done-keywords)
11775 (setq changes (append changes (cdr (assoc 'done l)))))
11776 (dolist (c changes)
11777 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11779 (defun org-local-logging (value)
11780 "Get logging settings from a property VALUE."
11781 (let* (words w a)
11782 ;; directly set the variables, they are already local.
11783 (setq org-log-done nil
11784 org-log-repeat nil
11785 org-todo-log-states nil)
11786 (setq words (org-split-string value))
11787 (while (setq w (pop words))
11788 (cond
11789 ((setq a (assoc w org-startup-options))
11790 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11791 (set (nth 1 a) (nth 2 a))))
11792 ((setq a (org-extract-log-state-settings w))
11793 (and (member (car a) org-todo-keywords-1)
11794 (push a org-todo-log-states)))))))
11796 (defun org-get-todo-sequence-head (kwd)
11797 "Return the head of the TODO sequence to which KWD belongs.
11798 If KWD is not set, check if there is a text property remembering the
11799 right sequence."
11800 (let (p)
11801 (cond
11802 ((not kwd)
11803 (or (get-text-property (point-at-bol) 'org-todo-head)
11804 (progn
11805 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11806 nil (point-at-eol)))
11807 (get-text-property p 'org-todo-head))))
11808 ((not (member kwd org-todo-keywords-1))
11809 (car org-todo-keywords-1))
11810 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11812 (defun org-fast-todo-selection ()
11813 "Fast TODO keyword selection with single keys.
11814 Returns the new TODO keyword, or nil if no state change should occur."
11815 (let* ((fulltable org-todo-key-alist)
11816 (done-keywords org-done-keywords) ;; needed for the faces.
11817 (maxlen (apply 'max (mapcar
11818 (lambda (x)
11819 (if (stringp (car x)) (string-width (car x)) 0))
11820 fulltable)))
11821 (expert nil)
11822 (fwidth (+ maxlen 3 1 3))
11823 (ncol (/ (- (window-width) 4) fwidth))
11824 tg cnt e c tbl
11825 groups ingroup)
11826 (save-excursion
11827 (save-window-excursion
11828 (if expert
11829 (set-buffer (get-buffer-create " *Org todo*"))
11830 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11831 (erase-buffer)
11832 (org-set-local 'org-done-keywords done-keywords)
11833 (setq tbl fulltable cnt 0)
11834 (while (setq e (pop tbl))
11835 (cond
11836 ((equal e '(:startgroup))
11837 (push '() groups) (setq ingroup t)
11838 (when (not (= cnt 0))
11839 (setq cnt 0)
11840 (insert "\n"))
11841 (insert "{ "))
11842 ((equal e '(:endgroup))
11843 (setq ingroup nil cnt 0)
11844 (insert "}\n"))
11845 ((equal e '(:newline))
11846 (when (not (= cnt 0))
11847 (setq cnt 0)
11848 (insert "\n")
11849 (setq e (car tbl))
11850 (while (equal (car tbl) '(:newline))
11851 (insert "\n")
11852 (setq tbl (cdr tbl)))))
11854 (setq tg (car e) c (cdr e))
11855 (if ingroup (push tg (car groups)))
11856 (setq tg (org-add-props tg nil 'face
11857 (org-get-todo-face tg)))
11858 (if (and (= cnt 0) (not ingroup)) (insert " "))
11859 (insert "[" c "] " tg (make-string
11860 (- fwidth 4 (length tg)) ?\ ))
11861 (when (= (setq cnt (1+ cnt)) ncol)
11862 (insert "\n")
11863 (if ingroup (insert " "))
11864 (setq cnt 0)))))
11865 (insert "\n")
11866 (goto-char (point-min))
11867 (if (not expert) (org-fit-window-to-buffer))
11868 (message "[a-z..]:Set [SPC]:clear")
11869 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11870 (cond
11871 ((or (= c ?\C-g)
11872 (and (= c ?q) (not (rassoc c fulltable))))
11873 (setq quit-flag t))
11874 ((= c ?\ ) nil)
11875 ((setq e (rassoc c fulltable) tg (car e))
11877 (t (setq quit-flag t)))))))
11879 (defun org-entry-is-todo-p ()
11880 (member (org-get-todo-state) org-not-done-keywords))
11882 (defun org-entry-is-done-p ()
11883 (member (org-get-todo-state) org-done-keywords))
11885 (defun org-get-todo-state ()
11886 (save-excursion
11887 (org-back-to-heading t)
11888 (and (looking-at org-todo-line-regexp)
11889 (match-end 2)
11890 (match-string 2))))
11892 (defun org-at-date-range-p (&optional inactive-ok)
11893 "Is the cursor inside a date range?"
11894 (interactive)
11895 (save-excursion
11896 (catch 'exit
11897 (let ((pos (point)))
11898 (skip-chars-backward "^[<\r\n")
11899 (skip-chars-backward "<[")
11900 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11901 (>= (match-end 0) pos)
11902 (throw 'exit t))
11903 (skip-chars-backward "^<[\r\n")
11904 (skip-chars-backward "<[")
11905 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11906 (>= (match-end 0) pos)
11907 (throw 'exit t)))
11908 nil)))
11910 (defun org-get-repeat (&optional tagline)
11911 "Check if there is a deadline/schedule with repeater in this entry."
11912 (save-match-data
11913 (save-excursion
11914 (org-back-to-heading t)
11915 (and (re-search-forward (if tagline
11916 (concat tagline "\\s-*" org-repeat-re)
11917 org-repeat-re)
11918 (org-entry-end-position) t)
11919 (match-string-no-properties 1)))))
11921 (defvar org-last-changed-timestamp)
11922 (defvar org-last-inserted-timestamp)
11923 (defvar org-log-post-message)
11924 (defvar org-log-note-purpose)
11925 (defvar org-log-note-how)
11926 (defvar org-log-note-extra)
11927 (defun org-auto-repeat-maybe (done-word)
11928 "Check if the current headline contains a repeated deadline/schedule.
11929 If yes, set TODO state back to what it was and change the base date
11930 of repeating deadline/scheduled time stamps to new date.
11931 This function is run automatically after each state change to a DONE state."
11932 ;; last-state is dynamically scoped into this function
11933 (let* ((repeat (org-get-repeat))
11934 (aa (assoc org-last-state org-todo-kwd-alist))
11935 (interpret (nth 1 aa))
11936 (head (nth 2 aa))
11937 (whata '(("d" . day) ("m" . month) ("y" . year)))
11938 (msg "Entry repeats: ")
11939 (org-log-done nil)
11940 (org-todo-log-states nil)
11941 re type n what ts time to-state)
11942 (when repeat
11943 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11944 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11945 org-todo-repeat-to-state))
11946 (unless (and to-state (member to-state org-todo-keywords-1))
11947 (setq to-state (if (eq interpret 'type) org-last-state head)))
11948 (org-todo to-state)
11949 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11950 (org-entry-put nil "LAST_REPEAT" (format-time-string
11951 (org-time-stamp-format t t))))
11952 (when org-log-repeat
11953 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11954 (memq 'org-add-log-note post-command-hook))
11955 ;; OK, we are already setup for some record
11956 (if (eq org-log-repeat 'note)
11957 ;; make sure we take a note, not only a time stamp
11958 (setq org-log-note-how 'note))
11959 ;; Set up for taking a record
11960 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11961 org-last-state
11962 'findpos org-log-repeat)))
11963 (org-back-to-heading t)
11964 (org-add-planning-info nil nil 'closed)
11965 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11966 org-deadline-time-regexp "\\)\\|\\("
11967 org-ts-regexp "\\)"))
11968 (while (re-search-forward
11969 re (save-excursion (outline-next-heading) (point)) t)
11970 (setq type (if (match-end 1) org-scheduled-string
11971 (if (match-end 3) org-deadline-string "Plain:"))
11972 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11973 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11974 (setq n (string-to-number (match-string 2 ts))
11975 what (match-string 3 ts))
11976 (if (equal what "w") (setq n (* n 7) what "d"))
11977 ;; Preparation, see if we need to modify the start date for the change
11978 (when (match-end 1)
11979 (setq time (save-match-data (org-time-string-to-time ts)))
11980 (cond
11981 ((equal (match-string 1 ts) ".")
11982 ;; Shift starting date to today
11983 (org-timestamp-change
11984 (- (org-today) (time-to-days time))
11985 'day))
11986 ((equal (match-string 1 ts) "+")
11987 (let ((nshiftmax 10) (nshift 0))
11988 (while (or (= nshift 0)
11989 (<= (time-to-days time)
11990 (time-to-days (current-time))))
11991 (when (= (incf nshift) nshiftmax)
11992 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11993 (error "Abort")))
11994 (org-timestamp-change n (cdr (assoc what whata)))
11995 (org-at-timestamp-p t)
11996 (setq ts (match-string 1))
11997 (setq time (save-match-data (org-time-string-to-time ts)))))
11998 (org-timestamp-change (- n) (cdr (assoc what whata)))
11999 ;; rematch, so that we have everything in place for the real shift
12000 (org-at-timestamp-p t)
12001 (setq ts (match-string 1))
12002 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
12003 (org-timestamp-change n (cdr (assoc what whata)))
12004 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12005 (setq org-log-post-message msg)
12006 (message "%s" msg))))
12008 (defun org-show-todo-tree (arg)
12009 "Make a compact tree which shows all headlines marked with TODO.
12010 The tree will show the lines where the regexp matches, and all higher
12011 headlines above the match.
12012 With a \\[universal-argument] prefix, prompt for a regexp to match.
12013 With a numeric prefix N, construct a sparse tree for the Nth element
12014 of `org-todo-keywords-1'."
12015 (interactive "P")
12016 (let ((case-fold-search nil)
12017 (kwd-re
12018 (cond ((null arg) org-not-done-regexp)
12019 ((equal arg '(4))
12020 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12021 (mapcar 'list org-todo-keywords-1))))
12022 (concat "\\("
12023 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12024 "\\)\\>")))
12025 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12026 (regexp-quote (nth (1- (prefix-numeric-value arg))
12027 org-todo-keywords-1)))
12028 (t (error "Invalid prefix argument: %s" arg)))))
12029 (message "%d TODO entries found"
12030 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12032 (defun org-deadline (&optional remove time)
12033 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12034 With argument REMOVE, remove any deadline from the item.
12035 With argument TIME, set the deadline at the corresponding date. TIME
12036 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12037 (interactive "P")
12038 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12039 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12040 'region-start-level 'region))
12041 org-loop-over-headlines-in-active-region)
12042 (org-map-entries
12043 `(org-deadline ',remove ,time)
12044 org-loop-over-headlines-in-active-region
12045 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12046 (let* ((old-date (org-entry-get nil "DEADLINE"))
12047 (repeater (and old-date
12048 (string-match
12049 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12050 old-date)
12051 (match-string 1 old-date))))
12052 (if remove
12053 (progn
12054 (when (and old-date org-log-redeadline)
12055 (org-add-log-setup 'deldeadline nil old-date 'findpos
12056 org-log-redeadline))
12057 (org-remove-timestamp-with-keyword org-deadline-string)
12058 (message "Item no longer has a deadline."))
12059 (org-add-planning-info 'deadline time 'closed)
12060 (when (and old-date org-log-redeadline
12061 (not (equal old-date
12062 (substring org-last-inserted-timestamp 1 -1))))
12063 (org-add-log-setup 'redeadline nil old-date 'findpos
12064 org-log-redeadline))
12065 (when repeater
12066 (save-excursion
12067 (org-back-to-heading t)
12068 (when (re-search-forward (concat org-deadline-string " "
12069 org-last-inserted-timestamp)
12070 (save-excursion
12071 (outline-next-heading) (point)) t)
12072 (goto-char (1- (match-end 0)))
12073 (insert " " repeater)
12074 (setq org-last-inserted-timestamp
12075 (concat (substring org-last-inserted-timestamp 0 -1)
12076 " " repeater
12077 (substring org-last-inserted-timestamp -1))))))
12078 (message "Deadline on %s" org-last-inserted-timestamp)))))
12080 (defun org-schedule (&optional remove time)
12081 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12082 With argument REMOVE, remove any scheduling date from the item.
12083 With argument TIME, scheduled at the corresponding date. TIME can
12084 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12085 (interactive "P")
12086 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12087 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12088 'region-start-level 'region))
12089 org-loop-over-headlines-in-active-region)
12090 (org-map-entries
12091 `(org-schedule ',remove ,time)
12092 org-loop-over-headlines-in-active-region
12093 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12094 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12095 (repeater (and old-date
12096 (string-match
12097 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12098 old-date)
12099 (match-string 1 old-date))))
12100 (if remove
12101 (progn
12102 (when (and old-date org-log-reschedule)
12103 (org-add-log-setup 'delschedule nil old-date 'findpos
12104 org-log-reschedule))
12105 (org-remove-timestamp-with-keyword org-scheduled-string)
12106 (message "Item is no longer scheduled."))
12107 (org-add-planning-info 'scheduled time 'closed)
12108 (when (and old-date org-log-reschedule
12109 (not (equal old-date
12110 (substring org-last-inserted-timestamp 1 -1))))
12111 (org-add-log-setup 'reschedule nil old-date 'findpos
12112 org-log-reschedule))
12113 (when repeater
12114 (save-excursion
12115 (org-back-to-heading t)
12116 (when (re-search-forward (concat org-scheduled-string " "
12117 org-last-inserted-timestamp)
12118 (save-excursion
12119 (outline-next-heading) (point)) t)
12120 (goto-char (1- (match-end 0)))
12121 (insert " " repeater)
12122 (setq org-last-inserted-timestamp
12123 (concat (substring org-last-inserted-timestamp 0 -1)
12124 " " repeater
12125 (substring org-last-inserted-timestamp -1))))))
12126 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12128 (defun org-get-scheduled-time (pom &optional inherit)
12129 "Get the scheduled time as a time tuple, of a format suitable
12130 for calling org-schedule with, or if there is no scheduling,
12131 returns nil."
12132 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12133 (when time
12134 (apply 'encode-time (org-parse-time-string time)))))
12136 (defun org-get-deadline-time (pom &optional inherit)
12137 "Get the deadline as a time tuple, of a format suitable for
12138 calling org-deadline with, or if there is no scheduling, returns
12139 nil."
12140 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12141 (when time
12142 (apply 'encode-time (org-parse-time-string time)))))
12144 (defun org-remove-timestamp-with-keyword (keyword)
12145 "Remove all time stamps with KEYWORD in the current entry."
12146 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12147 beg)
12148 (save-excursion
12149 (org-back-to-heading t)
12150 (setq beg (point))
12151 (outline-next-heading)
12152 (while (re-search-backward re beg t)
12153 (replace-match "")
12154 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12155 (equal (char-before) ?\ ))
12156 (backward-delete-char 1)
12157 (if (string-match "^[ \t]*$" (buffer-substring
12158 (point-at-bol) (point-at-eol)))
12159 (delete-region (point-at-bol)
12160 (min (point-max) (1+ (point-at-eol))))))))))
12162 (defun org-add-planning-info (what &optional time &rest remove)
12163 "Insert new timestamp with keyword in the line directly after the headline.
12164 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12165 If non is given, the user is prompted for a date.
12166 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12167 be removed."
12168 (interactive)
12169 (let (org-time-was-given org-end-time-was-given ts
12170 end default-time default-input)
12172 (catch 'exit
12173 (when (and (memq what '(scheduled deadline))
12174 (or (not time)
12175 (and (stringp time)
12176 (string-match "^[-+]+[0-9]" time))))
12177 ;; Try to get a default date/time from existing timestamp
12178 (save-excursion
12179 (org-back-to-heading t)
12180 (setq end (save-excursion (outline-next-heading) (point)))
12181 (when (re-search-forward (if (eq what 'scheduled)
12182 org-scheduled-time-regexp
12183 org-deadline-time-regexp)
12184 end t)
12185 (setq ts (match-string 1)
12186 default-time
12187 (apply 'encode-time (org-parse-time-string ts))
12188 default-input (and ts (org-get-compact-tod ts))))))
12189 (when what
12190 (setq time
12191 (if (stringp time)
12192 ;; This is a string (relative or absolute), set proper date
12193 (apply 'encode-time
12194 (org-read-date-analyze
12195 time default-time (decode-time default-time)))
12196 ;; If necessary, get the time from the user
12197 (or time (org-read-date nil 'to-time nil nil
12198 default-time default-input)))))
12200 (when (and org-insert-labeled-timestamps-at-point
12201 (member what '(scheduled deadline)))
12202 (insert
12203 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12204 (org-insert-time-stamp time org-time-was-given
12205 nil nil nil (list org-end-time-was-given))
12206 (setq what nil))
12207 (save-excursion
12208 (save-restriction
12209 (let (col list elt ts buffer-invisibility-spec)
12210 (org-back-to-heading t)
12211 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12212 (goto-char (match-end 1))
12213 (setq col (current-column))
12214 (goto-char (match-end 0))
12215 (if (eobp) (insert "\n") (forward-char 1))
12216 (when (and (not what)
12217 (not (looking-at
12218 (concat "[ \t]*"
12219 org-keyword-time-not-clock-regexp))))
12220 ;; Nothing to add, nothing to remove...... :-)
12221 (throw 'exit nil))
12222 (if (and (not (looking-at org-outline-regexp))
12223 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12224 "[^\r\n]*"))
12225 (not (equal (match-string 1) org-clock-string)))
12226 (narrow-to-region (match-beginning 0) (match-end 0))
12227 (insert-before-markers "\n")
12228 (backward-char 1)
12229 (narrow-to-region (point) (point))
12230 (and org-adapt-indentation (org-indent-to-column col)))
12231 ;; Check if we have to remove something.
12232 (setq list (cons what remove))
12233 (while list
12234 (setq elt (pop list))
12235 (when (or (and (eq elt 'scheduled)
12236 (re-search-forward org-scheduled-time-regexp nil t))
12237 (and (eq elt 'deadline)
12238 (re-search-forward org-deadline-time-regexp nil t))
12239 (and (eq elt 'closed)
12240 (re-search-forward org-closed-time-regexp nil t)))
12241 (replace-match "")
12242 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12243 (and (looking-at "[ \t]+") (replace-match ""))
12244 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12245 (when what
12246 (insert
12247 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12248 (cond ((eq what 'scheduled) org-scheduled-string)
12249 ((eq what 'deadline) org-deadline-string)
12250 ((eq what 'closed) org-closed-string))
12251 " ")
12252 (setq ts (org-insert-time-stamp
12253 time
12254 (or org-time-was-given
12255 (and (eq what 'closed) org-log-done-with-time))
12256 (eq what 'closed)
12257 nil nil (list org-end-time-was-given)))
12258 (insert
12259 (if (not (or (bolp) (eq (char-before) ?\ )
12260 (memq (char-after) '(32 10))
12261 (eobp))) " " ""))
12262 (end-of-line 1))
12263 (goto-char (point-min))
12264 (widen)
12265 (if (and (looking-at "[ \t]*\n")
12266 (equal (char-before) ?\n))
12267 (delete-region (1- (point)) (point-at-eol)))
12268 ts))))))
12270 (defvar org-log-note-marker (make-marker))
12271 (defvar org-log-note-purpose nil)
12272 (defvar org-log-note-state nil)
12273 (defvar org-log-note-previous-state nil)
12274 (defvar org-log-note-how nil)
12275 (defvar org-log-note-extra nil)
12276 (defvar org-log-note-window-configuration nil)
12277 (defvar org-log-note-return-to (make-marker))
12278 (defvar org-log-note-effective-time nil
12279 "Remembered current time so that dynamically scoped
12280 `org-extend-today-until' affects tha timestamps in state change
12281 log")
12283 (defvar org-log-post-message nil
12284 "Message to be displayed after a log note has been stored.
12285 The auto-repeater uses this.")
12287 (defun org-add-note ()
12288 "Add a note to the current entry.
12289 This is done in the same way as adding a state change note."
12290 (interactive)
12291 (org-add-log-setup 'note nil nil 'findpos nil))
12293 (defvar org-property-end-re)
12294 (defun org-add-log-setup (&optional purpose state prev-state
12295 findpos how extra)
12296 "Set up the post command hook to take a note.
12297 If this is about to TODO state change, the new state is expected in STATE.
12298 When FINDPOS is non-nil, find the correct position for the note in
12299 the current entry. If not, assume that it can be inserted at point.
12300 HOW is an indicator what kind of note should be created.
12301 EXTRA is additional text that will be inserted into the notes buffer."
12302 (let* ((org-log-into-drawer (org-log-into-drawer))
12303 (drawer (cond ((stringp org-log-into-drawer)
12304 org-log-into-drawer)
12305 (org-log-into-drawer "LOGBOOK")
12306 (t nil))))
12307 (save-restriction
12308 (save-excursion
12309 (when findpos
12310 (org-back-to-heading t)
12311 (narrow-to-region (point) (save-excursion
12312 (outline-next-heading) (point)))
12313 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12314 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12315 "[^\r\n]*\\)?"))
12316 (goto-char (match-end 0))
12317 (cond
12318 (drawer
12319 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12320 nil t)
12321 (progn
12322 (goto-char (match-end 0))
12323 (or org-log-states-order-reversed
12324 (and (re-search-forward org-property-end-re nil t)
12325 (goto-char (1- (match-beginning 0))))))
12326 (insert "\n:" drawer ":\n:END:")
12327 (beginning-of-line 0)
12328 (org-indent-line-function)
12329 (beginning-of-line 2)
12330 (org-indent-line-function)
12331 (end-of-line 0)))
12332 ((and org-log-state-notes-insert-after-drawers
12333 (save-excursion
12334 (forward-line) (looking-at org-drawer-regexp)))
12335 (forward-line)
12336 (while (looking-at org-drawer-regexp)
12337 (goto-char (match-end 0))
12338 (re-search-forward org-property-end-re (point-max) t)
12339 (forward-line))
12340 (forward-line -1)))
12341 (unless org-log-states-order-reversed
12342 (and (= (char-after) ?\n) (forward-char 1))
12343 (org-skip-over-state-notes)
12344 (skip-chars-backward " \t\n\r")))
12345 (move-marker org-log-note-marker (point))
12346 (setq org-log-note-purpose purpose
12347 org-log-note-state state
12348 org-log-note-previous-state prev-state
12349 org-log-note-how how
12350 org-log-note-extra extra
12351 org-log-note-effective-time (org-current-effective-time))
12352 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12354 (defun org-skip-over-state-notes ()
12355 "Skip past the list of State notes in an entry."
12356 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12357 (when (ignore-errors (goto-char (org-in-item-p)))
12358 (let* ((struct (org-list-struct))
12359 (prevs (org-list-prevs-alist struct)))
12360 (while (looking-at "[ \t]*- State")
12361 (goto-char (or (org-list-get-next-item (point) struct prevs)
12362 (org-list-get-item-end (point) struct)))))))
12364 (defun org-add-log-note (&optional purpose)
12365 "Pop up a window for taking a note, and add this note later at point."
12366 (remove-hook 'post-command-hook 'org-add-log-note)
12367 (setq org-log-note-window-configuration (current-window-configuration))
12368 (delete-other-windows)
12369 (move-marker org-log-note-return-to (point))
12370 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12371 (goto-char org-log-note-marker)
12372 (org-switch-to-buffer-other-window "*Org Note*")
12373 (erase-buffer)
12374 (if (memq org-log-note-how '(time state))
12375 (let (current-prefix-arg) (org-store-log-note))
12376 (let ((org-inhibit-startup t)) (org-mode))
12377 (insert (format "# Insert note for %s.
12378 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12379 (cond
12380 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12381 ((eq org-log-note-purpose 'done) "closed todo item")
12382 ((eq org-log-note-purpose 'state)
12383 (format "state change from \"%s\" to \"%s\""
12384 (or org-log-note-previous-state "")
12385 (or org-log-note-state "")))
12386 ((eq org-log-note-purpose 'reschedule)
12387 "rescheduling")
12388 ((eq org-log-note-purpose 'delschedule)
12389 "no longer scheduled")
12390 ((eq org-log-note-purpose 'redeadline)
12391 "changing deadline")
12392 ((eq org-log-note-purpose 'deldeadline)
12393 "removing deadline")
12394 ((eq org-log-note-purpose 'refile)
12395 "refiling")
12396 ((eq org-log-note-purpose 'note)
12397 "this entry")
12398 (t (error "This should not happen")))))
12399 (if org-log-note-extra (insert org-log-note-extra))
12400 (org-set-local 'org-finish-function 'org-store-log-note)
12401 (run-hooks 'org-log-buffer-setup-hook)))
12403 (defvar org-note-abort nil) ; dynamically scoped
12404 (defun org-store-log-note ()
12405 "Finish taking a log note, and insert it to where it belongs."
12406 (let ((txt (buffer-string))
12407 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12408 lines ind bul)
12409 (kill-buffer (current-buffer))
12410 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12411 (setq txt (replace-match "" t t txt)))
12412 (if (string-match "\\s-+\\'" txt)
12413 (setq txt (replace-match "" t t txt)))
12414 (setq lines (org-split-string txt "\n"))
12415 (when (and note (string-match "\\S-" note))
12416 (setq note
12417 (org-replace-escapes
12418 note
12419 (list (cons "%u" (user-login-name))
12420 (cons "%U" user-full-name)
12421 (cons "%t" (format-time-string
12422 (org-time-stamp-format 'long 'inactive)
12423 org-log-note-effective-time))
12424 (cons "%T" (format-time-string
12425 (org-time-stamp-format 'long nil)
12426 org-log-note-effective-time))
12427 (cons "%d" (format-time-string
12428 (org-time-stamp-format nil 'inactive)
12429 org-log-note-effective-time))
12430 (cons "%D" (format-time-string
12431 (org-time-stamp-format nil nil)
12432 org-log-note-effective-time))
12433 (cons "%s" (if org-log-note-state
12434 (concat "\"" org-log-note-state "\"")
12435 ""))
12436 (cons "%S" (if org-log-note-previous-state
12437 (concat "\"" org-log-note-previous-state "\"")
12438 "\"\"")))))
12439 (if lines (setq note (concat note " \\\\")))
12440 (push note lines))
12441 (when (or current-prefix-arg org-note-abort)
12442 (when org-log-into-drawer
12443 (org-remove-empty-drawer-at
12444 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12445 org-log-note-marker))
12446 (setq lines nil))
12447 (when lines
12448 (with-current-buffer (marker-buffer org-log-note-marker)
12449 (save-excursion
12450 (goto-char org-log-note-marker)
12451 (move-marker org-log-note-marker nil)
12452 (end-of-line 1)
12453 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12454 (setq ind (save-excursion
12455 (if (ignore-errors (goto-char (org-in-item-p)))
12456 (let ((struct (org-list-struct)))
12457 (org-list-get-ind
12458 (org-list-get-top-point struct) struct))
12459 (skip-chars-backward " \r\t\n")
12460 (cond
12461 ((and (org-at-heading-p)
12462 org-adapt-indentation)
12463 (1+ (org-current-level)))
12464 ((org-at-heading-p) 0)
12465 (t (org-get-indentation))))))
12466 (setq bul (org-list-bullet-string "-"))
12467 (org-indent-line-to ind)
12468 (insert bul (pop lines))
12469 (let ((ind-body (+ (length bul) ind)))
12470 (while lines
12471 (insert "\n")
12472 (org-indent-line-to ind-body)
12473 (insert (pop lines))))
12474 (message "Note stored")
12475 (org-back-to-heading t)
12476 (org-cycle-hide-drawers 'children)))))
12477 (set-window-configuration org-log-note-window-configuration)
12478 (with-current-buffer (marker-buffer org-log-note-return-to)
12479 (goto-char org-log-note-return-to))
12480 (move-marker org-log-note-return-to nil)
12481 (and org-log-post-message (message "%s" org-log-post-message)))
12483 (defun org-remove-empty-drawer-at (drawer pos)
12484 "Remove an empty drawer DRAWER at position POS.
12485 POS may also be a marker."
12486 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12487 (save-excursion
12488 (save-restriction
12489 (widen)
12490 (goto-char pos)
12491 (if (org-in-regexp
12492 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12493 (replace-match ""))))))
12495 (defun org-sparse-tree (&optional arg)
12496 "Create a sparse tree, prompt for the details.
12497 This command can create sparse trees. You first need to select the type
12498 of match used to create the tree:
12500 t Show all TODO entries.
12501 T Show entries with a specific TODO keyword.
12502 m Show entries selected by a tags/property match.
12503 p Enter a property name and its value (both with completion on existing
12504 names/values) and show entries with that property.
12505 r Show entries matching a regular expression (`/' can be used as well)
12506 d Show deadlines due within `org-deadline-warning-days'.
12507 b Show deadlines and scheduled items before a date.
12508 a Show deadlines and scheduled items after a date."
12509 (interactive "P")
12510 (let (ans kwd value)
12511 (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")
12512 (setq ans (read-char-exclusive))
12513 (cond
12514 ((equal ans ?d)
12515 (call-interactively 'org-check-deadlines))
12516 ((equal ans ?b)
12517 (call-interactively 'org-check-before-date))
12518 ((equal ans ?a)
12519 (call-interactively 'org-check-after-date))
12520 ((equal ans ?D)
12521 (call-interactively 'org-check-dates-range))
12522 ((equal ans ?t)
12523 (org-show-todo-tree nil))
12524 ((equal ans ?T)
12525 (org-show-todo-tree '(4)))
12526 ((member ans '(?T ?m))
12527 (call-interactively 'org-match-sparse-tree))
12528 ((member ans '(?p ?P))
12529 (setq kwd (org-icompleting-read "Property: "
12530 (mapcar 'list (org-buffer-property-keys))))
12531 (setq value (org-icompleting-read "Value: "
12532 (mapcar 'list (org-property-values kwd))))
12533 (unless (string-match "\\`{.*}\\'" value)
12534 (setq value (concat "\"" value "\"")))
12535 (org-match-sparse-tree arg (concat kwd "=" value)))
12536 ((member ans '(?r ?R ?/))
12537 (call-interactively 'org-occur))
12538 (t (error "No such sparse tree command \"%c\"" ans)))))
12540 (defvar org-occur-highlights nil
12541 "List of overlays used for occur matches.")
12542 (make-variable-buffer-local 'org-occur-highlights)
12543 (defvar org-occur-parameters nil
12544 "Parameters of the active org-occur calls.
12545 This is a list, each call to org-occur pushes as cons cell,
12546 containing the regular expression and the callback, onto the list.
12547 The list can contain several entries if `org-occur' has been called
12548 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12549 will only contain one set of parameters. When the highlights are
12550 removed (for example with `C-c C-c', or with the next edit (depending
12551 on `org-remove-highlights-with-change'), this variable is emptied
12552 as well.")
12553 (make-variable-buffer-local 'org-occur-parameters)
12555 (defun org-occur (regexp &optional keep-previous callback)
12556 "Make a compact tree which shows all matches of REGEXP.
12557 The tree will show the lines where the regexp matches, and all higher
12558 headlines above the match. It will also show the heading after the match,
12559 to make sure editing the matching entry is easy.
12560 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12561 call to `org-occur' will be kept, to allow stacking of calls to this
12562 command.
12563 If CALLBACK is non-nil, it is a function which is called to confirm
12564 that the match should indeed be shown."
12565 (interactive "sRegexp: \nP")
12566 (when (equal regexp "")
12567 (error "Regexp cannot be empty"))
12568 (unless keep-previous
12569 (org-remove-occur-highlights nil nil t))
12570 (push (cons regexp callback) org-occur-parameters)
12571 (let ((cnt 0))
12572 (save-excursion
12573 (goto-char (point-min))
12574 (if (or (not keep-previous) ; do not want to keep
12575 (not org-occur-highlights)) ; no previous matches
12576 ;; hide everything
12577 (org-overview))
12578 (while (re-search-forward regexp nil t)
12579 (when (or (not callback)
12580 (save-match-data (funcall callback)))
12581 (setq cnt (1+ cnt))
12582 (when org-highlight-sparse-tree-matches
12583 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12584 (org-show-context 'occur-tree))))
12585 (when org-remove-highlights-with-change
12586 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12587 nil 'local))
12588 (unless org-sparse-tree-open-archived-trees
12589 (org-hide-archived-subtrees (point-min) (point-max)))
12590 (run-hooks 'org-occur-hook)
12591 (if (org-called-interactively-p 'interactive)
12592 (message "%d match(es) for regexp %s" cnt regexp))
12593 cnt))
12595 (defun org-occur-next-match (&optional n reset)
12596 "Function for `next-error-function' to find sparse tree matches.
12597 N is the number of matches to move, when negative move backwards.
12598 RESET is entirely ignored - this function always goes back to the
12599 starting point when no match is found."
12600 (let* ((limit (if (< n 0) (point-min) (point-max)))
12601 (search-func (if (< n 0)
12602 'previous-single-char-property-change
12603 'next-single-char-property-change))
12604 (n (abs n))
12605 (pos (point))
12607 (catch 'exit
12608 (while (setq p1 (funcall search-func (point) 'org-type))
12609 (when (equal p1 limit)
12610 (goto-char pos)
12611 (error "No more matches"))
12612 (when (equal (get-char-property p1 'org-type) 'org-occur)
12613 (setq n (1- n))
12614 (when (= n 0)
12615 (goto-char p1)
12616 (throw 'exit (point))))
12617 (goto-char p1))
12618 (goto-char p1)
12619 (error "No more matches"))))
12621 (defun org-show-context (&optional key)
12622 "Make sure point and context are visible.
12623 How much context is shown depends upon the variables
12624 `org-show-hierarchy-above', `org-show-following-heading',
12625 `org-show-entry-below' and `org-show-siblings'."
12626 (let ((heading-p (org-at-heading-p t))
12627 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12628 (following-p (org-get-alist-option org-show-following-heading key))
12629 (entry-p (org-get-alist-option org-show-entry-below key))
12630 (siblings-p (org-get-alist-option org-show-siblings key)))
12631 (catch 'exit
12632 ;; Show heading or entry text
12633 (if (and heading-p (not entry-p))
12634 (org-flag-heading nil) ; only show the heading
12635 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12636 (org-show-hidden-entry))) ; show entire entry
12637 (when following-p
12638 ;; Show next sibling, or heading below text
12639 (save-excursion
12640 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12641 (org-flag-heading nil))))
12642 (when siblings-p (org-show-siblings))
12643 (when hierarchy-p
12644 ;; show all higher headings, possibly with siblings
12645 (save-excursion
12646 (while (and (condition-case nil
12647 (progn (org-up-heading-all 1) t)
12648 (error nil))
12649 (not (bobp)))
12650 (org-flag-heading nil)
12651 (when siblings-p (org-show-siblings))))))))
12653 (defvar org-reveal-start-hook nil
12654 "Hook run before revealing a location.")
12656 (defun org-reveal (&optional siblings)
12657 "Show current entry, hierarchy above it, and the following headline.
12658 This can be used to show a consistent set of context around locations
12659 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12660 not t for the search context.
12662 With optional argument SIBLINGS, on each level of the hierarchy all
12663 siblings are shown. This repairs the tree structure to what it would
12664 look like when opened with hierarchical calls to `org-cycle'.
12665 With double optional argument \\[universal-argument] \\[universal-argument], \
12666 go to the parent and show the
12667 entire tree."
12668 (interactive "P")
12669 (run-hooks 'org-reveal-start-hook)
12670 (let ((org-show-hierarchy-above t)
12671 (org-show-following-heading t)
12672 (org-show-siblings (if siblings t org-show-siblings)))
12673 (org-show-context nil))
12674 (when (equal siblings '(16))
12675 (save-excursion
12676 (when (org-up-heading-safe)
12677 (org-show-subtree)
12678 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12680 (defun org-highlight-new-match (beg end)
12681 "Highlight from BEG to END and mark the highlight is an occur headline."
12682 (let ((ov (make-overlay beg end)))
12683 (overlay-put ov 'face 'secondary-selection)
12684 (overlay-put ov 'org-type 'org-occur)
12685 (push ov org-occur-highlights)))
12687 (defun org-remove-occur-highlights (&optional beg end noremove)
12688 "Remove the occur highlights from the buffer.
12689 BEG and END are ignored. If NOREMOVE is nil, remove this function
12690 from the `before-change-functions' in the current buffer."
12691 (interactive)
12692 (unless org-inhibit-highlight-removal
12693 (mapc 'delete-overlay org-occur-highlights)
12694 (setq org-occur-highlights nil)
12695 (setq org-occur-parameters nil)
12696 (unless noremove
12697 (remove-hook 'before-change-functions
12698 'org-remove-occur-highlights 'local))))
12700 ;;;; Priorities
12702 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12703 "Regular expression matching the priority indicator.")
12705 (defvar org-remove-priority-next-time nil)
12707 (defun org-priority-up ()
12708 "Increase the priority of the current item."
12709 (interactive)
12710 (org-priority 'up))
12712 (defun org-priority-down ()
12713 "Decrease the priority of the current item."
12714 (interactive)
12715 (org-priority 'down))
12717 (defun org-priority (&optional action)
12718 "Change the priority of an item by ARG.
12719 ACTION can be `set', `up', `down', or a character."
12720 (interactive)
12721 (unless org-enable-priority-commands
12722 (error "Priority commands are disabled"))
12723 (setq action (or action 'set))
12724 (let (current new news have remove)
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (if (looking-at org-priority-regexp)
12728 (setq current (string-to-char (match-string 2))
12729 have t))
12730 (cond
12731 ((eq action 'remove)
12732 (setq remove t new ?\ ))
12733 ((or (eq action 'set)
12734 (if (featurep 'xemacs) (characterp action) (integerp action)))
12735 (if (not (eq action 'set))
12736 (setq new action)
12737 (message "Priority %c-%c, SPC to remove: "
12738 org-highest-priority org-lowest-priority)
12739 (save-match-data
12740 (setq new (read-char-exclusive))))
12741 (if (and (= (upcase org-highest-priority) org-highest-priority)
12742 (= (upcase org-lowest-priority) org-lowest-priority))
12743 (setq new (upcase new)))
12744 (cond ((equal new ?\ ) (setq remove t))
12745 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12746 (error "Priority must be between `%c' and `%c'"
12747 org-highest-priority org-lowest-priority))))
12748 ((eq action 'up)
12749 (setq new (if have
12750 (1- current) ; normal cycling
12751 ;; last priority was empty
12752 (if (eq last-command this-command)
12753 org-lowest-priority ; wrap around empty to lowest
12754 ;; default
12755 (if org-priority-start-cycle-with-default
12756 org-default-priority
12757 (1- org-default-priority))))))
12758 ((eq action 'down)
12759 (setq new (if have
12760 (1+ current) ; normal cycling
12761 ;; last priority was empty
12762 (if (eq last-command this-command)
12763 org-highest-priority ; wrap around empty to highest
12764 ;; default
12765 (if org-priority-start-cycle-with-default
12766 org-default-priority
12767 (1+ org-default-priority))))))
12768 (t (error "Invalid action")))
12769 (if (or (< (upcase new) org-highest-priority)
12770 (> (upcase new) org-lowest-priority))
12771 (if (and (memq action '(up down))
12772 (not have) (not (eq last-command this-command)))
12773 ;; `new' is from default priority
12774 (error
12775 "The default can not be set, see `org-default-priority' why")
12776 ;; normal cycling: `new' is beyond highest/lowest priority
12777 ;; and is wrapped around to the empty priority
12778 (setq remove t)))
12779 (setq news (format "%c" new))
12780 (if have
12781 (if remove
12782 (replace-match "" t t nil 1)
12783 (replace-match news t t nil 2))
12784 (if remove
12785 (error "No priority cookie found in line")
12786 (let ((case-fold-search nil))
12787 (looking-at org-todo-line-regexp))
12788 (if (match-end 2)
12789 (progn
12790 (goto-char (match-end 2))
12791 (insert " [#" news "]"))
12792 (goto-char (match-beginning 3))
12793 (insert "[#" news "] "))))
12794 (org-preserve-lc (org-set-tags nil 'align)))
12795 (if remove
12796 (message "Priority removed")
12797 (message "Priority of current item set to %s" news))))
12799 (defun org-get-priority (s)
12800 "Find priority cookie and return priority."
12801 (if (functionp org-get-priority-function)
12802 (funcall org-get-priority-function)
12803 (save-match-data
12804 (if (not (string-match org-priority-regexp s))
12805 (* 1000 (- org-lowest-priority org-default-priority))
12806 (* 1000 (- org-lowest-priority
12807 (string-to-char (match-string 2 s))))))))
12809 ;;;; Tags
12811 (defvar org-agenda-archives-mode)
12812 (defvar org-map-continue-from nil
12813 "Position from where mapping should continue.
12814 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12816 (defvar org-scanner-tags nil
12817 "The current tag list while the tags scanner is running.")
12818 (defvar org-trust-scanner-tags nil
12819 "Should `org-get-tags-at' use the tags for the scanner.
12820 This is for internal dynamical scoping only.
12821 When this is non-nil, the function `org-get-tags-at' will return the value
12822 of `org-scanner-tags' instead of building the list by itself. This
12823 can lead to large speed-ups when the tags scanner is used in a file with
12824 many entries, and when the list of tags is retrieved, for example to
12825 obtain a list of properties. Building the tags list for each entry in such
12826 a file becomes an N^2 operation - but with this variable set, it scales
12827 as N.")
12829 (defun org-scan-tags (action matcher todo-only &optional start-level)
12830 "Scan headline tags with inheritance and produce output ACTION.
12832 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12833 or `agenda' to produce an entry list for an agenda view. It can also be
12834 a Lisp form or a function that should be called at each matched headline, in
12835 this case the return value is a list of all return values from these calls.
12837 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12838 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12839 only lines with a not-done TODO keyword are included in the output.
12840 This should be the same variable that was scoped into
12841 and set by `org-make-tags-matcher' when it constructed MATCHER.
12843 START-LEVEL can be a string with asterisks, reducing the scope to
12844 headlines matching this string."
12845 (require 'org-agenda)
12846 (let* ((re (concat "^"
12847 (if start-level
12848 ;; Get the correct level to match
12849 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12850 org-outline-regexp)
12851 " *\\(\\<\\("
12852 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12853 (org-re
12854 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12855 (props (list 'face 'default
12856 'done-face 'org-agenda-done
12857 'undone-face 'default
12858 'mouse-face 'highlight
12859 'org-not-done-regexp org-not-done-regexp
12860 'org-todo-regexp org-todo-regexp
12861 'org-complex-heading-regexp org-complex-heading-regexp
12862 'help-echo
12863 (format "mouse-2 or RET jump to org file %s"
12864 (abbreviate-file-name
12865 (or (buffer-file-name (buffer-base-buffer))
12866 (buffer-name (buffer-base-buffer)))))))
12867 (case-fold-search nil)
12868 (org-map-continue-from nil)
12869 lspos tags tags-list
12870 (tags-alist (list (cons 0 org-file-tags)))
12871 (llast 0) rtn rtn1 level category i txt
12872 todo marker entry priority)
12873 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12874 (setq action (list 'lambda nil action)))
12875 (save-excursion
12876 (goto-char (point-min))
12877 (when (eq action 'sparse-tree)
12878 (org-overview)
12879 (org-remove-occur-highlights))
12880 (while (re-search-forward re nil t)
12881 (setq org-map-continue-from nil)
12882 (catch :skip
12883 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12884 tags (if (match-end 4) (org-match-string-no-properties 4)))
12885 (goto-char (setq lspos (match-beginning 0)))
12886 (setq level (org-reduced-level (funcall outline-level))
12887 category (org-get-category))
12888 (setq i llast llast level)
12889 ;; remove tag lists from same and sublevels
12890 (while (>= i level)
12891 (when (setq entry (assoc i tags-alist))
12892 (setq tags-alist (delete entry tags-alist)))
12893 (setq i (1- i)))
12894 ;; add the next tags
12895 (when tags
12896 (setq tags (org-split-string tags ":")
12897 tags-alist
12898 (cons (cons level tags) tags-alist)))
12899 ;; compile tags for current headline
12900 (setq tags-list
12901 (if org-use-tag-inheritance
12902 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12903 tags)
12904 org-scanner-tags tags-list)
12905 (when org-use-tag-inheritance
12906 (setcdr (car tags-alist)
12907 (mapcar (lambda (x)
12908 (setq x (copy-sequence x))
12909 (org-add-prop-inherited x))
12910 (cdar tags-alist))))
12911 (when (and tags org-use-tag-inheritance
12912 (or (not (eq t org-use-tag-inheritance))
12913 org-tags-exclude-from-inheritance))
12914 ;; selective inheritance, remove uninherited ones
12915 (setcdr (car tags-alist)
12916 (org-remove-uninherited-tags (cdar tags-alist))))
12917 (when (and
12919 ;; eval matcher only when the todo condition is OK
12920 (and (or (not todo-only) (member todo org-not-done-keywords))
12921 (let ((case-fold-search t) (org-trust-scanner-tags t))
12922 (eval matcher)))
12924 ;; Call the skipper, but return t if it does not skip,
12925 ;; so that the `and' form continues evaluating
12926 (progn
12927 (unless (eq action 'sparse-tree) (org-agenda-skip))
12930 ;; Check if timestamps are deselecting this entry
12931 (or (not todo-only)
12932 (and (member todo org-not-done-keywords)
12933 (or (not org-agenda-tags-todo-honor-ignore-options)
12934 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12936 ;; Extra check for the archive tag
12937 ;; FIXME: Does the skipper already do this????
12939 (not (member org-archive-tag tags-list))
12940 ;; we have an archive tag, should we use this anyway?
12941 (or (not org-agenda-skip-archived-trees)
12942 (and (eq action 'agenda) org-agenda-archives-mode))))
12944 ;; select this headline
12946 (cond
12947 ((eq action 'sparse-tree)
12948 (and org-highlight-sparse-tree-matches
12949 (org-get-heading) (match-end 0)
12950 (org-highlight-new-match
12951 (match-beginning 1) (match-end 1)))
12952 (org-show-context 'tags-tree))
12953 ((eq action 'agenda)
12954 (setq txt (org-agenda-format-item
12956 (concat
12957 (if (eq org-tags-match-list-sublevels 'indented)
12958 (make-string (1- level) ?.) "")
12959 (org-get-heading))
12960 category
12961 tags-list)
12962 priority (org-get-priority txt))
12963 (goto-char lspos)
12964 (setq marker (org-agenda-new-marker))
12965 (org-add-props txt props
12966 'org-marker marker 'org-hd-marker marker 'org-category category
12967 'todo-state todo
12968 'priority priority 'type "tagsmatch")
12969 (push txt rtn))
12970 ((functionp action)
12971 (setq org-map-continue-from nil)
12972 (save-excursion
12973 (setq rtn1 (funcall action))
12974 (push rtn1 rtn)))
12975 (t (error "Invalid action")))
12977 ;; if we are to skip sublevels, jump to end of subtree
12978 (unless org-tags-match-list-sublevels
12979 (org-end-of-subtree t)
12980 (backward-char 1))))
12981 ;; Get the correct position from where to continue
12982 (if org-map-continue-from
12983 (goto-char org-map-continue-from)
12984 (and (= (point) lspos) (end-of-line 1)))))
12985 (when (and (eq action 'sparse-tree)
12986 (not org-sparse-tree-open-archived-trees))
12987 (org-hide-archived-subtrees (point-min) (point-max)))
12988 (nreverse rtn)))
12990 (defun org-remove-uninherited-tags (tags)
12991 "Remove all tags that are not inherited from the list TAGS."
12992 (cond
12993 ((eq org-use-tag-inheritance t)
12994 (if org-tags-exclude-from-inheritance
12995 (org-delete-all org-tags-exclude-from-inheritance tags)
12996 tags))
12997 ((not org-use-tag-inheritance) nil)
12998 ((stringp org-use-tag-inheritance)
12999 (delq nil (mapcar
13000 (lambda (x)
13001 (if (and (string-match org-use-tag-inheritance x)
13002 (not (member x org-tags-exclude-from-inheritance)))
13003 x nil))
13004 tags)))
13005 ((listp org-use-tag-inheritance)
13006 (delq nil (mapcar
13007 (lambda (x)
13008 (if (member x org-use-tag-inheritance) x nil))
13009 tags)))))
13011 (defun org-match-sparse-tree (&optional todo-only match)
13012 "Create a sparse tree according to tags string MATCH.
13013 MATCH can contain positive and negative selection of tags, like
13014 \"+WORK+URGENT-WITHBOSS\".
13015 If optional argument TODO-ONLY is non-nil, only select lines that are
13016 also TODO lines."
13017 (interactive "P")
13018 (org-prepare-agenda-buffers (list (current-buffer)))
13019 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13021 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13023 (defvar org-cached-props nil)
13024 (defun org-cached-entry-get (pom property)
13025 (if (or (eq t org-use-property-inheritance)
13026 (and (stringp org-use-property-inheritance)
13027 (string-match org-use-property-inheritance property))
13028 (and (listp org-use-property-inheritance)
13029 (member property org-use-property-inheritance)))
13030 ;; Caching is not possible, check it directly
13031 (org-entry-get pom property 'inherit)
13032 ;; Get all properties, so that we can do complicated checks easily
13033 (cdr (assoc property (or org-cached-props
13034 (setq org-cached-props
13035 (org-entry-properties pom)))))))
13037 (defun org-global-tags-completion-table (&optional files)
13038 "Return the list of all tags in all agenda buffer/files.
13039 Optional FILES argument is a list of files to which can be used
13040 instead of the agenda files."
13041 (save-excursion
13042 (org-uniquify
13043 (delq nil
13044 (apply 'append
13045 (mapcar
13046 (lambda (file)
13047 (set-buffer (find-file-noselect file))
13048 (append (org-get-buffer-tags)
13049 (mapcar (lambda (x) (if (stringp (car-safe x))
13050 (list (car-safe x)) nil))
13051 org-tag-alist)))
13052 (if (and files (car files))
13053 files
13054 (org-agenda-files))))))))
13056 (defun org-make-tags-matcher (match)
13057 "Create the TAGS/TODO matcher form for the selection string MATCH.
13059 The variable `todo-only' is scoped dynamically into this function; it will be
13060 set to t if the matcher restricts matching to TODO entries,
13061 otherwise will not be touched.
13063 Returns a cons of the selection string MATCH and the constructed
13064 lisp form implementing the matcher. The matcher is to be
13065 evaluated at an Org entry, with point on the headline,
13066 and returns t if the entry matches the
13067 selection string MATCH. The returned lisp form references
13068 two variables with information about the entry, which must be
13069 bound around the form's evaluation: todo, the TODO keyword at the
13070 entry (or nil of none); and tags-list, the list of all tags at the
13071 entry including inherited ones. Additionally, the category
13072 of the entry (if any) must be specified as the text property
13073 'org-category on the headline.
13075 See also `org-scan-tags'.
13077 (declare (special todo-only))
13078 (unless (boundp 'todo-only)
13079 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13080 (unless match
13081 ;; Get a new match request, with completion
13082 (let ((org-last-tags-completion-table
13083 (org-global-tags-completion-table)))
13084 (setq match (org-completing-read-no-i
13085 "Match: " 'org-tags-completion-function nil nil nil
13086 'org-tags-history))))
13088 ;; Parse the string and create a lisp form
13089 (let ((match0 match)
13090 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13091 minus tag mm
13092 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13093 orterms term orlist re-p str-p level-p level-op time-p
13094 prop-p pn pv po gv rest)
13095 (if (string-match "/+" match)
13096 ;; match contains also a todo-matching request
13097 (progn
13098 (setq tagsmatch (substring match 0 (match-beginning 0))
13099 todomatch (substring match (match-end 0)))
13100 (if (string-match "^!" todomatch)
13101 (setq todo-only t todomatch (substring todomatch 1)))
13102 (if (string-match "^\\s-*$" todomatch)
13103 (setq todomatch nil)))
13104 ;; only matching tags
13105 (setq tagsmatch match todomatch nil))
13107 ;; Make the tags matcher
13108 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13109 (setq tagsmatcher t)
13110 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13111 (while (setq term (pop orterms))
13112 (while (and (equal (substring term -1) "\\") orterms)
13113 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13114 (while (string-match re term)
13115 (setq rest (substring term (match-end 0))
13116 minus (and (match-end 1)
13117 (equal (match-string 1 term) "-"))
13118 tag (save-match-data (replace-regexp-in-string
13119 "\\\\-" "-"
13120 (match-string 2 term)))
13121 re-p (equal (string-to-char tag) ?{)
13122 level-p (match-end 4)
13123 prop-p (match-end 5)
13124 mm (cond
13125 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13126 (level-p
13127 (setq level-op (org-op-to-function (match-string 3 term)))
13128 `(,level-op level ,(string-to-number
13129 (match-string 4 term))))
13130 (prop-p
13131 (setq pn (match-string 5 term)
13132 po (match-string 6 term)
13133 pv (match-string 7 term)
13134 re-p (equal (string-to-char pv) ?{)
13135 str-p (equal (string-to-char pv) ?\")
13136 time-p (save-match-data
13137 (string-match "^\"[[<].*[]>]\"$" pv))
13138 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13139 (if time-p (setq pv (org-matcher-time pv)))
13140 (setq po (org-op-to-function po (if time-p 'time str-p)))
13141 (cond
13142 ((equal pn "CATEGORY")
13143 (setq gv '(get-text-property (point) 'org-category)))
13144 ((equal pn "TODO")
13145 (setq gv 'todo))
13147 (setq gv `(org-cached-entry-get nil ,pn))))
13148 (if re-p
13149 (if (eq po 'org<>)
13150 `(not (string-match ,pv (or ,gv "")))
13151 `(string-match ,pv (or ,gv "")))
13152 (if str-p
13153 `(,po (or ,gv "") ,pv)
13154 `(,po (string-to-number (or ,gv ""))
13155 ,(string-to-number pv) ))))
13156 (t `(member ,tag tags-list)))
13157 mm (if minus (list 'not mm) mm)
13158 term rest)
13159 (push mm tagsmatcher))
13160 (push (if (> (length tagsmatcher) 1)
13161 (cons 'and tagsmatcher)
13162 (car tagsmatcher))
13163 orlist)
13164 (setq tagsmatcher nil))
13165 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13166 (setq tagsmatcher
13167 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13168 ;; Make the todo matcher
13169 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13170 (setq todomatcher t)
13171 (setq orterms (org-split-string todomatch "|") orlist nil)
13172 (while (setq term (pop orterms))
13173 (while (string-match re term)
13174 (setq minus (and (match-end 1)
13175 (equal (match-string 1 term) "-"))
13176 kwd (match-string 2 term)
13177 re-p (equal (string-to-char kwd) ?{)
13178 term (substring term (match-end 0))
13179 mm (if re-p
13180 `(string-match ,(substring kwd 1 -1) todo)
13181 (list 'equal 'todo kwd))
13182 mm (if minus (list 'not mm) mm))
13183 (push mm todomatcher))
13184 (push (if (> (length todomatcher) 1)
13185 (cons 'and todomatcher)
13186 (car todomatcher))
13187 orlist)
13188 (setq todomatcher nil))
13189 (setq todomatcher (if (> (length orlist) 1)
13190 (cons 'or orlist) (car orlist))))
13192 ;; Return the string and lisp forms of the matcher
13193 (setq matcher (if todomatcher
13194 (list 'and tagsmatcher todomatcher)
13195 tagsmatcher))
13196 (when todo-only
13197 (setq matcher (list 'and '(member todo org-not-done-keywords)
13198 matcher)))
13199 (cons match0 matcher)))
13201 (defun org-op-to-function (op &optional stringp)
13202 "Turn an operator into the appropriate function."
13203 (setq op
13204 (cond
13205 ((equal op "<" ) '(< string< org-time<))
13206 ((equal op ">" ) '(> org-string> org-time>))
13207 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13208 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13209 ((member op '("=" "==")) '(= string= org-time=))
13210 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13211 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13213 (defun org<> (a b) (not (= a b)))
13214 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13215 (defun org-string>= (a b) (not (string< a b)))
13216 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13217 (defun org-string<> (a b) (not (string= a b)))
13218 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13219 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13220 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13221 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13222 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13223 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13224 (defun org-2ft (s)
13225 "Convert S to a floating point time.
13226 If S is already a number, just return it. If it is a string, parse
13227 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13228 (cond
13229 ((numberp s) s)
13230 ((stringp s)
13231 (condition-case nil
13232 (float-time (apply 'encode-time (org-parse-time-string s)))
13233 (error 0.)))
13234 (t 0.)))
13236 (defun org-time-today ()
13237 "Time in seconds today at 0:00.
13238 Returns the float number of seconds since the beginning of the
13239 epoch to the beginning of today (00:00)."
13240 (float-time (apply 'encode-time
13241 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13243 (defun org-matcher-time (s)
13244 "Interpret a time comparison value."
13245 (save-match-data
13246 (cond
13247 ((string= s "<now>") (float-time))
13248 ((string= s "<today>") (org-time-today))
13249 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13250 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13251 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13252 (+ (org-time-today)
13253 (* (string-to-number (match-string 1 s))
13254 (cdr (assoc (match-string 2 s)
13255 '(("d" . 86400.0) ("w" . 604800.0)
13256 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13257 (t (org-2ft s)))))
13259 (defun org-match-any-p (re list)
13260 "Does re match any element of list?"
13261 (setq list (mapcar (lambda (x) (string-match re x)) list))
13262 (delq nil list))
13264 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13265 (defvar org-tags-overlay (make-overlay 1 1))
13266 (org-detach-overlay org-tags-overlay)
13268 (defun org-get-local-tags-at (&optional pos)
13269 "Get a list of tags defined in the current headline."
13270 (org-get-tags-at pos 'local))
13272 (defun org-get-local-tags ()
13273 "Get a list of tags defined in the current headline."
13274 (org-get-tags-at nil 'local))
13276 (defun org-get-tags-at (&optional pos local)
13277 "Get a list of all headline tags applicable at POS.
13278 POS defaults to point. If tags are inherited, the list contains
13279 the targets in the same sequence as the headlines appear, i.e.
13280 the tags of the current headline come last.
13281 When LOCAL is non-nil, only return tags from the current headline,
13282 ignore inherited ones."
13283 (interactive)
13284 (if (and org-trust-scanner-tags
13285 (or (not pos) (equal pos (point)))
13286 (not local))
13287 org-scanner-tags
13288 (let (tags ltags lastpos parent)
13289 (save-excursion
13290 (save-restriction
13291 (widen)
13292 (goto-char (or pos (point)))
13293 (save-match-data
13294 (catch 'done
13295 (condition-case nil
13296 (progn
13297 (org-back-to-heading t)
13298 (while (not (equal lastpos (point)))
13299 (setq lastpos (point))
13300 (when (looking-at
13301 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13302 (setq ltags (org-split-string
13303 (org-match-string-no-properties 1) ":"))
13304 (when parent
13305 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13306 (setq tags (append
13307 (if parent
13308 (org-remove-uninherited-tags ltags)
13309 ltags)
13310 tags)))
13311 (or org-use-tag-inheritance (throw 'done t))
13312 (if local (throw 'done t))
13313 (or (org-up-heading-safe) (error nil))
13314 (setq parent t)))
13315 (error nil)))))
13316 (if local
13317 tags
13318 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13320 (defun org-add-prop-inherited (s)
13321 (add-text-properties 0 (length s) '(inherited t) s)
13324 (defun org-toggle-tag (tag &optional onoff)
13325 "Toggle the tag TAG for the current line.
13326 If ONOFF is `on' or `off', don't toggle but set to this state."
13327 (let (res current)
13328 (save-excursion
13329 (org-back-to-heading t)
13330 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13331 (point-at-eol) t)
13332 (progn
13333 (setq current (match-string 1))
13334 (replace-match ""))
13335 (setq current ""))
13336 (setq current (nreverse (org-split-string current ":")))
13337 (cond
13338 ((eq onoff 'on)
13339 (setq res t)
13340 (or (member tag current) (push tag current)))
13341 ((eq onoff 'off)
13342 (or (not (member tag current)) (setq current (delete tag current))))
13343 (t (if (member tag current)
13344 (setq current (delete tag current))
13345 (setq res t)
13346 (push tag current))))
13347 (end-of-line 1)
13348 (if current
13349 (progn
13350 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13351 (org-set-tags nil t))
13352 (delete-horizontal-space))
13353 (run-hooks 'org-after-tags-change-hook))
13354 res))
13356 (defun org-align-tags-here (to-col)
13357 ;; Assumes that this is a headline
13358 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13359 (beginning-of-line 1)
13360 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13361 (< pos (match-beginning 2)))
13362 (progn
13363 (setq tags-l (- (match-end 2) (match-beginning 2)))
13364 (goto-char (match-beginning 1))
13365 (insert " ")
13366 (delete-region (point) (1+ (match-beginning 2)))
13367 (setq ncol (max (current-column)
13368 (1+ col)
13369 (if (> to-col 0)
13370 to-col
13371 (- (abs to-col) tags-l))))
13372 (setq p (point))
13373 (insert (make-string (- ncol (current-column)) ?\ ))
13374 (setq ncol (current-column))
13375 (when indent-tabs-mode (tabify p (point-at-eol)))
13376 (org-move-to-column (min ncol col) t))
13377 (goto-char pos))))
13379 (defun org-set-tags-command (&optional arg just-align)
13380 "Call the set-tags command for the current entry."
13381 (interactive "P")
13382 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13383 (org-set-tags arg just-align)
13384 (save-excursion
13385 (org-back-to-heading t)
13386 (org-set-tags arg just-align))))
13388 (defun org-set-tags-to (data)
13389 "Set the tags of the current entry to DATA, replacing the current tags.
13390 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13391 If DATA is nil or the empty string, any tags will be removed."
13392 (interactive "sTags: ")
13393 (setq data
13394 (cond
13395 ((eq data nil) "")
13396 ((equal data "") "")
13397 ((stringp data)
13398 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13399 ":"))
13400 ((listp data)
13401 (concat ":" (mapconcat 'identity data ":") ":"))
13402 (t nil)))
13403 (when data
13404 (save-excursion
13405 (org-back-to-heading t)
13406 (when (looking-at org-complex-heading-regexp)
13407 (if (match-end 5)
13408 (progn
13409 (goto-char (match-beginning 5))
13410 (insert data)
13411 (delete-region (point) (point-at-eol))
13412 (org-set-tags nil 'align))
13413 (goto-char (point-at-eol))
13414 (insert " " data)
13415 (org-set-tags nil 'align)))
13416 (beginning-of-line 1)
13417 (if (looking-at ".*?\\([ \t]+\\)$")
13418 (delete-region (match-beginning 1) (match-end 1))))))
13420 (defun org-align-all-tags ()
13421 "Align the tags i all headings."
13422 (interactive)
13423 (save-excursion
13424 (or (ignore-errors (org-back-to-heading t))
13425 (outline-next-heading))
13426 (if (org-at-heading-p)
13427 (org-set-tags t)
13428 (message "No headings"))))
13430 (defvar org-indent-indentation-per-level)
13431 (defun org-set-tags (&optional arg just-align)
13432 "Set the tags for the current headline.
13433 With prefix ARG, realign all tags in headings in the current buffer."
13434 (interactive "P")
13435 (let* ((re org-outline-regexp-bol)
13436 (current (unless arg (org-get-tags-string)))
13437 (col (current-column))
13438 (org-setting-tags t)
13439 table current-tags inherited-tags ; computed below when needed
13440 tags p0 c0 c1 rpl di tc level)
13441 (if arg
13442 (save-excursion
13443 (goto-char (point-min))
13444 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13445 (while (re-search-forward re nil t)
13446 (org-set-tags nil t)
13447 (end-of-line 1)))
13448 (message "All tags realigned to column %d" org-tags-column))
13449 (if just-align
13450 (setq tags current)
13451 ;; Get a new set of tags from the user
13452 (save-excursion
13453 (setq table (append org-tag-persistent-alist
13454 org-tag-alist
13455 (org-get-buffer-tags)
13456 (and
13457 org-complete-tags-always-offer-all-agenda-tags
13458 (org-global-tags-completion-table
13459 (org-agenda-files))))
13460 org-last-tags-completion-table table
13461 current-tags (org-split-string current ":")
13462 inherited-tags (nreverse
13463 (nthcdr (length current-tags)
13464 (nreverse (org-get-tags-at))))
13465 tags
13466 (if (or (eq t org-use-fast-tag-selection)
13467 (and org-use-fast-tag-selection
13468 (delq nil (mapcar 'cdr table))))
13469 (org-fast-tag-selection
13470 current-tags inherited-tags table
13471 (if org-fast-tag-selection-include-todo
13472 org-todo-key-alist))
13473 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13474 (org-trim
13475 (org-icompleting-read "Tags: "
13476 'org-tags-completion-function
13477 nil nil current 'org-tags-history))))))
13478 (while (string-match "[-+&]+" tags)
13479 ;; No boolean logic, just a list
13480 (setq tags (replace-match ":" t t tags))))
13482 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13484 (if org-tags-sort-function
13485 (setq tags (mapconcat 'identity
13486 (sort (org-split-string
13487 tags (org-re "[^[:alnum:]_@#%]+"))
13488 org-tags-sort-function) ":")))
13490 (if (string-match "\\`[\t ]*\\'" tags)
13491 (setq tags "")
13492 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13493 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13495 ;; Insert new tags at the correct column
13496 (beginning-of-line 1)
13497 (setq level (or (and (looking-at org-outline-regexp)
13498 (- (match-end 0) (point) 1))
13500 (cond
13501 ((and (equal current "") (equal tags "")))
13502 ((re-search-forward
13503 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13504 (point-at-eol) t)
13505 (if (equal tags "")
13506 (setq rpl "")
13507 (goto-char (match-beginning 0))
13508 (setq c0 (current-column)
13509 ;; compute offset for the case of org-indent-mode active
13510 di (if org-indent-mode
13511 (* (1- org-indent-indentation-per-level) (1- level))
13513 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13514 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13515 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13516 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13517 (replace-match rpl t t)
13518 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13519 tags)
13520 (t (error "Tags alignment failed")))
13521 (org-move-to-column col)
13522 (unless just-align
13523 (run-hooks 'org-after-tags-change-hook)))))
13525 (defun org-change-tag-in-region (beg end tag off)
13526 "Add or remove TAG for each entry in the region.
13527 This works in the agenda, and also in an org-mode buffer."
13528 (interactive
13529 (list (region-beginning) (region-end)
13530 (let ((org-last-tags-completion-table
13531 (if (eq major-mode 'org-mode)
13532 (org-get-buffer-tags)
13533 (org-global-tags-completion-table))))
13534 (org-icompleting-read
13535 "Tag: " 'org-tags-completion-function nil nil nil
13536 'org-tags-history))
13537 (progn
13538 (message "[s]et or [r]emove? ")
13539 (equal (read-char-exclusive) ?r))))
13540 (if (fboundp 'deactivate-mark) (deactivate-mark))
13541 (let ((agendap (equal major-mode 'org-agenda-mode))
13542 l1 l2 m buf pos newhead (cnt 0))
13543 (goto-char end)
13544 (setq l2 (1- (org-current-line)))
13545 (goto-char beg)
13546 (setq l1 (org-current-line))
13547 (loop for l from l1 to l2 do
13548 (org-goto-line l)
13549 (setq m (get-text-property (point) 'org-hd-marker))
13550 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13551 (and agendap m))
13552 (setq buf (if agendap (marker-buffer m) (current-buffer))
13553 pos (if agendap m (point)))
13554 (with-current-buffer buf
13555 (save-excursion
13556 (save-restriction
13557 (goto-char pos)
13558 (setq cnt (1+ cnt))
13559 (org-toggle-tag tag (if off 'off 'on))
13560 (setq newhead (org-get-heading)))))
13561 (and agendap (org-agenda-change-all-lines newhead m))))
13562 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13564 (defun org-tags-completion-function (string predicate &optional flag)
13565 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13566 (confirm (lambda (x) (stringp (car x)))))
13567 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13568 (setq s1 (match-string 1 string)
13569 s2 (match-string 2 string))
13570 (setq s1 "" s2 string))
13571 (cond
13572 ((eq flag nil)
13573 ;; try completion
13574 (setq rtn (try-completion s2 ctable confirm))
13575 (if (stringp rtn)
13576 (setq rtn
13577 (concat s1 s2 (substring rtn (length s2))
13578 (if (and org-add-colon-after-tag-completion
13579 (assoc rtn ctable))
13580 ":" ""))))
13581 rtn)
13582 ((eq flag t)
13583 ;; all-completions
13584 (all-completions s2 ctable confirm)
13586 ((eq flag 'lambda)
13587 ;; exact match?
13588 (assoc s2 ctable)))
13591 (defun org-fast-tag-insert (kwd tags face &optional end)
13592 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13593 (insert (format "%-12s" (concat kwd ":"))
13594 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13595 (or end "")))
13597 (defun org-fast-tag-show-exit (flag)
13598 (save-excursion
13599 (org-goto-line 3)
13600 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13601 (replace-match ""))
13602 (when flag
13603 (end-of-line 1)
13604 (org-move-to-column (- (window-width) 19) t)
13605 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13607 (defun org-set-current-tags-overlay (current prefix)
13608 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13609 (if (featurep 'xemacs)
13610 (org-overlay-display org-tags-overlay (concat prefix s)
13611 'secondary-selection)
13612 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13613 (org-overlay-display org-tags-overlay (concat prefix s)))))
13615 (defvar org-last-tag-selection-key nil)
13616 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13617 "Fast tag selection with single keys.
13618 CURRENT is the current list of tags in the headline, INHERITED is the
13619 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13620 possibly with grouping information. TODO-TABLE is a similar table with
13621 TODO keywords, should these have keys assigned to them.
13622 If the keys are nil, a-z are automatically assigned.
13623 Returns the new tags string, or nil to not change the current settings."
13624 (let* ((fulltable (append table todo-table))
13625 (maxlen (apply 'max (mapcar
13626 (lambda (x)
13627 (if (stringp (car x)) (string-width (car x)) 0))
13628 fulltable)))
13629 (buf (current-buffer))
13630 (expert (eq org-fast-tag-selection-single-key 'expert))
13631 (buffer-tags nil)
13632 (fwidth (+ maxlen 3 1 3))
13633 (ncol (/ (- (window-width) 4) fwidth))
13634 (i-face 'org-done)
13635 (c-face 'org-todo)
13636 tg cnt e c char c1 c2 ntable tbl rtn
13637 ov-start ov-end ov-prefix
13638 (exit-after-next org-fast-tag-selection-single-key)
13639 (done-keywords org-done-keywords)
13640 groups ingroup)
13641 (save-excursion
13642 (beginning-of-line 1)
13643 (if (looking-at
13644 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13645 (setq ov-start (match-beginning 1)
13646 ov-end (match-end 1)
13647 ov-prefix "")
13648 (setq ov-start (1- (point-at-eol))
13649 ov-end (1+ ov-start))
13650 (skip-chars-forward "^\n\r")
13651 (setq ov-prefix
13652 (concat
13653 (buffer-substring (1- (point)) (point))
13654 (if (> (current-column) org-tags-column)
13656 (make-string (- org-tags-column (current-column)) ?\ ))))))
13657 (move-overlay org-tags-overlay ov-start ov-end)
13658 (save-window-excursion
13659 (if expert
13660 (set-buffer (get-buffer-create " *Org tags*"))
13661 (delete-other-windows)
13662 (split-window-vertically)
13663 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13664 (erase-buffer)
13665 (org-set-local 'org-done-keywords done-keywords)
13666 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13667 (org-fast-tag-insert "Current" current c-face "\n\n")
13668 (org-fast-tag-show-exit exit-after-next)
13669 (org-set-current-tags-overlay current ov-prefix)
13670 (setq tbl fulltable char ?a cnt 0)
13671 (while (setq e (pop tbl))
13672 (cond
13673 ((equal (car e) :startgroup)
13674 (push '() groups) (setq ingroup t)
13675 (when (not (= cnt 0))
13676 (setq cnt 0)
13677 (insert "\n"))
13678 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13679 ((equal (car e) :endgroup)
13680 (setq ingroup nil cnt 0)
13681 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13682 ((equal e '(:newline))
13683 (when (not (= cnt 0))
13684 (setq cnt 0)
13685 (insert "\n")
13686 (setq e (car tbl))
13687 (while (equal (car tbl) '(:newline))
13688 (insert "\n")
13689 (setq tbl (cdr tbl)))))
13691 (setq tg (copy-sequence (car e)) c2 nil)
13692 (if (cdr e)
13693 (setq c (cdr e))
13694 ;; automatically assign a character.
13695 (setq c1 (string-to-char
13696 (downcase (substring
13697 tg (if (= (string-to-char tg) ?@) 1 0)))))
13698 (if (or (rassoc c1 ntable) (rassoc c1 table))
13699 (while (or (rassoc char ntable) (rassoc char table))
13700 (setq char (1+ char)))
13701 (setq c2 c1))
13702 (setq c (or c2 char)))
13703 (if ingroup (push tg (car groups)))
13704 (setq tg (org-add-props tg nil 'face
13705 (cond
13706 ((not (assoc tg table))
13707 (org-get-todo-face tg))
13708 ((member tg current) c-face)
13709 ((member tg inherited) i-face)
13710 (t nil))))
13711 (if (and (= cnt 0) (not ingroup)) (insert " "))
13712 (insert "[" c "] " tg (make-string
13713 (- fwidth 4 (length tg)) ?\ ))
13714 (push (cons tg c) ntable)
13715 (when (= (setq cnt (1+ cnt)) ncol)
13716 (insert "\n")
13717 (if ingroup (insert " "))
13718 (setq cnt 0)))))
13719 (setq ntable (nreverse ntable))
13720 (insert "\n")
13721 (goto-char (point-min))
13722 (if (not expert) (org-fit-window-to-buffer))
13723 (setq rtn
13724 (catch 'exit
13725 (while t
13726 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13727 (if (not groups) "no " "")
13728 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13729 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13730 (setq org-last-tag-selection-key c)
13731 (cond
13732 ((= c ?\r) (throw 'exit t))
13733 ((= c ?!)
13734 (setq groups (not groups))
13735 (goto-char (point-min))
13736 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13737 ((= c ?\C-c)
13738 (if (not expert)
13739 (org-fast-tag-show-exit
13740 (setq exit-after-next (not exit-after-next)))
13741 (setq expert nil)
13742 (delete-other-windows)
13743 (set-window-buffer (split-window-vertically) " *Org tags*")
13744 (org-switch-to-buffer-other-window " *Org tags*")
13745 (org-fit-window-to-buffer)))
13746 ((or (= c ?\C-g)
13747 (and (= c ?q) (not (rassoc c ntable))))
13748 (org-detach-overlay org-tags-overlay)
13749 (setq quit-flag t))
13750 ((= c ?\ )
13751 (setq current nil)
13752 (if exit-after-next (setq exit-after-next 'now)))
13753 ((= c ?\t)
13754 (condition-case nil
13755 (setq tg (org-icompleting-read
13756 "Tag: "
13757 (delete-dups
13758 (append (or buffer-tags
13759 (with-current-buffer buf
13760 (mapcar 'car (org-get-buffer-tags))))
13761 (delq nil
13762 (mapcar (lambda (x)
13763 (if (stringp
13764 (car x)) x)) table))))))
13765 (quit (setq tg "")))
13766 (when (string-match "\\S-" tg)
13767 (add-to-list 'buffer-tags (list tg))
13768 (if (member tg current)
13769 (setq current (delete tg current))
13770 (push tg current)))
13771 (if exit-after-next (setq exit-after-next 'now)))
13772 ((setq e (rassoc c todo-table) tg (car e))
13773 (with-current-buffer buf
13774 (save-excursion (org-todo tg)))
13775 (if exit-after-next (setq exit-after-next 'now)))
13776 ((setq e (rassoc c ntable) tg (car e))
13777 (if (member tg current)
13778 (setq current (delete tg current))
13779 (loop for g in groups do
13780 (if (member tg g)
13781 (mapc (lambda (x)
13782 (setq current (delete x current)))
13783 g)))
13784 (push tg current))
13785 (if exit-after-next (setq exit-after-next 'now))))
13787 ;; Create a sorted list
13788 (setq current
13789 (sort current
13790 (lambda (a b)
13791 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13792 (if (eq exit-after-next 'now) (throw 'exit t))
13793 (goto-char (point-min))
13794 (beginning-of-line 2)
13795 (delete-region (point) (point-at-eol))
13796 (org-fast-tag-insert "Current" current c-face)
13797 (org-set-current-tags-overlay current ov-prefix)
13798 (while (re-search-forward
13799 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13800 (setq tg (match-string 1))
13801 (add-text-properties
13802 (match-beginning 1) (match-end 1)
13803 (list 'face
13804 (cond
13805 ((member tg current) c-face)
13806 ((member tg inherited) i-face)
13807 (t (get-text-property (match-beginning 1) 'face))))))
13808 (goto-char (point-min)))))
13809 (org-detach-overlay org-tags-overlay)
13810 (if rtn
13811 (mapconcat 'identity current ":")
13812 nil))))
13814 (defun org-get-tags-string ()
13815 "Get the TAGS string in the current headline."
13816 (unless (org-at-heading-p t)
13817 (error "Not on a heading"))
13818 (save-excursion
13819 (beginning-of-line 1)
13820 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13821 (org-match-string-no-properties 1)
13822 "")))
13824 (defun org-get-tags ()
13825 "Get the list of tags specified in the current headline."
13826 (org-split-string (org-get-tags-string) ":"))
13828 (defun org-get-buffer-tags ()
13829 "Get a table of all tags used in the buffer, for completion."
13830 (let (tags)
13831 (save-excursion
13832 (goto-char (point-min))
13833 (while (re-search-forward
13834 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13835 (when (equal (char-after (point-at-bol 0)) ?*)
13836 (mapc (lambda (x) (add-to-list 'tags x))
13837 (org-split-string (org-match-string-no-properties 1) ":")))))
13838 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13839 (mapcar 'list tags)))
13841 ;;;; The mapping API
13843 ;;;###autoload
13844 (defun org-map-entries (func &optional match scope &rest skip)
13845 "Call FUNC at each headline selected by MATCH in SCOPE.
13847 FUNC is a function or a lisp form. The function will be called without
13848 arguments, with the cursor positioned at the beginning of the headline.
13849 The return values of all calls to the function will be collected and
13850 returned as a list.
13852 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13853 does not need to preserve point. After evaluation, the cursor will be
13854 moved to the end of the line (presumably of the headline of the
13855 processed entry) and search continues from there. Under some
13856 circumstances, this may not produce the wanted results. For example,
13857 if you have removed (e.g. archived) the current (sub)tree it could
13858 mean that the next entry will be skipped entirely. In such cases, you
13859 can specify the position from where search should continue by making
13860 FUNC set the variable `org-map-continue-from' to the desired buffer
13861 position.
13863 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13864 Only headlines that are matched by this query will be considered during
13865 the iteration. When MATCH is nil or t, all headlines will be
13866 visited by the iteration.
13868 SCOPE determines the scope of this command. It can be any of:
13870 nil The current buffer, respecting the restriction if any
13871 tree The subtree started with the entry at point
13872 region The entries within the active region, if any
13873 region-start-level
13874 The entries within the active region, but only those at
13875 the same level than the first one.
13876 file The current buffer, without restriction
13877 file-with-archives
13878 The current buffer, and any archives associated with it
13879 agenda All agenda files
13880 agenda-with-archives
13881 All agenda files with any archive files associated with them
13882 \(file1 file2 ...)
13883 If this is a list, all files in the list will be scanned
13885 The remaining args are treated as settings for the skipping facilities of
13886 the scanner. The following items can be given here:
13888 archive skip trees with the archive tag.
13889 comment skip trees with the COMMENT keyword
13890 function or Emacs Lisp form:
13891 will be used as value for `org-agenda-skip-function', so whenever
13892 the function returns t, FUNC will not be called for that
13893 entry and search will continue from the point where the
13894 function leaves it.
13896 If your function needs to retrieve the tags including inherited tags
13897 at the *current* entry, you can use the value of the variable
13898 `org-scanner-tags' which will be much faster than getting the value
13899 with `org-get-tags-at'. If your function gets properties with
13900 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13901 to t around the call to `org-entry-properties' to get the same speedup.
13902 Note that if your function moves around to retrieve tags and properties at
13903 a *different* entry, you cannot use these techniques."
13904 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13905 (not (org-region-active-p)))
13906 (let* ((org-agenda-archives-mode nil) ; just to make sure
13907 (org-agenda-skip-archived-trees (memq 'archive skip))
13908 (org-agenda-skip-comment-trees (memq 'comment skip))
13909 (org-agenda-skip-function
13910 (car (org-delete-all '(comment archive) skip)))
13911 (org-tags-match-list-sublevels t)
13912 (start-level (eq scope 'region-start-level))
13913 matcher file res
13914 org-todo-keywords-for-agenda
13915 org-done-keywords-for-agenda
13916 org-todo-keyword-alist-for-agenda
13917 org-drawers-for-agenda
13918 org-tag-alist-for-agenda
13919 todo-only)
13921 (cond
13922 ((eq match t) (setq matcher t))
13923 ((eq match nil) (setq matcher t))
13924 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13926 (save-excursion
13927 (save-restriction
13928 (cond ((eq scope 'tree)
13929 (org-back-to-heading t)
13930 (org-narrow-to-subtree)
13931 (setq scope nil))
13932 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13933 (org-region-active-p))
13934 ;; If needed, set start-level to a string like "2"
13935 (when start-level
13936 (save-excursion
13937 (goto-char (region-beginning))
13938 (unless (org-at-heading-p) (outline-next-heading))
13939 (setq start-level (org-current-level))))
13940 (narrow-to-region (region-beginning)
13941 (save-excursion
13942 (goto-char (region-end))
13943 (unless (and (bolp) (org-at-heading-p))
13944 (outline-next-heading))
13945 (point)))
13946 (setq scope nil)))
13948 (if (not scope)
13949 (progn
13950 (org-prepare-agenda-buffers
13951 (list (buffer-file-name (current-buffer))))
13952 (setq res (org-scan-tags func matcher todo-only start-level)))
13953 ;; Get the right scope
13954 (cond
13955 ((and scope (listp scope) (symbolp (car scope)))
13956 (setq scope (eval scope)))
13957 ((eq scope 'agenda)
13958 (setq scope (org-agenda-files t)))
13959 ((eq scope 'agenda-with-archives)
13960 (setq scope (org-agenda-files t))
13961 (setq scope (org-add-archive-files scope)))
13962 ((eq scope 'file)
13963 (setq scope (list (buffer-file-name))))
13964 ((eq scope 'file-with-archives)
13965 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13966 (org-prepare-agenda-buffers scope)
13967 (while (setq file (pop scope))
13968 (with-current-buffer (org-find-base-buffer-visiting file)
13969 (save-excursion
13970 (save-restriction
13971 (widen)
13972 (goto-char (point-min))
13973 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13974 res)))
13976 ;;;; Properties
13978 ;;; Setting and retrieving properties
13980 (defconst org-special-properties
13981 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13982 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13983 "The special properties valid in Org-mode.
13985 These are properties that are not defined in the property drawer,
13986 but in some other way.")
13988 (defconst org-default-properties
13989 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13990 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13991 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13992 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13993 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13994 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13995 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13996 "Some properties that are used by Org-mode for various purposes.
13997 Being in this list makes sure that they are offered for completion.")
13999 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14000 "Regular expression matching the first line of a property drawer.")
14002 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14003 "Regular expression matching the last line of a property drawer.")
14005 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14006 "Regular expression matching the first line of a property drawer.")
14008 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14009 "Regular expression matching the first line of a property drawer.")
14011 (defconst org-property-drawer-re
14012 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14013 org-property-end-re "\\)\n?")
14014 "Matches an entire property drawer.")
14016 (defconst org-clock-drawer-re
14017 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14018 org-property-end-re "\\)\n?")
14019 "Matches an entire clock drawer.")
14021 (defsubst org-re-property (property)
14022 "Return a regexp matching PROPERTY.
14023 Match group 1 will be set to the value "
14024 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14026 (defun org-property-action ()
14027 "Do an action on properties."
14028 (interactive)
14029 (let (c)
14030 (org-at-property-p)
14031 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14032 (setq c (read-char-exclusive))
14033 (cond
14034 ((equal c ?s)
14035 (call-interactively 'org-set-property))
14036 ((equal c ?d)
14037 (call-interactively 'org-delete-property))
14038 ((equal c ?D)
14039 (call-interactively 'org-delete-property-globally))
14040 ((equal c ?c)
14041 (call-interactively 'org-compute-property-at-point))
14042 (t (error "No such property action %c" c)))))
14044 (defun org-set-effort (&optional value)
14045 "Set the effort property of the current entry.
14046 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14047 allowed value."
14048 (interactive "P")
14049 (if (equal value 0) (setq value 10))
14050 (let* ((completion-ignore-case t)
14051 (prop org-effort-property)
14052 (cur (org-entry-get nil prop))
14053 (allowed (org-property-get-allowed-values nil prop 'table))
14054 (existing (mapcar 'list (org-property-values prop)))
14056 (val (cond
14057 ((stringp value) value)
14058 ((and allowed (integerp value))
14059 (or (car (nth (1- value) allowed))
14060 (car (org-last allowed))))
14061 (allowed
14062 (message "Select 1-9,0, [RET%s]: %s"
14063 (if cur (concat "=" cur) "")
14064 (mapconcat 'car allowed " "))
14065 (setq rpl (read-char-exclusive))
14066 (if (equal rpl ?\r)
14068 (setq rpl (- rpl ?0))
14069 (if (equal rpl 0) (setq rpl 10))
14070 (if (and (> rpl 0) (<= rpl (length allowed)))
14071 (car (nth (1- rpl) allowed))
14072 (org-completing-read "Effort: " allowed nil))))
14074 (let (org-completion-use-ido org-completion-use-iswitchb)
14075 (org-completing-read
14076 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14077 (concat "[" cur "]") "")
14078 ": ")
14079 existing nil nil "" nil cur))))))
14080 (unless (equal (org-entry-get nil prop) val)
14081 (org-entry-put nil prop val))
14082 (message "%s is now %s" prop val)))
14084 (defun org-at-property-p ()
14085 "Is cursor inside a property drawer?"
14086 (save-excursion
14087 (beginning-of-line 1)
14088 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14089 (save-match-data ;; Used by calling procedures
14090 (let ((p (point))
14091 (range (unless (org-before-first-heading-p)
14092 (org-get-property-block))))
14093 (and range (<= (car range) p) (< p (cdr range))))))))
14095 (defun org-get-property-block (&optional beg end force)
14096 "Return the (beg . end) range of the body of the property drawer.
14097 BEG and END can be beginning and end of subtree, if not given
14098 they will be found.
14099 If the drawer does not exist and FORCE is non-nil, create the drawer."
14100 (catch 'exit
14101 (save-excursion
14102 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14103 (end (or end (progn (outline-next-heading) (point)))))
14104 (goto-char beg)
14105 (if (re-search-forward org-property-start-re end t)
14106 (setq beg (1+ (match-end 0)))
14107 (if force
14108 (save-excursion
14109 (org-insert-property-drawer)
14110 (setq end (progn (outline-next-heading) (point))))
14111 (throw 'exit nil))
14112 (goto-char beg)
14113 (if (re-search-forward org-property-start-re end t)
14114 (setq beg (1+ (match-end 0)))))
14115 (if (re-search-forward org-property-end-re end t)
14116 (setq end (match-beginning 0))
14117 (or force (throw 'exit nil))
14118 (goto-char beg)
14119 (setq end beg)
14120 (org-indent-line-function)
14121 (insert ":END:\n"))
14122 (cons beg end)))))
14124 (defun org-entry-properties (&optional pom which specific)
14125 "Get all properties of the entry at point-or-marker POM.
14126 This includes the TODO keyword, the tags, time strings for deadline,
14127 scheduled, and clocking, and any additional properties defined in the
14128 entry. The return value is an alist, keys may occur multiple times
14129 if the property key was used several times.
14130 POM may also be nil, in which case the current entry is used.
14131 If WHICH is nil or `all', get all properties. If WHICH is
14132 `special' or `standard', only get that subclass. If WHICH
14133 is a string only get exactly this property. SPECIFIC can be a string, the
14134 specific property we are interested in. Specifying it can speed
14135 things up because then unnecessary parsing is avoided."
14136 (setq which (or which 'all))
14137 (org-with-point-at pom
14138 (let ((clockstr (substring org-clock-string 0 -1))
14139 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14140 (case-fold-search nil)
14141 beg end range props sum-props key key1 value string clocksum)
14142 (save-excursion
14143 (when (condition-case nil
14144 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14145 (error nil))
14146 (setq beg (point))
14147 (setq sum-props (get-text-property (point) 'org-summaries))
14148 (setq clocksum (get-text-property (point) :org-clock-minutes))
14149 (outline-next-heading)
14150 (setq end (point))
14151 (when (memq which '(all special))
14152 ;; Get the special properties, like TODO and tags
14153 (goto-char beg)
14154 (when (and (or (not specific) (string= specific "TODO"))
14155 (looking-at org-todo-line-regexp) (match-end 2))
14156 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14157 (when (and (or (not specific) (string= specific "PRIORITY"))
14158 (looking-at org-priority-regexp))
14159 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14160 (when (or (not specific) (string= specific "FILE"))
14161 (push (cons "FILE" buffer-file-name) props))
14162 (when (and (or (not specific) (string= specific "TAGS"))
14163 (setq value (org-get-tags-string))
14164 (string-match "\\S-" value))
14165 (push (cons "TAGS" value) props))
14166 (when (and (or (not specific) (string= specific "ALLTAGS"))
14167 (setq value (org-get-tags-at)))
14168 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14169 ":"))
14170 props))
14171 (when (or (not specific) (string= specific "BLOCKED"))
14172 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14173 (when (or (not specific)
14174 (member specific
14175 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14176 "TIMESTAMP" "TIMESTAMP_IA")))
14177 (catch 'match
14178 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14179 (setq key (if (match-end 1)
14180 (substring (org-match-string-no-properties 1)
14181 0 -1))
14182 string (if (equal key clockstr)
14183 (org-no-properties
14184 (org-trim
14185 (buffer-substring
14186 (match-beginning 3) (goto-char
14187 (point-at-eol)))))
14188 (substring (org-match-string-no-properties 3)
14189 1 -1)))
14190 ;; Get the correct property name from the key. This is
14191 ;; necessary if the user has configured time keywords.
14192 (setq key1 (concat key ":"))
14193 (cond
14194 ((not key)
14195 (setq key
14196 (if (= (char-after (match-beginning 3)) ?\[)
14197 "TIMESTAMP_IA" "TIMESTAMP")))
14198 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14199 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14200 ((equal key1 org-closed-string) (setq key "CLOSED"))
14201 ((equal key1 org-clock-string) (setq key "CLOCK")))
14202 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14203 (progn
14204 (push (cons key string) props)
14205 ;; no need to search further if match is found
14206 (throw 'match t))
14207 (when (or (equal key "CLOCK") (not (assoc key props)))
14208 (push (cons key string) props))))))
14211 (when (memq which '(all standard))
14212 ;; Get the standard properties, like :PROP: ...
14213 (setq range (org-get-property-block beg end))
14214 (when range
14215 (goto-char (car range))
14216 (while (re-search-forward
14217 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14218 (cdr range) t)
14219 (setq key (org-match-string-no-properties 1)
14220 value (org-trim (or (org-match-string-no-properties 2) "")))
14221 (unless (member key excluded)
14222 (push (cons key (or value "")) props)))))
14223 (if clocksum
14224 (push (cons "CLOCKSUM"
14225 (org-columns-number-to-string (/ (float clocksum) 60.)
14226 'add_times))
14227 props))
14228 (unless (assoc "CATEGORY" props)
14229 (push (cons "CATEGORY" (org-get-category)) props))
14230 (append sum-props (nreverse props)))))))
14232 (defun org-entry-get (pom property &optional inherit literal-nil)
14233 "Get value of PROPERTY for entry at point-or-marker POM.
14234 If INHERIT is non-nil and the entry does not have the property,
14235 then also check higher levels of the hierarchy.
14236 If INHERIT is the symbol `selective', use inheritance only if the setting
14237 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14238 If the property is present but empty, the return value is the empty string.
14239 If the property is not present at all, nil is returned.
14241 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14242 do not interpret it as the list atom nil. This is used for inheritance
14243 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14244 (org-with-point-at pom
14245 (if (and inherit (if (eq inherit 'selective)
14246 (org-property-inherit-p property)
14248 (org-entry-get-with-inheritance property literal-nil)
14249 (if (member property org-special-properties)
14250 ;; We need a special property. Use `org-entry-properties' to
14251 ;; retrieve it, but specify the wanted property
14252 (cdr (assoc property (org-entry-properties nil 'special property)))
14253 (let ((range (unless (org-before-first-heading-p)
14254 (org-get-property-block)))
14255 (props (list (or (assoc property org-file-properties)
14256 (assoc property org-global-properties)
14257 (assoc property org-global-properties-fixed))))
14258 val)
14259 (flet ((ap (key)
14260 (when (re-search-forward
14261 (org-re-property key) (cdr range) t)
14262 (setq props
14263 (org-update-property-plist
14265 (if (match-end 1)
14266 (org-match-string-no-properties 1) "")
14267 props)))))
14268 (when (and range (goto-char (car range)))
14269 (ap property)
14270 (goto-char (car range))
14271 (while (ap (concat property "+")))
14272 (setq val (cdr (assoc property props)))
14273 (when val (if literal-nil val (org-not-nil val))))))))))
14275 (defun org-property-or-variable-value (var &optional inherit)
14276 "Check if there is a property fixing the value of VAR.
14277 If yes, return this value. If not, return the current value of the variable."
14278 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14279 (if (and prop (stringp prop) (string-match "\\S-" prop))
14280 (read prop)
14281 (symbol-value var))))
14283 (defun org-entry-delete (pom property)
14284 "Delete the property PROPERTY from entry at point-or-marker POM."
14285 (org-with-point-at pom
14286 (if (member property org-special-properties)
14287 nil ; cannot delete these properties.
14288 (let ((range (org-get-property-block)))
14289 (if (and range
14290 (goto-char (car range))
14291 (re-search-forward
14292 (org-re-property property)
14293 (cdr range) t))
14294 (progn
14295 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14297 nil)))))
14299 ;; Multi-values properties are properties that contain multiple values
14300 ;; These values are assumed to be single words, separated by whitespace.
14301 (defun org-entry-add-to-multivalued-property (pom property value)
14302 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14303 (let* ((old (org-entry-get pom property))
14304 (values (and old (org-split-string old "[ \t]"))))
14305 (setq value (org-entry-protect-space value))
14306 (unless (member value values)
14307 (setq values (cons value values))
14308 (org-entry-put pom property
14309 (mapconcat 'identity values " ")))))
14311 (defun org-entry-remove-from-multivalued-property (pom property value)
14312 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14313 (let* ((old (org-entry-get pom property))
14314 (values (and old (org-split-string old "[ \t]"))))
14315 (setq value (org-entry-protect-space value))
14316 (when (member value values)
14317 (setq values (delete value values))
14318 (org-entry-put pom property
14319 (mapconcat 'identity values " ")))))
14321 (defun org-entry-member-in-multivalued-property (pom property value)
14322 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14323 (let* ((old (org-entry-get pom property))
14324 (values (and old (org-split-string old "[ \t]"))))
14325 (setq value (org-entry-protect-space value))
14326 (member value values)))
14328 (defun org-entry-get-multivalued-property (pom property)
14329 "Return a list of values in a multivalued property."
14330 (let* ((value (org-entry-get pom property))
14331 (values (and value (org-split-string value "[ \t]"))))
14332 (mapcar 'org-entry-restore-space values)))
14334 (defun org-entry-put-multivalued-property (pom property &rest values)
14335 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14336 VALUES should be a list of strings. Spaces will be protected."
14337 (org-entry-put pom property
14338 (mapconcat 'org-entry-protect-space values " "))
14339 (let* ((value (org-entry-get pom property))
14340 (values (and value (org-split-string value "[ \t]"))))
14341 (mapcar 'org-entry-restore-space values)))
14343 (defun org-entry-protect-space (s)
14344 "Protect spaces and newline in string S."
14345 (while (string-match " " s)
14346 (setq s (replace-match "%20" t t s)))
14347 (while (string-match "\n" s)
14348 (setq s (replace-match "%0A" t t s)))
14351 (defun org-entry-restore-space (s)
14352 "Restore spaces and newline in string S."
14353 (while (string-match "%20" s)
14354 (setq s (replace-match " " t t s)))
14355 (while (string-match "%0A" s)
14356 (setq s (replace-match "\n" t t s)))
14359 (defvar org-entry-property-inherited-from (make-marker)
14360 "Marker pointing to the entry from where a property was inherited.
14361 Each call to `org-entry-get-with-inheritance' will set this marker to the
14362 location of the entry where the inheritance search matched. If there was
14363 no match, the marker will point nowhere.
14364 Note that also `org-entry-get' calls this function, if the INHERIT flag
14365 is set.")
14367 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14368 "Get entry property, and search higher levels if not present.
14369 The search will stop at the first ancestor which has the property defined.
14370 If the value found is \"nil\", return nil to show that the property
14371 should be considered as undefined (this is the meaning of nil here).
14372 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14373 (move-marker org-entry-property-inherited-from nil)
14374 (let (tmp)
14375 (unless (org-before-first-heading-p)
14376 (save-excursion
14377 (save-restriction
14378 (widen)
14379 (catch 'ex
14380 (while t
14381 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14382 (org-back-to-heading t)
14383 (move-marker org-entry-property-inherited-from (point))
14384 (throw 'ex tmp))
14385 (or (org-up-heading-safe) (throw 'ex nil)))))))
14386 (setq tmp (or tmp
14387 (cdr (assoc property org-file-properties))
14388 (cdr (assoc property org-global-properties))
14389 (cdr (assoc property org-global-properties-fixed))))
14390 (if literal-nil tmp (org-not-nil tmp))))
14392 (defvar org-property-changed-functions nil
14393 "Hook called when the value of a property has changed.
14394 Each hook function should accept two arguments, the name of the property
14395 and the new value.")
14397 (defun org-entry-put (pom property value)
14398 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14399 (org-with-point-at pom
14400 (org-back-to-heading t)
14401 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14402 range)
14403 (cond
14404 ((equal property "TODO")
14405 (when (and (stringp value) (string-match "\\S-" value)
14406 (not (member value org-todo-keywords-1)))
14407 (error "\"%s\" is not a valid TODO state" value))
14408 (if (or (not value)
14409 (not (string-match "\\S-" value)))
14410 (setq value 'none))
14411 (org-todo value)
14412 (org-set-tags nil 'align))
14413 ((equal property "PRIORITY")
14414 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14415 (string-to-char value) ?\ ))
14416 (org-set-tags nil 'align))
14417 ((equal property "SCHEDULED")
14418 (if (re-search-forward org-scheduled-time-regexp end t)
14419 (cond
14420 ((eq value 'earlier) (org-timestamp-change -1 'day))
14421 ((eq value 'later) (org-timestamp-change 1 'day))
14422 (t (call-interactively 'org-schedule)))
14423 (call-interactively 'org-schedule)))
14424 ((equal property "DEADLINE")
14425 (if (re-search-forward org-deadline-time-regexp end t)
14426 (cond
14427 ((eq value 'earlier) (org-timestamp-change -1 'day))
14428 ((eq value 'later) (org-timestamp-change 1 'day))
14429 (t (call-interactively 'org-deadline)))
14430 (call-interactively 'org-deadline)))
14431 ((member property org-special-properties)
14432 (error "The %s property can not yet be set with `org-entry-put'"
14433 property))
14434 (t ; a non-special property
14435 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14436 (setq range (org-get-property-block beg end 'force))
14437 (goto-char (car range))
14438 (if (re-search-forward
14439 (org-re-property property) (cdr range) t)
14440 (progn
14441 (delete-region (match-beginning 0) (match-end 0))
14442 (goto-char (match-beginning 0)))
14443 (goto-char (cdr range))
14444 (insert "\n")
14445 (backward-char 1)
14446 (org-indent-line-function))
14447 (insert ":" property ":")
14448 (and value (insert " " value))
14449 (org-indent-line-function)))))
14450 (run-hook-with-args 'org-property-changed-functions property value)))
14452 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14453 "Get all property keys in the current buffer.
14454 With INCLUDE-SPECIALS, also list the special properties that reflect things
14455 like tags and TODO state.
14456 With INCLUDE-DEFAULTS, also include properties that has special meaning
14457 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14458 and others.
14459 With INCLUDE-COLUMNS, also include property names given in COLUMN
14460 formats in the current buffer."
14461 (let (rtn range cfmt s p)
14462 (save-excursion
14463 (save-restriction
14464 (widen)
14465 (goto-char (point-min))
14466 (while (re-search-forward org-property-start-re nil t)
14467 (setq range (org-get-property-block))
14468 (goto-char (car range))
14469 (while (re-search-forward
14470 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14471 (cdr range) t)
14472 (add-to-list 'rtn (org-match-string-no-properties 1)))
14473 (outline-next-heading))))
14475 (when include-specials
14476 (setq rtn (append org-special-properties rtn)))
14478 (when include-defaults
14479 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14480 (add-to-list 'rtn org-effort-property))
14482 (when include-columns
14483 (save-excursion
14484 (save-restriction
14485 (widen)
14486 (goto-char (point-min))
14487 (while (re-search-forward
14488 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14489 nil t)
14490 (setq cfmt (match-string 2) s 0)
14491 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14492 cfmt s)
14493 (setq s (match-end 0)
14494 p (match-string 1 cfmt))
14495 (unless (or (equal p "ITEM")
14496 (member p org-special-properties))
14497 (add-to-list 'rtn (match-string 1 cfmt))))))))
14499 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14501 (defun org-property-values (key)
14502 "Return a list of all values of property KEY in the current buffer."
14503 (save-excursion
14504 (save-restriction
14505 (widen)
14506 (goto-char (point-min))
14507 (let ((re (org-re-property key))
14508 values)
14509 (while (re-search-forward re nil t)
14510 (add-to-list 'values (org-trim (match-string 1))))
14511 (delete "" values)))))
14513 (defun org-insert-property-drawer ()
14514 "Insert a property drawer into the current entry."
14515 (org-back-to-heading t)
14516 (looking-at org-outline-regexp)
14517 (let ((indent (if org-adapt-indentation
14518 (- (match-end 0) (match-beginning 0))
14520 (beg (point))
14521 (re (concat "^[ \t]*" org-keyword-time-regexp))
14522 end hiddenp)
14523 (outline-next-heading)
14524 (setq end (point))
14525 (goto-char beg)
14526 (while (re-search-forward re end t))
14527 (setq hiddenp (outline-invisible-p))
14528 (end-of-line 1)
14529 (and (equal (char-after) ?\n) (forward-char 1))
14530 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14531 (if (member (match-string 1) '("CLOCK:" ":END:"))
14532 ;; just skip this line
14533 (beginning-of-line 2)
14534 ;; Drawer start, find the end
14535 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14536 (beginning-of-line 1)))
14537 (org-skip-over-state-notes)
14538 (skip-chars-backward " \t\n\r")
14539 (if (eq (char-before) ?*) (forward-char 1))
14540 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14541 (beginning-of-line 0)
14542 (org-indent-to-column indent)
14543 (beginning-of-line 2)
14544 (org-indent-to-column indent)
14545 (beginning-of-line 0)
14546 (if hiddenp
14547 (save-excursion
14548 (org-back-to-heading t)
14549 (hide-entry))
14550 (org-flag-drawer t))))
14552 (defun org-insert-drawer (&optional arg drawer)
14553 "Insert a drawer at point.
14555 Optional argument DRAWER, when non-nil, is a string representing
14556 drawer's name. Otherwise, the user is prompted for a name.
14558 If a region is active, insert the drawer around that region
14559 instead.
14561 Point is left between drawer's boundaries."
14562 (interactive "P")
14563 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14564 "LOGBOOK"))
14565 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14566 ;; internally by Org. They are meant to be inserted
14567 ;; automatically.
14568 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14569 ;; Remove system drawers from list. Note: For some reason,
14570 ;; `org-completing-read' ignores the predicate while
14571 ;; `completing-read' handles it fine.
14572 (drawer (if arg "PROPERTIES"
14573 (or drawer
14574 (completing-read
14575 "Drawer: " org-drawers
14576 (lambda (d) (not (member d system-drawers))))))))
14577 (cond
14578 ;; With C-u, fall back on `org-insert-property-drawer'
14579 (arg (org-insert-property-drawer))
14580 ;; With an active region, insert a drawer at point.
14581 ((not (org-region-active-p))
14582 (progn
14583 (unless (bolp) (insert "\n"))
14584 (insert (format ":%s:\n\n:END:\n" drawer))
14585 (forward-line -2)))
14586 ;; Otherwise, insert the drawer at point
14588 (let ((rbeg (region-beginning))
14589 (rend (copy-marker (region-end))))
14590 (unwind-protect
14591 (progn
14592 (goto-char rbeg)
14593 (beginning-of-line)
14594 (when (save-excursion
14595 (re-search-forward org-outline-regexp-bol rend t))
14596 (error "Drawers cannot contain headlines"))
14597 ;; Position point at the beginning of the first
14598 ;; non-blank line in region. Insert drawer's opening
14599 ;; there, then indent it.
14600 (org-skip-whitespace)
14601 (beginning-of-line)
14602 (insert ":" drawer ":\n")
14603 (forward-line -1)
14604 (indent-for-tab-command)
14605 ;; Move point to the beginning of the first blank line
14606 ;; after the last non-blank line in region. Insert
14607 ;; drawer's closing, then indent it.
14608 (goto-char rend)
14609 (skip-chars-backward " \r\t\n")
14610 (insert "\n:END:")
14611 (indent-for-tab-command)
14612 (unless (eolp) (insert "\n")))
14613 ;; Clear marker, whatever the outcome of insertion is.
14614 (set-marker rend nil)))))))
14616 (defvar org-property-set-functions-alist nil
14617 "Property set function alist.
14618 Each entry should have the following format:
14620 (PROPERTY . READ-FUNCTION)
14622 The read function will be called with the same argument as
14623 `org-completing-read'.")
14625 (defun org-set-property-function (property)
14626 "Get the function that should be used to set PROPERTY.
14627 This is computed according to `org-property-set-functions-alist'."
14628 (or (cdr (assoc property org-property-set-functions-alist))
14629 'org-completing-read))
14631 (defun org-read-property-value (property)
14632 "Read PROPERTY value from user."
14633 (let* ((completion-ignore-case t)
14634 (allowed (org-property-get-allowed-values nil property 'table))
14635 (cur (org-entry-get nil property))
14636 (prompt (concat property " value"
14637 (if (and cur (string-match "\\S-" cur))
14638 (concat " [" cur "]") "") ": "))
14639 (set-function (org-set-property-function property))
14640 (val (if allowed
14641 (funcall set-function prompt allowed nil
14642 (not (get-text-property 0 'org-unrestricted
14643 (caar allowed))))
14644 (let (org-completion-use-ido org-completion-use-iswitchb)
14645 (funcall set-function prompt
14646 (mapcar 'list (org-property-values property))
14647 nil nil "" nil cur)))))
14648 (if (equal val "")
14650 val)))
14652 (defvar org-last-set-property nil)
14653 (defun org-read-property-name ()
14654 "Read a property name."
14655 (let* ((completion-ignore-case t)
14656 (keys (org-buffer-property-keys nil t t))
14657 (default-prop (or (save-excursion
14658 (save-match-data
14659 (beginning-of-line)
14660 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14661 (null (string= (match-string 1) "END"))
14662 (match-string 1))))
14663 org-last-set-property))
14664 (property (org-icompleting-read
14665 (concat "Property"
14666 (if default-prop (concat " [" default-prop "]") "")
14667 ": ")
14668 (mapcar 'list keys)
14669 nil nil nil nil
14670 default-prop
14672 (if (member property keys)
14673 property
14674 (or (cdr (assoc (downcase property)
14675 (mapcar (lambda (x) (cons (downcase x) x))
14676 keys)))
14677 property))))
14679 (defun org-set-property (property value)
14680 "In the current entry, set PROPERTY to VALUE.
14681 When called interactively, this will prompt for a property name, offering
14682 completion on existing and default properties. And then it will prompt
14683 for a value, offering completion either on allowed values (via an inherited
14684 xxx_ALL property) or on existing values in other instances of this property
14685 in the current file."
14686 (interactive (list nil nil))
14687 (let* ((property (or property (org-read-property-name)))
14688 (value (or value (org-read-property-value property)))
14689 (fn (assoc property org-properties-postprocess-alist)))
14690 (setq org-last-set-property property)
14691 ;; Possibly postprocess the inserted value:
14692 (when fn (setq value (funcall (cadr fn) value)))
14693 (unless (equal (org-entry-get nil property) value)
14694 (org-entry-put nil property value))))
14696 (defun org-delete-property (property)
14697 "In the current entry, delete PROPERTY."
14698 (interactive
14699 (let* ((completion-ignore-case t)
14700 (prop (org-icompleting-read "Property: "
14701 (org-entry-properties nil 'standard))))
14702 (list prop)))
14703 (message "Property %s %s" property
14704 (if (org-entry-delete nil property)
14705 "deleted"
14706 "was not present in the entry")))
14708 (defun org-delete-property-globally (property)
14709 "Remove PROPERTY globally, from all entries."
14710 (interactive
14711 (let* ((completion-ignore-case t)
14712 (prop (org-icompleting-read
14713 "Globally remove property: "
14714 (mapcar 'list (org-buffer-property-keys)))))
14715 (list prop)))
14716 (save-excursion
14717 (save-restriction
14718 (widen)
14719 (goto-char (point-min))
14720 (let ((cnt 0))
14721 (while (re-search-forward
14722 (org-re-property property)
14723 nil t)
14724 (setq cnt (1+ cnt))
14725 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14726 (message "Property \"%s\" removed from %d entries" property cnt)))))
14728 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14730 (defun org-compute-property-at-point ()
14731 "Compute the property at point.
14732 This looks for an enclosing column format, extracts the operator and
14733 then applies it to the property in the column format's scope."
14734 (interactive)
14735 (unless (org-at-property-p)
14736 (error "Not at a property"))
14737 (let ((prop (org-match-string-no-properties 2)))
14738 (org-columns-get-format-and-top-level)
14739 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14740 (error "No operator defined for property %s" prop))
14741 (org-columns-compute prop)))
14743 (defvar org-property-allowed-value-functions nil
14744 "Hook for functions supplying allowed values for a specific property.
14745 The functions must take a single argument, the name of the property, and
14746 return a flat list of allowed values. If \":ETC\" is one of
14747 the values, this means that these values are intended as defaults for
14748 completion, but that other values should be allowed too.
14749 The functions must return nil if they are not responsible for this
14750 property.")
14752 (defun org-property-get-allowed-values (pom property &optional table)
14753 "Get allowed values for the property PROPERTY.
14754 When TABLE is non-nil, return an alist that can directly be used for
14755 completion."
14756 (let (vals)
14757 (cond
14758 ((equal property "TODO")
14759 (setq vals (org-with-point-at pom
14760 (append org-todo-keywords-1 '("")))))
14761 ((equal property "PRIORITY")
14762 (let ((n org-lowest-priority))
14763 (while (>= n org-highest-priority)
14764 (push (char-to-string n) vals)
14765 (setq n (1- n)))))
14766 ((member property org-special-properties))
14767 ((setq vals (run-hook-with-args-until-success
14768 'org-property-allowed-value-functions property)))
14770 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14771 (when (and vals (string-match "\\S-" vals))
14772 (setq vals (car (read-from-string (concat "(" vals ")"))))
14773 (setq vals (mapcar (lambda (x)
14774 (cond ((stringp x) x)
14775 ((numberp x) (number-to-string x))
14776 ((symbolp x) (symbol-name x))
14777 (t "???")))
14778 vals)))))
14779 (when (member ":ETC" vals)
14780 (setq vals (remove ":ETC" vals))
14781 (org-add-props (car vals) '(org-unrestricted t)))
14782 (if table (mapcar 'list vals) vals)))
14784 (defun org-property-previous-allowed-value (&optional previous)
14785 "Switch to the next allowed value for this property."
14786 (interactive)
14787 (org-property-next-allowed-value t))
14789 (defun org-property-next-allowed-value (&optional previous)
14790 "Switch to the next allowed value for this property."
14791 (interactive)
14792 (unless (org-at-property-p)
14793 (error "Not at a property"))
14794 (let* ((key (match-string 2))
14795 (value (match-string 3))
14796 (allowed (or (org-property-get-allowed-values (point) key)
14797 (and (member value '("[ ]" "[-]" "[X]"))
14798 '("[ ]" "[X]"))))
14799 nval)
14800 (unless allowed
14801 (error "Allowed values for this property have not been defined"))
14802 (if previous (setq allowed (reverse allowed)))
14803 (if (member value allowed)
14804 (setq nval (car (cdr (member value allowed)))))
14805 (setq nval (or nval (car allowed)))
14806 (if (equal nval value)
14807 (error "Only one allowed value for this property"))
14808 (org-at-property-p)
14809 (replace-match (concat " :" key ": " nval) t t)
14810 (org-indent-line-function)
14811 (beginning-of-line 1)
14812 (skip-chars-forward " \t")
14813 (run-hook-with-args 'org-property-changed-functions key nval)))
14815 (defun org-find-olp (path &optional this-buffer)
14816 "Return a marker pointing to the entry at outline path OLP.
14817 If anything goes wrong, throw an error.
14818 You can wrap this call to catch the error like this:
14820 (condition-case msg
14821 (org-mobile-locate-entry (match-string 4))
14822 (error (nth 1 msg)))
14824 The return value will then be either a string with the error message,
14825 or a marker if everything is OK.
14827 If THIS-BUFFER is set, the outline path does not contain a file,
14828 only headings."
14829 (let* ((file (if this-buffer buffer-file-name (pop path)))
14830 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14831 (level 1)
14832 (lmin 1)
14833 (lmax 1)
14834 limit re end found pos heading cnt flevel)
14835 (unless buffer (error "File not found :%s" file))
14836 (with-current-buffer buffer
14837 (save-excursion
14838 (save-restriction
14839 (widen)
14840 (setq limit (point-max))
14841 (goto-char (point-min))
14842 (while (setq heading (pop path))
14843 (setq re (format org-complex-heading-regexp-format
14844 (regexp-quote heading)))
14845 (setq cnt 0 pos (point))
14846 (while (re-search-forward re end t)
14847 (setq level (- (match-end 1) (match-beginning 1)))
14848 (if (and (>= level lmin) (<= level lmax))
14849 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14850 (when (= cnt 0) (error "Heading not found on level %d: %s"
14851 lmax heading))
14852 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14853 lmax heading))
14854 (goto-char found)
14855 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14856 (setq end (save-excursion (org-end-of-subtree t t))))
14857 (when (org-at-heading-p)
14858 (move-marker (make-marker) (point))))))))
14860 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14861 "Find node HEADING in BUFFER.
14862 Return a marker to the heading if it was found, or nil if not.
14863 If POS-ONLY is set, return just the position instead of a marker.
14865 The heading text must match exact, but it may have a TODO keyword,
14866 a priority cookie and tags in the standard locations."
14867 (with-current-buffer (or buffer (current-buffer))
14868 (save-excursion
14869 (save-restriction
14870 (widen)
14871 (goto-char (point-min))
14872 (let (case-fold-search)
14873 (if (re-search-forward
14874 (format org-complex-heading-regexp-format
14875 (regexp-quote heading)) nil t)
14876 (if pos-only
14877 (match-beginning 0)
14878 (move-marker (make-marker) (match-beginning 0)))))))))
14880 (defun org-find-exact-heading-in-directory (heading &optional dir)
14881 "Find Org node headline HEADING in all .org files in directory DIR.
14882 When the target headline is found, return a marker to this location."
14883 (let ((files (directory-files (or dir default-directory)
14884 nil "\\`[^.#].*\\.org\\'"))
14885 file visiting m buffer)
14886 (catch 'found
14887 (while (setq file (pop files))
14888 (message "trying %s" file)
14889 (setq visiting (org-find-base-buffer-visiting file))
14890 (setq buffer (or visiting (find-file-noselect file)))
14891 (setq m (org-find-exact-headline-in-buffer
14892 heading buffer))
14893 (when (and (not m) (not visiting)) (kill-buffer buffer))
14894 (and m (throw 'found m))))))
14896 (defun org-find-entry-with-id (ident)
14897 "Locate the entry that contains the ID property with exact value IDENT.
14898 IDENT can be a string, a symbol or a number, this function will search for
14899 the string representation of it.
14900 Return the position where this entry starts, or nil if there is no such entry."
14901 (interactive "sID: ")
14902 (let ((id (cond
14903 ((stringp ident) ident)
14904 ((symbol-name ident) (symbol-name ident))
14905 ((numberp ident) (number-to-string ident))
14906 (t (error "IDENT %s must be a string, symbol or number" ident))))
14907 (case-fold-search nil))
14908 (save-excursion
14909 (save-restriction
14910 (widen)
14911 (goto-char (point-min))
14912 (when (re-search-forward
14913 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14914 nil t)
14915 (org-back-to-heading t)
14916 (point))))))
14918 ;;;; Timestamps
14920 (defvar org-last-changed-timestamp nil)
14921 (defvar org-last-inserted-timestamp nil
14922 "The last time stamp inserted with `org-insert-time-stamp'.")
14923 (defvar org-time-was-given) ; dynamically scoped parameter
14924 (defvar org-end-time-was-given) ; dynamically scoped parameter
14925 (defvar org-ts-what) ; dynamically scoped parameter
14927 (defun org-time-stamp (arg &optional inactive)
14928 "Prompt for a date/time and insert a time stamp.
14929 If the user specifies a time like HH:MM, or if this command is called
14930 with a prefix argument, the time stamp will contain date and time.
14931 Otherwise, only the date will be included. All parts of a date not
14932 specified by the user will be filled in from the current date/time.
14933 So if you press just return without typing anything, the time stamp
14934 will represent the current date/time. If there is already a timestamp
14935 at the cursor, it will be modified."
14936 (interactive "P")
14937 (let* ((ts nil)
14938 (default-time
14939 ;; Default time is either today, or, when entering a range,
14940 ;; the range start.
14941 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14942 (save-excursion
14943 (re-search-backward
14944 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14945 (- (point) 20) t)))
14946 (apply 'encode-time (org-parse-time-string (match-string 1)))
14947 (current-time)))
14948 (default-input (and ts (org-get-compact-tod ts)))
14949 (repeater (save-excursion
14950 (save-match-data
14951 (beginning-of-line)
14952 (when (re-search-forward
14953 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14954 (save-excursion (progn (end-of-line) (point))) t)
14955 (match-string 0)))))
14956 org-time-was-given org-end-time-was-given time)
14957 (cond
14958 ((and (org-at-timestamp-p t)
14959 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14960 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14961 (insert "--")
14962 (setq time (let ((this-command this-command))
14963 (org-read-date arg 'totime nil nil
14964 default-time default-input inactive)))
14965 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14966 ((org-at-timestamp-p t)
14967 (setq time (let ((this-command this-command))
14968 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14969 (when (org-at-timestamp-p t) ; just to get the match data
14970 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14971 (replace-match "")
14972 (setq org-last-changed-timestamp
14973 (org-insert-time-stamp
14974 time (or org-time-was-given arg)
14975 inactive nil nil (list org-end-time-was-given)))
14976 (when repeater (goto-char (1- (point))) (insert " " repeater)
14977 (setq org-last-changed-timestamp
14978 (concat (substring org-last-inserted-timestamp 0 -1)
14979 " " repeater ">"))))
14980 (message "Timestamp updated"))
14982 (setq time (let ((this-command this-command))
14983 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14984 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14985 nil nil (list org-end-time-was-given))))))
14987 ;; FIXME: can we use this for something else, like computing time differences?
14988 (defun org-get-compact-tod (s)
14989 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14990 (let* ((t1 (match-string 1 s))
14991 (h1 (string-to-number (match-string 2 s)))
14992 (m1 (string-to-number (match-string 3 s)))
14993 (t2 (and (match-end 4) (match-string 5 s)))
14994 (h2 (and t2 (string-to-number (match-string 6 s))))
14995 (m2 (and t2 (string-to-number (match-string 7 s))))
14996 dh dm)
14997 (if (not t2)
14999 (setq dh (- h2 h1) dm (- m2 m1))
15000 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15001 (concat t1 "+" (number-to-string dh)
15002 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15004 (defun org-time-stamp-inactive (&optional arg)
15005 "Insert an inactive time stamp.
15006 An inactive time stamp is enclosed in square brackets instead of angle
15007 brackets. It is inactive in the sense that it does not trigger agenda entries,
15008 does not link to the calendar and cannot be changed with the S-cursor keys.
15009 So these are more for recording a certain time/date."
15010 (interactive "P")
15011 (org-time-stamp arg 'inactive))
15013 (defvar org-date-ovl (make-overlay 1 1))
15014 (overlay-put org-date-ovl 'face 'org-warning)
15015 (org-detach-overlay org-date-ovl)
15017 (defvar org-ans1) ; dynamically scoped parameter
15018 (defvar org-ans2) ; dynamically scoped parameter
15020 (defvar org-plain-time-of-day-regexp) ; defined below
15022 (defvar org-overriding-default-time nil) ; dynamically scoped
15023 (defvar org-read-date-overlay nil)
15024 (defvar org-dcst nil) ; dynamically scoped
15025 (defvar org-read-date-history nil)
15026 (defvar org-read-date-final-answer nil)
15027 (defvar org-read-date-analyze-futurep nil)
15028 (defvar org-read-date-analyze-forced-year nil)
15029 (defvar org-read-date-inactive)
15031 (defun org-read-date (&optional org-with-time to-time from-string prompt
15032 default-time default-input inactive)
15033 "Read a date, possibly a time, and make things smooth for the user.
15034 The prompt will suggest to enter an ISO date, but you can also enter anything
15035 which will at least partially be understood by `parse-time-string'.
15036 Unrecognized parts of the date will default to the current day, month, year,
15037 hour and minute. If this command is called to replace a timestamp at point,
15038 or to enter the second timestamp of a range, the default time is taken
15039 from the existing stamp. Furthermore, the command prefers the future,
15040 so if you are giving a date where the year is not given, and the day-month
15041 combination is already past in the current year, it will assume you
15042 mean next year. For details, see the manual. A few examples:
15044 3-2-5 --> 2003-02-05
15045 feb 15 --> currentyear-02-15
15046 2/15 --> currentyear-02-15
15047 sep 12 9 --> 2009-09-12
15048 12:45 --> today 12:45
15049 22 sept 0:34 --> currentyear-09-22 0:34
15050 12 --> currentyear-currentmonth-12
15051 Fri --> nearest Friday (today or later)
15052 etc.
15054 Furthermore you can specify a relative date by giving, as the *first* thing
15055 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15056 change in days weeks, months, years.
15057 With a single plus or minus, the date is relative to today. With a double
15058 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15059 +4d --> four days from today
15060 +4 --> same as above
15061 +2w --> two weeks from today
15062 ++5 --> five days from default date
15064 The function understands only English month and weekday abbreviations.
15066 While prompting, a calendar is popped up - you can also select the
15067 date with the mouse (button 1). The calendar shows a period of three
15068 months. To scroll it to other months, use the keys `>' and `<'.
15069 If you don't like the calendar, turn it off with
15070 \(setq org-read-date-popup-calendar nil)
15072 With optional argument TO-TIME, the date will immediately be converted
15073 to an internal time.
15074 With an optional argument WITH-TIME, the prompt will suggest to also
15075 insert a time. Note that when WITH-TIME is not set, you can still
15076 enter a time, and this function will inform the calling routine about
15077 this change. The calling routine may then choose to change the format
15078 used to insert the time stamp into the buffer to include the time.
15079 With optional argument FROM-STRING, read from this string instead from
15080 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15081 the time/date that is used for everything that is not specified by the
15082 user."
15083 (require 'parse-time)
15084 (let* ((org-time-stamp-rounding-minutes
15085 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15086 (org-dcst org-display-custom-times)
15087 (ct (org-current-time))
15088 (org-def (or org-overriding-default-time default-time ct))
15089 (org-defdecode (decode-time org-def))
15090 (dummy (progn
15091 (when (< (nth 2 org-defdecode) org-extend-today-until)
15092 (setcar (nthcdr 2 org-defdecode) -1)
15093 (setcar (nthcdr 1 org-defdecode) 59)
15094 (setq org-def (apply 'encode-time org-defdecode)
15095 org-defdecode (decode-time org-def)))))
15096 (calendar-frame-setup nil)
15097 (calendar-setup nil)
15098 (calendar-move-hook nil)
15099 (calendar-view-diary-initially-flag nil)
15100 (calendar-view-holidays-initially-flag nil)
15101 (timestr (format-time-string
15102 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15103 (prompt (concat (if prompt (concat prompt " ") "")
15104 (format "Date+time [%s]: " timestr)))
15105 ans (org-ans0 "") org-ans1 org-ans2 final)
15107 (cond
15108 (from-string (setq ans from-string))
15109 (org-read-date-popup-calendar
15110 (save-excursion
15111 (save-window-excursion
15112 (calendar)
15113 (unwind-protect
15114 (progn
15115 (calendar-forward-day (- (time-to-days org-def)
15116 (calendar-absolute-from-gregorian
15117 (calendar-current-date))))
15118 (org-eval-in-calendar nil t)
15119 (let* ((old-map (current-local-map))
15120 (map (copy-keymap calendar-mode-map))
15121 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15122 (org-defkey map (kbd "RET") 'org-calendar-select)
15123 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15124 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15125 (org-defkey minibuffer-local-map [(meta shift left)]
15126 (lambda () (interactive)
15127 (org-eval-in-calendar '(calendar-backward-month 1))))
15128 (org-defkey minibuffer-local-map [(meta shift right)]
15129 (lambda () (interactive)
15130 (org-eval-in-calendar '(calendar-forward-month 1))))
15131 (org-defkey minibuffer-local-map [(meta shift up)]
15132 (lambda () (interactive)
15133 (org-eval-in-calendar '(calendar-backward-year 1))))
15134 (org-defkey minibuffer-local-map [(meta shift down)]
15135 (lambda () (interactive)
15136 (org-eval-in-calendar '(calendar-forward-year 1))))
15137 (org-defkey minibuffer-local-map [?\e (shift left)]
15138 (lambda () (interactive)
15139 (org-eval-in-calendar '(calendar-backward-month 1))))
15140 (org-defkey minibuffer-local-map [?\e (shift right)]
15141 (lambda () (interactive)
15142 (org-eval-in-calendar '(calendar-forward-month 1))))
15143 (org-defkey minibuffer-local-map [?\e (shift up)]
15144 (lambda () (interactive)
15145 (org-eval-in-calendar '(calendar-backward-year 1))))
15146 (org-defkey minibuffer-local-map [?\e (shift down)]
15147 (lambda () (interactive)
15148 (org-eval-in-calendar '(calendar-forward-year 1))))
15149 (org-defkey minibuffer-local-map [(shift up)]
15150 (lambda () (interactive)
15151 (org-eval-in-calendar '(calendar-backward-week 1))))
15152 (org-defkey minibuffer-local-map [(shift down)]
15153 (lambda () (interactive)
15154 (org-eval-in-calendar '(calendar-forward-week 1))))
15155 (org-defkey minibuffer-local-map [(shift left)]
15156 (lambda () (interactive)
15157 (org-eval-in-calendar '(calendar-backward-day 1))))
15158 (org-defkey minibuffer-local-map [(shift right)]
15159 (lambda () (interactive)
15160 (org-eval-in-calendar '(calendar-forward-day 1))))
15161 (org-defkey minibuffer-local-map ">"
15162 (lambda () (interactive)
15163 (org-eval-in-calendar '(scroll-calendar-left 1))))
15164 (org-defkey minibuffer-local-map "<"
15165 (lambda () (interactive)
15166 (org-eval-in-calendar '(scroll-calendar-right 1))))
15167 (org-defkey minibuffer-local-map "\C-v"
15168 (lambda () (interactive)
15169 (org-eval-in-calendar
15170 '(calendar-scroll-left-three-months 1))))
15171 (org-defkey minibuffer-local-map "\M-v"
15172 (lambda () (interactive)
15173 (org-eval-in-calendar
15174 '(calendar-scroll-right-three-months 1))))
15175 (run-hooks 'org-read-date-minibuffer-setup-hook)
15176 (unwind-protect
15177 (progn
15178 (use-local-map map)
15179 (setq org-read-date-inactive inactive)
15180 (add-hook 'post-command-hook 'org-read-date-display)
15181 (setq org-ans0 (read-string prompt default-input
15182 'org-read-date-history nil))
15183 ;; org-ans0: from prompt
15184 ;; org-ans1: from mouse click
15185 ;; org-ans2: from calendar motion
15186 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15187 (remove-hook 'post-command-hook 'org-read-date-display)
15188 (use-local-map old-map)
15189 (when org-read-date-overlay
15190 (delete-overlay org-read-date-overlay)
15191 (setq org-read-date-overlay nil)))))
15192 (bury-buffer "*Calendar*")))))
15194 (t ; Naked prompt only
15195 (unwind-protect
15196 (setq ans (read-string prompt default-input
15197 'org-read-date-history timestr))
15198 (when org-read-date-overlay
15199 (delete-overlay org-read-date-overlay)
15200 (setq org-read-date-overlay nil)))))
15202 (setq final (org-read-date-analyze ans org-def org-defdecode))
15204 (when org-read-date-analyze-forced-year
15205 (message "Year was forced into %s"
15206 (if org-read-date-force-compatible-dates
15207 "compatible range (1970-2037)"
15208 "range representable on this machine"))
15209 (ding))
15211 ;; One round trip to get rid of 34th of August and stuff like that....
15212 (setq final (decode-time (apply 'encode-time final)))
15214 (setq org-read-date-final-answer ans)
15216 (if to-time
15217 (apply 'encode-time final)
15218 (if (and (boundp 'org-time-was-given) org-time-was-given)
15219 (format "%04d-%02d-%02d %02d:%02d"
15220 (nth 5 final) (nth 4 final) (nth 3 final)
15221 (nth 2 final) (nth 1 final))
15222 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15224 (defvar org-def)
15225 (defvar org-defdecode)
15226 (defvar org-with-time)
15227 (defun org-read-date-display ()
15228 "Display the current date prompt interpretation in the minibuffer."
15229 (when org-read-date-display-live
15230 (when org-read-date-overlay
15231 (delete-overlay org-read-date-overlay))
15232 (let ((p (point)))
15233 (end-of-line 1)
15234 (while (not (equal (buffer-substring
15235 (max (point-min) (- (point) 4)) (point))
15236 " "))
15237 (insert " "))
15238 (goto-char p))
15239 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15240 " " (or org-ans1 org-ans2)))
15241 (org-end-time-was-given nil)
15242 (f (org-read-date-analyze ans org-def org-defdecode))
15243 (fmts (if org-dcst
15244 org-time-stamp-custom-formats
15245 org-time-stamp-formats))
15246 (fmt (if (or org-with-time
15247 (and (boundp 'org-time-was-given) org-time-was-given))
15248 (cdr fmts)
15249 (car fmts)))
15250 (txt (format-time-string fmt (apply 'encode-time f)))
15251 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15252 (txt (concat "=> " txt)))
15253 (when (and org-end-time-was-given
15254 (string-match org-plain-time-of-day-regexp txt))
15255 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15256 org-end-time-was-given
15257 (substring txt (match-end 0)))))
15258 (when org-read-date-analyze-futurep
15259 (setq txt (concat txt " (=>F)")))
15260 (setq org-read-date-overlay
15261 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15262 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15264 (defun org-read-date-analyze (ans org-def org-defdecode)
15265 "Analyze the combined answer of the date prompt."
15266 ;; FIXME: cleanup and comment
15267 (let ((nowdecode (decode-time (current-time)))
15268 delta deltan deltaw deltadef year month day
15269 hour minute second wday pm h2 m2 tl wday1
15270 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15271 (setq org-read-date-analyze-futurep nil
15272 org-read-date-analyze-forced-year nil)
15273 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15274 (setq ans "+0"))
15276 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15277 (setq ans (replace-match "" t t ans)
15278 deltan (car delta)
15279 deltaw (nth 1 delta)
15280 deltadef (nth 2 delta)))
15282 ;; Check if there is an iso week date in there
15283 ;; If yes, store the info and postpone interpreting it until the rest
15284 ;; of the parsing is done
15285 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15286 (setq iso-year (if (match-end 1)
15287 (org-small-year-to-year
15288 (string-to-number (match-string 1 ans))))
15289 iso-weekday (if (match-end 3)
15290 (string-to-number (match-string 3 ans)))
15291 iso-week (string-to-number (match-string 2 ans)))
15292 (setq ans (replace-match "" t t ans)))
15294 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15295 (when (string-match
15296 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15297 (setq year (if (match-end 2)
15298 (string-to-number (match-string 2 ans))
15299 (progn (setq kill-year t)
15300 (string-to-number (format-time-string "%Y"))))
15301 month (string-to-number (match-string 3 ans))
15302 day (string-to-number (match-string 4 ans)))
15303 (if (< year 100) (setq year (+ 2000 year)))
15304 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15305 t nil ans)))
15307 ;; Help matching dotted european dates
15308 (when (string-match
15309 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15310 (setq year (if (match-end 3)
15311 (string-to-number (match-string 3 ans))
15312 (progn (setq kill-year t)
15313 (string-to-number (format-time-string "%Y"))))
15314 day (string-to-number (match-string 1 ans))
15315 month (string-to-number (match-string 2 ans))
15316 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15317 t nil ans)))
15319 ;; Help matching american dates, like 5/30 or 5/30/7
15320 (when (string-match
15321 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15322 (setq year (if (match-end 4)
15323 (string-to-number (match-string 4 ans))
15324 (progn (setq kill-year t)
15325 (string-to-number (format-time-string "%Y"))))
15326 month (string-to-number (match-string 1 ans))
15327 day (string-to-number (match-string 2 ans)))
15328 (if (< year 100) (setq year (+ 2000 year)))
15329 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15330 t nil ans)))
15331 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15332 ;; If there is a time with am/pm, and *no* time without it, we convert
15333 ;; so that matching will be successful.
15334 (loop for i from 1 to 2 do ; twice, for end time as well
15335 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15336 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15337 (setq hour (string-to-number (match-string 1 ans))
15338 minute (if (match-end 3)
15339 (string-to-number (match-string 3 ans))
15341 pm (equal ?p
15342 (string-to-char (downcase (match-string 4 ans)))))
15343 (if (and (= hour 12) (not pm))
15344 (setq hour 0)
15345 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15346 (setq ans (replace-match (format "%02d:%02d" hour minute)
15347 t t ans))))
15349 ;; Check if a time range is given as a duration
15350 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15351 (setq hour (string-to-number (match-string 1 ans))
15352 h2 (+ hour (string-to-number (match-string 3 ans)))
15353 minute (string-to-number (match-string 2 ans))
15354 m2 (+ minute (if (match-end 5) (string-to-number
15355 (match-string 5 ans))0)))
15356 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15357 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15358 t t ans)))
15360 ;; Check if there is a time range
15361 (when (boundp 'org-end-time-was-given)
15362 (setq org-time-was-given nil)
15363 (when (and (string-match org-plain-time-of-day-regexp ans)
15364 (match-end 8))
15365 (setq org-end-time-was-given (match-string 8 ans))
15366 (setq ans (concat (substring ans 0 (match-beginning 7))
15367 (substring ans (match-end 7))))))
15369 (setq tl (parse-time-string ans)
15370 day (or (nth 3 tl) (nth 3 org-defdecode))
15371 month (or (nth 4 tl)
15372 (if (and org-read-date-prefer-future
15373 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15374 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15375 (nth 4 org-defdecode)))
15376 year (or (and (not kill-year) (nth 5 tl))
15377 (if (and org-read-date-prefer-future
15378 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15379 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15380 (nth 5 org-defdecode)))
15381 hour (or (nth 2 tl) (nth 2 org-defdecode))
15382 minute (or (nth 1 tl) (nth 1 org-defdecode))
15383 second (or (nth 0 tl) 0)
15384 wday (nth 6 tl))
15386 (when (and (eq org-read-date-prefer-future 'time)
15387 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15388 (equal day (nth 3 nowdecode))
15389 (equal month (nth 4 nowdecode))
15390 (equal year (nth 5 nowdecode))
15391 (nth 2 tl)
15392 (or (< (nth 2 tl) (nth 2 nowdecode))
15393 (and (= (nth 2 tl) (nth 2 nowdecode))
15394 (nth 1 tl)
15395 (< (nth 1 tl) (nth 1 nowdecode)))))
15396 (setq day (1+ day)
15397 futurep t))
15399 ;; Special date definitions below
15400 (cond
15401 (iso-week
15402 ;; There was an iso week
15403 (require 'cal-iso)
15404 (setq futurep nil)
15405 (setq year (or iso-year year)
15406 day (or iso-weekday wday 1)
15407 wday nil ; to make sure that the trigger below does not match
15408 iso-date (calendar-gregorian-from-absolute
15409 (calendar-absolute-from-iso
15410 (list iso-week day year))))
15411 ; FIXME: Should we also push ISO weeks into the future?
15412 ; (when (and org-read-date-prefer-future
15413 ; (not iso-year)
15414 ; (< (calendar-absolute-from-gregorian iso-date)
15415 ; (time-to-days (current-time))))
15416 ; (setq year (1+ year)
15417 ; iso-date (calendar-gregorian-from-absolute
15418 ; (calendar-absolute-from-iso
15419 ; (list iso-week day year)))))
15420 (setq month (car iso-date)
15421 year (nth 2 iso-date)
15422 day (nth 1 iso-date)))
15423 (deltan
15424 (setq futurep nil)
15425 (unless deltadef
15426 (let ((now (decode-time (current-time))))
15427 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15428 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15429 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15430 ((equal deltaw "m") (setq month (+ month deltan)))
15431 ((equal deltaw "y") (setq year (+ year deltan)))))
15432 ((and wday (not (nth 3 tl)))
15433 (setq futurep nil)
15434 ;; Weekday was given, but no day, so pick that day in the week
15435 ;; on or after the derived date.
15436 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15437 (unless (equal wday wday1)
15438 (setq day (+ day (% (- wday wday1 -7) 7))))))
15439 (if (and (boundp 'org-time-was-given)
15440 (nth 2 tl))
15441 (setq org-time-was-given t))
15442 (if (< year 100) (setq year (+ 2000 year)))
15443 ;; Check of the date is representable
15444 (if org-read-date-force-compatible-dates
15445 (progn
15446 (if (< year 1970)
15447 (setq year 1970 org-read-date-analyze-forced-year t))
15448 (if (> year 2037)
15449 (setq year 2037 org-read-date-analyze-forced-year t)))
15450 (condition-case nil
15451 (ignore (encode-time second minute hour day month year))
15452 (error
15453 (setq year (nth 5 org-defdecode))
15454 (setq org-read-date-analyze-forced-year t))))
15455 (setq org-read-date-analyze-futurep futurep)
15456 (list second minute hour day month year)))
15458 (defvar parse-time-weekdays)
15459 (defun org-read-date-get-relative (s today default)
15460 "Check string S for special relative date string.
15461 TODAY and DEFAULT are internal times, for today and for a default.
15462 Return shift list (N what def-flag)
15463 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15464 N is the number of WHATs to shift.
15465 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15466 the DEFAULT date rather than TODAY."
15467 (require 'parse-time)
15468 (when (and
15469 (string-match
15470 (concat
15471 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15472 "\\([0-9]+\\)?"
15473 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15474 "\\([ \t]\\|$\\)") s)
15475 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15476 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15477 (string-to-char (substring (match-string 1 s) -1))
15478 ?+))
15479 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15480 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15481 (what (if (match-end 3) (match-string 3 s) "d"))
15482 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15483 (date (if rel default today))
15484 (wday (nth 6 (decode-time date)))
15485 delta)
15486 (if wday1
15487 (progn
15488 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15489 (if (= dir ?-) (setq delta (- delta 7)))
15490 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15491 (list delta "d" rel))
15492 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15494 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15495 "Turn a user-specified date into the internal representation.
15496 The internal representation needed by the calendar is (month day year).
15497 This is a wrapper to handle the brain-dead convention in calendar that
15498 user function argument order change dependent on argument order."
15499 (if (boundp 'calendar-date-style)
15500 (cond
15501 ((eq calendar-date-style 'american)
15502 (list arg1 arg2 arg3))
15503 ((eq calendar-date-style 'european)
15504 (list arg2 arg1 arg3))
15505 ((eq calendar-date-style 'iso)
15506 (list arg2 arg3 arg1)))
15507 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15508 (if (org-bound-and-true-p european-calendar-style)
15509 (list arg2 arg1 arg3)
15510 (list arg1 arg2 arg3)))))
15512 (defun org-eval-in-calendar (form &optional keepdate)
15513 "Eval FORM in the calendar window and return to current window.
15514 Also, store the cursor date in variable org-ans2."
15515 (let ((sf (selected-frame))
15516 (sw (selected-window)))
15517 (select-window (get-buffer-window "*Calendar*" t))
15518 (eval form)
15519 (when (and (not keepdate) (calendar-cursor-to-date))
15520 (let* ((date (calendar-cursor-to-date))
15521 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15522 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15523 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15524 (select-window sw)
15525 (org-select-frame-set-input-focus sf)))
15527 (defun org-calendar-select ()
15528 "Return to `org-read-date' with the date currently selected.
15529 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15530 (interactive)
15531 (when (calendar-cursor-to-date)
15532 (let* ((date (calendar-cursor-to-date))
15533 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15534 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15535 (if (active-minibuffer-window) (exit-minibuffer))))
15537 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15538 "Insert a date stamp for the date given by the internal TIME.
15539 WITH-HM means use the stamp format that includes the time of the day.
15540 INACTIVE means use square brackets instead of angular ones, so that the
15541 stamp will not contribute to the agenda.
15542 PRE and POST are optional strings to be inserted before and after the
15543 stamp.
15544 The command returns the inserted time stamp."
15545 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15546 stamp)
15547 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15548 (insert-before-markers (or pre ""))
15549 (when (listp extra)
15550 (setq extra (car extra))
15551 (if (and (stringp extra)
15552 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15553 (setq extra (format "-%02d:%02d"
15554 (string-to-number (match-string 1 extra))
15555 (string-to-number (match-string 2 extra))))
15556 (setq extra nil)))
15557 (when extra
15558 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15559 (insert-before-markers (setq stamp (format-time-string fmt time)))
15560 (insert-before-markers (or post ""))
15561 (setq org-last-inserted-timestamp stamp)))
15563 (defun org-toggle-time-stamp-overlays ()
15564 "Toggle the use of custom time stamp formats."
15565 (interactive)
15566 (setq org-display-custom-times (not org-display-custom-times))
15567 (unless org-display-custom-times
15568 (let ((p (point-min)) (bmp (buffer-modified-p)))
15569 (while (setq p (next-single-property-change p 'display))
15570 (if (and (get-text-property p 'display)
15571 (eq (get-text-property p 'face) 'org-date))
15572 (remove-text-properties
15573 p (setq p (next-single-property-change p 'display))
15574 '(display t))))
15575 (set-buffer-modified-p bmp)))
15576 (if (featurep 'xemacs)
15577 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15578 (org-restart-font-lock)
15579 (setq org-table-may-need-update t)
15580 (if org-display-custom-times
15581 (message "Time stamps are overlaid with custom format")
15582 (message "Time stamp overlays removed")))
15584 (defun org-display-custom-time (beg end)
15585 "Overlay modified time stamp format over timestamp between BEG and END."
15586 (let* ((ts (buffer-substring beg end))
15587 t1 w1 with-hm tf time str w2 (off 0))
15588 (save-match-data
15589 (setq t1 (org-parse-time-string ts t))
15590 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15591 (setq off (- (match-end 0) (match-beginning 0)))))
15592 (setq end (- end off))
15593 (setq w1 (- end beg)
15594 with-hm (and (nth 1 t1) (nth 2 t1))
15595 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15596 time (org-fix-decoded-time t1)
15597 str (org-add-props
15598 (format-time-string
15599 (substring tf 1 -1) (apply 'encode-time time))
15600 nil 'mouse-face 'highlight)
15601 w2 (length str))
15602 (if (not (= w2 w1))
15603 (add-text-properties (1+ beg) (+ 2 beg)
15604 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15605 (if (featurep 'xemacs)
15606 (progn
15607 (put-text-property beg end 'invisible t)
15608 (put-text-property beg end 'end-glyph (make-glyph str)))
15609 (put-text-property beg end 'display str))))
15611 (defun org-translate-time (string)
15612 "Translate all timestamps in STRING to custom format.
15613 But do this only if the variable `org-display-custom-times' is set."
15614 (when org-display-custom-times
15615 (save-match-data
15616 (let* ((start 0)
15617 (re org-ts-regexp-both)
15618 t1 with-hm inactive tf time str beg end)
15619 (while (setq start (string-match re string start))
15620 (setq beg (match-beginning 0)
15621 end (match-end 0)
15622 t1 (save-match-data
15623 (org-parse-time-string (substring string beg end) t))
15624 with-hm (and (nth 1 t1) (nth 2 t1))
15625 inactive (equal (substring string beg (1+ beg)) "[")
15626 tf (funcall (if with-hm 'cdr 'car)
15627 org-time-stamp-custom-formats)
15628 time (org-fix-decoded-time t1)
15629 str (format-time-string
15630 (concat
15631 (if inactive "[" "<") (substring tf 1 -1)
15632 (if inactive "]" ">"))
15633 (apply 'encode-time time))
15634 string (replace-match str t t string)
15635 start (+ start (length str)))))))
15636 string)
15638 (defun org-fix-decoded-time (time)
15639 "Set 0 instead of nil for the first 6 elements of time.
15640 Don't touch the rest."
15641 (let ((n 0))
15642 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15644 (defun org-days-to-time (timestamp-string)
15645 "Difference between TIMESTAMP-STRING and now in days."
15646 (- (time-to-days (org-time-string-to-time timestamp-string))
15647 (time-to-days (current-time))))
15649 (defun org-deadline-close (timestamp-string &optional ndays)
15650 "Is the time in TIMESTAMP-STRING close to the current date?"
15651 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15652 (and (< (org-days-to-time timestamp-string) ndays)
15653 (not (org-entry-is-done-p))))
15655 (defun org-get-wdays (ts)
15656 "Get the deadline lead time appropriate for timestring TS."
15657 (cond
15658 ((<= org-deadline-warning-days 0)
15659 ;; 0 or negative, enforce this value no matter what
15660 (- org-deadline-warning-days))
15661 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15662 ;; lead time is specified.
15663 (floor (* (string-to-number (match-string 1 ts))
15664 (cdr (assoc (match-string 2 ts)
15665 '(("d" . 1) ("w" . 7)
15666 ("m" . 30.4) ("y" . 365.25)))))))
15667 ;; go for the default.
15668 (t org-deadline-warning-days)))
15670 (defun org-calendar-select-mouse (ev)
15671 "Return to `org-read-date' with the date currently selected.
15672 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15673 (interactive "e")
15674 (mouse-set-point ev)
15675 (when (calendar-cursor-to-date)
15676 (let* ((date (calendar-cursor-to-date))
15677 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15678 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15679 (if (active-minibuffer-window) (exit-minibuffer))))
15681 (defun org-check-deadlines (ndays)
15682 "Check if there are any deadlines due or past due.
15683 A deadline is considered due if it happens within `org-deadline-warning-days'
15684 days from today's date. If the deadline appears in an entry marked DONE,
15685 it is not shown. The prefix arg NDAYS can be used to test that many
15686 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15687 (interactive "P")
15688 (let* ((org-warn-days
15689 (cond
15690 ((equal ndays '(4)) 100000)
15691 (ndays (prefix-numeric-value ndays))
15692 (t (abs org-deadline-warning-days))))
15693 (case-fold-search nil)
15694 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15695 (callback
15696 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15698 (message "%d deadlines past-due or due within %d days"
15699 (org-occur regexp nil callback)
15700 org-warn-days)))
15702 (defun org-check-before-date (date)
15703 "Check if there are deadlines or scheduled entries before DATE."
15704 (interactive (list (org-read-date)))
15705 (let ((case-fold-search nil)
15706 (regexp (concat "\\<\\(" org-deadline-string
15707 "\\|" org-scheduled-string
15708 "\\) *<\\([^>]+\\)>"))
15709 (callback
15710 (lambda () (time-less-p
15711 (org-time-string-to-time (match-string 2))
15712 (org-time-string-to-time date)))))
15713 (message "%d entries before %s"
15714 (org-occur regexp nil callback) date)))
15716 (defun org-check-after-date (date)
15717 "Check if there are deadlines or scheduled entries after DATE."
15718 (interactive (list (org-read-date)))
15719 (let ((case-fold-search nil)
15720 (regexp (concat "\\<\\(" org-deadline-string
15721 "\\|" org-scheduled-string
15722 "\\) *<\\([^>]+\\)>"))
15723 (callback
15724 (lambda () (not
15725 (time-less-p
15726 (org-time-string-to-time (match-string 2))
15727 (org-time-string-to-time date))))))
15728 (message "%d entries after %s"
15729 (org-occur regexp nil callback) date)))
15731 (defun org-check-dates-range (start-date end-date)
15732 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15733 (interactive (list (org-read-date nil nil nil "Range starts")
15734 (org-read-date nil nil nil "Range end")))
15735 (let ((case-fold-search nil)
15736 (regexp (concat "\\<\\(" org-deadline-string
15737 "\\|" org-scheduled-string
15738 "\\) *<\\([^>]+\\)>"))
15739 (callback
15740 (lambda ()
15741 (let ((match (match-string 2)))
15742 (and
15743 (not (time-less-p
15744 (org-time-string-to-time match)
15745 (org-time-string-to-time start-date)))
15746 (time-less-p
15747 (org-time-string-to-time match)
15748 (org-time-string-to-time end-date)))))))
15749 (message "%d entries between %s and %s"
15750 (org-occur regexp nil callback) start-date end-date)))
15752 (defun org-evaluate-time-range (&optional to-buffer)
15753 "Evaluate a time range by computing the difference between start and end.
15754 Normally the result is just printed in the echo area, but with prefix arg
15755 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15756 If the time range is actually in a table, the result is inserted into the
15757 next column.
15758 For time difference computation, a year is assumed to be exactly 365
15759 days in order to avoid rounding problems."
15760 (interactive "P")
15762 (org-clock-update-time-maybe)
15763 (save-excursion
15764 (unless (org-at-date-range-p t)
15765 (goto-char (point-at-bol))
15766 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15767 (if (not (org-at-date-range-p t))
15768 (error "Not at a time-stamp range, and none found in current line")))
15769 (let* ((ts1 (match-string 1))
15770 (ts2 (match-string 2))
15771 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15772 (match-end (match-end 0))
15773 (time1 (org-time-string-to-time ts1))
15774 (time2 (org-time-string-to-time ts2))
15775 (t1 (org-float-time time1))
15776 (t2 (org-float-time time2))
15777 (diff (abs (- t2 t1)))
15778 (negative (< (- t2 t1) 0))
15779 ;; (ys (floor (* 365 24 60 60)))
15780 (ds (* 24 60 60))
15781 (hs (* 60 60))
15782 (fy "%dy %dd %02d:%02d")
15783 (fy1 "%dy %dd")
15784 (fd "%dd %02d:%02d")
15785 (fd1 "%dd")
15786 (fh "%02d:%02d")
15787 y d h m align)
15788 (if havetime
15789 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15791 d (floor (/ diff ds)) diff (mod diff ds)
15792 h (floor (/ diff hs)) diff (mod diff hs)
15793 m (floor (/ diff 60)))
15794 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15796 d (floor (+ (/ diff ds) 0.5))
15797 h 0 m 0))
15798 (if (not to-buffer)
15799 (message "%s" (org-make-tdiff-string y d h m))
15800 (if (org-at-table-p)
15801 (progn
15802 (goto-char match-end)
15803 (setq align t)
15804 (and (looking-at " *|") (goto-char (match-end 0))))
15805 (goto-char match-end))
15806 (if (looking-at
15807 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15808 (replace-match ""))
15809 (if negative (insert " -"))
15810 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15811 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15812 (insert " " (format fh h m))))
15813 (if align (org-table-align))
15814 (message "Time difference inserted")))))
15816 (defun org-make-tdiff-string (y d h m)
15817 (let ((fmt "")
15818 (l nil))
15819 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15820 l (push y l)))
15821 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15822 l (push d l)))
15823 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15824 l (push h l)))
15825 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15826 l (push m l)))
15827 (apply 'format fmt (nreverse l))))
15829 (defun org-time-string-to-time (s &optional buffer pos)
15830 (condition-case errdata
15831 (apply 'encode-time (org-parse-time-string s))
15832 (error (error "Bad timestamp `%s'%s\nError was: %s"
15833 s (if (not (and buffer pos))
15835 (format " at %d in buffer `%s'" pos buffer))
15836 (cdr errdata)))))
15838 (defun org-time-string-to-seconds (s)
15839 (org-float-time (org-time-string-to-time s)))
15841 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15842 "Convert a time stamp to an absolute day number.
15843 If there is a specifier for a cyclic time stamp, get the closest date to
15844 DAYNR.
15845 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15846 The variable date is bound by the calendar when this is called."
15847 (cond
15848 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15849 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15850 daynr
15851 (+ daynr 1000)))
15852 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15853 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15854 (time-to-days (current-time))) (match-string 0 s)
15855 prefer show-all))
15856 (t (time-to-days
15857 (condition-case errdata
15858 (apply 'encode-time (org-parse-time-string s))
15859 (error (error "Bad timestamp `%s'%s\nError was: %s"
15860 s (if (not (and buffer pos))
15862 (format " at %d in buffer `%s'" pos buffer))
15863 (cdr errdata))))))))
15865 (defun org-days-to-iso-week (days)
15866 "Return the iso week number."
15867 (require 'cal-iso)
15868 (car (calendar-iso-from-absolute days)))
15870 (defun org-small-year-to-year (year)
15871 "Convert 2-digit years into 4-digit years.
15872 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15873 The year 2000 cannot be abbreviated. Any year larger than 99
15874 is returned unchanged."
15875 (if (< year 38)
15876 (setq year (+ 2000 year))
15877 (if (< year 100)
15878 (setq year (+ 1900 year))))
15879 year)
15881 (defun org-time-from-absolute (d)
15882 "Return the time corresponding to date D.
15883 D may be an absolute day number, or a calendar-type list (month day year)."
15884 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15885 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15887 (defun org-calendar-holiday ()
15888 "List of holidays, for Diary display in Org-mode."
15889 (require 'holidays)
15890 (let ((hl (funcall
15891 (if (fboundp 'calendar-check-holidays)
15892 'calendar-check-holidays 'check-calendar-holidays) date)))
15893 (if hl (mapconcat 'identity hl "; "))))
15895 (defun org-diary-sexp-entry (sexp entry date)
15896 "Process a SEXP diary ENTRY for DATE."
15897 (require 'diary-lib)
15898 (let ((result (if calendar-debug-sexp
15899 (let ((stack-trace-on-error t))
15900 (eval (car (read-from-string sexp))))
15901 (condition-case nil
15902 (eval (car (read-from-string sexp)))
15903 (error
15904 (beep)
15905 (message "Bad sexp at line %d in %s: %s"
15906 (org-current-line)
15907 (buffer-file-name) sexp)
15908 (sleep-for 2))))))
15909 (cond ((stringp result) (split-string result "; "))
15910 ((and (consp result)
15911 (not (consp (cdr result)))
15912 (stringp (cdr result))) (cdr result))
15913 ((and (consp result)
15914 (stringp (car result))) result)
15915 (result entry)
15916 (t nil))))
15918 (defun org-diary-to-ical-string (frombuf)
15919 "Get iCalendar entries from diary entries in buffer FROMBUF.
15920 This uses the icalendar.el library."
15921 (let* ((tmpdir (if (featurep 'xemacs)
15922 (temp-directory)
15923 temporary-file-directory))
15924 (tmpfile (make-temp-name
15925 (expand-file-name "orgics" tmpdir)))
15926 buf rtn b e)
15927 (with-current-buffer frombuf
15928 (icalendar-export-region (point-min) (point-max) tmpfile)
15929 (setq buf (find-buffer-visiting tmpfile))
15930 (set-buffer buf)
15931 (goto-char (point-min))
15932 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15933 (setq b (match-beginning 0)))
15934 (goto-char (point-max))
15935 (if (re-search-backward "^END:VEVENT" nil t)
15936 (setq e (match-end 0)))
15937 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15938 (kill-buffer buf)
15939 (delete-file tmpfile)
15940 rtn))
15942 (defun org-closest-date (start current change prefer show-all)
15943 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15944 When PREFER is `past', return a date that is either CURRENT or past.
15945 When PREFER is `future', return a date that is either CURRENT or future.
15946 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15947 ;; Make the proper lists from the dates
15948 (catch 'exit
15949 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15950 dn dw sday cday n1 n2 n0
15951 d m y y1 y2 date1 date2 nmonths nm ny m2)
15953 (setq start (org-date-to-gregorian start)
15954 current (org-date-to-gregorian
15955 (if show-all
15956 current
15957 (time-to-days (current-time))))
15958 sday (calendar-absolute-from-gregorian start)
15959 cday (calendar-absolute-from-gregorian current))
15961 (if (<= cday sday) (throw 'exit sday))
15963 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15964 (setq dn (string-to-number (match-string 1 change))
15965 dw (cdr (assoc (match-string 2 change) a1)))
15966 (error "Invalid change specifier: %s" change))
15967 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15968 (cond
15969 ((eq dw 'day)
15970 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15971 n2 (+ n1 dn)))
15972 ((eq dw 'year)
15973 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15974 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15975 (setq date1 (list m d y1)
15976 n1 (calendar-absolute-from-gregorian date1)
15977 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15978 n2 (calendar-absolute-from-gregorian date2)))
15979 ((eq dw 'month)
15980 ;; approx number of month between the two dates
15981 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15982 ;; How often does dn fit in there?
15983 (setq d (nth 1 start) m (car start) y (nth 2 start)
15984 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15985 m (+ m nm)
15986 ny (floor (/ m 12))
15987 y (+ y ny)
15988 m (- m (* ny 12)))
15989 (while (> m 12) (setq m (- m 12) y (1+ y)))
15990 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15991 (setq m2 (+ m dn) y2 y)
15992 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15993 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15994 (while (<= n2 cday)
15995 (setq n1 n2 m m2 y y2)
15996 (setq m2 (+ m dn) y2 y)
15997 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15998 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15999 ;; Make sure n1 is the earlier date
16000 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16001 (if show-all
16002 (cond
16003 ((eq prefer 'past) (if (= cday n2) n2 n1))
16004 ((eq prefer 'future) (if (= cday n1) n1 n2))
16005 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16006 (cond
16007 ((eq prefer 'past) (if (= cday n2) n2 n1))
16008 ((eq prefer 'future) (if (= cday n1) n1 n2))
16009 (t (if (= cday n1) n1 n2)))))))
16011 (defun org-date-to-gregorian (date)
16012 "Turn any specification of DATE into a Gregorian date for the calendar."
16013 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16014 ((and (listp date) (= (length date) 3)) date)
16015 ((stringp date)
16016 (setq date (org-parse-time-string date))
16017 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16018 ((listp date)
16019 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16021 (defun org-parse-time-string (s &optional nodefault)
16022 "Parse the standard Org-mode time string.
16023 This should be a lot faster than the normal `parse-time-string'.
16024 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16025 hour and minute fields will be nil if not given."
16026 (if (string-match org-ts-regexp0 s)
16027 (list 0
16028 (if (or (match-beginning 8) (not nodefault))
16029 (string-to-number (or (match-string 8 s) "0")))
16030 (if (or (match-beginning 7) (not nodefault))
16031 (string-to-number (or (match-string 7 s) "0")))
16032 (string-to-number (match-string 4 s))
16033 (string-to-number (match-string 3 s))
16034 (string-to-number (match-string 2 s))
16035 nil nil nil)
16036 (error "Not a standard Org-mode time string: %s" s)))
16038 (defun org-timestamp-up (&optional arg)
16039 "Increase the date item at the cursor by one.
16040 If the cursor is on the year, change the year. If it is on the month,
16041 the day or the time, change that.
16042 With prefix ARG, change by that many units."
16043 (interactive "p")
16044 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16046 (defun org-timestamp-down (&optional arg)
16047 "Decrease the date item at the cursor by one.
16048 If the cursor is on the year, change the year. If it is on the month,
16049 the day or the time, change that.
16050 With prefix ARG, change by that many units."
16051 (interactive "p")
16052 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16054 (defun org-timestamp-up-day (&optional arg)
16055 "Increase the date in the time stamp by one day.
16056 With prefix ARG, change that many days."
16057 (interactive "p")
16058 (if (and (not (org-at-timestamp-p t))
16059 (org-at-heading-p))
16060 (org-todo 'up)
16061 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16063 (defun org-timestamp-down-day (&optional arg)
16064 "Decrease the date in the time stamp by one day.
16065 With prefix ARG, change that many days."
16066 (interactive "p")
16067 (if (and (not (org-at-timestamp-p t))
16068 (org-at-heading-p))
16069 (org-todo 'down)
16070 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16072 (defun org-at-timestamp-p (&optional inactive-ok)
16073 "Determine if the cursor is in or at a timestamp."
16074 (interactive)
16075 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16076 (pos (point))
16077 (ans (or (looking-at tsr)
16078 (save-excursion
16079 (skip-chars-backward "^[<\n\r\t")
16080 (if (> (point) (point-min)) (backward-char 1))
16081 (and (looking-at tsr)
16082 (> (- (match-end 0) pos) -1))))))
16083 (and ans
16084 (boundp 'org-ts-what)
16085 (setq org-ts-what
16086 (cond
16087 ((= pos (match-beginning 0)) 'bracket)
16088 ;; Point is considered to be "on the bracket" whether
16089 ;; it's really on it or right after it.
16090 ((or (= pos (1- (match-end 0)))
16091 (= pos (match-end 0))) 'bracket)
16092 ((org-pos-in-match-range pos 2) 'year)
16093 ((org-pos-in-match-range pos 3) 'month)
16094 ((org-pos-in-match-range pos 7) 'hour)
16095 ((org-pos-in-match-range pos 8) 'minute)
16096 ((or (org-pos-in-match-range pos 4)
16097 (org-pos-in-match-range pos 5)) 'day)
16098 ((and (> pos (or (match-end 8) (match-end 5)))
16099 (< pos (match-end 0)))
16100 (- pos (or (match-end 8) (match-end 5))))
16101 (t 'day))))
16102 ans))
16104 (defun org-toggle-timestamp-type ()
16105 "Toggle the type (<active> or [inactive]) of a time stamp."
16106 (interactive)
16107 (when (org-at-timestamp-p t)
16108 (let ((beg (match-beginning 0)) (end (match-end 0))
16109 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16110 (save-excursion
16111 (goto-char beg)
16112 (while (re-search-forward "[][<>]" end t)
16113 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16114 t t)))
16115 (message "Timestamp is now %sactive"
16116 (if (equal (char-after beg) ?<) "" "in")))))
16118 (defun org-timestamp-change (n &optional what updown)
16119 "Change the date in the time stamp at point.
16120 The date will be changed by N times WHAT. WHAT can be `day', `month',
16121 `year', `minute', `second'. If WHAT is not given, the cursor position
16122 in the timestamp determines what will be changed."
16123 (let ((origin (point)) origin-cat
16124 with-hm inactive
16125 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16126 org-ts-what
16127 extra rem
16128 ts time time0)
16129 (if (not (org-at-timestamp-p t))
16130 (error "Not at a timestamp"))
16131 (if (and (not what) (eq org-ts-what 'bracket))
16132 (org-toggle-timestamp-type)
16133 ;; Point isn't on brackets. Remember the part of the time-stamp
16134 ;; the point was in. Indeed, size of time-stamps may change,
16135 ;; but point must be kept in the same category nonetheless.
16136 (setq origin-cat org-ts-what)
16137 (if (and (not what) (not (eq org-ts-what 'day))
16138 org-display-custom-times
16139 (get-text-property (point) 'display)
16140 (not (get-text-property (1- (point)) 'display)))
16141 (setq org-ts-what 'day))
16142 (setq org-ts-what (or what org-ts-what)
16143 inactive (= (char-after (match-beginning 0)) ?\[)
16144 ts (match-string 0))
16145 (replace-match "")
16146 (if (string-match
16147 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16149 (setq extra (match-string 1 ts)))
16150 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16151 (setq with-hm t))
16152 (setq time0 (org-parse-time-string ts))
16153 (when (and updown
16154 (eq org-ts-what 'minute)
16155 (not current-prefix-arg))
16156 ;; This looks like s-up and s-down. Change by one rounding step.
16157 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16158 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16159 (setcar (cdr time0) (+ (nth 1 time0)
16160 (if (> n 0) (- rem) (- dm rem))))))
16161 (setq time
16162 (encode-time (or (car time0) 0)
16163 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16164 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16165 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16166 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16167 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16168 (nthcdr 6 time0)))
16169 (when (and (member org-ts-what '(hour minute))
16170 extra
16171 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16172 (setq extra (org-modify-ts-extra
16173 extra
16174 (if (eq org-ts-what 'hour) 2 5)
16175 n dm)))
16176 (when (integerp org-ts-what)
16177 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16178 (if (eq what 'calendar)
16179 (let ((cal-date (org-get-date-from-calendar)))
16180 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16181 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16182 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16183 (setcar time0 (or (car time0) 0))
16184 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16185 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16186 (setq time (apply 'encode-time time0))))
16187 ;; Insert the new time-stamp, and ensure point stays in the same
16188 ;; category as before (i.e. not after the last position in that
16189 ;; category).
16190 (let ((pos (point)))
16191 ;; Stay before inserted string. `save-excursion' is of no use.
16192 (setq org-last-changed-timestamp
16193 (org-insert-time-stamp time with-hm inactive nil nil extra))
16194 (goto-char pos))
16195 (save-match-data
16196 (looking-at org-ts-regexp3)
16197 (goto-char (cond
16198 ;; `day' category ends before `hour' if any, or at
16199 ;; the end of the day name.
16200 ((eq origin-cat 'day)
16201 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16202 ((eq origin-cat 'hour) (min (match-end 7) origin))
16203 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16204 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16205 ;; `year' and `month' have both fixed size: point
16206 ;; couldn't have moved into another part.
16207 (t origin))))
16208 ;; Update clock if on a CLOCK line.
16209 (org-clock-update-time-maybe)
16210 ;; Try to recenter the calendar window, if any.
16211 (if (and org-calendar-follow-timestamp-change
16212 (get-buffer-window "*Calendar*" t)
16213 (memq org-ts-what '(day month year)))
16214 (org-recenter-calendar (time-to-days time))))))
16216 (defun org-modify-ts-extra (s pos n dm)
16217 "Change the different parts of the lead-time and repeat fields in timestamp."
16218 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16219 ng h m new rem)
16220 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16221 (cond
16222 ((or (org-pos-in-match-range pos 2)
16223 (org-pos-in-match-range pos 3))
16224 (setq m (string-to-number (match-string 3 s))
16225 h (string-to-number (match-string 2 s)))
16226 (if (org-pos-in-match-range pos 2)
16227 (setq h (+ h n))
16228 (setq n (* dm (org-no-warnings (signum n))))
16229 (when (not (= 0 (setq rem (% m dm))))
16230 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16231 (setq m (+ m n)))
16232 (if (< m 0) (setq m (+ m 60) h (1- h)))
16233 (if (> m 59) (setq m (- m 60) h (1+ h)))
16234 (setq h (min 24 (max 0 h)))
16235 (setq ng 1 new (format "-%02d:%02d" h m)))
16236 ((org-pos-in-match-range pos 6)
16237 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16238 ((org-pos-in-match-range pos 5)
16239 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16241 ((org-pos-in-match-range pos 9)
16242 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16243 ((org-pos-in-match-range pos 8)
16244 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16246 (when ng
16247 (setq s (concat
16248 (substring s 0 (match-beginning ng))
16250 (substring s (match-end ng))))))
16253 (defun org-recenter-calendar (date)
16254 "If the calendar is visible, recenter it to DATE."
16255 (let ((cwin (get-buffer-window "*Calendar*" t)))
16256 (when cwin
16257 (let ((calendar-move-hook nil))
16258 (with-selected-window cwin
16259 (calendar-goto-date (if (listp date) date
16260 (calendar-gregorian-from-absolute date))))))))
16262 (defun org-goto-calendar (&optional arg)
16263 "Go to the Emacs calendar at the current date.
16264 If there is a time stamp in the current line, go to that date.
16265 A prefix ARG can be used to force the current date."
16266 (interactive "P")
16267 (let ((tsr org-ts-regexp) diff
16268 (calendar-move-hook nil)
16269 (calendar-view-holidays-initially-flag nil)
16270 (calendar-view-diary-initially-flag nil))
16271 (if (or (org-at-timestamp-p)
16272 (save-excursion
16273 (beginning-of-line 1)
16274 (looking-at (concat ".*" tsr))))
16275 (let ((d1 (time-to-days (current-time)))
16276 (d2 (time-to-days
16277 (org-time-string-to-time (match-string 1)))))
16278 (setq diff (- d2 d1))))
16279 (calendar)
16280 (calendar-goto-today)
16281 (if (and diff (not arg)) (calendar-forward-day diff))))
16283 (defun org-get-date-from-calendar ()
16284 "Return a list (month day year) of date at point in calendar."
16285 (with-current-buffer "*Calendar*"
16286 (save-match-data
16287 (calendar-cursor-to-date))))
16289 (defun org-date-from-calendar ()
16290 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16291 If there is already a time stamp at the cursor position, update it."
16292 (interactive)
16293 (if (org-at-timestamp-p t)
16294 (org-timestamp-change 0 'calendar)
16295 (let ((cal-date (org-get-date-from-calendar)))
16296 (org-insert-time-stamp
16297 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16299 (defun org-minutes-to-hh:mm-string (m)
16300 "Compute H:MM from a number of minutes."
16301 (let ((h (/ m 60)))
16302 (setq m (- m (* 60 h)))
16303 (format org-time-clocksum-format h m)))
16305 (defun org-hh:mm-string-to-minutes (s)
16306 "Convert a string H:MM to a number of minutes.
16307 If the string is just a number, interpret it as minutes.
16308 In fact, the first hh:mm or number in the string will be taken,
16309 there can be extra stuff in the string.
16310 If no number is found, the return value is 0."
16311 (cond
16312 ((integerp s) s)
16313 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16314 (+ (* (string-to-number (match-string 1 s)) 60)
16315 (string-to-number (match-string 2 s))))
16316 ((string-match "\\([0-9]+\\)" s)
16317 (string-to-number (match-string 1 s)))
16318 (t 0)))
16320 (defcustom org-effort-durations
16321 `(("h" . 60)
16322 ("d" . ,(* 60 8))
16323 ("w" . ,(* 60 8 5))
16324 ("m" . ,(* 60 8 5 4))
16325 ("y" . ,(* 60 8 5 40)))
16326 "Conversion factor to minutes for an effort modifier.
16328 Each entry has the form (MODIFIER . MINUTES).
16330 In an effort string, a number followed by MODIFIER is multiplied
16331 by the specified number of MINUTES to obtain an effort in
16332 minutes.
16334 For example, if the value of this variable is ((\"hours\" . 60)), then an
16335 effort string \"2hours\" is equivalent to 120 minutes."
16336 :group 'org-agenda
16337 :version "24.1"
16338 :type '(alist :key-type (string :tag "Modifier")
16339 :value-type (number :tag "Minutes")))
16341 (defun org-duration-string-to-minutes (s)
16342 "Convert a duration string S to minutes.
16344 A bare number is interpreted as minutes, modifiers can be set by
16345 customizing `org-effort-durations' (which see).
16347 Entries containing a colon are interpreted as H:MM by
16348 `org-hh:mm-string-to-minutes'."
16349 (let ((result 0)
16350 (re (concat "\\([0-9]+\\) *\\("
16351 (regexp-opt (mapcar 'car org-effort-durations))
16352 "\\)")))
16353 (while (string-match re s)
16354 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16355 (string-to-number (match-string 1 s))))
16356 (setq s (replace-match "" nil t s)))
16357 (incf result (org-hh:mm-string-to-minutes s))
16358 result))
16360 ;;;; Files
16362 (defun org-save-all-org-buffers ()
16363 "Save all Org-mode buffers without user confirmation."
16364 (interactive)
16365 (message "Saving all Org-mode buffers...")
16366 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16367 (when (featurep 'org-id) (org-id-locations-save))
16368 (message "Saving all Org-mode buffers... done"))
16370 (defun org-revert-all-org-buffers ()
16371 "Revert all Org-mode buffers.
16372 Prompt for confirmation when there are unsaved changes.
16373 Be sure you know what you are doing before letting this function
16374 overwrite your changes.
16376 This function is useful in a setup where one tracks org files
16377 with a version control system, to revert on one machine after pulling
16378 changes from another. I believe the procedure must be like this:
16380 1. M-x org-save-all-org-buffers
16381 2. Pull changes from the other machine, resolve conflicts
16382 3. M-x org-revert-all-org-buffers"
16383 (interactive)
16384 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16385 (error "Abort"))
16386 (save-excursion
16387 (save-window-excursion
16388 (mapc
16389 (lambda (b)
16390 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16391 (with-current-buffer b buffer-file-name))
16392 (org-pop-to-buffer-same-window b)
16393 (revert-buffer t 'no-confirm)))
16394 (buffer-list))
16395 (when (and (featurep 'org-id) org-id-track-globally)
16396 (org-id-locations-load)))))
16398 ;;;; Agenda files
16400 ;;;###autoload
16401 (defun org-switchb (&optional arg)
16402 "Switch between Org buffers.
16403 With one prefix argument, restrict available buffers to files.
16404 With two prefix arguments, restrict available buffers to agenda files.
16406 Defaults to `iswitchb' for buffer name completion.
16407 Set `org-completion-use-ido' to make it use ido instead."
16408 (interactive "P")
16409 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16410 ((equal arg '(16)) (org-buffer-list 'agenda))
16411 (t (org-buffer-list))))
16412 (org-completion-use-iswitchb org-completion-use-iswitchb)
16413 (org-completion-use-ido org-completion-use-ido))
16414 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16415 (setq org-completion-use-iswitchb t))
16416 (org-pop-to-buffer-same-window
16417 (org-icompleting-read "Org buffer: "
16418 (mapcar 'list (mapcar 'buffer-name blist))
16419 nil t))))
16421 ;;; Define some older names previously used for this functionality
16422 ;;;###autoload
16423 (defalias 'org-ido-switchb 'org-switchb)
16424 ;;;###autoload
16425 (defalias 'org-iswitchb 'org-switchb)
16427 (defun org-buffer-list (&optional predicate exclude-tmp)
16428 "Return a list of Org buffers.
16429 PREDICATE can be `export', `files' or `agenda'.
16431 export restrict the list to Export buffers.
16432 files restrict the list to buffers visiting Org files.
16433 agenda restrict the list to buffers visiting agenda files.
16435 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16436 (let* ((bfn nil)
16437 (agenda-files (and (eq predicate 'agenda)
16438 (mapcar 'file-truename (org-agenda-files t))))
16439 (filter
16440 (cond
16441 ((eq predicate 'files)
16442 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16443 ((eq predicate 'export)
16444 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16445 ((eq predicate 'agenda)
16446 (lambda (b)
16447 (with-current-buffer b
16448 (and (eq major-mode 'org-mode)
16449 (setq bfn (buffer-file-name b))
16450 (member (file-truename bfn) agenda-files)))))
16451 (t (lambda (b) (with-current-buffer b
16452 (or (eq major-mode 'org-mode)
16453 (string-match "\*Org .*Export"
16454 (buffer-name b)))))))))
16455 (delq nil
16456 (mapcar
16457 (lambda(b)
16458 (if (and (funcall filter b)
16459 (or (not exclude-tmp)
16460 (not (string-match "tmp" (buffer-name b)))))
16462 nil))
16463 (buffer-list)))))
16465 (defun org-agenda-files (&optional unrestricted archives)
16466 "Get the list of agenda files.
16467 Optional UNRESTRICTED means return the full list even if a restriction
16468 is currently in place.
16469 When ARCHIVES is t, include all archive files that are really being
16470 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16471 `org-agenda-archives-mode' is t."
16472 (let ((files
16473 (cond
16474 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16475 ((stringp org-agenda-files) (org-read-agenda-file-list))
16476 ((listp org-agenda-files) org-agenda-files)
16477 (t (error "Invalid value of `org-agenda-files'")))))
16478 (setq files (apply 'append
16479 (mapcar (lambda (f)
16480 (if (file-directory-p f)
16481 (directory-files
16482 f t org-agenda-file-regexp)
16483 (list f)))
16484 files)))
16485 (when org-agenda-skip-unavailable-files
16486 (setq files (delq nil
16487 (mapcar (function
16488 (lambda (file)
16489 (and (file-readable-p file) file)))
16490 files))))
16491 (when (or (eq archives t)
16492 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16493 (setq files (org-add-archive-files files)))
16494 files))
16496 (defun org-agenda-file-p (&optional file)
16497 "Return non-nil, if FILE is an agenda file.
16498 If FILE is omitted, use the file associated with the current
16499 buffer."
16500 (member (or file (buffer-file-name))
16501 (org-agenda-files t)))
16503 (defun org-edit-agenda-file-list ()
16504 "Edit the list of agenda files.
16505 Depending on setup, this either uses customize to edit the variable
16506 `org-agenda-files', or it visits the file that is holding the list. In the
16507 latter case, the buffer is set up in a way that saving it automatically kills
16508 the buffer and restores the previous window configuration."
16509 (interactive)
16510 (if (stringp org-agenda-files)
16511 (let ((cw (current-window-configuration)))
16512 (find-file org-agenda-files)
16513 (org-set-local 'org-window-configuration cw)
16514 (org-add-hook 'after-save-hook
16515 (lambda ()
16516 (set-window-configuration
16517 (prog1 org-window-configuration
16518 (kill-buffer (current-buffer))))
16519 (org-install-agenda-files-menu)
16520 (message "New agenda file list installed"))
16521 nil 'local)
16522 (message "%s" (substitute-command-keys
16523 "Edit list and finish with \\[save-buffer]")))
16524 (customize-variable 'org-agenda-files)))
16526 (defun org-store-new-agenda-file-list (list)
16527 "Set new value for the agenda file list and save it correctly."
16528 (if (stringp org-agenda-files)
16529 (let ((fe (org-read-agenda-file-list t)) b u)
16530 (while (setq b (find-buffer-visiting org-agenda-files))
16531 (kill-buffer b))
16532 (with-temp-file org-agenda-files
16533 (insert
16534 (mapconcat
16535 (lambda (f) ;; Keep un-expanded entries.
16536 (if (setq u (assoc f fe))
16537 (cdr u)
16539 list "\n")
16540 "\n")))
16541 (let ((org-mode-hook nil) (org-inhibit-startup t)
16542 (org-insert-mode-line-in-empty-file nil))
16543 (setq org-agenda-files list)
16544 (customize-save-variable 'org-agenda-files org-agenda-files))))
16546 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16547 "Read the list of agenda files from a file.
16548 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16549 filenames, used by `org-store-new-agenda-file-list' to write back
16550 un-expanded file names."
16551 (when (file-directory-p org-agenda-files)
16552 (error "`org-agenda-files' cannot be a single directory"))
16553 (when (stringp org-agenda-files)
16554 (with-temp-buffer
16555 (insert-file-contents org-agenda-files)
16556 (mapcar
16557 (lambda (f)
16558 (let ((e (expand-file-name (substitute-in-file-name f)
16559 org-directory)))
16560 (if pair-with-expansion
16561 (cons e f)
16562 e)))
16563 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16565 ;;;###autoload
16566 (defun org-cycle-agenda-files ()
16567 "Cycle through the files in `org-agenda-files'.
16568 If the current buffer visits an agenda file, find the next one in the list.
16569 If the current buffer does not, find the first agenda file."
16570 (interactive)
16571 (let* ((fs (org-agenda-files t))
16572 (files (append fs (list (car fs))))
16573 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16574 file)
16575 (unless files (error "No agenda files"))
16576 (catch 'exit
16577 (while (setq file (pop files))
16578 (if (equal (file-truename file) tcf)
16579 (when (car files)
16580 (find-file (car files))
16581 (throw 'exit t))))
16582 (find-file (car fs)))
16583 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16585 (defun org-agenda-file-to-front (&optional to-end)
16586 "Move/add the current file to the top of the agenda file list.
16587 If the file is not present in the list, it is added to the front. If it is
16588 present, it is moved there. With optional argument TO-END, add/move to the
16589 end of the list."
16590 (interactive "P")
16591 (let ((org-agenda-skip-unavailable-files nil)
16592 (file-alist (mapcar (lambda (x)
16593 (cons (file-truename x) x))
16594 (org-agenda-files t)))
16595 (ctf (file-truename buffer-file-name))
16596 x had)
16597 (setq x (assoc ctf file-alist) had x)
16599 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16600 (if to-end
16601 (setq file-alist (append (delq x file-alist) (list x)))
16602 (setq file-alist (cons x (delq x file-alist))))
16603 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16604 (org-install-agenda-files-menu)
16605 (message "File %s to %s of agenda file list"
16606 (if had "moved" "added") (if to-end "end" "front"))))
16608 (defun org-remove-file (&optional file)
16609 "Remove current file from the list of files in variable `org-agenda-files'.
16610 These are the files which are being checked for agenda entries.
16611 Optional argument FILE means use this file instead of the current."
16612 (interactive)
16613 (let* ((org-agenda-skip-unavailable-files nil)
16614 (file (or file buffer-file-name))
16615 (true-file (file-truename file))
16616 (afile (abbreviate-file-name file))
16617 (files (delq nil (mapcar
16618 (lambda (x)
16619 (if (equal true-file
16620 (file-truename x))
16621 nil x))
16622 (org-agenda-files t)))))
16623 (if (not (= (length files) (length (org-agenda-files t))))
16624 (progn
16625 (org-store-new-agenda-file-list files)
16626 (org-install-agenda-files-menu)
16627 (message "Removed file: %s" afile))
16628 (message "File was not in list: %s (not removed)" afile))))
16630 (defun org-file-menu-entry (file)
16631 (vector file (list 'find-file file) t))
16633 (defun org-check-agenda-file (file)
16634 "Make sure FILE exists. If not, ask user what to do."
16635 (when (not (file-exists-p file))
16636 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16637 (abbreviate-file-name file))
16638 (let ((r (downcase (read-char-exclusive))))
16639 (cond
16640 ((equal r ?r)
16641 (org-remove-file file)
16642 (throw 'nextfile t))
16643 (t (error "Abort"))))))
16645 (defun org-get-agenda-file-buffer (file)
16646 "Get a buffer visiting FILE. If the buffer needs to be created, add
16647 it to the list of buffers which might be released later."
16648 (let ((buf (org-find-base-buffer-visiting file)))
16649 (if buf
16650 buf ; just return it
16651 ;; Make a new buffer and remember it
16652 (setq buf (find-file-noselect file))
16653 (if buf (push buf org-agenda-new-buffers))
16654 buf)))
16656 (defun org-release-buffers (blist)
16657 "Release all buffers in list, asking the user for confirmation when needed.
16658 When a buffer is unmodified, it is just killed. When modified, it is saved
16659 \(if the user agrees) and then killed."
16660 (let (buf file)
16661 (while (setq buf (pop blist))
16662 (setq file (buffer-file-name buf))
16663 (when (and (buffer-modified-p buf)
16664 file
16665 (y-or-n-p (format "Save file %s? " file)))
16666 (with-current-buffer buf (save-buffer)))
16667 (kill-buffer buf))))
16669 (defun org-prepare-agenda-buffers (files)
16670 "Create buffers for all agenda files, protect archived trees and comments."
16671 (interactive)
16672 (let ((pa '(:org-archived t))
16673 (pc '(:org-comment t))
16674 (pall '(:org-archived t :org-comment t))
16675 (inhibit-read-only t)
16676 (rea (concat ":" org-archive-tag ":"))
16677 bmp file re)
16678 (save-excursion
16679 (save-restriction
16680 (while (setq file (pop files))
16681 (catch 'nextfile
16682 (if (bufferp file)
16683 (set-buffer file)
16684 (org-check-agenda-file file)
16685 (set-buffer (org-get-agenda-file-buffer file)))
16686 (widen)
16687 (setq bmp (buffer-modified-p))
16688 (org-refresh-category-properties)
16689 (setq org-todo-keywords-for-agenda
16690 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16691 (setq org-done-keywords-for-agenda
16692 (append org-done-keywords-for-agenda org-done-keywords))
16693 (setq org-todo-keyword-alist-for-agenda
16694 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16695 (setq org-drawers-for-agenda
16696 (append org-drawers-for-agenda org-drawers))
16697 (setq org-tag-alist-for-agenda
16698 (append org-tag-alist-for-agenda org-tag-alist))
16700 (save-excursion
16701 (remove-text-properties (point-min) (point-max) pall)
16702 (when org-agenda-skip-archived-trees
16703 (goto-char (point-min))
16704 (while (re-search-forward rea nil t)
16705 (if (org-at-heading-p t)
16706 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16707 (goto-char (point-min))
16708 (setq re (format org-heading-keyword-regexp-format
16709 org-comment-string))
16710 (while (re-search-forward re nil t)
16711 (add-text-properties
16712 (match-beginning 0) (org-end-of-subtree t) pc)))
16713 (set-buffer-modified-p bmp)))))
16714 (setq org-todo-keywords-for-agenda
16715 (org-uniquify org-todo-keywords-for-agenda))
16716 (setq org-todo-keyword-alist-for-agenda
16717 (org-uniquify org-todo-keyword-alist-for-agenda)
16718 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16720 ;;;; Embedded LaTeX
16722 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16723 "Keymap for the minor `org-cdlatex-mode'.")
16725 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16726 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16727 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16728 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16729 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16731 (defvar org-cdlatex-texmathp-advice-is-done nil
16732 "Flag remembering if we have applied the advice to texmathp already.")
16734 (define-minor-mode org-cdlatex-mode
16735 "Toggle the minor `org-cdlatex-mode'.
16736 This mode supports entering LaTeX environment and math in LaTeX fragments
16737 in Org-mode.
16738 \\{org-cdlatex-mode-map}"
16739 nil " OCDL" nil
16740 (when org-cdlatex-mode
16741 (require 'cdlatex)
16742 (run-hooks 'cdlatex-mode-hook)
16743 (cdlatex-compute-tables))
16744 (unless org-cdlatex-texmathp-advice-is-done
16745 (setq org-cdlatex-texmathp-advice-is-done t)
16746 (defadvice texmathp (around org-math-always-on activate)
16747 "Always return t in org-mode buffers.
16748 This is because we want to insert math symbols without dollars even outside
16749 the LaTeX math segments. If Orgmode thinks that point is actually inside
16750 an embedded LaTeX fragment, let texmathp do its job.
16751 \\[org-cdlatex-mode-map]"
16752 (interactive)
16753 (let (p)
16754 (cond
16755 ((not (eq major-mode 'org-mode)) ad-do-it)
16756 ((eq this-command 'cdlatex-math-symbol)
16757 (setq ad-return-value t
16758 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16760 (let ((p (org-inside-LaTeX-fragment-p)))
16761 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16762 (setq ad-return-value t
16763 texmathp-why '("Org-mode embedded math" . 0))
16764 (if p ad-do-it)))))))))
16766 (defun turn-on-org-cdlatex ()
16767 "Unconditionally turn on `org-cdlatex-mode'."
16768 (org-cdlatex-mode 1))
16770 (defun org-inside-LaTeX-fragment-p ()
16771 "Test if point is inside a LaTeX fragment.
16772 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16773 sequence appearing also before point.
16774 Even though the matchers for math are configurable, this function assumes
16775 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16776 delimiters are skipped when they have been removed by customization.
16777 The return value is nil, or a cons cell with the delimiter and the
16778 position of this delimiter.
16780 This function does a reasonably good job, but can locally be fooled by
16781 for example currency specifications. For example it will assume being in
16782 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16783 fragments that are properly closed, but during editing, we have to live
16784 with the uncertainty caused by missing closing delimiters. This function
16785 looks only before point, not after."
16786 (catch 'exit
16787 (let ((pos (point))
16788 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16789 (lim (progn
16790 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16791 (point)))
16792 dd-on str (start 0) m re)
16793 (goto-char pos)
16794 (when dodollar
16795 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16796 re (nth 1 (assoc "$" org-latex-regexps)))
16797 (while (string-match re str start)
16798 (cond
16799 ((= (match-end 0) (length str))
16800 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16801 ((= (match-end 0) (- (length str) 5))
16802 (throw 'exit nil))
16803 (t (setq start (match-end 0))))))
16804 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16805 (goto-char pos)
16806 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16807 (and (match-beginning 2) (throw 'exit nil))
16808 ;; count $$
16809 (while (re-search-backward "\\$\\$" lim t)
16810 (setq dd-on (not dd-on)))
16811 (goto-char pos)
16812 (if dd-on (cons "$$" m))))))
16814 (defun org-inside-latex-macro-p ()
16815 "Is point inside a LaTeX macro or its arguments?"
16816 (save-match-data
16817 (org-in-regexp
16818 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16820 (defun org-try-cdlatex-tab ()
16821 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16822 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16823 - inside a LaTeX fragment, or
16824 - after the first word in a line, where an abbreviation expansion could
16825 insert a LaTeX environment."
16826 (when org-cdlatex-mode
16827 (cond
16828 ;; Before any word on the line: No expansion possible.
16829 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16830 ;; Just after first word on the line: Expand it. Make sure it
16831 ;; cannot happen on headlines, though.
16832 ((save-excursion
16833 (skip-chars-backward "a-zA-Z0-9*")
16834 (skip-chars-backward " \t")
16835 (and (bolp) (not (org-at-heading-p))))
16836 (cdlatex-tab) t)
16837 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16839 (defun org-cdlatex-underscore-caret (&optional arg)
16840 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16841 Revert to the normal definition outside of these fragments."
16842 (interactive "P")
16843 (if (org-inside-LaTeX-fragment-p)
16844 (call-interactively 'cdlatex-sub-superscript)
16845 (let (org-cdlatex-mode)
16846 (call-interactively (key-binding (vector last-input-event))))))
16848 (defun org-cdlatex-math-modify (&optional arg)
16849 "Execute `cdlatex-math-modify' in LaTeX fragments.
16850 Revert to the normal definition outside of these fragments."
16851 (interactive "P")
16852 (if (org-inside-LaTeX-fragment-p)
16853 (call-interactively 'cdlatex-math-modify)
16854 (let (org-cdlatex-mode)
16855 (call-interactively (key-binding (vector last-input-event))))))
16857 (defvar org-latex-fragment-image-overlays nil
16858 "List of overlays carrying the images of latex fragments.")
16859 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16861 (defun org-remove-latex-fragment-image-overlays ()
16862 "Remove all overlays with LaTeX fragment images in current buffer."
16863 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16864 (setq org-latex-fragment-image-overlays nil))
16866 (defun org-preview-latex-fragment (&optional subtree)
16867 "Preview the LaTeX fragment at point, or all locally or globally.
16868 If the cursor is in a LaTeX fragment, create the image and overlay
16869 it over the source code. If there is no fragment at point, display
16870 all fragments in the current text, from one headline to the next. With
16871 prefix SUBTREE, display all fragments in the current subtree. With a
16872 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16873 the cursor is before the first headline,
16874 display all fragments in the buffer.
16875 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16876 (interactive "P")
16877 (unless buffer-file-name
16878 (error "Can't preview LaTeX fragment in a non-file buffer"))
16879 (org-remove-latex-fragment-image-overlays)
16880 (save-excursion
16881 (save-restriction
16882 (let (beg end at msg)
16883 (cond
16884 ((or (equal subtree '(16))
16885 (not (save-excursion
16886 (re-search-backward org-outline-regexp-bol nil t))))
16887 (setq beg (point-min) end (point-max)
16888 msg "Creating images for buffer...%s"))
16889 ((equal subtree '(4))
16890 (org-back-to-heading)
16891 (setq beg (point) end (org-end-of-subtree t)
16892 msg "Creating images for subtree...%s"))
16894 (if (setq at (org-inside-LaTeX-fragment-p))
16895 (goto-char (max (point-min) (- (cdr at) 2)))
16896 (org-back-to-heading))
16897 (setq beg (point) end (progn (outline-next-heading) (point))
16898 msg (if at "Creating image...%s"
16899 "Creating images for entry...%s"))))
16900 (message msg "")
16901 (narrow-to-region beg end)
16902 (goto-char beg)
16903 (org-format-latex
16904 (concat "ltxpng/" (file-name-sans-extension
16905 (file-name-nondirectory
16906 buffer-file-name)))
16907 default-directory 'overlays msg at 'forbuffer 'dvipng)
16908 (message msg "done. Use `C-c C-c' to remove images.")))))
16910 (defvar org-latex-regexps
16911 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16912 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16913 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16914 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16915 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16916 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16917 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16918 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16919 "Regular expressions for matching embedded LaTeX.")
16921 (defvar org-export-have-math nil) ;; dynamic scoping
16922 (defun org-format-latex (prefix &optional dir overlays msg at
16923 forbuffer processing-type)
16924 "Replace LaTeX fragments with links to an image, and produce images.
16925 Some of the options can be changed using the variable
16926 `org-format-latex-options'."
16927 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16928 (let* ((prefixnodir (file-name-nondirectory prefix))
16929 (absprefix (expand-file-name prefix dir))
16930 (todir (file-name-directory absprefix))
16931 (opt org-format-latex-options)
16932 (matchers (plist-get opt :matchers))
16933 (re-list org-latex-regexps)
16934 (org-format-latex-header-extra
16935 (plist-get (org-infile-export-plist) :latex-header-extra))
16936 (cnt 0) txt hash link beg end re e checkdir
16937 executables-checked string
16938 m n block-type block linkfile movefile ov)
16939 ;; Check the different regular expressions
16940 (while (setq e (pop re-list))
16941 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16942 block (if block-type "\n\n" ""))
16943 (when (member m matchers)
16944 (goto-char (point-min))
16945 (while (re-search-forward re nil t)
16946 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16947 (not (get-text-property (match-beginning n)
16948 'org-protected))
16949 (or (not overlays)
16950 (not (eq (get-char-property (match-beginning n)
16951 'org-overlay-type)
16952 'org-latex-overlay))))
16953 (setq org-export-have-math t)
16954 (cond
16955 ((eq processing-type 'verbatim)
16956 ;; Leave the text verbatim, just protect it
16957 (add-text-properties (match-beginning n) (match-end n)
16958 '(org-protected t)))
16959 ((eq processing-type 'mathjax)
16960 ;; Prepare for MathJax processing
16961 (setq string (match-string n))
16962 (if (member m '("$" "$1"))
16963 (save-excursion
16964 (delete-region (match-beginning n) (match-end n))
16965 (goto-char (match-beginning n))
16966 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16967 "\\)")
16968 '(org-protected t))))
16969 (add-text-properties (match-beginning n) (match-end n)
16970 '(org-protected t))))
16971 ((eq processing-type 'dvipng)
16972 ;; Process to an image
16973 (setq txt (match-string n)
16974 beg (match-beginning n) end (match-end n)
16975 cnt (1+ cnt))
16976 (let (print-length print-level) ; make sure full list is printed
16977 (setq hash (sha1 (prin1-to-string
16978 (list org-format-latex-header
16979 org-format-latex-header-extra
16980 org-export-latex-default-packages-alist
16981 org-export-latex-packages-alist
16982 org-format-latex-options
16983 forbuffer txt)))
16984 linkfile (format "%s_%s.png" prefix hash)
16985 movefile (format "%s_%s.png" absprefix hash)))
16986 (setq link (concat block "[[file:" linkfile "]]" block))
16987 (if msg (message msg cnt))
16988 (goto-char beg)
16989 (unless checkdir ; make sure the directory exists
16990 (setq checkdir t)
16991 (or (file-directory-p todir) (make-directory todir t)))
16993 (unless executables-checked
16994 (org-check-external-command
16995 "latex" "needed to convert LaTeX fragments to images")
16996 (org-check-external-command
16997 "dvipng" "needed to convert LaTeX fragments to images")
16998 (setq executables-checked t))
17000 (unless (file-exists-p movefile)
17001 (org-create-formula-image
17002 txt movefile opt forbuffer))
17003 (if overlays
17004 (progn
17005 (mapc (lambda (o)
17006 (if (eq (overlay-get o 'org-overlay-type)
17007 'org-latex-overlay)
17008 (delete-overlay o)))
17009 (overlays-in beg end))
17010 (setq ov (make-overlay beg end))
17011 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17012 (if (featurep 'xemacs)
17013 (progn
17014 (overlay-put ov 'invisible t)
17015 (overlay-put
17016 ov 'end-glyph
17017 (make-glyph (vector 'png :file movefile))))
17018 (overlay-put
17019 ov 'display
17020 (list 'image :type 'png :file movefile :ascent 'center)))
17021 (push ov org-latex-fragment-image-overlays)
17022 (goto-char end))
17023 (delete-region beg end)
17024 (insert (org-add-props link
17025 (list 'org-latex-src
17026 (replace-regexp-in-string
17027 "\"" "" txt)
17028 'org-latex-src-embed-type
17029 (if block-type 'paragraph 'character))))))
17030 ((eq processing-type 'mathml)
17031 ;; Process to MathML
17032 (unless executables-checked
17033 (unless (save-match-data (org-format-latex-mathml-available-p))
17034 (error "LaTeX to MathML converter not configured"))
17035 (setq executables-checked t))
17036 (setq txt (match-string n)
17037 beg (match-beginning n) end (match-end n)
17038 cnt (1+ cnt))
17039 (if msg (message msg cnt))
17040 (goto-char beg)
17041 (delete-region beg end)
17042 (insert (org-format-latex-as-mathml
17043 txt block-type prefix dir)))
17045 (error "Unknown conversion type %s for latex fragments"
17046 processing-type)))))))))
17048 (defun org-create-math-formula (latex-frag &optional mathml-file)
17049 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17050 Use `org-latex-to-mathml-convert-command'. If the conversion is
17051 sucessful, return the portion between \"<math...> </math>\"
17052 elements otherwise return nil. When MATHML-FILE is specified,
17053 write the results in to that file. When invoked as an
17054 interactive command, prompt for LATEX-FRAG, with initial value
17055 set to the current active region and echo the results for user
17056 inspection."
17057 (interactive (list (let ((frag (when (region-active-p)
17058 (buffer-substring-no-properties
17059 (region-beginning) (region-end)))))
17060 (read-string "LaTeX Fragment: " frag nil frag))))
17061 (unless latex-frag (error "Invalid latex-frag"))
17062 (let* ((tmp-in-file (file-relative-name
17063 (make-temp-name (expand-file-name "ltxmathml-in"))))
17064 (ignore (write-region latex-frag nil tmp-in-file))
17065 (tmp-out-file (file-relative-name
17066 (make-temp-name (expand-file-name "ltxmathml-out"))))
17067 (cmd (format-spec
17068 org-latex-to-mathml-convert-command
17069 `((?j . ,(shell-quote-argument
17070 (expand-file-name org-latex-to-mathml-jar-file)))
17071 (?I . ,(shell-quote-argument tmp-in-file))
17072 (?o . ,(shell-quote-argument tmp-out-file)))))
17073 mathml shell-command-output)
17074 (when (org-called-interactively-p 'any)
17075 (unless (org-format-latex-mathml-available-p)
17076 (error "LaTeX to MathML converter not configured")))
17077 (message "Running %s" cmd)
17078 (setq shell-command-output (shell-command-to-string cmd))
17079 (setq mathml
17080 (when (file-readable-p tmp-out-file)
17081 (with-current-buffer (find-file-noselect tmp-out-file t)
17082 (goto-char (point-min))
17083 (when (re-search-forward
17084 (concat
17085 (regexp-quote
17086 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17087 "\\(.\\|\n\\)*"
17088 (regexp-quote "</math>")) nil t)
17089 (prog1 (match-string 0) (kill-buffer))))))
17090 (cond
17091 (mathml
17092 (setq mathml
17093 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17094 (when mathml-file
17095 (write-region mathml nil mathml-file))
17096 (when (org-called-interactively-p 'any)
17097 (message mathml)))
17098 ((message "LaTeX to MathML conversion failed")
17099 (message shell-command-output)))
17100 (delete-file tmp-in-file)
17101 (when (file-exists-p tmp-out-file)
17102 (delete-file tmp-out-file))
17103 mathml))
17105 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17106 prefix &optional dir)
17107 "Use `org-create-math-formula' but check local cache first."
17108 (let* ((absprefix (expand-file-name prefix dir))
17109 (print-length nil) (print-level nil)
17110 (formula-id (concat
17111 "formula-"
17112 (sha1
17113 (prin1-to-string
17114 (list latex-frag
17115 org-latex-to-mathml-convert-command)))))
17116 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17117 (formula-cache-dir (file-name-directory formula-cache)))
17119 (unless (file-directory-p formula-cache-dir)
17120 (make-directory formula-cache-dir t))
17122 (unless (file-exists-p formula-cache)
17123 (org-create-math-formula latex-frag formula-cache))
17125 (if (file-exists-p formula-cache)
17126 ;; Successful conversion. Return the link to MathML file.
17127 (org-add-props
17128 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17129 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17130 'org-latex-src-embed-type (if latex-frag-type
17131 'paragraph 'character)))
17132 ;; Failed conversion. Return the LaTeX fragment verbatim
17133 (add-text-properties
17134 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17135 latex-frag)))
17137 ;; This function borrows from Ganesh Swami's latex2png.el
17138 (defun org-create-formula-image (string tofile options buffer)
17139 "This calls dvipng."
17140 (require 'org-latex)
17141 (let* ((tmpdir (if (featurep 'xemacs)
17142 (temp-directory)
17143 temporary-file-directory))
17144 (texfilebase (make-temp-name
17145 (expand-file-name "orgtex" tmpdir)))
17146 (texfile (concat texfilebase ".tex"))
17147 (dvifile (concat texfilebase ".dvi"))
17148 (pngfile (concat texfilebase ".png"))
17149 (fnh (if (featurep 'xemacs)
17150 (font-height (face-font 'default))
17151 (face-attribute 'default :height nil)))
17152 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17153 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17154 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17155 "Black"))
17156 (bg (or (plist-get options (if buffer :background :html-background))
17157 "Transparent")))
17158 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17159 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17160 (with-temp-file texfile
17161 (insert (org-splice-latex-header
17162 org-format-latex-header
17163 org-export-latex-default-packages-alist
17164 org-export-latex-packages-alist t
17165 org-format-latex-header-extra))
17166 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17167 (require 'org-latex)
17168 (org-export-latex-fix-inputenc))
17169 (let ((dir default-directory))
17170 (condition-case nil
17171 (progn
17172 (cd tmpdir)
17173 (call-process "latex" nil nil nil texfile))
17174 (error nil))
17175 (cd dir))
17176 (if (not (file-exists-p dvifile))
17177 (progn (message "Failed to create dvi file from %s" texfile) nil)
17178 (condition-case nil
17179 (if (featurep 'xemacs)
17180 (call-process "dvipng" nil nil nil
17181 "-fg" fg "-bg" bg
17182 "-T" "tight"
17183 "-o" pngfile
17184 dvifile)
17185 (call-process "dvipng" nil nil nil
17186 "-fg" fg "-bg" bg
17187 "-D" dpi
17188 ;;"-x" scale "-y" scale
17189 "-T" "tight"
17190 "-o" pngfile
17191 dvifile))
17192 (error nil))
17193 (if (not (file-exists-p pngfile))
17194 (if org-format-latex-signal-error
17195 (error "Failed to create png file from %s" texfile)
17196 (message "Failed to create png file from %s" texfile)
17197 nil)
17198 ;; Use the requested file name and clean up
17199 (copy-file pngfile tofile 'replace)
17200 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17201 (delete-file (concat texfilebase e)))
17202 pngfile))))
17204 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17205 "Fill a LaTeX header template TPL.
17206 In the template, the following place holders will be recognized:
17208 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17209 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17210 [PACKAGES] \\usepackage statements for PKG
17211 [NO-PACKAGES] do not include PKG
17212 [EXTRA] the string EXTRA
17213 [NO-EXTRA] do not include EXTRA
17215 For backward compatibility, if both the positive and the negative place
17216 holder is missing, the positive one (without the \"NO-\") will be
17217 assumed to be present at the end of the template.
17218 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17219 EXTRA is a string.
17220 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17221 (let (rpl (end ""))
17222 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17223 (setq rpl (if (or (match-end 1) (not def-pkg))
17224 "" (org-latex-packages-to-string def-pkg snippets-p t))
17225 tpl (replace-match rpl t t tpl))
17226 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17228 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17229 (setq rpl (if (or (match-end 1) (not pkg))
17230 "" (org-latex-packages-to-string pkg snippets-p t))
17231 tpl (replace-match rpl t t tpl))
17232 (if pkg (setq end
17233 (concat end "\n"
17234 (org-latex-packages-to-string pkg snippets-p)))))
17236 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17237 (setq rpl (if (or (match-end 1) (not extra))
17238 "" (concat extra "\n"))
17239 tpl (replace-match rpl t t tpl))
17240 (if (and extra (string-match "\\S-" extra))
17241 (setq end (concat end "\n" extra))))
17243 (if (string-match "\\S-" end)
17244 (concat tpl "\n" end)
17245 tpl)))
17247 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17248 "Turn an alist of packages into a string with the \\usepackage macros."
17249 (setq pkg (mapconcat (lambda(p)
17250 (cond
17251 ((stringp p) p)
17252 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17253 (format "%% Package %s omitted" (cadr p)))
17254 ((equal "" (car p))
17255 (format "\\usepackage{%s}" (cadr p)))
17257 (format "\\usepackage[%s]{%s}"
17258 (car p) (cadr p)))))
17260 "\n"))
17261 (if newline (concat pkg "\n") pkg))
17263 (defun org-dvipng-color (attr)
17264 "Return an rgb color specification for dvipng."
17265 (apply 'format "rgb %s %s %s"
17266 (mapcar 'org-normalize-color
17267 (if (featurep 'xemacs)
17268 (color-rgb-components
17269 (face-property 'default
17270 (cond ((eq attr :foreground) 'foreground)
17271 ((eq attr :background) 'background))))
17272 (color-values (face-attribute 'default attr nil))))))
17274 (defun org-normalize-color (value)
17275 "Return string to be used as color value for an RGB component."
17276 (format "%g" (/ value 65535.0)))
17278 ;; Image display
17281 (defvar org-inline-image-overlays nil)
17282 (make-variable-buffer-local 'org-inline-image-overlays)
17284 (defun org-toggle-inline-images (&optional include-linked)
17285 "Toggle the display of inline images.
17286 INCLUDE-LINKED is passed to `org-display-inline-images'."
17287 (interactive "P")
17288 (if org-inline-image-overlays
17289 (progn
17290 (org-remove-inline-images)
17291 (message "Inline image display turned off"))
17292 (org-display-inline-images include-linked)
17293 (if org-inline-image-overlays
17294 (message "%d images displayed inline"
17295 (length org-inline-image-overlays))
17296 (message "No images to display inline"))))
17298 (defun org-display-inline-images (&optional include-linked refresh beg end)
17299 "Display inline images.
17300 Normally only links without a description part are inlined, because this
17301 is how it will work for export. When INCLUDE-LINKED is set, also links
17302 with a description part will be inlined. This can be nice for a quick
17303 look at those images, but it does not reflect what exported files will look
17304 like.
17305 When REFRESH is set, refresh existing images between BEG and END.
17306 This will create new image displays only if necessary.
17307 BEG and END default to the buffer boundaries."
17308 (interactive "P")
17309 (unless refresh
17310 (org-remove-inline-images)
17311 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17312 (save-excursion
17313 (save-restriction
17314 (widen)
17315 (setq beg (or beg (point-min)) end (or end (point-max)))
17316 (goto-char beg)
17317 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17318 (substring (org-image-file-name-regexp) 0 -2)
17319 "\\)\\]" (if include-linked "" "\\]")))
17320 old file ov img)
17321 (while (re-search-forward re end t)
17322 (setq old (get-char-property-and-overlay (match-beginning 1)
17323 'org-image-overlay))
17324 (setq file (expand-file-name
17325 (concat (or (match-string 3) "") (match-string 4))))
17326 (when (file-exists-p file)
17327 (if (and (car-safe old) refresh)
17328 (image-refresh (overlay-get (cdr old) 'display))
17329 (setq img (save-match-data (create-image file)))
17330 (when img
17331 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17332 (overlay-put ov 'display img)
17333 (overlay-put ov 'face 'default)
17334 (overlay-put ov 'org-image-overlay t)
17335 (overlay-put ov 'modification-hooks
17336 (list 'org-display-inline-modification-hook))
17337 (push ov org-inline-image-overlays)))))))))
17339 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17340 "Remove inline-display overlay if a corresponding region is modified."
17341 (let ((inhibit-modification-hooks t))
17342 (when (and ov after)
17343 (delete ov org-inline-image-overlays)
17344 (delete-overlay ov))))
17346 (defun org-remove-inline-images ()
17347 "Remove inline display of images."
17348 (interactive)
17349 (mapc 'delete-overlay org-inline-image-overlays)
17350 (setq org-inline-image-overlays nil))
17352 ;;;; Key bindings
17354 ;; Outline functions from `outline-mode-prefix-map'
17355 ;; that can be remapped in Org:
17356 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17357 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17358 (define-key org-mode-map [remap outline-forward-same-level]
17359 'org-forward-same-level)
17360 (define-key org-mode-map [remap outline-backward-same-level]
17361 'org-backward-same-level)
17362 (define-key org-mode-map [remap show-branches]
17363 'org-kill-note-or-show-branches)
17364 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17365 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17366 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17368 ;; Outline functions from `outline-mode-prefix-map'
17369 ;; that can not be remapped in Org:
17370 ;; - the column "key binding" shows whether the Outline function is still
17371 ;; available in Org mode on the same key that it has been bound to in
17372 ;; Outline mode:
17373 ;; - "overridden": key used for a different functionality in Org mode
17374 ;; - else: key still bound to the same Outline function in Org mode
17375 ;; | Outline function | key binding | Org replacement |
17376 ;; |------------------------------------+-------------+-----------------------|
17377 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17378 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17379 ;; | `show-children' | `C-c C-i' | visibility cycling |
17380 ;; | `hide-subtree' | overridden | visibility cycling |
17381 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17382 ;; | `hide-body' | overridden | no replacement |
17383 ;; | `show-all' | overridden | no replacement |
17384 ;; | `hide-entry' | overridden | visibility cycling |
17385 ;; | `show-entry' | overridden | no replacement |
17386 ;; | `hide-leaves' | overridden | no replacement |
17387 ;; | `hide-sublevels' | overridden | no replacement |
17388 ;; | `hide-other' | overridden | no replacement |
17389 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17390 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17392 ;; Make `C-c C-x' a prefix key
17393 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17395 ;; TAB key with modifiers
17396 (org-defkey org-mode-map "\C-i" 'org-cycle)
17397 (org-defkey org-mode-map [(tab)] 'org-cycle)
17398 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17399 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17400 ;; The following line is necessary under Suse GNU/Linux
17401 (unless (featurep 'xemacs)
17402 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17403 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17404 (define-key org-mode-map [backtab] 'org-shifttab)
17406 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17407 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17408 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17410 ;; Cursor keys with modifiers
17411 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17412 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17413 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17414 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17416 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17417 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17418 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17419 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17421 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17422 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17423 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17424 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17426 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17427 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17428 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17429 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17431 ;; Babel keys
17432 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17433 (mapc (lambda (pair)
17434 (define-key org-babel-map (car pair) (cdr pair)))
17435 org-babel-key-bindings)
17437 ;;; Extra keys for tty access.
17438 ;; We only set them when really needed because otherwise the
17439 ;; menus don't show the simple keys
17441 (when (or org-use-extra-keys
17442 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17443 (not window-system))
17444 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17445 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17446 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17447 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17448 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17449 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17450 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17451 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17452 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17453 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17454 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17455 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17456 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17457 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17458 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17459 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17460 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17461 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17462 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17463 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17464 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17465 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17466 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17467 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17468 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17469 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17470 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17471 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17473 ;; All the other keys
17475 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17476 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17477 (if (boundp 'narrow-map)
17478 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17479 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17480 (if (boundp 'narrow-map)
17481 (org-defkey narrow-map "b" 'org-narrow-to-block)
17482 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17483 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17484 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17485 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17486 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17487 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17488 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17489 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17490 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17491 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17492 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17493 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17494 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17495 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17496 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17497 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17498 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17499 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17500 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17501 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17502 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17503 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17504 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17505 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17506 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17507 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17508 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17509 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17510 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17511 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17512 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17513 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17514 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17515 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17516 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17517 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17518 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17519 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17520 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17521 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17522 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17523 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17524 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17525 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17526 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17527 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17528 (org-defkey org-mode-map "\C-c^" 'org-sort)
17529 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17530 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17531 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17532 (org-defkey org-mode-map "\C-m" 'org-return)
17533 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17534 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17535 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17536 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17537 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17538 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17539 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17540 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17541 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17542 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17543 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17544 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17545 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17546 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17547 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17548 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17549 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17550 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17551 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17552 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17553 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17554 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17555 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17557 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17558 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17559 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17560 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17562 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17563 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17564 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17565 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17566 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17567 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17568 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17569 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17570 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17571 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17572 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17573 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17574 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17575 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17576 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17577 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17578 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17579 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17581 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17582 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17583 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17584 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17585 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17587 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17589 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17591 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17592 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17594 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17597 (when (featurep 'xemacs)
17598 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17601 (defconst org-speed-commands-default
17603 ("Outline Navigation")
17604 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17605 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17606 ("f" . (org-speed-move-safe 'org-forward-same-level))
17607 ("b" . (org-speed-move-safe 'org-backward-same-level))
17608 ("u" . (org-speed-move-safe 'outline-up-heading))
17609 ("j" . org-goto)
17610 ("g" . (org-refile t))
17611 ("Outline Visibility")
17612 ("c" . org-cycle)
17613 ("C" . org-shifttab)
17614 (" " . org-display-outline-path)
17615 ("Outline Structure Editing")
17616 ("U" . org-shiftmetaup)
17617 ("D" . org-shiftmetadown)
17618 ("r" . org-metaright)
17619 ("l" . org-metaleft)
17620 ("R" . org-shiftmetaright)
17621 ("L" . org-shiftmetaleft)
17622 ("i" . (progn (forward-char 1) (call-interactively
17623 'org-insert-heading-respect-content)))
17624 ("^" . org-sort)
17625 ("w" . org-refile)
17626 ("a" . org-archive-subtree-default-with-confirmation)
17627 ("." . org-mark-subtree)
17628 ("Clock Commands")
17629 ("I" . org-clock-in)
17630 ("O" . org-clock-out)
17631 ("Meta Data Editing")
17632 ("t" . org-todo)
17633 ("0" . (org-priority ?\ ))
17634 ("1" . (org-priority ?A))
17635 ("2" . (org-priority ?B))
17636 ("3" . (org-priority ?C))
17637 (";" . org-set-tags-command)
17638 ("e" . org-set-effort)
17639 ("Agenda Views etc")
17640 ("v" . org-agenda)
17641 ("/" . org-sparse-tree)
17642 ("Misc")
17643 ("o" . org-open-at-point)
17644 ("?" . org-speed-command-help)
17645 ("<" . (org-agenda-set-restriction-lock 'subtree))
17646 (">" . (org-agenda-remove-restriction-lock))
17648 "The default speed commands.")
17650 (defun org-print-speed-command (e)
17651 (if (> (length (car e)) 1)
17652 (progn
17653 (princ "\n")
17654 (princ (car e))
17655 (princ "\n")
17656 (princ (make-string (length (car e)) ?-))
17657 (princ "\n"))
17658 (princ (car e))
17659 (princ " ")
17660 (if (symbolp (cdr e))
17661 (princ (symbol-name (cdr e)))
17662 (prin1 (cdr e)))
17663 (princ "\n")))
17665 (defun org-speed-command-help ()
17666 "Show the available speed commands."
17667 (interactive)
17668 (if (not org-use-speed-commands)
17669 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17670 (with-output-to-temp-buffer "*Help*"
17671 (princ "User-defined Speed commands\n===========================\n")
17672 (mapc 'org-print-speed-command org-speed-commands-user)
17673 (princ "\n")
17674 (princ "Built-in Speed commands\n=======================\n")
17675 (mapc 'org-print-speed-command org-speed-commands-default))
17676 (with-current-buffer "*Help*"
17677 (setq truncate-lines t))))
17679 (defun org-speed-move-safe (cmd)
17680 "Execute CMD, but make sure that the cursor always ends up in a headline.
17681 If not, return to the original position and throw an error."
17682 (interactive)
17683 (let ((pos (point)))
17684 (call-interactively cmd)
17685 (unless (and (bolp) (org-at-heading-p))
17686 (goto-char pos)
17687 (error "Boundary reached while executing %s" cmd))))
17689 (defvar org-self-insert-command-undo-counter 0)
17691 (defvar org-table-auto-blank-field) ; defined in org-table.el
17692 (defvar org-speed-command nil)
17694 (defun org-speed-command-default-hook (keys)
17695 "Hook for activating single-letter speed commands.
17696 `org-speed-commands-default' specifies a minimal command set.
17697 Use `org-speed-commands-user' for further customization."
17698 (when (or (and (bolp) (looking-at org-outline-regexp))
17699 (and (functionp org-use-speed-commands)
17700 (funcall org-use-speed-commands)))
17701 (cdr (assoc keys (append org-speed-commands-user
17702 org-speed-commands-default)))))
17704 (defun org-babel-speed-command-hook (keys)
17705 "Hook for activating single-letter code block commands."
17706 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17707 (cdr (assoc keys org-babel-key-bindings))))
17709 (defcustom org-speed-command-hook
17710 '(org-speed-command-default-hook org-babel-speed-command-hook)
17711 "Hook for activating speed commands at strategic locations.
17712 Hook functions are called in sequence until a valid handler is
17713 found.
17715 Each hook takes a single argument, a user-pressed command key
17716 which is also a `self-insert-command' from the global map.
17718 Within the hook, examine the cursor position and the command key
17719 and return nil or a valid handler as appropriate. Handler could
17720 be one of an interactive command, a function, or a form.
17722 Set `org-use-speed-commands' to non-nil value to enable this
17723 hook. The default setting is `org-speed-command-default-hook'."
17724 :group 'org-structure
17725 :version "24.1"
17726 :type 'hook)
17728 (defun org-self-insert-command (N)
17729 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17730 If the cursor is in a table looking at whitespace, the whitespace is
17731 overwritten, and the table is not marked as requiring realignment."
17732 (interactive "p")
17733 (org-check-before-invisible-edit 'insert)
17734 (cond
17735 ((and org-use-speed-commands
17736 (setq org-speed-command
17737 (run-hook-with-args-until-success
17738 'org-speed-command-hook (this-command-keys))))
17739 (cond
17740 ((commandp org-speed-command)
17741 (setq this-command org-speed-command)
17742 (call-interactively org-speed-command))
17743 ((functionp org-speed-command)
17744 (funcall org-speed-command))
17745 ((and org-speed-command (listp org-speed-command))
17746 (eval org-speed-command))
17747 (t (let (org-use-speed-commands)
17748 (call-interactively 'org-self-insert-command)))))
17749 ((and
17750 (org-table-p)
17751 (progn
17752 ;; check if we blank the field, and if that triggers align
17753 (and (featurep 'org-table) org-table-auto-blank-field
17754 (member last-command
17755 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17756 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17757 ;; got extra space, this field does not determine column width
17758 (let (org-table-may-need-update) (org-table-blank-field))
17759 ;; no extra space, this field may determine column width
17760 (org-table-blank-field)))
17762 (eq N 1)
17763 (looking-at "[^|\n]* |"))
17764 (let (org-table-may-need-update)
17765 (goto-char (1- (match-end 0)))
17766 (backward-delete-char 1)
17767 (goto-char (match-beginning 0))
17768 (self-insert-command N)))
17770 (setq org-table-may-need-update t)
17771 (self-insert-command N)
17772 (org-fix-tags-on-the-fly)
17773 (if org-self-insert-cluster-for-undo
17774 (if (not (eq last-command 'org-self-insert-command))
17775 (setq org-self-insert-command-undo-counter 1)
17776 (if (>= org-self-insert-command-undo-counter 20)
17777 (setq org-self-insert-command-undo-counter 1)
17778 (and (> org-self-insert-command-undo-counter 0)
17779 buffer-undo-list (listp buffer-undo-list)
17780 (not (cadr buffer-undo-list)) ; remove nil entry
17781 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17782 (setq org-self-insert-command-undo-counter
17783 (1+ org-self-insert-command-undo-counter))))))))
17785 (defun org-check-before-invisible-edit (kind)
17786 "Check is editing if kind KIND would be dangerous with invisible text around.
17787 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17788 ;; First, try to get out of here as quickly as possible, to reduce overhead
17789 (if (and org-catch-invisible-edits
17790 (or (not (boundp 'visible-mode)) (not visible-mode))
17791 (or (get-char-property (point) 'invisible)
17792 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17793 ;; OK, we need to take a closer look
17794 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17795 (invisible-before-point (if (bobp) nil (get-char-property
17796 (1- (point)) 'invisible)))
17797 (border-and-ok-direction
17799 ;; Check if we are acting predictably before invisible text
17800 (and invisible-at-point (not invisible-before-point)
17801 (memq kind '(insert delete-backward)))
17802 ;; Check if we are acting predictably after invisible text
17803 ;; This works not well, and I have turned it off. It seems
17804 ;; better to always show and stop after invisible text.
17805 ;; (and (not invisible-at-point) invisible-before-point
17806 ;; (memq kind '(insert delete)))
17809 (when (or (memq invisible-at-point '(outline org-hide-block))
17810 (memq invisible-before-point '(outline org-hide-block)))
17811 (if (eq org-catch-invisible-edits 'error)
17812 (error "Editing in invisible areas is prohibited - make visible first"))
17813 ;; Make the area visible
17814 (save-excursion
17815 (if invisible-before-point
17816 (goto-char (previous-single-char-property-change
17817 (point) 'invisible)))
17818 (org-cycle))
17819 (cond
17820 ((eq org-catch-invisible-edits 'show)
17821 ;; That's it, we do the edit after showing
17822 (message
17823 "Unfolding invisible region around point before editing")
17824 (sit-for 1))
17825 ((and (eq org-catch-invisible-edits 'smart)
17826 border-and-ok-direction)
17827 (message "Unfolding invisible region around point before editing"))
17829 ;; Don't do the edit, make the user repeat it in full visibility
17830 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17832 (defun org-fix-tags-on-the-fly ()
17833 (when (and (equal (char-after (point-at-bol)) ?*)
17834 (org-at-heading-p))
17835 (org-align-tags-here org-tags-column)))
17837 (defun org-delete-backward-char (N)
17838 "Like `delete-backward-char', insert whitespace at field end in tables.
17839 When deleting backwards, in tables this function will insert whitespace in
17840 front of the next \"|\" separator, to keep the table aligned. The table will
17841 still be marked for re-alignment if the field did fill the entire column,
17842 because, in this case the deletion might narrow the column."
17843 (interactive "p")
17844 (org-check-before-invisible-edit 'delete-backward)
17845 (if (and (org-table-p)
17846 (eq N 1)
17847 (string-match "|" (buffer-substring (point-at-bol) (point)))
17848 (looking-at ".*?|"))
17849 (let ((pos (point))
17850 (noalign (looking-at "[^|\n\r]* |"))
17851 (c org-table-may-need-update))
17852 (backward-delete-char N)
17853 (if (not overwrite-mode)
17854 (progn
17855 (skip-chars-forward "^|")
17856 (insert " ")
17857 (goto-char (1- pos))))
17858 ;; noalign: if there were two spaces at the end, this field
17859 ;; does not determine the width of the column.
17860 (if noalign (setq org-table-may-need-update c)))
17861 (backward-delete-char N)
17862 (org-fix-tags-on-the-fly)))
17864 (defun org-delete-char (N)
17865 "Like `delete-char', but insert whitespace at field end in tables.
17866 When deleting characters, in tables this function will insert whitespace in
17867 front of the next \"|\" separator, to keep the table aligned. The table will
17868 still be marked for re-alignment if the field did fill the entire column,
17869 because, in this case the deletion might narrow the column."
17870 (interactive "p")
17871 (org-check-before-invisible-edit 'delete)
17872 (if (and (org-table-p)
17873 (not (bolp))
17874 (not (= (char-after) ?|))
17875 (eq N 1))
17876 (if (looking-at ".*?|")
17877 (let ((pos (point))
17878 (noalign (looking-at "[^|\n\r]* |"))
17879 (c org-table-may-need-update))
17880 (replace-match (concat
17881 (substring (match-string 0) 1 -1)
17882 " |"))
17883 (goto-char pos)
17884 ;; noalign: if there were two spaces at the end, this field
17885 ;; does not determine the width of the column.
17886 (if noalign (setq org-table-may-need-update c)))
17887 (delete-char N))
17888 (delete-char N)
17889 (org-fix-tags-on-the-fly)))
17891 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17892 (put 'org-self-insert-command 'delete-selection t)
17893 (put 'orgtbl-self-insert-command 'delete-selection t)
17894 (put 'org-delete-char 'delete-selection 'supersede)
17895 (put 'org-delete-backward-char 'delete-selection 'supersede)
17896 (put 'org-yank 'delete-selection 'yank)
17898 ;; Make `flyspell-mode' delay after some commands
17899 (put 'org-self-insert-command 'flyspell-delayed t)
17900 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17901 (put 'org-delete-char 'flyspell-delayed t)
17902 (put 'org-delete-backward-char 'flyspell-delayed t)
17904 ;; Make pabbrev-mode expand after org-mode commands
17905 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17906 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17908 ;; How to do this: Measure non-white length of current string
17909 ;; If equal to column width, we should realign.
17911 (defun org-remap (map &rest commands)
17912 "In MAP, remap the functions given in COMMANDS.
17913 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17914 (let (new old)
17915 (while commands
17916 (setq old (pop commands) new (pop commands))
17917 (if (fboundp 'command-remapping)
17918 (org-defkey map (vector 'remap old) new)
17919 (substitute-key-definition old new map global-map)))))
17921 (when (eq org-enable-table-editor 'optimized)
17922 ;; If the user wants maximum table support, we need to hijack
17923 ;; some standard editing functions
17924 (org-remap org-mode-map
17925 'self-insert-command 'org-self-insert-command
17926 'delete-char 'org-delete-char
17927 'delete-backward-char 'org-delete-backward-char)
17928 (org-defkey org-mode-map "|" 'org-force-self-insert))
17930 (defvar org-ctrl-c-ctrl-c-hook nil
17931 "Hook for functions attaching themselves to `C-c C-c'.
17933 This can be used to add additional functionality to the C-c C-c
17934 key which executes context-dependent commands. This hook is run
17935 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17936 run after the last test.
17938 Each function will be called with no arguments. The function
17939 must check if the context is appropriate for it to act. If yes,
17940 it should do its thing and then return a non-nil value. If the
17941 context is wrong, just do nothing and return nil.")
17943 (defvar org-ctrl-c-ctrl-c-final-hook nil
17944 "Hook for functions attaching themselves to `C-c C-c'.
17946 This can be used to add additional functionality to the C-c C-c
17947 key which executes context-dependent commands. This hook is run
17948 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17949 before the first test.
17951 Each function will be called with no arguments. The function
17952 must check if the context is appropriate for it to act. If yes,
17953 it should do its thing and then return a non-nil value. If the
17954 context is wrong, just do nothing and return nil.")
17956 (defvar org-tab-first-hook nil
17957 "Hook for functions to attach themselves to TAB.
17958 See `org-ctrl-c-ctrl-c-hook' for more information.
17959 This hook runs as the first action when TAB is pressed, even before
17960 `org-cycle' messes around with the `outline-regexp' to cater for
17961 inline tasks and plain list item folding.
17962 If any function in this hook returns t, any other actions that
17963 would have been caused by TAB (such as table field motion or visibility
17964 cycling) will not occur.")
17966 (defvar org-tab-after-check-for-table-hook nil
17967 "Hook for functions to attach themselves to TAB.
17968 See `org-ctrl-c-ctrl-c-hook' for more information.
17969 This hook runs after it has been established that the cursor is not in a
17970 table, but before checking if the cursor is in a headline or if global cycling
17971 should be done.
17972 If any function in this hook returns t, not other actions like visibility
17973 cycling will be done.")
17975 (defvar org-tab-after-check-for-cycling-hook nil
17976 "Hook for functions to attach themselves to TAB.
17977 See `org-ctrl-c-ctrl-c-hook' for more information.
17978 This hook runs after it has been established that not table field motion and
17979 not visibility should be done because of current context. This is probably
17980 the place where a package like yasnippets can hook in.")
17982 (defvar org-tab-before-tab-emulation-hook nil
17983 "Hook for functions to attach themselves to TAB.
17984 See `org-ctrl-c-ctrl-c-hook' for more information.
17985 This hook runs after every other options for TAB have been exhausted, but
17986 before indentation and \t insertion takes place.")
17988 (defvar org-metaleft-hook nil
17989 "Hook for functions attaching themselves to `M-left'.
17990 See `org-ctrl-c-ctrl-c-hook' for more information.")
17991 (defvar org-metaright-hook nil
17992 "Hook for functions attaching themselves to `M-right'.
17993 See `org-ctrl-c-ctrl-c-hook' for more information.")
17994 (defvar org-metaup-hook nil
17995 "Hook for functions attaching themselves to `M-up'.
17996 See `org-ctrl-c-ctrl-c-hook' for more information.")
17997 (defvar org-metadown-hook nil
17998 "Hook for functions attaching themselves to `M-down'.
17999 See `org-ctrl-c-ctrl-c-hook' for more information.")
18000 (defvar org-shiftmetaleft-hook nil
18001 "Hook for functions attaching themselves to `M-S-left'.
18002 See `org-ctrl-c-ctrl-c-hook' for more information.")
18003 (defvar org-shiftmetaright-hook nil
18004 "Hook for functions attaching themselves to `M-S-right'.
18005 See `org-ctrl-c-ctrl-c-hook' for more information.")
18006 (defvar org-shiftmetaup-hook nil
18007 "Hook for functions attaching themselves to `M-S-up'.
18008 See `org-ctrl-c-ctrl-c-hook' for more information.")
18009 (defvar org-shiftmetadown-hook nil
18010 "Hook for functions attaching themselves to `M-S-down'.
18011 See `org-ctrl-c-ctrl-c-hook' for more information.")
18012 (defvar org-metareturn-hook nil
18013 "Hook for functions attaching themselves to `M-RET'.
18014 See `org-ctrl-c-ctrl-c-hook' for more information.")
18015 (defvar org-shiftup-hook nil
18016 "Hook for functions attaching themselves to `S-up'.
18017 See `org-ctrl-c-ctrl-c-hook' for more information.")
18018 (defvar org-shiftup-final-hook nil
18019 "Hook for functions attaching themselves to `S-up'.
18020 This one runs after all other options except shift-select have been excluded.
18021 See `org-ctrl-c-ctrl-c-hook' for more information.")
18022 (defvar org-shiftdown-hook nil
18023 "Hook for functions attaching themselves to `S-down'.
18024 See `org-ctrl-c-ctrl-c-hook' for more information.")
18025 (defvar org-shiftdown-final-hook nil
18026 "Hook for functions attaching themselves to `S-down'.
18027 This one runs after all other options except shift-select have been excluded.
18028 See `org-ctrl-c-ctrl-c-hook' for more information.")
18029 (defvar org-shiftleft-hook nil
18030 "Hook for functions attaching themselves to `S-left'.
18031 See `org-ctrl-c-ctrl-c-hook' for more information.")
18032 (defvar org-shiftleft-final-hook nil
18033 "Hook for functions attaching themselves to `S-left'.
18034 This one runs after all other options except shift-select have been excluded.
18035 See `org-ctrl-c-ctrl-c-hook' for more information.")
18036 (defvar org-shiftright-hook nil
18037 "Hook for functions attaching themselves to `S-right'.
18038 See `org-ctrl-c-ctrl-c-hook' for more information.")
18039 (defvar org-shiftright-final-hook nil
18040 "Hook for functions attaching themselves to `S-right'.
18041 This one runs after all other options except shift-select have been excluded.
18042 See `org-ctrl-c-ctrl-c-hook' for more information.")
18044 (defun org-modifier-cursor-error ()
18045 "Throw an error, a modified cursor command was applied in wrong context."
18046 (error "This command is active in special context like tables, headlines or items"))
18048 (defun org-shiftselect-error ()
18049 "Throw an error because Shift-Cursor command was applied in wrong context."
18050 (if (and (boundp 'shift-select-mode) shift-select-mode)
18051 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18052 (error "This command works only in special context like headlines or timestamps")))
18054 (defun org-call-for-shift-select (cmd)
18055 (let ((this-command-keys-shift-translated t))
18056 (call-interactively cmd)))
18058 (defun org-shifttab (&optional arg)
18059 "Global visibility cycling or move to previous table field.
18060 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18061 on context.
18062 See the individual commands for more information."
18063 (interactive "P")
18064 (cond
18065 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18066 ((integerp arg)
18067 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18068 (message "Content view to level: %d" arg)
18069 (org-content (prefix-numeric-value arg2))
18070 (setq org-cycle-global-status 'overview)))
18071 (t (call-interactively 'org-global-cycle))))
18073 (defun org-shiftmetaleft ()
18074 "Promote subtree or delete table column.
18075 Calls `org-promote-subtree', `org-outdent-item',
18076 or `org-table-delete-column', depending on context.
18077 See the individual commands for more information."
18078 (interactive)
18079 (cond
18080 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18081 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18082 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18083 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18084 (t (org-modifier-cursor-error))))
18086 (defun org-shiftmetaright ()
18087 "Demote subtree or insert table column.
18088 Calls `org-demote-subtree', `org-indent-item',
18089 or `org-table-insert-column', depending on context.
18090 See the individual commands for more information."
18091 (interactive)
18092 (cond
18093 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18094 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18095 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18096 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18097 (t (org-modifier-cursor-error))))
18099 (defun org-shiftmetaup (&optional arg)
18100 "Move subtree up or kill table row.
18101 Calls `org-move-subtree-up' or `org-table-kill-row' or
18102 `org-move-item-up' depending on context. See the individual commands
18103 for more information."
18104 (interactive "P")
18105 (cond
18106 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18107 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18108 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18109 ((org-at-item-p) (call-interactively 'org-move-item-up))
18110 (t (org-modifier-cursor-error))))
18112 (defun org-shiftmetadown (&optional arg)
18113 "Move subtree down or insert table row.
18114 Calls `org-move-subtree-down' or `org-table-insert-row' or
18115 `org-move-item-down', depending on context. See the individual
18116 commands for more information."
18117 (interactive "P")
18118 (cond
18119 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18120 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18121 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18122 ((org-at-item-p) (call-interactively 'org-move-item-down))
18123 (t (org-modifier-cursor-error))))
18125 (defsubst org-hidden-tree-error ()
18126 (error
18127 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18129 (defun org-metaleft (&optional arg)
18130 "Promote heading or move table column to left.
18131 Calls `org-do-promote' or `org-table-move-column', depending on context.
18132 With no specific context, calls the Emacs default `backward-word'.
18133 See the individual commands for more information."
18134 (interactive "P")
18135 (cond
18136 ((run-hook-with-args-until-success 'org-metaleft-hook))
18137 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18138 ((org-with-limited-levels
18139 (or (org-at-heading-p)
18140 (and (org-region-active-p)
18141 (save-excursion
18142 (goto-char (region-beginning))
18143 (org-at-heading-p)))))
18144 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18145 (call-interactively 'org-do-promote))
18146 ;; At an inline task.
18147 ((org-at-heading-p)
18148 (call-interactively 'org-inlinetask-promote))
18149 ((or (org-at-item-p)
18150 (and (org-region-active-p)
18151 (save-excursion
18152 (goto-char (region-beginning))
18153 (org-at-item-p))))
18154 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18155 (call-interactively 'org-outdent-item))
18156 (t (call-interactively 'backward-word))))
18158 (defun org-metaright (&optional arg)
18159 "Demote a subtree, a list item or move table column to right.
18160 In front of a drawer or a block keyword, indent it correctly.
18161 With no specific context, calls the Emacs default `forward-word'.
18162 See the individual commands for more information."
18163 (interactive "P")
18164 (cond
18165 ((run-hook-with-args-until-success 'org-metaright-hook))
18166 ((org-at-table-p) (call-interactively 'org-table-move-column))
18167 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18168 ((org-at-block-p) (call-interactively 'org-indent-block))
18169 ((org-with-limited-levels
18170 (or (org-at-heading-p)
18171 (and (org-region-active-p)
18172 (save-excursion
18173 (goto-char (region-beginning))
18174 (org-at-heading-p)))))
18175 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18176 (call-interactively 'org-do-demote))
18177 ;; At an inline task.
18178 ((org-at-heading-p)
18179 (call-interactively 'org-inlinetask-demote))
18180 ((or (org-at-item-p)
18181 (and (org-region-active-p)
18182 (save-excursion
18183 (goto-char (region-beginning))
18184 (org-at-item-p))))
18185 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18186 (call-interactively 'org-indent-item))
18187 (t (call-interactively 'forward-word))))
18189 (defun org-check-for-hidden (what)
18190 "Check if there are hidden headlines/items in the current visual line.
18191 WHAT can be either `headlines' or `items'. If the current line is
18192 an outline or item heading and it has a folded subtree below it,
18193 this function returns t, nil otherwise."
18194 (let ((re (cond
18195 ((eq what 'headlines) org-outline-regexp-bol)
18196 ((eq what 'items) (org-item-beginning-re))
18197 (t (error "This should not happen"))))
18198 beg end)
18199 (save-excursion
18200 (catch 'exit
18201 (unless (org-region-active-p)
18202 (setq beg (point-at-bol))
18203 (beginning-of-line 2)
18204 (while (and (not (eobp)) ;; this is like `next-line'
18205 (get-char-property (1- (point)) 'invisible))
18206 (beginning-of-line 2))
18207 (setq end (point))
18208 (goto-char beg)
18209 (goto-char (point-at-eol))
18210 (setq end (max end (point)))
18211 (while (re-search-forward re end t)
18212 (if (get-char-property (match-beginning 0) 'invisible)
18213 (throw 'exit t))))
18214 nil))))
18216 (defun org-metaup (&optional arg)
18217 "Move subtree up or move table row up.
18218 Calls `org-move-subtree-up' or `org-table-move-row' or
18219 `org-move-item-up', depending on context. See the individual commands
18220 for more information."
18221 (interactive "P")
18222 (cond
18223 ((run-hook-with-args-until-success 'org-metaup-hook))
18224 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18225 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18226 ((org-at-item-p) (call-interactively 'org-move-item-up))
18227 (t (transpose-lines 1) (beginning-of-line -1))))
18229 (defun org-metadown (&optional arg)
18230 "Move subtree down or move table row down.
18231 Calls `org-move-subtree-down' or `org-table-move-row' or
18232 `org-move-item-down', depending on context. See the individual
18233 commands for more information."
18234 (interactive "P")
18235 (cond
18236 ((run-hook-with-args-until-success 'org-metadown-hook))
18237 ((org-at-table-p) (call-interactively 'org-table-move-row))
18238 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18239 ((org-at-item-p) (call-interactively 'org-move-item-down))
18240 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18242 (defun org-shiftup (&optional arg)
18243 "Increase item in timestamp or increase priority of current headline.
18244 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18245 depending on context. See the individual commands for more information."
18246 (interactive "P")
18247 (cond
18248 ((run-hook-with-args-until-success 'org-shiftup-hook))
18249 ((and org-support-shift-select (org-region-active-p))
18250 (org-call-for-shift-select 'previous-line))
18251 ((org-at-timestamp-p t)
18252 (call-interactively (if org-edit-timestamp-down-means-later
18253 'org-timestamp-down 'org-timestamp-up)))
18254 ((and (not (eq org-support-shift-select 'always))
18255 org-enable-priority-commands
18256 (org-at-heading-p))
18257 (call-interactively 'org-priority-up))
18258 ((and (not org-support-shift-select) (org-at-item-p))
18259 (call-interactively 'org-previous-item))
18260 ((org-clocktable-try-shift 'up arg))
18261 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18262 (org-support-shift-select
18263 (org-call-for-shift-select 'previous-line))
18264 (t (org-shiftselect-error))))
18266 (defun org-shiftdown (&optional arg)
18267 "Decrease item in timestamp or decrease priority of current headline.
18268 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18269 depending on context. See the individual commands for more information."
18270 (interactive "P")
18271 (cond
18272 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18273 ((and org-support-shift-select (org-region-active-p))
18274 (org-call-for-shift-select 'next-line))
18275 ((org-at-timestamp-p t)
18276 (call-interactively (if org-edit-timestamp-down-means-later
18277 'org-timestamp-up 'org-timestamp-down)))
18278 ((and (not (eq org-support-shift-select 'always))
18279 org-enable-priority-commands
18280 (org-at-heading-p))
18281 (call-interactively 'org-priority-down))
18282 ((and (not org-support-shift-select) (org-at-item-p))
18283 (call-interactively 'org-next-item))
18284 ((org-clocktable-try-shift 'down arg))
18285 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18286 (org-support-shift-select
18287 (org-call-for-shift-select 'next-line))
18288 (t (org-shiftselect-error))))
18290 (defun org-shiftright (&optional arg)
18291 "Cycle the thing at point or in the current line, depending on context.
18292 Depending on context, this does one of the following:
18294 - switch a timestamp at point one day into the future
18295 - on a headline, switch to the next TODO keyword.
18296 - on an item, switch entire list to the next bullet type
18297 - on a property line, switch to the next allowed value
18298 - on a clocktable definition line, move time block into the future"
18299 (interactive "P")
18300 (cond
18301 ((run-hook-with-args-until-success 'org-shiftright-hook))
18302 ((and org-support-shift-select (org-region-active-p))
18303 (org-call-for-shift-select 'forward-char))
18304 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18305 ((and (not (eq org-support-shift-select 'always))
18306 (org-at-heading-p))
18307 (let ((org-inhibit-logging
18308 (not org-treat-S-cursor-todo-selection-as-state-change))
18309 (org-inhibit-blocking
18310 (not org-treat-S-cursor-todo-selection-as-state-change)))
18311 (org-call-with-arg 'org-todo 'right)))
18312 ((or (and org-support-shift-select
18313 (not (eq org-support-shift-select 'always))
18314 (org-at-item-bullet-p))
18315 (and (not org-support-shift-select) (org-at-item-p)))
18316 (org-call-with-arg 'org-cycle-list-bullet nil))
18317 ((and (not (eq org-support-shift-select 'always))
18318 (org-at-property-p))
18319 (call-interactively 'org-property-next-allowed-value))
18320 ((org-clocktable-try-shift 'right arg))
18321 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18322 (org-support-shift-select
18323 (org-call-for-shift-select 'forward-char))
18324 (t (org-shiftselect-error))))
18326 (defun org-shiftleft (&optional arg)
18327 "Cycle the thing at point or in the current line, depending on context.
18328 Depending on context, this does one of the following:
18330 - switch a timestamp at point one day into the past
18331 - on a headline, switch to the previous TODO keyword.
18332 - on an item, switch entire list to the previous bullet type
18333 - on a property line, switch to the previous allowed value
18334 - on a clocktable definition line, move time block into the past"
18335 (interactive "P")
18336 (cond
18337 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18338 ((and org-support-shift-select (org-region-active-p))
18339 (org-call-for-shift-select 'backward-char))
18340 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18341 ((and (not (eq org-support-shift-select 'always))
18342 (org-at-heading-p))
18343 (let ((org-inhibit-logging
18344 (not org-treat-S-cursor-todo-selection-as-state-change))
18345 (org-inhibit-blocking
18346 (not org-treat-S-cursor-todo-selection-as-state-change)))
18347 (org-call-with-arg 'org-todo 'left)))
18348 ((or (and org-support-shift-select
18349 (not (eq org-support-shift-select 'always))
18350 (org-at-item-bullet-p))
18351 (and (not org-support-shift-select) (org-at-item-p)))
18352 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18353 ((and (not (eq org-support-shift-select 'always))
18354 (org-at-property-p))
18355 (call-interactively 'org-property-previous-allowed-value))
18356 ((org-clocktable-try-shift 'left arg))
18357 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18358 (org-support-shift-select
18359 (org-call-for-shift-select 'backward-char))
18360 (t (org-shiftselect-error))))
18362 (defun org-shiftcontrolright ()
18363 "Switch to next TODO set."
18364 (interactive)
18365 (cond
18366 ((and org-support-shift-select (org-region-active-p))
18367 (org-call-for-shift-select 'forward-word))
18368 ((and (not (eq org-support-shift-select 'always))
18369 (org-at-heading-p))
18370 (org-call-with-arg 'org-todo 'nextset))
18371 (org-support-shift-select
18372 (org-call-for-shift-select 'forward-word))
18373 (t (org-shiftselect-error))))
18375 (defun org-shiftcontrolleft ()
18376 "Switch to previous TODO set."
18377 (interactive)
18378 (cond
18379 ((and org-support-shift-select (org-region-active-p))
18380 (org-call-for-shift-select 'backward-word))
18381 ((and (not (eq org-support-shift-select 'always))
18382 (org-at-heading-p))
18383 (org-call-with-arg 'org-todo 'previousset))
18384 (org-support-shift-select
18385 (org-call-for-shift-select 'backward-word))
18386 (t (org-shiftselect-error))))
18388 (defun org-shiftcontrolup ()
18389 "Change timestamps synchronously up in CLOCK log lines."
18390 (interactive)
18391 (cond ((and (not org-support-shift-select)
18392 (org-at-clock-log-p)
18393 (org-at-timestamp-p t))
18394 (org-clock-timestamps-up))
18395 (t (org-shiftselect-error))))
18397 (defun org-shiftcontroldown ()
18398 "Change timestamps synchronously down in CLOCK log lines."
18399 (interactive)
18400 (cond ((and (not org-support-shift-select)
18401 (org-at-clock-log-p)
18402 (org-at-timestamp-p t))
18403 (org-clock-timestamps-down))
18404 (t (org-shiftselect-error))))
18406 (defun org-ctrl-c-ret ()
18407 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18408 (interactive)
18409 (cond
18410 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18411 (t (call-interactively 'org-insert-heading))))
18413 (defun org-find-visible ()
18414 (let ((s (point)))
18415 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18416 (get-char-property s 'invisible)))
18418 (defun org-find-invisible ()
18419 (let ((s (point)))
18420 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18421 (not (get-char-property s 'invisible))))
18424 (defun org-copy-visible (beg end)
18425 "Copy the visible parts of the region."
18426 (interactive "r")
18427 (let (snippets s)
18428 (save-excursion
18429 (save-restriction
18430 (narrow-to-region beg end)
18431 (setq s (goto-char (point-min)))
18432 (while (not (= (point) (point-max)))
18433 (goto-char (org-find-invisible))
18434 (push (buffer-substring s (point)) snippets)
18435 (setq s (goto-char (org-find-visible))))))
18436 (kill-new (apply 'concat (nreverse snippets)))))
18438 (defun org-copy-special ()
18439 "Copy region in table or copy current subtree.
18440 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18441 See the individual commands for more information."
18442 (interactive)
18443 (call-interactively
18444 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18446 (defun org-cut-special ()
18447 "Cut region in table or cut current subtree.
18448 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18449 See the individual commands for more information."
18450 (interactive)
18451 (call-interactively
18452 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18454 (defun org-paste-special (arg)
18455 "Paste rectangular region into table, or past subtree relative to level.
18456 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18457 See the individual commands for more information."
18458 (interactive "P")
18459 (if (org-at-table-p)
18460 (org-table-paste-rectangle)
18461 (org-paste-subtree arg)))
18463 (defun org-edit-special (&optional arg)
18464 "Call a special editor for the stuff at point.
18465 When at a table, call the formula editor with `org-table-edit-formulas'.
18466 When at the first line of an src example, call `org-edit-src-code'.
18467 When in an #+include line, visit the include file. Otherwise call
18468 `ffap' to visit the file at point."
18469 (interactive)
18470 ;; possibly prep session before editing source
18471 (when arg
18472 (let* ((info (org-babel-get-src-block-info))
18473 (lang (nth 0 info))
18474 (params (nth 2 info))
18475 (session (cdr (assoc :session params))))
18476 (when (and info session) ;; we are in a source-code block with a session
18477 (funcall
18478 (intern (concat "org-babel-prep-session:" lang)) session params))))
18479 (cond ;; proceed with `org-edit-special'
18480 ((save-excursion
18481 (beginning-of-line 1)
18482 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18483 (find-file (org-trim (match-string 1))))
18484 ((org-edit-src-code))
18485 ((org-edit-fixed-width-region))
18486 ((org-at-table.el-p)
18487 (org-edit-src-code))
18488 ((or (org-at-table-p)
18489 (save-excursion
18490 (beginning-of-line 1)
18491 (looking-at "[ \t]*#\\+TBLFM:")))
18492 (call-interactively 'org-table-edit-formulas))
18493 (t (call-interactively 'ffap))))
18495 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18496 (defun org-ctrl-c-ctrl-c (&optional arg)
18497 "Set tags in headline, or update according to changed information at point.
18499 This command does many different things, depending on context:
18501 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18502 this is what we do.
18504 - If the cursor is on a statistics cookie, update it.
18506 - If the cursor is in a headline, prompt for tags and insert them
18507 into the current line, aligned to `org-tags-column'. When called
18508 with prefix arg, realign all tags in the current buffer.
18510 - If the cursor is in one of the special #+KEYWORD lines, this
18511 triggers scanning the buffer for these lines and updating the
18512 information.
18514 - If the cursor is inside a table, realign the table. This command
18515 works even if the automatic table editor has been turned off.
18517 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18518 the entire table.
18520 - If the cursor is at a footnote reference or definition, jump to
18521 the corresponding definition or references, respectively.
18523 - If the cursor is a the beginning of a dynamic block, update it.
18525 - If the current buffer is a capture buffer, close note and file it.
18527 - If the cursor is on a <<<target>>>, update radio targets and
18528 corresponding links in this buffer.
18530 - If the cursor is on a numbered item in a plain list, renumber the
18531 ordered list.
18533 - If the cursor is on a checkbox, toggle it.
18535 - If the cursor is on a code block, evaluate it. The variable
18536 `org-confirm-babel-evaluate' can be used to control prompting
18537 before code block evaluation, by default every code block
18538 evaluation requires confirmation. Code block evaluation can be
18539 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18540 (interactive "P")
18541 (let ((org-enable-table-editor t))
18542 (cond
18543 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18544 org-occur-highlights
18545 org-latex-fragment-image-overlays)
18546 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18547 (org-remove-occur-highlights)
18548 (org-remove-latex-fragment-image-overlays)
18549 (message "Temporary highlights/overlays removed from current buffer"))
18550 ((and (local-variable-p 'org-finish-function (current-buffer))
18551 (fboundp org-finish-function))
18552 (funcall org-finish-function))
18553 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18554 ((org-in-regexp org-ts-regexp-both)
18555 (org-timestamp-change 0 'day))
18556 ((or (looking-at org-property-start-re)
18557 (org-at-property-p))
18558 (call-interactively 'org-property-action))
18559 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18560 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18561 (or (org-at-heading-p) (org-at-item-p)))
18562 (call-interactively 'org-update-statistics-cookies))
18563 ((org-at-heading-p) (call-interactively 'org-set-tags))
18564 ((org-at-table.el-p)
18565 (message "Use C-c ' to edit table.el tables"))
18566 ((org-at-table-p)
18567 (org-table-maybe-eval-formula)
18568 (if arg
18569 (call-interactively 'org-table-recalculate)
18570 (org-table-maybe-recalculate-line))
18571 (call-interactively 'org-table-align)
18572 (orgtbl-send-table 'maybe))
18573 ((or (org-footnote-at-reference-p)
18574 (org-footnote-at-definition-p))
18575 (call-interactively 'org-footnote-action))
18576 ((org-at-item-checkbox-p)
18577 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18578 ;; list only if at top item.
18579 (let* ((cbox (match-string 1))
18580 (struct (org-list-struct))
18581 (old-struct (copy-tree struct))
18582 (parents (org-list-parents-alist struct))
18583 (orderedp (org-entry-get nil "ORDERED"))
18584 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18585 block-item)
18586 ;; Use a light version of `org-toggle-checkbox' to avoid
18587 ;; computing list structure twice.
18588 (let ((new-box (cond
18589 ((equal arg '(16)) "[-]")
18590 ((equal arg '(4)) nil)
18591 ((equal "[X]" cbox) "[ ]")
18592 (t "[X]"))))
18593 (if (and firstp arg)
18594 ;; If at first item of sub-list, remove check-box from
18595 ;; every item at the same level.
18596 (mapc
18597 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18598 (org-list-get-all-items
18599 (point-at-bol) struct (org-list-prevs-alist struct)))
18600 (org-list-set-checkbox (point-at-bol) struct new-box)))
18601 ;; Replicate `org-list-write-struct', while grabbing a return
18602 ;; value from `org-list-struct-fix-box'.
18603 (org-list-struct-fix-ind struct parents 2)
18604 (org-list-struct-fix-item-end struct)
18605 (let ((prevs (org-list-prevs-alist struct)))
18606 (org-list-struct-fix-bul struct prevs)
18607 (org-list-struct-fix-ind struct parents)
18608 (setq block-item
18609 (org-list-struct-fix-box struct parents prevs orderedp)))
18610 (org-list-struct-apply-struct struct old-struct)
18611 (org-update-checkbox-count-maybe)
18612 (when block-item
18613 (message
18614 "Checkboxes were removed due to unchecked box at line %d"
18615 (org-current-line block-item)))
18616 (when firstp (org-list-send-list 'maybe))))
18617 ((org-at-item-p)
18618 ;; Cursor at an item: repair list. Do checkbox related actions
18619 ;; only if function was called with an argument. Send list only
18620 ;; if at top item.
18621 (let* ((struct (org-list-struct))
18622 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18623 old-struct)
18624 (when arg
18625 (setq old-struct (copy-tree struct))
18626 (if firstp
18627 ;; If at first item of sub-list, add check-box to every
18628 ;; item at the same level.
18629 (mapc
18630 (lambda (pos)
18631 (unless (org-list-get-checkbox pos struct)
18632 (org-list-set-checkbox pos struct "[ ]")))
18633 (org-list-get-all-items
18634 (point-at-bol) struct (org-list-prevs-alist struct)))
18635 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18636 (org-list-write-struct
18637 struct (org-list-parents-alist struct) old-struct)
18638 (when arg (org-update-checkbox-count-maybe))
18639 (when firstp (org-list-send-list 'maybe))))
18640 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18641 ;; Dynamic block
18642 (beginning-of-line 1)
18643 (save-excursion (org-update-dblock)))
18644 ((save-excursion
18645 (beginning-of-line 1)
18646 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18647 (cond
18648 ((equal (match-string 1) "TBLFM")
18649 ;; Recalculate the table before this line
18650 (save-excursion
18651 (beginning-of-line 1)
18652 (skip-chars-backward " \r\n\t")
18653 (if (org-at-table-p)
18654 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18656 (let ((org-inhibit-startup-visibility-stuff t)
18657 (org-startup-align-all-tables nil))
18658 (when (boundp 'org-table-coordinate-overlays)
18659 (mapc 'delete-overlay org-table-coordinate-overlays)
18660 (setq org-table-coordinate-overlays nil))
18661 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18662 (message "Local setup has been refreshed"))))
18663 ((org-clock-update-time-maybe))
18665 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18666 (error "C-c C-c can do nothing useful at this location"))))))
18668 (defun org-mode-restart ()
18669 "Restart Org-mode, to scan again for special lines.
18670 Also updates the keyword regular expressions."
18671 (interactive)
18672 (org-mode)
18673 (message "Org-mode restarted"))
18675 (defun org-kill-note-or-show-branches ()
18676 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18677 (interactive)
18678 (if (not org-finish-function)
18679 (progn
18680 (hide-subtree)
18681 (call-interactively 'show-branches))
18682 (let ((org-note-abort t))
18683 (funcall org-finish-function))))
18685 (defun org-return (&optional indent)
18686 "Goto next table row or insert a newline.
18687 Calls `org-table-next-row' or `newline', depending on context.
18688 See the individual commands for more information."
18689 (interactive)
18690 (cond
18691 ((or (bobp) (org-in-src-block-p))
18692 (if indent (newline-and-indent) (newline)))
18693 ((org-at-table-p)
18694 (org-table-justify-field-maybe)
18695 (call-interactively 'org-table-next-row))
18696 ;; when `newline-and-indent' is called within a list, make sure
18697 ;; text moved stays inside the item.
18698 ((and (org-in-item-p) indent)
18699 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18700 (progn
18701 (save-match-data (newline))
18702 (org-indent-line-to (length (match-string 0))))
18703 (let ((ind (org-get-indentation)))
18704 (newline)
18705 (if (org-looking-back org-list-end-re)
18706 (org-indent-line-function)
18707 (org-indent-line-to ind)))))
18708 ((and org-return-follows-link
18709 (let ((tprop (get-text-property (point) 'face)))
18710 (or (eq tprop 'org-link)
18711 (and (listp tprop) (memq 'org-link tprop)))))
18712 (call-interactively 'org-open-at-point))
18713 ((and (org-at-heading-p)
18714 (looking-at
18715 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18716 (org-show-entry)
18717 (end-of-line 1)
18718 (newline))
18719 (t (if indent (newline-and-indent) (newline)))))
18721 (defun org-return-indent ()
18722 "Goto next table row or insert a newline and indent.
18723 Calls `org-table-next-row' or `newline-and-indent', depending on
18724 context. See the individual commands for more information."
18725 (interactive)
18726 (org-return t))
18728 (defun org-ctrl-c-star ()
18729 "Compute table, or change heading status of lines.
18730 Calls `org-table-recalculate' or `org-toggle-heading',
18731 depending on context."
18732 (interactive)
18733 (cond
18734 ((org-at-table-p)
18735 (call-interactively 'org-table-recalculate))
18737 ;; Convert all lines in region to list items
18738 (call-interactively 'org-toggle-heading))))
18740 (defun org-ctrl-c-minus ()
18741 "Insert separator line in table or modify bullet status of line.
18742 Also turns a plain line or a region of lines into list items.
18743 Calls `org-table-insert-hline', `org-toggle-item', or
18744 `org-cycle-list-bullet', depending on context."
18745 (interactive)
18746 (cond
18747 ((org-at-table-p)
18748 (call-interactively 'org-table-insert-hline))
18749 ((org-region-active-p)
18750 (call-interactively 'org-toggle-item))
18751 ((org-in-item-p)
18752 (call-interactively 'org-cycle-list-bullet))
18754 (call-interactively 'org-toggle-item))))
18756 (defun org-toggle-item (arg)
18757 "Convert headings or normal lines to items, items to normal lines.
18758 If there is no active region, only the current line is considered.
18760 If the first non blank line in the region is an headline, convert
18761 all headlines to items, shifting text accordingly.
18763 If it is an item, convert all items to normal lines.
18765 If it is normal text, change region into an item. With a prefix
18766 argument ARG, change each line in region into an item."
18767 (interactive "P")
18768 (let ((shift-text
18769 (function
18770 ;; Shift text in current section to IND, from point to END.
18771 ;; The function leaves point to END line.
18772 (lambda (ind end)
18773 (let ((min-i 1000) (end (copy-marker end)))
18774 ;; First determine the minimum indentation (MIN-I) of
18775 ;; the text.
18776 (save-excursion
18777 (catch 'exit
18778 (while (< (point) end)
18779 (let ((i (org-get-indentation)))
18780 (cond
18781 ;; Skip blank lines and inline tasks.
18782 ((looking-at "^[ \t]*$"))
18783 ((looking-at org-outline-regexp-bol))
18784 ;; We can't find less than 0 indentation.
18785 ((zerop i) (throw 'exit (setq min-i 0)))
18786 ((< i min-i) (setq min-i i))))
18787 (forward-line))))
18788 ;; Then indent each line so that a line indented to
18789 ;; MIN-I becomes indented to IND. Ignore blank lines
18790 ;; and inline tasks in the process.
18791 (let ((delta (- ind min-i)))
18792 (while (< (point) end)
18793 (unless (or (looking-at "^[ \t]*$")
18794 (looking-at org-outline-regexp-bol))
18795 (org-indent-line-to (+ (org-get-indentation) delta)))
18796 (forward-line)))))))
18797 (skip-blanks
18798 (function
18799 ;; Return beginning of first non-blank line, starting from
18800 ;; line at POS.
18801 (lambda (pos)
18802 (save-excursion
18803 (goto-char pos)
18804 (skip-chars-forward " \r\t\n")
18805 (point-at-bol)))))
18806 beg end)
18807 ;; Determine boundaries of changes.
18808 (if (org-region-active-p)
18809 (setq beg (funcall skip-blanks (region-beginning))
18810 end (copy-marker (region-end)))
18811 (setq beg (funcall skip-blanks (point-at-bol))
18812 end (copy-marker (point-at-eol))))
18813 ;; Depending on the starting line, choose an action on the text
18814 ;; between BEG and END.
18815 (org-with-limited-levels
18816 (save-excursion
18817 (goto-char beg)
18818 (cond
18819 ;; Case 1. Start at an item: de-itemize. Note that it only
18820 ;; happens when a region is active: `org-ctrl-c-minus'
18821 ;; would call `org-cycle-list-bullet' otherwise.
18822 ((org-at-item-p)
18823 (while (< (point) end)
18824 (when (org-at-item-p)
18825 (skip-chars-forward " \t")
18826 (delete-region (point) (match-end 0)))
18827 (forward-line)))
18828 ;; Case 2. Start at an heading: convert to items.
18829 ((org-at-heading-p)
18830 (let* ((bul (org-list-bullet-string "-"))
18831 (bul-len (length bul))
18832 ;; Indentation of the first heading. It should be
18833 ;; relative to the indentation of its parent, if any.
18834 (start-ind (save-excursion
18835 (cond
18836 ((not org-adapt-indentation) 0)
18837 ((not (outline-previous-heading)) 0)
18838 (t (length (match-string 0))))))
18839 ;; Level of first heading. Further headings will be
18840 ;; compared to it to determine hierarchy in the list.
18841 (ref-level (org-reduced-level (org-outline-level))))
18842 (while (< (point) end)
18843 (let* ((level (org-reduced-level (org-outline-level)))
18844 (delta (max 0 (- level ref-level))))
18845 ;; If current headline is less indented than the first
18846 ;; one, set it as reference, in order to preserve
18847 ;; subtrees.
18848 (when (< level ref-level) (setq ref-level level))
18849 (replace-match bul t t)
18850 (org-indent-line-to (+ start-ind (* delta bul-len)))
18851 ;; Ensure all text down to END (or SECTION-END) belongs
18852 ;; to the newly created item.
18853 (let ((section-end (save-excursion
18854 (or (outline-next-heading) (point)))))
18855 (forward-line)
18856 (funcall shift-text
18857 (+ start-ind (* (1+ delta) bul-len))
18858 (min end section-end)))))))
18859 ;; Case 3. Normal line with ARG: turn each non-item line into
18860 ;; an item.
18861 (arg
18862 (while (< (point) end)
18863 (unless (or (org-at-heading-p) (org-at-item-p))
18864 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18865 (replace-match
18866 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18867 (forward-line)))
18868 ;; Case 4. Normal line without ARG: make the first line of
18869 ;; region an item, and shift indentation of others
18870 ;; lines to set them as item's body.
18871 (t (let* ((bul (org-list-bullet-string "-"))
18872 (bul-len (length bul))
18873 (ref-ind (org-get-indentation)))
18874 (skip-chars-forward " \t")
18875 (insert bul)
18876 (forward-line)
18877 (while (< (point) end)
18878 ;; Ensure that lines less indented than first one
18879 ;; still get included in item body.
18880 (funcall shift-text
18881 (+ ref-ind bul-len)
18882 (min end (save-excursion (or (outline-next-heading)
18883 (point)))))
18884 (forward-line)))))))))
18886 (defun org-toggle-heading (&optional nstars)
18887 "Convert headings to normal text, or items or text to headings.
18888 If there is no active region, only the current line is considered.
18890 If the first non blank line is an headline, remove the stars from
18891 all headlines in the region.
18893 If it is a plain list item, turn all plain list items into headings.
18895 If it is a normal line, turn each and every normal line (i.e. not
18896 an heading or an item) in the region into a heading.
18898 When converting a line into a heading, the number of stars is chosen
18899 such that the lines become children of the current entry. However,
18900 when a prefix argument is given, its value determines the number of
18901 stars to add."
18902 (interactive "P")
18903 (let ((skip-blanks
18904 (function
18905 ;; Return beginning of first non-blank line, starting from
18906 ;; line at POS.
18907 (lambda (pos)
18908 (save-excursion
18909 (goto-char pos)
18910 (skip-chars-forward " \r\t\n")
18911 (point-at-bol)))))
18912 beg end)
18913 ;; Determine boundaries of changes. If region ends at a bol, do
18914 ;; not consider the last line to be in the region.
18915 (if (org-region-active-p)
18916 (setq beg (funcall skip-blanks (region-beginning))
18917 end (copy-marker (save-excursion
18918 (goto-char (region-end))
18919 (if (bolp) (point) (point-at-eol)))))
18920 (setq beg (funcall skip-blanks (point-at-bol))
18921 end (copy-marker (point-at-eol))))
18922 ;; Ensure inline tasks don't count as headings.
18923 (org-with-limited-levels
18924 (save-excursion
18925 (goto-char beg)
18926 (cond
18927 ;; Case 1. Started at an heading: de-star headings.
18928 ((org-at-heading-p)
18929 (while (< (point) end)
18930 (when (org-at-heading-p t)
18931 (looking-at org-outline-regexp) (replace-match ""))
18932 (forward-line)))
18933 ;; Case 2. Started at an item: change items into headlines.
18934 ;; One star will be added by `org-list-to-subtree'.
18935 ((org-at-item-p)
18936 (let* ((stars (make-string
18937 (if nstars
18938 ;; subtract the star that will be added again by
18939 ;; `org-list-to-subtree'
18940 (1- (prefix-numeric-value current-prefix-arg))
18941 (or (org-current-level) 0))
18942 ?*))
18943 (add-stars
18944 (cond (nstars "") ; stars from prefix only
18945 ((equal stars "") "") ; before first heading
18946 (org-odd-levels-only "*") ; inside heading, odd
18947 (t "")))) ; inside heading, oddeven
18948 (while (< (point) end)
18949 (when (org-at-item-p)
18950 ;; Pay attention to cases when region ends before list.
18951 (let* ((struct (org-list-struct))
18952 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18953 (save-restriction
18954 (narrow-to-region (point) list-end)
18955 (insert
18956 (org-list-to-subtree
18957 (org-list-parse-list t)
18958 '(:istart (concat stars add-stars (funcall get-stars depth))
18959 :icount (concat stars add-stars (funcall get-stars depth))))))))
18960 (forward-line))))
18961 ;; Case 3. Started at normal text: make every line an heading,
18962 ;; skipping headlines and items.
18963 (t (let* ((stars (make-string
18964 (if nstars
18965 (prefix-numeric-value current-prefix-arg)
18966 (or (org-current-level) 0))
18967 ?*))
18968 (add-stars
18969 (cond (nstars "") ; stars from prefix only
18970 ((equal stars "") "*") ; before first heading
18971 (org-odd-levels-only "**") ; inside heading, odd
18972 (t "*"))) ; inside heading, oddeven
18973 (rpl (concat stars add-stars " ")))
18974 (while (< (point) end)
18975 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18976 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18977 (replace-match (concat rpl (match-string 2))))
18978 (forward-line)))))))))
18980 (defun org-meta-return (&optional arg)
18981 "Insert a new heading or wrap a region in a table.
18982 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18983 See the individual commands for more information."
18984 (interactive "P")
18985 (cond
18986 ((run-hook-with-args-until-success 'org-metareturn-hook))
18987 ((or (org-at-drawer-p) (org-at-property-p))
18988 (newline-and-indent))
18989 ((org-at-table-p)
18990 (call-interactively 'org-table-wrap-region))
18991 (t (call-interactively 'org-insert-heading))))
18993 ;;; Menu entries
18995 ;; Define the Org-mode menus
18996 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18997 '("Tbl"
18998 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18999 ["Next Field" org-cycle (org-at-table-p)]
19000 ["Previous Field" org-shifttab (org-at-table-p)]
19001 ["Next Row" org-return (org-at-table-p)]
19002 "--"
19003 ["Blank Field" org-table-blank-field (org-at-table-p)]
19004 ["Edit Field" org-table-edit-field (org-at-table-p)]
19005 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19006 "--"
19007 ("Column"
19008 ["Move Column Left" org-metaleft (org-at-table-p)]
19009 ["Move Column Right" org-metaright (org-at-table-p)]
19010 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19011 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19012 ("Row"
19013 ["Move Row Up" org-metaup (org-at-table-p)]
19014 ["Move Row Down" org-metadown (org-at-table-p)]
19015 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19016 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19017 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19018 "--"
19019 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19020 ("Rectangle"
19021 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19022 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19023 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19024 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19025 "--"
19026 ("Calculate"
19027 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19028 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19029 ["Edit Formulas" org-edit-special (org-at-table-p)]
19030 "--"
19031 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19032 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19033 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19034 "--"
19035 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19036 "--"
19037 ["Sum Column/Rectangle" org-table-sum
19038 (or (org-at-table-p) (org-region-active-p))]
19039 ["Which Column?" org-table-current-column (org-at-table-p)])
19040 ["Debug Formulas"
19041 org-table-toggle-formula-debugger
19042 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19043 ["Show Col/Row Numbers"
19044 org-table-toggle-coordinate-overlays
19045 :style toggle
19046 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19047 "--"
19048 ["Create" org-table-create (and (not (org-at-table-p))
19049 org-enable-table-editor)]
19050 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19051 ["Import from File" org-table-import (not (org-at-table-p))]
19052 ["Export to File" org-table-export (org-at-table-p)]
19053 "--"
19054 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19056 (easy-menu-define org-org-menu org-mode-map "Org menu"
19057 '("Org"
19058 ("Show/Hide"
19059 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19060 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19061 ["Sparse Tree..." org-sparse-tree t]
19062 ["Reveal Context" org-reveal t]
19063 ["Show All" show-all t]
19064 "--"
19065 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19066 "--"
19067 ["New Heading" org-insert-heading t]
19068 ("Navigate Headings"
19069 ["Up" outline-up-heading t]
19070 ["Next" outline-next-visible-heading t]
19071 ["Previous" outline-previous-visible-heading t]
19072 ["Next Same Level" outline-forward-same-level t]
19073 ["Previous Same Level" outline-backward-same-level t]
19074 "--"
19075 ["Jump" org-goto t])
19076 ("Edit Structure"
19077 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19078 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19079 "--"
19080 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19081 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19082 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19083 "--"
19084 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19085 "--"
19086 ["Copy visible text" org-copy-visible t]
19087 "--"
19088 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19089 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19090 ["Demote Heading" org-metaright (not (org-at-table-p))]
19091 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19092 "--"
19093 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19094 "--"
19095 ["Convert to odd levels" org-convert-to-odd-levels t]
19096 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19097 ("Editing"
19098 ["Emphasis..." org-emphasize t]
19099 ["Edit Source Example" org-edit-special t]
19100 "--"
19101 ["Footnote new/jump" org-footnote-action t]
19102 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19103 ("Archive"
19104 ["Archive (default method)" org-archive-subtree-default t]
19105 "--"
19106 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19107 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19108 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19110 "--"
19111 ("Hyperlinks"
19112 ["Store Link (Global)" org-store-link t]
19113 ["Find existing link to here" org-occur-link-in-agenda-files t]
19114 ["Insert Link" org-insert-link t]
19115 ["Follow Link" org-open-at-point t]
19116 "--"
19117 ["Next link" org-next-link t]
19118 ["Previous link" org-previous-link t]
19119 "--"
19120 ["Descriptive Links"
19121 org-toggle-link-display
19122 :style radio
19123 :selected org-descriptive-links
19125 ["Literal Links"
19126 org-toggle-link-display
19127 :style radio
19128 :selected (not org-descriptive-links)])
19129 "--"
19130 ("TODO Lists"
19131 ["TODO/DONE/-" org-todo t]
19132 ("Select keyword"
19133 ["Next keyword" org-shiftright (org-at-heading-p)]
19134 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19135 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19136 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19137 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19138 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19139 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19140 "--"
19141 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19142 :selected org-enforce-todo-dependencies :style toggle :active t]
19143 "Settings for tree at point"
19144 ["Do Children sequentially" org-toggle-ordered-property :style radio
19145 :selected (org-entry-get nil "ORDERED")
19146 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19147 ["Do Children parallel" org-toggle-ordered-property :style radio
19148 :selected (not (org-entry-get nil "ORDERED"))
19149 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19150 "--"
19151 ["Set Priority" org-priority t]
19152 ["Priority Up" org-shiftup t]
19153 ["Priority Down" org-shiftdown t]
19154 "--"
19155 ["Get news from all feeds" org-feed-update-all t]
19156 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19157 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19158 ("TAGS and Properties"
19159 ["Set Tags" org-set-tags-command t]
19160 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19161 "--"
19162 ["Set property" org-set-property t]
19163 ["Column view of properties" org-columns t]
19164 ["Insert Column View DBlock" org-insert-columns-dblock t])
19165 ("Dates and Scheduling"
19166 ["Timestamp" org-time-stamp t]
19167 ["Timestamp (inactive)" org-time-stamp-inactive t]
19168 ("Change Date"
19169 ["1 Day Later" org-shiftright t]
19170 ["1 Day Earlier" org-shiftleft t]
19171 ["1 ... Later" org-shiftup t]
19172 ["1 ... Earlier" org-shiftdown t])
19173 ["Compute Time Range" org-evaluate-time-range t]
19174 ["Schedule Item" org-schedule t]
19175 ["Deadline" org-deadline t]
19176 "--"
19177 ["Custom time format" org-toggle-time-stamp-overlays
19178 :style radio :selected org-display-custom-times]
19179 "--"
19180 ["Goto Calendar" org-goto-calendar t]
19181 ["Date from Calendar" org-date-from-calendar t]
19182 "--"
19183 ["Start/Restart Timer" org-timer-start t]
19184 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19185 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19186 ["Insert Timer String" org-timer t]
19187 ["Insert Timer Item" org-timer-item t])
19188 ("Logging work"
19189 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19190 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19191 ["Clock out" org-clock-out t]
19192 ["Clock cancel" org-clock-cancel t]
19193 "--"
19194 ["Mark as default task" org-clock-mark-default-task t]
19195 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19196 ["Goto running clock" org-clock-goto t]
19197 "--"
19198 ["Display times" org-clock-display t]
19199 ["Create clock table" org-clock-report t]
19200 "--"
19201 ["Record DONE time"
19202 (progn (setq org-log-done (not org-log-done))
19203 (message "Switching to %s will %s record a timestamp"
19204 (car org-done-keywords)
19205 (if org-log-done "automatically" "not")))
19206 :style toggle :selected org-log-done])
19207 "--"
19208 ["Agenda Command..." org-agenda t]
19209 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19210 ("File List for Agenda")
19211 ("Special views current file"
19212 ["TODO Tree" org-show-todo-tree t]
19213 ["Check Deadlines" org-check-deadlines t]
19214 ["Timeline" org-timeline t]
19215 ["Tags/Property tree" org-match-sparse-tree t])
19216 "--"
19217 ["Export/Publish..." org-export t]
19218 ("LaTeX"
19219 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19220 :selected org-cdlatex-mode]
19221 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19222 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19223 ["Modify math symbol" org-cdlatex-math-modify
19224 (org-inside-LaTeX-fragment-p)]
19225 ["Insert citation" org-reftex-citation t]
19226 "--"
19227 ["Template for BEAMER" (progn (require 'org-beamer)
19228 (org-insert-beamer-options-template)) t])
19229 "--"
19230 ("MobileOrg"
19231 ["Push Files and Views" org-mobile-push t]
19232 ["Get Captured and Flagged" org-mobile-pull t]
19233 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19234 "--"
19235 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19236 "--"
19237 ("Documentation"
19238 ["Show Version" org-version t]
19239 ["Info Documentation" org-info t])
19240 ("Customize"
19241 ["Browse Org Group" org-customize t]
19242 "--"
19243 ["Expand This Menu" org-create-customize-menu
19244 (fboundp 'customize-menu-create)])
19245 ["Send bug report" org-submit-bug-report t]
19246 "--"
19247 ("Refresh/Reload"
19248 ["Refresh setup current buffer" org-mode-restart t]
19249 ["Reload Org (after update)" org-reload t]
19250 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19253 (defun org-info (&optional node)
19254 "Read documentation for Org-mode in the info system.
19255 With optional NODE, go directly to that node."
19256 (interactive)
19257 (info (format "(org)%s" (or node ""))))
19259 ;;;###autoload
19260 (defun org-submit-bug-report ()
19261 "Submit a bug report on Org-mode via mail.
19263 Don't hesitate to report any problems or inaccurate documentation.
19265 If you don't have setup sending mail from (X)Emacs, please copy the
19266 output buffer into your mail program, as it gives us important
19267 information about your Org-mode version and configuration."
19268 (interactive)
19269 (require 'reporter)
19270 (org-load-modules-maybe)
19271 (org-require-autoloaded-modules)
19272 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19273 (reporter-submit-bug-report
19274 "emacs-orgmode@gnu.org"
19275 (org-version)
19276 (let (list)
19277 (save-window-excursion
19278 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19279 (delete-other-windows)
19280 (erase-buffer)
19281 (insert "You are about to submit a bug report to the Org-mode mailing list.
19283 We would like to add your full Org-mode and Outline configuration to the
19284 bug report. This greatly simplifies the work of the maintainer and
19285 other experts on the mailing list.
19287 HOWEVER, some variables you have customized may contain private
19288 information. The names of customers, colleagues, or friends, might
19289 appear in the form of file names, tags, todo states, or search strings.
19290 If you answer yes to the prompt, you might want to check and remove
19291 such private information before sending the email.")
19292 (add-text-properties (point-min) (point-max) '(face org-warning))
19293 (when (yes-or-no-p "Include your Org-mode configuration ")
19294 (mapatoms
19295 (lambda (v)
19296 (and (boundp v)
19297 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19298 (or (and (symbol-value v)
19299 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19300 (and
19301 (get v 'custom-type) (get v 'standard-value)
19302 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19303 (push v list)))))
19304 (kill-buffer (get-buffer "*Warn about privacy*"))
19305 list))
19306 nil nil
19307 "Remember to cover the basics, that is, what you expected to happen and
19308 what in fact did happen. You don't know how to make a good report? See
19310 http://orgmode.org/manual/Feedback.html#Feedback
19312 Your bug report will be posted to the Org-mode mailing list.
19313 ------------------------------------------------------------------------")
19314 (save-excursion
19315 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19316 (replace-match "\\1Bug: \\3 [\\2]")))))
19319 (defun org-install-agenda-files-menu ()
19320 (let ((bl (buffer-list)))
19321 (save-excursion
19322 (while bl
19323 (set-buffer (pop bl))
19324 (if (eq major-mode 'org-mode) (setq bl nil)))
19325 (when (eq major-mode 'org-mode)
19326 (easy-menu-change
19327 '("Org") "File List for Agenda"
19328 (append
19329 (list
19330 ["Edit File List" (org-edit-agenda-file-list) t]
19331 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19332 ["Remove Current File from List" org-remove-file t]
19333 ["Cycle through agenda files" org-cycle-agenda-files t]
19334 ["Occur in all agenda files" org-occur-in-agenda-files t]
19335 "--")
19336 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19338 ;;;; Documentation
19340 ;;;###autoload
19341 (defun org-require-autoloaded-modules ()
19342 (interactive)
19343 (mapc 'require
19344 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19345 org-docbook org-exp org-html org-icalendar
19346 org-id org-latex
19347 org-publish org-remember org-table
19348 org-timer org-xoxo)))
19350 ;;;###autoload
19351 (defun org-reload (&optional uncompiled)
19352 "Reload all org lisp files.
19353 With prefix arg UNCOMPILED, load the uncompiled versions."
19354 (interactive "P")
19355 (require 'find-func)
19356 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19357 (dir-org (file-name-directory (org-find-library-name "org")))
19358 (dir-org-contrib (ignore-errors
19359 (file-name-directory
19360 (org-find-library-name "org-contribdir"))))
19361 (babel-files
19362 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19363 (append (list nil "comint" "eval" "exp" "keys"
19364 "lob" "ref" "table" "tangle")
19365 (delq nil
19366 (mapcar
19367 (lambda (lang)
19368 (when (cdr lang) (symbol-name (car lang))))
19369 org-babel-load-languages)))))
19370 (files
19371 (append (directory-files dir-org t file-re)
19372 babel-files
19373 (and dir-org-contrib
19374 (directory-files dir-org-contrib t file-re))))
19375 (remove-re (concat (if (featurep 'xemacs)
19376 "org-colview" "org-colview-xemacs")
19377 "\\'")))
19378 (setq files (mapcar 'file-name-sans-extension files))
19379 (setq files (mapcar
19380 (lambda (x) (if (string-match remove-re x) nil x))
19381 files))
19382 (setq files (delq nil files))
19383 (mapc
19384 (lambda (f)
19385 (when (featurep (intern (file-name-nondirectory f)))
19386 (if (and (not uncompiled)
19387 (file-exists-p (concat f ".elc")))
19388 (load (concat f ".elc") nil nil t)
19389 (load (concat f ".el") nil nil t))))
19390 files))
19391 (org-version))
19393 ;;;###autoload
19394 (defun org-customize ()
19395 "Call the customize function with org as argument."
19396 (interactive)
19397 (org-load-modules-maybe)
19398 (org-require-autoloaded-modules)
19399 (customize-browse 'org))
19401 (defun org-create-customize-menu ()
19402 "Create a full customization menu for Org-mode, insert it into the menu."
19403 (interactive)
19404 (org-load-modules-maybe)
19405 (org-require-autoloaded-modules)
19406 (if (fboundp 'customize-menu-create)
19407 (progn
19408 (easy-menu-change
19409 '("Org") "Customize"
19410 `(["Browse Org group" org-customize t]
19411 "--"
19412 ,(customize-menu-create 'org)
19413 ["Set" Custom-set t]
19414 ["Save" Custom-save t]
19415 ["Reset to Current" Custom-reset-current t]
19416 ["Reset to Saved" Custom-reset-saved t]
19417 ["Reset to Standard Settings" Custom-reset-standard t]))
19418 (message "\"Org\"-menu now contains full customization menu"))
19419 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19421 ;;;; Miscellaneous stuff
19423 ;;; Generally useful functions
19425 (defun org-get-at-bol (property)
19426 "Get text property PROPERTY at beginning of line."
19427 (get-text-property (point-at-bol) property))
19429 (defun org-find-text-property-in-string (prop s)
19430 "Return the first non-nil value of property PROP in string S."
19431 (or (get-text-property 0 prop s)
19432 (get-text-property (or (next-single-property-change 0 prop s) 0)
19433 prop s)))
19435 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19436 "Display the given MESSAGE as a warning."
19437 (if (fboundp 'display-warning)
19438 (display-warning 'org message
19439 (if (featurep 'xemacs) 'warning :warning))
19440 (let ((buf (get-buffer-create "*Org warnings*")))
19441 (with-current-buffer buf
19442 (goto-char (point-max))
19443 (insert "Warning (Org): " message)
19444 (unless (bolp)
19445 (newline)))
19446 (display-buffer buf)
19447 (sit-for 0))))
19449 (defun org-eval (form)
19450 "Eval FORM and return result."
19451 (condition-case error
19452 (eval form)
19453 (error (format "%%![Error: %s]" error))))
19455 (defun org-in-clocktable-p ()
19456 "Check if the cursor is in a clocktable."
19457 (let ((pos (point)) start)
19458 (save-excursion
19459 (end-of-line 1)
19460 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19461 (setq start (match-beginning 0))
19462 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19463 (>= (match-end 0) pos)
19464 start))))
19466 (defun org-in-commented-line ()
19467 "Is point in a line starting with `#'?"
19468 (equal (char-after (point-at-bol)) ?#))
19470 (defun org-in-indented-comment-line ()
19471 "Is point in a line starting with `#' after some white space?"
19472 (save-excursion
19473 (save-match-data
19474 (goto-char (point-at-bol))
19475 (looking-at "[ \t]*#"))))
19477 (defun org-in-verbatim-emphasis ()
19478 (save-match-data
19479 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19481 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19482 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19483 (if (and marker (marker-buffer marker)
19484 (buffer-live-p (marker-buffer marker)))
19485 (progn
19486 (org-pop-to-buffer-same-window (marker-buffer marker))
19487 (if (or (> marker (point-max)) (< marker (point-min)))
19488 (widen))
19489 (goto-char marker)
19490 (org-show-context 'org-goto))
19491 (if bookmark
19492 (bookmark-jump bookmark)
19493 (error "Cannot find location"))))
19495 (defun org-quote-csv-field (s)
19496 "Quote field for inclusion in CSV material."
19497 (if (string-match "[\",]" s)
19498 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19501 (defun org-force-self-insert (N)
19502 "Needed to enforce self-insert under remapping."
19503 (interactive "p")
19504 (self-insert-command N))
19506 (defun org-string-width (s)
19507 "Compute width of string, ignoring invisible characters.
19508 This ignores character with invisibility property `org-link', and also
19509 characters with property `org-cwidth', because these will become invisible
19510 upon the next fontification round."
19511 (let (b l)
19512 (when (or (eq t buffer-invisibility-spec)
19513 (assq 'org-link buffer-invisibility-spec))
19514 (while (setq b (text-property-any 0 (length s)
19515 'invisible 'org-link s))
19516 (setq s (concat (substring s 0 b)
19517 (substring s (or (next-single-property-change
19518 b 'invisible s) (length s)))))))
19519 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19520 (setq s (concat (substring s 0 b)
19521 (substring s (or (next-single-property-change
19522 b 'org-cwidth s) (length s))))))
19523 (setq l (string-width s) b -1)
19524 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19525 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19528 (defun org-shorten-string (s maxlength)
19529 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19530 If the string is shorter or has length MAXLENGTH, just return the
19531 original string. If it is longer, the functions finds a space in the
19532 string, breaks this string off at that locations and adds three dots
19533 as ellipsis. Including the ellipsis, the string will not be longer
19534 than MAXLENGTH. If finding a good breaking point in the string does
19535 not work, the string is just chopped off in the middle of a word
19536 if necessary."
19537 (if (<= (length s) maxlength)
19539 (let* ((n (max (- maxlength 4) 1))
19540 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19541 (if (string-match re s)
19542 (concat (match-string 1 s) "...")
19543 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19545 (defun org-get-indentation (&optional line)
19546 "Get the indentation of the current line, interpreting tabs.
19547 When LINE is given, assume it represents a line and compute its indentation."
19548 (if line
19549 (if (string-match "^ *" (org-remove-tabs line))
19550 (match-end 0))
19551 (save-excursion
19552 (beginning-of-line 1)
19553 (skip-chars-forward " \t")
19554 (current-column))))
19556 (defun org-get-string-indentation (s)
19557 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19558 (let ((n -1) (i 0) (w tab-width) c)
19559 (catch 'exit
19560 (while (< (setq n (1+ n)) (length s))
19561 (setq c (aref s n))
19562 (cond ((= c ?\ ) (setq i (1+ i)))
19563 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19564 (t (throw 'exit t)))))
19567 (defun org-remove-tabs (s &optional width)
19568 "Replace tabulators in S with spaces.
19569 Assumes that s is a single line, starting in column 0."
19570 (setq width (or width tab-width))
19571 (while (string-match "\t" s)
19572 (setq s (replace-match
19573 (make-string
19574 (- (* width (/ (+ (match-beginning 0) width) width))
19575 (match-beginning 0)) ?\ )
19576 t t s)))
19579 (defun org-fix-indentation (line ind)
19580 "Fix indentation in LINE.
19581 IND is a cons cell with target and minimum indentation.
19582 If the current indentation in LINE is smaller than the minimum,
19583 leave it alone. If it is larger than ind, set it to the target."
19584 (let* ((l (org-remove-tabs line))
19585 (i (org-get-indentation l))
19586 (i1 (car ind)) (i2 (cdr ind)))
19587 (if (>= i i2) (setq l (substring line i2)))
19588 (if (> i1 0)
19589 (concat (make-string i1 ?\ ) l)
19590 l)))
19592 (defun org-remove-indentation (code &optional n)
19593 "Remove the maximum common indentation from the lines in CODE.
19594 N may optionally be the number of spaces to remove."
19595 (with-temp-buffer
19596 (insert code)
19597 (org-do-remove-indentation n)
19598 (buffer-string)))
19600 (defun org-do-remove-indentation (&optional n)
19601 "Remove the maximum common indentation from the buffer."
19602 (untabify (point-min) (point-max))
19603 (let ((min 10000) re)
19604 (if n
19605 (setq min n)
19606 (goto-char (point-min))
19607 (while (re-search-forward "^ *[^ \n]" nil t)
19608 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19609 (unless (or (= min 0) (= min 10000))
19610 (setq re (format "^ \\{%d\\}" min))
19611 (goto-char (point-min))
19612 (while (re-search-forward re nil t)
19613 (replace-match "")
19614 (end-of-line 1))
19615 min)))
19617 (defun org-fill-template (template alist)
19618 "Find each %key of ALIST in TEMPLATE and replace it."
19619 (let ((case-fold-search nil)
19620 entry key value)
19621 (setq alist (sort (copy-sequence alist)
19622 (lambda (a b) (< (length (car a)) (length (car b))))))
19623 (while (setq entry (pop alist))
19624 (setq template
19625 (replace-regexp-in-string
19626 (concat "%" (regexp-quote (car entry)))
19627 (cdr entry) template t t)))
19628 template))
19630 (defun org-base-buffer (buffer)
19631 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19632 (if (not buffer)
19633 buffer
19634 (or (buffer-base-buffer buffer)
19635 buffer)))
19637 (defun org-trim (s)
19638 "Remove whitespace at beginning and end of string."
19639 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19640 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19643 (defun org-wrap (string &optional width lines)
19644 "Wrap string to either a number of lines, or a width in characters.
19645 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19646 that costs. If there is a word longer than WIDTH, the text is actually
19647 wrapped to the length of that word.
19648 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19649 many lines, whatever width that takes.
19650 The return value is a list of lines, without newlines at the end."
19651 (let* ((words (org-split-string string "[ \t\n]+"))
19652 (maxword (apply 'max (mapcar 'org-string-width words)))
19653 w ll)
19654 (cond (width
19655 (org-do-wrap words (max maxword width)))
19656 (lines
19657 (setq w maxword)
19658 (setq ll (org-do-wrap words maxword))
19659 (if (<= (length ll) lines)
19661 (setq ll words)
19662 (while (> (length ll) lines)
19663 (setq w (1+ w))
19664 (setq ll (org-do-wrap words w)))
19665 ll))
19666 (t (error "Cannot wrap this")))))
19668 (defun org-do-wrap (words width)
19669 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19670 (let (lines line)
19671 (while words
19672 (setq line (pop words))
19673 (while (and words (< (+ (length line) (length (car words))) width))
19674 (setq line (concat line " " (pop words))))
19675 (setq lines (push line lines)))
19676 (nreverse lines)))
19678 (defun org-split-string (string &optional separators)
19679 "Splits STRING into substrings at SEPARATORS.
19680 No empty strings are returned if there are matches at the beginning
19681 and end of string."
19682 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19683 (start 0)
19684 notfirst
19685 (list nil))
19686 (while (and (string-match rexp string
19687 (if (and notfirst
19688 (= start (match-beginning 0))
19689 (< start (length string)))
19690 (1+ start) start))
19691 (< (match-beginning 0) (length string)))
19692 (setq notfirst t)
19693 (or (eq (match-beginning 0) 0)
19694 (and (eq (match-beginning 0) (match-end 0))
19695 (eq (match-beginning 0) start))
19696 (setq list
19697 (cons (substring string start (match-beginning 0))
19698 list)))
19699 (setq start (match-end 0)))
19700 (or (eq start (length string))
19701 (setq list
19702 (cons (substring string start)
19703 list)))
19704 (nreverse list)))
19706 (defun org-quote-vert (s)
19707 "Replace \"|\" with \"\\vert\"."
19708 (while (string-match "|" s)
19709 (setq s (replace-match "\\vert" t t s)))
19712 (defun org-uuidgen-p (s)
19713 "Is S an ID created by UUIDGEN?"
19714 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19716 (defun org-in-src-block-p nil
19717 "Whether point is in a code source block."
19718 (let (ov)
19719 (when (setq ov (overlays-at (point)))
19720 (memq 'org-block-background
19721 (overlay-properties
19722 (car ov))))))
19724 (defun org-context ()
19725 "Return a list of contexts of the current cursor position.
19726 If several contexts apply, all are returned.
19727 Each context entry is a list with a symbol naming the context, and
19728 two positions indicating start and end of the context. Possible
19729 contexts are:
19731 :headline anywhere in a headline
19732 :headline-stars on the leading stars in a headline
19733 :todo-keyword on a TODO keyword (including DONE) in a headline
19734 :tags on the TAGS in a headline
19735 :priority on the priority cookie in a headline
19736 :item on the first line of a plain list item
19737 :item-bullet on the bullet/number of a plain list item
19738 :checkbox on the checkbox in a plain list item
19739 :table in an org-mode table
19740 :table-special on a special filed in a table
19741 :table-table in a table.el table
19742 :clocktable in a clocktable
19743 :src-block in a source block
19744 :link on a hyperlink
19745 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19746 :target on a <<target>>
19747 :radio-target on a <<<radio-target>>>
19748 :latex-fragment on a LaTeX fragment
19749 :latex-preview on a LaTeX fragment with overlaid preview image
19751 This function expects the position to be visible because it uses font-lock
19752 faces as a help to recognize the following contexts: :table-special, :link,
19753 and :keyword."
19754 (let* ((f (get-text-property (point) 'face))
19755 (faces (if (listp f) f (list f)))
19756 (case-fold-search t)
19757 (p (point)) clist o)
19758 ;; First the large context
19759 (cond
19760 ((org-at-heading-p t)
19761 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19762 (when (progn
19763 (beginning-of-line 1)
19764 (looking-at org-todo-line-tags-regexp))
19765 (push (org-point-in-group p 1 :headline-stars) clist)
19766 (push (org-point-in-group p 2 :todo-keyword) clist)
19767 (push (org-point-in-group p 4 :tags) clist))
19768 (goto-char p)
19769 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19770 (if (looking-at "\\[#[A-Z0-9]\\]")
19771 (push (org-point-in-group p 0 :priority) clist)))
19773 ((org-at-item-p)
19774 (push (org-point-in-group p 2 :item-bullet) clist)
19775 (push (list :item (point-at-bol)
19776 (save-excursion (org-end-of-item) (point)))
19777 clist)
19778 (and (org-at-item-checkbox-p)
19779 (push (org-point-in-group p 0 :checkbox) clist)))
19781 ((org-at-table-p)
19782 (push (list :table (org-table-begin) (org-table-end)) clist)
19783 (if (memq 'org-formula faces)
19784 (push (list :table-special
19785 (previous-single-property-change p 'face)
19786 (next-single-property-change p 'face)) clist)))
19787 ((org-at-table-p 'any)
19788 (push (list :table-table) clist)))
19789 (goto-char p)
19791 ;; New the "medium" contexts: clocktables, source blocks
19792 (cond ((org-in-clocktable-p)
19793 (push (list :clocktable
19794 (and (or (looking-at "#\\+BEGIN: clocktable")
19795 (search-backward "#+BEGIN: clocktable" nil t))
19796 (match-beginning 0))
19797 (and (re-search-forward "#\\+END:?" nil t)
19798 (match-end 0))) clist))
19799 ((org-in-src-block-p)
19800 (push (list :src-block
19801 (and (or (looking-at "#\\+BEGIN_SRC")
19802 (search-backward "#+BEGIN_SRC" nil t))
19803 (match-beginning 0))
19804 (and (search-forward "#+END_SRC" nil t)
19805 (match-beginning 0))) clist)))
19806 (goto-char p)
19808 ;; Now the small context
19809 (cond
19810 ((org-at-timestamp-p)
19811 (push (org-point-in-group p 0 :timestamp) clist))
19812 ((memq 'org-link faces)
19813 (push (list :link
19814 (previous-single-property-change p 'face)
19815 (next-single-property-change p 'face)) clist))
19816 ((memq 'org-special-keyword faces)
19817 (push (list :keyword
19818 (previous-single-property-change p 'face)
19819 (next-single-property-change p 'face)) clist))
19820 ((org-at-target-p)
19821 (push (org-point-in-group p 0 :target) clist)
19822 (goto-char (1- (match-beginning 0)))
19823 (if (looking-at org-radio-target-regexp)
19824 (push (org-point-in-group p 0 :radio-target) clist))
19825 (goto-char p))
19826 ((setq o (car (delq nil
19827 (mapcar
19828 (lambda (x)
19829 (if (memq x org-latex-fragment-image-overlays) x))
19830 (overlays-at (point))))))
19831 (push (list :latex-fragment
19832 (overlay-start o) (overlay-end o)) clist)
19833 (push (list :latex-preview
19834 (overlay-start o) (overlay-end o)) clist))
19835 ((org-inside-LaTeX-fragment-p)
19836 ;; FIXME: positions wrong.
19837 (push (list :latex-fragment (point) (point)) clist)))
19839 (setq clist (nreverse (delq nil clist)))
19840 clist))
19842 ;; FIXME: Compare with at-regexp-p Do we need both?
19843 (defun org-in-regexp (re &optional nlines visually)
19844 "Check if point is inside a match of regexp.
19845 Normally only the current line is checked, but you can include NLINES extra
19846 lines both before and after point into the search.
19847 If VISUALLY is set, require that the cursor is not after the match but
19848 really on, so that the block visually is on the match."
19849 (catch 'exit
19850 (let ((pos (point))
19851 (eol (point-at-eol (+ 1 (or nlines 0))))
19852 (inc (if visually 1 0)))
19853 (save-excursion
19854 (beginning-of-line (- 1 (or nlines 0)))
19855 (while (re-search-forward re eol t)
19856 (if (and (<= (match-beginning 0) pos)
19857 (>= (+ inc (match-end 0)) pos))
19858 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19860 (defun org-at-regexp-p (regexp)
19861 "Is point inside a match of REGEXP in the current line?"
19862 (catch 'exit
19863 (save-excursion
19864 (let ((pos (point)) (end (point-at-eol)))
19865 (beginning-of-line 1)
19866 (while (re-search-forward regexp end t)
19867 (if (and (<= (match-beginning 0) pos)
19868 (>= (match-end 0) pos))
19869 (throw 'exit t)))
19870 nil))))
19872 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19873 "Non-nil when point is between matches of START-RE and END-RE.
19875 Also return a non-nil value when point is on one of the matches.
19877 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19878 buffer positions. Default values are the positions of headlines
19879 surrounding the point.
19881 The functions returns a cons cell whose car (resp. cdr) is the
19882 position before START-RE (resp. after END-RE)."
19883 (save-match-data
19884 (let ((pos (point))
19885 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19886 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19887 beg end)
19888 (save-excursion
19889 ;; Point is on a block when on START-RE or if START-RE can be
19890 ;; found before it...
19891 (and (or (org-at-regexp-p start-re)
19892 (re-search-backward start-re limit-up t))
19893 (setq beg (match-beginning 0))
19894 ;; ... and END-RE after it...
19895 (goto-char (match-end 0))
19896 (re-search-forward end-re limit-down t)
19897 (> (setq end (match-end 0)) pos)
19898 ;; ... without another START-RE in-between.
19899 (goto-char (match-beginning 0))
19900 (not (re-search-backward start-re (1+ beg) t))
19901 ;; Return value.
19902 (cons beg end))))))
19904 (defun org-in-block-p (names)
19905 "Non-nil when point belongs to a block whose name belongs to NAMES.
19907 NAMES is a list of strings containing names of blocks.
19909 Return first block name matched, or nil. Beware that in case of
19910 nested blocks, the returned name may not belong to the closest
19911 block from point."
19912 (save-match-data
19913 (catch 'exit
19914 (let ((case-fold-search t)
19915 (lim-up (save-excursion (outline-previous-heading)))
19916 (lim-down (save-excursion (outline-next-heading))))
19917 (mapc (lambda (name)
19918 (let ((n (regexp-quote name)))
19919 (when (org-between-regexps-p
19920 (concat "^[ \t]*#\\+begin_" n)
19921 (concat "^[ \t]*#\\+end_" n)
19922 lim-up lim-down)
19923 (throw 'exit n))))
19924 names))
19925 nil)))
19927 (defun org-occur-in-agenda-files (regexp &optional nlines)
19928 "Call `multi-occur' with buffers for all agenda files."
19929 (interactive "sOrg-files matching: \np")
19930 (let* ((files (org-agenda-files))
19931 (tnames (mapcar 'file-truename files))
19932 (extra org-agenda-text-search-extra-files)
19934 (when (eq (car extra) 'agenda-archives)
19935 (setq extra (cdr extra))
19936 (setq files (org-add-archive-files files)))
19937 (while (setq f (pop extra))
19938 (unless (member (file-truename f) tnames)
19939 (add-to-list 'files f 'append)
19940 (add-to-list 'tnames (file-truename f) 'append)))
19941 (multi-occur
19942 (mapcar (lambda (x)
19943 (with-current-buffer
19944 (or (get-file-buffer x) (find-file-noselect x))
19945 (widen)
19946 (current-buffer)))
19947 files)
19948 regexp)))
19950 (if (boundp 'occur-mode-find-occurrence-hook)
19951 ;; Emacs 23
19952 (add-hook 'occur-mode-find-occurrence-hook
19953 (lambda ()
19954 (when (eq major-mode 'org-mode)
19955 (org-reveal))))
19956 ;; Emacs 22
19957 (defadvice occur-mode-goto-occurrence
19958 (after org-occur-reveal activate)
19959 (and (eq major-mode 'org-mode) (org-reveal)))
19960 (defadvice occur-mode-goto-occurrence-other-window
19961 (after org-occur-reveal activate)
19962 (and (eq major-mode 'org-mode) (org-reveal)))
19963 (defadvice occur-mode-display-occurrence
19964 (after org-occur-reveal activate)
19965 (when (eq major-mode 'org-mode)
19966 (let ((pos (occur-mode-find-occurrence)))
19967 (with-current-buffer (marker-buffer pos)
19968 (save-excursion
19969 (goto-char pos)
19970 (org-reveal)))))))
19972 (defun org-occur-link-in-agenda-files ()
19973 "Create a link and search for it in the agendas.
19974 The link is not stored in `org-stored-links', it is just created
19975 for the search purpose."
19976 (interactive)
19977 (let ((link (condition-case nil
19978 (org-store-link nil)
19979 (error "Unable to create a link to here"))))
19980 (org-occur-in-agenda-files (regexp-quote link))))
19982 (defun org-uniquify (list)
19983 "Remove duplicate elements from LIST."
19984 (let (res)
19985 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19986 res))
19988 (defun org-delete-all (elts list)
19989 "Remove all elements in ELTS from LIST."
19990 (while elts
19991 (setq list (delete (pop elts) list)))
19992 list)
19994 (defun org-count (cl-item cl-seq)
19995 "Count the number of occurrences of ITEM in SEQ.
19996 Taken from `count' in cl-seq.el with all keyword arguments removed."
19997 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19998 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19999 (while (< cl-start cl-end)
20000 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20001 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20002 (setq cl-start (1+ cl-start)))
20003 cl-count))
20005 (defun org-remove-if (predicate seq)
20006 "Remove everything from SEQ that fulfills PREDICATE."
20007 (let (res e)
20008 (while seq
20009 (setq e (pop seq))
20010 (if (not (funcall predicate e)) (push e res)))
20011 (nreverse res)))
20013 (defun org-remove-if-not (predicate seq)
20014 "Remove everything from SEQ that does not fulfill PREDICATE."
20015 (let (res e)
20016 (while seq
20017 (setq e (pop seq))
20018 (if (funcall predicate e) (push e res)))
20019 (nreverse res)))
20021 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20022 "Reduce two-argument FUNCTION across SEQ.
20023 Taken from `reduce' in cl-seq.el with all keyword arguments but
20024 \":initial-value\" removed."
20025 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20026 (cadr (memq :initial-value cl-keys)))
20027 (cl-seq (pop cl-seq))
20028 (t (funcall cl-func)))))
20029 (while cl-seq
20030 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20031 cl-accum))
20033 (defun org-back-over-empty-lines ()
20034 "Move backwards over whitespace, to the beginning of the first empty line.
20035 Returns the number of empty lines passed."
20036 (let ((pos (point)))
20037 (if (cdr (assoc 'heading org-blank-before-new-entry))
20038 (skip-chars-backward " \t\n\r")
20039 (unless (eobp)
20040 (forward-line -1)))
20041 (beginning-of-line 2)
20042 (goto-char (min (point) pos))
20043 (count-lines (point) pos)))
20045 (defun org-skip-whitespace ()
20046 (skip-chars-forward " \t\n\r"))
20048 (defun org-point-in-group (point group &optional context)
20049 "Check if POINT is in match-group GROUP.
20050 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20051 match. If the match group does not exist or point is not inside it,
20052 return nil."
20053 (and (match-beginning group)
20054 (>= point (match-beginning group))
20055 (<= point (match-end group))
20056 (if context
20057 (list context (match-beginning group) (match-end group))
20058 t)))
20060 (defun org-switch-to-buffer-other-window (&rest args)
20061 "Switch to buffer in a second window on the current frame.
20062 In particular, do not allow pop-up frames.
20063 Returns the newly created buffer."
20064 (let (pop-up-frames special-display-buffer-names special-display-regexps
20065 special-display-function)
20066 (apply 'switch-to-buffer-other-window args)))
20068 (defun org-combine-plists (&rest plists)
20069 "Create a single property list from all plists in PLISTS.
20070 The process starts by copying the first list, and then setting properties
20071 from the other lists. Settings in the last list are the most significant
20072 ones and overrule settings in the other lists."
20073 (let ((rtn (copy-sequence (pop plists)))
20074 p v ls)
20075 (while plists
20076 (setq ls (pop plists))
20077 (while ls
20078 (setq p (pop ls) v (pop ls))
20079 (setq rtn (plist-put rtn p v))))
20080 rtn))
20082 (defun org-move-line-down (arg)
20083 "Move the current line down. With prefix argument, move it past ARG lines."
20084 (interactive "p")
20085 (let ((col (current-column))
20086 beg end pos)
20087 (beginning-of-line 1) (setq beg (point))
20088 (beginning-of-line 2) (setq end (point))
20089 (beginning-of-line (+ 1 arg))
20090 (setq pos (move-marker (make-marker) (point)))
20091 (insert (delete-and-extract-region beg end))
20092 (goto-char pos)
20093 (org-move-to-column col)))
20095 (defun org-move-line-up (arg)
20096 "Move the current line up. With prefix argument, move it past ARG lines."
20097 (interactive "p")
20098 (let ((col (current-column))
20099 beg end pos)
20100 (beginning-of-line 1) (setq beg (point))
20101 (beginning-of-line 2) (setq end (point))
20102 (beginning-of-line (- arg))
20103 (setq pos (move-marker (make-marker) (point)))
20104 (insert (delete-and-extract-region beg end))
20105 (goto-char pos)
20106 (org-move-to-column col)))
20108 (defun org-replace-escapes (string table)
20109 "Replace %-escapes in STRING with values in TABLE.
20110 TABLE is an association list with keys like \"%a\" and string values.
20111 The sequences in STRING may contain normal field width and padding information,
20112 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20113 so values can contain further %-escapes if they are define later in TABLE."
20114 (let ((tbl (copy-alist table))
20115 (case-fold-search nil)
20116 (pchg 0)
20117 e re rpl)
20118 (while (setq e (pop tbl))
20119 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20120 (when (and (cdr e) (string-match re (cdr e)))
20121 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20122 (safe "SREF"))
20123 (add-text-properties 0 3 (list 'sref sref) safe)
20124 (setcdr e (replace-match safe t t (cdr e)))))
20125 (while (string-match re string)
20126 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20127 (cdr e)))
20128 (setq string (replace-match rpl t t string))))
20129 (while (setq pchg (next-property-change pchg string))
20130 (let ((sref (get-text-property pchg 'sref string)))
20131 (when (and sref (string-match "SREF" string pchg))
20132 (setq string (replace-match sref t t string)))))
20133 string))
20135 (defun org-sublist (list start end)
20136 "Return a section of LIST, from START to END.
20137 Counting starts at 1."
20138 (let (rtn (c start))
20139 (setq list (nthcdr (1- start) list))
20140 (while (and list (<= c end))
20141 (push (pop list) rtn)
20142 (setq c (1+ c)))
20143 (nreverse rtn)))
20145 (defun org-find-base-buffer-visiting (file)
20146 "Like `find-buffer-visiting' but always return the base buffer and
20147 not an indirect buffer."
20148 (let ((buf (or (get-file-buffer file)
20149 (find-buffer-visiting file))))
20150 (if buf
20151 (or (buffer-base-buffer buf) buf)
20152 nil)))
20154 (defun org-image-file-name-regexp (&optional extensions)
20155 "Return regexp matching the file names of images.
20156 If EXTENSIONS is given, only match these."
20157 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20158 (image-file-name-regexp)
20159 (let ((image-file-name-extensions
20160 (or extensions
20161 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20162 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20163 (concat "\\."
20164 (regexp-opt (nconc (mapcar 'upcase
20165 image-file-name-extensions)
20166 image-file-name-extensions)
20168 "\\'"))))
20170 (defun org-file-image-p (file &optional extensions)
20171 "Return non-nil if FILE is an image."
20172 (save-match-data
20173 (string-match (org-image-file-name-regexp extensions) file)))
20175 (defun org-get-cursor-date ()
20176 "Return the date at cursor in as a time.
20177 This works in the calendar and in the agenda, anywhere else it just
20178 returns the current time."
20179 (let (date day defd)
20180 (cond
20181 ((eq major-mode 'calendar-mode)
20182 (setq date (calendar-cursor-to-date)
20183 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20184 ((eq major-mode 'org-agenda-mode)
20185 (setq day (get-text-property (point) 'day))
20186 (if day
20187 (setq date (calendar-gregorian-from-absolute day)
20188 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20189 (nth 2 date))))))
20190 (or defd (current-time))))
20192 (defvar org-agenda-action-marker (make-marker)
20193 "Marker pointing to the entry for the next agenda action.")
20195 (defun org-mark-entry-for-agenda-action ()
20196 "Mark the current entry as target of an agenda action.
20197 Agenda actions are actions executed from the agenda with the key `k',
20198 which make use of the date at the cursor."
20199 (interactive)
20200 (move-marker org-agenda-action-marker
20201 (save-excursion (org-back-to-heading t) (point))
20202 (current-buffer))
20203 (message
20204 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20206 (defun org-mark-subtree ()
20207 "Mark the current subtree.
20208 This puts point at the start of the current subtree, and mark at the end.
20210 If point is in an inline task, mark that task instead."
20211 (interactive)
20212 (let ((inline-task-p
20213 (and (featurep 'org-inlinetask)
20214 (org-inlinetask-in-task-p)))
20215 (beg))
20216 ;; Get beginning of subtree
20217 (cond
20218 (inline-task-p (org-inlinetask-goto-beginning))
20219 ((org-at-heading-p) (beginning-of-line))
20220 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20221 (setq beg (point))
20222 ;; Get end of it
20223 (if inline-task-p
20224 (org-inlinetask-goto-end)
20225 (org-end-of-subtree))
20226 ;; Mark zone
20227 (push-mark (point) nil t)
20228 (goto-char beg)))
20230 ;;; Paragraph filling stuff.
20231 ;; We want this to be just right, so use the full arsenal.
20233 (defun org-indent-line-function ()
20234 "Indent line depending on context."
20235 (interactive)
20236 (let* ((pos (point))
20237 (itemp (org-at-item-p))
20238 (case-fold-search t)
20239 (org-drawer-regexp (or org-drawer-regexp "\000"))
20240 (inline-task-p (and (featurep 'org-inlinetask)
20241 (org-inlinetask-in-task-p)))
20242 (inline-re (and inline-task-p
20243 (org-inlinetask-outline-regexp)))
20244 column)
20245 (beginning-of-line 1)
20246 (cond
20247 ;; Comments
20248 ((looking-at "# ") (setq column 0))
20249 ;; Headings
20250 ((looking-at org-outline-regexp) (setq column 0))
20251 ;; Included files
20252 ((looking-at "#\\+include:") (setq column 0))
20253 ;; Footnote definition
20254 ((looking-at org-footnote-definition-re) (setq column 0))
20255 ;; Literal examples
20256 ((looking-at "[ \t]*:\\( \\|$\\)")
20257 (setq column (org-get-indentation))) ; do nothing
20258 ;; Lists
20259 ((ignore-errors (goto-char (org-in-item-p)))
20260 (setq column (if itemp
20261 (org-get-indentation)
20262 (org-list-item-body-column (point))))
20263 (goto-char pos))
20264 ;; Drawers
20265 ((and (looking-at "[ \t]*:END:")
20266 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20267 (save-excursion
20268 (goto-char (1- (match-beginning 1)))
20269 (setq column (current-column))))
20270 ;; Special blocks
20271 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20272 (save-excursion
20273 (re-search-backward
20274 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20275 (setq column (org-get-indentation (match-string 0))))
20276 ((and (not (looking-at "[ \t]*#\\+begin_"))
20277 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20278 (save-excursion
20279 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20280 (setq column
20281 (cond ((equal (downcase (match-string 1)) "src")
20282 ;; src blocks: let `org-edit-src-exit' handle them
20283 (org-get-indentation))
20284 ((equal (downcase (match-string 1)) "example")
20285 (max (org-get-indentation)
20286 (org-get-indentation (match-string 0))))
20288 (org-get-indentation (match-string 0))))))
20289 ;; This line has nothing special, look at the previous relevant
20290 ;; line to compute indentation
20292 (beginning-of-line 0)
20293 (while (and (not (bobp))
20294 (not (looking-at org-drawer-regexp))
20295 ;; When point started in an inline task, do not move
20296 ;; above task starting line.
20297 (not (and inline-task-p (looking-at inline-re)))
20298 ;; Skip drawers, blocks, empty lines, verbatim,
20299 ;; comments, tables, footnotes definitions, lists,
20300 ;; inline tasks.
20301 (or (and (looking-at "[ \t]*:END:")
20302 (re-search-backward org-drawer-regexp nil t))
20303 (and (looking-at "[ \t]*#\\+end_")
20304 (re-search-backward "[ \t]*#\\+begin_"nil t))
20305 (looking-at "[ \t]*[\n:#|]")
20306 (looking-at org-footnote-definition-re)
20307 (and (ignore-errors (goto-char (org-in-item-p)))
20308 (goto-char
20309 (org-list-get-top-point (org-list-struct))))
20310 (and (not inline-task-p)
20311 (featurep 'org-inlinetask)
20312 (org-inlinetask-in-task-p)
20313 (or (org-inlinetask-goto-beginning) t))))
20314 (beginning-of-line 0))
20315 (cond
20316 ;; There was an heading above.
20317 ((looking-at "\\*+[ \t]+")
20318 (if (not org-adapt-indentation)
20319 (setq column 0)
20320 (goto-char (match-end 0))
20321 (setq column (current-column))))
20322 ;; A drawer had started and is unfinished
20323 ((looking-at org-drawer-regexp)
20324 (goto-char (1- (match-beginning 1)))
20325 (setq column (current-column)))
20326 ;; Else, nothing noticeable found: get indentation and go on.
20327 (t (setq column (org-get-indentation))))))
20328 ;; Now apply indentation and move cursor accordingly
20329 (goto-char pos)
20330 (if (<= (current-column) (current-indentation))
20331 (org-indent-line-to column)
20332 (save-excursion (org-indent-line-to column)))
20333 ;; Special polishing for properties, see `org-property-format'
20334 (setq column (current-column))
20335 (beginning-of-line 1)
20336 (if (looking-at
20337 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20338 (replace-match (concat (match-string 1)
20339 (format org-property-format
20340 (match-string 2) (match-string 3)))
20341 t t))
20342 (org-move-to-column column)))
20344 (defun org-indent-drawer ()
20345 "Indent the drawer at point."
20346 (interactive)
20347 (let ((p (point))
20348 (e (and (save-excursion (re-search-forward ":END:" nil t))
20349 (match-end 0)))
20350 (folded
20351 (save-excursion
20352 (end-of-line)
20353 (when (overlays-at (point))
20354 (member 'invisible (overlay-properties
20355 (car (overlays-at (point)))))))))
20356 (when folded (org-cycle))
20357 (indent-for-tab-command)
20358 (while (and (move-beginning-of-line 2) (< (point) e))
20359 (indent-for-tab-command))
20360 (goto-char p)
20361 (when folded (org-cycle)))
20362 (message "Drawer at point indented"))
20364 (defun org-indent-block ()
20365 "Indent the block at point."
20366 (interactive)
20367 (let ((p (point))
20368 (case-fold-search t)
20369 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20370 (match-end 0)))
20371 (folded
20372 (save-excursion
20373 (end-of-line)
20374 (when (overlays-at (point))
20375 (member 'invisible (overlay-properties
20376 (car (overlays-at (point)))))))))
20377 (when folded (org-cycle))
20378 (indent-for-tab-command)
20379 (while (and (move-beginning-of-line 2) (< (point) e))
20380 (indent-for-tab-command))
20381 (goto-char p)
20382 (when folded (org-cycle)))
20383 (message "Block at point indented"))
20385 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20386 "Variable to store copy of `adaptive-fill-regexp'.
20387 Since `adaptive-fill-regexp' is set to never match, we need to
20388 store a backup of its value before entering `org-mode' so that
20389 the functionality can be provided as a fall-back.")
20391 (defun org-set-autofill-regexps ()
20392 (interactive)
20393 ;; In the paragraph separator we include headlines, because filling
20394 ;; text in a line directly attached to a headline would otherwise
20395 ;; fill the headline as well.
20396 (org-set-local 'comment-start-skip "^#+[ \t]*")
20397 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20398 ;; The paragraph starter includes hand-formatted lists.
20399 (org-set-local
20400 'paragraph-start
20401 (concat
20402 "\f" "\\|"
20403 "[ ]*$" "\\|"
20404 org-outline-regexp "\\|"
20405 "[ \t]*#" "\\|"
20406 (org-item-re) "\\|"
20407 "[ \t]*[:|]" "\\|"
20408 "\\$\\$" "\\|"
20409 "\\\\\\(begin\\|end\\|[][]\\)"))
20410 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20411 ;; But only if the user has not turned off tables or fixed-width regions
20412 (org-set-local
20413 'auto-fill-inhibit-regexp
20414 (concat org-outline-regexp
20415 "\\|#\\+"
20416 "\\|[ \t]*" org-keyword-time-regexp
20417 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20418 (concat
20419 "\\|[ \t]*["
20420 (if org-enable-table-editor "|" "")
20421 (if org-enable-fixed-width-editor ":" "")
20422 "]"))))
20423 ;; We use our own fill-paragraph function, to make sure that tables
20424 ;; and fixed-width regions are not wrapped. That function will pass
20425 ;; through to `fill-paragraph' when appropriate.
20426 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20427 ;; Prevent auto-fill from inserting unwanted new items.
20428 (if (boundp 'fill-nobreak-predicate)
20429 (org-set-local
20430 'fill-nobreak-predicate
20431 (org-uniquify
20432 (append fill-nobreak-predicate
20433 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20434 ;; Adaptive filling: To get full control, first make sure that
20435 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20436 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20437 (org-set-local 'org-adaptive-fill-regexp-backup
20438 adaptive-fill-regexp))
20439 (org-set-local 'adaptive-fill-regexp "\000")
20440 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20441 (org-set-local 'adaptive-fill-function
20442 'org-adaptive-fill-function)
20443 (org-set-local
20444 'align-mode-rules-list
20445 '((org-in-buffer-settings
20446 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20447 (modes . '(org-mode))))))
20449 (defun org-fill-item-nobreak-p ()
20450 "Non-nil when a line break at point would insert a new item."
20451 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20453 (defun org-fill-line-break-nobreak-p ()
20454 "Non-nil when a line break at point would create an Org line break."
20455 (save-excursion
20456 (skip-chars-backward "[ \t]")
20457 (skip-chars-backward "\\\\")
20458 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20460 (defun org-fill-paragraph (&optional justify)
20461 "Re-align a table, pass through to fill-paragraph if no table."
20462 (let ((table-p (org-at-table-p))
20463 (table.el-p (org-at-table.el-p))
20464 (itemp (org-in-item-p)))
20465 (cond ((and (equal (char-after (point-at-bol)) ?*)
20466 (save-excursion (goto-char (point-at-bol))
20467 (looking-at org-outline-regexp)))
20468 t) ; skip headlines
20469 (table.el-p t) ; skip table.el tables
20470 (table-p (org-table-align) t) ; align Org tables
20471 (itemp ; align text in items
20472 (let* ((struct (save-excursion (goto-char itemp)
20473 (org-list-struct)))
20474 (parents (org-list-parents-alist struct))
20475 (children (org-list-get-children itemp struct parents))
20476 beg end prev next prefix)
20477 ;; Determine in which part of item point is: before
20478 ;; first child, after last child, between two
20479 ;; sub-lists, or simply in item if there's no child.
20480 (cond
20481 ((not children)
20482 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20483 beg itemp
20484 end (org-list-get-item-end itemp struct)))
20485 ((< (point) (setq next (car children)))
20486 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20487 beg itemp
20488 end next))
20489 ((> (point) (setq prev (car (last children))))
20490 (setq beg (org-list-get-item-end prev struct)
20491 end (org-list-get-item-end itemp struct)
20492 prefix (save-excursion
20493 (goto-char beg)
20494 (skip-chars-forward " \t")
20495 (make-string (current-column) ?\ ))))
20496 (t (catch 'exit
20497 (while (setq next (pop children))
20498 (if (> (point) next)
20499 (setq prev next)
20500 (setq beg (org-list-get-item-end prev struct)
20501 end next
20502 prefix (save-excursion
20503 (goto-char beg)
20504 (skip-chars-forward " \t")
20505 (make-string (current-column) ?\ )))
20506 (throw 'exit nil))))))
20507 ;; Use `fill-paragraph' with buffer narrowed to item
20508 ;; without any child, and with our computed PREFIX.
20509 (flet ((fill-context-prefix (from to &optional flr) prefix))
20510 (save-restriction
20511 (narrow-to-region beg end)
20512 (save-excursion (fill-paragraph justify)))) t))
20513 ;; Special case where point is not in a list but is on
20514 ;; a paragraph adjacent to a list: make sure this paragraph
20515 ;; doesn't get merged with the end of the list by narrowing
20516 ;; buffer first.
20517 ((save-excursion (forward-paragraph -1)
20518 (setq itemp (org-in-item-p)))
20519 (let ((struct (save-excursion (goto-char itemp)
20520 (org-list-struct))))
20521 (save-restriction
20522 (narrow-to-region (org-list-get-bottom-point struct)
20523 (save-excursion (forward-paragraph 1)
20524 (point)))
20525 (fill-paragraph justify) t)))
20526 ;; Don't fill schedule/deadline line before a paragraph
20527 ((save-excursion (forward-paragraph -1)
20528 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20529 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$"))))
20530 (save-restriction
20531 (narrow-to-region (1+ (match-end 0))
20532 (save-excursion (forward-paragraph 1) (point)))
20533 (fill-paragraph justify) t))
20534 ;; Else simply call `fill-paragraph'.
20535 (t nil))))
20537 ;; For reference, this is the default value of adaptive-fill-regexp
20538 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20540 (defun org-adaptive-fill-function ()
20541 "Return a fill prefix for org-mode files."
20542 (let (itemp)
20543 (save-excursion
20544 (cond
20545 ;; Comment line
20546 ((looking-at "#[ \t]+")
20547 (match-string-no-properties 0))
20548 ;; Plain list item
20549 ((org-at-item-p)
20550 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20551 ;; Point is in a list after `backward-paragraph': original
20552 ;; point wasn't in the list, or filling would have been taken
20553 ;; care of by `org-auto-fill-function', but the list and the
20554 ;; real paragraph are not separated by a blank line. Thus, move
20555 ;; point after the list to go back to real paragraph and
20556 ;; determine fill-prefix.
20557 ((setq itemp (org-in-item-p))
20558 (goto-char itemp)
20559 (let* ((struct (org-list-struct))
20560 (bottom (org-list-get-bottom-point struct)))
20561 (goto-char bottom)
20562 (make-string (org-get-indentation) ?\ )))
20563 ;; Other text
20564 ((looking-at org-adaptive-fill-regexp-backup)
20565 (match-string-no-properties 0))))))
20567 (defun org-auto-fill-function ()
20568 "Auto-fill function."
20569 (let (itemp prefix)
20570 ;; When in a list, compute an appropriate fill-prefix and make
20571 ;; sure it will be used by `do-auto-fill'.
20572 (if (setq itemp (org-in-item-p))
20573 (progn
20574 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20575 (flet ((fill-context-prefix (from to &optional flr) prefix))
20576 (do-auto-fill)))
20577 ;; Else just use `do-auto-fill'.
20578 (do-auto-fill))))
20580 ;;; Other stuff.
20582 (defun org-toggle-fixed-width-section (arg)
20583 "Toggle the fixed-width export.
20584 If there is no active region, the QUOTE keyword at the current headline is
20585 inserted or removed. When present, it causes the text between this headline
20586 and the next to be exported as fixed-width text, and unmodified.
20587 If there is an active region, this command adds or removes a colon as the
20588 first character of this line. If the first character of a line is a colon,
20589 this line is also exported in fixed-width font."
20590 (interactive "P")
20591 (let* ((cc 0)
20592 (regionp (org-region-active-p))
20593 (beg (if regionp (region-beginning) (point)))
20594 (end (if regionp (region-end)))
20595 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20596 (case-fold-search nil)
20597 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20598 off)
20599 (if regionp
20600 (save-excursion
20601 (goto-char beg)
20602 (setq cc (current-column))
20603 (beginning-of-line 1)
20604 (setq off (looking-at re))
20605 (while (> nlines 0)
20606 (setq nlines (1- nlines))
20607 (beginning-of-line 1)
20608 (cond
20609 (arg
20610 (org-move-to-column cc t)
20611 (insert ": \n")
20612 (forward-line -1))
20613 ((and off (looking-at re))
20614 (replace-match "" t t nil 1))
20615 ((not off) (org-move-to-column cc t) (insert ": ")))
20616 (forward-line 1)))
20617 (save-excursion
20618 (org-back-to-heading)
20619 (cond
20620 ((looking-at (format org-heading-keyword-regexp-format
20621 org-quote-string))
20622 (goto-char (match-end 1))
20623 (looking-at (concat " +" org-quote-string))
20624 (replace-match "" t t)
20625 (when (eolp) (insert " ")))
20626 ((looking-at org-outline-regexp)
20627 (goto-char (match-end 0))
20628 (insert org-quote-string " ")))))))
20630 (defun org-reftex-citation ()
20631 "Use reftex-citation to insert a citation into the buffer.
20632 This looks for a line like
20634 #+BIBLIOGRAPHY: foo plain option:-d
20636 and derives from it that foo.bib is the bibliography file relevant
20637 for this document. It then installs the necessary environment for RefTeX
20638 to work in this buffer and calls `reftex-citation' to insert a citation
20639 into the buffer.
20641 Export of such citations to both LaTeX and HTML is handled by the contributed
20642 package org-exp-bibtex by Taru Karttunen."
20643 (interactive)
20644 (let ((reftex-docstruct-symbol 'rds)
20645 (reftex-cite-format "\\cite{%l}")
20646 rds bib)
20647 (save-excursion
20648 (save-restriction
20649 (widen)
20650 (let ((case-fold-search t)
20651 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20652 (if (not (save-excursion
20653 (or (re-search-forward re nil t)
20654 (re-search-backward re nil t))))
20655 (error "No bibliography defined in file")
20656 (setq bib (concat (match-string 1) ".bib")
20657 rds (list (list 'bib bib)))))))
20658 (call-interactively 'reftex-citation)))
20660 ;;;; Functions extending outline functionality
20662 (defun org-beginning-of-line (&optional arg)
20663 "Go to the beginning of the current line. If that is invisible, continue
20664 to a visible line beginning. This makes the function of C-a more intuitive.
20665 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20666 first attempt, and only move to after the tags when the cursor is already
20667 beyond the end of the headline."
20668 (interactive "P")
20669 (let ((pos (point))
20670 (special (if (consp org-special-ctrl-a/e)
20671 (car org-special-ctrl-a/e)
20672 org-special-ctrl-a/e))
20673 refpos)
20674 (if (org-bound-and-true-p line-move-visual)
20675 (beginning-of-visual-line 1)
20676 (beginning-of-line 1))
20677 (if (and arg (fboundp 'move-beginning-of-line))
20678 (call-interactively 'move-beginning-of-line)
20679 (if (bobp)
20681 (backward-char 1)
20682 (if (org-truely-invisible-p)
20683 (while (and (not (bobp)) (org-truely-invisible-p))
20684 (backward-char 1)
20685 (beginning-of-line 1))
20686 (forward-char 1))))
20687 (when special
20688 (cond
20689 ((and (looking-at org-complex-heading-regexp)
20690 (= (char-after (match-end 1)) ?\ ))
20691 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20692 (point-at-eol)))
20693 (goto-char
20694 (if (eq special t)
20695 (cond ((> pos refpos) refpos)
20696 ((= pos (point)) refpos)
20697 (t (point)))
20698 (cond ((> pos (point)) (point))
20699 ((not (eq last-command this-command)) (point))
20700 (t refpos)))))
20701 ((org-at-item-p)
20702 ;; Being at an item and not looking at an the item means point
20703 ;; was previously moved to beginning of a visual line, which
20704 ;; doesn't contain the item. Therefore, do nothing special,
20705 ;; just stay here.
20706 (when (looking-at org-list-full-item-re)
20707 ;; Set special position at first white space character after
20708 ;; bullet, and check-box, if any.
20709 (let ((after-bullet
20710 (let ((box (match-end 3)))
20711 (if (not box) (match-end 1)
20712 (let ((after (char-after box)))
20713 (if (and after (= after ? )) (1+ box) box))))))
20714 ;; Special case: Move point to special position when
20715 ;; currently after it or at beginning of line.
20716 (if (eq special t)
20717 (when (or (> pos after-bullet) (= (point) pos))
20718 (goto-char after-bullet))
20719 ;; Reversed case: Move point to special position when
20720 ;; point was already at beginning of line and command is
20721 ;; repeated.
20722 (when (and (= (point) pos) (eq last-command this-command))
20723 (goto-char after-bullet))))))))
20724 (org-no-warnings
20725 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20727 (defun org-end-of-line (&optional arg)
20728 "Go to the end of the line.
20729 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20730 first attempt, and only move to after the tags when the cursor is already
20731 beyond the end of the headline."
20732 (interactive "P")
20733 (let ((special (if (consp org-special-ctrl-a/e)
20734 (cdr org-special-ctrl-a/e)
20735 org-special-ctrl-a/e)))
20736 (cond
20737 ((or (not special) arg
20738 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20739 (call-interactively
20740 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20741 ((fboundp 'move-end-of-line) 'move-end-of-line)
20742 (t 'end-of-line))))
20743 ((org-at-heading-p)
20744 (let ((pos (point)))
20745 (beginning-of-line 1)
20746 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20747 (if (eq special t)
20748 (if (or (< pos (match-beginning 1))
20749 (= pos (match-end 0)))
20750 (goto-char (match-beginning 1))
20751 (goto-char (match-end 0)))
20752 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20753 (goto-char (match-end 0))
20754 (goto-char (match-beginning 1))))
20755 (call-interactively (if (fboundp 'move-end-of-line)
20756 'move-end-of-line
20757 'end-of-line)))))
20758 ((org-at-drawer-p)
20759 (move-end-of-line 1)
20760 (when (overlays-at (1- (point))) (backward-char 1)))
20761 ;; At an item: Move before any hidden text.
20762 (t (call-interactively
20763 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20764 ((fboundp 'move-end-of-line) 'move-end-of-line)
20765 (t 'end-of-line)))))
20766 (org-no-warnings
20767 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20769 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20770 (define-key org-mode-map "\C-e" 'org-end-of-line)
20772 (defun org-backward-sentence (&optional arg)
20773 "Go to beginning of sentence, or beginning of table field.
20774 This will call `backward-sentence' or `org-table-beginning-of-field',
20775 depending on context."
20776 (interactive "P")
20777 (cond
20778 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20779 (t (call-interactively 'backward-sentence))))
20781 (defun org-forward-sentence (&optional arg)
20782 "Go to end of sentence, or end of table field.
20783 This will call `forward-sentence' or `org-table-end-of-field',
20784 depending on context."
20785 (interactive "P")
20786 (cond
20787 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20788 (t (call-interactively 'forward-sentence))))
20790 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20791 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20793 (defun org-kill-line (&optional arg)
20794 "Kill line, to tags or end of line."
20795 (interactive "P")
20796 (cond
20797 ((or (not org-special-ctrl-k)
20798 (bolp)
20799 (not (org-at-heading-p)))
20800 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20801 org-ctrl-k-protect-subtree)
20802 (if (or (eq org-ctrl-k-protect-subtree 'error)
20803 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20804 (error "C-k aborted - would kill hidden subtree")))
20805 (call-interactively
20806 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20807 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20808 (kill-region (point) (match-beginning 1))
20809 (org-set-tags nil t))
20810 (t (kill-region (point) (point-at-eol)))))
20812 (define-key org-mode-map "\C-k" 'org-kill-line)
20814 (defun org-yank (&optional arg)
20815 "Yank. If the kill is a subtree, treat it specially.
20816 This command will look at the current kill and check if is a single
20817 subtree, or a series of subtrees[1]. If it passes the test, and if the
20818 cursor is at the beginning of a line or after the stars of a currently
20819 empty headline, then the yank is handled specially. How exactly depends
20820 on the value of the following variables, both set by default.
20822 org-yank-folded-subtrees
20823 When set, the subtree(s) will be folded after insertion, but only
20824 if doing so would now swallow text after the yanked text.
20826 org-yank-adjusted-subtrees
20827 When set, the subtree will be promoted or demoted in order to
20828 fit into the local outline tree structure, which means that the level
20829 will be adjusted so that it becomes the smaller one of the two
20830 *visible* surrounding headings.
20832 Any prefix to this command will cause `yank' to be called directly with
20833 no special treatment. In particular, a simple \\[universal-argument] prefix \
20834 will just
20835 plainly yank the text as it is.
20837 \[1] The test checks if the first non-white line is a heading
20838 and if there are no other headings with fewer stars."
20839 (interactive "P")
20840 (org-yank-generic 'yank arg))
20842 (defun org-yank-generic (command arg)
20843 "Perform some yank-like command.
20845 This function implements the behavior described in the `org-yank'
20846 documentation. However, it has been generalized to work for any
20847 interactive command with similar behavior."
20849 ;; pretend to be command COMMAND
20850 (setq this-command command)
20852 (if arg
20853 (call-interactively command)
20855 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20856 (and (org-kill-is-subtree-p)
20857 (or (bolp)
20858 (and (looking-at "[ \t]*$")
20859 (string-match
20860 "\\`\\*+\\'"
20861 (buffer-substring (point-at-bol) (point)))))))
20862 swallowp)
20863 (cond
20864 ((and subtreep org-yank-folded-subtrees)
20865 (let ((beg (point))
20866 end)
20867 (if (and subtreep org-yank-adjusted-subtrees)
20868 (org-paste-subtree nil nil 'for-yank)
20869 (call-interactively command))
20871 (setq end (point))
20872 (goto-char beg)
20873 (when (and (bolp) subtreep
20874 (not (setq swallowp
20875 (org-yank-folding-would-swallow-text beg end))))
20876 (org-with-limited-levels
20877 (or (looking-at org-outline-regexp)
20878 (re-search-forward org-outline-regexp-bol end t))
20879 (while (and (< (point) end) (looking-at org-outline-regexp))
20880 (hide-subtree)
20881 (org-cycle-show-empty-lines 'folded)
20882 (condition-case nil
20883 (outline-forward-same-level 1)
20884 (error (goto-char end))))))
20885 (when swallowp
20886 (message
20887 "Inserted text not folded because that would swallow text"))
20889 (goto-char end)
20890 (skip-chars-forward " \t\n\r")
20891 (beginning-of-line 1)
20892 (push-mark beg 'nomsg)))
20893 ((and subtreep org-yank-adjusted-subtrees)
20894 (let ((beg (point-at-bol)))
20895 (org-paste-subtree nil nil 'for-yank)
20896 (push-mark beg 'nomsg)))
20898 (call-interactively command))))))
20900 (defun org-yank-folding-would-swallow-text (beg end)
20901 "Would hide-subtree at BEG swallow any text after END?"
20902 (let (level)
20903 (org-with-limited-levels
20904 (save-excursion
20905 (goto-char beg)
20906 (when (or (looking-at org-outline-regexp)
20907 (re-search-forward org-outline-regexp-bol end t))
20908 (setq level (org-outline-level)))
20909 (goto-char end)
20910 (skip-chars-forward " \t\r\n\v\f")
20911 (if (or (eobp)
20912 (and (bolp) (looking-at org-outline-regexp)
20913 (<= (org-outline-level) level)))
20914 nil ; Nothing would be swallowed
20915 t))))) ; something would swallow
20917 (define-key org-mode-map "\C-y" 'org-yank)
20919 (defun org-truely-invisible-p ()
20920 "Check if point is at a character currently not visible.
20921 This version does not only check the character property, but also
20922 `visible-mode'."
20923 ;; Early versions of noutline don't have `outline-invisible-p'.
20924 (if (org-bound-and-true-p visible-mode)
20926 (outline-invisible-p)))
20928 (defun org-invisible-p2 ()
20929 "Check if point is at a character currently not visible."
20930 (save-excursion
20931 (if (and (eolp) (not (bobp))) (backward-char 1))
20932 ;; Early versions of noutline don't have `outline-invisible-p'.
20933 (outline-invisible-p)))
20935 (defun org-back-to-heading (&optional invisible-ok)
20936 "Call `outline-back-to-heading', but provide a better error message."
20937 (condition-case nil
20938 (outline-back-to-heading invisible-ok)
20939 (error (error "Before first headline at position %d in buffer %s"
20940 (point) (current-buffer)))))
20942 (defun org-beginning-of-defun ()
20943 "Go to the beginning of the subtree, i.e. back to the heading."
20944 (org-back-to-heading))
20945 (defun org-end-of-defun ()
20946 "Go to the end of the subtree."
20947 (org-end-of-subtree nil t))
20949 (defun org-before-first-heading-p ()
20950 "Before first heading?"
20951 (save-excursion
20952 (end-of-line)
20953 (null (re-search-backward org-outline-regexp-bol nil t))))
20955 (defun org-at-heading-p (&optional ignored)
20956 (outline-on-heading-p t))
20957 ;; Compatibility alias with Org versions < 7.8.03
20958 (defalias 'org-on-heading-p 'org-at-heading-p)
20960 (defun org-at-drawer-p nil
20961 "Is cursor at a drawer keyword?"
20962 (save-excursion
20963 (move-beginning-of-line 1)
20964 (looking-at org-drawer-regexp)))
20966 (defun org-at-block-p nil
20967 "Is cursor at a block keyword?"
20968 (save-excursion
20969 (move-beginning-of-line 1)
20970 (looking-at org-block-regexp)))
20972 (defun org-point-at-end-of-empty-headline ()
20973 "If point is at the end of an empty headline, return t, else nil.
20974 If the heading only contains a TODO keyword, it is still still considered
20975 empty."
20976 (and (looking-at "[ \t]*$")
20977 (save-excursion
20978 (beginning-of-line 1)
20979 (let ((case-fold-search nil))
20980 (looking-at org-todo-line-regexp)))
20981 (string= (match-string 3) "")))
20983 (defun org-at-heading-or-item-p ()
20984 (or (org-at-heading-p) (org-at-item-p)))
20986 (defun org-at-target-p ()
20987 (or (org-in-regexp org-radio-target-regexp)
20988 (org-in-regexp org-target-regexp)))
20989 ;; Compatibility alias with Org versions < 7.8.03
20990 (defalias 'org-on-target-p 'org-at-target-p)
20992 (defun org-up-heading-all (arg)
20993 "Move to the heading line of which the present line is a subheading.
20994 This function considers both visible and invisible heading lines.
20995 With argument, move up ARG levels."
20996 (if (fboundp 'outline-up-heading-all)
20997 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20998 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21000 (defun org-up-heading-safe ()
21001 "Move to the heading line of which the present line is a subheading.
21002 This version will not throw an error. It will return the level of the
21003 headline found, or nil if no higher level is found.
21005 Also, this function will be a lot faster than `outline-up-heading',
21006 because it relies on stars being the outline starters. This can really
21007 make a significant difference in outlines with very many siblings."
21008 (let (start-level re)
21009 (org-back-to-heading t)
21010 (setq start-level (funcall outline-level))
21011 (if (equal start-level 1)
21013 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21014 (if (re-search-backward re nil t)
21015 (funcall outline-level)))))
21017 (defun org-first-sibling-p ()
21018 "Is this heading the first child of its parents?"
21019 (interactive)
21020 (let ((re org-outline-regexp-bol)
21021 level l)
21022 (unless (org-at-heading-p t)
21023 (error "Not at a heading"))
21024 (setq level (funcall outline-level))
21025 (save-excursion
21026 (if (not (re-search-backward re nil t))
21028 (setq l (funcall outline-level))
21029 (< l level)))))
21031 (defun org-goto-sibling (&optional previous)
21032 "Goto the next sibling, even if it is invisible.
21033 When PREVIOUS is set, go to the previous sibling instead. Returns t
21034 when a sibling was found. When none is found, return nil and don't
21035 move point."
21036 (let ((fun (if previous 're-search-backward 're-search-forward))
21037 (pos (point))
21038 (re org-outline-regexp-bol)
21039 level l)
21040 (when (condition-case nil (org-back-to-heading t) (error nil))
21041 (setq level (funcall outline-level))
21042 (catch 'exit
21043 (or previous (forward-char 1))
21044 (while (funcall fun re nil t)
21045 (setq l (funcall outline-level))
21046 (when (< l level) (goto-char pos) (throw 'exit nil))
21047 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21048 (goto-char pos)
21049 nil))))
21051 (defun org-show-siblings ()
21052 "Show all siblings of the current headline."
21053 (save-excursion
21054 (while (org-goto-sibling) (org-flag-heading nil)))
21055 (save-excursion
21056 (while (org-goto-sibling 'previous)
21057 (org-flag-heading nil))))
21059 (defun org-goto-first-child ()
21060 "Goto the first child, even if it is invisible.
21061 Return t when a child was found. Otherwise don't move point and
21062 return nil."
21063 (let (level (pos (point)) (re org-outline-regexp-bol))
21064 (when (condition-case nil (org-back-to-heading t) (error nil))
21065 (setq level (outline-level))
21066 (forward-char 1)
21067 (if (and (re-search-forward re nil t) (> (outline-level) level))
21068 (progn (goto-char (match-beginning 0)) t)
21069 (goto-char pos) nil))))
21071 (defun org-show-hidden-entry ()
21072 "Show an entry where even the heading is hidden."
21073 (save-excursion
21074 (org-show-entry)))
21076 (defun org-flag-heading (flag &optional entry)
21077 "Flag the current heading. FLAG non-nil means make invisible.
21078 When ENTRY is non-nil, show the entire entry."
21079 (save-excursion
21080 (org-back-to-heading t)
21081 ;; Check if we should show the entire entry
21082 (if entry
21083 (progn
21084 (org-show-entry)
21085 (save-excursion
21086 (and (outline-next-heading)
21087 (org-flag-heading nil))))
21088 (outline-flag-region (max (point-min) (1- (point)))
21089 (save-excursion (outline-end-of-heading) (point))
21090 flag))))
21092 (defun org-get-next-sibling ()
21093 "Move to next heading of the same level, and return point.
21094 If there is no such heading, return nil.
21095 This is like outline-next-sibling, but invisible headings are ok."
21096 (let ((level (funcall outline-level)))
21097 (outline-next-heading)
21098 (while (and (not (eobp)) (> (funcall outline-level) level))
21099 (outline-next-heading))
21100 (if (or (eobp) (< (funcall outline-level) level))
21102 (point))))
21104 (defun org-get-last-sibling ()
21105 "Move to previous heading of the same level, and return point.
21106 If there is no such heading, return nil."
21107 (let ((opoint (point))
21108 (level (funcall outline-level)))
21109 (outline-previous-heading)
21110 (when (and (/= (point) opoint) (outline-on-heading-p t))
21111 (while (and (> (funcall outline-level) level)
21112 (not (bobp)))
21113 (outline-previous-heading))
21114 (if (< (funcall outline-level) level)
21116 (point)))))
21118 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21119 ;; This contains an exact copy of the original function, but it uses
21120 ;; `org-back-to-heading', to make it work also in invisible
21121 ;; trees. And is uses an invisible-OK argument.
21122 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21123 ;; Furthermore, when used inside Org, finding the end of a large subtree
21124 ;; with many children and grandchildren etc, this can be much faster
21125 ;; than the outline version.
21126 (org-back-to-heading invisible-OK)
21127 (let ((first t)
21128 (level (funcall outline-level)))
21129 (if (and (eq major-mode 'org-mode) (< level 1000))
21130 ;; A true heading (not a plain list item), in Org-mode
21131 ;; This means we can easily find the end by looking
21132 ;; only for the right number of stars. Using a regexp to do
21133 ;; this is so much faster than using a Lisp loop.
21134 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21135 (forward-char 1)
21136 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21137 ;; something else, do it the slow way
21138 (while (and (not (eobp))
21139 (or first (> (funcall outline-level) level)))
21140 (setq first nil)
21141 (outline-next-heading)))
21142 (unless to-heading
21143 (if (memq (preceding-char) '(?\n ?\^M))
21144 (progn
21145 ;; Go to end of line before heading
21146 (forward-char -1)
21147 (if (memq (preceding-char) '(?\n ?\^M))
21148 ;; leave blank line before heading
21149 (forward-char -1))))))
21150 (point))
21152 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21153 "Use Org version in org-mode, for dramatic speed-up."
21154 (if (eq major-mode 'org-mode)
21155 (progn
21156 (org-end-of-subtree nil t)
21157 (unless (eobp) (backward-char 1)))
21158 ad-do-it))
21160 (defun org-end-of-meta-data-and-drawers ()
21161 "Jump to the first text after meta data and drawers in the current entry.
21162 This will move over empty lines, lines with planning time stamps,
21163 clocking lines, and drawers."
21164 (org-back-to-heading t)
21165 (let ((end (save-excursion (outline-next-heading) (point)))
21166 (re (concat "\\(" org-drawer-regexp "\\)"
21167 "\\|" "[ \t]*" org-keyword-time-regexp)))
21168 (forward-line 1)
21169 (while (re-search-forward re end t)
21170 (if (not (match-end 1))
21171 ;; empty or planning line
21172 (forward-line 1)
21173 ;; a drawer, find the end
21174 (re-search-forward "^[ \t]*:END:" end 'move)
21175 (forward-line 1)))
21176 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21177 (point)))
21179 (defun org-forward-same-level (arg &optional invisible-ok)
21180 "Move forward to the arg'th subheading at same level as this one.
21181 Stop at the first and last subheadings of a superior heading.
21182 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21183 it wil also look at invisible ones."
21184 (interactive "p")
21185 (org-back-to-heading invisible-ok)
21186 (org-at-heading-p)
21187 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21188 (re (format "^\\*\\{1,%d\\} " level))
21190 (forward-char 1)
21191 (while (> arg 0)
21192 (while (and (re-search-forward re nil 'move)
21193 (setq l (- (match-end 0) (match-beginning 0) 1))
21194 (= l level)
21195 (not invisible-ok)
21196 (progn (backward-char 1) (outline-invisible-p)))
21197 (if (< l level) (setq arg 1)))
21198 (setq arg (1- arg)))
21199 (beginning-of-line 1)))
21201 (defun org-backward-same-level (arg &optional invisible-ok)
21202 "Move backward to the arg'th subheading at same level as this one.
21203 Stop at the first and last subheadings of a superior heading."
21204 (interactive "p")
21205 (org-back-to-heading)
21206 (org-at-heading-p)
21207 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21208 (re (format "^\\*\\{1,%d\\} " level))
21210 (while (> arg 0)
21211 (while (and (re-search-backward re nil 'move)
21212 (setq l (- (match-end 0) (match-beginning 0) 1))
21213 (= l level)
21214 (not invisible-ok)
21215 (outline-invisible-p))
21216 (if (< l level) (setq arg 1)))
21217 (setq arg (1- arg)))))
21219 (defun org-show-subtree ()
21220 "Show everything after this heading at deeper levels."
21221 (interactive)
21222 (outline-flag-region
21223 (point)
21224 (save-excursion
21225 (org-end-of-subtree t t))
21226 nil))
21228 (defun org-show-entry ()
21229 "Show the body directly following this heading.
21230 Show the heading too, if it is currently invisible."
21231 (interactive)
21232 (save-excursion
21233 (condition-case nil
21234 (progn
21235 (org-back-to-heading t)
21236 (outline-flag-region
21237 (max (point-min) (1- (point)))
21238 (save-excursion
21239 (if (re-search-forward
21240 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21241 (match-beginning 1)
21242 (point-max)))
21243 nil)
21244 (org-cycle-hide-drawers 'children))
21245 (error nil))))
21247 (defun org-make-options-regexp (kwds &optional extra)
21248 "Make a regular expression for keyword lines."
21249 (concat
21251 "#?[ \t]*\\+\\("
21252 (mapconcat 'regexp-quote kwds "\\|")
21253 (if extra (concat "\\|" extra))
21254 "\\):[ \t]*"
21255 "\\(.*\\)"))
21257 ;; Make isearch reveal the necessary context
21258 (defun org-isearch-end ()
21259 "Reveal context after isearch exits."
21260 (when isearch-success ; only if search was successful
21261 (if (featurep 'xemacs)
21262 ;; Under XEmacs, the hook is run in the correct place,
21263 ;; we directly show the context.
21264 (org-show-context 'isearch)
21265 ;; In Emacs the hook runs *before* restoring the overlays.
21266 ;; So we have to use a one-time post-command-hook to do this.
21267 ;; (Emacs 22 has a special variable, see function `org-mode')
21268 (unless (and (boundp 'isearch-mode-end-hook-quit)
21269 isearch-mode-end-hook-quit)
21270 ;; Only when the isearch was not quitted.
21271 (org-add-hook 'post-command-hook 'org-isearch-post-command
21272 'append 'local)))))
21274 (defun org-isearch-post-command ()
21275 "Remove self from hook, and show context."
21276 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21277 (org-show-context 'isearch))
21280 ;;;; Integration with and fixes for other packages
21282 ;;; Imenu support
21284 (defvar org-imenu-markers nil
21285 "All markers currently used by Imenu.")
21286 (make-variable-buffer-local 'org-imenu-markers)
21288 (defun org-imenu-new-marker (&optional pos)
21289 "Return a new marker for use by Imenu, and remember the marker."
21290 (let ((m (make-marker)))
21291 (move-marker m (or pos (point)))
21292 (push m org-imenu-markers)
21295 (defun org-imenu-get-tree ()
21296 "Produce the index for Imenu."
21297 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21298 (setq org-imenu-markers nil)
21299 (let* ((n org-imenu-depth)
21300 (re (concat "^" (org-get-limited-outline-regexp)))
21301 (subs (make-vector (1+ n) nil))
21302 (last-level 0)
21303 m level head)
21304 (save-excursion
21305 (save-restriction
21306 (widen)
21307 (goto-char (point-max))
21308 (while (re-search-backward re nil t)
21309 (setq level (org-reduced-level (funcall outline-level)))
21310 (when (and (<= level n)
21311 (looking-at org-complex-heading-regexp))
21312 (setq head (org-link-display-format
21313 (org-match-string-no-properties 4))
21314 m (org-imenu-new-marker))
21315 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21316 (if (>= level last-level)
21317 (push (cons head m) (aref subs level))
21318 (push (cons head (aref subs (1+ level))) (aref subs level))
21319 (loop for i from (1+ level) to n do (aset subs i nil)))
21320 (setq last-level level)))))
21321 (aref subs 1)))
21323 (eval-after-load "imenu"
21324 '(progn
21325 (add-hook 'imenu-after-jump-hook
21326 (lambda ()
21327 (if (eq major-mode 'org-mode)
21328 (org-show-context 'org-goto))))))
21330 (defun org-link-display-format (link)
21331 "Replace a link with either the description, or the link target
21332 if no description is present"
21333 (save-match-data
21334 (if (string-match org-bracket-link-analytic-regexp link)
21335 (replace-match (if (match-end 5)
21336 (match-string 5 link)
21337 (concat (match-string 1 link)
21338 (match-string 3 link)))
21339 nil t link)
21340 link)))
21342 (defun org-toggle-link-display ()
21343 "Toggle the literal or descriptive display of links."
21344 (interactive)
21345 (if org-descriptive-links
21346 (progn (org-remove-from-invisibility-spec '(org-link))
21347 (org-restart-font-lock)
21348 (setq org-descriptive-links nil))
21349 (progn (add-to-invisibility-spec '(org-link))
21350 (org-restart-font-lock)
21351 (setq org-descriptive-links t))))
21353 ;; Speedbar support
21355 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21356 "Overlay marking the agenda restriction line in speedbar.")
21357 (overlay-put org-speedbar-restriction-lock-overlay
21358 'face 'org-agenda-restriction-lock)
21359 (overlay-put org-speedbar-restriction-lock-overlay
21360 'help-echo "Agendas are currently limited to this item.")
21361 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21363 (defun org-speedbar-set-agenda-restriction ()
21364 "Restrict future agenda commands to the location at point in speedbar.
21365 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21366 (interactive)
21367 (require 'org-agenda)
21368 (let (p m tp np dir txt)
21369 (cond
21370 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21371 'org-imenu t))
21372 (setq m (get-text-property p 'org-imenu-marker))
21373 (with-current-buffer (marker-buffer m)
21374 (goto-char m)
21375 (org-agenda-set-restriction-lock 'subtree)))
21376 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21377 'speedbar-function 'speedbar-find-file))
21378 (setq tp (previous-single-property-change
21379 (1+ p) 'speedbar-function)
21380 np (next-single-property-change
21381 tp 'speedbar-function)
21382 dir (speedbar-line-directory)
21383 txt (buffer-substring-no-properties (or tp (point-min))
21384 (or np (point-max))))
21385 (with-current-buffer (find-file-noselect
21386 (let ((default-directory dir))
21387 (expand-file-name txt)))
21388 (unless (eq major-mode 'org-mode)
21389 (error "Cannot restrict to non-Org-mode file"))
21390 (org-agenda-set-restriction-lock 'file)))
21391 (t (error "Don't know how to restrict Org-mode's agenda")))
21392 (move-overlay org-speedbar-restriction-lock-overlay
21393 (point-at-bol) (point-at-eol))
21394 (setq current-prefix-arg nil)
21395 (org-agenda-maybe-redo)))
21397 (eval-after-load "speedbar"
21398 '(progn
21399 (speedbar-add-supported-extension ".org")
21400 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21401 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21402 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21403 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21404 (add-hook 'speedbar-visiting-tag-hook
21405 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21407 ;;; Fixes and Hacks for problems with other packages
21409 ;; Make flyspell not check words in links, to not mess up our keymap
21410 (defun org-mode-flyspell-verify ()
21411 "Don't let flyspell put overlays at active buttons, or on
21412 {todo,all-time,additional-option-like}-keywords."
21413 (let ((pos (max (1- (point)) (point-min)))
21414 (word (thing-at-point 'word)))
21415 (and (not (get-text-property pos 'keymap))
21416 (not (get-text-property pos 'org-no-flyspell))
21417 (not (member word org-todo-keywords-1))
21418 (not (member word org-all-time-keywords))
21419 (not (member word org-additional-option-like-keywords)))))
21421 (defun org-remove-flyspell-overlays-in (beg end)
21422 "Remove flyspell overlays in region."
21423 (and (org-bound-and-true-p flyspell-mode)
21424 (fboundp 'flyspell-delete-region-overlays)
21425 (flyspell-delete-region-overlays beg end))
21426 (add-text-properties beg end '(org-no-flyspell t)))
21428 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21429 (eval-after-load "bookmark"
21430 '(if (boundp 'bookmark-after-jump-hook)
21431 ;; We can use the hook
21432 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21433 ;; Hook not available, use advice
21434 (defadvice bookmark-jump (after org-make-visible activate)
21435 "Make the position visible."
21436 (org-bookmark-jump-unhide))))
21438 ;; Make sure saveplace shows the location if it was hidden
21439 (eval-after-load "saveplace"
21440 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21441 "Make the position visible."
21442 (org-bookmark-jump-unhide)))
21444 ;; Make sure ecb shows the location if it was hidden
21445 (eval-after-load "ecb"
21446 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21447 "Make hierarchy visible when jumping into location from ECB tree buffer."
21448 (if (eq major-mode 'org-mode)
21449 (org-show-context))))
21451 (defun org-bookmark-jump-unhide ()
21452 "Unhide the current position, to show the bookmark location."
21453 (and (eq major-mode 'org-mode)
21454 (or (outline-invisible-p)
21455 (save-excursion (goto-char (max (point-min) (1- (point))))
21456 (outline-invisible-p)))
21457 (org-show-context 'bookmark-jump)))
21459 ;; Make session.el ignore our circular variable
21460 (eval-after-load "session"
21461 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21463 ;;;; Experimental code
21465 (defun org-closed-in-range ()
21466 "Sparse tree of items closed in a certain time range.
21467 Still experimental, may disappear in the future."
21468 (interactive)
21469 ;; Get the time interval from the user.
21470 (let* ((time1 (org-float-time
21471 (org-read-date nil 'to-time nil "Starting date: ")))
21472 (time2 (org-float-time
21473 (org-read-date nil 'to-time nil "End date:")))
21474 ;; callback function
21475 (callback (lambda ()
21476 (let ((time
21477 (org-float-time
21478 (apply 'encode-time
21479 (org-parse-time-string
21480 (match-string 1))))))
21481 ;; check if time in interval
21482 (and (>= time time1) (<= time time2))))))
21483 ;; make tree, check each match with the callback
21484 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21486 ;;;; Finish up
21488 (provide 'org)
21490 (run-hooks 'org-load-hook)
21492 ;;; org.el ends here