Fixed compiler warnings, including one small bug in ob-lilypond
[org-mode.git] / lisp / org.el
blob136ba866953a6087343ab889b53754f434ad91ec
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.03
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.03"
213 "The version number of the file org.el.")
215 ;;;###autoload
216 (defun org-version (&optional here)
217 "Show the org-mode version in the echo area.
218 With prefix arg HERE, insert it at point."
219 (interactive "P")
220 (let* ((origin default-directory)
221 (version org-version)
222 (git-version)
223 (dir (concat (file-name-directory (locate-library "org")) "../" )))
224 (when (and (file-exists-p (expand-file-name ".git" dir))
225 (executable-find "git"))
226 (unwind-protect
227 (progn
228 (cd dir)
229 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
230 (with-current-buffer "*Shell Command Output*"
231 (goto-char (point-min))
232 (setq git-version (buffer-substring (point) (point-at-eol))))
233 (subst-char-in-string ?- ?. git-version t)
234 (when (string-match "\\S-"
235 (shell-command-to-string
236 "git diff-index --name-only HEAD --"))
237 (setq git-version (concat git-version ".dirty")))
238 (setq version (concat version " (" git-version ")"))))
239 (cd origin)))
240 (setq version (format "Org-mode version %s" version))
241 (if here (insert version))
242 (message version)))
244 ;;; Compatibility constants
246 ;;; The custom variables
248 (defgroup org nil
249 "Outline-based notes management and organizer."
250 :tag "Org"
251 :group 'outlines
252 :group 'calendar)
254 (defcustom org-mode-hook nil
255 "Mode hook for Org-mode, run after the mode was turned on."
256 :group 'org
257 :type 'hook)
259 (defcustom org-load-hook nil
260 "Hook that is run after org.el has been loaded."
261 :group 'org
262 :type 'hook)
264 (defcustom org-log-buffer-setup-hook nil
265 "Hook that is run after an Org log buffer is created."
266 :group 'org
267 :version "24.1"
268 :type 'hook)
270 (defvar org-modules) ; defined below
271 (defvar org-modules-loaded nil
272 "Have the modules been loaded already?")
274 (defun org-load-modules-maybe (&optional force)
275 "Load all extensions listed in `org-modules'."
276 (when (or force (not org-modules-loaded))
277 (mapc (lambda (ext)
278 (condition-case nil (require ext)
279 (error (message "Problems while trying to load feature `%s'" ext))))
280 org-modules)
281 (setq org-modules-loaded t)))
283 (defun org-set-modules (var value)
284 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
285 (set var value)
286 (when (featurep 'org)
287 (org-load-modules-maybe 'force)))
289 (when (org-bound-and-true-p org-modules)
290 (let ((a (member 'org-infojs org-modules)))
291 (and a (setcar a 'org-jsinfo))))
293 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
294 "Modules that should always be loaded together with org.el.
295 If a description starts with <C>, the file is not part of Emacs
296 and loading it will require that you have downloaded and properly installed
297 the org-mode distribution.
299 You can also use this system to load external packages (i.e. neither Org
300 core modules, nor modules from the CONTRIB directory). Just add symbols
301 to the end of the list. If the package is called org-xyz.el, then you need
302 to add the symbol `xyz', and the package must have a call to
304 (provide 'org-xyz)"
305 :group 'org
306 :set 'org-set-modules
307 :type
308 '(set :greedy t
309 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
310 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
311 (const :tag " crypt: Encryption of subtrees" org-crypt)
312 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
313 (const :tag " docview: Links to doc-view buffers" org-docview)
314 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
315 (const :tag " id: Global IDs for identifying entries" org-id)
316 (const :tag " info: Links to Info nodes" org-info)
317 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
318 (const :tag " habit: Track your consistency with habits" org-habit)
319 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
320 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
321 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
322 (const :tag " mew Links to Mew folders/messages" org-mew)
323 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
324 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
325 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
326 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
327 (const :tag " vm: Links to VM folders/messages" org-vm)
328 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
329 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
330 (const :tag " mouse: Additional mouse support" org-mouse)
331 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
333 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
334 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
335 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
336 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
337 (const :tag "C collector: Collect properties into tables" org-collector)
338 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
339 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
340 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
341 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
342 (const :tag "C eval: Include command output as text" org-eval)
343 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
344 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
345 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
346 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
347 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
349 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
351 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
352 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
353 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
354 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
355 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
356 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
357 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
358 (const :tag "C mtags: Support for muse-like tags" org-mtags)
359 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
360 (const :tag "C registry: A registry for Org-mode links" org-registry)
361 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
362 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
363 (const :tag "C secretary: Team management with org-mode" org-secretary)
364 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
365 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
366 (const :tag "C track: Keep up with Org-mode development" org-track)
367 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
368 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
369 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
371 (defcustom org-support-shift-select nil
372 "Non-nil means make shift-cursor commands select text when possible.
374 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
375 start selecting a region, or enlarge regions started in this way.
376 In Org-mode, in special contexts, these same keys are used for
377 other purposes, important enough to compete with shift selection.
378 Org tries to balance these needs by supporting `shift-select-mode'
379 outside these special contexts, under control of this variable.
381 The default of this variable is nil, to avoid confusing behavior. Shifted
382 cursor keys will then execute Org commands in the following contexts:
383 - on a headline, changing TODO state (left/right) and priority (up/down)
384 - on a time stamp, changing the time
385 - in a plain list item, changing the bullet type
386 - in a property definition line, switching between allowed values
387 - in the BEGIN line of a clock table (changing the time block).
388 Outside these contexts, the commands will throw an error.
390 When this variable is t and the cursor is not in a special
391 context, Org-mode will support shift-selection for making and
392 enlarging regions. To make this more effective, the bullet
393 cycling will no longer happen anywhere in an item line, but only
394 if the cursor is exactly on the bullet.
396 If you set this variable to the symbol `always', then the keys
397 will not be special in headlines, property lines, and item lines,
398 to make shift selection work there as well. If this is what you
399 want, you can use the following alternative commands: `C-c C-t'
400 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
401 can be used to switch TODO sets, `C-c -' to cycle item bullet
402 types, and properties can be edited by hand or in column view.
404 However, when the cursor is on a timestamp, shift-cursor commands
405 will still edit the time stamp - this is just too good to give up.
407 XEmacs user should have this variable set to nil, because
408 `shift-select-mode' is in Emacs 23 or later only."
409 :group 'org
410 :type '(choice
411 (const :tag "Never" nil)
412 (const :tag "When outside special context" t)
413 (const :tag "Everywhere except timestamps" always)))
415 (defcustom org-loop-over-headlines-in-active-region nil
416 "Shall some commands act upon headlines in the active region?
418 When set to `t', some commands will be performed in all headlines
419 within the active region.
421 When set to `start-level', some commands will be performed in all
422 headlines within the active region, provided that these headlines
423 are of the same level than the first one.
425 When set to a string, those commands will be performed on the
426 matching headlines within the active region. Such string must be
427 a tags/property/todo match as it is used in the agenda tags view.
429 The list of commands is: `org-schedule', `org-deadline',
430 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
431 `org-archive-to-archive-sibling'. The archiving commands skip
432 already archived entries."
433 :type '(choice (const :tag "Don't loop" nil)
434 (const :tag "All headlines in active region" t)
435 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
436 (string :tag "Tags/Property/Todo matcher"))
437 :version "24.1"
438 :group 'org-todo
439 :group 'org-archive)
441 (defgroup org-startup nil
442 "Options concerning startup of Org-mode."
443 :tag "Org Startup"
444 :group 'org)
446 (defcustom org-startup-folded t
447 "Non-nil means entering Org-mode will switch to OVERVIEW.
448 This can also be configured on a per-file basis by adding one of
449 the following lines anywhere in the buffer:
451 #+STARTUP: fold (or `overview', this is equivalent)
452 #+STARTUP: nofold (or `showall', this is equivalent)
453 #+STARTUP: content
454 #+STARTUP: showeverything"
455 :group 'org-startup
456 :type '(choice
457 (const :tag "nofold: show all" nil)
458 (const :tag "fold: overview" t)
459 (const :tag "content: all headlines" content)
460 (const :tag "show everything, even drawers" showeverything)))
462 (defcustom org-startup-truncated t
463 "Non-nil means entering Org-mode will set `truncate-lines'.
464 This is useful since some lines containing links can be very long and
465 uninteresting. Also tables look terrible when wrapped."
466 :group 'org-startup
467 :type 'boolean)
469 (defcustom org-startup-indented nil
470 "Non-nil means turn on `org-indent-mode' on startup.
471 This can also be configured on a per-file basis by adding one of
472 the following lines anywhere in the buffer:
474 #+STARTUP: indent
475 #+STARTUP: noindent"
476 :group 'org-structure
477 :type '(choice
478 (const :tag "Not" nil)
479 (const :tag "Globally (slow on startup in large files)" t)))
481 (defcustom org-use-sub-superscripts t
482 "Non-nil means interpret \"_\" and \"^\" for export.
483 When this option is turned on, you can use TeX-like syntax for sub- and
484 superscripts. Several characters after \"_\" or \"^\" will be
485 considered as a single item - so grouping with {} is normally not
486 needed. For example, the following things will be parsed as single
487 sub- or superscripts.
489 10^24 or 10^tau several digits will be considered 1 item.
490 10^-12 or 10^-tau a leading sign with digits or a word
491 x^2-y^3 will be read as x^2 - y^3, because items are
492 terminated by almost any nonword/nondigit char.
493 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
495 Still, ambiguity is possible - so when in doubt use {} to enclose the
496 sub/superscript. If you set this variable to the symbol `{}',
497 the braces are *required* in order to trigger interpretations as
498 sub/superscript. This can be helpful in documents that need \"_\"
499 frequently in plain text.
501 Not all export backends support this, but HTML does.
503 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
504 :group 'org-startup
505 :group 'org-export-translation
506 :version "24.1"
507 :type '(choice
508 (const :tag "Always interpret" t)
509 (const :tag "Only with braces" {})
510 (const :tag "Never interpret" nil)))
512 (if (fboundp 'defvaralias)
513 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
516 (defcustom org-startup-with-beamer-mode nil
517 "Non-nil means turn on `org-beamer-mode' on startup.
518 This can also be configured on a per-file basis by adding one of
519 the following lines anywhere in the buffer:
521 #+STARTUP: beamer"
522 :group 'org-startup
523 :version "24.1"
524 :type 'boolean)
526 (defcustom org-startup-align-all-tables nil
527 "Non-nil means align all tables when visiting a file.
528 This is useful when the column width in tables is forced with <N> cookies
529 in table fields. Such tables will look correct only after the first re-align.
530 This can also be configured on a per-file basis by adding one of
531 the following lines anywhere in the buffer:
532 #+STARTUP: align
533 #+STARTUP: noalign"
534 :group 'org-startup
535 :type 'boolean)
537 (defcustom org-startup-with-inline-images nil
538 "Non-nil means show inline images when loading a new Org file.
539 This can also be configured on a per-file basis by adding one of
540 the following lines anywhere in the buffer:
541 #+STARTUP: inlineimages
542 #+STARTUP: noinlineimages"
543 :group 'org-startup
544 :version "24.1"
545 :type 'boolean)
547 (defcustom org-insert-mode-line-in-empty-file nil
548 "Non-nil means insert the first line setting Org-mode in empty files.
549 When the function `org-mode' is called interactively in an empty file, this
550 normally means that the file name does not automatically trigger Org-mode.
551 To ensure that the file will always be in Org-mode in the future, a
552 line enforcing Org-mode will be inserted into the buffer, if this option
553 has been set."
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-replace-disputed-keys nil
558 "Non-nil means use alternative key bindings for some keys.
559 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
560 These keys are also used by other packages like shift-selection-mode'
561 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
562 If you want to use Org-mode together with one of these other modes,
563 or more generally if you would like to move some Org-mode commands to
564 other keys, set this variable and configure the keys with the variable
565 `org-disputed-keys'.
567 This option is only relevant at load-time of Org-mode, and must be set
568 *before* org.el is loaded. Changing it requires a restart of Emacs to
569 become effective."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-use-extra-keys nil
574 "Non-nil means use extra key sequence definitions for certain commands.
575 This happens automatically if you run XEmacs or if `window-system'
576 is nil. This variable lets you do the same manually. You must
577 set it before loading org.
579 Example: on Carbon Emacs 22 running graphically, with an external
580 keyboard on a Powerbook, the default way of setting M-left might
581 not work for either Alt or ESC. Setting this variable will make
582 it work for ESC."
583 :group 'org-startup
584 :type 'boolean)
586 (if (fboundp 'defvaralias)
587 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
589 (defcustom org-disputed-keys
590 '(([(shift up)] . [(meta p)])
591 ([(shift down)] . [(meta n)])
592 ([(shift left)] . [(meta -)])
593 ([(shift right)] . [(meta +)])
594 ([(control shift right)] . [(meta shift +)])
595 ([(control shift left)] . [(meta shift -)]))
596 "Keys for which Org-mode and other modes compete.
597 This is an alist, cars are the default keys, second element specifies
598 the alternative to use when `org-replace-disputed-keys' is t.
600 Keys can be specified in any syntax supported by `define-key'.
601 The value of this option takes effect only at Org-mode's startup,
602 therefore you'll have to restart Emacs to apply it after changing."
603 :group 'org-startup
604 :type 'alist)
606 (defun org-key (key)
607 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
608 Or return the original if not disputed.
609 Also apply the translations defined in `org-xemacs-key-equivalents'."
610 (when org-replace-disputed-keys
611 (let* ((nkey (key-description key))
612 (x (org-find-if (lambda (x)
613 (equal (key-description (car x)) nkey))
614 org-disputed-keys)))
615 (setq key (if x (cdr x) key))))
616 (when (featurep 'xemacs)
617 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
618 key)
620 (defun org-find-if (predicate seq)
621 (catch 'exit
622 (while seq
623 (if (funcall predicate (car seq))
624 (throw 'exit (car seq))
625 (pop seq)))))
627 (defun org-defkey (keymap key def)
628 "Define a key, possibly translated, as returned by `org-key'."
629 (define-key keymap (org-key key) def))
631 (defcustom org-ellipsis nil
632 "The ellipsis to use in the Org-mode outline.
633 When nil, just use the standard three dots. When a string, use that instead,
634 When a face, use the standard 3 dots, but with the specified face.
635 The change affects only Org-mode (which will then use its own display table).
636 Changing this requires executing `M-x org-mode' in a buffer to become
637 effective."
638 :group 'org-startup
639 :type '(choice (const :tag "Default" nil)
640 (face :tag "Face" :value org-warning)
641 (string :tag "String" :value "...#")))
643 (defvar org-display-table nil
644 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
646 (defgroup org-keywords nil
647 "Keywords in Org-mode."
648 :tag "Org Keywords"
649 :group 'org)
651 (defcustom org-deadline-string "DEADLINE:"
652 "String to mark deadline entries.
653 A deadline is this string, followed by a time stamp. Should be a word,
654 terminated by a colon. You can insert a schedule keyword and
655 a timestamp with \\[org-deadline].
656 Changes become only effective after restarting Emacs."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-scheduled-string "SCHEDULED:"
661 "String to mark scheduled TODO entries.
662 A schedule is this string, followed by a time stamp. Should be a word,
663 terminated by a colon. You can insert a schedule keyword and
664 a timestamp with \\[org-schedule].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-closed-string "CLOSED:"
670 "String used as the prefix for timestamps logging closing a TODO entry."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-clock-string "CLOCK:"
675 "String used as prefix for timestamps clocking work hours on an item."
676 :group 'org-keywords
677 :type 'string)
679 (defcustom org-comment-string "COMMENT"
680 "Entries starting with this keyword will never be exported.
681 An entry can be toggled between COMMENT and normal with
682 \\[org-toggle-comment].
683 Changes become only effective after restarting Emacs."
684 :group 'org-keywords
685 :type 'string)
687 (defcustom org-quote-string "QUOTE"
688 "Entries starting with this keyword will be exported in fixed-width font.
689 Quoting applies only to the text in the entry following the headline, and does
690 not extend beyond the next headline, even if that is lower level.
691 An entry can be toggled between QUOTE and normal with
692 \\[org-toggle-fixed-width-section]."
693 :group 'org-keywords
694 :type 'string)
696 (defconst org-repeat-re
697 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
698 "Regular expression for specifying repeated events.
699 After a match, group 1 contains the repeat expression.")
701 (defgroup org-structure nil
702 "Options concerning the general structure of Org-mode files."
703 :tag "Org Structure"
704 :group 'org)
706 (defgroup org-reveal-location nil
707 "Options about how to make context of a location visible."
708 :tag "Org Reveal Location"
709 :group 'org-structure)
711 (defconst org-context-choice
712 '(choice
713 (const :tag "Always" t)
714 (const :tag "Never" nil)
715 (repeat :greedy t :tag "Individual contexts"
716 (cons
717 (choice :tag "Context"
718 (const agenda)
719 (const org-goto)
720 (const occur-tree)
721 (const tags-tree)
722 (const link-search)
723 (const mark-goto)
724 (const bookmark-jump)
725 (const isearch)
726 (const default))
727 (boolean))))
728 "Contexts for the reveal options.")
730 (defcustom org-show-hierarchy-above '((default . t))
731 "Non-nil means show full hierarchy when revealing a location.
732 Org-mode often shows locations in an org-mode file which might have
733 been invisible before. When this is set, the hierarchy of headings
734 above the exposed location is shown.
735 Turning this off for example for sparse trees makes them very compact.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. Valid contexts are
738 agenda when exposing an entry from the agenda
739 org-goto when using the command `org-goto' on key C-c C-j
740 occur-tree when using the command `org-occur' on key C-c /
741 tags-tree when constructing a sparse tree based on tags matches
742 link-search when exposing search matches associated with a link
743 mark-goto when exposing the jump goal of a mark
744 bookmark-jump when exposing a bookmark location
745 isearch when exiting from an incremental search
746 default default for all contexts not set explicitly"
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-following-heading '((default . nil))
751 "Non-nil means show following heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the heading following the
754 match is shown.
755 Turning this off for example for sparse trees makes them very compact,
756 but makes it harder to edit the location of the match. In such a case,
757 use the command \\[org-reveal] to show more context.
758 Instead of t, this can also be an alist specifying this option for different
759 contexts. See `org-show-hierarchy-above' for valid contexts."
760 :group 'org-reveal-location
761 :type org-context-choice)
763 (defcustom org-show-siblings '((default . nil) (isearch t))
764 "Non-nil means show all sibling heading when revealing a location.
765 Org-mode often shows locations in an org-mode file which might have
766 been invisible before. When this is set, the sibling of the current entry
767 heading are all made visible. If `org-show-hierarchy-above' is t,
768 the same happens on each level of the hierarchy above the current entry.
770 By default this is on for the isearch context, off for all other contexts.
771 Turning this off for example for sparse trees makes them very compact,
772 but makes it harder to edit the location of the match. In such a case,
773 use the command \\[org-reveal] to show more context.
774 Instead of t, this can also be an alist specifying this option for different
775 contexts. See `org-show-hierarchy-above' for valid contexts."
776 :group 'org-reveal-location
777 :type org-context-choice)
779 (defcustom org-show-entry-below '((default . nil))
780 "Non-nil means show the entry below a headline when revealing a location.
781 Org-mode often shows locations in an org-mode file which might have
782 been invisible before. When this is set, the text below the headline that is
783 exposed is also shown.
785 By default this is off for all contexts.
786 Instead of t, this can also be an alist specifying this option for different
787 contexts. See `org-show-hierarchy-above' for valid contexts."
788 :group 'org-reveal-location
789 :type org-context-choice)
791 (defcustom org-indirect-buffer-display 'other-window
792 "How should indirect tree buffers be displayed?
793 This applies to indirect buffers created with the commands
794 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
795 Valid values are:
796 current-window Display in the current window
797 other-window Just display in another window.
798 dedicated-frame Create one new frame, and re-use it each time.
799 new-frame Make a new frame each time. Note that in this case
800 previously-made indirect buffers are kept, and you need to
801 kill these buffers yourself."
802 :group 'org-structure
803 :group 'org-agenda-windows
804 :type '(choice
805 (const :tag "In current window" current-window)
806 (const :tag "In current frame, other window" other-window)
807 (const :tag "Each time a new frame" new-frame)
808 (const :tag "One dedicated frame" dedicated-frame)))
810 (defcustom org-use-speed-commands nil
811 "Non-nil means activate single letter commands at beginning of a headline.
812 This may also be a function to test for appropriate locations where speed
813 commands should be active."
814 :group 'org-structure
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "At beginning of headline stars" t)
818 (function)))
820 (defcustom org-speed-commands-user nil
821 "Alist of additional speed commands.
822 This list will be checked before `org-speed-commands-default'
823 when the variable `org-use-speed-commands' is non-nil
824 and when the cursor is at the beginning of a headline.
825 The car if each entry is a string with a single letter, which must
826 be assigned to `self-insert-command' in the global map.
827 The cdr is either a command to be called interactively, a function
828 to be called, or a form to be evaluated.
829 An entry that is just a list with a single string will be interpreted
830 as a descriptive headline that will be added when listing the speed
831 commands in the Help buffer using the `?' speed command."
832 :group 'org-structure
833 :type '(repeat :value ("k" . ignore)
834 (choice :value ("k" . ignore)
835 (list :tag "Descriptive Headline" (string :tag "Headline"))
836 (cons :tag "Letter and Command"
837 (string :tag "Command letter")
838 (choice
839 (function)
840 (sexp))))))
842 (defgroup org-cycle nil
843 "Options concerning visibility cycling in Org-mode."
844 :tag "Org Cycle"
845 :group 'org-structure)
847 (defcustom org-cycle-skip-children-state-if-no-children t
848 "Non-nil means skip CHILDREN state in entries that don't have any."
849 :group 'org-cycle
850 :type 'boolean)
852 (defcustom org-cycle-max-level nil
853 "Maximum level which should still be subject to visibility cycling.
854 Levels higher than this will, for cycling, be treated as text, not a headline.
855 When `org-odd-levels-only' is set, a value of N in this variable actually
856 means 2N-1 stars as the limiting headline.
857 When nil, cycle all levels.
858 Note that the limiting level of cycling is also influenced by
859 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
860 `org-inlinetask-min-level' is, cycling will be limited to levels one less
861 than its value."
862 :group 'org-cycle
863 :type '(choice
864 (const :tag "No limit" nil)
865 (integer :tag "Maximum level")))
867 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
868 "Names of drawers. Drawers are not opened by cycling on the headline above.
869 Drawers only open with a TAB on the drawer line itself. A drawer looks like
870 this:
871 :DRAWERNAME:
872 .....
873 :END:
874 The drawer \"PROPERTIES\" is special for capturing properties through
875 the property API.
877 Drawers can be defined on the per-file basis with a line like:
879 #+DRAWERS: HIDDEN STATE PROPERTIES"
880 :group 'org-structure
881 :group 'org-cycle
882 :type '(repeat (string :tag "Drawer Name")))
884 (defcustom org-hide-block-startup nil
885 "Non-nil means entering Org-mode will fold all blocks.
886 This can also be set in on a per-file basis with
888 #+STARTUP: hideblocks
889 #+STARTUP: showblocks"
890 :group 'org-startup
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-global-at-bob nil
895 "Cycle globally if cursor is at beginning of buffer and not at a headline.
896 This makes it possible to do global cycling without having to use S-TAB or
897 \\[universal-argument] TAB. For this special case to work, the first line \
898 of the buffer
899 must not be a headline - it may be empty or some other text. When used in
900 this way, `org-cycle-hook' is disables temporarily, to make sure the
901 cursor stays at the beginning of the buffer.
902 When this option is nil, don't do anything special at the beginning
903 of the buffer."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-level-after-item/entry-creation t
908 "Non-nil means cycle entry level or item indentation in new empty entries.
910 When the cursor is at the end of an empty headline, i.e with only stars
911 and maybe a TODO keyword, TAB will then switch the entry to become a child,
912 and then all possible ancestor states, before returning to the original state.
913 This makes data entry extremely fast: M-RET to create a new headline,
914 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
916 When the cursor is at the end of an empty plain list item, one TAB will
917 make it a subitem, two or more tabs will back up to make this an item
918 higher up in the item hierarchy."
919 :group 'org-cycle
920 :type 'boolean)
922 (defcustom org-cycle-emulate-tab t
923 "Where should `org-cycle' emulate TAB.
924 nil Never
925 white Only in completely white lines
926 whitestart Only at the beginning of lines, before the first non-white char
927 t Everywhere except in headlines
928 exc-hl-bol Everywhere except at the start of a headline
929 If TAB is used in a place where it does not emulate TAB, the current subtree
930 visibility is cycled."
931 :group 'org-cycle
932 :type '(choice (const :tag "Never" nil)
933 (const :tag "Only in completely white lines" white)
934 (const :tag "Before first char in a line" whitestart)
935 (const :tag "Everywhere except in headlines" t)
936 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
939 (defcustom org-cycle-separator-lines 2
940 "Number of empty lines needed to keep an empty line between collapsed trees.
941 If you leave an empty line between the end of a subtree and the following
942 headline, this empty line is hidden when the subtree is folded.
943 Org-mode will leave (exactly) one empty line visible if the number of
944 empty lines is equal or larger to the number given in this variable.
945 So the default 2 means at least 2 empty lines after the end of a subtree
946 are needed to produce free space between a collapsed subtree and the
947 following headline.
949 If the number is negative, and the number of empty lines is at least -N,
950 all empty lines are shown.
952 Special case: when 0, never leave empty lines in collapsed view."
953 :group 'org-cycle
954 :type 'integer)
955 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
957 (defcustom org-pre-cycle-hook nil
958 "Hook that is run before visibility cycling is happening.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that will be set right after running this hook. The
961 argument is a symbol. Before a global state change, it can have the values
962 `overview', `content', or `all'. Before a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
968 org-cycle-hide-drawers
969 org-cycle-show-empty-lines
970 org-optimize-window-after-visibility-change)
971 "Hook that is run after `org-cycle' has changed the buffer visibility.
972 The function(s) in this hook must accept a single argument which indicates
973 the new state that was set by the most recent `org-cycle' command. The
974 argument is a symbol. After a global state change, it can have the values
975 `overview', `content', or `all'. After a local state change, it can have
976 the values `folded', `children', or `subtree'."
977 :group 'org-cycle
978 :type 'hook)
980 (defgroup org-edit-structure nil
981 "Options concerning structure editing in Org-mode."
982 :tag "Org Edit Structure"
983 :group 'org-structure)
985 (defcustom org-odd-levels-only nil
986 "Non-nil means skip even levels and only use odd levels for the outline.
987 This has the effect that two stars are being added/taken away in
988 promotion/demotion commands. It also influences how levels are
989 handled by the exporters.
990 Changing it requires restart of `font-lock-mode' to become effective
991 for fontification also in regions already fontified.
992 You may also set this on a per-file basis by adding one of the following
993 lines to the buffer:
995 #+STARTUP: odd
996 #+STARTUP: oddeven"
997 :group 'org-edit-structure
998 :group 'org-appearance
999 :type 'boolean)
1001 (defcustom org-adapt-indentation t
1002 "Non-nil means adapt indentation to outline node level.
1004 When this variable is set, Org assumes that you write outlines by
1005 indenting text in each node to align with the headline (after the stars).
1006 The following issues are influenced by this variable:
1008 - When this is set and the *entire* text in an entry is indented, the
1009 indentation is increased by one space in a demotion command, and
1010 decreased by one in a promotion command. If any line in the entry
1011 body starts with text at column 0, indentation is not changed at all.
1013 - Property drawers and planning information is inserted indented when
1014 this variable s set. When nil, they will not be indented.
1016 - TAB indents a line relative to context. The lines below a headline
1017 will be indented when this variable is set.
1019 Note that this is all about true indentation, by adding and removing
1020 space characters. See also `org-indent.el' which does level-dependent
1021 indentation in a virtual way, i.e. at display time in Emacs."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-special-ctrl-a/e nil
1026 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1028 When t, `C-a' will bring back the cursor to the beginning of the
1029 headline text, i.e. after the stars and after a possible TODO
1030 keyword. In an item, this will be the position after bullet and
1031 check-box, if any. When the cursor is already at that position,
1032 another `C-a' will bring it to the beginning of the line.
1034 `C-e' will jump to the end of the headline, ignoring the presence
1035 of tags in the headline. A second `C-e' will then jump to the
1036 true end of the line, after any tags. This also means that, when
1037 this variable is non-nil, `C-e' also will never jump beyond the
1038 end of the heading of a folded section, i.e. not after the
1039 ellipses.
1041 When set to the symbol `reversed', the first `C-a' or `C-e' works
1042 normally, going to the true line boundary first. Only a directly
1043 following, identical keypress will bring the cursor to the
1044 special positions.
1046 This may also be a cons cell where the behavior for `C-a' and
1047 `C-e' is set separately."
1048 :group 'org-edit-structure
1049 :type '(choice
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet and before tags first" t)
1052 (const :tag "reversed: true line boundary first" reversed)
1053 (cons :tag "Set C-a and C-e separately"
1054 (choice :tag "Special C-a"
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet first" t)
1057 (const :tag "reversed: before stars/bullet first" reversed))
1058 (choice :tag "Special C-e"
1059 (const :tag "off" nil)
1060 (const :tag "on: before tags first" t)
1061 (const :tag "reversed: after tags first" reversed)))))
1062 (if (fboundp 'defvaralias)
1063 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1065 (defcustom org-special-ctrl-k nil
1066 "Non-nil means `C-k' will behave specially in headlines.
1067 When nil, `C-k' will call the default `kill-line' command.
1068 When t, the following will happen while the cursor is in the headline:
1070 - When the cursor is at the beginning of a headline, kill the entire
1071 line and possible the folded subtree below the line.
1072 - When in the middle of the headline text, kill the headline up to the tags.
1073 - When after the headline text, kill the tags."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-ctrl-k-protect-subtree nil
1078 "Non-nil means, do not delete a hidden subtree with C-k.
1079 When set to the symbol `error', simply throw an error when C-k is
1080 used to kill (part-of) a headline that has hidden text behind it.
1081 Any other non-nil value will result in a query to the user, if it is
1082 OK to kill that hidden subtree. When nil, kill without remorse."
1083 :group 'org-edit-structure
1084 :version "24.1"
1085 :type '(choice
1086 (const :tag "Do not protect hidden subtrees" nil)
1087 (const :tag "Protect hidden subtrees with a security query" t)
1088 (const :tag "Never kill a hidden subtree with C-k" error)))
1090 (defcustom org-catch-invisible-edits nil
1091 "Check if in invisible region before inserting or deleting a character.
1092 Valid values are:
1094 nil Do not check, so just do invisible edits.
1095 error Throw an error and do nothing.
1096 show Make point visible, and do the requested edit.
1097 show-and-error Make point visible, then throw an error and abort the edit.
1098 smart Make point visible, and do insertion/deletion if it is
1099 adjacent to visible text and the change feels predictable.
1100 Never delete a previously invisible character or add in the
1101 middle or right after an invisible region. Basically, this
1102 allows insertion and backward-delete right before ellipses.
1103 FIXME: maybe in this case we should not even show?"
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not check" nil)
1108 (const :tag "Throw error when trying to edit" error)
1109 (const :tag "Unhide, but do not do the edit" show-and-error)
1110 (const :tag "Show invisible part and do the edit" show)
1111 (const :tag "Be smart and do the right thing" smart)))
1113 (defcustom org-yank-folded-subtrees t
1114 "Non-nil means when yanking subtrees, fold them.
1115 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1116 it starts with a heading and all other headings in it are either children
1117 or siblings, then fold all the subtrees. However, do this only if no
1118 text after the yank would be swallowed into a folded tree by this action."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-yank-adjusted-subtrees nil
1123 "Non-nil means when yanking subtrees, adjust the level.
1124 With this setting, `org-paste-subtree' is used to insert the subtree, see
1125 this function for details."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defcustom org-M-RET-may-split-line '((default . t))
1130 "Non-nil means M-RET will split the line at the cursor position.
1131 When nil, it will go to the end of the line before making a
1132 new line.
1133 You may also set this option in a different way for different
1134 contexts. Valid contexts are:
1136 headline when creating a new headline
1137 item when creating a new item
1138 table in a table field
1139 default the value to be used for all contexts not explicitly
1140 customized"
1141 :group 'org-structure
1142 :group 'org-table
1143 :type '(choice
1144 (const :tag "Always" t)
1145 (const :tag "Never" nil)
1146 (repeat :greedy t :tag "Individual contexts"
1147 (cons
1148 (choice :tag "Context"
1149 (const headline)
1150 (const item)
1151 (const table)
1152 (const default))
1153 (boolean)))))
1156 (defcustom org-insert-heading-respect-content nil
1157 "Non-nil means insert new headings after the current subtree.
1158 When nil, the new heading is created directly after the current line.
1159 The commands \\[org-insert-heading-respect-content] and
1160 \\[org-insert-todo-heading-respect-content] turn this variable on
1161 for the duration of the command."
1162 :group 'org-structure
1163 :type 'boolean)
1165 (defcustom org-blank-before-new-entry '((heading . auto)
1166 (plain-list-item . auto))
1167 "Should `org-insert-heading' leave a blank line before new heading/item?
1168 The value is an alist, with `heading' and `plain-list-item' as CAR,
1169 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1170 which case Org will look at the surrounding headings/items and try to
1171 make an intelligent decision whether to insert a blank line or not.
1173 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1174 set, the setting here is ignored and no empty line is inserted, to avoid
1175 breaking the list structure."
1176 :group 'org-edit-structure
1177 :type '(list
1178 (cons (const heading)
1179 (choice (const :tag "Never" nil)
1180 (const :tag "Always" t)
1181 (const :tag "Auto" auto)))
1182 (cons (const plain-list-item)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))))
1187 (defcustom org-insert-heading-hook nil
1188 "Hook being run after inserting a new heading."
1189 :group 'org-edit-structure
1190 :type 'hook)
1192 (defcustom org-enable-fixed-width-editor t
1193 "Non-nil means lines starting with \":\" are treated as fixed-width.
1194 This currently only means they are never auto-wrapped.
1195 When nil, such lines will be treated like ordinary lines.
1196 See also the QUOTE keyword."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defcustom org-goto-auto-isearch t
1201 "Non-nil means typing characters in `org-goto' starts incremental search."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defgroup org-sparse-trees nil
1206 "Options concerning sparse trees in Org-mode."
1207 :tag "Org Sparse Trees"
1208 :group 'org-structure)
1210 (defcustom org-highlight-sparse-tree-matches t
1211 "Non-nil means highlight all matches that define a sparse tree.
1212 The highlights will automatically disappear the next time the buffer is
1213 changed by an edit command."
1214 :group 'org-sparse-trees
1215 :type 'boolean)
1217 (defcustom org-remove-highlights-with-change t
1218 "Non-nil means any change to the buffer will remove temporary highlights.
1219 Such highlights are created by `org-occur' and `org-clock-display'.
1220 When nil, `C-c C-c needs to be used to get rid of the highlights.
1221 The highlights created by `org-preview-latex-fragment' always need
1222 `C-c C-c' to be removed."
1223 :group 'org-sparse-trees
1224 :group 'org-time
1225 :type 'boolean)
1228 (defcustom org-occur-hook '(org-first-headline-recenter)
1229 "Hook that is run after `org-occur' has constructed a sparse tree.
1230 This can be used to recenter the window to show as much of the structure
1231 as possible."
1232 :group 'org-sparse-trees
1233 :type 'hook)
1235 (defgroup org-imenu-and-speedbar nil
1236 "Options concerning imenu and speedbar in Org-mode."
1237 :tag "Org Imenu and Speedbar"
1238 :group 'org-structure)
1240 (defcustom org-imenu-depth 2
1241 "The maximum level for Imenu access to Org-mode headlines.
1242 This also applied for speedbar access."
1243 :group 'org-imenu-and-speedbar
1244 :type 'integer)
1246 (defgroup org-table nil
1247 "Options concerning tables in Org-mode."
1248 :tag "Org Table"
1249 :group 'org)
1251 (defcustom org-enable-table-editor 'optimized
1252 "Non-nil means lines starting with \"|\" are handled by the table editor.
1253 When nil, such lines will be treated like ordinary lines.
1255 When equal to the symbol `optimized', the table editor will be optimized to
1256 do the following:
1257 - Automatic overwrite mode in front of whitespace in table fields.
1258 This makes the structure of the table stay in tact as long as the edited
1259 field does not exceed the column width.
1260 - Minimize the number of realigns. Normally, the table is aligned each time
1261 TAB or RET are pressed to move to another field. With optimization this
1262 happens only if changes to a field might have changed the column width.
1263 Optimization requires replacing the functions `self-insert-command',
1264 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1265 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1266 very good at guessing when a re-align will be necessary, but you can always
1267 force one with \\[org-ctrl-c-ctrl-c].
1269 If you would like to use the optimized version in Org-mode, but the
1270 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1272 This variable can be used to turn on and off the table editor during a session,
1273 but in order to toggle optimization, a restart is required.
1275 See also the variable `org-table-auto-blank-field'."
1276 :group 'org-table
1277 :type '(choice
1278 (const :tag "off" nil)
1279 (const :tag "on" t)
1280 (const :tag "on, optimized" optimized)))
1282 (defcustom org-self-insert-cluster-for-undo t
1283 "Non-nil means cluster self-insert commands for undo when possible.
1284 If this is set, then, like in the Emacs command loop, 20 consecutive
1285 characters will be undone together.
1286 This is configurable, because there is some impact on typing performance."
1287 :group 'org-table
1288 :type 'boolean)
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1294 :group 'org-table-editing
1295 :type 'boolean)
1297 (defgroup org-link nil
1298 "Options concerning links in Org-mode."
1299 :tag "Org Link"
1300 :group 'org)
1302 (defvar org-link-abbrev-alist-local nil
1303 "Buffer-local version of `org-link-abbrev-alist', which see.
1304 The value of this is taken from the #+LINK lines.")
1305 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1307 (defcustom org-link-abbrev-alist nil
1308 "Alist of link abbreviations.
1309 The car of each element is a string, to be replaced at the start of a link.
1310 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1311 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1313 [[linkkey:tag][description]]
1315 The 'linkkey' must be a word word, starting with a letter, followed
1316 by letters, numbers, '-' or '_'.
1318 If REPLACE is a string, the tag will simply be appended to create the link.
1319 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1320 the placeholder \"%h\" will cause a url-encoded version of the tag to
1321 be inserted at that point (see the function `url-hexify-string').
1323 REPLACE may also be a function that will be called with the tag as the
1324 only argument to create the link, which should be returned as a string.
1326 See the manual for examples."
1327 :group 'org-link
1328 :type '(repeat
1329 (cons
1330 (string :tag "Protocol")
1331 (choice
1332 (string :tag "Format")
1333 (function)))))
1335 (defcustom org-descriptive-links t
1336 "Non-nil means Org will display descriptive links.
1337 E.g. [[http://orgmode.org][Org website]] will be displayed as
1338 \"Org Website\", hiding the link itself and just displaying its
1339 description. When set to `nil', Org will display the full links
1340 literally.
1342 You can interactively set the value of this variable by calling
1343 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1344 :group 'org-link
1345 :type 'boolean)
1347 (defcustom org-link-file-path-type 'adaptive
1348 "How the path name in file links should be stored.
1349 Valid values are:
1351 relative Relative to the current directory, i.e. the directory of the file
1352 into which the link is being inserted.
1353 absolute Absolute path, if possible with ~ for home directory.
1354 noabbrev Absolute path, no abbreviation of home directory.
1355 adaptive Use relative path for files in the current directory and sub-
1356 directories of it. For other files, use an absolute path."
1357 :group 'org-link
1358 :type '(choice
1359 (const relative)
1360 (const absolute)
1361 (const noabbrev)
1362 (const adaptive)))
1364 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1365 "Types of links that should be activated in Org-mode files.
1366 This is a list of symbols, each leading to the activation of a certain link
1367 type. In principle, it does not hurt to turn on most link types - there may
1368 be a small gain when turning off unused link types. The types are:
1370 bracket The recommended [[link][description]] or [[link]] links with hiding.
1371 angle Links in angular brackets that may contain whitespace like
1372 <bbdb:Carsten Dominik>.
1373 plain Plain links in normal text, no whitespace, like http://google.com.
1374 radio Text that is matched by a radio target, see manual for details.
1375 tag Tag settings in a headline (link to tag search).
1376 date Time stamps (link to calendar).
1377 footnote Footnote labels.
1379 Changing this variable requires a restart of Emacs to become effective."
1380 :group 'org-link
1381 :type '(set :greedy t
1382 (const :tag "Double bracket links" bracket)
1383 (const :tag "Angular bracket links" angle)
1384 (const :tag "Plain text links" plain)
1385 (const :tag "Radio target matches" radio)
1386 (const :tag "Tags" tag)
1387 (const :tag "Timestamps" date)
1388 (const :tag "Footnotes" footnote)))
1390 (defcustom org-make-link-description-function nil
1391 "Function to use to generate link descriptions from links.
1392 If nil the link location will be used. This function must take
1393 two parameters; the first is the link and the second the
1394 description `org-insert-link' has generated, and should return the
1395 description to use."
1396 :group 'org-link
1397 :type 'function)
1399 (defgroup org-link-store nil
1400 "Options concerning storing links in Org-mode."
1401 :tag "Org Store Link"
1402 :group 'org-link)
1404 (defcustom org-email-link-description-format "Email %c: %.30s"
1405 "Format of the description part of a link to an email or usenet message.
1406 The following %-escapes will be replaced by corresponding information:
1408 %F full \"From\" field
1409 %f name, taken from \"From\" field, address if no name
1410 %T full \"To\" field
1411 %t first name in \"To\" field, address if no name
1412 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1413 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1414 %s subject
1415 %d date
1416 %m message-id.
1418 You may use normal field width specification between the % and the letter.
1419 This is for example useful to limit the length of the subject.
1421 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1422 :group 'org-link-store
1423 :type 'string)
1425 (defcustom org-from-is-user-regexp
1426 (let (r1 r2)
1427 (when (and user-mail-address (not (string= user-mail-address "")))
1428 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1429 (when (and user-full-name (not (string= user-full-name "")))
1430 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1431 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1432 "Regexp matched against the \"From:\" header of an email or usenet message.
1433 It should match if the message is from the user him/herself."
1434 :group 'org-link-store
1435 :type 'regexp)
1437 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1438 "Non-nil means storing a link to an Org file will use entry IDs.
1440 Note that before this variable is even considered, org-id must be loaded,
1441 so please customize `org-modules' and turn it on.
1443 The variable can have the following values:
1445 t Create an ID if needed to make a link to the current entry.
1447 create-if-interactive
1448 If `org-store-link' is called directly (interactively, as a user
1449 command), do create an ID to support the link. But when doing the
1450 job for remember, only use the ID if it already exists. The
1451 purpose of this setting is to avoid proliferation of unwanted
1452 IDs, just because you happen to be in an Org file when you
1453 call `org-remember' that automatically and preemptively
1454 creates a link. If you do want to get an ID link in a remember
1455 template to an entry not having an ID, create it first by
1456 explicitly creating a link to it, using `C-c C-l' first.
1458 create-if-interactive-and-no-custom-id
1459 Like create-if-interactive, but do not create an ID if there is
1460 a CUSTOM_ID property defined in the entry. This is the default.
1462 use-existing
1463 Use existing ID, do not create one.
1465 nil Never use an ID to make a link, instead link using a text search for
1466 the headline text."
1467 :group 'org-link-store
1468 :type '(choice
1469 (const :tag "Create ID to make link" t)
1470 (const :tag "Create if storing link interactively"
1471 create-if-interactive)
1472 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1473 create-if-interactive-and-no-custom-id)
1474 (const :tag "Only use existing" use-existing)
1475 (const :tag "Do not use ID to create link" nil)))
1477 (defcustom org-context-in-file-links t
1478 "Non-nil means file links from `org-store-link' contain context.
1479 A search string will be added to the file name with :: as separator and
1480 used to find the context when the link is activated by the command
1481 `org-open-at-point'. When this option is t, the entire active region
1482 will be placed in the search string of the file link. If set to a
1483 positive integer, only the first n lines of context will be stored.
1485 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1486 negates this setting for the duration of the command."
1487 :group 'org-link-store
1488 :type '(choice boolean integer))
1490 (defcustom org-keep-stored-link-after-insertion nil
1491 "Non-nil means keep link in list for entire session.
1493 The command `org-store-link' adds a link pointing to the current
1494 location to an internal list. These links accumulate during a session.
1495 The command `org-insert-link' can be used to insert links into any
1496 Org-mode file (offering completion for all stored links). When this
1497 option is nil, every link which has been inserted once using \\[org-insert-link]
1498 will be removed from the list, to make completing the unused links
1499 more efficient."
1500 :group 'org-link-store
1501 :type 'boolean)
1503 (defgroup org-link-follow nil
1504 "Options concerning following links in Org-mode."
1505 :tag "Org Follow Link"
1506 :group 'org-link)
1508 (defcustom org-link-translation-function nil
1509 "Function to translate links with different syntax to Org syntax.
1510 This can be used to translate links created for example by the Planner
1511 or emacs-wiki packages to Org syntax.
1512 The function must accept two parameters, a TYPE containing the link
1513 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1514 which is everything after the link protocol. It should return a cons
1515 with possibly modified values of type and path.
1516 Org contains a function for this, so if you set this variable to
1517 `org-translate-link-from-planner', you should be able follow many
1518 links created by planner."
1519 :group 'org-link-follow
1520 :type 'function)
1522 (defcustom org-follow-link-hook nil
1523 "Hook that is run after a link has been followed."
1524 :group 'org-link-follow
1525 :type 'hook)
1527 (defcustom org-tab-follows-link nil
1528 "Non-nil means on links TAB will follow the link.
1529 Needs to be set before org.el is loaded.
1530 This really should not be used, it does not make sense, and the
1531 implementation is bad."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-return-follows-link nil
1536 "Non-nil means on links RET will follow the link."
1537 :group 'org-link-follow
1538 :type 'boolean)
1540 (defcustom org-mouse-1-follows-link
1541 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1542 "Non-nil means mouse-1 on a link will follow the link.
1543 A longer mouse click will still set point. Does not work on XEmacs.
1544 Needs to be set before org.el is loaded."
1545 :group 'org-link-follow
1546 :type 'boolean)
1548 (defcustom org-mark-ring-length 4
1549 "Number of different positions to be recorded in the ring.
1550 Changing this requires a restart of Emacs to work correctly."
1551 :group 'org-link-follow
1552 :type 'integer)
1554 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1555 "Non-nil means internal links in Org files must exactly match a headline.
1556 When nil, the link search tries to match a phrase with all words
1557 in the search text."
1558 :group 'org-link-follow
1559 :version "24.1"
1560 :type '(choice
1561 (const :tag "Use fuzzy text search" nil)
1562 (const :tag "Match only exact headline" t)
1563 (const :tag "Match exact headline or query to create it"
1564 query-to-create)))
1566 (defcustom org-link-frame-setup
1567 '((vm . vm-visit-folder-other-frame)
1568 (vm-imap . vm-visit-imap-folder-other-frame)
1569 (gnus . org-gnus-no-new-news)
1570 (file . find-file-other-window)
1571 (wl . wl-other-frame))
1572 "Setup the frame configuration for following links.
1573 When following a link with Emacs, it may often be useful to display
1574 this link in another window or frame. This variable can be used to
1575 set this up for the different types of links.
1576 For VM, use any of
1577 `vm-visit-folder'
1578 `vm-visit-folder-other-window'
1579 `vm-visit-folder-other-frame'
1580 For Gnus, use any of
1581 `gnus'
1582 `gnus-other-frame'
1583 `org-gnus-no-new-news'
1584 For FILE, use any of
1585 `find-file'
1586 `find-file-other-window'
1587 `find-file-other-frame'
1588 For Wanderlust use any of
1589 `wl'
1590 `wl-other-frame'
1591 For the calendar, use the variable `calendar-setup'.
1592 For BBDB, it is currently only possible to display the matches in
1593 another window."
1594 :group 'org-link-follow
1595 :type '(list
1596 (cons (const vm)
1597 (choice
1598 (const vm-visit-folder)
1599 (const vm-visit-folder-other-window)
1600 (const vm-visit-folder-other-frame)))
1601 (cons (const gnus)
1602 (choice
1603 (const gnus)
1604 (const gnus-other-frame)
1605 (const org-gnus-no-new-news)))
1606 (cons (const file)
1607 (choice
1608 (const find-file)
1609 (const find-file-other-window)
1610 (const find-file-other-frame)))
1611 (cons (const wl)
1612 (choice
1613 (const wl)
1614 (const wl-other-frame)))))
1616 (defcustom org-display-internal-link-with-indirect-buffer nil
1617 "Non-nil means use indirect buffer to display infile links.
1618 Activating internal links (from one location in a file to another location
1619 in the same file) normally just jumps to the location. When the link is
1620 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1621 is displayed in
1622 another window. When this option is set, the other window actually displays
1623 an indirect buffer clone of the current buffer, to avoid any visibility
1624 changes to the current buffer."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-non-existing-files nil
1629 "Non-nil means `org-open-file' will open non-existing files.
1630 When nil, an error will be generated.
1631 This variable applies only to external applications because they
1632 might choke on non-existing files. If the link is to a file that
1633 will be opened in Emacs, the variable is ignored."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-open-directory-means-index-dot-org nil
1638 "Non-nil means a link to a directory really means to index.org.
1639 When nil, following a directory link will run dired or open a finder/explorer
1640 window on that directory."
1641 :group 'org-link-follow
1642 :type 'boolean)
1644 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1645 "Function and arguments to call for following mailto links.
1646 This is a list with the first element being a Lisp function, and the
1647 remaining elements being arguments to the function. In string arguments,
1648 %a will be replaced by the address, and %s will be replaced by the subject
1649 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1650 :group 'org-link-follow
1651 :type '(choice
1652 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1653 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1654 (const :tag "message-mail" (message-mail "%a" "%s"))
1655 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1657 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1658 "Non-nil means ask for confirmation before executing shell links.
1659 Shell links can be dangerous: just think about a link
1661 [[shell:rm -rf ~/*][Google Search]]
1663 This link would show up in your Org-mode document as \"Google Search\",
1664 but really it would remove your entire home directory.
1665 Therefore we advise against setting this variable to nil.
1666 Just change it to `y-or-n-p' if you want to confirm with a
1667 single keystroke rather than having to type \"yes\"."
1668 :group 'org-link-follow
1669 :type '(choice
1670 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1671 (const :tag "with y-or-n (faster)" y-or-n-p)
1672 (const :tag "no confirmation (dangerous)" nil)))
1673 (put 'org-confirm-shell-link-function
1674 'safe-local-variable
1675 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1677 (defcustom org-confirm-shell-link-not-regexp ""
1678 "A regexp to skip confirmation for shell links."
1679 :group 'org-link-follow
1680 :version "24.1"
1681 :type 'regexp)
1683 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1684 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1685 Elisp links can be dangerous: just think about a link
1687 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1689 This link would show up in your Org-mode document as \"Google Search\",
1690 but really it would remove your entire home directory.
1691 Therefore we advise against setting this variable to nil.
1692 Just change it to `y-or-n-p' if you want to confirm with a
1693 single keystroke rather than having to type \"yes\"."
1694 :group 'org-link-follow
1695 :type '(choice
1696 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1697 (const :tag "with y-or-n (faster)" y-or-n-p)
1698 (const :tag "no confirmation (dangerous)" nil)))
1699 (put 'org-confirm-shell-link-function
1700 'safe-local-variable
1701 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1703 (defcustom org-confirm-elisp-link-not-regexp ""
1704 "A regexp to skip confirmation for Elisp links."
1705 :group 'org-link-follow
1706 :version "24.1"
1707 :type 'regexp)
1709 (defconst org-file-apps-defaults-gnu
1710 '((remote . emacs)
1711 (system . mailcap)
1712 (t . mailcap))
1713 "Default file applications on a UNIX or GNU/Linux system.
1714 See `org-file-apps'.")
1716 (defconst org-file-apps-defaults-macosx
1717 '((remote . emacs)
1718 (t . "open %s")
1719 (system . "open %s")
1720 ("ps.gz" . "gv %s")
1721 ("eps.gz" . "gv %s")
1722 ("dvi" . "xdvi %s")
1723 ("fig" . "xfig %s"))
1724 "Default file applications on a MacOS X system.
1725 The system \"open\" is known as a default, but we use X11 applications
1726 for some files for which the OS does not have a good default.
1727 See `org-file-apps'.")
1729 (defconst org-file-apps-defaults-windowsnt
1730 (list
1731 '(remote . emacs)
1732 (cons t
1733 (list (if (featurep 'xemacs)
1734 'mswindows-shell-execute
1735 'w32-shell-execute)
1736 "open" 'file))
1737 (cons 'system
1738 (list (if (featurep 'xemacs)
1739 'mswindows-shell-execute
1740 'w32-shell-execute)
1741 "open" 'file)))
1742 "Default file applications on a Windows NT system.
1743 The system \"open\" is used for most files.
1744 See `org-file-apps'.")
1746 (defcustom org-file-apps
1748 (auto-mode . emacs)
1749 ("\\.mm\\'" . default)
1750 ("\\.x?html?\\'" . default)
1751 ("\\.pdf\\'" . default)
1753 "External applications for opening `file:path' items in a document.
1754 Org-mode uses system defaults for different file types, but
1755 you can use this variable to set the application for a given file
1756 extension. The entries in this list are cons cells where the car identifies
1757 files and the cdr the corresponding command. Possible values for the
1758 file identifier are
1759 \"string\" A string as a file identifier can be interpreted in different
1760 ways, depending on its contents:
1762 - Alphanumeric characters only:
1763 Match links with this file extension.
1764 Example: (\"pdf\" . \"evince %s\")
1765 to open PDFs with evince.
1767 - Regular expression: Match links where the
1768 filename matches the regexp. If you want to
1769 use groups here, use shy groups.
1771 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1772 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1773 to open *.html and *.xhtml with firefox.
1775 - Regular expression which contains (non-shy) groups:
1776 Match links where the whole link, including \"::\", and
1777 anything after that, matches the regexp.
1778 In a custom command string, %1, %2, etc. are replaced with
1779 the parts of the link that were matched by the groups.
1780 For backwards compatibility, if a command string is given
1781 that does not use any of the group matches, this case is
1782 handled identically to the second one (i.e. match against
1783 file name only).
1784 In a custom lisp form, you can access the group matches with
1785 (match-string n link).
1787 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1788 to open [[file:document.pdf::5]] with evince at page 5.
1790 `directory' Matches a directory
1791 `remote' Matches a remote file, accessible through tramp or efs.
1792 Remote files most likely should be visited through Emacs
1793 because external applications cannot handle such paths.
1794 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1795 so all files Emacs knows how to handle. Using this with
1796 command `emacs' will open most files in Emacs. Beware that this
1797 will also open html files inside Emacs, unless you add
1798 (\"html\" . default) to the list as well.
1799 t Default for files not matched by any of the other options.
1800 `system' The system command to open files, like `open' on Windows
1801 and Mac OS X, and mailcap under GNU/Linux. This is the command
1802 that will be selected if you call `C-c C-o' with a double
1803 \\[universal-argument] \\[universal-argument] prefix.
1805 Possible values for the command are:
1806 `emacs' The file will be visited by the current Emacs process.
1807 `default' Use the default application for this file type, which is the
1808 association for t in the list, most likely in the system-specific
1809 part.
1810 This can be used to overrule an unwanted setting in the
1811 system-specific variable.
1812 `system' Use the system command for opening files, like \"open\".
1813 This command is specified by the entry whose car is `system'.
1814 Most likely, the system-specific version of this variable
1815 does define this command, but you can overrule/replace it
1816 here.
1817 string A command to be executed by a shell; %s will be replaced
1818 by the path to the file.
1819 sexp A Lisp form which will be evaluated. The file path will
1820 be available in the Lisp variable `file'.
1821 For more examples, see the system specific constants
1822 `org-file-apps-defaults-macosx'
1823 `org-file-apps-defaults-windowsnt'
1824 `org-file-apps-defaults-gnu'."
1825 :group 'org-link-follow
1826 :type '(repeat
1827 (cons (choice :value ""
1828 (string :tag "Extension")
1829 (const :tag "System command to open files" system)
1830 (const :tag "Default for unrecognized files" t)
1831 (const :tag "Remote file" remote)
1832 (const :tag "Links to a directory" directory)
1833 (const :tag "Any files that have Emacs modes"
1834 auto-mode))
1835 (choice :value ""
1836 (const :tag "Visit with Emacs" emacs)
1837 (const :tag "Use default" default)
1838 (const :tag "Use the system command" system)
1839 (string :tag "Command")
1840 (sexp :tag "Lisp form")))))
1844 (defgroup org-refile nil
1845 "Options concerning refiling entries in Org-mode."
1846 :tag "Org Refile"
1847 :group 'org)
1849 (defcustom org-directory "~/org"
1850 "Directory with org files.
1851 This is just a default location to look for Org files. There is no need
1852 at all to put your files into this directory. It is only used in the
1853 following situations:
1855 1. When a remember template specifies a target file that is not an
1856 absolute path. The path will then be interpreted relative to
1857 `org-directory'
1858 2. When a remember note is filed away in an interactive way (when exiting the
1859 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1860 with `org-directory' as the default path."
1861 :group 'org-refile
1862 :group 'org-remember
1863 :type 'directory)
1865 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1866 "Default target for storing notes.
1867 Used as a fall back file for org-remember.el and org-capture.el, for
1868 templates that do not specify a target file."
1869 :group 'org-refile
1870 :group 'org-remember
1871 :type '(choice
1872 (const :tag "Default from remember-data-file" nil)
1873 file))
1875 (defcustom org-goto-interface 'outline
1876 "The default interface to be used for `org-goto'.
1877 Allowed values are:
1878 outline The interface shows an outline of the relevant file
1879 and the correct heading is found by moving through
1880 the outline or by searching with incremental search.
1881 outline-path-completion Headlines in the current buffer are offered via
1882 completion. This is the interface also used by
1883 the refile command."
1884 :group 'org-refile
1885 :type '(choice
1886 (const :tag "Outline" outline)
1887 (const :tag "Outline-path-completion" outline-path-completion)))
1889 (defcustom org-goto-max-level 5
1890 "Maximum target level when running `org-goto' with refile interface."
1891 :group 'org-refile
1892 :type 'integer)
1894 (defcustom org-reverse-note-order nil
1895 "Non-nil means store new notes at the beginning of a file or entry.
1896 When nil, new notes will be filed to the end of a file or entry.
1897 This can also be a list with cons cells of regular expressions that
1898 are matched against file names, and values."
1899 :group 'org-remember
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Reverse always" t)
1903 (const :tag "Reverse never" nil)
1904 (repeat :tag "By file name regexp"
1905 (cons regexp boolean))))
1907 (defcustom org-log-refile nil
1908 "Information to record when a task is refiled.
1910 Possible values are:
1912 nil Don't add anything
1913 time Add a time stamp to the task
1914 note Prompt for a note and add it with template `org-log-note-headings'
1916 This option can also be set with on a per-file-basis with
1918 #+STARTUP: nologrefile
1919 #+STARTUP: logrefile
1920 #+STARTUP: lognoterefile
1922 You can have local logging settings for a subtree by setting the LOGGING
1923 property to one or more of these keywords.
1925 When bulk-refiling from the agenda, the value `note' is forbidden and
1926 will temporarily be changed to `time'."
1927 :group 'org-refile
1928 :group 'org-progress
1929 :version "24.1"
1930 :type '(choice
1931 (const :tag "No logging" nil)
1932 (const :tag "Record timestamp" time)
1933 (const :tag "Record timestamp with note." note)))
1935 (defcustom org-refile-targets nil
1936 "Targets for refiling entries with \\[org-refile].
1937 This is a list of cons cells. Each cell contains:
1938 - a specification of the files to be considered, either a list of files,
1939 or a symbol whose function or variable value will be used to retrieve
1940 a file name or a list of file names. If you use `org-agenda-files' for
1941 that, all agenda files will be scanned for targets. Nil means consider
1942 headings in the current buffer.
1943 - A specification of how to find candidate refile targets. This may be
1944 any of:
1945 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1946 This tag has to be present in all target headlines, inheritance will
1947 not be considered.
1948 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1949 todo keyword.
1950 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1951 headlines that are refiling targets.
1952 - a cons cell (:level . N). Any headline of level N is considered a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1955 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1956 Note that, when `org-odd-levels-only' is set, level corresponds to
1957 order in hierarchy, not to the number of stars.
1959 Each element of this list generates a set of possible targets.
1960 The union of these sets is presented (with completion) to
1961 the user by `org-refile'.
1963 You can set the variable `org-refile-target-verify-function' to a function
1964 to verify each headline found by the simple criteria above.
1966 When this variable is nil, all top-level headlines in the current buffer
1967 are used, equivalent to the value `((nil . (:level . 1))'."
1968 :group 'org-refile
1969 :type '(repeat
1970 (cons
1971 (choice :value org-agenda-files
1972 (const :tag "All agenda files" org-agenda-files)
1973 (const :tag "Current buffer" nil)
1974 (function) (variable) (file))
1975 (choice :tag "Identify target headline by"
1976 (cons :tag "Specific tag" (const :value :tag) (string))
1977 (cons :tag "TODO keyword" (const :value :todo) (string))
1978 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1979 (cons :tag "Level number" (const :value :level) (integer))
1980 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1982 (defcustom org-refile-target-verify-function nil
1983 "Function to verify if the headline at point should be a refile target.
1984 The function will be called without arguments, with point at the
1985 beginning of the headline. It should return t and leave point
1986 where it is if the headline is a valid target for refiling.
1988 If the target should not be selected, the function must return nil.
1989 In addition to this, it may move point to a place from where the search
1990 should be continued. For example, the function may decide that the entire
1991 subtree of the current entry should be excluded and move point to the end
1992 of the subtree."
1993 :group 'org-refile
1994 :type 'function)
1996 (defcustom org-refile-use-cache nil
1997 "Non-nil means cache refile targets to speed up the process.
1998 The cache for a particular file will be updated automatically when
1999 the buffer has been killed, or when any of the marker used for flagging
2000 refile targets no longer points at a live buffer.
2001 If you have added new entries to a buffer that might themselves be targets,
2002 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2003 find that easier, `C-u C-u C-u C-c C-w'."
2004 :group 'org-refile
2005 :version "24.1"
2006 :type 'boolean)
2008 (defcustom org-refile-use-outline-path nil
2009 "Non-nil means provide refile targets as paths.
2010 So a level 3 headline will be available as level1/level2/level3.
2012 When the value is `file', also include the file name (without directory)
2013 into the path. In this case, you can also stop the completion after
2014 the file name, to get entries inserted as top level in the file.
2016 When `full-file-path', include the full file path."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Not" nil)
2020 (const :tag "Yes" t)
2021 (const :tag "Start with file name" file)
2022 (const :tag "Start with full file path" full-file-path)))
2024 (defcustom org-outline-path-complete-in-steps t
2025 "Non-nil means complete the outline path in hierarchical steps.
2026 When Org-mode uses the refile interface to select an outline path
2027 \(see variable `org-refile-use-outline-path'), the completion of
2028 the path can be done is a single go, or if can be done in steps down
2029 the headline hierarchy. Going in steps is probably the best if you
2030 do not use a special completion package like `ido' or `icicles'.
2031 However, when using these packages, going in one step can be very
2032 fast, while still showing the whole path to the entry."
2033 :group 'org-refile
2034 :type 'boolean)
2036 (defcustom org-refile-allow-creating-parent-nodes nil
2037 "Non-nil means allow to create new nodes as refile targets.
2038 New nodes are then created by adding \"/new node name\" to the completion
2039 of an existing node. When the value of this variable is `confirm',
2040 new node creation must be confirmed by the user (recommended)
2041 When nil, the completion must match an existing entry.
2043 Note that, if the new heading is not seen by the criteria
2044 listed in `org-refile-targets', multiple instances of the same
2045 heading would be created by trying again to file under the new
2046 heading."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Never" nil)
2050 (const :tag "Always" t)
2051 (const :tag "Prompt for confirmation" confirm)))
2053 (defcustom org-refile-active-region-within-subtree nil
2054 "Non-nil means also refile active region within a subtree.
2056 By default `org-refile' doesn't allow refiling regions if they
2057 don't contain a set of subtrees, but it might be convenient to
2058 do so sometimes: in that case, the first line of the region is
2059 converted to a headline before refiling."
2060 :group 'org-refile
2061 :version "24.1"
2062 :type 'boolean)
2064 (defgroup org-todo nil
2065 "Options concerning TODO items in Org-mode."
2066 :tag "Org TODO"
2067 :group 'org)
2069 (defgroup org-progress nil
2070 "Options concerning Progress logging in Org-mode."
2071 :tag "Org Progress"
2072 :group 'org-time)
2074 (defvar org-todo-interpretation-widgets
2075 '((:tag "Sequence (cycling hits every state)" sequence)
2076 (:tag "Type (cycling directly to DONE)" type))
2077 "The available interpretation symbols for customizing `org-todo-keywords'.
2078 Interested libraries should add to this list.")
2080 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2081 "List of TODO entry keyword sequences and their interpretation.
2082 \\<org-mode-map>This is a list of sequences.
2084 Each sequence starts with a symbol, either `sequence' or `type',
2085 indicating if the keywords should be interpreted as a sequence of
2086 action steps, or as different types of TODO items. The first
2087 keywords are states requiring action - these states will select a headline
2088 for inclusion into the global TODO list Org-mode produces. If one of
2089 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2090 signify that no further action is necessary. If \"|\" is not found,
2091 the last keyword is treated as the only DONE state of the sequence.
2093 The command \\[org-todo] cycles an entry through these states, and one
2094 additional state where no keyword is present. For details about this
2095 cycling, see the manual.
2097 TODO keywords and interpretation can also be set on a per-file basis with
2098 the special #+SEQ_TODO and #+TYP_TODO lines.
2100 Each keyword can optionally specify a character for fast state selection
2101 \(in combination with the variable `org-use-fast-todo-selection')
2102 and specifiers for state change logging, using the same syntax
2103 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2104 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2105 indicates to record a time stamp each time this state is selected.
2107 Each keyword may also specify if a timestamp or a note should be
2108 recorded when entering or leaving the state, by adding additional
2109 characters in the parenthesis after the keyword. This looks like this:
2110 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2111 record only the time of the state change. With X and Y being either
2112 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2113 Y when leaving the state if and only if the *target* state does not
2114 define X. You may omit any of the fast-selection key or X or /Y,
2115 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2117 For backward compatibility, this variable may also be just a list
2118 of keywords - in this case the interpretation (sequence or type) will be
2119 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2120 :group 'org-todo
2121 :group 'org-keywords
2122 :type '(choice
2123 (repeat :tag "Old syntax, just keywords"
2124 (string :tag "Keyword"))
2125 (repeat :tag "New syntax"
2126 (cons
2127 (choice
2128 :tag "Interpretation"
2129 ;;Quick and dirty way to see
2130 ;;`org-todo-interpretations'. This takes the
2131 ;;place of item arguments
2132 :convert-widget
2133 (lambda (widget)
2134 (widget-put widget
2135 :args (mapcar
2136 #'(lambda (x)
2137 (widget-convert
2138 (cons 'const x)))
2139 org-todo-interpretation-widgets))
2140 widget))
2141 (repeat
2142 (string :tag "Keyword"))))))
2144 (defvar org-todo-keywords-1 nil
2145 "All TODO and DONE keywords active in a buffer.")
2146 (make-variable-buffer-local 'org-todo-keywords-1)
2147 (defvar org-todo-keywords-for-agenda nil)
2148 (defvar org-done-keywords-for-agenda nil)
2149 (defvar org-drawers-for-agenda nil)
2150 (defvar org-todo-keyword-alist-for-agenda nil)
2151 (defvar org-tag-alist-for-agenda nil)
2152 (defvar org-agenda-contributing-files nil)
2153 (defvar org-not-done-keywords nil)
2154 (make-variable-buffer-local 'org-not-done-keywords)
2155 (defvar org-done-keywords nil)
2156 (make-variable-buffer-local 'org-done-keywords)
2157 (defvar org-todo-heads nil)
2158 (make-variable-buffer-local 'org-todo-heads)
2159 (defvar org-todo-sets nil)
2160 (make-variable-buffer-local 'org-todo-sets)
2161 (defvar org-todo-log-states nil)
2162 (make-variable-buffer-local 'org-todo-log-states)
2163 (defvar org-todo-kwd-alist nil)
2164 (make-variable-buffer-local 'org-todo-kwd-alist)
2165 (defvar org-todo-key-alist nil)
2166 (make-variable-buffer-local 'org-todo-key-alist)
2167 (defvar org-todo-key-trigger nil)
2168 (make-variable-buffer-local 'org-todo-key-trigger)
2170 (defcustom org-todo-interpretation 'sequence
2171 "Controls how TODO keywords are interpreted.
2172 This variable is in principle obsolete and is only used for
2173 backward compatibility, if the interpretation of todo keywords is
2174 not given already in `org-todo-keywords'. See that variable for
2175 more information."
2176 :group 'org-todo
2177 :group 'org-keywords
2178 :type '(choice (const sequence)
2179 (const type)))
2181 (defcustom org-use-fast-todo-selection t
2182 "Non-nil means use the fast todo selection scheme with C-c C-t.
2183 This variable describes if and under what circumstances the cycling
2184 mechanism for TODO keywords will be replaced by a single-key, direct
2185 selection scheme.
2187 When nil, fast selection is never used.
2189 When the symbol `prefix', it will be used when `org-todo' is called with
2190 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2191 in an agenda buffer.
2193 When t, fast selection is used by default. In this case, the prefix
2194 argument forces cycling instead.
2196 In all cases, the special interface is only used if access keys have actually
2197 been assigned by the user, i.e. if keywords in the configuration are followed
2198 by a letter in parenthesis, like TODO(t)."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Never" nil)
2202 (const :tag "By default" t)
2203 (const :tag "Only with C-u C-c C-t" prefix)))
2205 (defcustom org-provide-todo-statistics t
2206 "Non-nil means update todo statistics after insert and toggle.
2207 ALL-HEADLINES means update todo statistics by including headlines
2208 with no TODO keyword as well, counting them as not done.
2209 A list of TODO keywords means the same, but skip keywords that are
2210 not in this list.
2212 When this is set, todo statistics is updated in the parent of the
2213 current entry each time a todo state is changed."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Yes, only for TODO entries" t)
2217 (const :tag "Yes, including all entries" 'all-headlines)
2218 (repeat :tag "Yes, for TODOs in this list"
2219 (string :tag "TODO keyword"))
2220 (other :tag "No TODO statistics" nil)))
2222 (defcustom org-hierarchical-todo-statistics t
2223 "Non-nil means TODO statistics covers just direct children.
2224 When nil, all entries in the subtree are considered.
2225 This has only an effect if `org-provide-todo-statistics' is set.
2226 To set this to nil for only a single subtree, use a COOKIE_DATA
2227 property and include the word \"recursive\" into the value."
2228 :group 'org-todo
2229 :type 'boolean)
2231 (defcustom org-after-todo-state-change-hook nil
2232 "Hook which is run after the state of a TODO item was changed.
2233 The new state (a string with a TODO keyword, or nil) is available in the
2234 Lisp variable `state'."
2235 :group 'org-todo
2236 :type 'hook)
2238 (defvar org-blocker-hook nil
2239 "Hook for functions that are allowed to block a state change.
2241 Each function gets as its single argument a property list, see
2242 `org-trigger-hook' for more information about this list.
2244 If any of the functions in this hook returns nil, the state change
2245 is blocked.")
2247 (defvar org-trigger-hook nil
2248 "Hook for functions that are triggered by a state change.
2250 Each function gets as its single argument a property list with at least
2251 the following elements:
2253 (:type type-of-change :position pos-at-entry-start
2254 :from old-state :to new-state)
2256 Depending on the type, more properties may be present.
2258 This mechanism is currently implemented for:
2260 TODO state changes
2261 ------------------
2262 :type todo-state-change
2263 :from previous state (keyword as a string), or nil, or a symbol
2264 'todo' or 'done', to indicate the general type of state.
2265 :to new state, like in :from")
2267 (defcustom org-enforce-todo-dependencies nil
2268 "Non-nil means undone TODO entries will block switching the parent to DONE.
2269 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2270 be blocked if any prior sibling is not yet done.
2271 Finally, if the parent is blocked because of ordered siblings of its own,
2272 the child will also be blocked.
2273 This variable needs to be set before org.el is loaded, and you need to
2274 restart Emacs after a change to make the change effective. The only way
2275 to change is while Emacs is running is through the customize interface."
2276 :set (lambda (var val)
2277 (set var val)
2278 (if val
2279 (add-hook 'org-blocker-hook
2280 'org-block-todo-from-children-or-siblings-or-parent)
2281 (remove-hook 'org-blocker-hook
2282 'org-block-todo-from-children-or-siblings-or-parent)))
2283 :group 'org-todo
2284 :type 'boolean)
2286 (defcustom org-enforce-todo-checkbox-dependencies nil
2287 "Non-nil means unchecked boxes will block switching the parent to DONE.
2288 When this is nil, checkboxes have no influence on switching TODO states.
2289 When non-nil, you first need to check off all check boxes before the TODO
2290 entry can be switched to DONE.
2291 This variable needs to be set before org.el is loaded, and you need to
2292 restart Emacs after a change to make the change effective. The only way
2293 to change is while Emacs is running is through the customize interface."
2294 :set (lambda (var val)
2295 (set var val)
2296 (if val
2297 (add-hook 'org-blocker-hook
2298 'org-block-todo-from-checkboxes)
2299 (remove-hook 'org-blocker-hook
2300 'org-block-todo-from-checkboxes)))
2301 :group 'org-todo
2302 :type 'boolean)
2304 (defcustom org-treat-insert-todo-heading-as-state-change nil
2305 "Non-nil means inserting a TODO heading is treated as state change.
2306 So when the command \\[org-insert-todo-heading] is used, state change
2307 logging will apply if appropriate. When nil, the new TODO item will
2308 be inserted directly, and no logging will take place."
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2313 "Non-nil means switching TODO states with S-cursor counts as state change.
2314 This is the default behavior. However, setting this to nil allows a
2315 convenient way to select a TODO state and bypass any logging associated
2316 with that."
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-todo-state-tags-triggers nil
2321 "Tag changes that should be triggered by TODO state changes.
2322 This is a list. Each entry is
2324 (state-change (tag . flag) .......)
2326 State-change can be a string with a state, and empty string to indicate the
2327 state that has no TODO keyword, or it can be one of the symbols `todo'
2328 or `done', meaning any not-done or done state, respectively."
2329 :group 'org-todo
2330 :group 'org-tags
2331 :type '(repeat
2332 (cons (choice :tag "When changing to"
2333 (const :tag "Not-done state" todo)
2334 (const :tag "Done state" done)
2335 (string :tag "State"))
2336 (repeat
2337 (cons :tag "Tag action"
2338 (string :tag "Tag")
2339 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2341 (defcustom org-log-done nil
2342 "Information to record when a task moves to the DONE state.
2344 Possible values are:
2346 nil Don't add anything, just change the keyword
2347 time Add a time stamp to the task
2348 note Prompt for a note and add it with template `org-log-note-headings'
2350 This option can also be set with on a per-file-basis with
2352 #+STARTUP: nologdone
2353 #+STARTUP: logdone
2354 #+STARTUP: lognotedone
2356 You can have local logging settings for a subtree by setting the LOGGING
2357 property to one or more of these keywords."
2358 :group 'org-todo
2359 :group 'org-progress
2360 :type '(choice
2361 (const :tag "No logging" nil)
2362 (const :tag "Record CLOSED timestamp" time)
2363 (const :tag "Record CLOSED timestamp with note." note)))
2365 ;; Normalize old uses of org-log-done.
2366 (cond
2367 ((eq org-log-done t) (setq org-log-done 'time))
2368 ((and (listp org-log-done) (memq 'done org-log-done))
2369 (setq org-log-done 'note)))
2371 (defcustom org-log-reschedule nil
2372 "Information to record when the scheduling date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologreschedule
2383 #+STARTUP: logreschedule
2384 #+STARTUP: lognotereschedule"
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "No logging" nil)
2389 (const :tag "Record timestamp" time)
2390 (const :tag "Record timestamp with note." note)))
2392 (defcustom org-log-redeadline nil
2393 "Information to record when the deadline date of a tasks is modified.
2395 Possible values are:
2397 nil Don't add anything, just change the date
2398 time Add a time stamp to the task
2399 note Prompt for a note and add it with template `org-log-note-headings'
2401 This option can also be set with on a per-file-basis with
2403 #+STARTUP: nologredeadline
2404 #+STARTUP: logredeadline
2405 #+STARTUP: lognoteredeadline
2407 You can have local logging settings for a subtree by setting the LOGGING
2408 property to one or more of these keywords."
2409 :group 'org-todo
2410 :group 'org-progress
2411 :type '(choice
2412 (const :tag "No logging" nil)
2413 (const :tag "Record timestamp" time)
2414 (const :tag "Record timestamp with note." note)))
2416 (defcustom org-log-note-clock-out nil
2417 "Non-nil means record a note when clocking out of an item.
2418 This can also be configured on a per-file basis by adding one of
2419 the following lines anywhere in the buffer:
2421 #+STARTUP: lognoteclock-out
2422 #+STARTUP: nolognoteclock-out"
2423 :group 'org-todo
2424 :group 'org-progress
2425 :type 'boolean)
2427 (defcustom org-log-done-with-time t
2428 "Non-nil means the CLOSED time stamp will contain date and time.
2429 When nil, only the date will be recorded."
2430 :group 'org-progress
2431 :type 'boolean)
2433 (defcustom org-log-note-headings
2434 '((done . "CLOSING NOTE %t")
2435 (state . "State %-12s from %-12S %t")
2436 (note . "Note taken on %t")
2437 (reschedule . "Rescheduled from %S on %t")
2438 (delschedule . "Not scheduled, was %S on %t")
2439 (redeadline . "New deadline from %S on %t")
2440 (deldeadline . "Removed deadline, was %S on %t")
2441 (refile . "Refiled on %t")
2442 (clock-out . ""))
2443 "Headings for notes added to entries.
2444 The value is an alist, with the car being a symbol indicating the note
2445 context, and the cdr is the heading to be used. The heading may also be the
2446 empty string.
2447 %t in the heading will be replaced by a time stamp.
2448 %T will be an active time stamp instead the default inactive one
2449 %d will be replaced by a short-format time stamp.
2450 %D will be replaced by an active short-format time stamp.
2451 %s will be replaced by the new TODO state, in double quotes.
2452 %S will be replaced by the old TODO state, in double quotes.
2453 %u will be replaced by the user name.
2454 %U will be replaced by the full user name.
2456 In fact, it is not a good idea to change the `state' entry, because
2457 agenda log mode depends on the format of these entries."
2458 :group 'org-todo
2459 :group 'org-progress
2460 :type '(list :greedy t
2461 (cons (const :tag "Heading when closing an item" done) string)
2462 (cons (const :tag
2463 "Heading when changing todo state (todo sequence only)"
2464 state) string)
2465 (cons (const :tag "Heading when just taking a note" note) string)
2466 (cons (const :tag "Heading when clocking out" clock-out) string)
2467 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2468 (cons (const :tag "Heading when rescheduling" reschedule) string)
2469 (cons (const :tag "Heading when changing deadline" redeadline) string)
2470 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2471 (cons (const :tag "Heading when refiling" refile) string)))
2473 (unless (assq 'note org-log-note-headings)
2474 (push '(note . "%t") org-log-note-headings))
2476 (defcustom org-log-into-drawer nil
2477 "Non-nil means insert state change notes and time stamps into a drawer.
2478 When nil, state changes notes will be inserted after the headline and
2479 any scheduling and clock lines, but not inside a drawer.
2481 The value of this variable should be the name of the drawer to use.
2482 LOGBOOK is proposed as the default drawer for this purpose, you can
2483 also set this to a string to define the drawer of your choice.
2485 A value of t is also allowed, representing \"LOGBOOK\".
2487 If this variable is set, `org-log-state-notes-insert-after-drawers'
2488 will be ignored.
2490 You can set the property LOG_INTO_DRAWER to overrule this setting for
2491 a subtree."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type '(choice
2495 (const :tag "Not into a drawer" nil)
2496 (const :tag "LOGBOOK" t)
2497 (string :tag "Other")))
2499 (if (fboundp 'defvaralias)
2500 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2502 (defun org-log-into-drawer ()
2503 "Return the value of `org-log-into-drawer', but let properties overrule.
2504 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2505 used instead of the default value."
2506 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2507 (cond
2508 ((or (not p) (equal p "nil")) org-log-into-drawer)
2509 ((equal p "t") "LOGBOOK")
2510 (t p))))
2512 (defcustom org-log-state-notes-insert-after-drawers nil
2513 "Non-nil means insert state change notes after any drawers in entry.
2514 Only the drawers that *immediately* follow the headline and the
2515 deadline/scheduled line are skipped.
2516 When nil, insert notes right after the heading and perhaps the line
2517 with deadline/scheduling if present.
2519 This variable will have no effect if `org-log-into-drawer' is
2520 set."
2521 :group 'org-todo
2522 :group 'org-progress
2523 :type 'boolean)
2525 (defcustom org-log-states-order-reversed t
2526 "Non-nil means the latest state note will be directly after heading.
2527 When nil, the state change notes will be ordered according to time."
2528 :group 'org-todo
2529 :group 'org-progress
2530 :type 'boolean)
2532 (defcustom org-todo-repeat-to-state nil
2533 "The TODO state to which a repeater should return the repeating task.
2534 By default this is the first task in a TODO sequence, or the previous state
2535 in a TODO_TYP set. But you can specify another task here.
2536 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2537 :group 'org-todo
2538 :version "24.1"
2539 :type '(choice (const :tag "Head of sequence" nil)
2540 (string :tag "Specific state")))
2542 (defcustom org-log-repeat 'time
2543 "Non-nil means record moving through the DONE state when triggering repeat.
2544 An auto-repeating task is immediately switched back to TODO when
2545 marked DONE. If you are not logging state changes (by adding \"@\"
2546 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2547 record a closing note, there will be no record of the task moving
2548 through DONE. This variable forces taking a note anyway.
2550 nil Don't force a record
2551 time Record a time stamp
2552 note Record a note
2554 This option can also be set with on a per-file-basis with
2556 #+STARTUP: logrepeat
2557 #+STARTUP: lognoterepeat
2558 #+STARTUP: nologrepeat
2560 You can have local logging settings for a subtree by setting the LOGGING
2561 property to one or more of these keywords."
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "Don't force a record" nil)
2566 (const :tag "Force recording the DONE state" time)
2567 (const :tag "Force recording a note with the DONE state" note)))
2570 (defgroup org-priorities nil
2571 "Priorities in Org-mode."
2572 :tag "Org Priorities"
2573 :group 'org-todo)
2575 (defcustom org-enable-priority-commands t
2576 "Non-nil means priority commands are active.
2577 When nil, these commands will be disabled, so that you never accidentally
2578 set a priority."
2579 :group 'org-priorities
2580 :type 'boolean)
2582 (defcustom org-highest-priority ?A
2583 "The highest priority of TODO items. A character like ?A, ?B etc.
2584 Must have a smaller ASCII number than `org-lowest-priority'."
2585 :group 'org-priorities
2586 :type 'character)
2588 (defcustom org-lowest-priority ?C
2589 "The lowest priority of TODO items. A character like ?A, ?B etc.
2590 Must have a larger ASCII number than `org-highest-priority'."
2591 :group 'org-priorities
2592 :type 'character)
2594 (defcustom org-default-priority ?B
2595 "The default priority of TODO items.
2596 This is the priority an item gets if no explicit priority is given.
2597 When starting to cycle on an empty priority the first step in the cycle
2598 depends on `org-priority-start-cycle-with-default'. The resulting first
2599 step priority must not exceed the range from `org-highest-priority' to
2600 `org-lowest-priority' which means that `org-default-priority' has to be
2601 in this range exclusive or inclusive the range boundaries. Else the
2602 first step refuses to set the default and the second will fall back
2603 to (depending on the command used) the highest or lowest priority."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-priority-start-cycle-with-default t
2608 "Non-nil means start with default priority when starting to cycle.
2609 When this is nil, the first step in the cycle will be (depending on the
2610 command used) one higher or lower than the default priority.
2611 See also `org-default-priority'."
2612 :group 'org-priorities
2613 :type 'boolean)
2615 (defcustom org-get-priority-function nil
2616 "Function to extract the priority from a string.
2617 The string is normally the headline. If this is nil Org computes the
2618 priority from the priority cookie like [#A] in the headline. It returns
2619 an integer, increasing by 1000 for each priority level.
2620 The user can set a different function here, which should take a string
2621 as an argument and return the numeric priority."
2622 :group 'org-priorities
2623 :version "24.1"
2624 :type 'function)
2626 (defgroup org-time nil
2627 "Options concerning time stamps and deadlines in Org-mode."
2628 :tag "Org Time"
2629 :group 'org)
2631 (defcustom org-insert-labeled-timestamps-at-point nil
2632 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2633 When nil, these labeled time stamps are forces into the second line of an
2634 entry, just after the headline. When scheduling from the global TODO list,
2635 the time stamp will always be forced into the second line."
2636 :group 'org-time
2637 :type 'boolean)
2639 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2640 "Formats for `format-time-string' which are used for time stamps.
2641 It is not recommended to change this constant.")
2643 (defcustom org-time-stamp-rounding-minutes '(0 5)
2644 "Number of minutes to round time stamps to.
2645 These are two values, the first applies when first creating a time stamp.
2646 The second applies when changing it with the commands `S-up' and `S-down'.
2647 When changing the time stamp, this means that it will change in steps
2648 of N minutes, as given by the second value.
2650 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2651 numbers should be factors of 60, so for example 5, 10, 15.
2653 When this is larger than 1, you can still force an exact time stamp by using
2654 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2655 and by using a prefix arg to `S-up/down' to specify the exact number
2656 of minutes to shift."
2657 :group 'org-time
2658 :get #'(lambda (var) ; Make sure both elements are there
2659 (if (integerp (default-value var))
2660 (list (default-value var) 5)
2661 (default-value var)))
2662 :type '(list
2663 (integer :tag "when inserting times")
2664 (integer :tag "when modifying times")))
2666 ;; Normalize old customizations of this variable.
2667 (when (integerp org-time-stamp-rounding-minutes)
2668 (setq org-time-stamp-rounding-minutes
2669 (list org-time-stamp-rounding-minutes
2670 org-time-stamp-rounding-minutes)))
2672 (defcustom org-display-custom-times nil
2673 "Non-nil means overlay custom formats over all time stamps.
2674 The formats are defined through the variable `org-time-stamp-custom-formats'.
2675 To turn this on on a per-file basis, insert anywhere in the file:
2676 #+STARTUP: customtime"
2677 :group 'org-time
2678 :set 'set-default
2679 :type 'sexp)
2680 (make-variable-buffer-local 'org-display-custom-times)
2682 (defcustom org-time-stamp-custom-formats
2683 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2684 "Custom formats for time stamps. See `format-time-string' for the syntax.
2685 These are overlaid over the default ISO format if the variable
2686 `org-display-custom-times' is set. Time like %H:%M should be at the
2687 end of the second format. The custom formats are also honored by export
2688 commands, if custom time display is turned on at the time of export."
2689 :group 'org-time
2690 :type 'sexp)
2692 (defun org-time-stamp-format (&optional long inactive)
2693 "Get the right format for a time string."
2694 (let ((f (if long (cdr org-time-stamp-formats)
2695 (car org-time-stamp-formats))))
2696 (if inactive
2697 (concat "[" (substring f 1 -1) "]")
2698 f)))
2700 (defcustom org-time-clocksum-format "%d:%02d"
2701 "The format string used when creating CLOCKSUM lines.
2702 This is also used when org-mode generates a time duration."
2703 :group 'org-time
2704 :type 'string)
2706 (defcustom org-time-clocksum-use-fractional nil
2707 "If non-nil, \\[org-clock-display] uses fractional times.
2708 org-mode generates a time duration."
2709 :group 'org-time
2710 :type 'boolean)
2712 (defcustom org-time-clocksum-fractional-format "%.2f"
2713 "The format string used when creating CLOCKSUM lines, or when
2714 org-mode generates a time duration."
2715 :group 'org-time
2716 :type 'string)
2718 (defcustom org-deadline-warning-days 14
2719 "No. of days before expiration during which a deadline becomes active.
2720 This variable governs the display in sparse trees and in the agenda.
2721 When 0 or negative, it means use this number (the absolute value of it)
2722 even if a deadline has a different individual lead time specified.
2724 Custom commands can set this variable in the options section."
2725 :group 'org-time
2726 :group 'org-agenda-daily/weekly
2727 :type 'integer)
2729 (defcustom org-read-date-prefer-future t
2730 "Non-nil means assume future for incomplete date input from user.
2731 This affects the following situations:
2732 1. The user gives a month but not a year.
2733 For example, if it is April and you enter \"feb 2\", this will be read
2734 as Feb 2, *next* year. \"May 5\", however, will be this year.
2735 2. The user gives a day, but no month.
2736 For example, if today is the 15th, and you enter \"3\", Org-mode will
2737 read this as the third of *next* month. However, if you enter \"17\",
2738 it will be considered as *this* month.
2740 If you set this variable to the symbol `time', then also the following
2741 will work:
2743 3. If the user gives a time, but no day. If the time is before now,
2744 to will be interpreted as tomorrow.
2746 Currently none of this works for ISO week specifications.
2748 When this option is nil, the current day, month and year will always be
2749 used as defaults.
2751 See also `org-agenda-jump-prefer-future'."
2752 :group 'org-time
2753 :type '(choice
2754 (const :tag "Never" nil)
2755 (const :tag "Check month and day" t)
2756 (const :tag "Check month, day, and time" time)))
2758 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2759 "Should the agenda jump command prefer the future for incomplete dates?
2760 The default is to do the same as configured in `org-read-date-prefer-future'.
2761 But you can also set a deviating value here.
2762 This may t or nil, or the symbol `org-read-date-prefer-future'."
2763 :group 'org-agenda
2764 :group 'org-time
2765 :version "24.1"
2766 :type '(choice
2767 (const :tag "Use org-read-date-prefer-future"
2768 org-read-date-prefer-future)
2769 (const :tag "Never" nil)
2770 (const :tag "Always" t)))
2772 (defcustom org-read-date-force-compatible-dates t
2773 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2775 Depending on the system Emacs is running on, certain dates cannot
2776 be represented with the type used internally to represent time.
2777 Dates between 1970-1-1 and 2038-1-1 can always be represented
2778 correctly. Some systems allow for earlier dates, some for later,
2779 some for both. One way to find out it to insert any date into an
2780 Org buffer, putting the cursor on the year and hitting S-up and
2781 S-down to test the range.
2783 When this variable is set to t, the date/time prompt will not let
2784 you specify dates outside the 1970-2037 range, so it is certain that
2785 these dates will work in whatever version of Emacs you are
2786 running, and also that you can move a file from one Emacs implementation
2787 to another. WHenever Org is forcing the year for you, it will display
2788 a message and beep.
2790 When this variable is nil, Org will check if the date is
2791 representable in the specific Emacs implementation you are using.
2792 If not, it will force a year, usually the current year, and beep
2793 to remind you. Currently this setting is not recommended because
2794 the likelihood that you will open your Org files in an Emacs that
2795 has limited date range is not negligible.
2797 A workaround for this problem is to use diary sexp dates for time
2798 stamps outside of this range."
2799 :group 'org-time
2800 :version "24.1"
2801 :type 'boolean)
2803 (defcustom org-read-date-display-live t
2804 "Non-nil means display current interpretation of date prompt live.
2805 This display will be in an overlay, in the minibuffer."
2806 :group 'org-time
2807 :type 'boolean)
2809 (defcustom org-read-date-popup-calendar t
2810 "Non-nil means pop up a calendar when prompting for a date.
2811 In the calendar, the date can be selected with mouse-1. However, the
2812 minibuffer will also be active, and you can simply enter the date as well.
2813 When nil, only the minibuffer will be available."
2814 :group 'org-time
2815 :type 'boolean)
2816 (if (fboundp 'defvaralias)
2817 (defvaralias 'org-popup-calendar-for-date-prompt
2818 'org-read-date-popup-calendar))
2820 (defcustom org-read-date-minibuffer-setup-hook nil
2821 "Hook to be used to set up keys for the date/time interface.
2822 Add key definitions to `minibuffer-local-map', which will be a temporary
2823 copy."
2824 :group 'org-time
2825 :type 'hook)
2827 (defcustom org-extend-today-until 0
2828 "The hour when your day really ends. Must be an integer.
2829 This has influence for the following applications:
2830 - When switching the agenda to \"today\". It it is still earlier than
2831 the time given here, the day recognized as TODAY is actually yesterday.
2832 - When a date is read from the user and it is still before the time given
2833 here, the current date and time will be assumed to be yesterday, 23:59.
2834 Also, timestamps inserted in remember templates follow this rule.
2836 IMPORTANT: This is a feature whose implementation is and likely will
2837 remain incomplete. Really, it is only here because past midnight seems to
2838 be the favorite working time of John Wiegley :-)"
2839 :group 'org-time
2840 :type 'integer)
2842 (defcustom org-use-effective-time nil
2843 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2844 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2845 \"effective time\" of any timestamps between midnight and 8am will be
2846 23:59 of the previous day."
2847 :group 'boolean
2848 :version "24.1"
2849 :type 'integer)
2851 (defcustom org-edit-timestamp-down-means-later nil
2852 "Non-nil means S-down will increase the time in a time stamp.
2853 When nil, S-up will increase."
2854 :group 'org-time
2855 :type 'boolean)
2857 (defcustom org-calendar-follow-timestamp-change t
2858 "Non-nil means make the calendar window follow timestamp changes.
2859 When a timestamp is modified and the calendar window is visible, it will be
2860 moved to the new date."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defgroup org-tags nil
2865 "Options concerning tags in Org-mode."
2866 :tag "Org Tags"
2867 :group 'org)
2869 (defcustom org-tag-alist nil
2870 "List of tags allowed in Org-mode files.
2871 When this list is nil, Org-mode will base TAG input on what is already in the
2872 buffer.
2873 The value of this variable is an alist, the car of each entry must be a
2874 keyword as a string, the cdr may be a character that is used to select
2875 that tag through the fast-tag-selection interface.
2876 See the manual for details."
2877 :group 'org-tags
2878 :type '(repeat
2879 (choice
2880 (cons (string :tag "Tag name")
2881 (character :tag "Access char"))
2882 (list :tag "Start radio group"
2883 (const :startgroup)
2884 (option (string :tag "Group description")))
2885 (list :tag "End radio group"
2886 (const :endgroup)
2887 (option (string :tag "Group description")))
2888 (const :tag "New line" (:newline)))))
2890 (defcustom org-tag-persistent-alist nil
2891 "List of tags that will always appear in all Org-mode files.
2892 This is in addition to any in buffer settings or customizations
2893 of `org-tag-alist'.
2894 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2895 The value of this variable is an alist, the car of each entry must be a
2896 keyword as a string, the cdr may be a character that is used to select
2897 that tag through the fast-tag-selection interface.
2898 See the manual for details.
2899 To disable these tags on a per-file basis, insert anywhere in the file:
2900 #+STARTUP: noptag"
2901 :group 'org-tags
2902 :type '(repeat
2903 (choice
2904 (cons (string :tag "Tag name")
2905 (character :tag "Access char"))
2906 (const :tag "Start radio group" (:startgroup))
2907 (const :tag "End radio group" (:endgroup))
2908 (const :tag "New line" (:newline)))))
2910 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2911 "If non-nil, always offer completion for all tags of all agenda files.
2912 Instead of customizing this variable directly, you might want to
2913 set it locally for capture buffers, because there no list of
2914 tags in that file can be created dynamically (there are none).
2916 (add-hook 'org-capture-mode-hook
2917 (lambda ()
2918 (set (make-local-variable
2919 'org-complete-tags-always-offer-all-agenda-tags)
2920 t)))"
2921 :group 'org-tags
2922 :version "24.1"
2923 :type 'boolean)
2925 (defvar org-file-tags nil
2926 "List of tags that can be inherited by all entries in the file.
2927 The tags will be inherited if the variable `org-use-tag-inheritance'
2928 says they should be.
2929 This variable is populated from #+FILETAGS lines.")
2931 (defcustom org-use-fast-tag-selection 'auto
2932 "Non-nil means use fast tag selection scheme.
2933 This is a special interface to select and deselect tags with single keys.
2934 When nil, fast selection is never used.
2935 When the symbol `auto', fast selection is used if and only if selection
2936 characters for tags have been configured, either through the variable
2937 `org-tag-alist' or through a #+TAGS line in the buffer.
2938 When t, fast selection is always used and selection keys are assigned
2939 automatically if necessary."
2940 :group 'org-tags
2941 :type '(choice
2942 (const :tag "Always" t)
2943 (const :tag "Never" nil)
2944 (const :tag "When selection characters are configured" 'auto)))
2946 (defcustom org-fast-tag-selection-single-key nil
2947 "Non-nil means fast tag selection exits after first change.
2948 When nil, you have to press RET to exit it.
2949 During fast tag selection, you can toggle this flag with `C-c'.
2950 This variable can also have the value `expert'. In this case, the window
2951 displaying the tags menu is not even shown, until you press C-c again."
2952 :group 'org-tags
2953 :type '(choice
2954 (const :tag "No" nil)
2955 (const :tag "Yes" t)
2956 (const :tag "Expert" expert)))
2958 (defvar org-fast-tag-selection-include-todo nil
2959 "Non-nil means fast tags selection interface will also offer TODO states.
2960 This is an undocumented feature, you should not rely on it.")
2962 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2963 "The column to which tags should be indented in a headline.
2964 If this number is positive, it specifies the column. If it is negative,
2965 it means that the tags should be flushright to that column. For example,
2966 -80 works well for a normal 80 character screen.
2967 When 0, place tags directly after headline text, with only one space in
2968 between."
2969 :group 'org-tags
2970 :type 'integer)
2972 (defcustom org-auto-align-tags t
2973 "Non-nil keeps tags aligned when modifying headlines.
2974 Some operations (i.e. demoting) change the length of a headline and
2975 therefore shift the tags around. With this option turned on, after
2976 each such operation the tags are again aligned to `org-tags-column'."
2977 :group 'org-tags
2978 :type 'boolean)
2980 (defcustom org-use-tag-inheritance t
2981 "Non-nil means tags in levels apply also for sublevels.
2982 When nil, only the tags directly given in a specific line apply there.
2983 This may also be a list of tags that should be inherited, or a regexp that
2984 matches tags that should be inherited. Additional control is possible
2985 with the variable `org-tags-exclude-from-inheritance' which gives an
2986 explicit list of tags to be excluded from inheritance., even if the value of
2987 `org-use-tag-inheritance' would select it for inheritance.
2989 If this option is t, a match early-on in a tree can lead to a large
2990 number of matches in the subtree when constructing the agenda or creating
2991 a sparse tree. If you only want to see the first match in a tree during
2992 a search, check out the variable `org-tags-match-list-sublevels'."
2993 :group 'org-tags
2994 :type '(choice
2995 (const :tag "Not" nil)
2996 (const :tag "Always" t)
2997 (repeat :tag "Specific tags" (string :tag "Tag"))
2998 (regexp :tag "Tags matched by regexp")))
3000 (defcustom org-tags-exclude-from-inheritance nil
3001 "List of tags that should never be inherited.
3002 This is a way to exclude a few tags from inheritance. For way to do
3003 the opposite, to actively allow inheritance for selected tags,
3004 see the variable `org-use-tag-inheritance'."
3005 :group 'org-tags
3006 :type '(repeat (string :tag "Tag")))
3008 (defun org-tag-inherit-p (tag)
3009 "Check if TAG is one that should be inherited."
3010 (cond
3011 ((member tag org-tags-exclude-from-inheritance) nil)
3012 ((eq org-use-tag-inheritance t) t)
3013 ((not org-use-tag-inheritance) nil)
3014 ((stringp org-use-tag-inheritance)
3015 (string-match org-use-tag-inheritance tag))
3016 ((listp org-use-tag-inheritance)
3017 (member tag org-use-tag-inheritance))
3018 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3020 (defcustom org-tags-match-list-sublevels t
3021 "Non-nil means list also sublevels of headlines matching a search.
3022 This variable applies to tags/property searches, and also to stuck
3023 projects because this search is based on a tags match as well.
3025 When set to the symbol `indented', sublevels are indented with
3026 leading dots.
3028 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3029 the sublevels of a headline matching a tag search often also match
3030 the same search. Listing all of them can create very long lists.
3031 Setting this variable to nil causes subtrees of a match to be skipped.
3033 This variable is semi-obsolete and probably should always be true. It
3034 is better to limit inheritance to certain tags using the variables
3035 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3036 :group 'org-tags
3037 :type '(choice
3038 (const :tag "No, don't list them" nil)
3039 (const :tag "Yes, do list them" t)
3040 (const :tag "List them, indented with leading dots" indented)))
3042 (defcustom org-tags-sort-function nil
3043 "When set, tags are sorted using this function as a comparator."
3044 :group 'org-tags
3045 :type '(choice
3046 (const :tag "No sorting" nil)
3047 (const :tag "Alphabetical" string<)
3048 (const :tag "Reverse alphabetical" string>)
3049 (function :tag "Custom function" nil)))
3051 (defvar org-tags-history nil
3052 "History of minibuffer reads for tags.")
3053 (defvar org-last-tags-completion-table nil
3054 "The last used completion table for tags.")
3055 (defvar org-after-tags-change-hook nil
3056 "Hook that is run after the tags in a line have changed.")
3058 (defgroup org-properties nil
3059 "Options concerning properties in Org-mode."
3060 :tag "Org Properties"
3061 :group 'org)
3063 (defcustom org-property-format "%-10s %s"
3064 "How property key/value pairs should be formatted by `indent-line'.
3065 When `indent-line' hits a property definition, it will format the line
3066 according to this format, mainly to make sure that the values are
3067 lined-up with respect to each other."
3068 :group 'org-properties
3069 :type 'string)
3071 (defcustom org-properties-postprocess-alist nil
3072 "Alist of properties and functions to adjust inserted values.
3073 Elements of this alist must be of the form
3075 ([string] [function])
3077 where [string] must be a property name and [function] must be a
3078 lambda expression: this lambda expression must take one argument,
3079 the value to adjust, and return the new value as a string.
3081 For example, this element will allow the property \"Remaining\"
3082 to be updated wrt the relation between the \"Effort\" property
3083 and the clock summary:
3085 ((\"Remaining\" (lambda(value)
3086 (let ((clocksum (org-clock-sum-current-item))
3087 (effort (org-duration-string-to-minutes
3088 (org-entry-get (point) \"Effort\"))))
3089 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3090 :group 'org-properties
3091 :version "24.1"
3092 :type 'alist)
3094 (defcustom org-use-property-inheritance nil
3095 "Non-nil means properties apply also for sublevels.
3097 This setting is chiefly used during property searches. Turning it on can
3098 cause significant overhead when doing a search, which is why it is not
3099 on by default.
3101 When nil, only the properties directly given in the current entry count.
3102 When t, every property is inherited. The value may also be a list of
3103 properties that should have inheritance, or a regular expression matching
3104 properties that should be inherited.
3106 However, note that some special properties use inheritance under special
3107 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3108 and the properties ending in \"_ALL\" when they are used as descriptor
3109 for valid values of a property.
3111 Note for programmers:
3112 When querying an entry with `org-entry-get', you can control if inheritance
3113 should be used. By default, `org-entry-get' looks only at the local
3114 properties. You can request inheritance by setting the inherit argument
3115 to t (to force inheritance) or to `selective' (to respect the setting
3116 in this variable)."
3117 :group 'org-properties
3118 :type '(choice
3119 (const :tag "Not" nil)
3120 (const :tag "Always" t)
3121 (repeat :tag "Specific properties" (string :tag "Property"))
3122 (regexp :tag "Properties matched by regexp")))
3124 (defun org-property-inherit-p (property)
3125 "Check if PROPERTY is one that should be inherited."
3126 (cond
3127 ((eq org-use-property-inheritance t) t)
3128 ((not org-use-property-inheritance) nil)
3129 ((stringp org-use-property-inheritance)
3130 (string-match org-use-property-inheritance property))
3131 ((listp org-use-property-inheritance)
3132 (member property org-use-property-inheritance))
3133 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3135 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3136 "The default column format, if no other format has been defined.
3137 This variable can be set on the per-file basis by inserting a line
3139 #+COLUMNS: %25ITEM ....."
3140 :group 'org-properties
3141 :type 'string)
3143 (defcustom org-columns-ellipses ".."
3144 "The ellipses to be used when a field in column view is truncated.
3145 When this is the empty string, as many characters as possible are shown,
3146 but then there will be no visual indication that the field has been truncated.
3147 When this is a string of length N, the last N characters of a truncated
3148 field are replaced by this string. If the column is narrower than the
3149 ellipses string, only part of the ellipses string will be shown."
3150 :group 'org-properties
3151 :type 'string)
3153 (defcustom org-columns-modify-value-for-display-function nil
3154 "Function that modifies values for display in column view.
3155 For example, it can be used to cut out a certain part from a time stamp.
3156 The function must take 2 arguments:
3158 column-title The title of the column (*not* the property name)
3159 value The value that should be modified.
3161 The function should return the value that should be displayed,
3162 or nil if the normal value should be used."
3163 :group 'org-properties
3164 :type 'function)
3166 (defcustom org-effort-property "Effort"
3167 "The property that is being used to keep track of effort estimates.
3168 Effort estimates given in this property need to have the format H:MM."
3169 :group 'org-properties
3170 :group 'org-progress
3171 :type '(string :tag "Property"))
3173 (defconst org-global-properties-fixed
3174 '(("VISIBILITY_ALL" . "folded children content all")
3175 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3176 "List of property/value pairs that can be inherited by any entry.
3178 These are fixed values, for the preset properties. The user variable
3179 that can be used to add to this list is `org-global-properties'.
3181 The entries in this list are cons cells where the car is a property
3182 name and cdr is a string with the value. If the value represents
3183 multiple items like an \"_ALL\" property, separate the items by
3184 spaces.")
3186 (defcustom org-global-properties nil
3187 "List of property/value pairs that can be inherited by any entry.
3189 This list will be combined with the constant `org-global-properties-fixed'.
3191 The entries in this list are cons cells where the car is a property
3192 name and cdr is a string with the value.
3194 You can set buffer-local values for the same purpose in the variable
3195 `org-file-properties' this by adding lines like
3197 #+PROPERTY: NAME VALUE"
3198 :group 'org-properties
3199 :type '(repeat
3200 (cons (string :tag "Property")
3201 (string :tag "Value"))))
3203 (defvar org-file-properties nil
3204 "List of property/value pairs that can be inherited by any entry.
3205 Valid for the current buffer.
3206 This variable is populated from #+PROPERTY lines.")
3207 (make-variable-buffer-local 'org-file-properties)
3209 (defgroup org-agenda nil
3210 "Options concerning agenda views in Org-mode."
3211 :tag "Org Agenda"
3212 :group 'org)
3214 (defvar org-category nil
3215 "Variable used by org files to set a category for agenda display.
3216 Such files should use a file variable to set it, for example
3218 # -*- mode: org; org-category: \"ELisp\"
3220 or contain a special line
3222 #+CATEGORY: ELisp
3224 If the file does not specify a category, then file's base name
3225 is used instead.")
3226 (make-variable-buffer-local 'org-category)
3227 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3229 (defcustom org-agenda-files nil
3230 "The files to be used for agenda display.
3231 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3232 \\[org-remove-file]. You can also use customize to edit the list.
3234 If an entry is a directory, all files in that directory that are matched by
3235 `org-agenda-file-regexp' will be part of the file list.
3237 If the value of the variable is not a list but a single file name, then
3238 the list of agenda files is actually stored and maintained in that file, one
3239 agenda file per line. In this file paths can be given relative to
3240 `org-directory'. Tilde expansion and environment variable substitution
3241 are also made."
3242 :group 'org-agenda
3243 :type '(choice
3244 (repeat :tag "List of files and directories" file)
3245 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3247 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3248 "Regular expression to match files for `org-agenda-files'.
3249 If any element in the list in that variable contains a directory instead
3250 of a normal file, all files in that directory that are matched by this
3251 regular expression will be included."
3252 :group 'org-agenda
3253 :type 'regexp)
3255 (defcustom org-agenda-text-search-extra-files nil
3256 "List of extra files to be searched by text search commands.
3257 These files will be search in addition to the agenda files by the
3258 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3259 Note that these files will only be searched for text search commands,
3260 not for the other agenda views like todo lists, tag searches or the weekly
3261 agenda. This variable is intended to list notes and possibly archive files
3262 that should also be searched by these two commands.
3263 In fact, if the first element in the list is the symbol `agenda-archives',
3264 than all archive files of all agenda files will be added to the search
3265 scope."
3266 :group 'org-agenda
3267 :type '(set :greedy t
3268 (const :tag "Agenda Archives" agenda-archives)
3269 (repeat :inline t (file))))
3271 (if (fboundp 'defvaralias)
3272 (defvaralias 'org-agenda-multi-occur-extra-files
3273 'org-agenda-text-search-extra-files))
3275 (defcustom org-agenda-skip-unavailable-files nil
3276 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3277 A nil value means to remove them, after a query, from the list."
3278 :group 'org-agenda
3279 :type 'boolean)
3281 (defcustom org-calendar-to-agenda-key [?c]
3282 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3283 The command `org-calendar-goto-agenda' will be bound to this key. The
3284 default is the character `c' because then `c' can be used to switch back and
3285 forth between agenda and calendar."
3286 :group 'org-agenda
3287 :type 'sexp)
3289 (defcustom org-calendar-agenda-action-key [?k]
3290 "The key to be installed in `calendar-mode-map' for agenda-action.
3291 The command `org-agenda-action' will be bound to this key. The
3292 default is the character `k' because we use the same key in the agenda."
3293 :group 'org-agenda
3294 :type 'sexp)
3296 (defcustom org-calendar-insert-diary-entry-key [?i]
3297 "The key to be installed in `calendar-mode-map' for adding diary entries.
3298 This option is irrelevant until `org-agenda-diary-file' has been configured
3299 to point to an Org-mode file. When that is the case, the command
3300 `org-agenda-diary-entry' will be bound to the key given here, by default
3301 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3302 if you want to continue doing this, you need to change this to a different
3303 key."
3304 :group 'org-agenda
3305 :type 'sexp)
3307 (defcustom org-agenda-diary-file 'diary-file
3308 "File to which to add new entries with the `i' key in agenda and calendar.
3309 When this is the symbol `diary-file', the functionality in the Emacs
3310 calendar will be used to add entries to the `diary-file'. But when this
3311 points to a file, `org-agenda-diary-entry' will be used instead."
3312 :group 'org-agenda
3313 :type '(choice
3314 (const :tag "The standard Emacs diary file" diary-file)
3315 (file :tag "Special Org file diary entries")))
3317 (eval-after-load "calendar"
3318 '(progn
3319 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3320 'org-calendar-goto-agenda)
3321 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3322 'org-agenda-action)
3323 (add-hook 'calendar-mode-hook
3324 (lambda ()
3325 (unless (eq org-agenda-diary-file 'diary-file)
3326 (define-key calendar-mode-map
3327 org-calendar-insert-diary-entry-key
3328 'org-agenda-diary-entry))))))
3330 (defgroup org-latex nil
3331 "Options for embedding LaTeX code into Org-mode."
3332 :tag "Org LaTeX"
3333 :group 'org)
3335 (defcustom org-format-latex-options
3336 '(:foreground default :background default :scale 1.0
3337 :html-foreground "Black" :html-background "Transparent"
3338 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3339 "Options for creating images from LaTeX fragments.
3340 This is a property list with the following properties:
3341 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3342 `default' means use the foreground of the default face.
3343 :background the background color, or \"Transparent\".
3344 `default' means use the background of the default face.
3345 :scale a scaling factor for the size of the images, to get more pixels
3346 :html-foreground, :html-background, :html-scale
3347 the same numbers for HTML export.
3348 :matchers a list indicating which matchers should be used to
3349 find LaTeX fragments. Valid members of this list are:
3350 \"begin\" find environments
3351 \"$1\" find single characters surrounded by $.$
3352 \"$\" find math expressions surrounded by $...$
3353 \"$$\" find math expressions surrounded by $$....$$
3354 \"\\(\" find math expressions surrounded by \\(...\\)
3355 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3356 :group 'org-latex
3357 :type 'plist)
3359 (defcustom org-format-latex-signal-error t
3360 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3361 When nil, just push out a message."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-latex-to-mathml-jar-file nil
3367 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3368 Use this to specify additional executable file say a jar file.
3370 When using MathToWeb as the converter, specify the full-path to
3371 your mathtoweb.jar file."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (file :tag "JAR file" :must-match t)))
3378 (defcustom org-latex-to-mathml-convert-command nil
3379 "Command to convert LaTeX fragments to MathML.
3380 Replace format-specifiers in the command as noted below and use
3381 `shell-command' to convert LaTeX to MathML.
3382 %j: Executable file in fully expanded form as specified by
3383 `org-latex-to-mathml-jar-file'.
3384 %I: Input LaTeX file in fully expanded form
3385 %o: Output MathML file
3386 This command is used by `org-create-math-formula'.
3388 When using MathToWeb as the converter, set this to
3389 \"java -jar %j -unicode -force -df %o %I\"."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (string :tag "\nShell command")))
3396 (defun org-format-latex-mathml-available-p ()
3397 "Return t if `org-latex-to-mathml-convert-command' is usable."
3398 (save-match-data
3399 (when (and (boundp 'org-latex-to-mathml-convert-command)
3400 org-latex-to-mathml-convert-command)
3401 (let ((executable (car (split-string
3402 org-latex-to-mathml-convert-command))))
3403 (when (executable-find executable)
3404 (if (string-match
3405 "%j" org-latex-to-mathml-convert-command)
3406 (file-readable-p org-latex-to-mathml-jar-file)
3407 t))))))
3409 (defcustom org-format-latex-header "\\documentclass{article}
3410 \\usepackage[usenames]{color}
3411 \\usepackage{amsmath}
3412 \\usepackage[mathscr]{eucal}
3413 \\pagestyle{empty} % do not remove
3414 \[PACKAGES]
3415 \[DEFAULT-PACKAGES]
3416 % The settings below are copied from fullpage.sty
3417 \\setlength{\\textwidth}{\\paperwidth}
3418 \\addtolength{\\textwidth}{-3cm}
3419 \\setlength{\\oddsidemargin}{1.5cm}
3420 \\addtolength{\\oddsidemargin}{-2.54cm}
3421 \\setlength{\\evensidemargin}{\\oddsidemargin}
3422 \\setlength{\\textheight}{\\paperheight}
3423 \\addtolength{\\textheight}{-\\headheight}
3424 \\addtolength{\\textheight}{-\\headsep}
3425 \\addtolength{\\textheight}{-\\footskip}
3426 \\addtolength{\\textheight}{-3cm}
3427 \\setlength{\\topmargin}{1.5cm}
3428 \\addtolength{\\topmargin}{-2.54cm}"
3429 "The document header used for processing LaTeX fragments.
3430 It is imperative that this header make sure that no page number
3431 appears on the page. The package defined in the variables
3432 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3433 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3434 will be appended."
3435 :group 'org-latex
3436 :type 'string)
3438 (defvar org-format-latex-header-extra nil)
3440 (defun org-set-packages-alist (var val)
3441 "Set the packages alist and make sure it has 3 elements per entry."
3442 (set var (mapcar (lambda (x)
3443 (if (and (consp x) (= (length x) 2))
3444 (list (car x) (nth 1 x) t)
3446 val)))
3448 (defun org-get-packages-alist (var)
3450 "Get the packages alist and make sure it has 3 elements per entry."
3451 (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 (default-value var)))
3457 ;; The following variables are defined here because is it also used
3458 ;; when formatting latex fragments. Originally it was part of the
3459 ;; LaTeX exporter, which is why the name includes "export".
3460 (defcustom org-export-latex-default-packages-alist
3461 '(("AUTO" "inputenc" t)
3462 ("T1" "fontenc" t)
3463 ("" "fixltx2e" nil)
3464 ("" "graphicx" t)
3465 ("" "longtable" nil)
3466 ("" "float" nil)
3467 ("" "wrapfig" nil)
3468 ("" "soul" t)
3469 ("" "textcomp" t)
3470 ("" "marvosym" t)
3471 ("" "wasysym" t)
3472 ("" "latexsym" t)
3473 ("" "amssymb" t)
3474 ("" "hyperref" nil)
3475 "\\tolerance=1000"
3477 "Alist of default packages to be inserted in the header.
3478 Change this only if one of the packages here causes an incompatibility
3479 with another package you are using.
3480 The packages in this list are needed by one part or another of Org-mode
3481 to function properly.
3483 - inputenc, fontenc: for basic font and character selection
3484 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3485 for interpreting the entities in `org-entities'. You can skip some of these
3486 packages if you don't use any of the symbols in it.
3487 - graphicx: for including images
3488 - float, wrapfig: for figure placement
3489 - longtable: for long tables
3490 - hyperref: for cross references
3492 Therefore you should not modify this variable unless you know what you
3493 are doing. The one reason to change it anyway is that you might be loading
3494 some other package that conflicts with one of the default packages.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3496 If SNIPPET-FLAG is t, the package also needs to be included when
3497 compiling LaTeX snippets into images for inclusion into HTML."
3498 :group 'org-export-latex
3499 :set 'org-set-packages-alist
3500 :get 'org-get-packages-alist
3501 :version "24.1"
3502 :type '(repeat
3503 (choice
3504 (list :tag "options/package pair"
3505 (string :tag "options")
3506 (string :tag "package")
3507 (boolean :tag "Snippet"))
3508 (string :tag "A line of LaTeX"))))
3510 (defcustom org-export-latex-packages-alist nil
3511 "Alist of packages to be inserted in every LaTeX header.
3512 These will be inserted after `org-export-latex-default-packages-alist'.
3513 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3514 SNIPPET-FLAG, when t, indicates that this package is also needed when
3515 turning LaTeX snippets into images for inclusion into HTML.
3516 Make sure that you only list packages here which:
3517 - you want in every file
3518 - do not conflict with the default packages in
3519 `org-export-latex-default-packages-alist'
3520 - do not conflict with the setup in `org-format-latex-header'."
3521 :group 'org-export-latex
3522 :set 'org-set-packages-alist
3523 :get 'org-get-packages-alist
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3533 (defgroup org-appearance nil
3534 "Settings for Org-mode appearance."
3535 :tag "Org Appearance"
3536 :group 'org)
3538 (defcustom org-level-color-stars-only nil
3539 "Non-nil means fontify only the stars in each headline.
3540 When nil, the entire headline is fontified.
3541 Changing it requires restart of `font-lock-mode' to become effective
3542 also in regions already fontified."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-hide-leading-stars nil
3547 "Non-nil means hide the first N-1 stars in a headline.
3548 This works by using the face `org-hide' for these stars. This
3549 face is white for a light background, and black for a dark
3550 background. You may have to customize the face `org-hide' to
3551 make this work.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified.
3554 You may also set this on a per-file basis by adding one of the following
3555 lines to the buffer:
3557 #+STARTUP: hidestars
3558 #+STARTUP: showstars"
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-hidden-keywords nil
3563 "List of symbols corresponding to keywords to be hidden the org buffer.
3564 For example, a value '(title) for this list will make the document's title
3565 appear in the buffer without the initial #+TITLE: keyword."
3566 :group 'org-appearance
3567 :version "24.1"
3568 :type '(set (const :tag "#+AUTHOR" author)
3569 (const :tag "#+DATE" date)
3570 (const :tag "#+EMAIL" email)
3571 (const :tag "#+TITLE" title)))
3573 (defcustom org-fontify-done-headline nil
3574 "Non-nil means change the face of a headline if it is marked DONE.
3575 Normally, only the TODO/DONE keyword indicates the state of a headline.
3576 When this is non-nil, the headline after the keyword is set to the
3577 `org-headline-done' as an additional indication."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-fontify-emphasized-text t
3582 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3583 Changing this variable requires a restart of Emacs to take effect."
3584 :group 'org-appearance
3585 :type 'boolean)
3587 (defcustom org-fontify-whole-heading-line nil
3588 "Non-nil means fontify the whole line for headings.
3589 This is useful when setting a background color for the
3590 org-level-* faces."
3591 :group 'org-appearance
3592 :type 'boolean)
3594 (defcustom org-highlight-latex-fragments-and-specials nil
3595 "Non-nil means fontify what is treated specially by the exporters."
3596 :group 'org-appearance
3597 :type 'boolean)
3599 (defcustom org-hide-emphasis-markers nil
3600 "Non-nil mean font-lock should hide the emphasis marker characters."
3601 :group 'org-appearance
3602 :type 'boolean)
3604 (defcustom org-pretty-entities nil
3605 "Non-nil means show entities as UTF8 characters.
3606 When nil, the \\name form remains in the buffer."
3607 :group 'org-appearance
3608 :version "24.1"
3609 :type 'boolean)
3611 (defcustom org-pretty-entities-include-sub-superscripts t
3612 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3613 :group 'org-appearance
3614 :version "24.1"
3615 :type 'boolean)
3617 (defvar org-emph-re nil
3618 "Regular expression for matching emphasis.
3619 After a match, the match groups contain these elements:
3620 0 The match of the full regular expression, including the characters
3621 before and after the proper match
3622 1 The character before the proper match, or empty at beginning of line
3623 2 The proper match, including the leading and trailing markers
3624 3 The leading marker like * or /, indicating the type of highlighting
3625 4 The text between the emphasis markers, not including the markers
3626 5 The character after the match, empty at the end of a line")
3627 (defvar org-verbatim-re nil
3628 "Regular expression for matching verbatim text.")
3629 (defvar org-emphasis-regexp-components) ; defined just below
3630 (defvar org-emphasis-alist) ; defined just below
3631 (defun org-set-emph-re (var val)
3632 "Set variable and compute the emphasis regular expression."
3633 (set var val)
3634 (when (and (boundp 'org-emphasis-alist)
3635 (boundp 'org-emphasis-regexp-components)
3636 org-emphasis-alist org-emphasis-regexp-components)
3637 (let* ((e org-emphasis-regexp-components)
3638 (pre (car e))
3639 (post (nth 1 e))
3640 (border (nth 2 e))
3641 (body (nth 3 e))
3642 (nl (nth 4 e))
3643 (body1 (concat body "*?"))
3644 (markers (mapconcat 'car org-emphasis-alist ""))
3645 (vmarkers (mapconcat
3646 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3647 org-emphasis-alist "")))
3648 ;; make sure special characters appear at the right position in the class
3649 (if (string-match "\\^" markers)
3650 (setq markers (concat (replace-match "" t t markers) "^")))
3651 (if (string-match "-" markers)
3652 (setq markers (concat (replace-match "" t t markers) "-")))
3653 (if (string-match "\\^" vmarkers)
3654 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3655 (if (string-match "-" vmarkers)
3656 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3657 (if (> nl 0)
3658 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3659 (int-to-string nl) "\\}")))
3660 ;; Make the regexp
3661 (setq org-emph-re
3662 (concat "\\([" pre "]\\|^\\)"
3663 "\\("
3664 "\\([" markers "]\\)"
3665 "\\("
3666 "[^" border "]\\|"
3667 "[^" border "]"
3668 body1
3669 "[^" border "]"
3670 "\\)"
3671 "\\3\\)"
3672 "\\([" post "]\\|$\\)"))
3673 (setq org-verbatim-re
3674 (concat "\\([" pre "]\\|^\\)"
3675 "\\("
3676 "\\([" vmarkers "]\\)"
3677 "\\("
3678 "[^" border "]\\|"
3679 "[^" border "]"
3680 body1
3681 "[^" border "]"
3682 "\\)"
3683 "\\3\\)"
3684 "\\([" post "]\\|$\\)")))))
3686 (defcustom org-emphasis-regexp-components
3687 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3688 "Components used to build the regular expression for emphasis.
3689 This is a list with five entries. Terminology: In an emphasis string
3690 like \" *strong word* \", we call the initial space PREMATCH, the final
3691 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3692 and \"trong wor\" is the body. The different components in this variable
3693 specify what is allowed/forbidden in each part:
3695 pre Chars allowed as prematch. Beginning of line will be allowed too.
3696 post Chars allowed as postmatch. End of line will be allowed too.
3697 border The chars *forbidden* as border characters.
3698 body-regexp A regexp like \".\" to match a body character. Don't use
3699 non-shy groups here, and don't allow newline here.
3700 newline The maximum number of newlines allowed in an emphasis exp.
3702 Use customize to modify this, or restart Emacs after changing it."
3703 :group 'org-appearance
3704 :set 'org-set-emph-re
3705 :type '(list
3706 (sexp :tag "Allowed chars in pre ")
3707 (sexp :tag "Allowed chars in post ")
3708 (sexp :tag "Forbidden chars in border ")
3709 (sexp :tag "Regexp for body ")
3710 (integer :tag "number of newlines allowed")
3711 (option (boolean :tag "Please ignore this button"))))
3713 (defcustom org-emphasis-alist
3714 `(("*" bold "<b>" "</b>")
3715 ("/" italic "<i>" "</i>")
3716 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3717 ("=" org-code "<code>" "</code>" verbatim)
3718 ("~" org-verbatim "<code>" "</code>" verbatim)
3719 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3720 "<del>" "</del>")
3722 "Special syntax for emphasized text.
3723 Text starting and ending with a special character will be emphasized, for
3724 example *bold*, _underlined_ and /italic/. This variable sets the marker
3725 characters, the face to be used by font-lock for highlighting in Org-mode
3726 Emacs buffers, and the HTML tags to be used for this.
3727 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3728 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3729 Use customize to modify this, or restart Emacs after changing it."
3730 :group 'org-appearance
3731 :set 'org-set-emph-re
3732 :type '(repeat
3733 (list
3734 (string :tag "Marker character")
3735 (choice
3736 (face :tag "Font-lock-face")
3737 (plist :tag "Face property list"))
3738 (string :tag "HTML start tag")
3739 (string :tag "HTML end tag")
3740 (option (const verbatim)))))
3742 (defvar org-protecting-blocks
3743 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3744 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3745 This is needed for font-lock setup.")
3747 ;;; Miscellaneous options
3749 (defgroup org-completion nil
3750 "Completion in Org-mode."
3751 :tag "Org Completion"
3752 :group 'org)
3754 (defcustom org-completion-use-ido nil
3755 "Non-nil means use ido completion wherever possible.
3756 Note that `ido-mode' must be active for this variable to be relevant.
3757 If you decide to turn this variable on, you might well want to turn off
3758 `org-outline-path-complete-in-steps'.
3759 See also `org-completion-use-iswitchb'."
3760 :group 'org-completion
3761 :type 'boolean)
3763 (defcustom org-completion-use-iswitchb nil
3764 "Non-nil means use iswitchb completion wherever possible.
3765 Note that `iswitchb-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-fallback-command 'hippie-expand
3773 "The expansion command called by \\[pcomplete] in normal context.
3774 Normal means, no org-mode-specific context."
3775 :group 'org-completion
3776 :type 'function)
3778 ;;; Functions and variables from their packages
3779 ;; Declared here to avoid compiler warnings
3781 ;; XEmacs only
3782 (defvar outline-mode-menu-heading)
3783 (defvar outline-mode-menu-show)
3784 (defvar outline-mode-menu-hide)
3785 (defvar zmacs-regions) ; XEmacs regions
3787 ;; Emacs only
3788 (defvar mark-active)
3790 ;; Various packages
3791 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3792 (declare-function calendar-forward-day "cal-move" (arg))
3793 (declare-function calendar-goto-date "cal-move" (date))
3794 (declare-function calendar-goto-today "cal-move" ())
3795 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3796 (defvar calc-embedded-close-formula)
3797 (defvar calc-embedded-open-formula)
3798 (declare-function cdlatex-tab "ext:cdlatex" ())
3799 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3800 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3801 (defvar font-lock-unfontify-region-function)
3802 (declare-function iswitchb-read-buffer "iswitchb"
3803 (prompt &optional default require-match start matches-set))
3804 (defvar iswitchb-temp-buflist)
3805 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3806 (defvar org-agenda-tags-todo-honor-ignore-options)
3807 (declare-function org-agenda-skip "org-agenda" ())
3808 (declare-function
3809 org-agenda-format-item "org-agenda"
3810 (extra txt &optional category tags dotime noprefix remove-re habitp))
3811 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3812 (declare-function org-agenda-change-all-lines "org-agenda"
3813 (newhead hdmarker &optional fixface just-this))
3814 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3815 (declare-function org-agenda-maybe-redo "org-agenda" ())
3816 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3817 (beg end))
3818 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3819 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3820 "org-agenda" (&optional end))
3821 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3822 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3823 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3824 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3825 (declare-function org-indent-mode "org-indent" (&optional arg))
3826 (declare-function parse-time-string "parse-time" (string))
3827 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3828 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3829 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3830 (defvar remember-data-file)
3831 (defvar texmathp-why)
3832 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3833 (declare-function table--at-cell-p "table" (position &optional object at-column))
3835 (defvar w3m-current-url)
3836 (defvar w3m-current-title)
3838 (defvar org-latex-regexps)
3840 ;;; Autoload and prepare some org modules
3842 ;; Some table stuff that needs to be defined here, because it is used
3843 ;; by the functions setting up org-mode or checking for table context.
3845 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3846 "Detect an org-type or table-type table.")
3847 (defconst org-table-line-regexp "^[ \t]*|"
3848 "Detect an org-type table line.")
3849 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3850 "Detect an org-type table line.")
3851 (defconst org-table-hline-regexp "^[ \t]*|-"
3852 "Detect an org-type table hline.")
3853 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3854 "Detect a table-type table hline.")
3855 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3856 "Detect the first line outside a table when searching from within it.
3857 This works for both table types.")
3859 ;; Autoload the functions in org-table.el that are needed by functions here.
3861 (eval-and-compile
3862 (org-autoload "org-table"
3863 '(org-table-align org-table-begin org-table-blank-field
3864 org-table-convert org-table-convert-region org-table-copy-down
3865 org-table-copy-region org-table-create
3866 org-table-create-or-convert-from-region
3867 org-table-create-with-table.el org-table-current-dline
3868 org-table-cut-region org-table-delete-column org-table-edit-field
3869 org-table-edit-formulas org-table-end org-table-eval-formula
3870 org-table-export org-table-field-info
3871 org-table-get-stored-formulas org-table-goto-column
3872 org-table-hline-and-move org-table-import org-table-insert-column
3873 org-table-insert-hline org-table-insert-row org-table-iterate
3874 org-table-justify-field-maybe org-table-kill-row
3875 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3876 org-table-move-column org-table-move-column-left
3877 org-table-move-column-right org-table-move-row
3878 org-table-move-row-down org-table-move-row-up
3879 org-table-next-field org-table-next-row org-table-paste-rectangle
3880 org-table-previous-field org-table-recalculate
3881 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3882 org-table-toggle-coordinate-overlays
3883 org-table-toggle-formula-debugger org-table-wrap-region
3884 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3885 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3886 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3888 (defun org-at-table-p (&optional table-type)
3889 "Return t if the cursor is inside an org-type table.
3890 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3891 (if org-enable-table-editor
3892 (save-excursion
3893 (beginning-of-line 1)
3894 (looking-at (if table-type org-table-any-line-regexp
3895 org-table-line-regexp)))
3896 nil))
3897 (defsubst org-table-p () (org-at-table-p))
3899 (defun org-at-table.el-p ()
3900 "Return t if and only if we are at a table.el table."
3901 (and (org-at-table-p 'any)
3902 (save-excursion
3903 (goto-char (org-table-begin 'any))
3904 (looking-at org-table1-hline-regexp))))
3905 (defun org-table-recognize-table.el ()
3906 "If there is a table.el table nearby, recognize it and move into it."
3907 (if org-table-tab-recognizes-table.el
3908 (if (org-at-table.el-p)
3909 (progn
3910 (beginning-of-line 1)
3911 (if (looking-at org-table-dataline-regexp)
3913 (if (looking-at org-table1-hline-regexp)
3914 (progn
3915 (beginning-of-line 2)
3916 (if (looking-at org-table-any-border-regexp)
3917 (beginning-of-line -1)))))
3918 (if (re-search-forward "|" (org-table-end t) t)
3919 (progn
3920 (require 'table)
3921 (if (table--at-cell-p (point))
3923 (message "recognizing table.el table...")
3924 (table-recognize-table)
3925 (message "recognizing table.el table...done")))
3926 (error "This should not happen"))
3928 nil)
3929 nil))
3931 (defun org-at-table-hline-p ()
3932 "Return t if the cursor is inside a hline in a table."
3933 (if org-enable-table-editor
3934 (save-excursion
3935 (beginning-of-line 1)
3936 (looking-at org-table-hline-regexp))
3937 nil))
3939 (defvar org-table-clean-did-remove-column nil)
3941 (defun org-table-map-tables (function &optional quietly)
3942 "Apply FUNCTION to the start of all tables in the buffer."
3943 (save-excursion
3944 (save-restriction
3945 (widen)
3946 (goto-char (point-min))
3947 (while (re-search-forward org-table-any-line-regexp nil t)
3948 (unless quietly
3949 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3950 (beginning-of-line 1)
3951 (when (looking-at org-table-line-regexp)
3952 (save-excursion (funcall function))
3953 (or (looking-at org-table-line-regexp)
3954 (forward-char 1)))
3955 (re-search-forward org-table-any-border-regexp nil 1))))
3956 (unless quietly (message "Mapping tables: done")))
3958 ;; Declare and autoload functions from org-exp.el & Co
3960 (declare-function org-default-export-plist "org-exp")
3961 (declare-function org-infile-export-plist "org-exp")
3962 (declare-function org-get-current-options "org-exp")
3963 (eval-and-compile
3964 (org-autoload "org-exp"
3965 '(org-export org-export-visible
3966 org-insert-export-options-template
3967 org-table-clean-before-export))
3968 (org-autoload "org-ascii"
3969 '(org-export-as-ascii org-export-ascii-preprocess
3970 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3971 org-export-region-as-ascii))
3972 (org-autoload "org-latex"
3973 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3974 org-replace-region-by-latex org-export-region-as-latex
3975 org-export-as-latex org-export-as-pdf
3976 org-export-as-pdf-and-open))
3977 (org-autoload "org-html"
3978 '(org-export-as-html-and-open
3979 org-export-as-html-batch org-export-as-html-to-buffer
3980 org-replace-region-by-html org-export-region-as-html
3981 org-export-as-html))
3982 (org-autoload "org-docbook"
3983 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3984 org-replace-region-by-docbook org-export-region-as-docbook
3985 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3986 org-export-as-docbook))
3987 (org-autoload "org-icalendar"
3988 '(org-export-icalendar-this-file
3989 org-export-icalendar-all-agenda-files
3990 org-export-icalendar-combine-agenda-files))
3991 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3992 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3994 ;; Declare and autoload functions from org-agenda.el
3996 (eval-and-compile
3997 (org-autoload "org-agenda"
3998 '(org-agenda org-agenda-list org-search-view
3999 org-todo-list org-tags-view org-agenda-list-stuck-projects
4000 org-diary org-agenda-to-appt
4001 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4003 ;; Autoload org-remember
4005 (eval-and-compile
4006 (org-autoload "org-remember"
4007 '(org-remember-insinuate org-remember-annotation
4008 org-remember-apply-template org-remember org-remember-handler)))
4010 (eval-and-compile
4011 (org-autoload "org-capture"
4012 '(org-capture org-capture-insert-template-here
4013 org-capture-import-remember-templates)))
4015 ;; Autoload org-clock.el
4017 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4018 (beg end))
4019 (declare-function org-clock-update-mode-line "org-clock" ())
4020 (declare-function org-resolve-clocks "org-clock"
4021 (&optional also-non-dangling-p prompt last-valid))
4022 (defvar org-clock-start-time)
4023 (defvar org-clock-marker (make-marker)
4024 "Marker recording the last clock-in.")
4025 (defvar org-clock-hd-marker (make-marker)
4026 "Marker recording the last clock-in, but the headline position.")
4027 (defvar org-clock-heading ""
4028 "The heading of the current clock entry.")
4029 (defun org-clock-is-active ()
4030 "Return non-nil if clock is currently running.
4031 The return value is actually the clock marker."
4032 (marker-buffer org-clock-marker))
4034 (eval-and-compile
4035 (org-autoload
4036 "org-clock"
4037 '(org-clock-in org-clock-out org-clock-cancel
4038 org-clock-goto org-clock-sum org-clock-display
4039 org-clock-remove-overlays org-clock-report
4040 org-clocktable-shift org-dblock-write:clocktable
4041 org-get-clocktable org-resolve-clocks)))
4043 (defun org-clock-update-time-maybe ()
4044 "If this is a CLOCK line, update it and return t.
4045 Otherwise, return nil."
4046 (interactive)
4047 (save-excursion
4048 (beginning-of-line 1)
4049 (skip-chars-forward " \t")
4050 (when (looking-at org-clock-string)
4051 (let ((re (concat "[ \t]*" org-clock-string
4052 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4053 "\\([ \t]*=>.*\\)?\\)?"))
4054 ts te h m s neg)
4055 (cond
4056 ((not (looking-at re))
4057 nil)
4058 ((not (match-end 2))
4059 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4060 (> org-clock-marker (point))
4061 (<= org-clock-marker (point-at-eol)))
4062 ;; The clock is running here
4063 (setq org-clock-start-time
4064 (apply 'encode-time
4065 (org-parse-time-string (match-string 1))))
4066 (org-clock-update-mode-line)))
4068 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4069 (end-of-line 1)
4070 (setq ts (match-string 1)
4071 te (match-string 3))
4072 (setq s (- (org-float-time
4073 (apply 'encode-time (org-parse-time-string te)))
4074 (org-float-time
4075 (apply 'encode-time (org-parse-time-string ts))))
4076 neg (< s 0)
4077 s (abs s)
4078 h (floor (/ s 3600))
4079 s (- s (* 3600 h))
4080 m (floor (/ s 60))
4081 s (- s (* 60 s)))
4082 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4083 t))))))
4085 (defun org-check-running-clock ()
4086 "Check if the current buffer contains the running clock.
4087 If yes, offer to stop it and to save the buffer with the changes."
4088 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4089 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4090 (buffer-name))))
4091 (org-clock-out)
4092 (when (y-or-n-p "Save changed buffer?")
4093 (save-buffer))))
4095 (defun org-clocktable-try-shift (dir n)
4096 "Check if this line starts a clock table, if yes, shift the time block."
4097 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4098 (org-clocktable-shift dir n)))
4100 ;; Autoload org-timer.el
4102 (eval-and-compile
4103 (org-autoload
4104 "org-timer"
4105 '(org-timer-start org-timer org-timer-item
4106 org-timer-change-times-in-region
4107 org-timer-set-timer
4108 org-timer-reset-timers
4109 org-timer-show-remaining-time)))
4111 ;; Autoload org-feed.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-feed"
4116 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4119 ;; Autoload org-indent.el
4121 ;; Define the variable already here, to make sure we have it.
4122 (defvar org-indent-mode nil
4123 "Non-nil if Org-Indent mode is enabled.
4124 Use the command `org-indent-mode' to change this variable.")
4126 (eval-and-compile
4127 (org-autoload
4128 "org-indent"
4129 '(org-indent-mode)))
4131 ;; Autoload org-mobile.el
4133 (eval-and-compile
4134 (org-autoload
4135 "org-mobile"
4136 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4138 ;; Autoload archiving code
4139 ;; The stuff that is needed for cycling and tags has to be defined here.
4141 (defgroup org-archive nil
4142 "Options concerning archiving in Org-mode."
4143 :tag "Org Archive"
4144 :group 'org-structure)
4146 (defcustom org-archive-location "%s_archive::"
4147 "The location where subtrees should be archived.
4149 The value of this variable is a string, consisting of two parts,
4150 separated by a double-colon. The first part is a filename and
4151 the second part is a headline.
4153 When the filename is omitted, archiving happens in the same file.
4154 %s in the filename will be replaced by the current file
4155 name (without the directory part). Archiving to a different file
4156 is useful to keep archived entries from contributing to the
4157 Org-mode Agenda.
4159 The archived entries will be filed as subtrees of the specified
4160 headline. When the headline is omitted, the subtrees are simply
4161 filed away at the end of the file, as top-level entries. Also in
4162 the heading you can use %s to represent the file name, this can be
4163 useful when using the same archive for a number of different files.
4165 Here are a few examples:
4166 \"%s_archive::\"
4167 If the current file is Projects.org, archive in file
4168 Projects.org_archive, as top-level trees. This is the default.
4170 \"::* Archived Tasks\"
4171 Archive in the current file, under the top-level headline
4172 \"* Archived Tasks\".
4174 \"~/org/archive.org::\"
4175 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4177 \"~/org/archive.org::* From %s\"
4178 Archive in file ~/org/archive.org (absolute path), under headlines
4179 \"From FILENAME\" where file name is the current file name.
4181 \"basement::** Finished Tasks\"
4182 Archive in file ./basement (relative path), as level 3 trees
4183 below the level 2 heading \"** Finished Tasks\".
4185 You may set this option on a per-file basis by adding to the buffer a
4186 line like
4188 #+ARCHIVE: basement::** Finished Tasks
4190 You may also define it locally for a subtree by setting an ARCHIVE property
4191 in the entry. If such a property is found in an entry, or anywhere up
4192 the hierarchy, it will be used."
4193 :group 'org-archive
4194 :type 'string)
4196 (defcustom org-archive-tag "ARCHIVE"
4197 "The tag that marks a subtree as archived.
4198 An archived subtree does not open during visibility cycling, and does
4199 not contribute to the agenda listings.
4200 After changing this, font-lock must be restarted in the relevant buffers to
4201 get the proper fontification."
4202 :group 'org-archive
4203 :group 'org-keywords
4204 :type 'string)
4206 (defcustom org-agenda-skip-archived-trees t
4207 "Non-nil means the agenda will skip any items located in archived trees.
4208 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4209 variable is no longer recommended, you should leave it at the value t.
4210 Instead, use the key `v' to cycle the archives-mode in the agenda."
4211 :group 'org-archive
4212 :group 'org-agenda-skip
4213 :type 'boolean)
4215 (defcustom org-columns-skip-archived-trees t
4216 "Non-nil means ignore archived trees when creating column view."
4217 :group 'org-archive
4218 :group 'org-properties
4219 :type 'boolean)
4221 (defcustom org-cycle-open-archived-trees nil
4222 "Non-nil means `org-cycle' will open archived trees.
4223 An archived tree is a tree marked with the tag ARCHIVE.
4224 When nil, archived trees will stay folded. You can still open them with
4225 normal outline commands like `show-all', but not with the cycling commands."
4226 :group 'org-archive
4227 :group 'org-cycle
4228 :type 'boolean)
4230 (defcustom org-sparse-tree-open-archived-trees nil
4231 "Non-nil means sparse tree construction shows matches in archived trees.
4232 When nil, matches in these trees are highlighted, but the trees are kept in
4233 collapsed state."
4234 :group 'org-archive
4235 :group 'org-sparse-trees
4236 :type 'boolean)
4238 (defun org-cycle-hide-archived-subtrees (state)
4239 "Re-hide all archived subtrees after a visibility state change."
4240 (when (and (not org-cycle-open-archived-trees)
4241 (not (memq state '(overview folded))))
4242 (save-excursion
4243 (let* ((globalp (memq state '(contents all)))
4244 (beg (if globalp (point-min) (point)))
4245 (end (if globalp (point-max) (org-end-of-subtree t))))
4246 (org-hide-archived-subtrees beg end)
4247 (goto-char beg)
4248 (if (looking-at (concat ".*:" org-archive-tag ":"))
4249 (message "%s" (substitute-command-keys
4250 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4252 (defun org-force-cycle-archived ()
4253 "Cycle subtree even if it is archived."
4254 (interactive)
4255 (setq this-command 'org-cycle)
4256 (let ((org-cycle-open-archived-trees t))
4257 (call-interactively 'org-cycle)))
4259 (defun org-hide-archived-subtrees (beg end)
4260 "Re-hide all archived subtrees after a visibility state change."
4261 (save-excursion
4262 (let* ((re (concat ":" org-archive-tag ":")))
4263 (goto-char beg)
4264 (while (re-search-forward re end t)
4265 (when (org-at-heading-p)
4266 (org-flag-subtree t)
4267 (org-end-of-subtree t))))))
4269 (defun org-flag-subtree (flag)
4270 (save-excursion
4271 (org-back-to-heading t)
4272 (outline-end-of-heading)
4273 (outline-flag-region (point)
4274 (progn (org-end-of-subtree t) (point))
4275 flag)))
4277 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4279 (eval-and-compile
4280 (org-autoload "org-archive"
4281 '(org-add-archive-files org-archive-subtree
4282 org-archive-to-archive-sibling org-toggle-archive-tag
4283 org-archive-subtree-default
4284 org-archive-subtree-default-with-confirmation)))
4286 ;; Autoload Column View Code
4288 (declare-function org-columns-number-to-string "org-colview")
4289 (declare-function org-columns-get-format-and-top-level "org-colview")
4290 (declare-function org-columns-compute "org-colview")
4292 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4293 '(org-columns-number-to-string org-columns-get-format-and-top-level
4294 org-columns-compute org-agenda-columns org-columns-remove-overlays
4295 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4297 ;; Autoload ID code
4299 (declare-function org-id-store-link "org-id")
4300 (declare-function org-id-locations-load "org-id")
4301 (declare-function org-id-locations-save "org-id")
4302 (defvar org-id-track-globally)
4303 (org-autoload "org-id"
4304 '(org-id-get-create org-id-new org-id-copy org-id-get
4305 org-id-get-with-outline-path-completion
4306 org-id-get-with-outline-drilling org-id-store-link
4307 org-id-goto org-id-find org-id-store-link))
4309 ;; Autoload Plotting Code
4311 (org-autoload "org-plot"
4312 '(org-plot/gnuplot))
4314 ;;; Variables for pre-computed regular expressions, all buffer local
4316 (defvar org-drawer-regexp nil
4317 "Matches first line of a hidden block.")
4318 (make-variable-buffer-local 'org-drawer-regexp)
4319 (defvar org-todo-regexp nil
4320 "Matches any of the TODO state keywords.")
4321 (make-variable-buffer-local 'org-todo-regexp)
4322 (defvar org-not-done-regexp nil
4323 "Matches any of the TODO state keywords except the last one.")
4324 (make-variable-buffer-local 'org-not-done-regexp)
4325 (defvar org-not-done-heading-regexp nil
4326 "Matches a TODO headline that is not done.")
4327 (make-variable-buffer-local 'org-not-done-regexp)
4328 (defvar org-todo-line-regexp nil
4329 "Matches a headline and puts TODO state into group 2 if present.")
4330 (make-variable-buffer-local 'org-todo-line-regexp)
4331 (defvar org-complex-heading-regexp nil
4332 "Matches a headline and puts everything into groups:
4333 group 1: the stars
4334 group 2: The todo keyword, maybe
4335 group 3: Priority cookie
4336 group 4: True headline
4337 group 5: Tags")
4338 (make-variable-buffer-local 'org-complex-heading-regexp)
4339 (defvar org-complex-heading-regexp-format nil
4340 "Printf format to make regexp to match an exact headline.
4341 This regexp will match the headline of any node which has the
4342 exact headline text that is put into the format, but may have any
4343 TODO state, priority and tags.")
4344 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4345 (defvar org-todo-line-tags-regexp nil
4346 "Matches a headline and puts TODO state into group 2 if present.
4347 Also put tags into group 4 if tags are present.")
4348 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4349 (defvar org-ds-keyword-length 12
4350 "Maximum length of the Deadline and SCHEDULED keywords.")
4351 (make-variable-buffer-local 'org-ds-keyword-length)
4352 (defvar org-deadline-regexp nil
4353 "Matches the DEADLINE keyword.")
4354 (make-variable-buffer-local 'org-deadline-regexp)
4355 (defvar org-deadline-time-regexp nil
4356 "Matches the DEADLINE keyword together with a time stamp.")
4357 (make-variable-buffer-local 'org-deadline-time-regexp)
4358 (defvar org-deadline-line-regexp nil
4359 "Matches the DEADLINE keyword and the rest of the line.")
4360 (make-variable-buffer-local 'org-deadline-line-regexp)
4361 (defvar org-scheduled-regexp nil
4362 "Matches the SCHEDULED keyword.")
4363 (make-variable-buffer-local 'org-scheduled-regexp)
4364 (defvar org-scheduled-time-regexp nil
4365 "Matches the SCHEDULED keyword together with a time stamp.")
4366 (make-variable-buffer-local 'org-scheduled-time-regexp)
4367 (defvar org-closed-time-regexp nil
4368 "Matches the CLOSED keyword together with a time stamp.")
4369 (make-variable-buffer-local 'org-closed-time-regexp)
4371 (defvar org-keyword-time-regexp nil
4372 "Matches any of the 4 keywords, together with the time stamp.")
4373 (make-variable-buffer-local 'org-keyword-time-regexp)
4374 (defvar org-keyword-time-not-clock-regexp nil
4375 "Matches any of the 3 keywords, together with the time stamp.")
4376 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4377 (defvar org-maybe-keyword-time-regexp nil
4378 "Matches a timestamp, possibly preceded by a keyword.")
4379 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4380 (defvar org-planning-or-clock-line-re nil
4381 "Matches a line with planning or clock info.")
4382 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4383 (defvar org-all-time-keywords nil
4384 "List of time keywords.")
4385 (make-variable-buffer-local 'org-all-time-keywords)
4387 (defconst org-plain-time-of-day-regexp
4388 (concat
4389 "\\(\\<[012]?[0-9]"
4390 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4391 "\\(--?"
4392 "\\(\\<[012]?[0-9]"
4393 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4394 "\\)?")
4395 "Regular expression to match a plain time or time range.
4396 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4397 groups carry important information:
4398 0 the full match
4399 1 the first time, range or not
4400 8 the second time, if it is a range.")
4402 (defconst org-plain-time-extension-regexp
4403 (concat
4404 "\\(\\<[012]?[0-9]"
4405 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4406 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4407 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4408 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4409 groups carry important information:
4410 0 the full match
4411 7 hours of duration
4412 9 minutes of duration")
4414 (defconst org-stamp-time-of-day-regexp
4415 (concat
4416 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4417 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4418 "\\(--?"
4419 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4420 "Regular expression to match a timestamp time or time range.
4421 After a match, the following groups carry important information:
4422 0 the full match
4423 1 date plus weekday, for back referencing to make sure both times are on the same day
4424 2 the first time, range or not
4425 4 the second time, if it is a range.")
4427 (defconst org-startup-options
4428 '(("fold" org-startup-folded t)
4429 ("overview" org-startup-folded t)
4430 ("nofold" org-startup-folded nil)
4431 ("showall" org-startup-folded nil)
4432 ("showeverything" org-startup-folded showeverything)
4433 ("content" org-startup-folded content)
4434 ("indent" org-startup-indented t)
4435 ("noindent" org-startup-indented nil)
4436 ("hidestars" org-hide-leading-stars t)
4437 ("showstars" org-hide-leading-stars nil)
4438 ("odd" org-odd-levels-only t)
4439 ("oddeven" org-odd-levels-only nil)
4440 ("align" org-startup-align-all-tables t)
4441 ("noalign" org-startup-align-all-tables nil)
4442 ("inlineimages" org-startup-with-inline-images t)
4443 ("noinlineimages" org-startup-with-inline-images nil)
4444 ("customtime" org-display-custom-times t)
4445 ("logdone" org-log-done time)
4446 ("lognotedone" org-log-done note)
4447 ("nologdone" org-log-done nil)
4448 ("lognoteclock-out" org-log-note-clock-out t)
4449 ("nolognoteclock-out" org-log-note-clock-out nil)
4450 ("logrepeat" org-log-repeat state)
4451 ("lognoterepeat" org-log-repeat note)
4452 ("nologrepeat" org-log-repeat nil)
4453 ("logreschedule" org-log-reschedule time)
4454 ("lognotereschedule" org-log-reschedule note)
4455 ("nologreschedule" org-log-reschedule nil)
4456 ("logredeadline" org-log-redeadline time)
4457 ("lognoteredeadline" org-log-redeadline note)
4458 ("nologredeadline" org-log-redeadline nil)
4459 ("logrefile" org-log-refile time)
4460 ("lognoterefile" org-log-refile note)
4461 ("nologrefile" org-log-refile nil)
4462 ("fninline" org-footnote-define-inline t)
4463 ("nofninline" org-footnote-define-inline nil)
4464 ("fnlocal" org-footnote-section nil)
4465 ("fnauto" org-footnote-auto-label t)
4466 ("fnprompt" org-footnote-auto-label nil)
4467 ("fnconfirm" org-footnote-auto-label confirm)
4468 ("fnplain" org-footnote-auto-label plain)
4469 ("fnadjust" org-footnote-auto-adjust t)
4470 ("nofnadjust" org-footnote-auto-adjust nil)
4471 ("constcgs" constants-unit-system cgs)
4472 ("constSI" constants-unit-system SI)
4473 ("noptag" org-tag-persistent-alist nil)
4474 ("hideblocks" org-hide-block-startup t)
4475 ("nohideblocks" org-hide-block-startup nil)
4476 ("beamer" org-startup-with-beamer-mode t)
4477 ("entitiespretty" org-pretty-entities t)
4478 ("entitiesplain" org-pretty-entities nil))
4479 "Variable associated with STARTUP options for org-mode.
4480 Each element is a list of three items: The startup options as written
4481 in the #+STARTUP line, the corresponding variable, and the value to
4482 set this variable to if the option is found. An optional forth element PUSH
4483 means to push this value onto the list in the variable.")
4485 (defun org-update-property-plist (key val props)
4486 "Update PROPS with KEY and VAL."
4487 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4488 (key (if appending (substring key 0 (- (length key) 1)) key))
4489 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4490 (previous (cdr (assoc key props))))
4491 (if appending
4492 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4493 (cons (cons key val) remainder))))
4495 (defconst org-block-regexp
4496 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4497 "Regular expression for hiding blocks.")
4498 (defconst org-heading-keyword-regexp-format
4499 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4500 "Printf format for a regexp matching an headline with some keyword.
4501 This regexp will match the headline of any node which has the
4502 exact keyword that is put into the format. The keyword isn't in
4503 any group by default, but the stars and the body are.")
4504 (defconst org-heading-keyword-maybe-regexp-format
4505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4506 "Printf format for a regexp matching an headline, possibly with some keyword.
4507 This regexp can match any headline with the specified keyword, or
4508 without a keyword. The keyword isn't in any group by default,
4509 but the stars and the body are.")
4511 (defun org-set-regexps-and-options ()
4512 "Precompute regular expressions for current buffer."
4513 (when (eq major-mode 'org-mode)
4514 (org-set-local 'org-todo-kwd-alist nil)
4515 (org-set-local 'org-todo-key-alist nil)
4516 (org-set-local 'org-todo-key-trigger nil)
4517 (org-set-local 'org-todo-keywords-1 nil)
4518 (org-set-local 'org-done-keywords nil)
4519 (org-set-local 'org-todo-heads nil)
4520 (org-set-local 'org-todo-sets nil)
4521 (org-set-local 'org-todo-log-states nil)
4522 (org-set-local 'org-file-properties nil)
4523 (org-set-local 'org-file-tags nil)
4524 (let ((re (org-make-options-regexp
4525 '("CATEGORY" "TODO" "COLUMNS"
4526 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4527 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4528 "OPTIONS")
4529 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4530 (splitre "[ \t]+")
4531 (scripts org-use-sub-superscripts)
4532 kwds kws0 kwsa key log value cat arch tags const links hw dws
4533 tail sep kws1 prio props ftags drawers beamer-p
4534 ext-setup-or-nil setup-contents (start 0))
4535 (save-excursion
4536 (save-restriction
4537 (widen)
4538 (goto-char (point-min))
4539 (while (or (and ext-setup-or-nil
4540 (string-match re ext-setup-or-nil start)
4541 (setq start (match-end 0)))
4542 (and (setq ext-setup-or-nil nil start 0)
4543 (re-search-forward re nil t)))
4544 (setq key (upcase (match-string 1 ext-setup-or-nil))
4545 value (org-match-string-no-properties 2 ext-setup-or-nil))
4546 (if (stringp value) (setq value (org-trim value)))
4547 (cond
4548 ((equal key "CATEGORY")
4549 (setq cat value))
4550 ((member key '("SEQ_TODO" "TODO"))
4551 (push (cons 'sequence (org-split-string value splitre)) kwds))
4552 ((equal key "TYP_TODO")
4553 (push (cons 'type (org-split-string value splitre)) kwds))
4554 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4555 ;; general TODO-like setup
4556 (push (cons (intern (downcase (match-string 1 key)))
4557 (org-split-string value splitre)) kwds))
4558 ((equal key "TAGS")
4559 (setq tags (append tags (if tags '("\\n") nil)
4560 (org-split-string value splitre))))
4561 ((equal key "COLUMNS")
4562 (org-set-local 'org-columns-default-format value))
4563 ((equal key "LINK")
4564 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4565 (push (cons (match-string 1 value)
4566 (org-trim (match-string 2 value)))
4567 links)))
4568 ((equal key "PRIORITIES")
4569 (setq prio (org-split-string value " +")))
4570 ((equal key "PROPERTY")
4571 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4572 (setq props (org-update-property-plist (match-string 1 value)
4573 (match-string 2 value)
4574 props))))
4575 ((equal key "FILETAGS")
4576 (when (string-match "\\S-" value)
4577 (setq ftags
4578 (append
4579 ftags
4580 (apply 'append
4581 (mapcar (lambda (x) (org-split-string x ":"))
4582 (org-split-string value)))))))
4583 ((equal key "DRAWERS")
4584 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4585 ((equal key "CONSTANTS")
4586 (setq const (append const (org-split-string value splitre))))
4587 ((equal key "STARTUP")
4588 (let ((opts (org-split-string value splitre))
4589 l var val)
4590 (while (setq l (pop opts))
4591 (when (setq l (assoc l org-startup-options))
4592 (setq var (nth 1 l) val (nth 2 l))
4593 (if (not (nth 3 l))
4594 (set (make-local-variable var) val)
4595 (if (not (listp (symbol-value var)))
4596 (set (make-local-variable var) nil))
4597 (set (make-local-variable var) (symbol-value var))
4598 (add-to-list var val))))))
4599 ((equal key "ARCHIVE")
4600 (setq arch value)
4601 (remove-text-properties 0 (length arch)
4602 '(face t fontified t) arch))
4603 ((equal key "LATEX_CLASS")
4604 (setq beamer-p (equal value "beamer")))
4605 ((equal key "OPTIONS")
4606 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4607 (setq scripts (read (match-string 2 value)))))
4608 ((equal key "SETUPFILE")
4609 (setq setup-contents (org-file-contents
4610 (expand-file-name
4611 (org-remove-double-quotes value))
4612 'noerror))
4613 (if (not ext-setup-or-nil)
4614 (setq ext-setup-or-nil setup-contents start 0)
4615 (setq ext-setup-or-nil
4616 (concat (substring ext-setup-or-nil 0 start)
4617 "\n" setup-contents "\n"
4618 (substring ext-setup-or-nil start)))))))
4619 ;; search for property blocks
4620 (goto-char (point-min))
4621 (while (re-search-forward org-block-regexp nil t)
4622 (when (equal "PROPERTY" (upcase (match-string 1)))
4623 (setq value (replace-regexp-in-string
4624 "[\n\r]" " " (match-string 4)))
4625 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4626 (setq props (org-update-property-plist (match-string 1 value)
4627 (match-string 2 value)
4628 props)))))))
4629 (org-set-local 'org-use-sub-superscripts scripts)
4630 (when cat
4631 (org-set-local 'org-category (intern cat))
4632 (push (cons "CATEGORY" cat) props))
4633 (when prio
4634 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4635 (setq prio (mapcar 'string-to-char prio))
4636 (org-set-local 'org-highest-priority (nth 0 prio))
4637 (org-set-local 'org-lowest-priority (nth 1 prio))
4638 (org-set-local 'org-default-priority (nth 2 prio)))
4639 (and props (org-set-local 'org-file-properties (nreverse props)))
4640 (and ftags (org-set-local 'org-file-tags
4641 (mapcar 'org-add-prop-inherited ftags)))
4642 (and drawers (org-set-local 'org-drawers drawers))
4643 (and arch (org-set-local 'org-archive-location arch))
4644 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4645 ;; Process the TODO keywords
4646 (unless kwds
4647 ;; Use the global values as if they had been given locally.
4648 (setq kwds (default-value 'org-todo-keywords))
4649 (if (stringp (car kwds))
4650 (setq kwds (list (cons org-todo-interpretation
4651 (default-value 'org-todo-keywords)))))
4652 (setq kwds (reverse kwds)))
4653 (setq kwds (nreverse kwds))
4654 (let (inter kws kw)
4655 (while (setq kws (pop kwds))
4656 (let ((kws (or
4657 (run-hook-with-args-until-success
4658 'org-todo-setup-filter-hook kws)
4659 kws)))
4660 (setq inter (pop kws) sep (member "|" kws)
4661 kws0 (delete "|" (copy-sequence kws))
4662 kwsa nil
4663 kws1 (mapcar
4664 (lambda (x)
4665 ;; 1 2
4666 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4667 (progn
4668 (setq kw (match-string 1 x)
4669 key (and (match-end 2) (match-string 2 x))
4670 log (org-extract-log-state-settings x))
4671 (push (cons kw (and key (string-to-char key))) kwsa)
4672 (and log (push log org-todo-log-states))
4674 (error "Invalid TODO keyword %s" x)))
4675 kws0)
4676 kwsa (if kwsa (append '((:startgroup))
4677 (nreverse kwsa)
4678 '((:endgroup))))
4679 hw (car kws1)
4680 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4681 tail (list inter hw (car dws) (org-last dws))))
4682 (add-to-list 'org-todo-heads hw 'append)
4683 (push kws1 org-todo-sets)
4684 (setq org-done-keywords (append org-done-keywords dws nil))
4685 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4686 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4687 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4688 (setq org-todo-sets (nreverse org-todo-sets)
4689 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4690 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4691 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4692 ;; Process the constants
4693 (when const
4694 (let (e cst)
4695 (while (setq e (pop const))
4696 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4697 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4698 (setq org-table-formula-constants-local cst)))
4700 ;; Process the tags.
4701 (when tags
4702 (let (e tgs)
4703 (while (setq e (pop tags))
4704 (cond
4705 ((equal e "{") (push '(:startgroup) tgs))
4706 ((equal e "}") (push '(:endgroup) tgs))
4707 ((equal e "\\n") (push '(:newline) tgs))
4708 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4709 (push (cons (match-string 1 e)
4710 (string-to-char (match-string 2 e)))
4711 tgs))
4712 (t (push (list e) tgs))))
4713 (org-set-local 'org-tag-alist nil)
4714 (while (setq e (pop tgs))
4715 (or (and (stringp (car e))
4716 (assoc (car e) org-tag-alist))
4717 (push e org-tag-alist)))))
4719 ;; Compute the regular expressions and other local variables.
4720 ;; Using `org-outline-regexp-bol' would complicate them much,
4721 ;; because of the fixed white space at the end of that string.
4722 (if (not org-done-keywords)
4723 (setq org-done-keywords (and org-todo-keywords-1
4724 (list (org-last org-todo-keywords-1)))))
4725 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4726 (length org-scheduled-string)
4727 (length org-clock-string)
4728 (length org-closed-string)))
4729 org-drawer-regexp
4730 (concat "^[ \t]*:\\("
4731 (mapconcat 'regexp-quote org-drawers "\\|")
4732 "\\):[ \t]*$")
4733 org-not-done-keywords
4734 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4735 org-todo-regexp
4736 (concat "\\("
4737 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4738 "\\)")
4739 org-not-done-regexp
4740 (concat "\\("
4741 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4742 "\\)")
4743 org-not-done-heading-regexp
4744 (format org-heading-keyword-regexp-format org-not-done-regexp)
4745 org-todo-line-regexp
4746 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4747 org-complex-heading-regexp
4748 (concat "^\\(\\*+\\)"
4749 "\\(?: +" org-todo-regexp "\\)?"
4750 "\\(?: +\\(\\[#.\\]\\)\\)?"
4751 "\\(?: +\\(.*?\\)\\)?"
4752 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4753 "[ \t]*$")
4754 org-complex-heading-regexp-format
4755 (concat "^\\(\\*+\\)"
4756 "\\(?: +" org-todo-regexp "\\)?"
4757 "\\(?: +\\(\\[#.\\]\\)\\)?"
4758 "\\(?: +"
4759 ;; Stats cookies can be stuck to body.
4760 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4761 "\\(%s\\)"
4762 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4763 "\\)"
4764 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4765 "[ \t]*$")
4766 org-todo-line-tags-regexp
4767 (concat "^\\(\\*+\\)"
4768 "\\(?: +" org-todo-regexp "\\)?"
4769 "\\(?: +\\(.*?\\)\\)?"
4770 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4771 "[ \t]*$")
4772 org-deadline-regexp (concat "\\<" org-deadline-string)
4773 org-deadline-time-regexp
4774 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4775 org-deadline-line-regexp
4776 (concat "\\<\\(" org-deadline-string "\\).*")
4777 org-scheduled-regexp
4778 (concat "\\<" org-scheduled-string)
4779 org-scheduled-time-regexp
4780 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4781 org-closed-time-regexp
4782 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4783 org-keyword-time-regexp
4784 (concat "\\<\\(" org-scheduled-string
4785 "\\|" org-deadline-string
4786 "\\|" org-closed-string
4787 "\\|" org-clock-string "\\)"
4788 " *[[<]\\([^]>]+\\)[]>]")
4789 org-keyword-time-not-clock-regexp
4790 (concat "\\<\\(" org-scheduled-string
4791 "\\|" org-deadline-string
4792 "\\|" org-closed-string
4793 "\\)"
4794 " *[[<]\\([^]>]+\\)[]>]")
4795 org-maybe-keyword-time-regexp
4796 (concat "\\(\\<\\(" org-scheduled-string
4797 "\\|" org-deadline-string
4798 "\\|" org-closed-string
4799 "\\|" org-clock-string "\\)\\)?"
4800 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4801 org-planning-or-clock-line-re
4802 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4803 "\\|" org-deadline-string
4804 "\\|" org-closed-string "\\|" org-clock-string
4805 "\\)\\>\\)")
4806 org-all-time-keywords
4807 (mapcar (lambda (w) (substring w 0 -1))
4808 (list org-scheduled-string org-deadline-string
4809 org-clock-string org-closed-string))
4811 (org-compute-latex-and-specials-regexp)
4812 (org-set-font-lock-defaults))))
4814 (defun org-file-contents (file &optional noerror)
4815 "Return the contents of FILE, as a string."
4816 (if (or (not file)
4817 (not (file-readable-p file)))
4818 (if noerror
4819 (progn
4820 (message "Cannot read file \"%s\"" file)
4821 (ding) (sit-for 2)
4823 (error "Cannot read file \"%s\"" file))
4824 (with-temp-buffer
4825 (insert-file-contents file)
4826 (buffer-string))))
4828 (defun org-extract-log-state-settings (x)
4829 "Extract the log state setting from a TODO keyword string.
4830 This will extract info from a string like \"WAIT(w@/!)\"."
4831 (let (kw key log1 log2)
4832 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4833 (setq kw (match-string 1 x)
4834 key (and (match-end 2) (match-string 2 x))
4835 log1 (and (match-end 3) (match-string 3 x))
4836 log2 (and (match-end 4) (match-string 4 x)))
4837 (and (or log1 log2)
4838 (list kw
4839 (and log1 (if (equal log1 "!") 'time 'note))
4840 (and log2 (if (equal log2 "!") 'time 'note)))))))
4842 (defun org-remove-keyword-keys (list)
4843 "Remove a pair of parenthesis at the end of each string in LIST."
4844 (mapcar (lambda (x)
4845 (if (string-match "(.*)$" x)
4846 (substring x 0 (match-beginning 0))
4848 list))
4850 (defun org-assign-fast-keys (alist)
4851 "Assign fast keys to a keyword-key alist.
4852 Respect keys that are already there."
4853 (let (new e (alt ?0))
4854 (while (setq e (pop alist))
4855 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4856 (cdr e)) ;; Key already assigned.
4857 (push e new)
4858 (let ((clist (string-to-list (downcase (car e))))
4859 (used (append new alist)))
4860 (when (= (car clist) ?@)
4861 (pop clist))
4862 (while (and clist (rassoc (car clist) used))
4863 (pop clist))
4864 (unless clist
4865 (while (rassoc alt used)
4866 (incf alt)))
4867 (push (cons (car e) (or (car clist) alt)) new))))
4868 (nreverse new)))
4870 ;;; Some variables used in various places
4872 (defvar org-window-configuration nil
4873 "Used in various places to store a window configuration.")
4874 (defvar org-selected-window nil
4875 "Used in various places to store a window configuration.")
4876 (defvar org-finish-function nil
4877 "Function to be called when `C-c C-c' is used.
4878 This is for getting out of special buffers like remember.")
4881 ;; FIXME: Occasionally check by commenting these, to make sure
4882 ;; no other functions uses these, forgetting to let-bind them.
4883 (defvar entry)
4884 (defvar last-state)
4885 (defvar date)
4887 ;; Defined somewhere in this file, but used before definition.
4888 (defvar org-entities) ;; defined in org-entities.el
4889 (defvar org-struct-menu)
4890 (defvar org-org-menu)
4891 (defvar org-tbl-menu)
4893 ;;;; Define the Org-mode
4895 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4896 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4899 ;; We use a before-change function to check if a table might need
4900 ;; an update.
4901 (defvar org-table-may-need-update t
4902 "Indicates that a table might need an update.
4903 This variable is set by `org-before-change-function'.
4904 `org-table-align' sets it back to nil.")
4905 (defun org-before-change-function (beg end)
4906 "Every change indicates that a table might need an update."
4907 (setq org-table-may-need-update t))
4908 (defvar org-mode-map)
4909 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4910 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4911 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4912 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4913 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4914 (defvar org-table-buffer-is-an nil)
4916 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4917 ;; some places -- e.g. see the macro org-with-limited-levels.
4919 ;; In Org buffers, the value of `outline-regexp' is that of
4920 ;; `org-outline-regexp'. The only function still directly relying on
4921 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4922 ;; job when `orgstruct-mode' is active.
4923 (defvar org-outline-regexp "\\*+ "
4924 "Regexp to match Org headlines.")
4925 (defconst org-outline-regexp-bol "^\\*+ "
4926 "Regexp to match Org headlines.
4927 This is similar to `org-outline-regexp' but additionally makes
4928 sure that we are at the beginning of the line.")
4930 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4931 "Matches an headline, putting stars and text into groups.
4932 Stars are put in group 1 and the trimmed body in group 2.")
4934 (defvar bidi-paragraph-direction)
4936 ;;;###autoload
4937 (define-derived-mode org-mode outline-mode "Org"
4938 "Outline-based notes management and organizer, alias
4939 \"Carsten's outline-mode for keeping track of everything.\"
4941 Org-mode develops organizational tasks around a NOTES file which
4942 contains information about projects as plain text. Org-mode is
4943 implemented on top of outline-mode, which is ideal to keep the content
4944 of large files well structured. It supports ToDo items, deadlines and
4945 time stamps, which magically appear in the diary listing of the Emacs
4946 calendar. Tables are easily created with a built-in table editor.
4947 Plain text URL-like links connect to websites, emails (VM), Usenet
4948 messages (Gnus), BBDB entries, and any files related to the project.
4949 For printing and sharing of notes, an Org-mode file (or a part of it)
4950 can be exported as a structured ASCII or HTML file.
4952 The following commands are available:
4954 \\{org-mode-map}"
4956 ;; Get rid of Outline menus, they are not needed
4957 ;; Need to do this here because define-derived-mode sets up
4958 ;; the keymap so late. Still, it is a waste to call this each time
4959 ;; we switch another buffer into org-mode.
4960 (if (featurep 'xemacs)
4961 (when (boundp 'outline-mode-menu-heading)
4962 ;; Assume this is Greg's port, it uses easymenu
4963 (easy-menu-remove outline-mode-menu-heading)
4964 (easy-menu-remove outline-mode-menu-show)
4965 (easy-menu-remove outline-mode-menu-hide))
4966 (define-key org-mode-map [menu-bar headings] 'undefined)
4967 (define-key org-mode-map [menu-bar hide] 'undefined)
4968 (define-key org-mode-map [menu-bar show] 'undefined))
4970 (org-load-modules-maybe)
4971 (easy-menu-add org-org-menu)
4972 (easy-menu-add org-tbl-menu)
4973 (org-install-agenda-files-menu)
4974 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4975 (add-to-invisibility-spec '(org-cwidth))
4976 (add-to-invisibility-spec '(org-hide-block . t))
4977 (when (featurep 'xemacs)
4978 (org-set-local 'line-move-ignore-invisible t))
4979 (org-set-local 'outline-regexp org-outline-regexp)
4980 (org-set-local 'outline-level 'org-outline-level)
4981 (setq bidi-paragraph-direction 'left-to-right)
4982 (when (and org-ellipsis
4983 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4984 (fboundp 'make-glyph-code))
4985 (unless org-display-table
4986 (setq org-display-table (make-display-table)))
4987 (set-display-table-slot
4988 org-display-table 4
4989 (vconcat (mapcar
4990 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4991 org-ellipsis)))
4992 (if (stringp org-ellipsis) org-ellipsis "..."))))
4993 (setq buffer-display-table org-display-table))
4994 (org-set-regexps-and-options)
4995 (when (and org-tag-faces (not org-tags-special-faces-re))
4996 ;; tag faces set outside customize.... force initialization.
4997 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4998 ;; Calc embedded
4999 (org-set-local 'calc-embedded-open-mode "# ")
5000 (modify-syntax-entry ?@ "w")
5001 (if org-startup-truncated (setq truncate-lines t))
5002 (org-set-local 'font-lock-unfontify-region-function
5003 'org-unfontify-region)
5004 ;; Activate before-change-function
5005 (org-set-local 'org-table-may-need-update t)
5006 (org-add-hook 'before-change-functions 'org-before-change-function nil
5007 'local)
5008 ;; Check for running clock before killing a buffer
5009 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5010 ;; Paragraphs and auto-filling
5011 (org-set-autofill-regexps)
5012 (setq indent-line-function 'org-indent-line-function)
5013 (org-update-radio-target-regexp)
5014 ;; Beginning/end of defun
5015 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5016 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5017 ;; Next error for sparse trees
5018 (org-set-local 'next-error-function 'org-occur-next-match)
5019 ;; Make sure dependence stuff works reliably, even for users who set it
5020 ;; too late :-(
5021 (if org-enforce-todo-dependencies
5022 (add-hook 'org-blocker-hook
5023 'org-block-todo-from-children-or-siblings-or-parent)
5024 (remove-hook 'org-blocker-hook
5025 'org-block-todo-from-children-or-siblings-or-parent))
5026 (if org-enforce-todo-checkbox-dependencies
5027 (add-hook 'org-blocker-hook
5028 'org-block-todo-from-checkboxes)
5029 (remove-hook 'org-blocker-hook
5030 'org-block-todo-from-checkboxes))
5032 ;; Comment characters
5033 (org-set-local 'comment-start "#")
5034 (org-set-local 'comment-padding " ")
5036 ;; Align options lines
5037 (org-set-local
5038 'align-mode-rules-list
5039 '((org-in-buffer-settings
5040 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5041 (modes . '(org-mode)))))
5043 ;; Imenu
5044 (org-set-local 'imenu-create-index-function
5045 'org-imenu-get-tree)
5047 ;; Make isearch reveal context
5048 (if (or (featurep 'xemacs)
5049 (not (boundp 'outline-isearch-open-invisible-function)))
5050 ;; Emacs 21 and XEmacs make use of the hook
5051 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5052 ;; Emacs 22 deals with this through a special variable
5053 (org-set-local 'outline-isearch-open-invisible-function
5054 (lambda (&rest ignore) (org-show-context 'isearch))))
5056 ;; Turn on org-beamer-mode?
5057 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5059 ;; Setup the pcomplete hooks
5060 (set (make-local-variable 'pcomplete-command-completion-function)
5061 'org-pcomplete-initial)
5062 (set (make-local-variable 'pcomplete-command-name-function)
5063 'org-command-at-point)
5064 (set (make-local-variable 'pcomplete-default-completion-function)
5065 'ignore)
5066 (set (make-local-variable 'pcomplete-parse-arguments-function)
5067 'org-parse-arguments)
5068 (set (make-local-variable 'pcomplete-termination-string) "")
5069 (set (make-local-variable 'face-remapping-alist)
5070 '((default org-default)))
5072 ;; If empty file that did not turn on org-mode automatically, make it to.
5073 (if (and org-insert-mode-line-in-empty-file
5074 (org-called-interactively-p 'any)
5075 (= (point-min) (point-max)))
5076 (insert "# -*- mode: org -*-\n\n"))
5077 (unless org-inhibit-startup
5078 (when org-startup-align-all-tables
5079 (let ((bmp (buffer-modified-p)))
5080 (org-table-map-tables 'org-table-align 'quietly)
5081 (set-buffer-modified-p bmp)))
5082 (when org-startup-with-inline-images
5083 (org-display-inline-images))
5084 (when org-startup-indented
5085 (require 'org-indent)
5086 (org-indent-mode 1))
5087 (unless org-inhibit-startup-visibility-stuff
5088 (org-set-startup-visibility))))
5090 (when (fboundp 'abbrev-table-put)
5091 (abbrev-table-put org-mode-abbrev-table
5092 :parents (list text-mode-abbrev-table)))
5094 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5096 (defun org-current-time ()
5097 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5098 (if (> (car org-time-stamp-rounding-minutes) 1)
5099 (let ((r (car org-time-stamp-rounding-minutes))
5100 (time (decode-time)))
5101 (apply 'encode-time
5102 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5103 (nthcdr 2 time))))
5104 (current-time)))
5106 (defun org-today ()
5107 "Return today date, considering `org-extend-today-until'."
5108 (time-to-days
5109 (time-subtract (current-time)
5110 (list 0 (* 3600 org-extend-today-until) 0))))
5112 ;;;; Font-Lock stuff, including the activators
5114 (defvar org-mouse-map (make-sparse-keymap))
5115 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5116 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5117 (when org-mouse-1-follows-link
5118 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5119 (when org-tab-follows-link
5120 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5121 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5123 (require 'font-lock)
5125 (defconst org-non-link-chars "]\t\n\r<>")
5126 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5127 "shell" "elisp" "doi" "message"))
5128 (defvar org-link-types-re nil
5129 "Matches a link that has a url-like prefix like \"http:\"")
5130 (defvar org-link-re-with-space nil
5131 "Matches a link with spaces, optional angular brackets around it.")
5132 (defvar org-link-re-with-space2 nil
5133 "Matches a link with spaces, optional angular brackets around it.")
5134 (defvar org-link-re-with-space3 nil
5135 "Matches a link with spaces, only for internal part in bracket links.")
5136 (defvar org-angle-link-re nil
5137 "Matches link with angular brackets, spaces are allowed.")
5138 (defvar org-plain-link-re nil
5139 "Matches plain link, without spaces.")
5140 (defvar org-bracket-link-regexp nil
5141 "Matches a link in double brackets.")
5142 (defvar org-bracket-link-analytic-regexp nil
5143 "Regular expression used to analyze links.
5144 Here is what the match groups contain after a match:
5145 1: http:
5146 2: http
5147 3: path
5148 4: [desc]
5149 5: desc")
5150 (defvar org-bracket-link-analytic-regexp++ nil
5151 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5152 (defvar org-any-link-re nil
5153 "Regular expression matching any link.")
5155 (defcustom org-match-sexp-depth 3
5156 "Number of stacked braces for sub/superscript matching.
5157 This has to be set before loading org.el to be effective."
5158 :group 'org-export-translation ; ??????????????????????????/
5159 :type 'integer)
5161 (defun org-create-multibrace-regexp (left right n)
5162 "Create a regular expression which will match a balanced sexp.
5163 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5164 as single character strings.
5165 The regexp returned will match the entire expression including the
5166 delimiters. It will also define a single group which contains the
5167 match except for the outermost delimiters. The maximum depth of
5168 stacked delimiters is N. Escaping delimiters is not possible."
5169 (let* ((nothing (concat "[^" left right "]*?"))
5170 (or "\\|")
5171 (re nothing)
5172 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5173 (while (> n 1)
5174 (setq n (1- n)
5175 re (concat re or next)
5176 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5177 (concat left "\\(" re "\\)" right)))
5179 (defvar org-match-substring-regexp
5180 (concat
5181 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5182 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5183 "\\|"
5184 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5185 "\\|"
5186 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5187 "The regular expression matching a sub- or superscript.")
5189 (defvar org-match-substring-with-braces-regexp
5190 (concat
5191 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5192 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5193 "\\)")
5194 "The regular expression matching a sub- or superscript, forcing braces.")
5196 (defun org-make-link-regexps ()
5197 "Update the link regular expressions.
5198 This should be called after the variable `org-link-types' has changed."
5199 (setq org-link-types-re
5200 (concat
5201 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5202 org-link-re-with-space
5203 (concat
5204 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5205 "\\([^" org-non-link-chars " ]"
5206 "[^" org-non-link-chars "]*"
5207 "[^" org-non-link-chars " ]\\)>?")
5208 org-link-re-with-space2
5209 (concat
5210 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5211 "\\([^" org-non-link-chars " ]"
5212 "[^\t\n\r]*"
5213 "[^" org-non-link-chars " ]\\)>?")
5214 org-link-re-with-space3
5215 (concat
5216 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5217 "\\([^" org-non-link-chars " ]"
5218 "[^\t\n\r]*\\)")
5219 org-angle-link-re
5220 (concat
5221 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5222 "\\([^" org-non-link-chars " ]"
5223 "[^" org-non-link-chars "]*"
5224 "\\)>")
5225 org-plain-link-re
5226 (concat
5227 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5228 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5229 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5230 org-bracket-link-regexp
5231 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5232 org-bracket-link-analytic-regexp
5233 (concat
5234 "\\[\\["
5235 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5236 "\\([^]]+\\)"
5237 "\\]"
5238 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5239 "\\]")
5240 org-bracket-link-analytic-regexp++
5241 (concat
5242 "\\[\\["
5243 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5244 "\\([^]]+\\)"
5245 "\\]"
5246 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5247 "\\]")
5248 org-any-link-re
5249 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5250 org-angle-link-re "\\)\\|\\("
5251 org-plain-link-re "\\)")))
5253 (org-make-link-regexps)
5255 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5256 "Regular expression for fast time stamp matching.")
5257 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5258 "Regular expression for fast time stamp matching.")
5259 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5260 "Regular expression matching time strings for analysis.
5261 This one does not require the space after the date, so it can be used
5262 on a string that terminates immediately after the date.")
5263 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5264 "Regular expression matching time strings for analysis.")
5265 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5266 "Regular expression matching time stamps, with groups.")
5267 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5268 "Regular expression matching time stamps (also [..]), with groups.")
5269 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5270 "Regular expression matching a time stamp range.")
5271 (defconst org-tr-regexp-both
5272 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5273 "Regular expression matching a time stamp range.")
5274 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5275 org-ts-regexp "\\)?")
5276 "Regular expression matching a time stamp or time stamp range.")
5277 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5278 org-ts-regexp-both "\\)?")
5279 "Regular expression matching a time stamp or time stamp range.
5280 The time stamps may be either active or inactive.")
5282 (defvar org-emph-face nil)
5284 (defun org-do-emphasis-faces (limit)
5285 "Run through the buffer and add overlays to emphasized strings."
5286 (let (rtn a)
5287 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5288 (if (not (= (char-after (match-beginning 3))
5289 (char-after (match-beginning 4))))
5290 (progn
5291 (setq rtn t)
5292 (setq a (assoc (match-string 3) org-emphasis-alist))
5293 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5294 'face
5295 (nth 1 a))
5296 (and (nth 4 a)
5297 (org-remove-flyspell-overlays-in
5298 (match-beginning 0) (match-end 0)))
5299 (add-text-properties (match-beginning 2) (match-end 2)
5300 '(font-lock-multiline t org-emphasis t))
5301 (when org-hide-emphasis-markers
5302 (add-text-properties (match-end 4) (match-beginning 5)
5303 '(invisible org-link))
5304 (add-text-properties (match-beginning 3) (match-end 3)
5305 '(invisible org-link)))))
5306 (backward-char 1))
5307 rtn))
5309 (defun org-emphasize (&optional char)
5310 "Insert or change an emphasis, i.e. a font like bold or italic.
5311 If there is an active region, change that region to a new emphasis.
5312 If there is no region, just insert the marker characters and position
5313 the cursor between them.
5314 CHAR should be either the marker character, or the first character of the
5315 HTML tag associated with that emphasis. If CHAR is a space, the means
5316 to remove the emphasis of the selected region.
5317 If char is not given (for example in an interactive call) it
5318 will be prompted for."
5319 (interactive)
5320 (let ((eal org-emphasis-alist) e det
5321 (erc org-emphasis-regexp-components)
5322 (prompt "")
5323 (string "") beg end move tag c s)
5324 (if (org-region-active-p)
5325 (setq beg (region-beginning) end (region-end)
5326 string (buffer-substring beg end))
5327 (setq move t))
5329 (while (setq e (pop eal))
5330 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5331 c (aref tag 0))
5332 (push (cons c (string-to-char (car e))) det)
5333 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5334 (substring tag 1)))))
5335 (setq det (nreverse det))
5336 (unless char
5337 (message "%s" (concat "Emphasis marker or tag:" prompt))
5338 (setq char (read-char-exclusive)))
5339 (setq char (or (cdr (assoc char det)) char))
5340 (if (equal char ?\ )
5341 (setq s "" move nil)
5342 (unless (assoc (char-to-string char) org-emphasis-alist)
5343 (error "No such emphasis marker: \"%c\"" char))
5344 (setq s (char-to-string char)))
5345 (while (and (> (length string) 1)
5346 (equal (substring string 0 1) (substring string -1))
5347 (assoc (substring string 0 1) org-emphasis-alist))
5348 (setq string (substring string 1 -1)))
5349 (setq string (concat s string s))
5350 (if beg (delete-region beg end))
5351 (unless (or (bolp)
5352 (string-match (concat "[" (nth 0 erc) "\n]")
5353 (char-to-string (char-before (point)))))
5354 (insert " "))
5355 (unless (or (eobp)
5356 (string-match (concat "[" (nth 1 erc) "\n]")
5357 (char-to-string (char-after (point)))))
5358 (insert " ") (backward-char 1))
5359 (insert string)
5360 (and move (backward-char 1))))
5362 (defconst org-nonsticky-props
5363 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5365 (defsubst org-rear-nonsticky-at (pos)
5366 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5368 (defun org-activate-plain-links (limit)
5369 "Run through the buffer and add overlays to links."
5370 (catch 'exit
5371 (let (f)
5372 (if (re-search-forward org-plain-link-re limit t)
5373 (progn
5374 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5375 (setq f (get-text-property (match-beginning 0) 'face))
5376 (if (or (eq f 'org-tag)
5377 (and (listp f) (memq 'org-tag f)))
5379 (add-text-properties (match-beginning 0) (match-end 0)
5380 (list 'mouse-face 'highlight
5381 'face 'org-link
5382 'keymap org-mouse-map))
5383 (org-rear-nonsticky-at (match-end 0)))
5384 t)))))
5386 (defun org-activate-code (limit)
5387 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5388 (progn
5389 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5390 (remove-text-properties (match-beginning 0) (match-end 0)
5391 '(display t invisible t intangible t))
5392 t)))
5394 (defcustom org-src-fontify-natively nil
5395 "When non-nil, fontify code in code blocks."
5396 :type 'boolean
5397 :version "24.1"
5398 :group 'org-appearance
5399 :group 'org-babel)
5401 (defun org-fontify-meta-lines-and-blocks (limit)
5402 (condition-case nil
5403 (org-fontify-meta-lines-and-blocks-1 limit)
5404 (error (message "org-mode fontification error"))))
5406 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5407 "Fontify #+ lines and blocks, in the correct ways."
5408 (let ((case-fold-search t))
5409 (if (re-search-forward
5410 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5411 limit t)
5412 (let ((beg (match-beginning 0))
5413 (block-start (match-end 0))
5414 (block-end nil)
5415 (lang (match-string 7))
5416 (beg1 (line-beginning-position 2))
5417 (dc1 (downcase (match-string 2)))
5418 (dc3 (downcase (match-string 3)))
5419 end end1 quoting block-type ovl)
5420 (cond
5421 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5422 ;; a single line of backend-specific content
5423 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5424 (remove-text-properties (match-beginning 0) (match-end 0)
5425 '(display t invisible t intangible t))
5426 (add-text-properties (match-beginning 1) (match-end 3)
5427 '(font-lock-fontified t face org-meta-line))
5428 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5429 '(font-lock-fontified t face org-block))
5430 ; for backend-specific code
5432 ((and (match-end 4) (equal dc3 "begin"))
5433 ;; Truly a block
5434 (setq block-type (downcase (match-string 5))
5435 quoting (member block-type org-protecting-blocks))
5436 (when (re-search-forward
5437 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5438 nil t) ;; on purpose, we look further than LIMIT
5439 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5440 (setq block-end (match-beginning 0))
5441 (when quoting
5442 (remove-text-properties beg end
5443 '(display t invisible t intangible t)))
5444 (add-text-properties
5445 beg end
5446 '(font-lock-fontified t font-lock-multiline t))
5447 (add-text-properties beg beg1 '(face org-meta-line))
5448 (add-text-properties end1 (min (point-max) (1+ end))
5449 '(face org-meta-line)) ; for end_src
5450 (cond
5451 ((and lang (not (string= lang "")) org-src-fontify-natively)
5452 (org-src-font-lock-fontify-block lang block-start block-end)
5453 ;; remove old background overlays
5454 (mapc (lambda (ov)
5455 (if (eq (overlay-get ov 'face) 'org-block-background)
5456 (delete-overlay ov)))
5457 (overlays-at (/ (+ beg1 block-end) 2)))
5458 ;; add a background overlay
5459 (setq ovl (make-overlay beg1 block-end))
5460 (overlay-put ovl 'face 'org-block-background)
5461 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5462 (quoting
5463 (add-text-properties beg1 (min (point-max) (1+ end1))
5464 '(face org-block))) ; end of source block
5465 ((not org-fontify-quote-and-verse-blocks))
5466 ((string= block-type "quote")
5467 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5468 ((string= block-type "verse")
5469 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5470 (add-text-properties beg beg1 '(face org-block-begin-line))
5471 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5473 ((member dc1 '("title:" "author:" "email:" "date:"))
5474 (add-text-properties
5475 beg (match-end 3)
5476 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5477 '(font-lock-fontified t invisible t)
5478 '(font-lock-fontified t face org-document-info-keyword)))
5479 (add-text-properties
5480 (match-beginning 6) (match-end 6)
5481 (if (string-equal dc1 "title:")
5482 '(font-lock-fontified t face org-document-title)
5483 '(font-lock-fontified t face org-document-info))))
5484 ((not (member (char-after beg) '(?\ ?\t)))
5485 ;; just any other in-buffer setting, but not indented
5486 (add-text-properties
5487 beg (1+ (match-end 0))
5488 '(font-lock-fontified t face org-meta-line))
5490 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5491 "orgtbl:" "tblfm:" "tblname:" "results:"
5492 "call:" "header:" "headers:" "name:"))
5493 (and (match-end 4) (equal dc3 "attr")))
5494 (add-text-properties
5495 beg (match-end 0)
5496 '(font-lock-fontified t face org-meta-line))
5498 ((member dc3 '(" " ""))
5499 (add-text-properties
5500 beg (match-end 0)
5501 '(font-lock-fontified t face font-lock-comment-face)))
5502 (t nil))))))
5504 (defun org-strip-protective-commas (beg end)
5505 "Strip protective commas between BEG and END in the current buffer."
5506 (interactive "r")
5507 (save-excursion
5508 (save-match-data
5509 (goto-char beg)
5510 (let ((front-line (save-excursion
5511 (re-search-forward
5512 "[^[:space:]]" end t)
5513 (goto-char (match-beginning 0))
5514 (current-column))))
5515 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5516 (goto-char (match-beginning 1))
5517 (when (= (current-column) front-line)
5518 (replace-match "" nil nil nil 1)))))))
5520 (defun org-activate-angle-links (limit)
5521 "Run through the buffer and add overlays to links."
5522 (if (re-search-forward org-angle-link-re limit t)
5523 (progn
5524 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5525 (add-text-properties (match-beginning 0) (match-end 0)
5526 (list 'mouse-face 'highlight
5527 'keymap org-mouse-map))
5528 (org-rear-nonsticky-at (match-end 0))
5529 t)))
5531 (defun org-activate-footnote-links (limit)
5532 "Run through the buffer and add overlays to footnotes."
5533 (let ((fn (org-footnote-next-reference-or-definition limit)))
5534 (when fn
5535 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5536 (org-remove-flyspell-overlays-in beg end)
5537 (add-text-properties beg end
5538 (list 'mouse-face 'highlight
5539 'keymap org-mouse-map
5540 'help-echo
5541 (if (= (point-at-bol) beg)
5542 "Footnote definition"
5543 "Footnote reference")
5544 'font-lock-fontified t
5545 'font-lock-multiline t
5546 'face 'org-footnote))))))
5548 (defun org-activate-bracket-links (limit)
5549 "Run through the buffer and add overlays to bracketed links."
5550 (if (re-search-forward org-bracket-link-regexp limit t)
5551 (let* ((help (concat "LINK: "
5552 (org-match-string-no-properties 1)))
5553 ;; FIXME: above we should remove the escapes.
5554 ;; but that requires another match, protecting match data,
5555 ;; a lot of overhead for font-lock.
5556 (ip (org-maybe-intangible
5557 (list 'invisible 'org-link
5558 'keymap org-mouse-map 'mouse-face 'highlight
5559 'font-lock-multiline t 'help-echo help)))
5560 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5561 'font-lock-multiline t 'help-echo help)))
5562 ;; We need to remove the invisible property here. Table narrowing
5563 ;; may have made some of this invisible.
5564 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5565 (remove-text-properties (match-beginning 0) (match-end 0)
5566 '(invisible nil))
5567 (if (match-end 3)
5568 (progn
5569 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5570 (org-rear-nonsticky-at (match-beginning 3))
5571 (add-text-properties (match-beginning 3) (match-end 3) vp)
5572 (org-rear-nonsticky-at (match-end 3))
5573 (add-text-properties (match-end 3) (match-end 0) ip)
5574 (org-rear-nonsticky-at (match-end 0)))
5575 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5576 (org-rear-nonsticky-at (match-beginning 1))
5577 (add-text-properties (match-beginning 1) (match-end 1) vp)
5578 (org-rear-nonsticky-at (match-end 1))
5579 (add-text-properties (match-end 1) (match-end 0) ip)
5580 (org-rear-nonsticky-at (match-end 0)))
5581 t)))
5583 (defun org-activate-dates (limit)
5584 "Run through the buffer and add overlays to dates."
5585 (if (re-search-forward org-tsr-regexp-both limit t)
5586 (progn
5587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5588 (add-text-properties (match-beginning 0) (match-end 0)
5589 (list 'mouse-face 'highlight
5590 'keymap org-mouse-map))
5591 (org-rear-nonsticky-at (match-end 0))
5592 (when org-display-custom-times
5593 (if (match-end 3)
5594 (org-display-custom-time (match-beginning 3) (match-end 3)))
5595 (org-display-custom-time (match-beginning 1) (match-end 1)))
5596 t)))
5598 (defvar org-target-link-regexp nil
5599 "Regular expression matching radio targets in plain text.")
5600 (make-variable-buffer-local 'org-target-link-regexp)
5601 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5602 "Regular expression matching a link target.")
5603 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5604 "Regular expression matching a radio target.")
5605 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5606 "Regular expression matching any target.")
5608 (defun org-activate-target-links (limit)
5609 "Run through the buffer and add overlays to target matches."
5610 (when org-target-link-regexp
5611 (let ((case-fold-search t))
5612 (if (re-search-forward org-target-link-regexp limit t)
5613 (progn
5614 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5615 (add-text-properties (match-beginning 0) (match-end 0)
5616 (list 'mouse-face 'highlight
5617 'keymap org-mouse-map
5618 'help-echo "Radio target link"
5619 'org-linked-text t))
5620 (org-rear-nonsticky-at (match-end 0))
5621 t)))))
5623 (defun org-update-radio-target-regexp ()
5624 "Find all radio targets in this file and update the regular expression."
5625 (interactive)
5626 (when (memq 'radio org-activate-links)
5627 (setq org-target-link-regexp
5628 (org-make-target-link-regexp (org-all-targets 'radio)))
5629 (org-restart-font-lock)))
5631 (defun org-hide-wide-columns (limit)
5632 (let (s e)
5633 (setq s (text-property-any (point) (or limit (point-max))
5634 'org-cwidth t))
5635 (when s
5636 (setq e (next-single-property-change s 'org-cwidth))
5637 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5638 (goto-char e)
5639 t)))
5641 (defvar org-latex-and-specials-regexp nil
5642 "Regular expression for highlighting export special stuff.")
5643 (defvar org-match-substring-regexp)
5644 (defvar org-match-substring-with-braces-regexp)
5646 ;; This should be with the exporter code, but we also use if for font-locking
5647 (defconst org-export-html-special-string-regexps
5648 '(("\\\\-" . "&shy;")
5649 ("---\\([^-]\\)" . "&mdash;\\1")
5650 ("--\\([^-]\\)" . "&ndash;\\1")
5651 ("\\.\\.\\." . "&hellip;"))
5652 "Regular expressions for special string conversion.")
5655 (defun org-compute-latex-and-specials-regexp ()
5656 "Compute regular expression for stuff treated specially by exporters."
5657 (if (not org-highlight-latex-fragments-and-specials)
5658 (org-set-local 'org-latex-and-specials-regexp nil)
5659 (require 'org-exp)
5660 (let*
5661 ((matchers (plist-get org-format-latex-options :matchers))
5662 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5663 org-latex-regexps)))
5664 (org-export-allow-BIND nil)
5665 (options (org-combine-plists (org-default-export-plist)
5666 (org-infile-export-plist)))
5667 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5668 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5669 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5670 (org-export-html-expand (plist-get options :expand-quoted-html))
5671 (org-export-with-special-strings (plist-get options :special-strings))
5672 (re-sub
5673 (cond
5674 ((equal org-export-with-sub-superscripts '{})
5675 (list org-match-substring-with-braces-regexp))
5676 (org-export-with-sub-superscripts
5677 (list org-match-substring-regexp))
5678 (t nil)))
5679 (re-latex
5680 (if org-export-with-LaTeX-fragments
5681 (mapcar (lambda (x) (nth 1 x)) latexs)))
5682 (re-macros
5683 (if org-export-with-TeX-macros
5684 (list (concat "\\\\"
5685 (regexp-opt
5686 (append
5688 (delq nil
5689 (mapcar 'car-safe
5690 (append org-entities-user
5691 org-entities)))
5692 (if (boundp 'org-latex-entities)
5693 (mapcar (lambda (x)
5694 (or (car-safe x) x))
5695 org-latex-entities)
5696 nil))
5697 'words))) ; FIXME
5699 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5700 (re-special (if org-export-with-special-strings
5701 (mapcar (lambda (x) (car x))
5702 org-export-html-special-string-regexps)))
5703 (re-rest
5704 (delq nil
5705 (list
5706 (if org-export-html-expand "@<[^>\n]+>")
5707 ))))
5708 (org-set-local
5709 'org-latex-and-specials-regexp
5710 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5711 re-rest) "\\|")))))
5713 (defun org-do-latex-and-special-faces (limit)
5714 "Run through the buffer and add overlays to links."
5715 (when org-latex-and-specials-regexp
5716 (let (rtn d)
5717 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5718 limit t))
5719 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5720 'face))
5721 '(org-code org-verbatim underline)))
5722 (progn
5723 (setq rtn t
5724 d (cond ((member (char-after (1+ (match-beginning 0)))
5725 '(?_ ?^)) 1)
5726 (t 0)))
5727 (font-lock-prepend-text-property
5728 (+ d (match-beginning 0)) (match-end 0)
5729 'face 'org-latex-and-export-specials)
5730 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5731 '(font-lock-multiline t)))))
5732 rtn)))
5734 (defun org-restart-font-lock ()
5735 "Restart `font-lock-mode', to force refontification."
5736 (when (and (boundp 'font-lock-mode) font-lock-mode)
5737 (font-lock-mode -1)
5738 (font-lock-mode 1)))
5740 (defun org-all-targets (&optional radio)
5741 "Return a list of all targets in this file.
5742 With optional argument RADIO, only find radio targets."
5743 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5744 rtn)
5745 (save-excursion
5746 (goto-char (point-min))
5747 (while (re-search-forward re nil t)
5748 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5749 rtn)))
5751 (defun org-make-target-link-regexp (targets)
5752 "Make regular expression matching all strings in TARGETS.
5753 The regular expression finds the targets also if there is a line break
5754 between words."
5755 (and targets
5756 (concat
5757 "\\<\\("
5758 (mapconcat
5759 (lambda (x)
5760 (setq x (regexp-quote x))
5761 (while (string-match " +" x)
5762 (setq x (replace-match "\\s-+" t t x)))
5764 targets
5765 "\\|")
5766 "\\)\\>")))
5768 (defun org-activate-tags (limit)
5769 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5772 (add-text-properties (match-beginning 1) (match-end 1)
5773 (list 'mouse-face 'highlight
5774 'keymap org-mouse-map))
5775 (org-rear-nonsticky-at (match-end 1))
5776 t)))
5778 (defun org-outline-level ()
5779 "Compute the outline level of the heading at point.
5780 This function assumes that the cursor is at the beginning of a line matched
5781 by `outline-regexp'. Otherwise it returns garbage.
5782 If this is called at a normal headline, the level is the number of stars.
5783 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5784 (save-excursion
5785 (looking-at org-outline-regexp)
5786 (1- (- (match-end 0) (match-beginning 0)))))
5788 (defvar org-font-lock-keywords nil)
5790 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5791 "Regular expression matching a property line.")
5793 (defvar org-font-lock-hook nil
5794 "Functions to be called for special font lock stuff.")
5796 (defvar org-font-lock-set-keywords-hook nil
5797 "Functions that can manipulate `org-font-lock-extra-keywords'.
5798 This is called after `org-font-lock-extra-keywords' is defined, but before
5799 it is installed to be used by font lock. This can be useful if something
5800 needs to be inserted at a specific position in the font-lock sequence.")
5802 (defun org-font-lock-hook (limit)
5803 (run-hook-with-args 'org-font-lock-hook limit))
5805 (defun org-set-font-lock-defaults ()
5806 (let* ((em org-fontify-emphasized-text)
5807 (lk org-activate-links)
5808 (org-font-lock-extra-keywords
5809 (list
5810 ;; Call the hook
5811 '(org-font-lock-hook)
5812 ;; Headlines
5813 `(,(if org-fontify-whole-heading-line
5814 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5815 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5816 (1 (org-get-level-face 1))
5817 (2 (org-get-level-face 2))
5818 (3 (org-get-level-face 3)))
5819 ;; Table lines
5820 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5821 (1 'org-table t))
5822 ;; Table internals
5823 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5824 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5825 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5826 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5827 ;; Drawers
5828 (list org-drawer-regexp '(0 'org-special-keyword t))
5829 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5830 ;; Properties
5831 (list org-property-re
5832 '(1 'org-special-keyword t)
5833 '(3 'org-property-value t))
5834 ;; Links
5835 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5836 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5837 (if (memq 'plain lk) '(org-activate-plain-links))
5838 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5839 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5840 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5841 (if (memq 'footnote lk) '(org-activate-footnote-links))
5842 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5843 '(org-hide-wide-columns (0 nil append))
5844 ;; TODO keyword
5845 (list (format org-heading-keyword-regexp-format
5846 org-todo-regexp)
5847 '(2 (org-get-todo-face 2) t))
5848 ;; DONE
5849 (if org-fontify-done-headline
5850 (list (format org-heading-keyword-regexp-format
5851 (concat
5852 "\\(?:"
5853 (mapconcat 'regexp-quote org-done-keywords "\\|")
5854 "\\)"))
5855 '(2 'org-headline-done t))
5856 nil)
5857 ;; Priorities
5858 '(org-font-lock-add-priority-faces)
5859 ;; Tags
5860 '(org-font-lock-add-tag-faces)
5861 ;; Special keywords
5862 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5863 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5864 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5865 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5866 ;; Emphasis
5867 (if em
5868 (if (featurep 'xemacs)
5869 '(org-do-emphasis-faces (0 nil append))
5870 '(org-do-emphasis-faces)))
5871 ;; Checkboxes
5872 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5873 1 'org-checkbox prepend)
5874 (if (cdr (assq 'checkbox org-list-automatic-rules))
5875 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5876 (0 (org-get-checkbox-statistics-face) t)))
5877 ;; Description list items
5878 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5879 1 'bold prepend)
5880 ;; ARCHIVEd headings
5881 (list (concat
5882 org-outline-regexp-bol
5883 "\\(.*:" org-archive-tag ":.*\\)")
5884 '(1 'org-archived prepend))
5885 ;; Specials
5886 '(org-do-latex-and-special-faces)
5887 '(org-fontify-entities)
5888 '(org-raise-scripts)
5889 ;; Code
5890 '(org-activate-code (1 'org-code t))
5891 ;; COMMENT
5892 (list (format org-heading-keyword-regexp-format
5893 (concat "\\("
5894 org-comment-string "\\|" org-quote-string
5895 "\\)"))
5896 '(2 'org-special-keyword t))
5897 '("^#.*" (0 'font-lock-comment-face t))
5898 ;; Blocks and meta lines
5899 '(org-fontify-meta-lines-and-blocks)
5901 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5902 (run-hooks 'org-font-lock-set-keywords-hook)
5903 ;; Now set the full font-lock-keywords
5904 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5905 (org-set-local 'font-lock-defaults
5906 '(org-font-lock-keywords t nil nil backward-paragraph))
5907 (kill-local-variable 'font-lock-keywords) nil))
5909 (defun org-toggle-pretty-entities ()
5910 "Toggle the composition display of entities as UTF8 characters."
5911 (interactive)
5912 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5913 (org-restart-font-lock)
5914 (if org-pretty-entities
5915 (message "Entities are displayed as UTF8 characters")
5916 (save-restriction
5917 (widen)
5918 (org-decompose-region (point-min) (point-max))
5919 (message "Entities are displayed plain"))))
5921 (defun org-fontify-entities (limit)
5922 "Find an entity to fontify."
5923 (let (ee)
5924 (when org-pretty-entities
5925 (catch 'match
5926 (while (re-search-forward
5927 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5928 limit t)
5929 (if (and (not (org-in-indented-comment-line))
5930 (setq ee (org-entity-get (match-string 1)))
5931 (= (length (nth 6 ee)) 1))
5932 (progn
5933 (add-text-properties
5934 (match-beginning 0) (match-end 1)
5935 (list 'font-lock-fontified t))
5936 (compose-region (match-beginning 0) (match-end 1)
5937 (nth 6 ee) nil)
5938 (backward-char 1)
5939 (throw 'match t))))
5940 nil))))
5942 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5943 "Fontify string S like in Org-mode."
5944 (with-temp-buffer
5945 (insert s)
5946 (let ((org-odd-levels-only odd-levels))
5947 (org-mode)
5948 (font-lock-fontify-buffer)
5949 (buffer-string))))
5951 (defvar org-m nil)
5952 (defvar org-l nil)
5953 (defvar org-f nil)
5954 (defun org-get-level-face (n)
5955 "Get the right face for match N in font-lock matching of headlines."
5956 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5957 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5958 (if org-cycle-level-faces
5959 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5960 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5961 (cond
5962 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5963 ((eq n 2) org-f)
5964 (t (if org-level-color-stars-only nil org-f))))
5967 (defun org-get-todo-face (kwd)
5968 "Get the right face for a TODO keyword KWD.
5969 If KWD is a number, get the corresponding match group."
5970 (if (numberp kwd) (setq kwd (match-string kwd)))
5971 (or (org-face-from-face-or-color
5972 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5973 (and (member kwd org-done-keywords) 'org-done)
5974 'org-todo))
5976 (defun org-face-from-face-or-color (context inherit face-or-color)
5977 "Create a face list that inherits INHERIT, but sets the foreground color.
5978 When FACE-OR-COLOR is not a string, just return it."
5979 (if (stringp face-or-color)
5980 (list :inherit inherit
5981 (cdr (assoc context org-faces-easy-properties))
5982 face-or-color)
5983 face-or-color))
5985 (defun org-font-lock-add-tag-faces (limit)
5986 "Add the special tag faces."
5987 (when (and org-tag-faces org-tags-special-faces-re)
5988 (while (re-search-forward org-tags-special-faces-re limit t)
5989 (add-text-properties (match-beginning 1) (match-end 1)
5990 (list 'face (org-get-tag-face 1)
5991 'font-lock-fontified t))
5992 (backward-char 1))))
5994 (defun org-font-lock-add-priority-faces (limit)
5995 "Add the special priority faces."
5996 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5997 (add-text-properties
5998 (match-beginning 0) (match-end 0)
5999 (list 'face (or (org-face-from-face-or-color
6000 'priority 'org-special-keyword
6001 (cdr (assoc (char-after (match-beginning 1))
6002 org-priority-faces)))
6003 'org-special-keyword)
6004 'font-lock-fontified t))))
6006 (defun org-get-tag-face (kwd)
6007 "Get the right face for a TODO keyword KWD.
6008 If KWD is a number, get the corresponding match group."
6009 (if (numberp kwd) (setq kwd (match-string kwd)))
6010 (or (org-face-from-face-or-color
6011 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6012 'org-tag))
6014 (defun org-unfontify-region (beg end &optional maybe_loudly)
6015 "Remove fontification and activation overlays from links."
6016 (font-lock-default-unfontify-region beg end)
6017 (let* ((buffer-undo-list t)
6018 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6019 (inhibit-modification-hooks t)
6020 deactivate-mark buffer-file-name buffer-file-truename)
6021 (org-decompose-region beg end)
6022 (remove-text-properties beg end
6023 '(mouse-face t keymap t org-linked-text t
6024 invisible t intangible t
6025 org-no-flyspell t org-emphasis t))
6026 (org-remove-font-lock-display-properties beg end)))
6028 (defconst org-script-display '(((raise -0.3) (height 0.7))
6029 ((raise 0.3) (height 0.7))
6030 ((raise -0.5))
6031 ((raise 0.5)))
6032 "Display properties for showing superscripts and subscripts.")
6034 (defun org-remove-font-lock-display-properties (beg end)
6035 "Remove specific display properties that have been added by font lock.
6036 The will remove the raise properties that are used to show superscripts
6037 and subscripts."
6038 (let (next prop)
6039 (while (< beg end)
6040 (setq next (next-single-property-change beg 'display nil end)
6041 prop (get-text-property beg 'display))
6042 (if (member prop org-script-display)
6043 (put-text-property beg next 'display nil))
6044 (setq beg next))))
6046 (defun org-raise-scripts (limit)
6047 "Add raise properties to sub/superscripts."
6048 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6049 (if (re-search-forward
6050 (if (eq org-use-sub-superscripts t)
6051 org-match-substring-regexp
6052 org-match-substring-with-braces-regexp)
6053 limit t)
6054 (let* ((pos (point)) table-p comment-p
6055 (mpos (match-beginning 3))
6056 (emph-p (get-text-property mpos 'org-emphasis))
6057 (link-p (get-text-property mpos 'mouse-face))
6058 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6059 (goto-char (point-at-bol))
6060 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6061 comment-p (org-looking-at-p "[ \t]*#"))
6062 (goto-char pos)
6063 ;; FIXME: Should we go back one character here, for a_b^c
6064 ;; (goto-char (1- pos)) ;????????????????????
6065 (if (or comment-p emph-p link-p keyw-p)
6067 (put-text-property (match-beginning 3) (match-end 0)
6068 'display
6069 (if (equal (char-after (match-beginning 2)) ?^)
6070 (nth (if table-p 3 1) org-script-display)
6071 (nth (if table-p 2 0) org-script-display)))
6072 (add-text-properties (match-beginning 2) (match-end 2)
6073 (list 'invisible t
6074 'org-dwidth t 'org-dwidth-n 1))
6075 (if (and (eq (char-after (match-beginning 3)) ?{)
6076 (eq (char-before (match-end 3)) ?}))
6077 (progn
6078 (add-text-properties
6079 (match-beginning 3) (1+ (match-beginning 3))
6080 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6081 (add-text-properties
6082 (1- (match-end 3)) (match-end 3)
6083 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6084 t)))))
6086 ;;;; Visibility cycling, including org-goto and indirect buffer
6088 ;;; Cycling
6090 (defvar org-cycle-global-status nil)
6091 (make-variable-buffer-local 'org-cycle-global-status)
6092 (defvar org-cycle-subtree-status nil)
6093 (make-variable-buffer-local 'org-cycle-subtree-status)
6095 ;;;###autoload
6097 (defvar org-inlinetask-min-level)
6099 (defun org-cycle (&optional arg)
6100 "TAB-action and visibility cycling for Org-mode.
6102 This is the command invoked in Org-mode by the TAB key. Its main purpose
6103 is outline visibility cycling, but it also invokes other actions
6104 in special contexts.
6106 - When this function is called with a prefix argument, rotate the entire
6107 buffer through 3 states (global cycling)
6108 1. OVERVIEW: Show only top-level headlines.
6109 2. CONTENTS: Show all headlines of all levels, but no body text.
6110 3. SHOW ALL: Show everything.
6111 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6112 determined by the variable `org-startup-folded', and by any VISIBILITY
6113 properties in the buffer.
6114 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6115 including any drawers.
6117 - When inside a table, re-align the table and move to the next field.
6119 - When point is at the beginning of a headline, rotate the subtree started
6120 by this line through 3 different states (local cycling)
6121 1. FOLDED: Only the main headline is shown.
6122 2. CHILDREN: The main headline and the direct children are shown.
6123 From this state, you can move to one of the children
6124 and zoom in further.
6125 3. SUBTREE: Show the entire subtree, including body text.
6126 If there is no subtree, switch directly from CHILDREN to FOLDED.
6128 - When point is at the beginning of an empty headline and the variable
6129 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6130 of the headline by demoting and promoting it to likely levels. This
6131 speeds up creation document structure by pressing TAB once or several
6132 times right after creating a new headline.
6134 - When there is a numeric prefix, go up to a heading with level ARG, do
6135 a `show-subtree' and return to the previous cursor position. If ARG
6136 is negative, go up that many levels.
6138 - When point is not at the beginning of a headline, execute the global
6139 binding for TAB, which is re-indenting the line. See the option
6140 `org-cycle-emulate-tab' for details.
6142 - Special case: if point is at the beginning of the buffer and there is
6143 no headline in line 1, this function will act as if called with prefix arg
6144 (C-u TAB, same as S-TAB) also when called without prefix arg.
6145 But only if also the variable `org-cycle-global-at-bob' is t."
6146 (interactive "P")
6147 (org-load-modules-maybe)
6148 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6149 (and org-cycle-level-after-item/entry-creation
6150 (or (org-cycle-level)
6151 (org-cycle-item-indentation))))
6152 (let* ((limit-level
6153 (or org-cycle-max-level
6154 (and (boundp 'org-inlinetask-min-level)
6155 org-inlinetask-min-level
6156 (1- org-inlinetask-min-level))))
6157 (nstars (and limit-level
6158 (if org-odd-levels-only
6159 (and limit-level (1- (* limit-level 2)))
6160 limit-level)))
6161 (org-outline-regexp
6162 (if (not (eq major-mode 'org-mode))
6163 outline-regexp
6164 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6165 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6166 (not (looking-at org-outline-regexp))))
6167 (org-cycle-hook
6168 (if bob-special
6169 (delq 'org-optimize-window-after-visibility-change
6170 (copy-sequence org-cycle-hook))
6171 org-cycle-hook))
6172 (pos (point)))
6174 (if (or bob-special (equal arg '(4)))
6175 ;; special case: use global cycling
6176 (setq arg t))
6178 (cond
6180 ((equal arg '(16))
6181 (setq last-command 'dummy)
6182 (org-set-startup-visibility)
6183 (message "Startup visibility, plus VISIBILITY properties"))
6185 ((equal arg '(64))
6186 (show-all)
6187 (message "Entire buffer visible, including drawers"))
6189 ;; Table: enter it or move to the next field.
6190 ((org-at-table-p 'any)
6191 (if (org-at-table.el-p)
6192 (message "Use C-c ' to edit table.el tables")
6193 (if arg (org-table-edit-field t)
6194 (org-table-justify-field-maybe)
6195 (call-interactively 'org-table-next-field))))
6197 ((run-hook-with-args-until-success
6198 'org-tab-after-check-for-table-hook))
6200 ;; Global cycling: delegate to `org-cycle-internal-global'.
6201 ((eq arg t) (org-cycle-internal-global))
6203 ;; Drawers: delegate to `org-flag-drawer'.
6204 ((and org-drawers org-drawer-regexp
6205 (save-excursion
6206 (beginning-of-line 1)
6207 (looking-at org-drawer-regexp)))
6208 (org-flag-drawer ; toggle block visibility
6209 (not (get-char-property (match-end 0) 'invisible))))
6211 ;; Show-subtree, ARG levels up from here.
6212 ((integerp arg)
6213 (save-excursion
6214 (org-back-to-heading)
6215 (outline-up-heading (if (< arg 0) (- arg)
6216 (- (funcall outline-level) arg)))
6217 (org-show-subtree)))
6219 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6220 ((and (featurep 'org-inlinetask)
6221 (org-inlinetask-at-task-p)
6222 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6223 (org-inlinetask-toggle-visibility))
6225 ((org-try-cdlatex-tab))
6227 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6228 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6229 (save-excursion (beginning-of-line 1)
6230 (looking-at org-outline-regexp)))
6231 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6232 (org-cycle-internal-local))
6234 ;; From there: TAB emulation and template completion.
6235 (buffer-read-only (org-back-to-heading))
6237 ((run-hook-with-args-until-success
6238 'org-tab-after-check-for-cycling-hook))
6240 ((org-try-structure-completion))
6242 ((run-hook-with-args-until-success
6243 'org-tab-before-tab-emulation-hook))
6245 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6246 (or (not (bolp))
6247 (not (looking-at org-outline-regexp))))
6248 (call-interactively (global-key-binding "\t")))
6250 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6251 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6252 (or (and (eq org-cycle-emulate-tab 'white)
6253 (= (match-end 0) (point-at-eol)))
6254 (and (eq org-cycle-emulate-tab 'whitestart)
6255 (>= (match-end 0) pos))))
6257 (eq org-cycle-emulate-tab t))
6258 (call-interactively (global-key-binding "\t")))
6260 (t (save-excursion
6261 (org-back-to-heading)
6262 (org-cycle)))))))
6264 (defun org-cycle-internal-global ()
6265 "Do the global cycling action."
6266 ;; Hack to avoid display of messages for .org attachments in Gnus
6267 (let ((ga (string-match "\\*fontification" (buffer-name))))
6268 (cond
6269 ((and (eq last-command this-command)
6270 (eq org-cycle-global-status 'overview))
6271 ;; We just created the overview - now do table of contents
6272 ;; This can be slow in very large buffers, so indicate action
6273 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6274 (unless ga (message "CONTENTS..."))
6275 (org-content)
6276 (unless ga (message "CONTENTS...done"))
6277 (setq org-cycle-global-status 'contents)
6278 (run-hook-with-args 'org-cycle-hook 'contents))
6280 ((and (eq last-command this-command)
6281 (eq org-cycle-global-status 'contents))
6282 ;; We just showed the table of contents - now show everything
6283 (run-hook-with-args 'org-pre-cycle-hook 'all)
6284 (show-all)
6285 (unless ga (message "SHOW ALL"))
6286 (setq org-cycle-global-status 'all)
6287 (run-hook-with-args 'org-cycle-hook 'all))
6290 ;; Default action: go to overview
6291 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6292 (org-overview)
6293 (unless ga (message "OVERVIEW"))
6294 (setq org-cycle-global-status 'overview)
6295 (run-hook-with-args 'org-cycle-hook 'overview)))))
6297 (defun org-cycle-internal-local ()
6298 "Do the local cycling action."
6299 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6300 ;; First, determine end of headline (EOH), end of subtree or item
6301 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6302 (save-excursion
6303 (if (org-at-item-p)
6304 (progn
6305 (beginning-of-line)
6306 (setq struct (org-list-struct))
6307 (setq eoh (point-at-eol))
6308 (setq eos (org-list-get-item-end-before-blank (point) struct))
6309 (setq has-children (org-list-has-child-p (point) struct)))
6310 (org-back-to-heading)
6311 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6312 (setq eos (save-excursion
6313 (org-end-of-subtree t)
6314 (unless (eobp)
6315 (skip-chars-forward " \t\n"))
6316 (if (eobp) (point) (1- (point)))))
6317 (setq has-children
6318 (or (save-excursion
6319 (let ((level (funcall outline-level)))
6320 (outline-next-heading)
6321 (and (org-at-heading-p t)
6322 (> (funcall outline-level) level))))
6323 (save-excursion
6324 (org-list-search-forward (org-item-beginning-re) eos t)))))
6325 ;; Determine end invisible part of buffer (EOL)
6326 (beginning-of-line 2)
6327 ;; XEmacs doesn't have `next-single-char-property-change'
6328 (if (featurep 'xemacs)
6329 (while (and (not (eobp)) ;; this is like `next-line'
6330 (get-char-property (1- (point)) 'invisible))
6331 (beginning-of-line 2))
6332 (while (and (not (eobp)) ;; this is like `next-line'
6333 (get-char-property (1- (point)) 'invisible))
6334 (goto-char (next-single-char-property-change (point) 'invisible))
6335 (and (eolp) (beginning-of-line 2))))
6336 (setq eol (point)))
6337 ;; Find out what to do next and set `this-command'
6338 (cond
6339 ((= eos eoh)
6340 ;; Nothing is hidden behind this heading
6341 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6342 (message "EMPTY ENTRY")
6343 (setq org-cycle-subtree-status nil)
6344 (save-excursion
6345 (goto-char eos)
6346 (outline-next-heading)
6347 (if (outline-invisible-p) (org-flag-heading nil))))
6348 ((and (or (>= eol eos)
6349 (not (string-match "\\S-" (buffer-substring eol eos))))
6350 (or has-children
6351 (not (setq children-skipped
6352 org-cycle-skip-children-state-if-no-children))))
6353 ;; Entire subtree is hidden in one line: children view
6354 (run-hook-with-args 'org-pre-cycle-hook 'children)
6355 (if (org-at-item-p)
6356 (org-list-set-item-visibility (point-at-bol) struct 'children)
6357 (org-show-entry)
6358 (org-with-limited-levels (show-children))
6359 (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6360 (org-cycle-hide-drawers 'subtree))
6361 ;; Fold every list in subtree to top-level items.
6362 (when (eq org-cycle-include-plain-lists 'integrate)
6363 (save-excursion
6364 (org-back-to-heading)
6365 (while (org-list-search-forward (org-item-beginning-re) eos t)
6366 (beginning-of-line 1)
6367 (let* ((struct (org-list-struct))
6368 (prevs (org-list-prevs-alist struct))
6369 (end (org-list-get-bottom-point struct)))
6370 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6371 (org-list-get-all-items (point) struct prevs))
6372 (goto-char end))))))
6373 (message "CHILDREN")
6374 (save-excursion
6375 (goto-char eos)
6376 (outline-next-heading)
6377 (if (outline-invisible-p) (org-flag-heading nil)))
6378 (setq org-cycle-subtree-status 'children)
6379 (run-hook-with-args 'org-cycle-hook 'children))
6380 ((or children-skipped
6381 (and (eq last-command this-command)
6382 (eq org-cycle-subtree-status 'children)))
6383 ;; We just showed the children, or no children are there,
6384 ;; now show everything.
6385 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6386 (outline-flag-region eoh eos nil)
6387 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6388 (setq org-cycle-subtree-status 'subtree)
6389 (run-hook-with-args 'org-cycle-hook 'subtree))
6391 ;; Default action: hide the subtree.
6392 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6393 (outline-flag-region eoh eos t)
6394 (message "FOLDED")
6395 (setq org-cycle-subtree-status 'folded)
6396 (run-hook-with-args 'org-cycle-hook 'folded)))))
6398 ;;;###autoload
6399 (defun org-global-cycle (&optional arg)
6400 "Cycle the global visibility. For details see `org-cycle'.
6401 With \\[universal-argument] prefix arg, switch to startup visibility.
6402 With a numeric prefix, show all headlines up to that level."
6403 (interactive "P")
6404 (let ((org-cycle-include-plain-lists
6405 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6406 (cond
6407 ((integerp arg)
6408 (show-all)
6409 (hide-sublevels arg)
6410 (setq org-cycle-global-status 'contents))
6411 ((equal arg '(4))
6412 (org-set-startup-visibility)
6413 (message "Startup visibility, plus VISIBILITY properties."))
6415 (org-cycle '(4))))))
6417 (defun org-set-startup-visibility ()
6418 "Set the visibility required by startup options and properties."
6419 (cond
6420 ((eq org-startup-folded t)
6421 (org-cycle '(4)))
6422 ((eq org-startup-folded 'content)
6423 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6424 (org-cycle '(4)) (org-cycle '(4)))))
6425 (unless (eq org-startup-folded 'showeverything)
6426 (if org-hide-block-startup (org-hide-block-all))
6427 (org-set-visibility-according-to-property 'no-cleanup)
6428 (org-cycle-hide-archived-subtrees 'all)
6429 (org-cycle-hide-drawers 'all)
6430 (org-cycle-show-empty-lines t)))
6432 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6433 "Switch subtree visibilities according to :VISIBILITY: property."
6434 (interactive)
6435 (let (org-show-entry-below state)
6436 (save-excursion
6437 (goto-char (point-min))
6438 (while (re-search-forward
6439 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6440 nil t)
6441 (setq state (match-string 1))
6442 (save-excursion
6443 (org-back-to-heading t)
6444 (hide-subtree)
6445 (org-reveal)
6446 (cond
6447 ((equal state '("fold" "folded"))
6448 (hide-subtree))
6449 ((equal state "children")
6450 (org-show-hidden-entry)
6451 (show-children))
6452 ((equal state "content")
6453 (save-excursion
6454 (save-restriction
6455 (org-narrow-to-subtree)
6456 (org-content))))
6457 ((member state '("all" "showall"))
6458 (show-subtree)))))
6459 (unless no-cleanup
6460 (org-cycle-hide-archived-subtrees 'all)
6461 (org-cycle-hide-drawers 'all)
6462 (org-cycle-show-empty-lines 'all)))))
6464 ;; This function uses outline-regexp instead of the more fundamental
6465 ;; org-outline-regexp so that org-cycle-global works outside of Org
6466 ;; buffers, where outline-regexp is needed.
6467 (defun org-overview ()
6468 "Switch to overview mode, showing only top-level headlines.
6469 Really, this shows all headlines with level equal or greater than the level
6470 of the first headline in the buffer. This is important, because if the
6471 first headline is not level one, then (hide-sublevels 1) gives confusing
6472 results."
6473 (interactive)
6474 (let ((level (save-excursion
6475 (goto-char (point-min))
6476 (if (re-search-forward (concat "^" outline-regexp) nil t)
6477 (progn
6478 (goto-char (match-beginning 0))
6479 (funcall outline-level))))))
6480 (and level (hide-sublevels level))))
6482 (defun org-content (&optional arg)
6483 "Show all headlines in the buffer, like a table of contents.
6484 With numerical argument N, show content up to level N."
6485 (interactive "P")
6486 (save-excursion
6487 ;; Visit all headings and show their offspring
6488 (and (integerp arg) (org-overview))
6489 (goto-char (point-max))
6490 (catch 'exit
6491 (while (and (progn (condition-case nil
6492 (outline-previous-visible-heading 1)
6493 (error (goto-char (point-min))))
6495 (looking-at org-outline-regexp))
6496 (if (integerp arg)
6497 (show-children (1- arg))
6498 (show-branches))
6499 (if (bobp) (throw 'exit nil))))))
6502 (defun org-optimize-window-after-visibility-change (state)
6503 "Adjust the window after a change in outline visibility.
6504 This function is the default value of the hook `org-cycle-hook'."
6505 (when (get-buffer-window (current-buffer))
6506 (cond
6507 ((eq state 'content) nil)
6508 ((eq state 'all) nil)
6509 ((eq state 'folded) nil)
6510 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6511 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6513 (defun org-remove-empty-overlays-at (pos)
6514 "Remove outline overlays that do not contain non-white stuff."
6515 (mapc
6516 (lambda (o)
6517 (and (eq 'outline (overlay-get o 'invisible))
6518 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6519 (overlay-end o))))
6520 (delete-overlay o)))
6521 (overlays-at pos)))
6523 (defun org-clean-visibility-after-subtree-move ()
6524 "Fix visibility issues after moving a subtree."
6525 ;; First, find a reasonable region to look at:
6526 ;; Start two siblings above, end three below
6527 (let* ((beg (save-excursion
6528 (and (org-get-last-sibling)
6529 (org-get-last-sibling))
6530 (point)))
6531 (end (save-excursion
6532 (and (org-get-next-sibling)
6533 (org-get-next-sibling)
6534 (org-get-next-sibling))
6535 (if (org-at-heading-p)
6536 (point-at-eol)
6537 (point))))
6538 (level (looking-at "\\*+"))
6539 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6540 (save-excursion
6541 (save-restriction
6542 (narrow-to-region beg end)
6543 (when re
6544 ;; Properly fold already folded siblings
6545 (goto-char (point-min))
6546 (while (re-search-forward re nil t)
6547 (if (and (not (outline-invisible-p))
6548 (save-excursion
6549 (goto-char (point-at-eol)) (outline-invisible-p)))
6550 (hide-entry))))
6551 (org-cycle-show-empty-lines 'overview)
6552 (org-cycle-hide-drawers 'overview)))))
6554 (defun org-cycle-show-empty-lines (state)
6555 "Show empty lines above all visible headlines.
6556 The region to be covered depends on STATE when called through
6557 `org-cycle-hook'. Lisp program can use t for STATE to get the
6558 entire buffer covered. Note that an empty line is only shown if there
6559 are at least `org-cycle-separator-lines' empty lines before the headline."
6560 (when (not (= org-cycle-separator-lines 0))
6561 (save-excursion
6562 (let* ((n (abs org-cycle-separator-lines))
6563 (re (cond
6564 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6565 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6566 (t (let ((ns (number-to-string (- n 2))))
6567 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6568 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6569 beg end b e)
6570 (cond
6571 ((memq state '(overview contents t))
6572 (setq beg (point-min) end (point-max)))
6573 ((memq state '(children folded))
6574 (setq beg (point) end (progn (org-end-of-subtree t t)
6575 (beginning-of-line 2)
6576 (point)))))
6577 (when beg
6578 (goto-char beg)
6579 (while (re-search-forward re end t)
6580 (unless (get-char-property (match-end 1) 'invisible)
6581 (setq e (match-end 1))
6582 (if (< org-cycle-separator-lines 0)
6583 (setq b (save-excursion
6584 (goto-char (match-beginning 0))
6585 (org-back-over-empty-lines)
6586 (if (save-excursion
6587 (goto-char (max (point-min) (1- (point))))
6588 (org-at-heading-p))
6589 (1- (point))
6590 (point))))
6591 (setq b (match-beginning 1)))
6592 (outline-flag-region b e nil)))))))
6593 ;; Never hide empty lines at the end of the file.
6594 (save-excursion
6595 (goto-char (point-max))
6596 (outline-previous-heading)
6597 (outline-end-of-heading)
6598 (if (and (looking-at "[ \t\n]+")
6599 (= (match-end 0) (point-max)))
6600 (outline-flag-region (point) (match-end 0) nil))))
6602 (defun org-show-empty-lines-in-parent ()
6603 "Move to the parent and re-show empty lines before visible headlines."
6604 (save-excursion
6605 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6606 (org-cycle-show-empty-lines context))))
6608 (defun org-files-list ()
6609 "Return `org-agenda-files' list, plus all open org-mode files.
6610 This is useful for operations that need to scan all of a user's
6611 open and agenda-wise Org files."
6612 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6613 (dolist (buf (buffer-list))
6614 (with-current-buffer buf
6615 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6616 (let ((file (expand-file-name (buffer-file-name))))
6617 (unless (member file files)
6618 (push file files))))))
6619 files))
6621 (defsubst org-entry-beginning-position ()
6622 "Return the beginning position of the current entry."
6623 (save-excursion (outline-back-to-heading t) (point)))
6625 (defsubst org-entry-end-position ()
6626 "Return the end position of the current entry."
6627 (save-excursion (outline-next-heading) (point)))
6629 (defun org-cycle-hide-drawers (state)
6630 "Re-hide all drawers after a visibility state change."
6631 (when (and (eq major-mode 'org-mode)
6632 (not (memq state '(overview folded contents))))
6633 (save-excursion
6634 (let* ((globalp (memq state '(contents all)))
6635 (beg (if globalp (point-min) (point)))
6636 (end (if globalp (point-max)
6637 (if (eq state 'children)
6638 (save-excursion (outline-next-heading) (point))
6639 (org-end-of-subtree t)))))
6640 (goto-char beg)
6641 (while (re-search-forward org-drawer-regexp end t)
6642 (org-flag-drawer t))))))
6644 (defun org-flag-drawer (flag)
6645 (save-excursion
6646 (beginning-of-line 1)
6647 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6648 (let ((b (match-end 0)))
6649 (if (re-search-forward
6650 "^[ \t]*:END:"
6651 (save-excursion (outline-next-heading) (point)) t)
6652 (outline-flag-region b (point-at-eol) flag)
6653 (error ":END: line missing at position %s" b))))))
6655 (defun org-subtree-end-visible-p ()
6656 "Is the end of the current subtree visible?"
6657 (pos-visible-in-window-p
6658 (save-excursion (org-end-of-subtree t) (point))))
6660 (defun org-first-headline-recenter (&optional N)
6661 "Move cursor to the first headline and recenter the headline.
6662 Optional argument N means put the headline into the Nth line of the window."
6663 (goto-char (point-min))
6664 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6665 (beginning-of-line)
6666 (recenter (prefix-numeric-value N))))
6668 ;;; Saving and restoring visibility
6670 (defun org-outline-overlay-data (&optional use-markers)
6671 "Return a list of the locations of all outline overlays.
6672 These are overlays with the `invisible' property value `outline'.
6673 The return value is a list of cons cells, with start and stop
6674 positions for each overlay.
6675 If USE-MARKERS is set, return the positions as markers."
6676 (let (beg end)
6677 (save-excursion
6678 (save-restriction
6679 (widen)
6680 (delq nil
6681 (mapcar (lambda (o)
6682 (when (eq (overlay-get o 'invisible) 'outline)
6683 (setq beg (overlay-start o)
6684 end (overlay-end o))
6685 (and beg end (> end beg)
6686 (if use-markers
6687 (cons (move-marker (make-marker) beg)
6688 (move-marker (make-marker) end))
6689 (cons beg end)))))
6690 (overlays-in (point-min) (point-max))))))))
6692 (defun org-set-outline-overlay-data (data)
6693 "Create visibility overlays for all positions in DATA.
6694 DATA should have been made by `org-outline-overlay-data'."
6695 (let (o)
6696 (save-excursion
6697 (save-restriction
6698 (widen)
6699 (show-all)
6700 (mapc (lambda (c)
6701 (outline-flag-region (car c) (cdr c) t))
6702 data)))))
6704 ;;; Folding of blocks
6706 (defvar org-hide-block-overlays nil
6707 "Overlays hiding blocks.")
6708 (make-variable-buffer-local 'org-hide-block-overlays)
6710 (defun org-block-map (function &optional start end)
6711 "Call FUNCTION at the head of all source blocks in the current buffer.
6712 Optional arguments START and END can be used to limit the range."
6713 (let ((start (or start (point-min)))
6714 (end (or end (point-max))))
6715 (save-excursion
6716 (goto-char start)
6717 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6718 (save-excursion
6719 (save-match-data
6720 (goto-char (match-beginning 0))
6721 (funcall function)))))))
6723 (defun org-hide-block-toggle-all ()
6724 "Toggle the visibility of all blocks in the current buffer."
6725 (org-block-map #'org-hide-block-toggle))
6727 (defun org-hide-block-all ()
6728 "Fold all blocks in the current buffer."
6729 (interactive)
6730 (org-show-block-all)
6731 (org-block-map #'org-hide-block-toggle-maybe))
6733 (defun org-show-block-all ()
6734 "Unfold all blocks in the current buffer."
6735 (interactive)
6736 (mapc 'delete-overlay org-hide-block-overlays)
6737 (setq org-hide-block-overlays nil))
6739 (defun org-hide-block-toggle-maybe ()
6740 "Toggle visibility of block at point."
6741 (interactive)
6742 (let ((case-fold-search t))
6743 (if (save-excursion
6744 (beginning-of-line 1)
6745 (looking-at org-block-regexp))
6746 (progn (org-hide-block-toggle)
6747 t) ;; to signal that we took action
6748 nil))) ;; to signal that we did not
6750 (defun org-hide-block-toggle (&optional force)
6751 "Toggle the visibility of the current block."
6752 (interactive)
6753 (save-excursion
6754 (beginning-of-line)
6755 (if (re-search-forward org-block-regexp nil t)
6756 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6757 (end (match-end 0)) ;; end of entire body
6759 (if (memq t (mapcar (lambda (overlay)
6760 (eq (overlay-get overlay 'invisible)
6761 'org-hide-block))
6762 (overlays-at start)))
6763 (if (or (not force) (eq force 'off))
6764 (mapc (lambda (ov)
6765 (when (member ov org-hide-block-overlays)
6766 (setq org-hide-block-overlays
6767 (delq ov org-hide-block-overlays)))
6768 (when (eq (overlay-get ov 'invisible)
6769 'org-hide-block)
6770 (delete-overlay ov)))
6771 (overlays-at start)))
6772 (setq ov (make-overlay start end))
6773 (overlay-put ov 'invisible 'org-hide-block)
6774 ;; make the block accessible to isearch
6775 (overlay-put
6776 ov 'isearch-open-invisible
6777 (lambda (ov)
6778 (when (member ov org-hide-block-overlays)
6779 (setq org-hide-block-overlays
6780 (delq ov org-hide-block-overlays)))
6781 (when (eq (overlay-get ov 'invisible)
6782 'org-hide-block)
6783 (delete-overlay ov))))
6784 (push ov org-hide-block-overlays)))
6785 (error "Not looking at a source block"))))
6787 ;; org-tab-after-check-for-cycling-hook
6788 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6789 ;; Remove overlays when changing major mode
6790 (add-hook 'org-mode-hook
6791 (lambda () (org-add-hook 'change-major-mode-hook
6792 'org-show-block-all 'append 'local)))
6794 ;;; Org-goto
6796 (defvar org-goto-window-configuration nil)
6797 (defvar org-goto-marker nil)
6798 (defvar org-goto-map
6799 (let ((map (make-sparse-keymap)))
6800 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6801 (while (setq cmd (pop cmds))
6802 (substitute-key-definition cmd cmd map global-map)))
6803 (suppress-keymap map)
6804 (org-defkey map "\C-m" 'org-goto-ret)
6805 (org-defkey map [(return)] 'org-goto-ret)
6806 (org-defkey map [(left)] 'org-goto-left)
6807 (org-defkey map [(right)] 'org-goto-right)
6808 (org-defkey map [(control ?g)] 'org-goto-quit)
6809 (org-defkey map "\C-i" 'org-cycle)
6810 (org-defkey map [(tab)] 'org-cycle)
6811 (org-defkey map [(down)] 'outline-next-visible-heading)
6812 (org-defkey map [(up)] 'outline-previous-visible-heading)
6813 (if org-goto-auto-isearch
6814 (if (fboundp 'define-key-after)
6815 (define-key-after map [t] 'org-goto-local-auto-isearch)
6816 nil)
6817 (org-defkey map "q" 'org-goto-quit)
6818 (org-defkey map "n" 'outline-next-visible-heading)
6819 (org-defkey map "p" 'outline-previous-visible-heading)
6820 (org-defkey map "f" 'outline-forward-same-level)
6821 (org-defkey map "b" 'outline-backward-same-level)
6822 (org-defkey map "u" 'outline-up-heading))
6823 (org-defkey map "/" 'org-occur)
6824 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6825 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6826 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6827 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6828 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6829 map))
6831 (defconst org-goto-help
6832 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6833 RET=jump to location [Q]uit and return to previous location
6834 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6836 (defvar org-goto-start-pos) ; dynamically scoped parameter
6838 ;; FIXME: Docstring does not mention both interfaces
6839 (defun org-goto (&optional alternative-interface)
6840 "Look up a different location in the current file, keeping current visibility.
6842 When you want look-up or go to a different location in a document, the
6843 fastest way is often to fold the entire buffer and then dive into the tree.
6844 This method has the disadvantage, that the previous location will be folded,
6845 which may not be what you want.
6847 This command works around this by showing a copy of the current buffer
6848 in an indirect buffer, in overview mode. You can dive into the tree in
6849 that copy, use org-occur and incremental search to find a location.
6850 When pressing RET or `Q', the command returns to the original buffer in
6851 which the visibility is still unchanged. After RET it will also jump to
6852 the location selected in the indirect buffer and expose the headline
6853 hierarchy above."
6854 (interactive "P")
6855 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6856 (org-refile-use-outline-path t)
6857 (org-refile-target-verify-function nil)
6858 (interface
6859 (if (not alternative-interface)
6860 org-goto-interface
6861 (if (eq org-goto-interface 'outline)
6862 'outline-path-completion
6863 'outline)))
6864 (org-goto-start-pos (point))
6865 (selected-point
6866 (if (eq interface 'outline)
6867 (car (org-get-location (current-buffer) org-goto-help))
6868 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6869 (org-refile-check-position pa)
6870 (nth 3 pa)))))
6871 (if selected-point
6872 (progn
6873 (org-mark-ring-push org-goto-start-pos)
6874 (goto-char selected-point)
6875 (if (or (outline-invisible-p) (org-invisible-p2))
6876 (org-show-context 'org-goto)))
6877 (message "Quit"))))
6879 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6880 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6881 (defvar org-goto-local-auto-isearch-map) ; defined below
6883 (defun org-get-location (buf help)
6884 "Let the user select a location in the Org-mode buffer BUF.
6885 This function uses a recursive edit. It returns the selected position
6886 or nil."
6887 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6888 (isearch-hide-immediately nil)
6889 (isearch-search-fun-function
6890 (lambda () 'org-goto-local-search-headings))
6891 (org-goto-selected-point org-goto-exit-command)
6892 (pop-up-frames nil)
6893 (special-display-buffer-names nil)
6894 (special-display-regexps nil)
6895 (special-display-function nil))
6896 (save-excursion
6897 (save-window-excursion
6898 (delete-other-windows)
6899 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6900 (org-pop-to-buffer-same-window
6901 (condition-case nil
6902 (make-indirect-buffer (current-buffer) "*org-goto*")
6903 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6904 (with-output-to-temp-buffer "*Help*"
6905 (princ help))
6906 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6907 (setq buffer-read-only nil)
6908 (let ((org-startup-truncated t)
6909 (org-startup-folded nil)
6910 (org-startup-align-all-tables nil))
6911 (org-mode)
6912 (org-overview))
6913 (setq buffer-read-only t)
6914 (if (and (boundp 'org-goto-start-pos)
6915 (integer-or-marker-p org-goto-start-pos))
6916 (let ((org-show-hierarchy-above t)
6917 (org-show-siblings t)
6918 (org-show-following-heading t))
6919 (goto-char org-goto-start-pos)
6920 (and (outline-invisible-p) (org-show-context)))
6921 (goto-char (point-min)))
6922 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6923 (message "Select location and press RET")
6924 (use-local-map org-goto-map)
6925 (recursive-edit)
6927 (kill-buffer "*org-goto*")
6928 (cons org-goto-selected-point org-goto-exit-command)))
6930 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6931 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6932 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6933 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6935 (defun org-goto-local-search-headings (string bound noerror)
6936 "Search and make sure that any matches are in headlines."
6937 (catch 'return
6938 (while (if isearch-forward
6939 (search-forward string bound noerror)
6940 (search-backward string bound noerror))
6941 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6942 (and (member :headline context)
6943 (not (member :tags context))))
6944 (throw 'return (point))))))
6946 (defun org-goto-local-auto-isearch ()
6947 "Start isearch."
6948 (interactive)
6949 (goto-char (point-min))
6950 (let ((keys (this-command-keys)))
6951 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6952 (isearch-mode t)
6953 (isearch-process-search-char (string-to-char keys)))))
6955 (defun org-goto-ret (&optional arg)
6956 "Finish `org-goto' by going to the new location."
6957 (interactive "P")
6958 (setq org-goto-selected-point (point)
6959 org-goto-exit-command 'return)
6960 (throw 'exit nil))
6962 (defun org-goto-left ()
6963 "Finish `org-goto' by going to the new location."
6964 (interactive)
6965 (if (org-at-heading-p)
6966 (progn
6967 (beginning-of-line 1)
6968 (setq org-goto-selected-point (point)
6969 org-goto-exit-command 'left)
6970 (throw 'exit nil))
6971 (error "Not on a heading")))
6973 (defun org-goto-right ()
6974 "Finish `org-goto' by going to the new location."
6975 (interactive)
6976 (if (org-at-heading-p)
6977 (progn
6978 (setq org-goto-selected-point (point)
6979 org-goto-exit-command 'right)
6980 (throw 'exit nil))
6981 (error "Not on a heading")))
6983 (defun org-goto-quit ()
6984 "Finish `org-goto' without cursor motion."
6985 (interactive)
6986 (setq org-goto-selected-point nil)
6987 (setq org-goto-exit-command 'quit)
6988 (throw 'exit nil))
6990 ;;; Indirect buffer display of subtrees
6992 (defvar org-indirect-dedicated-frame nil
6993 "This is the frame being used for indirect tree display.")
6994 (defvar org-last-indirect-buffer nil)
6996 (defun org-tree-to-indirect-buffer (&optional arg)
6997 "Create indirect buffer and narrow it to current subtree.
6998 With numerical prefix ARG, go up to this level and then take that tree.
6999 If ARG is negative, go up that many levels.
7000 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7001 indirect buffer previously made with this command, to avoid proliferation of
7002 indirect buffers. However, when you call the command with a \
7003 \\[universal-argument] prefix, or
7004 when `org-indirect-buffer-display' is `new-frame', the last buffer
7005 is kept so that you can work with several indirect buffers at the same time.
7006 If `org-indirect-buffer-display' is `dedicated-frame', the \
7007 \\[universal-argument] prefix also
7008 requests that a new frame be made for the new buffer, so that the dedicated
7009 frame is not changed."
7010 (interactive "P")
7011 (let ((cbuf (current-buffer))
7012 (cwin (selected-window))
7013 (pos (point))
7014 beg end level heading ibuf)
7015 (save-excursion
7016 (org-back-to-heading t)
7017 (when (numberp arg)
7018 (setq level (org-outline-level))
7019 (if (< arg 0) (setq arg (+ level arg)))
7020 (while (> (setq level (org-outline-level)) arg)
7021 (outline-up-heading 1 t)))
7022 (setq beg (point)
7023 heading (org-get-heading))
7024 (org-end-of-subtree t t)
7025 (if (org-at-heading-p) (backward-char 1))
7026 (setq end (point)))
7027 (if (and (buffer-live-p org-last-indirect-buffer)
7028 (not (eq org-indirect-buffer-display 'new-frame))
7029 (not arg))
7030 (kill-buffer org-last-indirect-buffer))
7031 (setq ibuf (org-get-indirect-buffer cbuf)
7032 org-last-indirect-buffer ibuf)
7033 (cond
7034 ((or (eq org-indirect-buffer-display 'new-frame)
7035 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7036 (select-frame (make-frame))
7037 (delete-other-windows)
7038 (org-pop-to-buffer-same-window ibuf)
7039 (org-set-frame-title heading))
7040 ((eq org-indirect-buffer-display 'dedicated-frame)
7041 (raise-frame
7042 (select-frame (or (and org-indirect-dedicated-frame
7043 (frame-live-p org-indirect-dedicated-frame)
7044 org-indirect-dedicated-frame)
7045 (setq org-indirect-dedicated-frame (make-frame)))))
7046 (delete-other-windows)
7047 (org-pop-to-buffer-same-window ibuf)
7048 (org-set-frame-title (concat "Indirect: " heading)))
7049 ((eq org-indirect-buffer-display 'current-window)
7050 (org-pop-to-buffer-same-window ibuf))
7051 ((eq org-indirect-buffer-display 'other-window)
7052 (pop-to-buffer ibuf))
7053 (t (error "Invalid value")))
7054 (if (featurep 'xemacs)
7055 (save-excursion (org-mode) (turn-on-font-lock)))
7056 (narrow-to-region beg end)
7057 (show-all)
7058 (goto-char pos)
7059 (run-hook-with-args 'org-cycle-hook 'all)
7060 (and (window-live-p cwin) (select-window cwin))))
7062 (defun org-get-indirect-buffer (&optional buffer)
7063 (setq buffer (or buffer (current-buffer)))
7064 (let ((n 1) (base (buffer-name buffer)) bname)
7065 (while (buffer-live-p
7066 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7067 (setq n (1+ n)))
7068 (condition-case nil
7069 (make-indirect-buffer buffer bname 'clone)
7070 (error (make-indirect-buffer buffer bname)))))
7072 (defun org-set-frame-title (title)
7073 "Set the title of the current frame to the string TITLE."
7074 ;; FIXME: how to name a single frame in XEmacs???
7075 (unless (featurep 'xemacs)
7076 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7078 ;;;; Structure editing
7080 ;;; Inserting headlines
7082 (defun org-previous-line-empty-p ()
7083 (save-excursion
7084 (and (not (bobp))
7085 (or (beginning-of-line 0) t)
7086 (save-match-data
7087 (looking-at "[ \t]*$")))))
7089 (defun org-insert-heading (&optional force-heading invisible-ok)
7090 "Insert a new heading or item with same depth at point.
7091 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7092 If point is at the beginning of a headline, insert a sibling before the
7093 current headline. If point is not at the beginning, split the line,
7094 create the new headline with the text in the current line after point
7095 \(but see also the variable `org-M-RET-may-split-line').
7097 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7098 This is important for non-interactive uses of the command."
7099 (interactive "P")
7100 (if (or (= (buffer-size) 0)
7101 (and (not (save-excursion
7102 (and (ignore-errors (org-back-to-heading invisible-ok))
7103 (org-at-heading-p))))
7104 (or force-heading (not (org-in-item-p)))))
7105 (progn
7106 (insert "\n* ")
7107 (run-hooks 'org-insert-heading-hook))
7108 (when (or force-heading (not (org-insert-item)))
7109 (let* ((empty-line-p nil)
7110 (level nil)
7111 (on-heading (org-at-heading-p))
7112 (head (save-excursion
7113 (condition-case nil
7114 (progn
7115 (org-back-to-heading invisible-ok)
7116 (when (and (not on-heading)
7117 (featurep 'org-inlinetask)
7118 (integerp org-inlinetask-min-level)
7119 (>= (length (match-string 0))
7120 org-inlinetask-min-level))
7121 ;; Find a heading level before the inline task
7122 (while (and (setq level (org-up-heading-safe))
7123 (>= level org-inlinetask-min-level)))
7124 (if (org-at-heading-p)
7125 (org-back-to-heading invisible-ok)
7126 (error "This should not happen")))
7127 (setq empty-line-p (org-previous-line-empty-p))
7128 (match-string 0))
7129 (error "*"))))
7130 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7131 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7132 pos hide-previous previous-pos)
7133 (cond
7134 ((and (org-at-heading-p) (bolp)
7135 (or (bobp)
7136 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7137 ;; insert before the current line
7138 (open-line (if blank 2 1)))
7139 ((and (bolp)
7140 (not org-insert-heading-respect-content)
7141 (or (bobp)
7142 (save-excursion
7143 (backward-char 1) (not (outline-invisible-p)))))
7144 ;; insert right here
7145 nil)
7147 ;; somewhere in the line
7148 (save-excursion
7149 (setq previous-pos (point-at-bol))
7150 (end-of-line)
7151 (setq hide-previous (outline-invisible-p)))
7152 (and org-insert-heading-respect-content (org-show-subtree))
7153 (let ((split
7154 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7155 (save-excursion
7156 (let ((p (point)))
7157 (goto-char (point-at-bol))
7158 (and (looking-at org-complex-heading-regexp)
7159 (match-beginning 4)
7160 (> p (match-beginning 4)))))))
7161 tags pos)
7162 (cond
7163 (org-insert-heading-respect-content
7164 (org-end-of-subtree nil t)
7165 (when (featurep 'org-inlinetask)
7166 (while (and (not (eobp))
7167 (looking-at "\\(\\*+\\)[ \t]+")
7168 (>= (length (match-string 1))
7169 org-inlinetask-min-level))
7170 (org-end-of-subtree nil t)))
7171 (or (bolp) (newline))
7172 (or (org-previous-line-empty-p)
7173 (and blank (newline)))
7174 (open-line 1))
7175 ((org-at-heading-p)
7176 (when hide-previous
7177 (show-children)
7178 (org-show-entry))
7179 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7180 (setq tags (and (match-end 2) (match-string 2)))
7181 (and (match-end 1)
7182 (delete-region (match-beginning 1) (match-end 1)))
7183 (setq pos (point-at-bol))
7184 (or split (end-of-line 1))
7185 (delete-horizontal-space)
7186 (if (string-match "\\`\\*+\\'"
7187 (buffer-substring (point-at-bol) (point)))
7188 (insert " "))
7189 (newline (if blank 2 1))
7190 (when tags
7191 (save-excursion
7192 (goto-char pos)
7193 (end-of-line 1)
7194 (insert " " tags)
7195 (org-set-tags nil 'align))))
7197 (or split (end-of-line 1))
7198 (newline (if blank 2 1)))))))
7199 (insert head) (just-one-space)
7200 (setq pos (point))
7201 (end-of-line 1)
7202 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7203 (when (and org-insert-heading-respect-content hide-previous)
7204 (save-excursion
7205 (goto-char previous-pos)
7206 (hide-subtree)))
7207 (run-hooks 'org-insert-heading-hook)))))
7209 (defun org-get-heading (&optional no-tags no-todo)
7210 "Return the heading of the current entry, without the stars.
7211 When NO-TAGS is non-nil, don't include tags.
7212 When NO-TODO is non-nil, don't include TODO keywords."
7213 (save-excursion
7214 (org-back-to-heading t)
7215 (cond
7216 ((and no-tags no-todo)
7217 (looking-at org-complex-heading-regexp)
7218 (match-string 4))
7219 (no-tags
7220 (looking-at (concat org-outline-regexp
7221 "\\(.*?\\)"
7222 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7223 (match-string 1))
7224 (no-todo
7225 (looking-at org-todo-line-regexp)
7226 (match-string 3))
7227 (t (looking-at org-heading-regexp)
7228 (match-string 2)))))
7230 (defun org-heading-components ()
7231 "Return the components of the current heading.
7232 This is a list with the following elements:
7233 - the level as an integer
7234 - the reduced level, different if `org-odd-levels-only' is set.
7235 - the TODO keyword, or nil
7236 - the priority character, like ?A, or nil if no priority is given
7237 - the headline text itself, or the tags string if no headline text
7238 - the tags string, or nil."
7239 (save-excursion
7240 (org-back-to-heading t)
7241 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7242 (list (length (match-string 1))
7243 (org-reduced-level (length (match-string 1)))
7244 (org-match-string-no-properties 2)
7245 (and (match-end 3) (aref (match-string 3) 2))
7246 (org-match-string-no-properties 4)
7247 (org-match-string-no-properties 5)))))
7249 (defun org-get-entry ()
7250 "Get the entry text, after heading, entire subtree."
7251 (save-excursion
7252 (org-back-to-heading t)
7253 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7255 (defun org-insert-heading-after-current ()
7256 "Insert a new heading with same level as current, after current subtree."
7257 (interactive)
7258 (org-back-to-heading)
7259 (org-insert-heading)
7260 (org-move-subtree-down)
7261 (end-of-line 1))
7263 (defun org-insert-heading-respect-content ()
7264 (interactive)
7265 (let ((org-insert-heading-respect-content t))
7266 (org-insert-heading t)))
7268 (defun org-insert-todo-heading-respect-content (&optional force-state)
7269 (interactive "P")
7270 (let ((org-insert-heading-respect-content t))
7271 (org-insert-todo-heading force-state t)))
7273 (defun org-insert-todo-heading (arg &optional force-heading)
7274 "Insert a new heading with the same level and TODO state as current heading.
7275 If the heading has no TODO state, or if the state is DONE, use the first
7276 state (TODO by default). Also with prefix arg, force first state."
7277 (interactive "P")
7278 (when (or force-heading (not (org-insert-item 'checkbox)))
7279 (org-insert-heading force-heading)
7280 (save-excursion
7281 (org-back-to-heading)
7282 (outline-previous-heading)
7283 (looking-at org-todo-line-regexp))
7284 (let*
7285 ((new-mark-x
7286 (if (or arg
7287 (not (match-beginning 2))
7288 (member (match-string 2) org-done-keywords))
7289 (car org-todo-keywords-1)
7290 (match-string 2)))
7291 (new-mark
7293 (run-hook-with-args-until-success
7294 'org-todo-get-default-hook new-mark-x nil)
7295 new-mark-x)))
7296 (beginning-of-line 1)
7297 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7298 (if org-treat-insert-todo-heading-as-state-change
7299 (org-todo new-mark)
7300 (insert new-mark " "))))
7301 (when org-provide-todo-statistics
7302 (org-update-parent-todo-statistics))))
7304 (defun org-insert-subheading (arg)
7305 "Insert a new subheading and demote it.
7306 Works for outline headings and for plain lists alike."
7307 (interactive "P")
7308 (org-insert-heading arg)
7309 (cond
7310 ((org-at-heading-p) (org-do-demote))
7311 ((org-at-item-p) (org-indent-item))))
7313 (defun org-insert-todo-subheading (arg)
7314 "Insert a new subheading with TODO keyword or checkbox and demote it.
7315 Works for outline headings and for plain lists alike."
7316 (interactive "P")
7317 (org-insert-todo-heading arg)
7318 (cond
7319 ((org-at-heading-p) (org-do-demote))
7320 ((org-at-item-p) (org-indent-item))))
7322 ;;; Promotion and Demotion
7324 (defvar org-after-demote-entry-hook nil
7325 "Hook run after an entry has been demoted.
7326 The cursor will be at the beginning of the entry.
7327 When a subtree is being demoted, the hook will be called for each node.")
7329 (defvar org-after-promote-entry-hook nil
7330 "Hook run after an entry has been promoted.
7331 The cursor will be at the beginning of the entry.
7332 When a subtree is being promoted, the hook will be called for each node.")
7334 (defun org-promote-subtree ()
7335 "Promote the entire subtree.
7336 See also `org-promote'."
7337 (interactive)
7338 (save-excursion
7339 (org-with-limited-levels (org-map-tree 'org-promote)))
7340 (org-fix-position-after-promote))
7342 (defun org-demote-subtree ()
7343 "Demote the entire subtree. See `org-demote'.
7344 See also `org-promote'."
7345 (interactive)
7346 (save-excursion
7347 (org-with-limited-levels (org-map-tree 'org-demote)))
7348 (org-fix-position-after-promote))
7351 (defun org-do-promote ()
7352 "Promote the current heading higher up the tree.
7353 If the region is active in `transient-mark-mode', promote all headings
7354 in the region."
7355 (interactive)
7356 (save-excursion
7357 (if (org-region-active-p)
7358 (org-map-region 'org-promote (region-beginning) (region-end))
7359 (org-promote)))
7360 (org-fix-position-after-promote))
7362 (defun org-do-demote ()
7363 "Demote the current heading lower down the tree.
7364 If the region is active in `transient-mark-mode', demote all headings
7365 in the region."
7366 (interactive)
7367 (save-excursion
7368 (if (org-region-active-p)
7369 (org-map-region 'org-demote (region-beginning) (region-end))
7370 (org-demote)))
7371 (org-fix-position-after-promote))
7373 (defun org-fix-position-after-promote ()
7374 "Make sure that after pro/demotion cursor position is right."
7375 (let ((pos (point)))
7376 (when (save-excursion
7377 (beginning-of-line 1)
7378 (looking-at org-todo-line-regexp)
7379 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7380 (cond ((eobp) (insert " "))
7381 ((eolp) (insert " "))
7382 ((equal (char-after) ?\ ) (forward-char 1))))))
7384 (defun org-current-level ()
7385 "Return the level of the current entry, or nil if before the first headline.
7386 The level is the number of stars at the beginning of the headline."
7387 (save-excursion
7388 (org-with-limited-levels
7389 (if (ignore-errors (org-back-to-heading t))
7390 (funcall outline-level)))))
7392 (defun org-get-previous-line-level ()
7393 "Return the outline depth of the last headline before the current line.
7394 Returns 0 for the first headline in the buffer, and nil if before the
7395 first headline."
7396 (let ((current-level (org-current-level))
7397 (prev-level (when (> (line-number-at-pos) 1)
7398 (save-excursion
7399 (beginning-of-line 0)
7400 (org-current-level)))))
7401 (cond ((null current-level) nil) ; Before first headline
7402 ((null prev-level) 0) ; At first headline
7403 (prev-level))))
7405 (defun org-reduced-level (l)
7406 "Compute the effective level of a heading.
7407 This takes into account the setting of `org-odd-levels-only'."
7408 (cond
7409 ((zerop l) 0)
7410 (org-odd-levels-only (1+ (floor (/ l 2))))
7411 (t l)))
7413 (defun org-level-increment ()
7414 "Return the number of stars that will be added or removed at a
7415 time to headlines when structure editing, based on the value of
7416 `org-odd-levels-only'."
7417 (if org-odd-levels-only 2 1))
7419 (defun org-get-valid-level (level &optional change)
7420 "Rectify a level change under the influence of `org-odd-levels-only'
7421 LEVEL is a current level, CHANGE is by how much the level should be
7422 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7423 even level numbers will become the next higher odd number."
7424 (if org-odd-levels-only
7425 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7426 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7427 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7428 (max 1 (+ level (or change 0)))))
7430 (if (boundp 'define-obsolete-function-alias)
7431 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7432 (define-obsolete-function-alias 'org-get-legal-level
7433 'org-get-valid-level)
7434 (define-obsolete-function-alias 'org-get-legal-level
7435 'org-get-valid-level "23.1")))
7437 (defun org-promote ()
7438 "Promote the current heading higher up the tree.
7439 If the region is active in `transient-mark-mode', promote all headings
7440 in the region."
7441 (org-back-to-heading t)
7442 (let* ((level (save-match-data (funcall outline-level)))
7443 (after-change-functions (remove 'flyspell-after-change-function
7444 after-change-functions))
7445 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7446 (diff (abs (- level (length up-head) -1))))
7447 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7448 (replace-match up-head nil t)
7449 ;; Fixup tag positioning
7450 (and org-auto-align-tags (org-set-tags nil t))
7451 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7452 (run-hooks 'org-after-promote-entry-hook)))
7454 (defun org-demote ()
7455 "Demote the current heading lower down the tree.
7456 If the region is active in `transient-mark-mode', demote all headings
7457 in the region."
7458 (org-back-to-heading t)
7459 (let* ((level (save-match-data (funcall outline-level)))
7460 (after-change-functions (remove 'flyspell-after-change-function
7461 after-change-functions))
7462 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7463 (diff (abs (- level (length down-head) -1))))
7464 (replace-match down-head nil t)
7465 ;; Fixup tag positioning
7466 (and org-auto-align-tags (org-set-tags nil t))
7467 (if org-adapt-indentation (org-fixup-indentation diff))
7468 (run-hooks 'org-after-demote-entry-hook)))
7470 (defun org-cycle-level ()
7471 "Cycle the level of an empty headline through possible states.
7472 This goes first to child, then to parent, level, then up the hierarchy.
7473 After top level, it switches back to sibling level."
7474 (interactive)
7475 (let ((org-adapt-indentation nil))
7476 (when (org-point-at-end-of-empty-headline)
7477 (setq this-command 'org-cycle-level) ; Only needed for caching
7478 (let ((cur-level (org-current-level))
7479 (prev-level (org-get-previous-line-level)))
7480 (cond
7481 ;; If first headline in file, promote to top-level.
7482 ((= prev-level 0)
7483 (loop repeat (/ (- cur-level 1) (org-level-increment))
7484 do (org-do-promote)))
7485 ;; If same level as prev, demote one.
7486 ((= prev-level cur-level)
7487 (org-do-demote))
7488 ;; If parent is top-level, promote to top level if not already.
7489 ((= prev-level 1)
7490 (loop repeat (/ (- cur-level 1) (org-level-increment))
7491 do (org-do-promote)))
7492 ;; If top-level, return to prev-level.
7493 ((= cur-level 1)
7494 (loop repeat (/ (- prev-level 1) (org-level-increment))
7495 do (org-do-demote)))
7496 ;; If less than prev-level, promote one.
7497 ((< cur-level prev-level)
7498 (org-do-promote))
7499 ;; If deeper than prev-level, promote until higher than
7500 ;; prev-level.
7501 ((> cur-level prev-level)
7502 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7503 do (org-do-promote))))
7504 t))))
7506 (defun org-map-tree (fun)
7507 "Call FUN for every heading underneath the current one."
7508 (org-back-to-heading)
7509 (let ((level (funcall outline-level)))
7510 (save-excursion
7511 (funcall fun)
7512 (while (and (progn
7513 (outline-next-heading)
7514 (> (funcall outline-level) level))
7515 (not (eobp)))
7516 (funcall fun)))))
7518 (defun org-map-region (fun beg end)
7519 "Call FUN for every heading between BEG and END."
7520 (let ((org-ignore-region t))
7521 (save-excursion
7522 (setq end (copy-marker end))
7523 (goto-char beg)
7524 (if (and (re-search-forward org-outline-regexp-bol nil t)
7525 (< (point) end))
7526 (funcall fun))
7527 (while (and (progn
7528 (outline-next-heading)
7529 (< (point) end))
7530 (not (eobp)))
7531 (funcall fun)))))
7533 (defvar org-property-end-re) ; silence byte-compiler
7534 (defun org-fixup-indentation (diff)
7535 "Change the indentation in the current entry by DIFF.
7536 However, if any line in the current entry has no indentation, or if it
7537 would end up with no indentation after the change, nothing at all is done."
7538 (save-excursion
7539 (let ((end (save-excursion (outline-next-heading)
7540 (point-marker)))
7541 (prohibit (if (> diff 0)
7542 "^\\S-"
7543 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7544 col)
7545 (unless (save-excursion (end-of-line 1)
7546 (re-search-forward prohibit end t))
7547 (while (and (< (point) end)
7548 (re-search-forward "^[ \t]+" end t))
7549 (goto-char (match-end 0))
7550 (setq col (current-column))
7551 (if (< diff 0) (replace-match ""))
7552 (org-indent-to-column (+ diff col))))
7553 (move-marker end nil))))
7555 (defun org-convert-to-odd-levels ()
7556 "Convert an org-mode file with all levels allowed to one with odd levels.
7557 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7558 level 5 etc."
7559 (interactive)
7560 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7561 (let ((outline-level 'org-outline-level)
7562 (org-odd-levels-only nil) n)
7563 (save-excursion
7564 (goto-char (point-min))
7565 (while (re-search-forward "^\\*\\*+ " nil t)
7566 (setq n (- (length (match-string 0)) 2))
7567 (while (>= (setq n (1- n)) 0)
7568 (org-demote))
7569 (end-of-line 1))))))
7571 (defun org-convert-to-oddeven-levels ()
7572 "Convert an org-mode file with only odd levels to one with odd/even levels.
7573 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7574 file contains a section with an even level, conversion would
7575 destroy the structure of the file. An error is signaled in this
7576 case."
7577 (interactive)
7578 (goto-char (point-min))
7579 ;; First check if there are no even levels
7580 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7581 (org-show-context t)
7582 (error "Not all levels are odd in this file. Conversion not possible"))
7583 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7584 (let ((outline-regexp org-outline-regexp)
7585 (outline-level 'org-outline-level)
7586 (org-odd-levels-only nil) n)
7587 (save-excursion
7588 (goto-char (point-min))
7589 (while (re-search-forward "^\\*\\*+ " nil t)
7590 (setq n (/ (1- (length (match-string 0))) 2))
7591 (while (>= (setq n (1- n)) 0)
7592 (org-promote))
7593 (end-of-line 1))))))
7595 (defun org-tr-level (n)
7596 "Make N odd if required."
7597 (if org-odd-levels-only (1+ (/ n 2)) n))
7599 ;;; Vertical tree motion, cutting and pasting of subtrees
7601 (defun org-move-subtree-up (&optional arg)
7602 "Move the current subtree up past ARG headlines of the same level."
7603 (interactive "p")
7604 (org-move-subtree-down (- (prefix-numeric-value arg))))
7606 (defun org-move-subtree-down (&optional arg)
7607 "Move the current subtree down past ARG headlines of the same level."
7608 (interactive "p")
7609 (setq arg (prefix-numeric-value arg))
7610 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7611 'org-get-last-sibling))
7612 (ins-point (make-marker))
7613 (cnt (abs arg))
7614 (col (current-column))
7615 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7616 ;; Select the tree
7617 (org-back-to-heading)
7618 (setq beg0 (point))
7619 (save-excursion
7620 (setq ne-beg (org-back-over-empty-lines))
7621 (setq beg (point)))
7622 (save-match-data
7623 (save-excursion (outline-end-of-heading)
7624 (setq folded (outline-invisible-p)))
7625 (outline-end-of-subtree))
7626 (outline-next-heading)
7627 (setq ne-end (org-back-over-empty-lines))
7628 (setq end (point))
7629 (goto-char beg0)
7630 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7631 ;; include less whitespace
7632 (save-excursion
7633 (goto-char beg)
7634 (forward-line (- ne-beg ne-end))
7635 (setq beg (point))))
7636 ;; Find insertion point, with error handling
7637 (while (> cnt 0)
7638 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7639 (progn (goto-char beg0)
7640 (error "Cannot move past superior level or buffer limit")))
7641 (setq cnt (1- cnt)))
7642 (if (> arg 0)
7643 ;; Moving forward - still need to move over subtree
7644 (progn (org-end-of-subtree t t)
7645 (save-excursion
7646 (org-back-over-empty-lines)
7647 (or (bolp) (newline)))))
7648 (setq ne-ins (org-back-over-empty-lines))
7649 (move-marker ins-point (point))
7650 (setq txt (buffer-substring beg end))
7651 (org-save-markers-in-region beg end)
7652 (delete-region beg end)
7653 (org-remove-empty-overlays-at beg)
7654 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7655 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7656 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7657 (let ((bbb (point)))
7658 (insert-before-markers txt)
7659 (org-reinstall-markers-in-region bbb)
7660 (move-marker ins-point bbb))
7661 (or (bolp) (insert "\n"))
7662 (setq ins-end (point))
7663 (goto-char ins-point)
7664 (org-skip-whitespace)
7665 (when (and (< arg 0)
7666 (org-first-sibling-p)
7667 (> ne-ins ne-beg))
7668 ;; Move whitespace back to beginning
7669 (save-excursion
7670 (goto-char ins-end)
7671 (let ((kill-whole-line t))
7672 (kill-line (- ne-ins ne-beg)) (point)))
7673 (insert (make-string (- ne-ins ne-beg) ?\n)))
7674 (move-marker ins-point nil)
7675 (if folded
7676 (hide-subtree)
7677 (org-show-entry)
7678 (show-children)
7679 (org-cycle-hide-drawers 'children))
7680 (org-clean-visibility-after-subtree-move)
7681 ;; move back to the initial column we were at
7682 (move-to-column col)))
7684 (defvar org-subtree-clip ""
7685 "Clipboard for cut and paste of subtrees.
7686 This is actually only a copy of the kill, because we use the normal kill
7687 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7689 (defvar org-subtree-clip-folded nil
7690 "Was the last copied subtree folded?
7691 This is used to fold the tree back after pasting.")
7693 (defun org-cut-subtree (&optional n)
7694 "Cut the current subtree into the clipboard.
7695 With prefix arg N, cut this many sequential subtrees.
7696 This is a short-hand for marking the subtree and then cutting it."
7697 (interactive "p")
7698 (org-copy-subtree n 'cut))
7700 (defun org-copy-subtree (&optional n cut force-store-markers)
7701 "Cut the current subtree into the clipboard.
7702 With prefix arg N, cut this many sequential subtrees.
7703 This is a short-hand for marking the subtree and then copying it.
7704 If CUT is non-nil, actually cut the subtree.
7705 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7706 of some markers in the region, even if CUT is non-nil. This is
7707 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7708 (interactive "p")
7709 (let (beg end folded (beg0 (point)))
7710 (if (org-called-interactively-p 'any)
7711 (org-back-to-heading nil) ; take what looks like a subtree
7712 (org-back-to-heading t)) ; take what is really there
7713 (org-back-over-empty-lines)
7714 (setq beg (point))
7715 (skip-chars-forward " \t\r\n")
7716 (save-match-data
7717 (save-excursion (outline-end-of-heading)
7718 (setq folded (outline-invisible-p)))
7719 (condition-case nil
7720 (org-forward-same-level (1- n) t)
7721 (error nil))
7722 (org-end-of-subtree t t))
7723 (org-back-over-empty-lines)
7724 (setq end (point))
7725 (goto-char beg0)
7726 (when (> end beg)
7727 (setq org-subtree-clip-folded folded)
7728 (when (or cut force-store-markers)
7729 (org-save-markers-in-region beg end))
7730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7731 (setq org-subtree-clip (current-kill 0))
7732 (message "%s: Subtree(s) with %d characters"
7733 (if cut "Cut" "Copied")
7734 (length org-subtree-clip)))))
7736 (defun org-paste-subtree (&optional level tree for-yank)
7737 "Paste the clipboard as a subtree, with modification of headline level.
7738 The entire subtree is promoted or demoted in order to match a new headline
7739 level.
7741 If the cursor is at the beginning of a headline, the same level as
7742 that headline is used to paste the tree
7744 If not, the new level is derived from the *visible* headings
7745 before and after the insertion point, and taken to be the inferior headline
7746 level of the two. So if the previous visible heading is level 3 and the
7747 next is level 4 (or vice versa), level 4 will be used for insertion.
7748 This makes sure that the subtree remains an independent subtree and does
7749 not swallow low level entries.
7751 You can also force a different level, either by using a numeric prefix
7752 argument, or by inserting the heading marker by hand. For example, if the
7753 cursor is after \"*****\", then the tree will be shifted to level 5.
7755 If optional TREE is given, use this text instead of the kill ring.
7757 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7758 move back over whitespace before inserting, and move point to the end of
7759 the inserted text when done."
7760 (interactive "P")
7761 (setq tree (or tree (and kill-ring (current-kill 0))))
7762 (unless (org-kill-is-subtree-p tree)
7763 (error "%s"
7764 (substitute-command-keys
7765 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7766 (org-with-limited-levels
7767 (let* ((visp (not (outline-invisible-p)))
7768 (txt tree)
7769 (^re_ "\\(\\*+\\)[ \t]*")
7770 (old-level (if (string-match org-outline-regexp-bol txt)
7771 (- (match-end 0) (match-beginning 0) 1)
7772 -1))
7773 (force-level (cond (level (prefix-numeric-value level))
7774 ((and (looking-at "[ \t]*$")
7775 (string-match
7776 "^\\*+$" (buffer-substring
7777 (point-at-bol) (point))))
7778 (- (match-end 1) (match-beginning 1)))
7779 ((and (bolp)
7780 (looking-at org-outline-regexp))
7781 (- (match-end 0) (point) 1))
7782 (t nil)))
7783 (previous-level (save-excursion
7784 (condition-case nil
7785 (progn
7786 (outline-previous-visible-heading 1)
7787 (if (looking-at ^re_)
7788 (- (match-end 0) (match-beginning 0) 1)
7790 (error 1))))
7791 (next-level (save-excursion
7792 (condition-case nil
7793 (progn
7794 (or (looking-at org-outline-regexp)
7795 (outline-next-visible-heading 1))
7796 (if (looking-at ^re_)
7797 (- (match-end 0) (match-beginning 0) 1)
7799 (error 1))))
7800 (new-level (or force-level (max previous-level next-level)))
7801 (shift (if (or (= old-level -1)
7802 (= new-level -1)
7803 (= old-level new-level))
7805 (- new-level old-level)))
7806 (delta (if (> shift 0) -1 1))
7807 (func (if (> shift 0) 'org-demote 'org-promote))
7808 (org-odd-levels-only nil)
7809 beg end newend)
7810 ;; Remove the forced level indicator
7811 (if force-level
7812 (delete-region (point-at-bol) (point)))
7813 ;; Paste
7814 (beginning-of-line (if (bolp) 1 2))
7815 (unless for-yank (org-back-over-empty-lines))
7816 (setq beg (point))
7817 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7818 (insert-before-markers txt)
7819 (unless (string-match "\n\\'" txt) (insert "\n"))
7820 (setq newend (point))
7821 (org-reinstall-markers-in-region beg)
7822 (setq end (point))
7823 (goto-char beg)
7824 (skip-chars-forward " \t\n\r")
7825 (setq beg (point))
7826 (if (and (outline-invisible-p) visp)
7827 (save-excursion (outline-show-heading)))
7828 ;; Shift if necessary
7829 (unless (= shift 0)
7830 (save-restriction
7831 (narrow-to-region beg end)
7832 (while (not (= shift 0))
7833 (org-map-region func (point-min) (point-max))
7834 (setq shift (+ delta shift)))
7835 (goto-char (point-min))
7836 (setq newend (point-max))))
7837 (when (or (org-called-interactively-p 'interactive) for-yank)
7838 (message "Clipboard pasted as level %d subtree" new-level))
7839 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7840 kill-ring
7841 (eq org-subtree-clip (current-kill 0))
7842 org-subtree-clip-folded)
7843 ;; The tree was folded before it was killed/copied
7844 (hide-subtree))
7845 (and for-yank (goto-char newend)))))
7847 (defun org-kill-is-subtree-p (&optional txt)
7848 "Check if the current kill is an outline subtree, or a set of trees.
7849 Returns nil if kill does not start with a headline, or if the first
7850 headline level is not the largest headline level in the tree.
7851 So this will actually accept several entries of equal levels as well,
7852 which is OK for `org-paste-subtree'.
7853 If optional TXT is given, check this string instead of the current kill."
7854 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7855 (re (org-get-limited-outline-regexp))
7856 (^re (concat "^" re))
7857 (start-level (and kill
7858 (string-match
7859 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7860 kill)
7861 (- (match-end 2) (match-beginning 2) 1)))
7862 (start (1+ (or (match-beginning 2) -1))))
7863 (if (not start-level)
7864 (progn
7865 nil) ;; does not even start with a heading
7866 (catch 'exit
7867 (while (setq start (string-match ^re kill (1+ start)))
7868 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7869 (throw 'exit nil)))
7870 t))))
7872 (defvar org-markers-to-move nil
7873 "Markers that should be moved with a cut-and-paste operation.
7874 Those markers are stored together with their positions relative to
7875 the start of the region.")
7877 (defun org-save-markers-in-region (beg end)
7878 "Check markers in region.
7879 If these markers are between BEG and END, record their position relative
7880 to BEG, so that after moving the block of text, we can put the markers back
7881 into place.
7882 This function gets called just before an entry or tree gets cut from the
7883 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7884 called immediately, to move the markers with the entries."
7885 (setq org-markers-to-move nil)
7886 (when (featurep 'org-clock)
7887 (org-clock-save-markers-for-cut-and-paste beg end))
7888 (when (featurep 'org-agenda)
7889 (org-agenda-save-markers-for-cut-and-paste beg end)))
7891 (defun org-check-and-save-marker (marker beg end)
7892 "Check if MARKER is between BEG and END.
7893 If yes, remember the marker and the distance to BEG."
7894 (when (and (marker-buffer marker)
7895 (equal (marker-buffer marker) (current-buffer)))
7896 (if (and (>= marker beg) (< marker end))
7897 (push (cons marker (- marker beg)) org-markers-to-move))))
7899 (defun org-reinstall-markers-in-region (beg)
7900 "Move all remembered markers to their position relative to BEG."
7901 (mapc (lambda (x)
7902 (move-marker (car x) (+ beg (cdr x))))
7903 org-markers-to-move)
7904 (setq org-markers-to-move nil))
7906 (defun org-narrow-to-subtree ()
7907 "Narrow buffer to the current subtree."
7908 (interactive)
7909 (save-excursion
7910 (save-match-data
7911 (org-with-limited-levels
7912 (narrow-to-region
7913 (progn (org-back-to-heading t) (point))
7914 (progn (org-end-of-subtree t t)
7915 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7916 (point)))))))
7918 (defun org-narrow-to-block ()
7919 "Narrow buffer to the current block."
7920 (interactive)
7921 (let* ((case-fold-search t)
7922 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7923 "^[ \t]*#\\+end_.*")))
7924 (if blockp
7925 (narrow-to-region (car blockp) (cdr blockp))
7926 (error "Not in a block"))))
7928 (eval-when-compile
7929 (defvar org-property-drawer-re))
7931 (defvar org-property-start-re) ;; defined below
7932 (defun org-clone-subtree-with-time-shift (n &optional shift)
7933 "Clone the task (subtree) at point N times.
7934 The clones will be inserted as siblings.
7936 In interactive use, the user will be prompted for the number of
7937 clones to be produced, and for a time SHIFT, which may be a
7938 repeater as used in time stamps, for example `+3d'.
7940 When a valid repeater is given and the entry contains any time
7941 stamps, the clones will become a sequence in time, with time
7942 stamps in the subtree shifted for each clone produced. If SHIFT
7943 is nil or the empty string, time stamps will be left alone. The
7944 ID property of the original subtree is removed.
7946 If the original subtree did contain time stamps with a repeater,
7947 the following will happen:
7948 - the repeater will be removed in each clone
7949 - an additional clone will be produced, with the current, unshifted
7950 date(s) in the entry.
7951 - the original entry will be placed *after* all the clones, with
7952 repeater intact.
7953 - the start days in the repeater in the original entry will be shifted
7954 to past the last clone.
7955 In this way you can spell out a number of instances of a repeating task,
7956 and still retain the repeater to cover future instances of the task."
7957 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7958 (let (beg end template task idprop
7959 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7960 (drawer-re org-drawer-regexp))
7961 (if (not (and (integerp n) (> n 0)))
7962 (error "Invalid number of replications %s" n))
7963 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7964 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7965 shift)))
7966 (error "Invalid shift specification %s" shift))
7967 (when doshift
7968 (setq shift-n (string-to-number (match-string 1 shift))
7969 shift-what (cdr (assoc (match-string 2 shift)
7970 '(("d" . day) ("w" . week)
7971 ("m" . month) ("y" . year))))))
7972 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7973 (setq nmin 1 nmax n)
7974 (org-back-to-heading t)
7975 (setq beg (point))
7976 (setq idprop (org-entry-get nil "ID"))
7977 (org-end-of-subtree t t)
7978 (or (bolp) (insert "\n"))
7979 (setq end (point))
7980 (setq template (buffer-substring beg end))
7981 (when (and doshift
7982 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7983 (delete-region beg end)
7984 (setq end beg)
7985 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7986 (goto-char end)
7987 (loop for n from nmin to nmax do
7988 ;; prepare clone
7989 (with-temp-buffer
7990 (insert template)
7991 (org-mode)
7992 (goto-char (point-min))
7993 (org-show-subtree)
7994 (and idprop (if org-clone-delete-id
7995 (org-entry-delete nil "ID")
7996 (org-id-get-create t)))
7997 (unless (= n 0)
7998 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7999 (kill-whole-line))
8000 (goto-char (point-min))
8001 (while (re-search-forward drawer-re nil t)
8002 (mapc (lambda (d)
8003 (org-remove-empty-drawer-at d (point))) org-drawers)))
8004 (goto-char (point-min))
8005 (when doshift
8006 (while (re-search-forward org-ts-regexp-both nil t)
8007 (org-timestamp-change (* n shift-n) shift-what))
8008 (unless (= n n-no-remove)
8009 (goto-char (point-min))
8010 (while (re-search-forward org-ts-regexp nil t)
8011 (save-excursion
8012 (goto-char (match-beginning 0))
8013 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8014 (delete-region (match-beginning 1) (match-end 1)))))))
8015 (setq task (buffer-string)))
8016 (insert task))
8017 (goto-char beg)))
8019 ;;; Outline Sorting
8021 (defun org-sort (with-case)
8022 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8023 Optional argument WITH-CASE means sort case-sensitively."
8024 (interactive "P")
8025 (cond
8026 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8027 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8029 (org-call-with-arg 'org-sort-entries with-case))))
8031 (defun org-sort-remove-invisible (s)
8032 (remove-text-properties 0 (length s) org-rm-props s)
8033 (while (string-match org-bracket-link-regexp s)
8034 (setq s (replace-match (if (match-end 2)
8035 (match-string 3 s)
8036 (match-string 1 s)) t t s)))
8039 (defvar org-priority-regexp) ; defined later in the file
8041 (defvar org-after-sorting-entries-or-items-hook nil
8042 "Hook that is run after a bunch of entries or items have been sorted.
8043 When children are sorted, the cursor is in the parent line when this
8044 hook gets called. When a region or a plain list is sorted, the cursor
8045 will be in the first entry of the sorted region/list.")
8047 (defun org-sort-entries
8048 (&optional with-case sorting-type getkey-func compare-func property)
8049 "Sort entries on a certain level of an outline tree.
8050 If there is an active region, the entries in the region are sorted.
8051 Else, if the cursor is before the first entry, sort the top-level items.
8052 Else, the children of the entry at point are sorted.
8054 Sorting can be alphabetically, numerically, by date/time as given by
8055 a time stamp, by a property or by priority.
8057 The command prompts for the sorting type unless it has been given to the
8058 function through the SORTING-TYPE argument, which needs to be a character,
8059 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8060 precise meaning of each character:
8062 n Numerically, by converting the beginning of the entry/item to a number.
8063 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8064 t By date/time, either the first active time stamp in the entry, or, if
8065 none exist, by the first inactive one.
8066 s By the scheduled date/time.
8067 d By deadline date/time.
8068 c By creation time, which is assumed to be the first inactive time stamp
8069 at the beginning of a line.
8070 p By priority according to the cookie.
8071 r By the value of a property.
8073 Capital letters will reverse the sort order.
8075 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8076 called with point at the beginning of the record. It must return either
8077 a string or a number that should serve as the sorting key for that record.
8079 Comparing entries ignores case by default. However, with an optional argument
8080 WITH-CASE, the sorting considers case as well."
8081 (interactive "P")
8082 (let ((case-func (if with-case 'identity 'downcase))
8083 start beg end stars re re2
8084 txt what tmp)
8085 ;; Find beginning and end of region to sort
8086 (cond
8087 ((org-region-active-p)
8088 ;; we will sort the region
8089 (setq end (region-end)
8090 what "region")
8091 (goto-char (region-beginning))
8092 (if (not (org-at-heading-p)) (outline-next-heading))
8093 (setq start (point)))
8094 ((or (org-at-heading-p)
8095 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8096 ;; we will sort the children of the current headline
8097 (org-back-to-heading)
8098 (setq start (point)
8099 end (progn (org-end-of-subtree t t)
8100 (or (bolp) (insert "\n"))
8101 (org-back-over-empty-lines)
8102 (point))
8103 what "children")
8104 (goto-char start)
8105 (show-subtree)
8106 (outline-next-heading))
8108 ;; we will sort the top-level entries in this file
8109 (goto-char (point-min))
8110 (or (org-at-heading-p) (outline-next-heading))
8111 (setq start (point))
8112 (goto-char (point-max))
8113 (beginning-of-line 1)
8114 (when (looking-at ".*?\\S-")
8115 ;; File ends in a non-white line
8116 (end-of-line 1)
8117 (insert "\n"))
8118 (setq end (point-max))
8119 (setq what "top-level")
8120 (goto-char start)
8121 (show-all)))
8123 (setq beg (point))
8124 (if (>= beg end) (error "Nothing to sort"))
8126 (looking-at "\\(\\*+\\)")
8127 (setq stars (match-string 1)
8128 re (concat "^" (regexp-quote stars) " +")
8129 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8130 txt (buffer-substring beg end))
8131 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8132 (if (and (not (equal stars "*")) (string-match re2 txt))
8133 (error "Region to sort contains a level above the first entry"))
8135 (unless sorting-type
8136 (message
8137 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8138 [t]ime [s]cheduled [d]eadline [c]reated
8139 A/N/T/S/D/C/P/O/F means reversed:"
8140 what)
8141 (setq sorting-type (read-char-exclusive))
8143 (and (= (downcase sorting-type) ?f)
8144 (setq getkey-func
8145 (org-icompleting-read "Sort using function: "
8146 obarray 'fboundp t nil nil))
8147 (setq getkey-func (intern getkey-func)))
8149 (and (= (downcase sorting-type) ?r)
8150 (setq property
8151 (org-icompleting-read "Property: "
8152 (mapcar 'list (org-buffer-property-keys t))
8153 nil t))))
8155 (message "Sorting entries...")
8157 (save-restriction
8158 (narrow-to-region start end)
8159 (let ((dcst (downcase sorting-type))
8160 (case-fold-search nil)
8161 (now (current-time)))
8162 (sort-subr
8163 (/= dcst sorting-type)
8164 ;; This function moves to the beginning character of the "record" to
8165 ;; be sorted.
8166 (lambda nil
8167 (if (re-search-forward re nil t)
8168 (goto-char (match-beginning 0))
8169 (goto-char (point-max))))
8170 ;; This function moves to the last character of the "record" being
8171 ;; sorted.
8172 (lambda nil
8173 (save-match-data
8174 (condition-case nil
8175 (outline-forward-same-level 1)
8176 (error
8177 (goto-char (point-max))))))
8178 ;; This function returns the value that gets sorted against.
8179 (lambda nil
8180 (cond
8181 ((= dcst ?n)
8182 (if (looking-at org-complex-heading-regexp)
8183 (string-to-number (match-string 4))
8184 nil))
8185 ((= dcst ?a)
8186 (if (looking-at org-complex-heading-regexp)
8187 (funcall case-func (match-string 4))
8188 nil))
8189 ((= dcst ?t)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (or (re-search-forward org-ts-regexp end t)
8192 (re-search-forward org-ts-regexp-both end t))
8193 (org-time-string-to-seconds (match-string 0))
8194 (org-float-time now))))
8195 ((= dcst ?c)
8196 (let ((end (save-excursion (outline-next-heading) (point))))
8197 (if (re-search-forward
8198 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8199 end t)
8200 (org-time-string-to-seconds (match-string 0))
8201 (org-float-time now))))
8202 ((= dcst ?s)
8203 (let ((end (save-excursion (outline-next-heading) (point))))
8204 (if (re-search-forward org-scheduled-time-regexp end t)
8205 (org-time-string-to-seconds (match-string 1))
8206 (org-float-time now))))
8207 ((= dcst ?d)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (re-search-forward org-deadline-time-regexp end t)
8210 (org-time-string-to-seconds (match-string 1))
8211 (org-float-time now))))
8212 ((= dcst ?p)
8213 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8214 (string-to-char (match-string 2))
8215 org-default-priority))
8216 ((= dcst ?r)
8217 (or (org-entry-get nil property) ""))
8218 ((= dcst ?o)
8219 (if (looking-at org-complex-heading-regexp)
8220 (- 9999 (length (member (match-string 2)
8221 org-todo-keywords-1)))))
8222 ((= dcst ?f)
8223 (if getkey-func
8224 (progn
8225 (setq tmp (funcall getkey-func))
8226 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8227 tmp)
8228 (error "Invalid key function `%s'" getkey-func)))
8229 (t (error "Invalid sorting type `%c'" sorting-type))))
8231 (cond
8232 ((= dcst ?a) 'string<)
8233 ((= dcst ?f) compare-func)
8234 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8235 (t nil)))))
8236 (run-hooks 'org-after-sorting-entries-or-items-hook)
8237 (message "Sorting entries...done")))
8239 (defun org-do-sort (table what &optional with-case sorting-type)
8240 "Sort TABLE of WHAT according to SORTING-TYPE.
8241 The user will be prompted for the SORTING-TYPE if the call to this
8242 function does not specify it. WHAT is only for the prompt, to indicate
8243 what is being sorted. The sorting key will be extracted from
8244 the car of the elements of the table.
8245 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8246 (unless sorting-type
8247 (message
8248 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8249 what)
8250 (setq sorting-type (read-char-exclusive)))
8251 (let ((dcst (downcase sorting-type))
8252 extractfun comparefun)
8253 ;; Define the appropriate functions
8254 (cond
8255 ((= dcst ?n)
8256 (setq extractfun 'string-to-number
8257 comparefun (if (= dcst sorting-type) '< '>)))
8258 ((= dcst ?a)
8259 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8260 (lambda(x) (downcase (org-sort-remove-invisible x))))
8261 comparefun (if (= dcst sorting-type)
8262 'string<
8263 (lambda (a b) (and (not (string< a b))
8264 (not (string= a b)))))))
8265 ((= dcst ?t)
8266 (setq extractfun
8267 (lambda (x)
8268 (if (or (string-match org-ts-regexp x)
8269 (string-match org-ts-regexp-both x))
8270 (org-float-time
8271 (org-time-string-to-time (match-string 0 x)))
8273 comparefun (if (= dcst sorting-type) '< '>)))
8274 (t (error "Invalid sorting type `%c'" sorting-type)))
8276 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8277 table)
8278 (lambda (a b) (funcall comparefun (car a) (car b))))))
8281 ;;; The orgstruct minor mode
8283 ;; Define a minor mode which can be used in other modes in order to
8284 ;; integrate the org-mode structure editing commands.
8286 ;; This is really a hack, because the org-mode structure commands use
8287 ;; keys which normally belong to the major mode. Here is how it
8288 ;; works: The minor mode defines all the keys necessary to operate the
8289 ;; structure commands, but wraps the commands into a function which
8290 ;; tests if the cursor is currently at a headline or a plain list
8291 ;; item. If that is the case, the structure command is used,
8292 ;; temporarily setting many Org-mode variables like regular
8293 ;; expressions for filling etc. However, when any of those keys is
8294 ;; used at a different location, function uses `key-binding' to look
8295 ;; up if the key has an associated command in another currently active
8296 ;; keymap (minor modes, major mode, global), and executes that
8297 ;; command. There might be problems if any of the keys is otherwise
8298 ;; used as a prefix key.
8300 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8301 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8302 ;; addresses this by checking explicitly for both bindings.
8304 (defvar orgstruct-mode-map (make-sparse-keymap)
8305 "Keymap for the minor `orgstruct-mode'.")
8307 (defvar org-local-vars nil
8308 "List of local variables, for use by `orgstruct-mode'.")
8310 ;;;###autoload
8311 (define-minor-mode orgstruct-mode
8312 "Toggle the minor mode `orgstruct-mode'.
8313 This mode is for using Org-mode structure commands in other
8314 modes. The following keys behave as if Org-mode were active, if
8315 the cursor is on a headline, or on a plain list item (both as
8316 defined by Org-mode).
8318 M-up Move entry/item up
8319 M-down Move entry/item down
8320 M-left Promote
8321 M-right Demote
8322 M-S-up Move entry/item up
8323 M-S-down Move entry/item down
8324 M-S-left Promote subtree
8325 M-S-right Demote subtree
8326 M-q Fill paragraph and items like in Org-mode
8327 C-c ^ Sort entries
8328 C-c - Cycle list bullet
8329 TAB Cycle item visibility
8330 M-RET Insert new heading/item
8331 S-M-RET Insert new TODO heading / Checkbox item
8332 C-c C-c Set tags / toggle checkbox"
8333 nil " OrgStruct" nil
8334 (org-load-modules-maybe)
8335 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8337 ;;;###autoload
8338 (defun turn-on-orgstruct ()
8339 "Unconditionally turn on `orgstruct-mode'."
8340 (orgstruct-mode 1))
8342 (defun orgstruct++-mode (&optional arg)
8343 "Toggle `orgstruct-mode', the enhanced version of it.
8344 In addition to setting orgstruct-mode, this also exports all indentation
8345 and autofilling variables from org-mode into the buffer. It will also
8346 recognize item context in multiline items.
8347 Note that turning off orgstruct-mode will *not* remove the
8348 indentation/paragraph settings. This can only be done by refreshing the
8349 major mode, for example with \\[normal-mode]."
8350 (interactive "P")
8351 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8352 (if (< arg 1)
8353 (orgstruct-mode -1)
8354 (orgstruct-mode 1)
8355 (let (var val)
8356 (mapc
8357 (lambda (x)
8358 (when (string-match
8359 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8360 (symbol-name (car x)))
8361 (setq var (car x) val (nth 1 x))
8362 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8363 org-local-vars)
8364 (org-set-local 'orgstruct-is-++ t))))
8366 (defvar orgstruct-is-++ nil
8367 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8368 (make-variable-buffer-local 'orgstruct-is-++)
8370 ;;;###autoload
8371 (defun turn-on-orgstruct++ ()
8372 "Unconditionally turn on `orgstruct++-mode'."
8373 (orgstruct++-mode 1))
8375 (defun orgstruct-error ()
8376 "Error when there is no default binding for a structure key."
8377 (interactive)
8378 (error "This key has no function outside structure elements"))
8380 (defun orgstruct-setup ()
8381 "Setup orgstruct keymaps."
8382 (let ((nfunc 0)
8383 (bindings
8384 (list
8385 '([(meta up)] org-metaup)
8386 '([(meta down)] org-metadown)
8387 '([(meta left)] org-metaleft)
8388 '([(meta right)] org-metaright)
8389 '([(meta shift up)] org-shiftmetaup)
8390 '([(meta shift down)] org-shiftmetadown)
8391 '([(meta shift left)] org-shiftmetaleft)
8392 '([(meta shift right)] org-shiftmetaright)
8393 '([?\e (up)] org-metaup)
8394 '([?\e (down)] org-metadown)
8395 '([?\e (left)] org-metaleft)
8396 '([?\e (right)] org-metaright)
8397 '([?\e (shift up)] org-shiftmetaup)
8398 '([?\e (shift down)] org-shiftmetadown)
8399 '([?\e (shift left)] org-shiftmetaleft)
8400 '([?\e (shift right)] org-shiftmetaright)
8401 '([(shift up)] org-shiftup)
8402 '([(shift down)] org-shiftdown)
8403 '([(shift left)] org-shiftleft)
8404 '([(shift right)] org-shiftright)
8405 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8406 '("\M-q" fill-paragraph)
8407 '("\C-c^" org-sort)
8408 '("\C-c-" org-cycle-list-bullet)))
8409 elt key fun cmd)
8410 (while (setq elt (pop bindings))
8411 (setq nfunc (1+ nfunc))
8412 (setq key (org-key (car elt))
8413 fun (nth 1 elt)
8414 cmd (orgstruct-make-binding fun nfunc key))
8415 (org-defkey orgstruct-mode-map key cmd))
8417 ;; Special treatment needed for TAB and RET
8418 (org-defkey orgstruct-mode-map [(tab)]
8419 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8420 (org-defkey orgstruct-mode-map "\C-i"
8421 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8423 (org-defkey orgstruct-mode-map "\M-\C-m"
8424 (orgstruct-make-binding 'org-insert-heading 105
8425 "\M-\C-m" [(meta return)]))
8426 (org-defkey orgstruct-mode-map [(meta return)]
8427 (orgstruct-make-binding 'org-insert-heading 106
8428 [(meta return)] "\M-\C-m"))
8430 (org-defkey orgstruct-mode-map [(shift meta return)]
8431 (orgstruct-make-binding 'org-insert-todo-heading 107
8432 [(meta return)] "\M-\C-m"))
8434 (org-defkey orgstruct-mode-map "\e\C-m"
8435 (orgstruct-make-binding 'org-insert-heading 108
8436 "\e\C-m" [?\e (return)]))
8437 (org-defkey orgstruct-mode-map [?\e (return)]
8438 (orgstruct-make-binding 'org-insert-heading 109
8439 [?\e (return)] "\e\C-m"))
8440 (org-defkey orgstruct-mode-map [?\e (shift return)]
8441 (orgstruct-make-binding 'org-insert-todo-heading 110
8442 [?\e (return)] "\e\C-m"))
8444 (unless org-local-vars
8445 (setq org-local-vars (org-get-local-variables)))
8449 (defun orgstruct-make-binding (fun n &rest keys)
8450 "Create a function for binding in the structure minor mode.
8451 FUN is the command to call inside a table. N is used to create a unique
8452 command name. KEYS are keys that should be checked in for a command
8453 to execute outside of tables."
8454 (eval
8455 (list 'defun
8456 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8457 '(arg)
8458 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8459 "Outside of structure, run the binding of `"
8460 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8461 "'.")
8462 '(interactive "p")
8463 (list 'if
8464 `(org-context-p 'headline 'item
8465 (and orgstruct-is-++
8466 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8467 'item-body))
8468 (list 'org-run-like-in-org-mode (list 'quote fun))
8469 (list 'let '(orgstruct-mode)
8470 (list 'call-interactively
8471 (append '(or)
8472 (mapcar (lambda (k)
8473 (list 'key-binding k))
8474 keys)
8475 '('orgstruct-error))))))))
8477 (defun org-context-p (&rest contexts)
8478 "Check if local context is any of CONTEXTS.
8479 Possible values in the list of contexts are `table', `headline', and `item'."
8480 (let ((pos (point)))
8481 (goto-char (point-at-bol))
8482 (prog1 (or (and (memq 'table contexts)
8483 (looking-at "[ \t]*|"))
8484 (and (memq 'headline contexts)
8485 (looking-at org-outline-regexp))
8486 (and (memq 'item contexts)
8487 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8488 (and (memq 'item-body contexts)
8489 (org-in-item-p)))
8490 (goto-char pos))))
8492 (defun org-get-local-variables ()
8493 "Return a list of all local variables in an org-mode buffer."
8494 (let (varlist)
8495 (with-current-buffer (get-buffer-create "*Org tmp*")
8496 (erase-buffer)
8497 (org-mode)
8498 (setq varlist (buffer-local-variables)))
8499 (kill-buffer "*Org tmp*")
8500 (delq nil
8501 (mapcar
8502 (lambda (x)
8503 (setq x
8504 (if (symbolp x)
8505 (list x)
8506 (list (car x) (list 'quote (cdr x)))))
8507 (if (string-match
8508 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8509 (symbol-name (car x)))
8510 x nil))
8511 varlist))))
8513 (defun org-clone-local-variables (from-buffer &optional regexp)
8514 "Clone local variables from FROM-BUFFER.
8515 Optional argument REGEXP selects variables to clone."
8516 (mapc
8517 (lambda (pair)
8518 (and (symbolp (car pair))
8519 (or (null regexp)
8520 (string-match regexp (symbol-name (car pair))))
8521 (set (make-local-variable (car pair))
8522 (cdr pair))))
8523 (buffer-local-variables from-buffer)))
8525 ;;;###autoload
8526 (defun org-run-like-in-org-mode (cmd)
8527 "Run a command, pretending that the current buffer is in Org-mode.
8528 This will temporarily bind local variables that are typically bound in
8529 Org-mode to the values they have in Org-mode, and then interactively
8530 call CMD."
8531 (org-load-modules-maybe)
8532 (unless org-local-vars
8533 (setq org-local-vars (org-get-local-variables)))
8534 (eval (list 'let org-local-vars
8535 (list 'call-interactively (list 'quote cmd)))))
8537 ;;;; Archiving
8539 (defun org-get-category (&optional pos force-refresh)
8540 "Get the category applying to position POS."
8541 (save-match-data
8542 (if force-refresh (org-refresh-category-properties))
8543 (let ((pos (or pos (point))))
8544 (or (get-text-property pos 'org-category)
8545 (progn (org-refresh-category-properties)
8546 (get-text-property pos 'org-category))))))
8548 (defun org-refresh-category-properties ()
8549 "Refresh category text properties in the buffer."
8550 (let ((def-cat (cond
8551 ((null org-category)
8552 (if buffer-file-name
8553 (file-name-sans-extension
8554 (file-name-nondirectory buffer-file-name))
8555 "???"))
8556 ((symbolp org-category) (symbol-name org-category))
8557 (t org-category)))
8558 beg end cat pos optionp)
8559 (org-unmodified
8560 (save-excursion
8561 (save-restriction
8562 (widen)
8563 (goto-char (point-min))
8564 (put-text-property (point) (point-max) 'org-category def-cat)
8565 (while (re-search-forward
8566 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8567 (setq pos (match-end 0)
8568 optionp (equal (char-after (match-beginning 0)) ?#)
8569 cat (org-trim (match-string 2)))
8570 (if optionp
8571 (setq beg (point-at-bol) end (point-max))
8572 (org-back-to-heading t)
8573 (setq beg (point) end (org-end-of-subtree t t)))
8574 (put-text-property beg end 'org-category cat)
8575 (put-text-property beg end 'org-category-position beg)
8576 (goto-char pos)))))))
8579 ;;;; Link Stuff
8581 ;;; Link abbreviations
8583 (defun org-link-expand-abbrev (link)
8584 "Apply replacements as defined in `org-link-abbrev-alist."
8585 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8586 (let* ((key (match-string 1 link))
8587 (as (or (assoc key org-link-abbrev-alist-local)
8588 (assoc key org-link-abbrev-alist)))
8589 (tag (and (match-end 2) (match-string 3 link)))
8590 rpl)
8591 (if (not as)
8592 link
8593 (setq rpl (cdr as))
8594 (cond
8595 ((symbolp rpl) (funcall rpl tag))
8596 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8597 ((string-match "%h" rpl)
8598 (replace-match (url-hexify-string (or tag "")) t t rpl))
8599 (t (concat rpl tag)))))
8600 link))
8602 ;;; Storing and inserting links
8604 (defvar org-insert-link-history nil
8605 "Minibuffer history for links inserted with `org-insert-link'.")
8607 (defvar org-stored-links nil
8608 "Contains the links stored with `org-store-link'.")
8610 (defvar org-store-link-plist nil
8611 "Plist with info about the most recently link created with `org-store-link'.")
8613 (defvar org-link-protocols nil
8614 "Link protocols added to Org-mode using `org-add-link-type'.")
8616 (defvar org-store-link-functions nil
8617 "List of functions that are called to create and store a link.
8618 Each function will be called in turn until one returns a non-nil
8619 value. Each function should check if it is responsible for creating
8620 this link (for example by looking at the major mode).
8621 If not, it must exit and return nil.
8622 If yes, it should return a non-nil value after a calling
8623 `org-store-link-props' with a list of properties and values.
8624 Special properties are:
8626 :type The link prefix, like \"http\". This must be given.
8627 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8628 This is obligatory as well.
8629 :description Optional default description for the second pair
8630 of brackets in an Org-mode link. The user can still change
8631 this when inserting this link into an Org-mode buffer.
8633 In addition to these, any additional properties can be specified
8634 and then used in remember templates.")
8636 (defun org-add-link-type (type &optional follow export)
8637 "Add TYPE to the list of `org-link-types'.
8638 Re-compute all regular expressions depending on `org-link-types'
8640 FOLLOW and EXPORT are two functions.
8642 FOLLOW should take the link path as the single argument and do whatever
8643 is necessary to follow the link, for example find a file or display
8644 a mail message.
8646 EXPORT should format the link path for export to one of the export formats.
8647 It should be a function accepting three arguments:
8649 path the path of the link, the text after the prefix (like \"http:\")
8650 desc the description of the link, if any, or a description added by
8651 org-export-normalize-links if there is none
8652 format the export format, a symbol like `html' or `latex' or `ascii'..
8654 The function may use the FORMAT information to return different values
8655 depending on the format. The return value will be put literally into
8656 the exported file. If the return value is nil, this means Org should
8657 do what it normally does with links which do not have EXPORT defined.
8659 Org-mode has a built-in default for exporting links. If you are happy with
8660 this default, there is no need to define an export function for the link
8661 type. For a simple example of an export function, see `org-bbdb.el'."
8662 (add-to-list 'org-link-types type t)
8663 (org-make-link-regexps)
8664 (if (assoc type org-link-protocols)
8665 (setcdr (assoc type org-link-protocols) (list follow export))
8666 (push (list type follow export) org-link-protocols)))
8668 (defvar org-agenda-buffer-name)
8670 ;;;###autoload
8671 (defun org-store-link (arg)
8672 "\\<org-mode-map>Store an org-link to the current location.
8673 This link is added to `org-stored-links' and can later be inserted
8674 into an org-buffer with \\[org-insert-link].
8676 For some link types, a prefix arg is interpreted:
8677 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8678 For file links, arg negates `org-context-in-file-links'."
8679 (interactive "P")
8680 (org-load-modules-maybe)
8681 (setq org-store-link-plist nil) ; reset
8682 (org-with-limited-levels
8683 (let (link cpltxt desc description search txt custom-id agenda-link)
8684 (cond
8686 ((run-hook-with-args-until-success 'org-store-link-functions)
8687 (setq link (plist-get org-store-link-plist :link)
8688 desc (or (plist-get org-store-link-plist :description) link)))
8690 ((equal (buffer-name) "*Org Edit Src Example*")
8691 (let (label gc)
8692 (while (or (not label)
8693 (save-excursion
8694 (save-restriction
8695 (widen)
8696 (goto-char (point-min))
8697 (re-search-forward
8698 (regexp-quote (format org-coderef-label-format label))
8699 nil t))))
8700 (when label (message "Label exists already") (sit-for 2))
8701 (setq label (read-string "Code line label: " label)))
8702 (end-of-line 1)
8703 (setq link (format org-coderef-label-format label))
8704 (setq gc (- 79 (length link)))
8705 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8706 (insert link)
8707 (setq link (concat "(" label ")") desc nil)))
8709 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8710 ;; We are in the agenda, link to referenced location
8711 (let ((m (or (get-text-property (point) 'org-hd-marker)
8712 (get-text-property (point) 'org-marker))))
8713 (when m
8714 (org-with-point-at m
8715 (setq agenda-link
8716 (if (org-called-interactively-p 'any)
8717 (call-interactively 'org-store-link)
8718 (org-store-link nil)))))))
8720 ((eq major-mode 'calendar-mode)
8721 (let ((cd (calendar-cursor-to-date)))
8722 (setq link
8723 (format-time-string
8724 (car org-time-stamp-formats)
8725 (apply 'encode-time
8726 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8727 nil nil nil))))
8728 (org-store-link-props :type "calendar" :date cd)))
8730 ((eq major-mode 'w3-mode)
8731 (setq cpltxt (if (and (buffer-name)
8732 (not (string-match "Untitled" (buffer-name))))
8733 (buffer-name)
8734 (url-view-url t))
8735 link (org-make-link (url-view-url t)))
8736 (org-store-link-props :type "w3" :url (url-view-url t)))
8738 ((eq major-mode 'w3m-mode)
8739 (setq cpltxt (or w3m-current-title w3m-current-url)
8740 link (org-make-link w3m-current-url))
8741 (org-store-link-props :type "w3m" :url (url-view-url t)))
8743 ((setq search (run-hook-with-args-until-success
8744 'org-create-file-search-functions))
8745 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8746 "::" search))
8747 (setq cpltxt (or description link)))
8749 ((eq major-mode 'image-mode)
8750 (setq cpltxt (concat "file:"
8751 (abbreviate-file-name buffer-file-name))
8752 link (org-make-link cpltxt))
8753 (org-store-link-props :type "image" :file buffer-file-name))
8755 ((eq major-mode 'dired-mode)
8756 ;; link to the file in the current line
8757 (let ((file (dired-get-filename nil t)))
8758 (setq file (if file
8759 (abbreviate-file-name
8760 (expand-file-name (dired-get-filename nil t)))
8761 ;; otherwise, no file so use current directory.
8762 default-directory))
8763 (setq cpltxt (concat "file:" file)
8764 link (org-make-link cpltxt))))
8766 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8767 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8768 (cond
8769 ((org-in-regexp "<<\\(.*?\\)>>")
8770 (setq cpltxt
8771 (concat "file:"
8772 (abbreviate-file-name
8773 (buffer-file-name (buffer-base-buffer)))
8774 "::" (match-string 1))
8775 link (org-make-link cpltxt)))
8776 ((and (featurep 'org-id)
8777 (or (eq org-link-to-org-use-id t)
8778 (and (eq org-link-to-org-use-id 'create-if-interactive)
8779 (org-called-interactively-p 'any))
8780 (and (eq org-link-to-org-use-id
8781 'create-if-interactive-and-no-custom-id)
8782 (org-called-interactively-p 'any)
8783 (not custom-id))
8784 (and org-link-to-org-use-id
8785 (org-entry-get nil "ID"))))
8786 ;; We can make a link using the ID.
8787 (setq link (condition-case nil
8788 (prog1 (org-id-store-link)
8789 (setq desc (plist-get org-store-link-plist
8790 :description)))
8791 (error
8792 ;; probably before first headline, link to file only
8793 (concat "file:"
8794 (abbreviate-file-name
8795 (buffer-file-name (buffer-base-buffer))))))))
8797 ;; Just link to current headline
8798 (setq cpltxt (concat "file:"
8799 (abbreviate-file-name
8800 (buffer-file-name (buffer-base-buffer)))))
8801 ;; Add a context search string
8802 (when (org-xor org-context-in-file-links arg)
8803 (setq txt (cond
8804 ((org-at-heading-p) nil)
8805 ((org-region-active-p)
8806 (buffer-substring (region-beginning) (region-end)))
8807 (t nil)))
8808 (when (or (null txt) (string-match "\\S-" txt))
8809 (setq cpltxt
8810 (concat cpltxt "::"
8811 (condition-case nil
8812 (org-make-org-heading-search-string txt)
8813 (error "")))
8814 desc (or (nth 4 (ignore-errors
8815 (org-heading-components))) "NONE"))))
8816 (if (string-match "::\\'" cpltxt)
8817 (setq cpltxt (substring cpltxt 0 -2)))
8818 (setq link (org-make-link cpltxt)))))
8820 ((buffer-file-name (buffer-base-buffer))
8821 ;; Just link to this file here.
8822 (setq cpltxt (concat "file:"
8823 (abbreviate-file-name
8824 (buffer-file-name (buffer-base-buffer)))))
8825 ;; Add a context string
8826 (when (org-xor org-context-in-file-links arg)
8827 (setq txt (if (org-region-active-p)
8828 (buffer-substring (region-beginning) (region-end))
8829 (buffer-substring (point-at-bol) (point-at-eol))))
8830 ;; Only use search option if there is some text.
8831 (when (string-match "\\S-" txt)
8832 (setq cpltxt
8833 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8834 desc "NONE")))
8835 (setq link (org-make-link cpltxt)))
8837 ((org-called-interactively-p 'interactive)
8838 (error "Cannot link to a buffer which is not visiting a file"))
8840 (t (setq link nil)))
8842 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8843 (setq link (or link cpltxt)
8844 desc (or desc cpltxt))
8845 (if (equal desc "NONE") (setq desc nil))
8847 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8848 (progn
8849 (setq org-stored-links
8850 (cons (list link desc) org-stored-links))
8851 (message "Stored: %s" (or desc link))
8852 (when custom-id
8853 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8854 "::#" custom-id))
8855 (setq org-stored-links
8856 (cons (list link desc) org-stored-links))))
8857 (or agenda-link (and link (org-make-link-string link desc)))))))
8859 (defun org-store-link-props (&rest plist)
8860 "Store link properties, extract names and addresses."
8861 (let (x adr)
8862 (when (setq x (plist-get plist :from))
8863 (setq adr (mail-extract-address-components x))
8864 (setq plist (plist-put plist :fromname (car adr)))
8865 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8866 (when (setq x (plist-get plist :to))
8867 (setq adr (mail-extract-address-components x))
8868 (setq plist (plist-put plist :toname (car adr)))
8869 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8870 (let ((from (plist-get plist :from))
8871 (to (plist-get plist :to)))
8872 (when (and from to org-from-is-user-regexp)
8873 (setq plist
8874 (plist-put plist :fromto
8875 (if (string-match org-from-is-user-regexp from)
8876 (concat "to %t")
8877 (concat "from %f"))))))
8878 (setq org-store-link-plist plist))
8880 (defun org-add-link-props (&rest plist)
8881 "Add these properties to the link property list."
8882 (let (key value)
8883 (while plist
8884 (setq key (pop plist) value (pop plist))
8885 (setq org-store-link-plist
8886 (plist-put org-store-link-plist key value)))))
8888 (defun org-email-link-description (&optional fmt)
8889 "Return the description part of an email link.
8890 This takes information from `org-store-link-plist' and formats it
8891 according to FMT (default from `org-email-link-description-format')."
8892 (setq fmt (or fmt org-email-link-description-format))
8893 (let* ((p org-store-link-plist)
8894 (to (plist-get p :toaddress))
8895 (from (plist-get p :fromaddress))
8896 (table
8897 (list
8898 (cons "%c" (plist-get p :fromto))
8899 (cons "%F" (plist-get p :from))
8900 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8901 (cons "%T" (plist-get p :to))
8902 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8903 (cons "%s" (plist-get p :subject))
8904 (cons "%d" (plist-get p :date))
8905 (cons "%m" (plist-get p :message-id)))))
8906 (when (string-match "%c" fmt)
8907 ;; Check if the user wrote this message
8908 (if (and org-from-is-user-regexp from to
8909 (save-match-data (string-match org-from-is-user-regexp from)))
8910 (setq fmt (replace-match "to %t" t t fmt))
8911 (setq fmt (replace-match "from %f" t t fmt))))
8912 (org-replace-escapes fmt table)))
8914 (defun org-make-org-heading-search-string (&optional string heading)
8915 "Make search string for STRING or current headline."
8916 (interactive)
8917 (let ((s (or string (org-get-heading)))
8918 (lines org-context-in-file-links))
8919 (unless (and string (not heading))
8920 ;; We are using a headline, clean up garbage in there.
8921 (if (string-match org-todo-regexp s)
8922 (setq s (replace-match "" t t s)))
8923 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8924 (setq s (replace-match "" t t s)))
8925 (setq s (org-trim s))
8926 (if (string-match (concat "^\\(" org-quote-string "\\|"
8927 org-comment-string "\\)") s)
8928 (setq s (replace-match "" t t s)))
8929 (while (string-match org-ts-regexp s)
8930 (setq s (replace-match "" t t s))))
8931 (or string (setq s (concat "*" s))) ; Add * for headlines
8932 (when (and string (integerp lines) (> lines 0))
8933 (let ((slines (org-split-string s "\n")))
8934 (when (< lines (length slines))
8935 (setq s (mapconcat
8936 'identity
8937 (reverse (nthcdr (- (length slines) lines)
8938 (reverse slines))) "\n")))))
8939 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8941 (defun org-make-link (&rest strings)
8942 "Concatenate STRINGS."
8943 (apply 'concat strings))
8945 (defun org-make-link-string (link &optional description)
8946 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8947 (unless (string-match "\\S-" link)
8948 (error "Empty link"))
8949 (when (and description
8950 (stringp description)
8951 (not (string-match "\\S-" description)))
8952 (setq description nil))
8953 (when (stringp description)
8954 ;; Remove brackets from the description, they are fatal.
8955 (while (string-match "\\[" description)
8956 (setq description (replace-match "{" t t description)))
8957 (while (string-match "\\]" description)
8958 (setq description (replace-match "}" t t description))))
8959 (when (equal link description)
8960 ;; No description needed, it is identical
8961 (setq description nil))
8962 (when (and (not description)
8963 (not (string-match (org-image-file-name-regexp) link))
8964 (not (equal link (org-link-escape link))))
8965 (setq description (org-extract-attributes link)))
8966 (setq link
8967 (cond ((string-match (org-image-file-name-regexp) link) link)
8968 ((string-match org-link-types-re link)
8969 (concat (match-string 1 link)
8970 (org-link-escape (substring link (match-end 1)))))
8971 (t (org-link-escape link))))
8972 (concat "[[" link "]"
8973 (if description (concat "[" description "]") "")
8974 "]"))
8976 (defconst org-link-escape-chars
8977 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8978 "List of characters that should be escaped in link.
8979 This is the list that is used for internal purposes.")
8981 (defvar org-url-encoding-use-url-hexify nil)
8983 (defconst org-link-escape-chars-browser
8984 '(?\ )
8985 "List of escapes for characters that are problematic in links.
8986 This is the list that is used before handing over to the browser.")
8988 (defun org-link-escape (text &optional table merge)
8989 "Return percent escaped representation of TEXT.
8990 TEXT is a string with the text to escape.
8991 Optional argument TABLE is a list with characters that should be
8992 escaped. When nil, `org-link-escape-chars' is used.
8993 If optional argument MERGE is set, merge TABLE into
8994 `org-link-escape-chars'."
8995 (if (and org-url-encoding-use-url-hexify (not table))
8996 (url-hexify-string text)
8997 (cond
8998 ((and table merge)
8999 (mapc (lambda (defchr)
9000 (unless (member defchr table)
9001 (setq table (cons defchr table)))) org-link-escape-chars))
9002 ((null table)
9003 (setq table org-link-escape-chars)))
9004 (mapconcat
9005 (lambda (char)
9006 (if (or (member char table)
9007 (< char 32) (= char 37) (> char 126))
9008 (mapconcat (lambda (sequence-element)
9009 (format "%%%.2X" sequence-element))
9010 (or (encode-coding-char char 'utf-8)
9011 (error "Unable to percent escape character: %s"
9012 (char-to-string char))) "")
9013 (char-to-string char))) text "")))
9015 (defun org-link-unescape (str)
9016 "Unhex hexified Unicode strings as returned from the JavaScript function
9017 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9018 (unless (and (null str) (string= "" str))
9019 (let ((pos 0) (case-fold-search t) unhexed)
9020 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9021 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9022 (setq str (replace-match unhexed t t str))
9023 (setq pos (+ pos (length unhexed))))))
9024 str)
9026 (defun org-link-unescape-compound (hex)
9027 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9028 Note: this function also decodes single byte encodings like
9029 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9030 (save-match-data
9031 (let* ((bytes (cdr (split-string hex "%")))
9032 (ret "")
9033 (eat 0)
9034 (sum 0))
9035 (while bytes
9036 (let* ((val (string-to-number (pop bytes) 16))
9037 (shift-xor
9038 (if (= 0 eat)
9039 (cond
9040 ((>= val 252) (cons 6 252))
9041 ((>= val 248) (cons 5 248))
9042 ((>= val 240) (cons 4 240))
9043 ((>= val 224) (cons 3 224))
9044 ((>= val 192) (cons 2 192))
9045 (t (cons 0 0)))
9046 (cons 6 128))))
9047 (if (>= val 192) (setq eat (car shift-xor)))
9048 (setq val (logxor val (cdr shift-xor)))
9049 (setq sum (+ (lsh sum (car shift-xor)) val))
9050 (if (> eat 0) (setq eat (- eat 1)))
9051 (cond
9052 ((= 0 eat) ;multi byte
9053 (setq ret (concat ret (org-char-to-string sum)))
9054 (setq sum 0))
9055 ((not bytes) ; single byte(s)
9056 (setq ret (org-link-unescape-single-byte-sequence hex))))
9057 )) ;; end (while bytes
9058 ret )))
9060 (defun org-link-unescape-single-byte-sequence (hex)
9061 "Unhexify hex-encoded single byte character sequences."
9062 (mapconcat (lambda (byte)
9063 (char-to-string (string-to-number byte 16)))
9064 (cdr (split-string hex "%")) ""))
9066 (defun org-xor (a b)
9067 "Exclusive or."
9068 (if a (not b) b))
9070 (defun org-fixup-message-id-for-http (s)
9071 "Replace special characters in a message id, so it can be used in an http query."
9072 (when (string-match "%" s)
9073 (setq s (mapconcat (lambda (c)
9074 (if (eq c ?%)
9075 "%25"
9076 (char-to-string c)))
9077 s "")))
9078 (while (string-match "<" s)
9079 (setq s (replace-match "%3C" t t s)))
9080 (while (string-match ">" s)
9081 (setq s (replace-match "%3E" t t s)))
9082 (while (string-match "@" s)
9083 (setq s (replace-match "%40" t t s)))
9086 ;;;###autoload
9087 (defun org-insert-link-global ()
9088 "Insert a link like Org-mode does.
9089 This command can be called in any mode to insert a link in Org-mode syntax."
9090 (interactive)
9091 (org-load-modules-maybe)
9092 (org-run-like-in-org-mode 'org-insert-link))
9094 (defun org-insert-link (&optional complete-file link-location default-description)
9095 "Insert a link. At the prompt, enter the link.
9097 Completion can be used to insert any of the link protocol prefixes like
9098 http or ftp in use.
9100 The history can be used to select a link previously stored with
9101 `org-store-link'. When the empty string is entered (i.e. if you just
9102 press RET at the prompt), the link defaults to the most recently
9103 stored link. As SPC triggers completion in the minibuffer, you need to
9104 use M-SPC or C-q SPC to force the insertion of a space character.
9106 You will also be prompted for a description, and if one is given, it will
9107 be displayed in the buffer instead of the link.
9109 If there is already a link at point, this command will allow you to edit link
9110 and description parts.
9112 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9113 be selected using completion. The path to the file will be relative to the
9114 current directory if the file is in the current directory or a subdirectory.
9115 Otherwise, the link will be the absolute path as completed in the minibuffer
9116 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9117 option `org-link-file-path-type'.
9119 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9120 the current directory or below.
9122 With three \\[universal-argument] prefixes, negate the meaning of
9123 `org-keep-stored-link-after-insertion'.
9125 If `org-make-link-description-function' is non-nil, this function will be
9126 called with the link target, and the result will be the default
9127 link description.
9129 If the LINK-LOCATION parameter is non-nil, this value will be
9130 used as the link location instead of reading one interactively.
9132 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9133 be used as the default description."
9134 (interactive "P")
9135 (let* ((wcf (current-window-configuration))
9136 (region (if (org-region-active-p)
9137 (buffer-substring (region-beginning) (region-end))))
9138 (remove (and region (list (region-beginning) (region-end))))
9139 (desc region)
9140 tmphist ; byte-compile incorrectly complains about this
9141 (link link-location)
9142 entry file all-prefixes)
9143 (cond
9144 (link-location) ; specified by arg, just use it.
9145 ((org-in-regexp org-bracket-link-regexp 1)
9146 ;; We do have a link at point, and we are going to edit it.
9147 (setq remove (list (match-beginning 0) (match-end 0)))
9148 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9149 (setq link (read-string "Link: "
9150 (org-link-unescape
9151 (org-match-string-no-properties 1)))))
9152 ((or (org-in-regexp org-angle-link-re)
9153 (org-in-regexp org-plain-link-re))
9154 ;; Convert to bracket link
9155 (setq remove (list (match-beginning 0) (match-end 0))
9156 link (read-string "Link: "
9157 (org-remove-angle-brackets (match-string 0)))))
9158 ((member complete-file '((4) (16)))
9159 ;; Completing read for file names.
9160 (setq link (org-file-complete-link complete-file)))
9162 ;; Read link, with completion for stored links.
9163 (with-output-to-temp-buffer "*Org Links*"
9164 (princ "Insert a link.
9165 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9166 (when org-stored-links
9167 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9168 (princ (mapconcat
9169 (lambda (x)
9170 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9171 (reverse org-stored-links) "\n"))))
9172 (let ((cw (selected-window)))
9173 (select-window (get-buffer-window "*Org Links*" 'visible))
9174 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9175 (unless (pos-visible-in-window-p (point-max))
9176 (org-fit-window-to-buffer))
9177 (and (window-live-p cw) (select-window cw)))
9178 ;; Fake a link history, containing the stored links.
9179 (setq tmphist (append (mapcar 'car org-stored-links)
9180 org-insert-link-history))
9181 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9182 (mapcar 'car org-link-abbrev-alist)
9183 org-link-types))
9184 (unwind-protect
9185 (progn
9186 (setq link
9187 (let ((org-completion-use-ido nil)
9188 (org-completion-use-iswitchb nil))
9189 (org-completing-read
9190 "Link: "
9191 (append
9192 (mapcar (lambda (x) (list (concat x ":")))
9193 all-prefixes)
9194 (mapcar 'car org-stored-links))
9195 nil nil nil
9196 'tmphist
9197 (car (car org-stored-links)))))
9198 (if (not (string-match "\\S-" link))
9199 (error "No link selected"))
9200 (if (or (member link all-prefixes)
9201 (and (equal ":" (substring link -1))
9202 (member (substring link 0 -1) all-prefixes)
9203 (setq link (substring link 0 -1))))
9204 (setq link (org-link-try-special-completion link))))
9205 (set-window-configuration wcf)
9206 (kill-buffer "*Org Links*"))
9207 (setq entry (assoc link org-stored-links))
9208 (or entry (push link org-insert-link-history))
9209 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9210 (not org-keep-stored-link-after-insertion))
9211 (setq org-stored-links (delq (assoc link org-stored-links)
9212 org-stored-links)))
9213 (setq desc (or desc (nth 1 entry)))))
9215 (if (string-match org-plain-link-re link)
9216 ;; URL-like link, normalize the use of angular brackets.
9217 (setq link (org-make-link (org-remove-angle-brackets link))))
9219 ;; Check if we are linking to the current file with a search option
9220 ;; If yes, simplify the link by using only the search option.
9221 (when (and buffer-file-name
9222 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9223 (let* ((path (match-string 1 link))
9224 (case-fold-search nil)
9225 (search (match-string 2 link)))
9226 (save-match-data
9227 (if (equal (file-truename buffer-file-name) (file-truename path))
9228 ;; We are linking to this same file, with a search option
9229 (setq link search)))))
9231 ;; Check if we can/should use a relative path. If yes, simplify the link
9232 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9233 (let* ((type (match-string 1 link))
9234 (path (match-string 2 link))
9235 (origpath path)
9236 (case-fold-search nil))
9237 (cond
9238 ((or (eq org-link-file-path-type 'absolute)
9239 (equal complete-file '(16)))
9240 (setq path (abbreviate-file-name (expand-file-name path))))
9241 ((eq org-link-file-path-type 'noabbrev)
9242 (setq path (expand-file-name path)))
9243 ((eq org-link-file-path-type 'relative)
9244 (setq path (file-relative-name path)))
9246 (save-match-data
9247 (if (string-match (concat "^" (regexp-quote
9248 (expand-file-name
9249 (file-name-as-directory
9250 default-directory))))
9251 (expand-file-name path))
9252 ;; We are linking a file with relative path name.
9253 (setq path (substring (expand-file-name path)
9254 (match-end 0)))
9255 (setq path (abbreviate-file-name (expand-file-name path)))))))
9256 (setq link (concat type path))
9257 (if (equal desc origpath)
9258 (setq desc path))))
9260 (if org-make-link-description-function
9261 (setq desc (funcall org-make-link-description-function link desc))
9262 (if default-description (setq desc default-description)))
9264 (setq desc (read-string "Description: " desc))
9265 (unless (string-match "\\S-" desc) (setq desc nil))
9266 (if remove (apply 'delete-region remove))
9267 (insert (org-make-link-string link desc))))
9269 (defun org-link-try-special-completion (type)
9270 "If there is completion support for link type TYPE, offer it."
9271 (let ((fun (intern (concat "org-" type "-complete-link"))))
9272 (if (functionp fun)
9273 (funcall fun)
9274 (read-string "Link (no completion support): " (concat type ":")))))
9276 (defun org-file-complete-link (&optional arg)
9277 "Create a file link using completion."
9278 (let (file link)
9279 (setq file (read-file-name "File: "))
9280 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9281 (pwd1 (file-name-as-directory (abbreviate-file-name
9282 (expand-file-name ".")))))
9283 (cond
9284 ((equal arg '(16))
9285 (setq link (org-make-link
9286 "file:"
9287 (abbreviate-file-name (expand-file-name file)))))
9288 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9289 (setq link (org-make-link "file:" (match-string 1 file))))
9290 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9291 (expand-file-name file))
9292 (setq link (org-make-link
9293 "file:" (match-string 1 (expand-file-name file)))))
9294 (t (setq link (org-make-link "file:" file)))))
9295 link))
9297 (defun org-completing-read (&rest args)
9298 "Completing-read with SPACE being a normal character."
9299 (let ((enable-recursive-minibuffers t)
9300 (minibuffer-local-completion-map
9301 (copy-keymap minibuffer-local-completion-map)))
9302 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9303 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9304 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9305 (apply 'org-icompleting-read args)))
9307 (defun org-completing-read-no-i (&rest args)
9308 (let (org-completion-use-ido org-completion-use-iswitchb)
9309 (apply 'org-completing-read args)))
9311 (defun org-iswitchb-completing-read (prompt choices &rest args)
9312 "Use iswitch as a completing-read replacement to choose from choices.
9313 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9314 from."
9315 (let* ((iswitchb-use-virtual-buffers nil)
9316 (iswitchb-make-buflist-hook
9317 (lambda ()
9318 (setq iswitchb-temp-buflist choices))))
9319 (iswitchb-read-buffer prompt)))
9321 (defun org-icompleting-read (&rest args)
9322 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9323 (org-without-partial-completion
9324 (if (and org-completion-use-ido
9325 (fboundp 'ido-completing-read)
9326 (boundp 'ido-mode) ido-mode
9327 (listp (second args)))
9328 (let ((ido-enter-matching-directory nil))
9329 (apply 'ido-completing-read (concat (car args))
9330 (if (consp (car (nth 1 args)))
9331 (mapcar 'car (nth 1 args))
9332 (nth 1 args))
9333 (cddr args)))
9334 (if (and org-completion-use-iswitchb
9335 (boundp 'iswitchb-mode) iswitchb-mode
9336 (listp (second args)))
9337 (apply 'org-iswitchb-completing-read (concat (car args))
9338 (if (consp (car (nth 1 args)))
9339 (mapcar 'car (nth 1 args))
9340 (nth 1 args))
9341 (cddr args))
9342 (apply 'completing-read args)))))
9344 (defun org-extract-attributes (s)
9345 "Extract the attributes cookie from a string and set as text property."
9346 (let (a attr (start 0) key value)
9347 (save-match-data
9348 (when (string-match "{{\\([^}]+\\)}}$" s)
9349 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9350 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9351 (setq key (match-string 1 a) value (match-string 2 a)
9352 start (match-end 0)
9353 attr (plist-put attr (intern key) value))))
9354 (org-add-props s nil 'org-attr attr))
9357 (defun org-extract-attributes-from-string (tag)
9358 (let (key value attr)
9359 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9360 (setq key (match-string 1 tag) value (match-string 2 tag)
9361 tag (replace-match "" t t tag)
9362 attr (plist-put attr (intern key) value)))
9363 (cons tag attr)))
9365 (defun org-attributes-to-string (plist)
9366 "Format a property list into an HTML attribute list."
9367 (let ((s "") key value)
9368 (while plist
9369 (setq key (pop plist) value (pop plist))
9370 (and value
9371 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9374 ;;; Opening/following a link
9376 (defvar org-link-search-failed nil)
9378 (defvar org-open-link-functions nil
9379 "Hook for functions finding a plain text link.
9380 These functions must take a single argument, the link content.
9381 They will be called for links that look like [[link text][description]]
9382 when LINK TEXT does not have a protocol like \"http:\" and does not look
9383 like a filename (e.g. \"./blue.png\").
9385 These functions will be called *before* Org attempts to resolve the
9386 link by doing text searches in the current buffer - so if you want a
9387 link \"[[target]]\" to still find \"<<target>>\", your function should
9388 handle this as a special case.
9390 When the function does handle the link, it must return a non-nil value.
9391 If it decides that it is not responsible for this link, it must return
9392 nil to indicate that that Org-mode can continue with other options
9393 like exact and fuzzy text search.")
9395 (defun org-next-link ()
9396 "Move forward to the next link.
9397 If the link is in hidden text, expose it."
9398 (interactive)
9399 (when (and org-link-search-failed (eq this-command last-command))
9400 (goto-char (point-min))
9401 (message "Link search wrapped back to beginning of buffer"))
9402 (setq org-link-search-failed nil)
9403 (let* ((pos (point))
9404 (ct (org-context))
9405 (a (assoc :link ct)))
9406 (if a (goto-char (nth 2 a)))
9407 (if (re-search-forward org-any-link-re nil t)
9408 (progn
9409 (goto-char (match-beginning 0))
9410 (if (outline-invisible-p) (org-show-context)))
9411 (goto-char pos)
9412 (setq org-link-search-failed t)
9413 (error "No further link found"))))
9415 (defun org-previous-link ()
9416 "Move backward to the previous link.
9417 If the link is in hidden text, expose it."
9418 (interactive)
9419 (when (and org-link-search-failed (eq this-command last-command))
9420 (goto-char (point-max))
9421 (message "Link search wrapped back to end of buffer"))
9422 (setq org-link-search-failed nil)
9423 (let* ((pos (point))
9424 (ct (org-context))
9425 (a (assoc :link ct)))
9426 (if a (goto-char (nth 1 a)))
9427 (if (re-search-backward org-any-link-re nil t)
9428 (progn
9429 (goto-char (match-beginning 0))
9430 (if (outline-invisible-p) (org-show-context)))
9431 (goto-char pos)
9432 (setq org-link-search-failed t)
9433 (error "No further link found"))))
9435 (defun org-translate-link (s)
9436 "Translate a link string if a translation function has been defined."
9437 (if (and org-link-translation-function
9438 (fboundp org-link-translation-function)
9439 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9440 (progn
9441 (setq s (funcall org-link-translation-function
9442 (match-string 1) (match-string 2)))
9443 (concat (car s) ":" (cdr s)))
9446 (defun org-translate-link-from-planner (type path)
9447 "Translate a link from Emacs Planner syntax so that Org can follow it.
9448 This is still an experimental function, your mileage may vary."
9449 (cond
9450 ((member type '("http" "https" "news" "ftp"))
9451 ;; standard Internet links are the same.
9452 nil)
9453 ((and (equal type "irc") (string-match "^//" path))
9454 ;; Planner has two / at the beginning of an irc link, we have 1.
9455 ;; We should have zero, actually....
9456 (setq path (substring path 1)))
9457 ((and (equal type "lisp") (string-match "^/" path))
9458 ;; Planner has a slash, we do not.
9459 (setq type "elisp" path (substring path 1)))
9460 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9461 ;; A typical message link. Planner has the id after the final slash,
9462 ;; we separate it with a hash mark
9463 (setq path (concat (match-string 1 path) "#"
9464 (org-remove-angle-brackets (match-string 2 path)))))
9466 (cons type path))
9468 (defun org-find-file-at-mouse (ev)
9469 "Open file link or URL at mouse."
9470 (interactive "e")
9471 (mouse-set-point ev)
9472 (org-open-at-point 'in-emacs))
9474 (defun org-open-at-mouse (ev)
9475 "Open file link or URL at mouse.
9476 See the docstring of `org-open-file' for details."
9477 (interactive "e")
9478 (mouse-set-point ev)
9479 (if (eq major-mode 'org-agenda-mode)
9480 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9481 (org-open-at-point))
9483 (defvar org-window-config-before-follow-link nil
9484 "The window configuration before following a link.
9485 This is saved in case the need arises to restore it.")
9487 (defvar org-open-link-marker (make-marker)
9488 "Marker pointing to the location where `org-open-at-point; was called.")
9490 ;;;###autoload
9491 (defun org-open-at-point-global ()
9492 "Follow a link like Org-mode does.
9493 This command can be called in any mode to follow a link that has
9494 Org-mode syntax."
9495 (interactive)
9496 (org-run-like-in-org-mode 'org-open-at-point))
9498 ;;;###autoload
9499 (defun org-open-link-from-string (s &optional arg reference-buffer)
9500 "Open a link in the string S, as if it was in Org-mode."
9501 (interactive "sLink: \nP")
9502 (let ((reference-buffer (or reference-buffer (current-buffer))))
9503 (with-temp-buffer
9504 (let ((org-inhibit-startup (not reference-buffer)))
9505 (org-mode)
9506 (insert s)
9507 (goto-char (point-min))
9508 (when reference-buffer
9509 (setq org-link-abbrev-alist-local
9510 (with-current-buffer reference-buffer
9511 org-link-abbrev-alist-local)))
9512 (org-open-at-point arg reference-buffer)))))
9514 (defvar org-open-at-point-functions nil
9515 "Hook that is run when following a link at point.
9517 Functions in this hook must return t if they identify and follow
9518 a link at point. If they don't find anything interesting at point,
9519 they must return nil.")
9521 (defun org-open-at-point (&optional arg reference-buffer)
9522 "Open link at or after point.
9523 If there is no link at point, this function will search forward up to
9524 the end of the current line.
9525 Normally, files will be opened by an appropriate application. If the
9526 optional prefix argument ARG is non-nil, Emacs will visit the file.
9527 With a double prefix argument, try to open outside of Emacs, in the
9528 application the system uses for this file type."
9529 (interactive "P")
9530 ;; if in a code block, then open the block's results
9531 (unless (call-interactively #'org-babel-open-src-block-result)
9532 (org-load-modules-maybe)
9533 (move-marker org-open-link-marker (point))
9534 (setq org-window-config-before-follow-link (current-window-configuration))
9535 (org-remove-occur-highlights nil nil t)
9536 (cond
9537 ((and (org-at-heading-p)
9538 (not (org-in-regexp
9539 (concat org-plain-link-re "\\|"
9540 org-bracket-link-regexp "\\|"
9541 org-angle-link-re "\\|"
9542 "[ \t]:[^ \t\n]+:[ \t]*$")))
9543 (not (get-text-property (point) 'org-linked-text)))
9544 (or (org-offer-links-in-entry arg)
9545 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9546 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9547 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9548 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9549 (not (org-in-regexp org-bracket-link-regexp)))
9550 (org-footnote-action))
9552 (let (type path link line search (pos (point)))
9553 (catch 'match
9554 (save-excursion
9555 (skip-chars-forward "^]\n\r")
9556 (when (org-in-regexp org-bracket-link-regexp 1)
9557 (setq link (org-extract-attributes
9558 (org-link-unescape (org-match-string-no-properties 1))))
9559 (while (string-match " *\n *" link)
9560 (setq link (replace-match " " t t link)))
9561 (setq link (org-link-expand-abbrev link))
9562 (cond
9563 ((or (file-name-absolute-p link)
9564 (string-match "^\\.\\.?/" link))
9565 (setq type "file" path link))
9566 ((string-match org-link-re-with-space3 link)
9567 (setq type (match-string 1 link) path (match-string 2 link)))
9568 (t (setq type "thisfile" path link)))
9569 (throw 'match t)))
9571 (when (get-text-property (point) 'org-linked-text)
9572 (setq type "thisfile"
9573 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9574 (1+ (point)) (point))
9575 path (buffer-substring
9576 (or (previous-single-property-change pos 'org-linked-text)
9577 (point-min))
9578 (or (next-single-property-change pos 'org-linked-text)
9579 (point-max))))
9580 (throw 'match t))
9582 (save-excursion
9583 (when (or (org-in-regexp org-angle-link-re)
9584 (org-in-regexp org-plain-link-re))
9585 (setq type (match-string 1)
9586 path (org-link-unescape (match-string 2)))
9587 (throw 'match t)))
9588 (save-excursion
9589 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9590 (setq type "tags"
9591 path (match-string 1))
9592 (while (string-match ":" path)
9593 (setq path (replace-match "+" t t path)))
9594 (throw 'match t)))
9595 (when (org-in-regexp "<\\([^><\n]+\\)>")
9596 (setq type "tree-match"
9597 path (match-string 1))
9598 (throw 'match t)))
9599 (unless path
9600 (error "No link found"))
9602 ;; switch back to reference buffer
9603 ;; needed when if called in a temporary buffer through
9604 ;; org-open-link-from-string
9605 (with-current-buffer (or reference-buffer (current-buffer))
9607 ;; Remove any trailing spaces in path
9608 (if (string-match " +\\'" path)
9609 (setq path (replace-match "" t t path)))
9610 (if (and org-link-translation-function
9611 (fboundp org-link-translation-function))
9612 ;; Check if we need to translate the link
9613 (let ((tmp (funcall org-link-translation-function type path)))
9614 (setq type (car tmp) path (cdr tmp))))
9616 (cond
9618 ((assoc type org-link-protocols)
9619 (funcall (nth 1 (assoc type org-link-protocols)) path))
9621 ((equal type "mailto")
9622 (let ((cmd (car org-link-mailto-program))
9623 (args (cdr org-link-mailto-program)) args1
9624 (address path) (subject "") a)
9625 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9626 (setq address (match-string 1 path)
9627 subject (org-link-escape (match-string 2 path))))
9628 (while args
9629 (cond
9630 ((not (stringp (car args))) (push (pop args) args1))
9631 (t (setq a (pop args))
9632 (if (string-match "%a" a)
9633 (setq a (replace-match address t t a)))
9634 (if (string-match "%s" a)
9635 (setq a (replace-match subject t t a)))
9636 (push a args1))))
9637 (apply cmd (nreverse args1))))
9639 ((member type '("http" "https" "ftp" "news"))
9640 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9641 (org-link-escape
9642 path org-link-escape-chars-browser)
9643 path))))
9645 ((string= type "doi")
9646 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9647 (org-link-escape
9648 path org-link-escape-chars-browser)
9649 path))))
9651 ((member type '("message"))
9652 (browse-url (concat type ":" path)))
9654 ((string= type "tags")
9655 (org-tags-view arg path))
9657 ((string= type "tree-match")
9658 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9660 ((string= type "file")
9661 (if (string-match "::\\([0-9]+\\)\\'" path)
9662 (setq line (string-to-number (match-string 1 path))
9663 path (substring path 0 (match-beginning 0)))
9664 (if (string-match "::\\(.+\\)\\'" path)
9665 (setq search (match-string 1 path)
9666 path (substring path 0 (match-beginning 0)))))
9667 (if (string-match "[*?{]" (file-name-nondirectory path))
9668 (dired path)
9669 (org-open-file path arg line search)))
9671 ((string= type "shell")
9672 (let ((cmd path))
9673 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9674 (string-match org-confirm-shell-link-not-regexp cmd))
9675 (not org-confirm-shell-link-function)
9676 (funcall org-confirm-shell-link-function
9677 (format "Execute \"%s\" in shell? "
9678 (org-add-props cmd nil
9679 'face 'org-warning))))
9680 (progn
9681 (message "Executing %s" cmd)
9682 (shell-command cmd))
9683 (error "Abort"))))
9685 ((string= type "elisp")
9686 (let ((cmd path))
9687 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9688 (string-match org-confirm-elisp-link-not-regexp cmd))
9689 (not org-confirm-elisp-link-function)
9690 (funcall org-confirm-elisp-link-function
9691 (format "Execute \"%s\" as elisp? "
9692 (org-add-props cmd nil
9693 'face 'org-warning))))
9694 (message "%s => %s" cmd
9695 (if (equal (string-to-char cmd) ?\()
9696 (eval (read cmd))
9697 (call-interactively (read cmd))))
9698 (error "Abort"))))
9700 ((and (string= type "thisfile")
9701 (run-hook-with-args-until-success
9702 'org-open-link-functions path)))
9704 ((string= type "thisfile")
9705 (if arg
9706 (switch-to-buffer-other-window
9707 (org-get-buffer-for-internal-link (current-buffer)))
9708 (org-mark-ring-push))
9709 (let ((cmd `(org-link-search
9710 ,path
9711 ,(cond ((equal arg '(4)) ''occur)
9712 ((equal arg '(16)) ''org-occur)
9713 (t nil))
9714 ,pos)))
9715 (condition-case nil (let ((org-link-search-inhibit-query t))
9716 (eval cmd))
9717 (error (progn (widen) (eval cmd))))))
9720 (browse-url-at-point)))))))
9721 (move-marker org-open-link-marker nil)
9722 (run-hook-with-args 'org-follow-link-hook)))
9724 (defun org-offer-links-in-entry (&optional nth zero)
9725 "Offer links in the current entry and follow the selected link.
9726 If there is only one link, follow it immediately as well.
9727 If NTH is an integer, immediately pick the NTH link found.
9728 If ZERO is a string, check also this string for a link, and if
9729 there is one, offer it as link number zero."
9730 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9731 "\\(" org-angle-link-re "\\)\\|"
9732 "\\(" org-plain-link-re "\\)"))
9733 (cnt ?0)
9734 (in-emacs (if (integerp nth) nil nth))
9735 have-zero end links link c)
9736 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9737 (push (match-string 0 zero) links)
9738 (setq cnt (1- cnt) have-zero t))
9739 (save-excursion
9740 (org-back-to-heading t)
9741 (setq end (save-excursion (outline-next-heading) (point)))
9742 (while (re-search-forward re end t)
9743 (push (match-string 0) links))
9744 (setq links (org-uniquify (reverse links))))
9746 (cond
9747 ((null links)
9748 (message "No links"))
9749 ((equal (length links) 1)
9750 (setq link (list (car links))))
9751 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9752 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9753 (t ; we have to select a link
9754 (save-excursion
9755 (save-window-excursion
9756 (delete-other-windows)
9757 (with-output-to-temp-buffer "*Select Link*"
9758 (mapc (lambda (l)
9759 (if (not (string-match org-bracket-link-regexp l))
9760 (princ (format "[%c] %s\n" (incf cnt)
9761 (org-remove-angle-brackets l)))
9762 (if (match-end 3)
9763 (princ (format "[%c] %s (%s)\n" (incf cnt)
9764 (match-string 3 l) (match-string 1 l)))
9765 (princ (format "[%c] %s\n" (incf cnt)
9766 (match-string 1 l))))))
9767 links))
9768 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9769 (message "Select link to open, RET to open all:")
9770 (setq c (read-char-exclusive))
9771 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9772 (when (equal c ?q) (error "Abort"))
9773 (if (equal c ?\C-m)
9774 (setq link links)
9775 (setq nth (- c ?0))
9776 (if have-zero (setq nth (1+ nth)))
9777 (unless (and (integerp nth) (>= (length links) nth))
9778 (error "Invalid link selection"))
9779 (setq link (list (nth (1- nth) links))))))
9780 (if link
9781 (let ((buf (current-buffer)))
9782 (dolist (l link)
9783 (org-open-link-from-string l in-emacs buf))
9785 nil)))
9787 ;; Add special file links that specify the way of opening
9789 (org-add-link-type "file+sys" 'org-open-file-with-system)
9790 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9791 (defun org-open-file-with-system (path)
9792 "Open file at PATH using the system way of opening it."
9793 (org-open-file path 'system))
9794 (defun org-open-file-with-emacs (path)
9795 "Open file at PATH in Emacs."
9796 (org-open-file path 'emacs))
9797 (defun org-remove-file-link-modifiers ()
9798 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9799 (goto-char (point-min))
9800 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9801 (org-if-unprotected
9802 (replace-match "file:" t t))))
9803 (eval-after-load "org-exp"
9804 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9805 'org-remove-file-link-modifiers))
9807 ;;;; Time estimates
9809 (defun org-get-effort (&optional pom)
9810 "Get the effort estimate for the current entry."
9811 (org-entry-get pom org-effort-property))
9813 ;;; File search
9815 (defvar org-create-file-search-functions nil
9816 "List of functions to construct the right search string for a file link.
9817 These functions are called in turn with point at the location to
9818 which the link should point.
9820 A function in the hook should first test if it would like to
9821 handle this file type, for example by checking the `major-mode'
9822 or the file extension. If it decides not to handle this file, it
9823 should just return nil to give other functions a chance. If it
9824 does handle the file, it must return the search string to be used
9825 when following the link. The search string will be part of the
9826 file link, given after a double colon, and `org-open-at-point'
9827 will automatically search for it. If special measures must be
9828 taken to make the search successful, another function should be
9829 added to the companion hook `org-execute-file-search-functions',
9830 which see.
9832 A function in this hook may also use `setq' to set the variable
9833 `description' to provide a suggestion for the descriptive text to
9834 be used for this link when it gets inserted into an Org-mode
9835 buffer with \\[org-insert-link].")
9837 (defvar org-execute-file-search-functions nil
9838 "List of functions to execute a file search triggered by a link.
9840 Functions added to this hook must accept a single argument, the
9841 search string that was part of the file link, the part after the
9842 double colon. The function must first check if it would like to
9843 handle this search, for example by checking the `major-mode' or
9844 the file extension. If it decides not to handle this search, it
9845 should just return nil to give other functions a chance. If it
9846 does handle the search, it must return a non-nil value to keep
9847 other functions from trying.
9849 Each function can access the current prefix argument through the
9850 variable `current-prefix-argument'. Note that a single prefix is
9851 used to force opening a link in Emacs, so it may be good to only
9852 use a numeric or double prefix to guide the search function.
9854 In case this is needed, a function in this hook can also restore
9855 the window configuration before `org-open-at-point' was called using:
9857 (set-window-configuration org-window-config-before-follow-link)")
9859 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9860 (defun org-link-search (s &optional type avoid-pos stealth)
9861 "Search for a link search option.
9862 If S is surrounded by forward slashes, it is interpreted as a
9863 regular expression. In org-mode files, this will create an `org-occur'
9864 sparse tree. In ordinary files, `occur' will be used to list matches.
9865 If the current buffer is in `dired-mode', grep will be used to search
9866 in all files. If AVOID-POS is given, ignore matches near that position.
9868 When optional argument STEALTH is non-nil, do not modify
9869 visibility around point, thus ignoring
9870 `org-show-hierarchy-above', `org-show-following-heading' and
9871 `org-show-siblings' variables."
9872 (let ((case-fold-search t)
9873 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9874 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9875 (append '(("") (" ") ("\t") ("\n"))
9876 org-emphasis-alist)
9877 "\\|") "\\)"))
9878 (pos (point))
9879 (pre nil) (post nil)
9880 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9881 (cond
9882 ;; First check if there are any special search functions
9883 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9884 ;; Now try the builtin stuff
9885 ((and (equal (string-to-char s0) ?#)
9886 (> (length s0) 1)
9887 (save-excursion
9888 (goto-char (point-min))
9889 (and
9890 (re-search-forward
9891 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9892 (setq type 'dedicated
9893 pos (match-beginning 0))))
9894 ;; There is an exact target for this
9895 (goto-char pos)
9896 (org-back-to-heading t)))
9897 ((save-excursion
9898 (goto-char (point-min))
9899 (and
9900 (re-search-forward
9901 (concat "<<" (regexp-quote s0) ">>") nil t)
9902 (setq type 'dedicated
9903 pos (match-beginning 0))))
9904 ;; There is an exact target for this
9905 (goto-char pos))
9906 ((save-excursion
9907 (goto-char (point-min))
9908 (and
9909 (re-search-forward
9910 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9911 (setq type 'dedicated pos (match-beginning 0))))
9912 ;; Found an invisible target.
9913 (goto-char pos))
9914 ((save-excursion
9915 (goto-char (point-min))
9916 (and
9917 (re-search-forward
9918 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9919 (setq type 'dedicated pos (match-beginning 0))))
9920 ;; Found an element with a matching #+name affiliated keyword.
9921 (goto-char pos))
9922 ((and (string-match "^(\\(.*\\))$" s0)
9923 (save-excursion
9924 (goto-char (point-min))
9925 (and
9926 (re-search-forward
9927 (concat "[^[]" (regexp-quote
9928 (format org-coderef-label-format
9929 (match-string 1 s0))))
9930 nil t)
9931 (setq type 'dedicated
9932 pos (1+ (match-beginning 0))))))
9933 ;; There is a coderef target for this
9934 (goto-char pos))
9935 ((string-match "^/\\(.*\\)/$" s)
9936 ;; A regular expression
9937 (cond
9938 ((eq major-mode 'org-mode)
9939 (org-occur (match-string 1 s)))
9940 ;;((eq major-mode 'dired-mode)
9941 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9942 (t (org-do-occur (match-string 1 s)))))
9943 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9944 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9945 (goto-char (point-min))
9946 (cond
9947 ((let (case-fold-search)
9948 (re-search-forward (format org-complex-heading-regexp-format
9949 (regexp-quote s))
9950 nil t))
9951 ;; OK, found a match
9952 (setq type 'dedicated)
9953 (goto-char (match-beginning 0)))
9954 ((and (not org-link-search-inhibit-query)
9955 (eq org-link-search-must-match-exact-headline 'query-to-create)
9956 (y-or-n-p "No match - create this as a new heading? "))
9957 (goto-char (point-max))
9958 (or (bolp) (newline))
9959 (insert "* " s "\n")
9960 (beginning-of-line 0))
9962 (goto-char pos)
9963 (error "No match"))))
9965 ;; A normal search string
9966 (when (equal (string-to-char s) ?*)
9967 ;; Anchor on headlines, post may include tags.
9968 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9969 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9970 s (substring s 1)))
9971 (remove-text-properties
9972 0 (length s)
9973 '(face nil mouse-face nil keymap nil fontified nil) s)
9974 ;; Make a series of regular expressions to find a match
9975 (setq words (org-split-string s "[ \n\r\t]+")
9977 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9978 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9979 "\\)" markers)
9980 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9981 re2a (concat "[ \t\r\n]" re2a_)
9982 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9983 re4 (concat "[^a-zA-Z_]" re4_)
9985 re1 (concat pre re2 post)
9986 re3 (concat pre (if pre re4_ re4) post)
9987 re5 (concat pre ".*" re4)
9988 re2 (concat pre re2)
9989 re2a (concat pre (if pre re2a_ re2a))
9990 re4 (concat pre (if pre re4_ re4))
9991 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9992 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9993 re5 "\\)"
9995 (cond
9996 ((eq type 'org-occur) (org-occur reall))
9997 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9998 (t (goto-char (point-min))
9999 (setq type 'fuzzy)
10000 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10001 (org-search-not-self 1 re1 nil t)
10002 (org-search-not-self 1 re2 nil t)
10003 (org-search-not-self 1 re2a nil t)
10004 (org-search-not-self 1 re3 nil t)
10005 (org-search-not-self 1 re4 nil t)
10006 (org-search-not-self 1 re5 nil t)
10008 (goto-char (match-beginning 1))
10009 (goto-char pos)
10010 (error "No match"))))))
10011 (and (eq major-mode 'org-mode)
10012 (not stealth)
10013 (org-show-context 'link-search))
10014 type))
10016 (defun org-search-not-self (group &rest args)
10017 "Execute `re-search-forward', but only accept matches that do not
10018 enclose the position of `org-open-link-marker'."
10019 (let ((m org-open-link-marker))
10020 (catch 'exit
10021 (while (apply 're-search-forward args)
10022 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10023 (goto-char (match-end group))
10024 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10025 (> (match-beginning 0) (marker-position m))
10026 (< (match-end 0) (marker-position m)))
10027 (save-match-data
10028 (or (not (org-in-regexp
10029 org-bracket-link-analytic-regexp 1))
10030 (not (match-end 4)) ; no description
10031 (and (<= (match-beginning 4) (point))
10032 (>= (match-end 4) (point))))))
10033 (throw 'exit (point))))))))
10035 (defun org-get-buffer-for-internal-link (buffer)
10036 "Return a buffer to be used for displaying the link target of internal links."
10037 (cond
10038 ((not org-display-internal-link-with-indirect-buffer)
10039 buffer)
10040 ((string-match "(Clone)$" (buffer-name buffer))
10041 (message "Buffer is already a clone, not making another one")
10042 ;; we also do not modify visibility in this case
10043 buffer)
10044 (t ; make a new indirect buffer for displaying the link
10045 (let* ((bn (buffer-name buffer))
10046 (ibn (concat bn "(Clone)"))
10047 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10048 (with-current-buffer ib (org-overview))
10049 ib))))
10051 (defun org-do-occur (regexp &optional cleanup)
10052 "Call the Emacs command `occur'.
10053 If CLEANUP is non-nil, remove the printout of the regular expression
10054 in the *Occur* buffer. This is useful if the regex is long and not useful
10055 to read."
10056 (occur regexp)
10057 (when cleanup
10058 (let ((cwin (selected-window)) win beg end)
10059 (when (setq win (get-buffer-window "*Occur*"))
10060 (select-window win))
10061 (goto-char (point-min))
10062 (when (re-search-forward "match[a-z]+" nil t)
10063 (setq beg (match-end 0))
10064 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10065 (setq end (1- (match-beginning 0)))))
10066 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10067 (goto-char (point-min))
10068 (select-window cwin))))
10070 ;;; The mark ring for links jumps
10072 (defvar org-mark-ring nil
10073 "Mark ring for positions before jumps in Org-mode.")
10074 (defvar org-mark-ring-last-goto nil
10075 "Last position in the mark ring used to go back.")
10076 ;; Fill and close the ring
10077 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10078 (loop for i from 1 to org-mark-ring-length do
10079 (push (make-marker) org-mark-ring))
10080 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10081 org-mark-ring)
10083 (defun org-mark-ring-push (&optional pos buffer)
10084 "Put the current position or POS into the mark ring and rotate it."
10085 (interactive)
10086 (setq pos (or pos (point)))
10087 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10088 (move-marker (car org-mark-ring)
10089 (or pos (point))
10090 (or buffer (current-buffer)))
10091 (message "%s"
10092 (substitute-command-keys
10093 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10095 (defun org-mark-ring-goto (&optional n)
10096 "Jump to the previous position in the mark ring.
10097 With prefix arg N, jump back that many stored positions. When
10098 called several times in succession, walk through the entire ring.
10099 Org-mode commands jumping to a different position in the current file,
10100 or to another Org-mode file, automatically push the old position
10101 onto the ring."
10102 (interactive "p")
10103 (let (p m)
10104 (if (eq last-command this-command)
10105 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10106 (setq p org-mark-ring))
10107 (setq org-mark-ring-last-goto p)
10108 (setq m (car p))
10109 (org-pop-to-buffer-same-window (marker-buffer m))
10110 (goto-char m)
10111 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10113 (defun org-remove-angle-brackets (s)
10114 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10115 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10117 (defun org-add-angle-brackets (s)
10118 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10119 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10121 (defun org-remove-double-quotes (s)
10122 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10123 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10126 ;;; Following specific links
10128 (defun org-follow-timestamp-link ()
10129 (cond
10130 ((org-at-date-range-p t)
10131 (let ((org-agenda-start-on-weekday)
10132 (t1 (match-string 1))
10133 (t2 (match-string 2)))
10134 (setq t1 (time-to-days (org-time-string-to-time t1))
10135 t2 (time-to-days (org-time-string-to-time t2)))
10136 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10137 ((org-at-timestamp-p t)
10138 (org-agenda-list nil (time-to-days (org-time-string-to-time
10139 (substring (match-string 1) 0 10)))
10141 (t (error "This should not happen"))))
10144 ;;; Following file links
10145 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10146 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10147 (declare-function mailcap-mime-info
10148 "mailcap" (string &optional request no-decode))
10149 (defvar org-wait nil)
10150 (defun org-open-file (path &optional in-emacs line search)
10151 "Open the file at PATH.
10152 First, this expands any special file name abbreviations. Then the
10153 configuration variable `org-file-apps' is checked if it contains an
10154 entry for this file type, and if yes, the corresponding command is launched.
10156 If no application is found, Emacs simply visits the file.
10158 With optional prefix argument IN-EMACS, Emacs will visit the file.
10159 With a double \\[universal-argument] \\[universal-argument] \
10160 prefix arg, Org tries to avoid opening in Emacs
10161 and to use an external application to visit the file.
10163 Optional LINE specifies a line to go to, optional SEARCH a string
10164 to search for. If LINE or SEARCH is given, the file will be
10165 opened in Emacs, unless an entry from org-file-apps that makes
10166 use of groups in a regexp matches.
10168 If you want to change the way frames are used when following a
10169 link, please customize `org-link-frame-setup'.
10171 If the file does not exist, an error is thrown."
10172 (let* ((file (if (equal path "")
10173 buffer-file-name
10174 (substitute-in-file-name (expand-file-name path))))
10175 (file-apps (append org-file-apps (org-default-apps)))
10176 (apps (org-remove-if
10177 'org-file-apps-entry-match-against-dlink-p file-apps))
10178 (apps-dlink (org-remove-if-not
10179 'org-file-apps-entry-match-against-dlink-p file-apps))
10180 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10181 (dirp (if remp nil (file-directory-p file)))
10182 (file (if (and dirp org-open-directory-means-index-dot-org)
10183 (concat (file-name-as-directory file) "index.org")
10184 file))
10185 (a-m-a-p (assq 'auto-mode apps))
10186 (dfile (downcase file))
10187 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10188 (link (cond ((and (eq line nil)
10189 (eq search nil))
10190 file)
10191 (line
10192 (concat file "::" (number-to-string line)))
10193 (search
10194 (concat file "::" search))))
10195 (dlink (downcase link))
10196 (old-buffer (current-buffer))
10197 (old-pos (point))
10198 (old-mode major-mode)
10199 ext cmd link-match-data)
10200 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10201 (setq ext (match-string 1 dfile))
10202 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10203 (setq ext (match-string 1 dfile))))
10204 (cond
10205 ((member in-emacs '((16) system))
10206 (setq cmd (cdr (assoc 'system apps))))
10207 (in-emacs (setq cmd 'emacs))
10209 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10210 (and dirp (cdr (assoc 'directory apps)))
10211 ; first, try matching against apps-dlink
10212 ; if we get a match here, store the match data for later
10213 (let ((match (assoc-default dlink apps-dlink
10214 'string-match)))
10215 (if match
10216 (progn (setq link-match-data (match-data))
10217 match)
10218 (progn (setq in-emacs (or in-emacs line search))
10219 nil))) ; if we have no match in apps-dlink,
10220 ; always open the file in emacs if line or search
10221 ; is given (for backwards compatibility)
10222 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10223 'string-match)
10224 (cdr (assoc ext apps))
10225 (cdr (assoc t apps))))))
10226 (when (eq cmd 'system)
10227 (setq cmd (cdr (assoc 'system apps))))
10228 (when (eq cmd 'default)
10229 (setq cmd (cdr (assoc t apps))))
10230 (when (eq cmd 'mailcap)
10231 (require 'mailcap)
10232 (mailcap-parse-mailcaps)
10233 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10234 (command (mailcap-mime-info mime-type)))
10235 (if (stringp command)
10236 (setq cmd command)
10237 (setq cmd 'emacs))))
10238 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10239 (not (file-exists-p file))
10240 (not org-open-non-existing-files))
10241 (error "No such file: %s" file))
10242 (cond
10243 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10244 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10245 (while (string-match "['\"]%s['\"]" cmd)
10246 (setq cmd (replace-match "%s" t t cmd)))
10247 (while (string-match "%s" cmd)
10248 (setq cmd (replace-match
10249 (save-match-data
10250 (shell-quote-argument
10251 (convert-standard-filename file)))
10252 t t cmd)))
10254 ;; Replace "%1", "%2" etc. in command with group matches from regex
10255 (save-match-data
10256 (let ((match-index 1)
10257 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10258 (set-match-data link-match-data)
10259 (while (<= match-index number-of-groups)
10260 (let ((regex (concat "%" (number-to-string match-index)))
10261 (replace-with (match-string match-index dlink)))
10262 (while (string-match regex cmd)
10263 (setq cmd (replace-match replace-with t t cmd))))
10264 (setq match-index (+ match-index 1)))))
10266 (save-window-excursion
10267 (start-process-shell-command cmd nil cmd)
10268 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10270 ((or (stringp cmd)
10271 (eq cmd 'emacs))
10272 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10273 (widen)
10274 (if line (org-goto-line line)
10275 (if search (org-link-search search))))
10276 ((consp cmd)
10277 (let ((file (convert-standard-filename file)))
10278 (save-match-data
10279 (set-match-data link-match-data)
10280 (eval cmd))))
10281 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10282 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10283 (or (not (equal old-buffer (current-buffer)))
10284 (not (equal old-pos (point))))
10285 (org-mark-ring-push old-pos old-buffer))))
10287 (defun org-file-apps-entry-match-against-dlink-p (entry)
10288 "This function returns non-nil if `entry' uses a regular
10289 expression which should be matched against the whole link by
10290 org-open-file.
10292 It assumes that is the case when the entry uses a regular
10293 expression which has at least one grouping construct and the
10294 action is either a lisp form or a command string containing
10295 '%1', i.e. using at least one subexpression match as a
10296 parameter."
10297 (let ((selector (car entry))
10298 (action (cdr entry)))
10299 (if (stringp selector)
10300 (and (> (regexp-opt-depth selector) 0)
10301 (or (and (stringp action)
10302 (string-match "%[0-9]" action))
10303 (consp action)))
10304 nil)))
10306 (defun org-default-apps ()
10307 "Return the default applications for this operating system."
10308 (cond
10309 ((eq system-type 'darwin)
10310 org-file-apps-defaults-macosx)
10311 ((eq system-type 'windows-nt)
10312 org-file-apps-defaults-windowsnt)
10313 (t org-file-apps-defaults-gnu)))
10315 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10316 "Convert extensions to regular expressions in the cars of LIST.
10317 Also, weed out any non-string entries, because the return value is used
10318 only for regexp matching.
10319 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10320 point to the symbol `emacs', indicating that the file should
10321 be opened in Emacs."
10322 (append
10323 (delq nil
10324 (mapcar (lambda (x)
10325 (if (not (stringp (car x)))
10327 (if (string-match "\\W" (car x))
10329 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10330 list))
10331 (if add-auto-mode
10332 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10334 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10335 (defun org-file-remote-p (file)
10336 "Test whether FILE specifies a location on a remote system.
10337 Return non-nil if the location is indeed remote.
10339 For example, the filename \"/user@host:/foo\" specifies a location
10340 on the system \"/user@host:\"."
10341 (cond ((fboundp 'file-remote-p)
10342 (file-remote-p file))
10343 ((fboundp 'tramp-handle-file-remote-p)
10344 (tramp-handle-file-remote-p file))
10345 ((and (boundp 'ange-ftp-name-format)
10346 (string-match (car ange-ftp-name-format) file))
10348 (t nil)))
10351 ;;;; Refiling
10353 (defun org-get-org-file ()
10354 "Read a filename, with default directory `org-directory'."
10355 (let ((default (or org-default-notes-file remember-data-file)))
10356 (read-file-name (format "File name [%s]: " default)
10357 (file-name-as-directory org-directory)
10358 default)))
10360 (defun org-notes-order-reversed-p ()
10361 "Check if the current file should receive notes in reversed order."
10362 (cond
10363 ((not org-reverse-note-order) nil)
10364 ((eq t org-reverse-note-order) t)
10365 ((not (listp org-reverse-note-order)) nil)
10366 (t (catch 'exit
10367 (let ((all org-reverse-note-order)
10368 entry)
10369 (while (setq entry (pop all))
10370 (if (string-match (car entry) buffer-file-name)
10371 (throw 'exit (cdr entry))))
10372 nil)))))
10374 (defvar org-refile-target-table nil
10375 "The list of refile targets, created by `org-refile'.")
10377 (defvar org-agenda-new-buffers nil
10378 "Buffers created to visit agenda files.")
10380 (defvar org-refile-cache nil
10381 "Cache for refile targets.")
10383 (defvar org-refile-markers nil
10384 "All the markers used for caching refile locations.")
10386 (defun org-refile-marker (pos)
10387 "Get a new refile marker, but only if caching is in use."
10388 (if (not org-refile-use-cache)
10390 (let ((m (make-marker)))
10391 (move-marker m pos)
10392 (push m org-refile-markers)
10393 m)))
10395 (defun org-refile-cache-clear ()
10396 "Clear the refile cache and disable all the markers."
10397 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10398 (setq org-refile-markers nil)
10399 (setq org-refile-cache nil)
10400 (message "Refile cache has been cleared"))
10402 (defun org-refile-cache-check-set (set)
10403 "Check if all the markers in the cache still have live buffers."
10404 (let (marker)
10405 (catch 'exit
10406 (while (and set (setq marker (nth 3 (pop set))))
10407 ;; if org-refile-use-outline-path is 'file, marker may be nil
10408 (when (and marker (null (marker-buffer marker)))
10409 (message "not found") (sit-for 3)
10410 (throw 'exit nil)))
10411 t)))
10413 (defun org-refile-cache-put (set &rest identifiers)
10414 "Push the refile targets SET into the cache, under IDENTIFIERS."
10415 (let* ((key (sha1 (prin1-to-string identifiers)))
10416 (entry (assoc key org-refile-cache)))
10417 (if entry
10418 (setcdr entry set)
10419 (push (cons key set) org-refile-cache))))
10421 (defun org-refile-cache-get (&rest identifiers)
10422 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10423 (cond
10424 ((not org-refile-cache) nil)
10425 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10427 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10428 org-refile-cache))))
10429 (and set (org-refile-cache-check-set set) set)))))
10431 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10432 "Produce a table with refile targets."
10433 (let ((case-fold-search nil)
10434 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10435 (entries (or org-refile-targets '((nil . (:level . 1)))))
10436 targets tgs txt re files f desc descre fast-path-p level pos0)
10437 (message "Getting targets...")
10438 (with-current-buffer (or default-buffer (current-buffer))
10439 (while (setq entry (pop entries))
10440 (setq files (car entry) desc (cdr entry))
10441 (setq fast-path-p nil)
10442 (cond
10443 ((null files) (setq files (list (current-buffer))))
10444 ((eq files 'org-agenda-files)
10445 (setq files (org-agenda-files 'unrestricted)))
10446 ((and (symbolp files) (fboundp files))
10447 (setq files (funcall files)))
10448 ((and (symbolp files) (boundp files))
10449 (setq files (symbol-value files))))
10450 (if (stringp files) (setq files (list files)))
10451 (cond
10452 ((eq (car desc) :tag)
10453 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10454 ((eq (car desc) :todo)
10455 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10456 ((eq (car desc) :regexp)
10457 (setq descre (cdr desc)))
10458 ((eq (car desc) :level)
10459 (setq descre (concat "^\\*\\{" (number-to-string
10460 (if org-odd-levels-only
10461 (1- (* 2 (cdr desc)))
10462 (cdr desc)))
10463 "\\}[ \t]")))
10464 ((eq (car desc) :maxlevel)
10465 (setq fast-path-p t)
10466 (setq descre (concat "^\\*\\{1," (number-to-string
10467 (if org-odd-levels-only
10468 (1- (* 2 (cdr desc)))
10469 (cdr desc)))
10470 "\\}[ \t]")))
10471 (t (error "Bad refiling target description %s" desc)))
10472 (while (setq f (pop files))
10473 (with-current-buffer
10474 (if (bufferp f) f (org-get-agenda-file-buffer f))
10476 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10477 (progn
10478 (if (bufferp f) (setq f (buffer-file-name
10479 (buffer-base-buffer f))))
10480 (setq f (and f (expand-file-name f)))
10481 (if (eq org-refile-use-outline-path 'file)
10482 (push (list (file-name-nondirectory f) f nil nil) tgs))
10483 (save-excursion
10484 (save-restriction
10485 (widen)
10486 (goto-char (point-min))
10487 (while (re-search-forward descre nil t)
10488 (goto-char (setq pos0 (point-at-bol)))
10489 (catch 'next
10490 (when org-refile-target-verify-function
10491 (save-match-data
10492 (or (funcall org-refile-target-verify-function)
10493 (throw 'next t))))
10494 (when (and (looking-at org-complex-heading-regexp)
10495 (not (member (match-string 4) excluded-entries))
10496 (match-string 4))
10497 (setq level (org-reduced-level
10498 (- (match-end 1) (match-beginning 1)))
10499 txt (org-link-display-format (match-string 4))
10500 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10501 re (format org-complex-heading-regexp-format
10502 (regexp-quote (match-string 4))))
10503 (when org-refile-use-outline-path
10504 (setq txt (mapconcat
10505 'org-protect-slash
10506 (append
10507 (if (eq org-refile-use-outline-path
10508 'file)
10509 (list (file-name-nondirectory
10510 (buffer-file-name
10511 (buffer-base-buffer))))
10512 (if (eq org-refile-use-outline-path
10513 'full-file-path)
10514 (list (buffer-file-name
10515 (buffer-base-buffer)))))
10516 (org-get-outline-path fast-path-p
10517 level txt)
10518 (list txt))
10519 "/")))
10520 (push (list txt f re (org-refile-marker (point)))
10521 tgs)))
10522 (when (= (point) pos0)
10523 ;; verification function has not moved point
10524 (goto-char (point-at-eol))))))))
10525 (when org-refile-use-cache
10526 (org-refile-cache-put tgs (buffer-file-name) descre))
10527 (setq targets (append tgs targets))
10528 ))))
10529 (message "Getting targets...done")
10530 (nreverse targets)))
10532 (defun org-protect-slash (s)
10533 (while (string-match "/" s)
10534 (setq s (replace-match "\\" t t s)))
10537 (defvar org-olpa (make-vector 20 nil))
10539 (defun org-get-outline-path (&optional fastp level heading)
10540 "Return the outline path to the current entry, as a list.
10542 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10543 routine which makes outline path derivations for an entire file,
10544 avoiding backtracing. Refile target collection makes use of that."
10545 (if fastp
10546 (progn
10547 (if (> level 19)
10548 (error "Outline path failure, more than 19 levels"))
10549 (loop for i from level upto 19 do
10550 (aset org-olpa i nil))
10551 (prog1
10552 (delq nil (append org-olpa nil))
10553 (aset org-olpa level heading)))
10554 (let (rtn case-fold-search)
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (while (org-up-heading-safe)
10559 (when (looking-at org-complex-heading-regexp)
10560 (push (org-match-string-no-properties 4) rtn)))
10561 rtn)))))
10563 (defun org-format-outline-path (path &optional width prefix)
10564 "Format the outline path PATH for display.
10565 Width is the maximum number of characters that is available.
10566 Prefix is a prefix to be included in the returned string,
10567 such as the file name."
10568 (setq width (or width 79))
10569 (if prefix (setq width (- width (length prefix))))
10570 (if (not path)
10571 (or prefix "")
10572 (let* ((nsteps (length path))
10573 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10574 (maxwidth (if (<= total-width width)
10575 10000 ;; everything fits
10576 ;; we need to shorten the level headings
10577 (/ (- width nsteps) nsteps)))
10578 (org-odd-levels-only nil)
10579 (n 0)
10580 (total (1+ (length prefix))))
10581 (setq maxwidth (max maxwidth 10))
10582 (concat prefix
10583 (mapconcat
10584 (lambda (h)
10585 (setq n (1+ n))
10586 (if (and (= n nsteps) (< maxwidth 10000))
10587 (setq maxwidth (- total-width total)))
10588 (if (< (length h) maxwidth)
10589 (progn (setq total (+ total (length h) 1)) h)
10590 (setq h (substring h 0 (- maxwidth 2))
10591 total (+ total maxwidth 1))
10592 (if (string-match "[ \t]+\\'" h)
10593 (setq h (substring h 0 (match-beginning 0))))
10594 (setq h (concat h "..")))
10595 (org-add-props h nil 'face
10596 (nth (% (1- n) org-n-level-faces)
10597 org-level-faces))
10599 path "/")))))
10601 (defun org-display-outline-path (&optional file current)
10602 "Display the current outline path in the echo area."
10603 (interactive "P")
10604 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10605 (case-fold-search nil)
10606 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10607 (if current (setq path (append path
10608 (save-excursion
10609 (org-back-to-heading t)
10610 (if (looking-at org-complex-heading-regexp)
10611 (list (match-string 4)))))))
10612 (message "%s"
10613 (org-format-outline-path
10614 path
10615 (1- (frame-width))
10616 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10618 (defvar org-refile-history nil
10619 "History for refiling operations.")
10621 (defvar org-after-refile-insert-hook nil
10622 "Hook run after `org-refile' has inserted its stuff at the new location.
10623 Note that this is still *before* the stuff will be removed from
10624 the *old* location.")
10626 (defvar org-capture-last-stored-marker)
10627 (defun org-refile (&optional goto default-buffer rfloc)
10628 "Move the entry or entries at point to another heading.
10629 The list of target headings is compiled using the information in
10630 `org-refile-targets', which see.
10632 At the target location, the entry is filed as a subitem of the target
10633 heading. Depending on `org-reverse-note-order', the new subitem will
10634 either be the first or the last subitem.
10636 If there is an active region, all entries in that region will be moved.
10637 However, the region must fulfill the requirement that the first heading
10638 is the first one sets the top-level of the moved text - at most siblings
10639 below it are allowed.
10641 With prefix arg GOTO, the command will only visit the target location
10642 and not actually move anything.
10644 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10645 go to the location where the last refiling operation has put the subtree.
10646 With a prefix argument of `2', refile to the running clock.
10648 RFLOC can be a refile location obtained in a different way.
10650 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10652 If you are using target caching (see `org-refile-use-cache'),
10653 You have to clear the target cache in order to find new targets.
10654 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10655 prefix argument (`C-u C-u C-u C-c C-w')."
10657 (interactive "P")
10658 (if (member goto '(0 (64)))
10659 (org-refile-cache-clear)
10660 (let* ((cbuf (current-buffer))
10661 (regionp (org-region-active-p))
10662 (region-start (and regionp (region-beginning)))
10663 (region-end (and regionp (region-end)))
10664 (region-length (and regionp (- region-end region-start)))
10665 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10666 pos it nbuf file re level reversed)
10667 (setq last-command nil)
10668 (when regionp
10669 (goto-char region-start)
10670 (or (bolp) (goto-char (point-at-bol)))
10671 (setq region-start (point))
10672 (unless (or (org-kill-is-subtree-p
10673 (buffer-substring region-start region-end))
10674 (prog1 org-refile-active-region-within-subtree
10675 (org-toggle-heading)))
10676 (error "The region is not a (sequence of) subtree(s)")))
10677 (if (equal goto '(16))
10678 (org-refile-goto-last-stored)
10679 (when (or
10680 (and (equal goto 2)
10681 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10682 (prog1
10683 (setq it (list (or org-clock-heading "running clock")
10684 (buffer-file-name
10685 (marker-buffer org-clock-hd-marker))
10687 (marker-position org-clock-hd-marker)))
10688 (setq goto nil)))
10689 (setq it (or rfloc
10690 (let (heading-text)
10691 (save-excursion
10692 (unless goto
10693 (org-back-to-heading t)
10694 (setq heading-text
10695 (nth 4 (org-heading-components))))
10696 (org-refile-get-location
10697 (cond (goto "Goto")
10698 (regionp "Refile region to")
10699 (t (concat "Refile subtree \""
10700 heading-text "\" to")))
10701 default-buffer
10702 org-refile-allow-creating-parent-nodes
10703 goto))))))
10704 (setq file (nth 1 it)
10705 re (nth 2 it)
10706 pos (nth 3 it))
10707 (if (and (not goto)
10709 (equal (buffer-file-name) file)
10710 (if regionp
10711 (and (>= pos region-start)
10712 (<= pos region-end))
10713 (and (>= pos (point))
10714 (< pos (save-excursion
10715 (org-end-of-subtree t t))))))
10716 (error "Cannot refile to position inside the tree or region"))
10718 (setq nbuf (or (find-buffer-visiting file)
10719 (find-file-noselect file)))
10720 (if goto
10721 (progn
10722 (org-pop-to-buffer-same-window nbuf)
10723 (goto-char pos)
10724 (org-show-context 'org-goto))
10725 (if regionp
10726 (progn
10727 (org-kill-new (buffer-substring region-start region-end))
10728 (org-save-markers-in-region region-start region-end))
10729 (org-copy-subtree 1 nil t))
10730 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10731 (find-file-noselect file)))
10732 (setq reversed (org-notes-order-reversed-p))
10733 (save-excursion
10734 (save-restriction
10735 (widen)
10736 (if pos
10737 (progn
10738 (goto-char pos)
10739 (looking-at org-outline-regexp)
10740 (setq level (org-get-valid-level (funcall outline-level) 1))
10741 (goto-char
10742 (if reversed
10743 (or (outline-next-heading) (point-max))
10744 (or (save-excursion (org-get-next-sibling))
10745 (org-end-of-subtree t t)
10746 (point-max)))))
10747 (setq level 1)
10748 (if (not reversed)
10749 (goto-char (point-max))
10750 (goto-char (point-min))
10751 (or (outline-next-heading) (goto-char (point-max)))))
10752 (if (not (bolp)) (newline))
10753 (org-paste-subtree level)
10754 (when org-log-refile
10755 (org-add-log-setup 'refile nil nil 'findpos
10756 org-log-refile)
10757 (unless (eq org-log-refile 'note)
10758 (save-excursion (org-add-log-note))))
10759 (and org-auto-align-tags (org-set-tags nil t))
10760 (bookmark-set "org-refile-last-stored")
10761 ;; If we are refiling for capture, make sure that the
10762 ;; last-capture pointers point here
10763 (when (org-bound-and-true-p org-refile-for-capture)
10764 (bookmark-set "org-capture-last-stored-marker")
10765 (move-marker org-capture-last-stored-marker (point)))
10766 (if (fboundp 'deactivate-mark) (deactivate-mark))
10767 (run-hooks 'org-after-refile-insert-hook))))
10768 (if regionp
10769 (delete-region (point) (+ (point) region-length))
10770 (org-cut-subtree))
10771 (when (featurep 'org-inlinetask)
10772 (org-inlinetask-remove-END-maybe))
10773 (setq org-markers-to-move nil)
10774 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10776 (defun org-refile-goto-last-stored ()
10777 "Go to the location where the last refile was stored."
10778 (interactive)
10779 (bookmark-jump "org-refile-last-stored")
10780 (message "This is the location of the last refile"))
10782 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10783 no-exclude)
10784 "Prompt the user for a refile location, using PROMPT.
10785 PROMPT should not be suffixed with a colon and a space, because
10786 this function appends the default value from
10787 `org-refile-history' automatically, if that is not empty.
10788 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10789 this is used for the GOTO interface."
10790 (let ((org-refile-targets org-refile-targets)
10791 (org-refile-use-outline-path org-refile-use-outline-path)
10792 excluded-entries)
10793 (when (and (eq major-mode 'org-mode)
10794 (not org-refile-use-cache)
10795 (not no-exclude))
10796 (org-map-tree
10797 (lambda()
10798 (setq excluded-entries
10799 (append excluded-entries (list (org-get-heading t t)))))))
10800 (setq org-refile-target-table
10801 (org-refile-get-targets default-buffer excluded-entries)))
10802 (unless org-refile-target-table
10803 (error "No refile targets"))
10804 (let* ((prompt (concat prompt
10805 (and (car org-refile-history)
10806 (concat " (default " (car org-refile-history) ")"))
10807 ": "))
10808 (cbuf (current-buffer))
10809 (partial-completion-mode nil)
10810 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10811 (cfunc (if (and org-refile-use-outline-path
10812 org-outline-path-complete-in-steps)
10813 'org-olpath-completing-read
10814 'org-icompleting-read))
10815 (extra (if org-refile-use-outline-path "/" ""))
10816 (filename (and cfn (expand-file-name cfn)))
10817 (tbl (mapcar
10818 (lambda (x)
10819 (if (and (not (member org-refile-use-outline-path
10820 '(file full-file-path)))
10821 (not (equal filename (nth 1 x))))
10822 (cons (concat (car x) extra " ("
10823 (file-name-nondirectory (nth 1 x)) ")")
10824 (cdr x))
10825 (cons (concat (car x) extra) (cdr x))))
10826 org-refile-target-table))
10827 (completion-ignore-case t)
10828 pa answ parent-target child parent old-hist)
10829 (setq old-hist org-refile-history)
10830 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10831 nil 'org-refile-history (car org-refile-history)))
10832 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10833 (org-refile-check-position pa)
10834 (if pa
10835 (progn
10836 (when (or (not org-refile-history)
10837 (not (eq old-hist org-refile-history))
10838 (not (equal (car pa) (car org-refile-history))))
10839 (setq org-refile-history
10840 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10841 org-refile-history
10842 (cdr org-refile-history))))
10843 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10844 (pop org-refile-history)))
10846 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10847 (progn
10848 (setq parent (match-string 1 answ)
10849 child (match-string 2 answ))
10850 (setq parent-target (or (assoc parent tbl)
10851 (assoc (concat parent "/") tbl)))
10852 (when (and parent-target
10853 (or (eq new-nodes t)
10854 (and (eq new-nodes 'confirm)
10855 (y-or-n-p (format "Create new node \"%s\"? "
10856 child)))))
10857 (org-refile-new-child parent-target child)))
10858 (error "Invalid target location")))))
10860 (defun org-refile-check-position (refile-pointer)
10861 "Check if the refile pointer matches the readline to which it points."
10862 (let* ((file (nth 1 refile-pointer))
10863 (re (nth 2 refile-pointer))
10864 (pos (nth 3 refile-pointer))
10865 buffer)
10866 (when (org-string-nw-p re)
10867 (setq buffer (if (markerp pos)
10868 (marker-buffer pos)
10869 (or (find-buffer-visiting file)
10870 (find-file-noselect file))))
10871 (with-current-buffer buffer
10872 (save-excursion
10873 (save-restriction
10874 (widen)
10875 (goto-char pos)
10876 (beginning-of-line 1)
10877 (unless (org-looking-at-p re)
10878 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10880 (defun org-refile-new-child (parent-target child)
10881 "Use refile target PARENT-TARGET to add new CHILD below it."
10882 (unless parent-target
10883 (error "Cannot find parent for new node"))
10884 (let ((file (nth 1 parent-target))
10885 (pos (nth 3 parent-target))
10886 level)
10887 (with-current-buffer (or (find-buffer-visiting file)
10888 (find-file-noselect file))
10889 (save-excursion
10890 (save-restriction
10891 (widen)
10892 (if pos
10893 (goto-char pos)
10894 (goto-char (point-max))
10895 (if (not (bolp)) (newline)))
10896 (when (looking-at org-outline-regexp)
10897 (setq level (funcall outline-level))
10898 (org-end-of-subtree t t))
10899 (org-back-over-empty-lines)
10900 (insert "\n" (make-string
10901 (if pos (org-get-valid-level level 1) 1) ?*)
10902 " " child "\n")
10903 (beginning-of-line 0)
10904 (list (concat (car parent-target) "/" child) file "" (point)))))))
10906 (defun org-olpath-completing-read (prompt collection &rest args)
10907 "Read an outline path like a file name."
10908 (let ((thetable collection)
10909 (org-completion-use-ido nil) ; does not work with ido.
10910 (org-completion-use-iswitchb nil)) ; or iswitchb
10911 (apply
10912 'org-icompleting-read prompt
10913 (lambda (string predicate &optional flag)
10914 (let (rtn r f (l (length string)))
10915 (cond
10916 ((eq flag nil)
10917 ;; try completion
10918 (try-completion string thetable))
10919 ((eq flag t)
10920 ;; all-completions
10921 (setq rtn (all-completions string thetable predicate))
10922 (mapcar
10923 (lambda (x)
10924 (setq r (substring x l))
10925 (if (string-match " ([^)]*)$" x)
10926 (setq f (match-string 0 x))
10927 (setq f ""))
10928 (if (string-match "/" r)
10929 (concat string (substring r 0 (match-end 0)) f)
10931 rtn))
10932 ((eq flag 'lambda)
10933 ;; exact match?
10934 (assoc string thetable)))
10936 args)))
10938 ;;;; Dynamic blocks
10940 (defun org-find-dblock (name)
10941 "Find the first dynamic block with name NAME in the buffer.
10942 If not found, stay at current position and return nil."
10943 (let (pos)
10944 (save-excursion
10945 (goto-char (point-min))
10946 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10947 nil t)
10948 (match-beginning 0))))
10949 (if pos (goto-char pos))
10950 pos))
10952 (defconst org-dblock-start-re
10953 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10954 "Matches the start line of a dynamic block, with parameters.")
10956 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10957 "Matches the end of a dynamic block.")
10959 (defun org-create-dblock (plist)
10960 "Create a dynamic block section, with parameters taken from PLIST.
10961 PLIST must contain a :name entry which is used as name of the block."
10962 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10963 (end-of-line 1)
10964 (newline))
10965 (let ((col (current-column))
10966 (name (plist-get plist :name)))
10967 (insert "#+BEGIN: " name)
10968 (while plist
10969 (if (eq (car plist) :name)
10970 (setq plist (cddr plist))
10971 (insert " " (prin1-to-string (pop plist)))))
10972 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10973 (beginning-of-line -2)))
10975 (defun org-prepare-dblock ()
10976 "Prepare dynamic block for refresh.
10977 This empties the block, puts the cursor at the insert position and returns
10978 the property list including an extra property :name with the block name."
10979 (unless (looking-at org-dblock-start-re)
10980 (error "Not at a dynamic block"))
10981 (let* ((begdel (1+ (match-end 0)))
10982 (name (org-no-properties (match-string 1)))
10983 (params (append (list :name name)
10984 (read (concat "(" (match-string 3) ")")))))
10985 (save-excursion
10986 (beginning-of-line 1)
10987 (skip-chars-forward " \t")
10988 (setq params (plist-put params :indentation-column (current-column))))
10989 (unless (re-search-forward org-dblock-end-re nil t)
10990 (error "Dynamic block not terminated"))
10991 (setq params
10992 (append params
10993 (list :content (buffer-substring
10994 begdel (match-beginning 0)))))
10995 (delete-region begdel (match-beginning 0))
10996 (goto-char begdel)
10997 (open-line 1)
10998 params))
11000 (defun org-map-dblocks (&optional command)
11001 "Apply COMMAND to all dynamic blocks in the current buffer.
11002 If COMMAND is not given, use `org-update-dblock'."
11003 (let ((cmd (or command 'org-update-dblock)))
11004 (save-excursion
11005 (goto-char (point-min))
11006 (while (re-search-forward org-dblock-start-re nil t)
11007 (goto-char (match-beginning 0))
11008 (save-excursion
11009 (condition-case nil
11010 (funcall cmd)
11011 (error (message "Error during update of dynamic block"))))
11012 (unless (re-search-forward org-dblock-end-re nil t)
11013 (error "Dynamic block not terminated"))))))
11015 (defun org-dblock-update (&optional arg)
11016 "User command for updating dynamic blocks.
11017 Update the dynamic block at point. With prefix ARG, update all dynamic
11018 blocks in the buffer."
11019 (interactive "P")
11020 (if arg
11021 (org-update-all-dblocks)
11022 (or (looking-at org-dblock-start-re)
11023 (org-beginning-of-dblock))
11024 (org-update-dblock)))
11026 (defun org-update-dblock ()
11027 "Update the dynamic block at point.
11028 This means to empty the block, parse for parameters and then call
11029 the correct writing function."
11030 (interactive)
11031 (save-window-excursion
11032 (let* ((pos (point))
11033 (line (org-current-line))
11034 (params (org-prepare-dblock))
11035 (name (plist-get params :name))
11036 (indent (plist-get params :indentation-column))
11037 (cmd (intern (concat "org-dblock-write:" name))))
11038 (message "Updating dynamic block `%s' at line %d..." name line)
11039 (funcall cmd params)
11040 (message "Updating dynamic block `%s' at line %d...done" name line)
11041 (goto-char pos)
11042 (when (and indent (> indent 0))
11043 (setq indent (make-string indent ?\ ))
11044 (save-excursion
11045 (org-beginning-of-dblock)
11046 (forward-line 1)
11047 (while (not (looking-at org-dblock-end-re))
11048 (insert indent)
11049 (beginning-of-line 2))
11050 (when (looking-at org-dblock-end-re)
11051 (and (looking-at "[ \t]+")
11052 (replace-match ""))
11053 (insert indent)))))))
11055 (defun org-beginning-of-dblock ()
11056 "Find the beginning of the dynamic block at point.
11057 Error if there is no such block at point."
11058 (let ((pos (point))
11059 beg)
11060 (end-of-line 1)
11061 (if (and (re-search-backward org-dblock-start-re nil t)
11062 (setq beg (match-beginning 0))
11063 (re-search-forward org-dblock-end-re nil t)
11064 (> (match-end 0) pos))
11065 (goto-char beg)
11066 (goto-char pos)
11067 (error "Not in a dynamic block"))))
11069 (defun org-update-all-dblocks ()
11070 "Update all dynamic blocks in the buffer.
11071 This function can be used in a hook."
11072 (interactive)
11073 (when (eq major-mode 'org-mode)
11074 (org-map-dblocks 'org-update-dblock)))
11077 ;;;; Completion
11079 (defconst org-additional-option-like-keywords
11080 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11081 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11082 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11083 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11084 "BEGIN:" "END:"
11085 "ORGTBL" "TBLFM:" "TBLNAME:"
11086 "BEGIN_EXAMPLE" "END_EXAMPLE"
11087 "BEGIN_QUOTE" "END_QUOTE"
11088 "BEGIN_VERSE" "END_VERSE"
11089 "BEGIN_CENTER" "END_CENTER"
11090 "BEGIN_SRC" "END_SRC"
11091 "BEGIN_RESULT" "END_RESULT"
11092 "NAME:" "RESULTS:"
11093 "HEADER:" "HEADERS:"
11094 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11095 "CAPTION:" "LABEL:"
11096 "SETUPFILE:"
11097 "INCLUDE:"
11098 "BIND:"
11099 "MACRO:"))
11101 (defcustom org-structure-template-alist
11103 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11104 "<src lang=\"?\">\n\n</src>")
11105 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11106 "<example>\n?\n</example>")
11107 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11108 "<quote>\n?\n</quote>")
11109 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11110 "<verse>\n?\n</verse>")
11111 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11112 "<center>\n?\n</center>")
11113 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11114 "<literal style=\"latex\">\n?\n</literal>")
11115 ("L" "#+LaTeX: "
11116 "<literal style=\"latex\">?</literal>")
11117 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11118 "<literal style=\"html\">\n?\n</literal>")
11119 ("H" "#+HTML: "
11120 "<literal style=\"html\">?</literal>")
11121 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11122 ("A" "#+ASCII: ")
11123 ("i" "#+INDEX: ?"
11124 "#+INDEX: ?")
11125 ("I" "#+INCLUDE %file ?"
11126 "<include file=%file markup=\"?\">")
11128 "Structure completion elements.
11129 This is a list of abbreviation keys and values. The value gets inserted
11130 if you type `<' followed by the key and then press the completion key,
11131 usually `M-TAB'. %file will be replaced by a file name after prompting
11132 for the file using completion. The cursor will be placed at the position
11133 of the `?` in the template.
11134 There are two templates for each key, the first uses the original Org syntax,
11135 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11136 the default when the /org-mtags.el/ module has been loaded. See also the
11137 variable `org-mtags-prefer-muse-templates'."
11138 :group 'org-completion
11139 :type '(repeat
11140 (string :tag "Key")
11141 (string :tag "Template")
11142 (string :tag "Muse Template")))
11144 (defun org-try-structure-completion ()
11145 "Try to complete a structure template before point.
11146 This looks for strings like \"<e\" on an otherwise empty line and
11147 expands them."
11148 (let ((l (buffer-substring (point-at-bol) (point)))
11150 (when (and (looking-at "[ \t]*$")
11151 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11152 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11153 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11154 (match-beginning 1)) a)
11155 t)))
11157 (defun org-complete-expand-structure-template (start cell)
11158 "Expand a structure template."
11159 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11160 (rpl (nth (if musep 2 1) cell))
11161 (ind ""))
11162 (delete-region start (point))
11163 (when (string-match "\\`#\\+" rpl)
11164 (cond
11165 ((bolp))
11166 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11167 (setq ind (buffer-substring (point-at-bol) (point))))
11168 (t (newline))))
11169 (setq start (point))
11170 (if (string-match "%file" rpl)
11171 (setq rpl (replace-match
11172 (concat
11173 "\""
11174 (save-match-data
11175 (abbreviate-file-name (read-file-name "Include file: ")))
11176 "\"")
11177 t t rpl)))
11178 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11179 (concat "\n" ind)))
11180 (insert rpl)
11181 (if (re-search-backward "\\?" start t) (delete-char 1))))
11183 ;;;; TODO, DEADLINE, Comments
11185 (defun org-toggle-comment ()
11186 "Change the COMMENT state of an entry."
11187 (interactive)
11188 (save-excursion
11189 (org-back-to-heading)
11190 (let (case-fold-search)
11191 (cond
11192 ((looking-at (format org-heading-keyword-regexp-format
11193 org-comment-string))
11194 (goto-char (match-end 1))
11195 (looking-at (concat " +" org-comment-string))
11196 (replace-match "" t t)
11197 (when (eolp) (insert " ")))
11198 ((looking-at org-outline-regexp)
11199 (goto-char (match-end 0))
11200 (insert org-comment-string " "))))))
11202 (defvar org-last-todo-state-is-todo nil
11203 "This is non-nil when the last TODO state change led to a TODO state.
11204 If the last change removed the TODO tag or switched to DONE, then
11205 this is nil.")
11207 (defvar org-setting-tags nil) ; dynamically skipped
11209 (defvar org-todo-setup-filter-hook nil
11210 "Hook for functions that pre-filter todo specs.
11211 Each function takes a todo spec and returns either nil or the spec
11212 transformed into canonical form." )
11214 (defvar org-todo-get-default-hook nil
11215 "Hook for functions that get a default item for todo.
11216 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11217 nil or a string to be used for the todo mark." )
11219 (defvar org-agenda-headline-snapshot-before-repeat)
11221 (defun org-current-effective-time ()
11222 "Return current time adjusted for `org-extend-today-until' variable"
11223 (let* ((ct (org-current-time))
11224 (dct (decode-time ct))
11225 (ct1
11226 (if (and org-use-effective-time
11227 (< (nth 2 dct) org-extend-today-until))
11228 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11229 ct)))
11230 ct1))
11232 (defun org-todo-yesterday (&optional arg)
11233 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11234 (interactive "P")
11235 (if (eq major-mode 'org-agenda-mode)
11236 (apply 'org-agenda-todo-yesterday arg)
11237 (let* ((hour (third (decode-time
11238 (org-current-time))))
11239 (org-extend-today-until (1+ hour)))
11240 (org-todo arg))))
11242 (defun org-todo (&optional arg)
11243 "Change the TODO state of an item.
11244 The state of an item is given by a keyword at the start of the heading,
11245 like
11246 *** TODO Write paper
11247 *** DONE Call mom
11249 The different keywords are specified in the variable `org-todo-keywords'.
11250 By default the available states are \"TODO\" and \"DONE\".
11251 So for this example: when the item starts with TODO, it is changed to DONE.
11252 When it starts with DONE, the DONE is removed. And when neither TODO nor
11253 DONE are present, add TODO at the beginning of the heading.
11255 With \\[universal-argument] prefix arg, use completion to determine the new \
11256 state.
11257 With numeric prefix arg, switch to that state.
11258 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11259 keywords (nextset).
11260 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11261 With a numeric prefix arg of 0, inhibit note taking for the change.
11263 For calling through lisp, arg is also interpreted in the following way:
11264 'none -> empty state
11265 \"\"(empty string) -> switch to empty state
11266 'done -> switch to DONE
11267 'nextset -> switch to the next set of keywords
11268 'previousset -> switch to the previous set of keywords
11269 \"WAITING\" -> switch to the specified keyword, but only if it
11270 really is a member of `org-todo-keywords'."
11271 (interactive "P")
11272 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11273 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11274 'region-start-level 'region))
11275 org-loop-over-headlines-in-active-region)
11276 (org-map-entries
11277 `(org-todo ,arg)
11278 org-loop-over-headlines-in-active-region
11279 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11280 (if (equal arg '(16)) (setq arg 'nextset))
11281 (let ((org-blocker-hook org-blocker-hook)
11282 (case-fold-search nil))
11283 (when (equal arg '(64))
11284 (setq arg nil org-blocker-hook nil))
11285 (when (and org-blocker-hook
11286 (or org-inhibit-blocking
11287 (org-entry-get nil "NOBLOCKING")))
11288 (setq org-blocker-hook nil))
11289 (save-excursion
11290 (catch 'exit
11291 (org-back-to-heading t)
11292 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11293 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11294 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11295 (let* ((match-data (match-data))
11296 (startpos (point-at-bol))
11297 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11298 (org-log-done org-log-done)
11299 (org-log-repeat org-log-repeat)
11300 (org-todo-log-states org-todo-log-states)
11301 (org-inhibit-logging
11302 (if (equal arg 0)
11303 (progn (setq arg nil) 'note) org-inhibit-logging))
11304 (this (match-string 1))
11305 (hl-pos (match-beginning 0))
11306 (head (org-get-todo-sequence-head this))
11307 (ass (assoc head org-todo-kwd-alist))
11308 (interpret (nth 1 ass))
11309 (done-word (nth 3 ass))
11310 (final-done-word (nth 4 ass))
11311 (last-state (or this ""))
11312 (completion-ignore-case t)
11313 (member (member this org-todo-keywords-1))
11314 (tail (cdr member))
11315 (state (cond
11316 ((and org-todo-key-trigger
11317 (or (and (equal arg '(4))
11318 (eq org-use-fast-todo-selection 'prefix))
11319 (and (not arg) org-use-fast-todo-selection
11320 (not (eq org-use-fast-todo-selection
11321 'prefix)))))
11322 ;; Use fast selection
11323 (org-fast-todo-selection))
11324 ((and (equal arg '(4))
11325 (or (not org-use-fast-todo-selection)
11326 (not org-todo-key-trigger)))
11327 ;; Read a state with completion
11328 (org-icompleting-read
11329 "State: " (mapcar (lambda(x) (list x))
11330 org-todo-keywords-1)
11331 nil t))
11332 ((eq arg 'right)
11333 (if this
11334 (if tail (car tail) nil)
11335 (car org-todo-keywords-1)))
11336 ((eq arg 'left)
11337 (if (equal member org-todo-keywords-1)
11339 (if this
11340 (nth (- (length org-todo-keywords-1)
11341 (length tail) 2)
11342 org-todo-keywords-1)
11343 (org-last org-todo-keywords-1))))
11344 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11345 (setq arg nil))) ; hack to fall back to cycling
11346 (arg
11347 ;; user or caller requests a specific state
11348 (cond
11349 ((equal arg "") nil)
11350 ((eq arg 'none) nil)
11351 ((eq arg 'done) (or done-word (car org-done-keywords)))
11352 ((eq arg 'nextset)
11353 (or (car (cdr (member head org-todo-heads)))
11354 (car org-todo-heads)))
11355 ((eq arg 'previousset)
11356 (let ((org-todo-heads (reverse org-todo-heads)))
11357 (or (car (cdr (member head org-todo-heads)))
11358 (car org-todo-heads))))
11359 ((car (member arg org-todo-keywords-1)))
11360 ((stringp arg)
11361 (error "State `%s' not valid in this file" arg))
11362 ((nth (1- (prefix-numeric-value arg))
11363 org-todo-keywords-1))))
11364 ((null member) (or head (car org-todo-keywords-1)))
11365 ((equal this final-done-word) nil) ;; -> make empty
11366 ((null tail) nil) ;; -> first entry
11367 ((memq interpret '(type priority))
11368 (if (eq this-command last-command)
11369 (car tail)
11370 (if (> (length tail) 0)
11371 (or done-word (car org-done-keywords))
11372 nil)))
11374 (car tail))))
11375 (state (or
11376 (run-hook-with-args-until-success
11377 'org-todo-get-default-hook state last-state)
11378 state))
11379 (next (if state (concat " " state " ") " "))
11380 (change-plist (list :type 'todo-state-change :from this :to state
11381 :position startpos))
11382 dolog now-done-p)
11383 (when org-blocker-hook
11384 (setq org-last-todo-state-is-todo
11385 (not (member this org-done-keywords)))
11386 (unless (save-excursion
11387 (save-match-data
11388 (org-with-wide-buffer
11389 (run-hook-with-args-until-failure
11390 'org-blocker-hook change-plist))))
11391 (if (org-called-interactively-p 'interactive)
11392 (error "TODO state change from %s to %s blocked" this state)
11393 ;; fail silently
11394 (message "TODO state change from %s to %s blocked" this state)
11395 (throw 'exit nil))))
11396 (store-match-data match-data)
11397 (replace-match next t t)
11398 (unless (pos-visible-in-window-p hl-pos)
11399 (message "TODO state changed to %s" (org-trim next)))
11400 (unless head
11401 (setq head (org-get-todo-sequence-head state)
11402 ass (assoc head org-todo-kwd-alist)
11403 interpret (nth 1 ass)
11404 done-word (nth 3 ass)
11405 final-done-word (nth 4 ass)))
11406 (when (memq arg '(nextset previousset))
11407 (message "Keyword-Set %d/%d: %s"
11408 (- (length org-todo-sets) -1
11409 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11410 (length org-todo-sets)
11411 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11412 (setq org-last-todo-state-is-todo
11413 (not (member state org-done-keywords)))
11414 (setq now-done-p (and (member state org-done-keywords)
11415 (not (member this org-done-keywords))))
11416 (and logging (org-local-logging logging))
11417 (when (and (or org-todo-log-states org-log-done)
11418 (not (eq org-inhibit-logging t))
11419 (not (memq arg '(nextset previousset))))
11420 ;; we need to look at recording a time and note
11421 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11422 (nth 2 (assoc this org-todo-log-states))))
11423 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11424 (setq dolog 'time))
11425 (when (and state
11426 (member state org-not-done-keywords)
11427 (not (member this org-not-done-keywords)))
11428 ;; This is now a todo state and was not one before
11429 ;; If there was a CLOSED time stamp, get rid of it.
11430 (org-add-planning-info nil nil 'closed))
11431 (when (and now-done-p org-log-done)
11432 ;; It is now done, and it was not done before
11433 (org-add-planning-info 'closed (org-current-effective-time))
11434 (if (and (not dolog) (eq 'note org-log-done))
11435 (org-add-log-setup 'done state this 'findpos 'note)))
11436 (when (and state dolog)
11437 ;; This is a non-nil state, and we need to log it
11438 (org-add-log-setup 'state state this 'findpos dolog)))
11439 ;; Fixup tag positioning
11440 (org-todo-trigger-tag-changes state)
11441 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11442 (when org-provide-todo-statistics
11443 (org-update-parent-todo-statistics))
11444 (run-hooks 'org-after-todo-state-change-hook)
11445 (if (and arg (not (member state org-done-keywords)))
11446 (setq head (org-get-todo-sequence-head state)))
11447 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11448 ;; Do we need to trigger a repeat?
11449 (when now-done-p
11450 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11451 ;; This is for the agenda, take a snapshot of the headline.
11452 (save-match-data
11453 (setq org-agenda-headline-snapshot-before-repeat
11454 (org-get-heading))))
11455 (org-auto-repeat-maybe state))
11456 ;; Fixup cursor location if close to the keyword
11457 (if (and (outline-on-heading-p)
11458 (not (bolp))
11459 (save-excursion (beginning-of-line 1)
11460 (looking-at org-todo-line-regexp))
11461 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11462 (progn
11463 (goto-char (or (match-end 2) (match-end 1)))
11464 (and (looking-at " ") (just-one-space))))
11465 (when org-trigger-hook
11466 (save-excursion
11467 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11469 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11470 "Block turning an entry into a TODO, using the hierarchy.
11471 This checks whether the current task should be blocked from state
11472 changes. Such blocking occurs when:
11474 1. The task has children which are not all in a completed state.
11476 2. A task has a parent with the property :ORDERED:, and there
11477 are siblings prior to the current task with incomplete
11478 status.
11480 3. The parent of the task is blocked because it has siblings that should
11481 be done first, or is child of a block grandparent TODO entry."
11483 (if (not org-enforce-todo-dependencies)
11484 t ; if locally turned off don't block
11485 (catch 'dont-block
11486 ;; If this is not a todo state change, or if this entry is already DONE,
11487 ;; do not block
11488 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11489 (member (plist-get change-plist :from)
11490 (cons 'done org-done-keywords))
11491 (member (plist-get change-plist :to)
11492 (cons 'todo org-not-done-keywords))
11493 (not (plist-get change-plist :to)))
11494 (throw 'dont-block t))
11495 ;; If this task has children, and any are undone, it's blocked
11496 (save-excursion
11497 (org-back-to-heading t)
11498 (let ((this-level (funcall outline-level)))
11499 (outline-next-heading)
11500 (let ((child-level (funcall outline-level)))
11501 (while (and (not (eobp))
11502 (> child-level this-level))
11503 ;; this todo has children, check whether they are all
11504 ;; completed
11505 (if (and (not (org-entry-is-done-p))
11506 (org-entry-is-todo-p))
11507 (throw 'dont-block nil))
11508 (outline-next-heading)
11509 (setq child-level (funcall outline-level))))))
11510 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11511 ;; any previous siblings are undone, it's blocked
11512 (save-excursion
11513 (org-back-to-heading t)
11514 (let* ((pos (point))
11515 (parent-pos (and (org-up-heading-safe) (point))))
11516 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11517 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11518 (forward-line 1)
11519 (re-search-forward org-not-done-heading-regexp pos t))
11520 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11521 ;; Search further up the hierarchy, to see if an ancestor is blocked
11522 (while t
11523 (goto-char parent-pos)
11524 (if (not (looking-at org-not-done-heading-regexp))
11525 (throw 'dont-block t)) ; do not block, parent is not a TODO
11526 (setq pos (point))
11527 (setq parent-pos (and (org-up-heading-safe) (point)))
11528 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11529 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11530 (forward-line 1)
11531 (re-search-forward org-not-done-heading-regexp pos t))
11532 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11534 (defcustom org-track-ordered-property-with-tag nil
11535 "Should the ORDERED property also be shown as a tag?
11536 The ORDERED property decides if an entry should require subtasks to be
11537 completed in sequence. Since a property is not very visible, setting
11538 this option means that toggling the ORDERED property with the command
11539 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11540 not relevant for the behavior, but it makes things more visible.
11542 Note that toggling the tag with tags commands will not change the property
11543 and therefore not influence behavior!
11545 This can be t, meaning the tag ORDERED should be used, It can also be a
11546 string to select a different tag for this task."
11547 :group 'org-todo
11548 :type '(choice
11549 (const :tag "No tracking" nil)
11550 (const :tag "Track with ORDERED tag" t)
11551 (string :tag "Use other tag")))
11553 (defun org-toggle-ordered-property ()
11554 "Toggle the ORDERED property of the current entry.
11555 For better visibility, you can track the value of this property with a tag.
11556 See variable `org-track-ordered-property-with-tag'."
11557 (interactive)
11558 (let* ((t1 org-track-ordered-property-with-tag)
11559 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11560 (save-excursion
11561 (org-back-to-heading)
11562 (if (org-entry-get nil "ORDERED")
11563 (progn
11564 (org-delete-property "ORDERED")
11565 (and tag (org-toggle-tag tag 'off))
11566 (message "Subtasks can be completed in arbitrary order"))
11567 (org-entry-put nil "ORDERED" "t")
11568 (and tag (org-toggle-tag tag 'on))
11569 (message "Subtasks must be completed in sequence")))))
11571 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11572 (defun org-block-todo-from-checkboxes (change-plist)
11573 "Block turning an entry into a TODO, using checkboxes.
11574 This checks whether the current task should be blocked from state
11575 changes because there are unchecked boxes in this entry."
11576 (if (not org-enforce-todo-checkbox-dependencies)
11577 t ; if locally turned off don't block
11578 (catch 'dont-block
11579 ;; If this is not a todo state change, or if this entry is already DONE,
11580 ;; do not block
11581 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11582 (member (plist-get change-plist :from)
11583 (cons 'done org-done-keywords))
11584 (member (plist-get change-plist :to)
11585 (cons 'todo org-not-done-keywords))
11586 (not (plist-get change-plist :to)))
11587 (throw 'dont-block t))
11588 ;; If this task has checkboxes that are not checked, it's blocked
11589 (save-excursion
11590 (org-back-to-heading t)
11591 (let ((beg (point)) end)
11592 (outline-next-heading)
11593 (setq end (point))
11594 (goto-char beg)
11595 (if (org-list-search-forward
11596 (concat (org-item-beginning-re)
11597 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11598 "\\[[- ]\\]")
11599 end t)
11600 (progn
11601 (if (boundp 'org-blocked-by-checkboxes)
11602 (setq org-blocked-by-checkboxes t))
11603 (throw 'dont-block nil)))))
11604 t))) ; do not block
11606 (defun org-entry-blocked-p ()
11607 "Is the current entry blocked?"
11608 (if (org-entry-get nil "NOBLOCKING")
11609 nil ;; Never block this entry
11610 (not
11611 (run-hook-with-args-until-failure
11612 'org-blocker-hook
11613 (list :type 'todo-state-change
11614 :position (point)
11615 :from 'todo
11616 :to 'done)))))
11618 (defun org-update-statistics-cookies (all)
11619 "Update the statistics cookie, either from TODO or from checkboxes.
11620 This should be called with the cursor in a line with a statistics cookie."
11621 (interactive "P")
11622 (if all
11623 (progn
11624 (org-update-checkbox-count 'all)
11625 (org-map-entries 'org-update-parent-todo-statistics))
11626 (if (not (org-at-heading-p))
11627 (org-update-checkbox-count)
11628 (let ((pos (move-marker (make-marker) (point)))
11629 end l1 l2)
11630 (ignore-errors (org-back-to-heading t))
11631 (if (not (org-at-heading-p))
11632 (org-update-checkbox-count)
11633 (setq l1 (org-outline-level))
11634 (setq end (save-excursion
11635 (outline-next-heading)
11636 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11637 (point)))
11638 (if (and (save-excursion
11639 (re-search-forward
11640 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11641 (not (save-excursion (re-search-forward
11642 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11643 (org-update-checkbox-count)
11644 (if (and l2 (> l2 l1))
11645 (progn
11646 (goto-char end)
11647 (org-update-parent-todo-statistics))
11648 (goto-char pos)
11649 (beginning-of-line 1)
11650 (while (re-search-forward
11651 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11652 (point-at-eol) t)
11653 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11654 (goto-char pos)
11655 (move-marker pos nil)))))
11657 (defvar org-entry-property-inherited-from) ;; defined below
11658 (defun org-update-parent-todo-statistics ()
11659 "Update any statistics cookie in the parent of the current headline.
11660 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11661 the entire subtree and this will travel up the hierarchy and update
11662 statistics everywhere."
11663 (let* ((prop (save-excursion (org-up-heading-safe)
11664 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11665 (recursive (or (not org-hierarchical-todo-statistics)
11666 (and prop (string-match "\\<recursive\\>" prop))))
11667 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11669 (first t)
11670 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11671 level ltoggle l1 new ndel
11672 (cnt-all 0) (cnt-done 0) is-percent kwd
11673 checkbox-beg ov ovs ove cookie-present)
11674 (catch 'exit
11675 (save-excursion
11676 (beginning-of-line 1)
11677 (setq ltoggle (funcall outline-level))
11678 ;; Three situations are to consider:
11680 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11681 ;; to the top-level ancestor on the headline;
11683 ;; 2. If parent has "recursive" property, repeat up to the
11684 ;; headline setting that property, taking inheritance into
11685 ;; account;
11687 ;; 3. Else, move up to direct parent and proceed only once.
11688 (while (and (setq level (org-up-heading-safe))
11689 (or recursive first)
11690 (>= (point) lim))
11691 (setq first nil cookie-present nil)
11692 (unless (and level
11693 (not (string-match
11694 "\\<checkbox\\>"
11695 (downcase (or (org-entry-get nil "COOKIE_DATA")
11696 "")))))
11697 (throw 'exit nil))
11698 (while (re-search-forward box-re (point-at-eol) t)
11699 (setq cnt-all 0 cnt-done 0 cookie-present t)
11700 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11701 (save-match-data
11702 (unless (outline-next-heading) (throw 'exit nil))
11703 (while (and (looking-at org-complex-heading-regexp)
11704 (> (setq l1 (length (match-string 1))) level))
11705 (setq kwd (and (or recursive (= l1 ltoggle))
11706 (match-string 2)))
11707 (if (or (eq org-provide-todo-statistics 'all-headlines)
11708 (and (listp org-provide-todo-statistics)
11709 (or (member kwd org-provide-todo-statistics)
11710 (member kwd org-done-keywords))))
11711 (setq cnt-all (1+ cnt-all))
11712 (if (eq org-provide-todo-statistics t)
11713 (and kwd (setq cnt-all (1+ cnt-all)))))
11714 (and (member kwd org-done-keywords)
11715 (setq cnt-done (1+ cnt-done)))
11716 (outline-next-heading)))
11717 (setq new
11718 (if is-percent
11719 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11720 (format "[%d/%d]" cnt-done cnt-all))
11721 ndel (- (match-end 0) checkbox-beg))
11722 ;; handle overlays when updating cookie from column view
11723 (when (setq ov (car (overlays-at checkbox-beg)))
11724 (setq ovs (overlay-start ov) ove (overlay-end ov))
11725 (delete-overlay ov))
11726 (goto-char checkbox-beg)
11727 (insert new)
11728 (delete-region (point) (+ (point) ndel))
11729 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11730 (when ov (move-overlay ov ovs ove)))
11731 (when cookie-present
11732 (run-hook-with-args 'org-after-todo-statistics-hook
11733 cnt-done (- cnt-all cnt-done))))))
11734 (run-hooks 'org-todo-statistics-hook)))
11736 (defvar org-after-todo-statistics-hook nil
11737 "Hook that is called after a TODO statistics cookie has been updated.
11738 Each function is called with two arguments: the number of not-done entries
11739 and the number of done entries.
11741 For example, the following function, when added to this hook, will switch
11742 an entry to DONE when all children are done, and back to TODO when new
11743 entries are set to a TODO status. Note that this hook is only called
11744 when there is a statistics cookie in the headline!
11746 (defun org-summary-todo (n-done n-not-done)
11747 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11748 (let (org-log-done org-log-states) ; turn off logging
11749 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11752 (defvar org-todo-statistics-hook nil
11753 "Hook that is run whenever Org thinks TODO statistics should be updated.
11754 This hook runs even if there is no statistics cookie present, in which case
11755 `org-after-todo-statistics-hook' would not run.")
11757 (defun org-todo-trigger-tag-changes (state)
11758 "Apply the changes defined in `org-todo-state-tags-triggers'."
11759 (let ((l org-todo-state-tags-triggers)
11760 changes)
11761 (when (or (not state) (equal state ""))
11762 (setq changes (append changes (cdr (assoc "" l)))))
11763 (when (and (stringp state) (> (length state) 0))
11764 (setq changes (append changes (cdr (assoc state l)))))
11765 (when (member state org-not-done-keywords)
11766 (setq changes (append changes (cdr (assoc 'todo l)))))
11767 (when (member state org-done-keywords)
11768 (setq changes (append changes (cdr (assoc 'done l)))))
11769 (dolist (c changes)
11770 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11772 (defun org-local-logging (value)
11773 "Get logging settings from a property VALUE."
11774 (let* (words w a)
11775 ;; directly set the variables, they are already local.
11776 (setq org-log-done nil
11777 org-log-repeat nil
11778 org-todo-log-states nil)
11779 (setq words (org-split-string value))
11780 (while (setq w (pop words))
11781 (cond
11782 ((setq a (assoc w org-startup-options))
11783 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11784 (set (nth 1 a) (nth 2 a))))
11785 ((setq a (org-extract-log-state-settings w))
11786 (and (member (car a) org-todo-keywords-1)
11787 (push a org-todo-log-states)))))))
11789 (defun org-get-todo-sequence-head (kwd)
11790 "Return the head of the TODO sequence to which KWD belongs.
11791 If KWD is not set, check if there is a text property remembering the
11792 right sequence."
11793 (let (p)
11794 (cond
11795 ((not kwd)
11796 (or (get-text-property (point-at-bol) 'org-todo-head)
11797 (progn
11798 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11799 nil (point-at-eol)))
11800 (get-text-property p 'org-todo-head))))
11801 ((not (member kwd org-todo-keywords-1))
11802 (car org-todo-keywords-1))
11803 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11805 (defun org-fast-todo-selection ()
11806 "Fast TODO keyword selection with single keys.
11807 Returns the new TODO keyword, or nil if no state change should occur."
11808 (let* ((fulltable org-todo-key-alist)
11809 (done-keywords org-done-keywords) ;; needed for the faces.
11810 (maxlen (apply 'max (mapcar
11811 (lambda (x)
11812 (if (stringp (car x)) (string-width (car x)) 0))
11813 fulltable)))
11814 (expert nil)
11815 (fwidth (+ maxlen 3 1 3))
11816 (ncol (/ (- (window-width) 4) fwidth))
11817 tg cnt e c tbl
11818 groups ingroup)
11819 (save-excursion
11820 (save-window-excursion
11821 (if expert
11822 (set-buffer (get-buffer-create " *Org todo*"))
11823 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11824 (erase-buffer)
11825 (org-set-local 'org-done-keywords done-keywords)
11826 (setq tbl fulltable cnt 0)
11827 (while (setq e (pop tbl))
11828 (cond
11829 ((equal e '(:startgroup))
11830 (push '() groups) (setq ingroup t)
11831 (when (not (= cnt 0))
11832 (setq cnt 0)
11833 (insert "\n"))
11834 (insert "{ "))
11835 ((equal e '(:endgroup))
11836 (setq ingroup nil cnt 0)
11837 (insert "}\n"))
11838 ((equal e '(:newline))
11839 (when (not (= cnt 0))
11840 (setq cnt 0)
11841 (insert "\n")
11842 (setq e (car tbl))
11843 (while (equal (car tbl) '(:newline))
11844 (insert "\n")
11845 (setq tbl (cdr tbl)))))
11847 (setq tg (car e) c (cdr e))
11848 (if ingroup (push tg (car groups)))
11849 (setq tg (org-add-props tg nil 'face
11850 (org-get-todo-face tg)))
11851 (if (and (= cnt 0) (not ingroup)) (insert " "))
11852 (insert "[" c "] " tg (make-string
11853 (- fwidth 4 (length tg)) ?\ ))
11854 (when (= (setq cnt (1+ cnt)) ncol)
11855 (insert "\n")
11856 (if ingroup (insert " "))
11857 (setq cnt 0)))))
11858 (insert "\n")
11859 (goto-char (point-min))
11860 (if (not expert) (org-fit-window-to-buffer))
11861 (message "[a-z..]:Set [SPC]:clear")
11862 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11863 (cond
11864 ((or (= c ?\C-g)
11865 (and (= c ?q) (not (rassoc c fulltable))))
11866 (setq quit-flag t))
11867 ((= c ?\ ) nil)
11868 ((setq e (rassoc c fulltable) tg (car e))
11870 (t (setq quit-flag t)))))))
11872 (defun org-entry-is-todo-p ()
11873 (member (org-get-todo-state) org-not-done-keywords))
11875 (defun org-entry-is-done-p ()
11876 (member (org-get-todo-state) org-done-keywords))
11878 (defun org-get-todo-state ()
11879 (save-excursion
11880 (org-back-to-heading t)
11881 (and (looking-at org-todo-line-regexp)
11882 (match-end 2)
11883 (match-string 2))))
11885 (defun org-at-date-range-p (&optional inactive-ok)
11886 "Is the cursor inside a date range?"
11887 (interactive)
11888 (save-excursion
11889 (catch 'exit
11890 (let ((pos (point)))
11891 (skip-chars-backward "^[<\r\n")
11892 (skip-chars-backward "<[")
11893 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11894 (>= (match-end 0) pos)
11895 (throw 'exit t))
11896 (skip-chars-backward "^<[\r\n")
11897 (skip-chars-backward "<[")
11898 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11899 (>= (match-end 0) pos)
11900 (throw 'exit t)))
11901 nil)))
11903 (defun org-get-repeat (&optional tagline)
11904 "Check if there is a deadline/schedule with repeater in this entry."
11905 (save-match-data
11906 (save-excursion
11907 (org-back-to-heading t)
11908 (and (re-search-forward (if tagline
11909 (concat tagline "\\s-*" org-repeat-re)
11910 org-repeat-re)
11911 (org-entry-end-position) t)
11912 (match-string-no-properties 1)))))
11914 (defvar org-last-changed-timestamp)
11915 (defvar org-last-inserted-timestamp)
11916 (defvar org-log-post-message)
11917 (defvar org-log-note-purpose)
11918 (defvar org-log-note-how)
11919 (defvar org-log-note-extra)
11920 (defun org-auto-repeat-maybe (done-word)
11921 "Check if the current headline contains a repeated deadline/schedule.
11922 If yes, set TODO state back to what it was and change the base date
11923 of repeating deadline/scheduled time stamps to new date.
11924 This function is run automatically after each state change to a DONE state."
11925 ;; last-state is dynamically scoped into this function
11926 (let* ((repeat (org-get-repeat))
11927 (aa (assoc last-state org-todo-kwd-alist))
11928 (interpret (nth 1 aa))
11929 (head (nth 2 aa))
11930 (whata '(("d" . day) ("m" . month) ("y" . year)))
11931 (msg "Entry repeats: ")
11932 (org-log-done nil)
11933 (org-todo-log-states nil)
11934 re type n what ts time to-state)
11935 (when repeat
11936 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11937 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11938 org-todo-repeat-to-state))
11939 (unless (and to-state (member to-state org-todo-keywords-1))
11940 (setq to-state (if (eq interpret 'type) last-state head)))
11941 (org-todo to-state)
11942 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11943 (org-entry-put nil "LAST_REPEAT" (format-time-string
11944 (org-time-stamp-format t t))))
11945 (when org-log-repeat
11946 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11947 (memq 'org-add-log-note post-command-hook))
11948 ;; OK, we are already setup for some record
11949 (if (eq org-log-repeat 'note)
11950 ;; make sure we take a note, not only a time stamp
11951 (setq org-log-note-how 'note))
11952 ;; Set up for taking a record
11953 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11954 last-state
11955 'findpos org-log-repeat)))
11956 (org-back-to-heading t)
11957 (org-add-planning-info nil nil 'closed)
11958 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11959 org-deadline-time-regexp "\\)\\|\\("
11960 org-ts-regexp "\\)"))
11961 (while (re-search-forward
11962 re (save-excursion (outline-next-heading) (point)) t)
11963 (setq type (if (match-end 1) org-scheduled-string
11964 (if (match-end 3) org-deadline-string "Plain:"))
11965 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11966 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11967 (setq n (string-to-number (match-string 2 ts))
11968 what (match-string 3 ts))
11969 (if (equal what "w") (setq n (* n 7) what "d"))
11970 ;; Preparation, see if we need to modify the start date for the change
11971 (when (match-end 1)
11972 (setq time (save-match-data (org-time-string-to-time ts)))
11973 (cond
11974 ((equal (match-string 1 ts) ".")
11975 ;; Shift starting date to today
11976 (org-timestamp-change
11977 (- (org-today) (time-to-days time))
11978 'day))
11979 ((equal (match-string 1 ts) "+")
11980 (let ((nshiftmax 10) (nshift 0))
11981 (while (or (= nshift 0)
11982 (<= (time-to-days time)
11983 (time-to-days (current-time))))
11984 (when (= (incf nshift) nshiftmax)
11985 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11986 (error "Abort")))
11987 (org-timestamp-change n (cdr (assoc what whata)))
11988 (org-at-timestamp-p t)
11989 (setq ts (match-string 1))
11990 (setq time (save-match-data (org-time-string-to-time ts)))))
11991 (org-timestamp-change (- n) (cdr (assoc what whata)))
11992 ;; rematch, so that we have everything in place for the real shift
11993 (org-at-timestamp-p t)
11994 (setq ts (match-string 1))
11995 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11996 (org-timestamp-change n (cdr (assoc what whata)))
11997 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11998 (setq org-log-post-message msg)
11999 (message "%s" msg))))
12001 (defun org-show-todo-tree (arg)
12002 "Make a compact tree which shows all headlines marked with TODO.
12003 The tree will show the lines where the regexp matches, and all higher
12004 headlines above the match.
12005 With a \\[universal-argument] prefix, prompt for a regexp to match.
12006 With a numeric prefix N, construct a sparse tree for the Nth element
12007 of `org-todo-keywords-1'."
12008 (interactive "P")
12009 (let ((case-fold-search nil)
12010 (kwd-re
12011 (cond ((null arg) org-not-done-regexp)
12012 ((equal arg '(4))
12013 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12014 (mapcar 'list org-todo-keywords-1))))
12015 (concat "\\("
12016 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12017 "\\)\\>")))
12018 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12019 (regexp-quote (nth (1- (prefix-numeric-value arg))
12020 org-todo-keywords-1)))
12021 (t (error "Invalid prefix argument: %s" arg)))))
12022 (message "%d TODO entries found"
12023 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12025 (defun org-deadline (&optional remove time)
12026 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12027 With argument REMOVE, remove any deadline from the item.
12028 With argument TIME, set the deadline at the corresponding date. TIME
12029 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12030 (interactive "P")
12031 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12032 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12033 'region-start-level 'region))
12034 org-loop-over-headlines-in-active-region)
12035 (org-map-entries
12036 `(org-deadline ',remove ,time)
12037 org-loop-over-headlines-in-active-region
12038 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12039 (let* ((old-date (org-entry-get nil "DEADLINE"))
12040 (repeater (and old-date
12041 (string-match
12042 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12043 old-date)
12044 (match-string 1 old-date))))
12045 (if remove
12046 (progn
12047 (when (and old-date org-log-redeadline)
12048 (org-add-log-setup 'deldeadline nil old-date 'findpos
12049 org-log-redeadline))
12050 (org-remove-timestamp-with-keyword org-deadline-string)
12051 (message "Item no longer has a deadline."))
12052 (org-add-planning-info 'deadline time 'closed)
12053 (when (and old-date org-log-redeadline
12054 (not (equal old-date
12055 (substring org-last-inserted-timestamp 1 -1))))
12056 (org-add-log-setup 'redeadline nil old-date 'findpos
12057 org-log-redeadline))
12058 (when repeater
12059 (save-excursion
12060 (org-back-to-heading t)
12061 (when (re-search-forward (concat org-deadline-string " "
12062 org-last-inserted-timestamp)
12063 (save-excursion
12064 (outline-next-heading) (point)) t)
12065 (goto-char (1- (match-end 0)))
12066 (insert " " repeater)
12067 (setq org-last-inserted-timestamp
12068 (concat (substring org-last-inserted-timestamp 0 -1)
12069 " " repeater
12070 (substring org-last-inserted-timestamp -1))))))
12071 (message "Deadline on %s" org-last-inserted-timestamp)))))
12073 (defun org-schedule (&optional remove time)
12074 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12075 With argument REMOVE, remove any scheduling date from the item.
12076 With argument TIME, scheduled at the corresponding date. TIME can
12077 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12078 (interactive "P")
12079 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12080 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12081 'region-start-level 'region))
12082 org-loop-over-headlines-in-active-region)
12083 (org-map-entries
12084 `(org-schedule ',remove ,time)
12085 org-loop-over-headlines-in-active-region
12086 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12087 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12088 (repeater (and old-date
12089 (string-match
12090 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12091 old-date)
12092 (match-string 1 old-date))))
12093 (if remove
12094 (progn
12095 (when (and old-date org-log-reschedule)
12096 (org-add-log-setup 'delschedule nil old-date 'findpos
12097 org-log-reschedule))
12098 (org-remove-timestamp-with-keyword org-scheduled-string)
12099 (message "Item is no longer scheduled."))
12100 (org-add-planning-info 'scheduled time 'closed)
12101 (when (and old-date org-log-reschedule
12102 (not (equal old-date
12103 (substring org-last-inserted-timestamp 1 -1))))
12104 (org-add-log-setup 'reschedule nil old-date 'findpos
12105 org-log-reschedule))
12106 (when repeater
12107 (save-excursion
12108 (org-back-to-heading t)
12109 (when (re-search-forward (concat org-scheduled-string " "
12110 org-last-inserted-timestamp)
12111 (save-excursion
12112 (outline-next-heading) (point)) t)
12113 (goto-char (1- (match-end 0)))
12114 (insert " " repeater)
12115 (setq org-last-inserted-timestamp
12116 (concat (substring org-last-inserted-timestamp 0 -1)
12117 " " repeater
12118 (substring org-last-inserted-timestamp -1))))))
12119 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12121 (defun org-get-scheduled-time (pom &optional inherit)
12122 "Get the scheduled time as a time tuple, of a format suitable
12123 for calling org-schedule with, or if there is no scheduling,
12124 returns nil."
12125 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12126 (when time
12127 (apply 'encode-time (org-parse-time-string time)))))
12129 (defun org-get-deadline-time (pom &optional inherit)
12130 "Get the deadline as a time tuple, of a format suitable for
12131 calling org-deadline with, or if there is no scheduling, returns
12132 nil."
12133 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12134 (when time
12135 (apply 'encode-time (org-parse-time-string time)))))
12137 (defun org-remove-timestamp-with-keyword (keyword)
12138 "Remove all time stamps with KEYWORD in the current entry."
12139 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12140 beg)
12141 (save-excursion
12142 (org-back-to-heading t)
12143 (setq beg (point))
12144 (outline-next-heading)
12145 (while (re-search-backward re beg t)
12146 (replace-match "")
12147 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12148 (equal (char-before) ?\ ))
12149 (backward-delete-char 1)
12150 (if (string-match "^[ \t]*$" (buffer-substring
12151 (point-at-bol) (point-at-eol)))
12152 (delete-region (point-at-bol)
12153 (min (point-max) (1+ (point-at-eol))))))))))
12155 (defun org-add-planning-info (what &optional time &rest remove)
12156 "Insert new timestamp with keyword in the line directly after the headline.
12157 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12158 If non is given, the user is prompted for a date.
12159 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12160 be removed."
12161 (interactive)
12162 (let (org-time-was-given org-end-time-was-given ts
12163 end default-time default-input)
12165 (catch 'exit
12166 (when (and (memq what '(scheduled deadline))
12167 (or (not time)
12168 (and (stringp time)
12169 (string-match "^[-+]+[0-9]" time))))
12170 ;; Try to get a default date/time from existing timestamp
12171 (save-excursion
12172 (org-back-to-heading t)
12173 (setq end (save-excursion (outline-next-heading) (point)))
12174 (when (re-search-forward (if (eq what 'scheduled)
12175 org-scheduled-time-regexp
12176 org-deadline-time-regexp)
12177 end t)
12178 (setq ts (match-string 1)
12179 default-time
12180 (apply 'encode-time (org-parse-time-string ts))
12181 default-input (and ts (org-get-compact-tod ts))))))
12182 (when what
12183 (setq time
12184 (if (stringp time)
12185 ;; This is a string (relative or absolute), set proper date
12186 (apply 'encode-time
12187 (org-read-date-analyze
12188 time default-time (decode-time default-time)))
12189 ;; If necessary, get the time from the user
12190 (or time (org-read-date nil 'to-time nil nil
12191 default-time default-input)))))
12193 (when (and org-insert-labeled-timestamps-at-point
12194 (member what '(scheduled deadline)))
12195 (insert
12196 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12197 (org-insert-time-stamp time org-time-was-given
12198 nil nil nil (list org-end-time-was-given))
12199 (setq what nil))
12200 (save-excursion
12201 (save-restriction
12202 (let (col list elt ts buffer-invisibility-spec)
12203 (org-back-to-heading t)
12204 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12205 (goto-char (match-end 1))
12206 (setq col (current-column))
12207 (goto-char (match-end 0))
12208 (if (eobp) (insert "\n") (forward-char 1))
12209 (when (and (not what)
12210 (not (looking-at
12211 (concat "[ \t]*"
12212 org-keyword-time-not-clock-regexp))))
12213 ;; Nothing to add, nothing to remove...... :-)
12214 (throw 'exit nil))
12215 (if (and (not (looking-at org-outline-regexp))
12216 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12217 "[^\r\n]*"))
12218 (not (equal (match-string 1) org-clock-string)))
12219 (narrow-to-region (match-beginning 0) (match-end 0))
12220 (insert-before-markers "\n")
12221 (backward-char 1)
12222 (narrow-to-region (point) (point))
12223 (and org-adapt-indentation (org-indent-to-column col)))
12224 ;; Check if we have to remove something.
12225 (setq list (cons what remove))
12226 (while list
12227 (setq elt (pop list))
12228 (when (or (and (eq elt 'scheduled)
12229 (re-search-forward org-scheduled-time-regexp nil t))
12230 (and (eq elt 'deadline)
12231 (re-search-forward org-deadline-time-regexp nil t))
12232 (and (eq elt 'closed)
12233 (re-search-forward org-closed-time-regexp nil t)))
12234 (replace-match "")
12235 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12236 (and (looking-at "[ \t]+") (replace-match ""))
12237 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12238 (when what
12239 (insert
12240 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12241 (cond ((eq what 'scheduled) org-scheduled-string)
12242 ((eq what 'deadline) org-deadline-string)
12243 ((eq what 'closed) org-closed-string))
12244 " ")
12245 (setq ts (org-insert-time-stamp
12246 time
12247 (or org-time-was-given
12248 (and (eq what 'closed) org-log-done-with-time))
12249 (eq what 'closed)
12250 nil nil (list org-end-time-was-given)))
12251 (insert
12252 (if (not (or (bolp) (eq (char-before) ?\ )
12253 (memq (char-after) '(32 10))
12254 (eobp))) " " ""))
12255 (end-of-line 1))
12256 (goto-char (point-min))
12257 (widen)
12258 (if (and (looking-at "[ \t]*\n")
12259 (equal (char-before) ?\n))
12260 (delete-region (1- (point)) (point-at-eol)))
12261 ts))))))
12263 (defvar org-log-note-marker (make-marker))
12264 (defvar org-log-note-purpose nil)
12265 (defvar org-log-note-state nil)
12266 (defvar org-log-note-previous-state nil)
12267 (defvar org-log-note-how nil)
12268 (defvar org-log-note-extra nil)
12269 (defvar org-log-note-window-configuration nil)
12270 (defvar org-log-note-return-to (make-marker))
12271 (defvar org-log-note-effective-time nil
12272 "Remembered current time so that dynamically scoped
12273 `org-extend-today-until' affects tha timestamps in state change
12274 log")
12276 (defvar org-log-post-message nil
12277 "Message to be displayed after a log note has been stored.
12278 The auto-repeater uses this.")
12280 (defun org-add-note ()
12281 "Add a note to the current entry.
12282 This is done in the same way as adding a state change note."
12283 (interactive)
12284 (org-add-log-setup 'note nil nil 'findpos nil))
12286 (defvar org-property-end-re)
12287 (defun org-add-log-setup (&optional purpose state prev-state
12288 findpos how extra)
12289 "Set up the post command hook to take a note.
12290 If this is about to TODO state change, the new state is expected in STATE.
12291 When FINDPOS is non-nil, find the correct position for the note in
12292 the current entry. If not, assume that it can be inserted at point.
12293 HOW is an indicator what kind of note should be created.
12294 EXTRA is additional text that will be inserted into the notes buffer."
12295 (let* ((org-log-into-drawer (org-log-into-drawer))
12296 (drawer (cond ((stringp org-log-into-drawer)
12297 org-log-into-drawer)
12298 (org-log-into-drawer "LOGBOOK")
12299 (t nil))))
12300 (save-restriction
12301 (save-excursion
12302 (when findpos
12303 (org-back-to-heading t)
12304 (narrow-to-region (point) (save-excursion
12305 (outline-next-heading) (point)))
12306 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12307 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12308 "[^\r\n]*\\)?"))
12309 (goto-char (match-end 0))
12310 (cond
12311 (drawer
12312 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12313 nil t)
12314 (progn
12315 (goto-char (match-end 0))
12316 (or org-log-states-order-reversed
12317 (and (re-search-forward org-property-end-re nil t)
12318 (goto-char (1- (match-beginning 0))))))
12319 (insert "\n:" drawer ":\n:END:")
12320 (beginning-of-line 0)
12321 (org-indent-line-function)
12322 (beginning-of-line 2)
12323 (org-indent-line-function)
12324 (end-of-line 0)))
12325 ((and org-log-state-notes-insert-after-drawers
12326 (save-excursion
12327 (forward-line) (looking-at org-drawer-regexp)))
12328 (forward-line)
12329 (while (looking-at org-drawer-regexp)
12330 (goto-char (match-end 0))
12331 (re-search-forward org-property-end-re (point-max) t)
12332 (forward-line))
12333 (forward-line -1)))
12334 (unless org-log-states-order-reversed
12335 (and (= (char-after) ?\n) (forward-char 1))
12336 (org-skip-over-state-notes)
12337 (skip-chars-backward " \t\n\r")))
12338 (move-marker org-log-note-marker (point))
12339 (setq org-log-note-purpose purpose
12340 org-log-note-state state
12341 org-log-note-previous-state prev-state
12342 org-log-note-how how
12343 org-log-note-extra extra
12344 org-log-note-effective-time (org-current-effective-time))
12345 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12347 (defun org-skip-over-state-notes ()
12348 "Skip past the list of State notes in an entry."
12349 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12350 (when (ignore-errors (goto-char (org-in-item-p)))
12351 (let* ((struct (org-list-struct))
12352 (prevs (org-list-prevs-alist struct)))
12353 (while (looking-at "[ \t]*- State")
12354 (goto-char (or (org-list-get-next-item (point) struct prevs)
12355 (org-list-get-item-end (point) struct)))))))
12357 (defun org-add-log-note (&optional purpose)
12358 "Pop up a window for taking a note, and add this note later at point."
12359 (remove-hook 'post-command-hook 'org-add-log-note)
12360 (setq org-log-note-window-configuration (current-window-configuration))
12361 (delete-other-windows)
12362 (move-marker org-log-note-return-to (point))
12363 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12364 (goto-char org-log-note-marker)
12365 (org-switch-to-buffer-other-window "*Org Note*")
12366 (erase-buffer)
12367 (if (memq org-log-note-how '(time state))
12368 (let (current-prefix-arg) (org-store-log-note))
12369 (let ((org-inhibit-startup t)) (org-mode))
12370 (insert (format "# Insert note for %s.
12371 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12372 (cond
12373 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12374 ((eq org-log-note-purpose 'done) "closed todo item")
12375 ((eq org-log-note-purpose 'state)
12376 (format "state change from \"%s\" to \"%s\""
12377 (or org-log-note-previous-state "")
12378 (or org-log-note-state "")))
12379 ((eq org-log-note-purpose 'reschedule)
12380 "rescheduling")
12381 ((eq org-log-note-purpose 'delschedule)
12382 "no longer scheduled")
12383 ((eq org-log-note-purpose 'redeadline)
12384 "changing deadline")
12385 ((eq org-log-note-purpose 'deldeadline)
12386 "removing deadline")
12387 ((eq org-log-note-purpose 'refile)
12388 "refiling")
12389 ((eq org-log-note-purpose 'note)
12390 "this entry")
12391 (t (error "This should not happen")))))
12392 (if org-log-note-extra (insert org-log-note-extra))
12393 (org-set-local 'org-finish-function 'org-store-log-note)
12394 (run-hooks 'org-log-buffer-setup-hook)))
12396 (defvar org-note-abort nil) ; dynamically scoped
12397 (defun org-store-log-note ()
12398 "Finish taking a log note, and insert it to where it belongs."
12399 (let ((txt (buffer-string))
12400 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12401 lines ind bul)
12402 (kill-buffer (current-buffer))
12403 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12404 (setq txt (replace-match "" t t txt)))
12405 (if (string-match "\\s-+\\'" txt)
12406 (setq txt (replace-match "" t t txt)))
12407 (setq lines (org-split-string txt "\n"))
12408 (when (and note (string-match "\\S-" note))
12409 (setq note
12410 (org-replace-escapes
12411 note
12412 (list (cons "%u" (user-login-name))
12413 (cons "%U" user-full-name)
12414 (cons "%t" (format-time-string
12415 (org-time-stamp-format 'long 'inactive)
12416 org-log-note-effective-time))
12417 (cons "%T" (format-time-string
12418 (org-time-stamp-format 'long nil)
12419 org-log-note-effective-time))
12420 (cons "%d" (format-time-string
12421 (org-time-stamp-format nil 'inactive)
12422 org-log-note-effective-time))
12423 (cons "%D" (format-time-string
12424 (org-time-stamp-format nil nil)
12425 org-log-note-effective-time))
12426 (cons "%s" (if org-log-note-state
12427 (concat "\"" org-log-note-state "\"")
12428 ""))
12429 (cons "%S" (if org-log-note-previous-state
12430 (concat "\"" org-log-note-previous-state "\"")
12431 "\"\"")))))
12432 (if lines (setq note (concat note " \\\\")))
12433 (push note lines))
12434 (when (or current-prefix-arg org-note-abort)
12435 (when org-log-into-drawer
12436 (org-remove-empty-drawer-at
12437 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12438 org-log-note-marker))
12439 (setq lines nil))
12440 (when lines
12441 (with-current-buffer (marker-buffer org-log-note-marker)
12442 (save-excursion
12443 (goto-char org-log-note-marker)
12444 (move-marker org-log-note-marker nil)
12445 (end-of-line 1)
12446 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12447 (setq ind (save-excursion
12448 (if (ignore-errors (goto-char (org-in-item-p)))
12449 (let ((struct (org-list-struct)))
12450 (org-list-get-ind
12451 (org-list-get-top-point struct) struct))
12452 (skip-chars-backward " \r\t\n")
12453 (cond
12454 ((and (org-at-heading-p)
12455 org-adapt-indentation)
12456 (1+ (org-current-level)))
12457 ((org-at-heading-p) 0)
12458 (t (org-get-indentation))))))
12459 (setq bul (org-list-bullet-string "-"))
12460 (org-indent-line-to ind)
12461 (insert bul (pop lines))
12462 (let ((ind-body (+ (length bul) ind)))
12463 (while lines
12464 (insert "\n")
12465 (org-indent-line-to ind-body)
12466 (insert (pop lines))))
12467 (message "Note stored")
12468 (org-back-to-heading t)
12469 (org-cycle-hide-drawers 'children)))))
12470 (set-window-configuration org-log-note-window-configuration)
12471 (with-current-buffer (marker-buffer org-log-note-return-to)
12472 (goto-char org-log-note-return-to))
12473 (move-marker org-log-note-return-to nil)
12474 (and org-log-post-message (message "%s" org-log-post-message)))
12476 (defun org-remove-empty-drawer-at (drawer pos)
12477 "Remove an empty drawer DRAWER at position POS.
12478 POS may also be a marker."
12479 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12480 (save-excursion
12481 (save-restriction
12482 (widen)
12483 (goto-char pos)
12484 (if (org-in-regexp
12485 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12486 (replace-match ""))))))
12488 (defun org-sparse-tree (&optional arg)
12489 "Create a sparse tree, prompt for the details.
12490 This command can create sparse trees. You first need to select the type
12491 of match used to create the tree:
12493 t Show all TODO entries.
12494 T Show entries with a specific TODO keyword.
12495 m Show entries selected by a tags/property match.
12496 p Enter a property name and its value (both with completion on existing
12497 names/values) and show entries with that property.
12498 r Show entries matching a regular expression (`/' can be used as well)
12499 d Show deadlines due within `org-deadline-warning-days'.
12500 b Show deadlines and scheduled items before a date.
12501 a Show deadlines and scheduled items after a date."
12502 (interactive "P")
12503 (let (ans kwd value)
12504 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range")
12505 (setq ans (read-char-exclusive))
12506 (cond
12507 ((equal ans ?d)
12508 (call-interactively 'org-check-deadlines))
12509 ((equal ans ?b)
12510 (call-interactively 'org-check-before-date))
12511 ((equal ans ?a)
12512 (call-interactively 'org-check-after-date))
12513 ((equal ans ?D)
12514 (call-interactively 'org-check-dates-range))
12515 ((equal ans ?t)
12516 (org-show-todo-tree nil))
12517 ((equal ans ?T)
12518 (org-show-todo-tree '(4)))
12519 ((member ans '(?T ?m))
12520 (call-interactively 'org-match-sparse-tree))
12521 ((member ans '(?p ?P))
12522 (setq kwd (org-icompleting-read "Property: "
12523 (mapcar 'list (org-buffer-property-keys))))
12524 (setq value (org-icompleting-read "Value: "
12525 (mapcar 'list (org-property-values kwd))))
12526 (unless (string-match "\\`{.*}\\'" value)
12527 (setq value (concat "\"" value "\"")))
12528 (org-match-sparse-tree arg (concat kwd "=" value)))
12529 ((member ans '(?r ?R ?/))
12530 (call-interactively 'org-occur))
12531 (t (error "No such sparse tree command \"%c\"" ans)))))
12533 (defvar org-occur-highlights nil
12534 "List of overlays used for occur matches.")
12535 (make-variable-buffer-local 'org-occur-highlights)
12536 (defvar org-occur-parameters nil
12537 "Parameters of the active org-occur calls.
12538 This is a list, each call to org-occur pushes as cons cell,
12539 containing the regular expression and the callback, onto the list.
12540 The list can contain several entries if `org-occur' has been called
12541 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12542 will only contain one set of parameters. When the highlights are
12543 removed (for example with `C-c C-c', or with the next edit (depending
12544 on `org-remove-highlights-with-change'), this variable is emptied
12545 as well.")
12546 (make-variable-buffer-local 'org-occur-parameters)
12548 (defun org-occur (regexp &optional keep-previous callback)
12549 "Make a compact tree which shows all matches of REGEXP.
12550 The tree will show the lines where the regexp matches, and all higher
12551 headlines above the match. It will also show the heading after the match,
12552 to make sure editing the matching entry is easy.
12553 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12554 call to `org-occur' will be kept, to allow stacking of calls to this
12555 command.
12556 If CALLBACK is non-nil, it is a function which is called to confirm
12557 that the match should indeed be shown."
12558 (interactive "sRegexp: \nP")
12559 (when (equal regexp "")
12560 (error "Regexp cannot be empty"))
12561 (unless keep-previous
12562 (org-remove-occur-highlights nil nil t))
12563 (push (cons regexp callback) org-occur-parameters)
12564 (let ((cnt 0))
12565 (save-excursion
12566 (goto-char (point-min))
12567 (if (or (not keep-previous) ; do not want to keep
12568 (not org-occur-highlights)) ; no previous matches
12569 ;; hide everything
12570 (org-overview))
12571 (while (re-search-forward regexp nil t)
12572 (when (or (not callback)
12573 (save-match-data (funcall callback)))
12574 (setq cnt (1+ cnt))
12575 (when org-highlight-sparse-tree-matches
12576 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12577 (org-show-context 'occur-tree))))
12578 (when org-remove-highlights-with-change
12579 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12580 nil 'local))
12581 (unless org-sparse-tree-open-archived-trees
12582 (org-hide-archived-subtrees (point-min) (point-max)))
12583 (run-hooks 'org-occur-hook)
12584 (if (org-called-interactively-p 'interactive)
12585 (message "%d match(es) for regexp %s" cnt regexp))
12586 cnt))
12588 (defun org-occur-next-match (&optional n reset)
12589 "Function for `next-error-function' to find sparse tree matches.
12590 N is the number of matches to move, when negative move backwards.
12591 RESET is entirely ignored - this function always goes back to the
12592 starting point when no match is found."
12593 (let* ((limit (if (< n 0) (point-min) (point-max)))
12594 (search-func (if (< n 0)
12595 'previous-single-char-property-change
12596 'next-single-char-property-change))
12597 (n (abs n))
12598 (pos (point))
12600 (catch 'exit
12601 (while (setq p1 (funcall search-func (point) 'org-type))
12602 (when (equal p1 limit)
12603 (goto-char pos)
12604 (error "No more matches"))
12605 (when (equal (get-char-property p1 'org-type) 'org-occur)
12606 (setq n (1- n))
12607 (when (= n 0)
12608 (goto-char p1)
12609 (throw 'exit (point))))
12610 (goto-char p1))
12611 (goto-char p1)
12612 (error "No more matches"))))
12614 (defun org-show-context (&optional key)
12615 "Make sure point and context are visible.
12616 How much context is shown depends upon the variables
12617 `org-show-hierarchy-above', `org-show-following-heading',
12618 `org-show-entry-below' and `org-show-siblings'."
12619 (let ((heading-p (org-at-heading-p t))
12620 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12621 (following-p (org-get-alist-option org-show-following-heading key))
12622 (entry-p (org-get-alist-option org-show-entry-below key))
12623 (siblings-p (org-get-alist-option org-show-siblings key)))
12624 (catch 'exit
12625 ;; Show heading or entry text
12626 (if (and heading-p (not entry-p))
12627 (org-flag-heading nil) ; only show the heading
12628 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12629 (org-show-hidden-entry))) ; show entire entry
12630 (when following-p
12631 ;; Show next sibling, or heading below text
12632 (save-excursion
12633 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12634 (org-flag-heading nil))))
12635 (when siblings-p (org-show-siblings))
12636 (when hierarchy-p
12637 ;; show all higher headings, possibly with siblings
12638 (save-excursion
12639 (while (and (condition-case nil
12640 (progn (org-up-heading-all 1) t)
12641 (error nil))
12642 (not (bobp)))
12643 (org-flag-heading nil)
12644 (when siblings-p (org-show-siblings))))))))
12646 (defvar org-reveal-start-hook nil
12647 "Hook run before revealing a location.")
12649 (defun org-reveal (&optional siblings)
12650 "Show current entry, hierarchy above it, and the following headline.
12651 This can be used to show a consistent set of context around locations
12652 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12653 not t for the search context.
12655 With optional argument SIBLINGS, on each level of the hierarchy all
12656 siblings are shown. This repairs the tree structure to what it would
12657 look like when opened with hierarchical calls to `org-cycle'.
12658 With double optional argument \\[universal-argument] \\[universal-argument], \
12659 go to the parent and show the
12660 entire tree."
12661 (interactive "P")
12662 (run-hooks 'org-reveal-start-hook)
12663 (let ((org-show-hierarchy-above t)
12664 (org-show-following-heading t)
12665 (org-show-siblings (if siblings t org-show-siblings)))
12666 (org-show-context nil))
12667 (when (equal siblings '(16))
12668 (save-excursion
12669 (when (org-up-heading-safe)
12670 (org-show-subtree)
12671 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12673 (defun org-highlight-new-match (beg end)
12674 "Highlight from BEG to END and mark the highlight is an occur headline."
12675 (let ((ov (make-overlay beg end)))
12676 (overlay-put ov 'face 'secondary-selection)
12677 (overlay-put ov 'org-type 'org-occur)
12678 (push ov org-occur-highlights)))
12680 (defun org-remove-occur-highlights (&optional beg end noremove)
12681 "Remove the occur highlights from the buffer.
12682 BEG and END are ignored. If NOREMOVE is nil, remove this function
12683 from the `before-change-functions' in the current buffer."
12684 (interactive)
12685 (unless org-inhibit-highlight-removal
12686 (mapc 'delete-overlay org-occur-highlights)
12687 (setq org-occur-highlights nil)
12688 (setq org-occur-parameters nil)
12689 (unless noremove
12690 (remove-hook 'before-change-functions
12691 'org-remove-occur-highlights 'local))))
12693 ;;;; Priorities
12695 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12696 "Regular expression matching the priority indicator.")
12698 (defvar org-remove-priority-next-time nil)
12700 (defun org-priority-up ()
12701 "Increase the priority of the current item."
12702 (interactive)
12703 (org-priority 'up))
12705 (defun org-priority-down ()
12706 "Decrease the priority of the current item."
12707 (interactive)
12708 (org-priority 'down))
12710 (defun org-priority (&optional action)
12711 "Change the priority of an item by ARG.
12712 ACTION can be `set', `up', `down', or a character."
12713 (interactive)
12714 (unless org-enable-priority-commands
12715 (error "Priority commands are disabled"))
12716 (setq action (or action 'set))
12717 (let (current new news have remove)
12718 (save-excursion
12719 (org-back-to-heading t)
12720 (if (looking-at org-priority-regexp)
12721 (setq current (string-to-char (match-string 2))
12722 have t))
12723 (cond
12724 ((eq action 'remove)
12725 (setq remove t new ?\ ))
12726 ((or (eq action 'set)
12727 (if (featurep 'xemacs) (characterp action) (integerp action)))
12728 (if (not (eq action 'set))
12729 (setq new action)
12730 (message "Priority %c-%c, SPC to remove: "
12731 org-highest-priority org-lowest-priority)
12732 (save-match-data
12733 (setq new (read-char-exclusive))))
12734 (if (and (= (upcase org-highest-priority) org-highest-priority)
12735 (= (upcase org-lowest-priority) org-lowest-priority))
12736 (setq new (upcase new)))
12737 (cond ((equal new ?\ ) (setq remove t))
12738 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12739 (error "Priority must be between `%c' and `%c'"
12740 org-highest-priority org-lowest-priority))))
12741 ((eq action 'up)
12742 (setq new (if have
12743 (1- current) ; normal cycling
12744 ;; last priority was empty
12745 (if (eq last-command this-command)
12746 org-lowest-priority ; wrap around empty to lowest
12747 ;; default
12748 (if org-priority-start-cycle-with-default
12749 org-default-priority
12750 (1- org-default-priority))))))
12751 ((eq action 'down)
12752 (setq new (if have
12753 (1+ current) ; normal cycling
12754 ;; last priority was empty
12755 (if (eq last-command this-command)
12756 org-highest-priority ; wrap around empty to highest
12757 ;; default
12758 (if org-priority-start-cycle-with-default
12759 org-default-priority
12760 (1+ org-default-priority))))))
12761 (t (error "Invalid action")))
12762 (if (or (< (upcase new) org-highest-priority)
12763 (> (upcase new) org-lowest-priority))
12764 (if (and (memq action '(up down))
12765 (not have) (not (eq last-command this-command)))
12766 ;; `new' is from default priority
12767 (error
12768 "The default can not be set, see `org-default-priority' why")
12769 ;; normal cycling: `new' is beyond highest/lowest priority
12770 ;; and is wrapped around to the empty priority
12771 (setq remove t)))
12772 (setq news (format "%c" new))
12773 (if have
12774 (if remove
12775 (replace-match "" t t nil 1)
12776 (replace-match news t t nil 2))
12777 (if remove
12778 (error "No priority cookie found in line")
12779 (let ((case-fold-search nil))
12780 (looking-at org-todo-line-regexp))
12781 (if (match-end 2)
12782 (progn
12783 (goto-char (match-end 2))
12784 (insert " [#" news "]"))
12785 (goto-char (match-beginning 3))
12786 (insert "[#" news "] "))))
12787 (org-preserve-lc (org-set-tags nil 'align)))
12788 (if remove
12789 (message "Priority removed")
12790 (message "Priority of current item set to %s" news))))
12792 (defun org-get-priority (s)
12793 "Find priority cookie and return priority."
12794 (if (functionp org-get-priority-function)
12795 (funcall org-get-priority-function)
12796 (save-match-data
12797 (if (not (string-match org-priority-regexp s))
12798 (* 1000 (- org-lowest-priority org-default-priority))
12799 (* 1000 (- org-lowest-priority
12800 (string-to-char (match-string 2 s))))))))
12802 ;;;; Tags
12804 (defvar org-agenda-archives-mode)
12805 (defvar org-map-continue-from nil
12806 "Position from where mapping should continue.
12807 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12809 (defvar org-scanner-tags nil
12810 "The current tag list while the tags scanner is running.")
12811 (defvar org-trust-scanner-tags nil
12812 "Should `org-get-tags-at' use the tags for the scanner.
12813 This is for internal dynamical scoping only.
12814 When this is non-nil, the function `org-get-tags-at' will return the value
12815 of `org-scanner-tags' instead of building the list by itself. This
12816 can lead to large speed-ups when the tags scanner is used in a file with
12817 many entries, and when the list of tags is retrieved, for example to
12818 obtain a list of properties. Building the tags list for each entry in such
12819 a file becomes an N^2 operation - but with this variable set, it scales
12820 as N.")
12822 (defun org-scan-tags (action matcher &optional todo-only start-level)
12823 "Scan headline tags with inheritance and produce output ACTION.
12825 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12826 or `agenda' to produce an entry list for an agenda view. It can also be
12827 a Lisp form or a function that should be called at each matched headline, in
12828 this case the return value is a list of all return values from these calls.
12830 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12831 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12832 only lines with a TODO keyword are included in the output.
12834 START-LEVEL can be a string with asterisks, reducing the scope to
12835 headlines matching this string."
12836 (require 'org-agenda)
12837 (let* ((re (concat "^"
12838 (if start-level
12839 ;; Get the correct level to match
12840 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12841 org-outline-regexp)
12842 " *\\(\\<\\("
12843 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12844 (org-re
12845 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12846 (props (list 'face 'default
12847 'done-face 'org-agenda-done
12848 'undone-face 'default
12849 'mouse-face 'highlight
12850 'org-not-done-regexp org-not-done-regexp
12851 'org-todo-regexp org-todo-regexp
12852 'org-complex-heading-regexp org-complex-heading-regexp
12853 'help-echo
12854 (format "mouse-2 or RET jump to org file %s"
12855 (abbreviate-file-name
12856 (or (buffer-file-name (buffer-base-buffer))
12857 (buffer-name (buffer-base-buffer)))))))
12858 (case-fold-search nil)
12859 (org-map-continue-from nil)
12860 lspos tags tags-list
12861 (tags-alist (list (cons 0 org-file-tags)))
12862 (llast 0) rtn rtn1 level category i txt
12863 todo marker entry priority)
12864 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12865 (setq action (list 'lambda nil action)))
12866 (save-excursion
12867 (goto-char (point-min))
12868 (when (eq action 'sparse-tree)
12869 (org-overview)
12870 (org-remove-occur-highlights))
12871 (while (re-search-forward re nil t)
12872 (setq org-map-continue-from nil)
12873 (catch :skip
12874 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12875 tags (if (match-end 4) (org-match-string-no-properties 4)))
12876 (goto-char (setq lspos (match-beginning 0)))
12877 (setq level (org-reduced-level (funcall outline-level))
12878 category (org-get-category))
12879 (setq i llast llast level)
12880 ;; remove tag lists from same and sublevels
12881 (while (>= i level)
12882 (when (setq entry (assoc i tags-alist))
12883 (setq tags-alist (delete entry tags-alist)))
12884 (setq i (1- i)))
12885 ;; add the next tags
12886 (when tags
12887 (setq tags (org-split-string tags ":")
12888 tags-alist
12889 (cons (cons level tags) tags-alist)))
12890 ;; compile tags for current headline
12891 (setq tags-list
12892 (if org-use-tag-inheritance
12893 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12894 tags)
12895 org-scanner-tags tags-list)
12896 (when org-use-tag-inheritance
12897 (setcdr (car tags-alist)
12898 (mapcar (lambda (x)
12899 (setq x (copy-sequence x))
12900 (org-add-prop-inherited x))
12901 (cdar tags-alist))))
12902 (when (and tags org-use-tag-inheritance
12903 (or (not (eq t org-use-tag-inheritance))
12904 org-tags-exclude-from-inheritance))
12905 ;; selective inheritance, remove uninherited ones
12906 (setcdr (car tags-alist)
12907 (org-remove-uninherited-tags (cdar tags-alist))))
12908 (when (and
12910 ;; eval matcher only when the todo condition is OK
12911 (and (or (not todo-only) (member todo org-not-done-keywords))
12912 (let ((case-fold-search t)) (eval matcher)))
12914 ;; Call the skipper, but return t if it does not skip,
12915 ;; so that the `and' form continues evaluating
12916 (progn
12917 (unless (eq action 'sparse-tree) (org-agenda-skip))
12920 ;; Check if timestamps are deselecting this entry
12921 (or (not todo-only)
12922 (and (member todo org-not-done-keywords)
12923 (or (not org-agenda-tags-todo-honor-ignore-options)
12924 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12926 ;; Extra check for the archive tag
12927 ;; FIXME: Does the skipper already do this????
12929 (not (member org-archive-tag tags-list))
12930 ;; we have an archive tag, should we use this anyway?
12931 (or (not org-agenda-skip-archived-trees)
12932 (and (eq action 'agenda) org-agenda-archives-mode))))
12934 ;; select this headline
12936 (cond
12937 ((eq action 'sparse-tree)
12938 (and org-highlight-sparse-tree-matches
12939 (org-get-heading) (match-end 0)
12940 (org-highlight-new-match
12941 (match-beginning 1) (match-end 1)))
12942 (org-show-context 'tags-tree))
12943 ((eq action 'agenda)
12944 (setq txt (org-agenda-format-item
12946 (concat
12947 (if (eq org-tags-match-list-sublevels 'indented)
12948 (make-string (1- level) ?.) "")
12949 (org-get-heading))
12950 category
12951 tags-list)
12952 priority (org-get-priority txt))
12953 (goto-char lspos)
12954 (setq marker (org-agenda-new-marker))
12955 (org-add-props txt props
12956 'org-marker marker 'org-hd-marker marker 'org-category category
12957 'todo-state todo
12958 'priority priority 'type "tagsmatch")
12959 (push txt rtn))
12960 ((functionp action)
12961 (setq org-map-continue-from nil)
12962 (save-excursion
12963 (setq rtn1 (funcall action))
12964 (push rtn1 rtn)))
12965 (t (error "Invalid action")))
12967 ;; if we are to skip sublevels, jump to end of subtree
12968 (unless org-tags-match-list-sublevels
12969 (org-end-of-subtree t)
12970 (backward-char 1))))
12971 ;; Get the correct position from where to continue
12972 (if org-map-continue-from
12973 (goto-char org-map-continue-from)
12974 (and (= (point) lspos) (end-of-line 1)))))
12975 (when (and (eq action 'sparse-tree)
12976 (not org-sparse-tree-open-archived-trees))
12977 (org-hide-archived-subtrees (point-min) (point-max)))
12978 (nreverse rtn)))
12980 (defun org-remove-uninherited-tags (tags)
12981 "Remove all tags that are not inherited from the list TAGS."
12982 (cond
12983 ((eq org-use-tag-inheritance t)
12984 (if org-tags-exclude-from-inheritance
12985 (org-delete-all org-tags-exclude-from-inheritance tags)
12986 tags))
12987 ((not org-use-tag-inheritance) nil)
12988 ((stringp org-use-tag-inheritance)
12989 (delq nil (mapcar
12990 (lambda (x)
12991 (if (and (string-match org-use-tag-inheritance x)
12992 (not (member x org-tags-exclude-from-inheritance)))
12993 x nil))
12994 tags)))
12995 ((listp org-use-tag-inheritance)
12996 (delq nil (mapcar
12997 (lambda (x)
12998 (if (member x org-use-tag-inheritance) x nil))
12999 tags)))))
13001 (defvar todo-only) ;; dynamically scoped
13003 (defun org-match-sparse-tree (&optional todo-only match)
13004 "Create a sparse tree according to tags string MATCH.
13005 MATCH can contain positive and negative selection of tags, like
13006 \"+WORK+URGENT-WITHBOSS\".
13007 If optional argument TODO-ONLY is non-nil, only select lines that are
13008 also TODO lines."
13009 (interactive "P")
13010 (org-prepare-agenda-buffers (list (current-buffer)))
13011 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13013 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13015 (defvar org-cached-props nil)
13016 (defun org-cached-entry-get (pom property)
13017 (if (or (eq t org-use-property-inheritance)
13018 (and (stringp org-use-property-inheritance)
13019 (string-match org-use-property-inheritance property))
13020 (and (listp org-use-property-inheritance)
13021 (member property org-use-property-inheritance)))
13022 ;; Caching is not possible, check it directly
13023 (org-entry-get pom property 'inherit)
13024 ;; Get all properties, so that we can do complicated checks easily
13025 (cdr (assoc property (or org-cached-props
13026 (setq org-cached-props
13027 (org-entry-properties pom)))))))
13029 (defun org-global-tags-completion-table (&optional files)
13030 "Return the list of all tags in all agenda buffer/files.
13031 Optional FILES argument is a list of files to which can be used
13032 instead of the agenda files."
13033 (save-excursion
13034 (org-uniquify
13035 (delq nil
13036 (apply 'append
13037 (mapcar
13038 (lambda (file)
13039 (set-buffer (find-file-noselect file))
13040 (append (org-get-buffer-tags)
13041 (mapcar (lambda (x) (if (stringp (car-safe x))
13042 (list (car-safe x)) nil))
13043 org-tag-alist)))
13044 (if (and files (car files))
13045 files
13046 (org-agenda-files))))))))
13048 (defun org-make-tags-matcher (match)
13049 "Create the TAGS/TODO matcher form for the selection string MATCH."
13050 ;; todo-only is scoped dynamically into this function, and the function
13051 ;; may change it if the matcher asks for it.
13052 (unless match
13053 ;; Get a new match request, with completion
13054 (let ((org-last-tags-completion-table
13055 (org-global-tags-completion-table)))
13056 (setq match (org-completing-read-no-i
13057 "Match: " 'org-tags-completion-function nil nil nil
13058 'org-tags-history))))
13060 ;; Parse the string and create a lisp form
13061 (let ((match0 match)
13062 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13063 minus tag mm
13064 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13065 orterms term orlist re-p str-p level-p level-op time-p
13066 prop-p pn pv po gv rest)
13067 (if (string-match "/+" match)
13068 ;; match contains also a todo-matching request
13069 (progn
13070 (setq tagsmatch (substring match 0 (match-beginning 0))
13071 todomatch (substring match (match-end 0)))
13072 (if (string-match "^!" todomatch)
13073 (setq todo-only t todomatch (substring todomatch 1)))
13074 (if (string-match "^\\s-*$" todomatch)
13075 (setq todomatch nil)))
13076 ;; only matching tags
13077 (setq tagsmatch match todomatch nil))
13079 ;; Make the tags matcher
13080 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13081 (setq tagsmatcher t)
13082 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13083 (while (setq term (pop orterms))
13084 (while (and (equal (substring term -1) "\\") orterms)
13085 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13086 (while (string-match re term)
13087 (setq rest (substring term (match-end 0))
13088 minus (and (match-end 1)
13089 (equal (match-string 1 term) "-"))
13090 tag (save-match-data (replace-regexp-in-string
13091 "\\\\-" "-"
13092 (match-string 2 term)))
13093 re-p (equal (string-to-char tag) ?{)
13094 level-p (match-end 4)
13095 prop-p (match-end 5)
13096 mm (cond
13097 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13098 (level-p
13099 (setq level-op (org-op-to-function (match-string 3 term)))
13100 `(,level-op level ,(string-to-number
13101 (match-string 4 term))))
13102 (prop-p
13103 (setq pn (match-string 5 term)
13104 po (match-string 6 term)
13105 pv (match-string 7 term)
13106 re-p (equal (string-to-char pv) ?{)
13107 str-p (equal (string-to-char pv) ?\")
13108 time-p (save-match-data
13109 (string-match "^\"[[<].*[]>]\"$" pv))
13110 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13111 (if time-p (setq pv (org-matcher-time pv)))
13112 (setq po (org-op-to-function po (if time-p 'time str-p)))
13113 (cond
13114 ((equal pn "CATEGORY")
13115 (setq gv '(get-text-property (point) 'org-category)))
13116 ((equal pn "TODO")
13117 (setq gv 'todo))
13119 (setq gv `(org-cached-entry-get nil ,pn))))
13120 (if re-p
13121 (if (eq po 'org<>)
13122 `(not (string-match ,pv (or ,gv "")))
13123 `(string-match ,pv (or ,gv "")))
13124 (if str-p
13125 `(,po (or ,gv "") ,pv)
13126 `(,po (string-to-number (or ,gv ""))
13127 ,(string-to-number pv) ))))
13128 (t `(member ,tag tags-list)))
13129 mm (if minus (list 'not mm) mm)
13130 term rest)
13131 (push mm tagsmatcher))
13132 (push (if (> (length tagsmatcher) 1)
13133 (cons 'and tagsmatcher)
13134 (car tagsmatcher))
13135 orlist)
13136 (setq tagsmatcher nil))
13137 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13138 (setq tagsmatcher
13139 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13140 ;; Make the todo matcher
13141 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13142 (setq todomatcher t)
13143 (setq orterms (org-split-string todomatch "|") orlist nil)
13144 (while (setq term (pop orterms))
13145 (while (string-match re term)
13146 (setq minus (and (match-end 1)
13147 (equal (match-string 1 term) "-"))
13148 kwd (match-string 2 term)
13149 re-p (equal (string-to-char kwd) ?{)
13150 term (substring term (match-end 0))
13151 mm (if re-p
13152 `(string-match ,(substring kwd 1 -1) todo)
13153 (list 'equal 'todo kwd))
13154 mm (if minus (list 'not mm) mm))
13155 (push mm todomatcher))
13156 (push (if (> (length todomatcher) 1)
13157 (cons 'and todomatcher)
13158 (car todomatcher))
13159 orlist)
13160 (setq todomatcher nil))
13161 (setq todomatcher (if (> (length orlist) 1)
13162 (cons 'or orlist) (car orlist))))
13164 ;; Return the string and lisp forms of the matcher
13165 (setq matcher (if todomatcher
13166 (list 'and tagsmatcher todomatcher)
13167 tagsmatcher))
13168 (cons match0 matcher)))
13170 (defun org-op-to-function (op &optional stringp)
13171 "Turn an operator into the appropriate function."
13172 (setq op
13173 (cond
13174 ((equal op "<" ) '(< string< org-time<))
13175 ((equal op ">" ) '(> org-string> org-time>))
13176 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13177 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13178 ((member op '("=" "==")) '(= string= org-time=))
13179 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13180 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13182 (defun org<> (a b) (not (= a b)))
13183 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13184 (defun org-string>= (a b) (not (string< a b)))
13185 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13186 (defun org-string<> (a b) (not (string= a b)))
13187 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13188 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13189 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13190 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13191 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13192 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13193 (defun org-2ft (s)
13194 "Convert S to a floating point time.
13195 If S is already a number, just return it. If it is a string, parse
13196 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13197 (cond
13198 ((numberp s) s)
13199 ((stringp s)
13200 (condition-case nil
13201 (float-time (apply 'encode-time (org-parse-time-string s)))
13202 (error 0.)))
13203 (t 0.)))
13205 (defun org-time-today ()
13206 "Time in seconds today at 0:00.
13207 Returns the float number of seconds since the beginning of the
13208 epoch to the beginning of today (00:00)."
13209 (float-time (apply 'encode-time
13210 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13212 (defun org-matcher-time (s)
13213 "Interpret a time comparison value."
13214 (save-match-data
13215 (cond
13216 ((string= s "<now>") (float-time))
13217 ((string= s "<today>") (org-time-today))
13218 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13219 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13220 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13221 (+ (org-time-today)
13222 (* (string-to-number (match-string 1 s))
13223 (cdr (assoc (match-string 2 s)
13224 '(("d" . 86400.0) ("w" . 604800.0)
13225 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13226 (t (org-2ft s)))))
13228 (defun org-match-any-p (re list)
13229 "Does re match any element of list?"
13230 (setq list (mapcar (lambda (x) (string-match re x)) list))
13231 (delq nil list))
13233 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13234 (defvar org-tags-overlay (make-overlay 1 1))
13235 (org-detach-overlay org-tags-overlay)
13237 (defun org-get-local-tags-at (&optional pos)
13238 "Get a list of tags defined in the current headline."
13239 (org-get-tags-at pos 'local))
13241 (defun org-get-local-tags ()
13242 "Get a list of tags defined in the current headline."
13243 (org-get-tags-at nil 'local))
13245 (defun org-get-tags-at (&optional pos local)
13246 "Get a list of all headline tags applicable at POS.
13247 POS defaults to point. If tags are inherited, the list contains
13248 the targets in the same sequence as the headlines appear, i.e.
13249 the tags of the current headline come last.
13250 When LOCAL is non-nil, only return tags from the current headline,
13251 ignore inherited ones."
13252 (interactive)
13253 (if (and org-trust-scanner-tags
13254 (or (not pos) (equal pos (point)))
13255 (not local))
13256 org-scanner-tags
13257 (let (tags ltags lastpos parent)
13258 (save-excursion
13259 (save-restriction
13260 (widen)
13261 (goto-char (or pos (point)))
13262 (save-match-data
13263 (catch 'done
13264 (condition-case nil
13265 (progn
13266 (org-back-to-heading t)
13267 (while (not (equal lastpos (point)))
13268 (setq lastpos (point))
13269 (when (looking-at
13270 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13271 (setq ltags (org-split-string
13272 (org-match-string-no-properties 1) ":"))
13273 (when parent
13274 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13275 (setq tags (append
13276 (if parent
13277 (org-remove-uninherited-tags ltags)
13278 ltags)
13279 tags)))
13280 (or org-use-tag-inheritance (throw 'done t))
13281 (if local (throw 'done t))
13282 (or (org-up-heading-safe) (error nil))
13283 (setq parent t)))
13284 (error nil)))))
13285 (if local
13286 tags
13287 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13289 (defun org-add-prop-inherited (s)
13290 (add-text-properties 0 (length s) '(inherited t) s)
13293 (defun org-toggle-tag (tag &optional onoff)
13294 "Toggle the tag TAG for the current line.
13295 If ONOFF is `on' or `off', don't toggle but set to this state."
13296 (let (res current)
13297 (save-excursion
13298 (org-back-to-heading t)
13299 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13300 (point-at-eol) t)
13301 (progn
13302 (setq current (match-string 1))
13303 (replace-match ""))
13304 (setq current ""))
13305 (setq current (nreverse (org-split-string current ":")))
13306 (cond
13307 ((eq onoff 'on)
13308 (setq res t)
13309 (or (member tag current) (push tag current)))
13310 ((eq onoff 'off)
13311 (or (not (member tag current)) (setq current (delete tag current))))
13312 (t (if (member tag current)
13313 (setq current (delete tag current))
13314 (setq res t)
13315 (push tag current))))
13316 (end-of-line 1)
13317 (if current
13318 (progn
13319 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13320 (org-set-tags nil t))
13321 (delete-horizontal-space))
13322 (run-hooks 'org-after-tags-change-hook))
13323 res))
13325 (defun org-align-tags-here (to-col)
13326 ;; Assumes that this is a headline
13327 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13328 (beginning-of-line 1)
13329 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13330 (< pos (match-beginning 2)))
13331 (progn
13332 (setq tags-l (- (match-end 2) (match-beginning 2)))
13333 (goto-char (match-beginning 1))
13334 (insert " ")
13335 (delete-region (point) (1+ (match-beginning 2)))
13336 (setq ncol (max (current-column)
13337 (1+ col)
13338 (if (> to-col 0)
13339 to-col
13340 (- (abs to-col) tags-l))))
13341 (setq p (point))
13342 (insert (make-string (- ncol (current-column)) ?\ ))
13343 (setq ncol (current-column))
13344 (when indent-tabs-mode (tabify p (point-at-eol)))
13345 (org-move-to-column (min ncol col) t))
13346 (goto-char pos))))
13348 (defun org-set-tags-command (&optional arg just-align)
13349 "Call the set-tags command for the current entry."
13350 (interactive "P")
13351 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13352 (org-set-tags arg just-align)
13353 (save-excursion
13354 (org-back-to-heading t)
13355 (org-set-tags arg just-align))))
13357 (defun org-set-tags-to (data)
13358 "Set the tags of the current entry to DATA, replacing the current tags.
13359 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13360 If DATA is nil or the empty string, any tags will be removed."
13361 (interactive "sTags: ")
13362 (setq data
13363 (cond
13364 ((eq data nil) "")
13365 ((equal data "") "")
13366 ((stringp data)
13367 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13368 ":"))
13369 ((listp data)
13370 (concat ":" (mapconcat 'identity data ":") ":"))
13371 (t nil)))
13372 (when data
13373 (save-excursion
13374 (org-back-to-heading t)
13375 (when (looking-at org-complex-heading-regexp)
13376 (if (match-end 5)
13377 (progn
13378 (goto-char (match-beginning 5))
13379 (insert data)
13380 (delete-region (point) (point-at-eol))
13381 (org-set-tags nil 'align))
13382 (goto-char (point-at-eol))
13383 (insert " " data)
13384 (org-set-tags nil 'align)))
13385 (beginning-of-line 1)
13386 (if (looking-at ".*?\\([ \t]+\\)$")
13387 (delete-region (match-beginning 1) (match-end 1))))))
13389 (defun org-align-all-tags ()
13390 "Align the tags i all headings."
13391 (interactive)
13392 (save-excursion
13393 (or (ignore-errors (org-back-to-heading t))
13394 (outline-next-heading))
13395 (if (org-at-heading-p)
13396 (org-set-tags t)
13397 (message "No headings"))))
13399 (defvar org-indent-indentation-per-level)
13400 (defun org-set-tags (&optional arg just-align)
13401 "Set the tags for the current headline.
13402 With prefix ARG, realign all tags in headings in the current buffer."
13403 (interactive "P")
13404 (let* ((re org-outline-regexp-bol)
13405 (current (unless arg (org-get-tags-string)))
13406 (col (current-column))
13407 (org-setting-tags t)
13408 table current-tags inherited-tags ; computed below when needed
13409 tags p0 c0 c1 rpl di tc level)
13410 (if arg
13411 (save-excursion
13412 (goto-char (point-min))
13413 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13414 (while (re-search-forward re nil t)
13415 (org-set-tags nil t)
13416 (end-of-line 1)))
13417 (message "All tags realigned to column %d" org-tags-column))
13418 (if just-align
13419 (setq tags current)
13420 ;; Get a new set of tags from the user
13421 (save-excursion
13422 (setq table (append org-tag-persistent-alist
13423 (or org-tag-alist (org-get-buffer-tags))
13424 (and
13425 org-complete-tags-always-offer-all-agenda-tags
13426 (org-global-tags-completion-table
13427 (org-agenda-files))))
13428 org-last-tags-completion-table table
13429 current-tags (org-split-string current ":")
13430 inherited-tags (nreverse
13431 (nthcdr (length current-tags)
13432 (nreverse (org-get-tags-at))))
13433 tags
13434 (if (or (eq t org-use-fast-tag-selection)
13435 (and org-use-fast-tag-selection
13436 (delq nil (mapcar 'cdr table))))
13437 (org-fast-tag-selection
13438 current-tags inherited-tags table
13439 (if org-fast-tag-selection-include-todo
13440 org-todo-key-alist))
13441 (let ((org-add-colon-after-tag-completion t))
13442 (org-trim
13443 (org-icompleting-read "Tags: "
13444 'org-tags-completion-function
13445 nil nil current 'org-tags-history))))))
13446 (while (string-match "[-+&]+" tags)
13447 ;; No boolean logic, just a list
13448 (setq tags (replace-match ":" t t tags))))
13450 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13452 (if org-tags-sort-function
13453 (setq tags (mapconcat 'identity
13454 (sort (org-split-string
13455 tags (org-re "[^[:alnum:]_@#%]+"))
13456 org-tags-sort-function) ":")))
13458 (if (string-match "\\`[\t ]*\\'" tags)
13459 (setq tags "")
13460 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13461 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13463 ;; Insert new tags at the correct column
13464 (beginning-of-line 1)
13465 (setq level (or (and (looking-at org-outline-regexp)
13466 (- (match-end 0) (point) 1))
13468 (cond
13469 ((and (equal current "") (equal tags "")))
13470 ((re-search-forward
13471 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13472 (point-at-eol) t)
13473 (if (equal tags "")
13474 (setq rpl "")
13475 (goto-char (match-beginning 0))
13476 (setq c0 (current-column)
13477 ;; compute offset for the case of org-indent-mode active
13478 di (if org-indent-mode
13479 (* (1- org-indent-indentation-per-level) (1- level))
13481 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13482 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13483 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13484 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13485 (replace-match rpl t t)
13486 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13487 tags)
13488 (t (error "Tags alignment failed")))
13489 (org-move-to-column col)
13490 (unless just-align
13491 (run-hooks 'org-after-tags-change-hook)))))
13493 (defun org-change-tag-in-region (beg end tag off)
13494 "Add or remove TAG for each entry in the region.
13495 This works in the agenda, and also in an org-mode buffer."
13496 (interactive
13497 (list (region-beginning) (region-end)
13498 (let ((org-last-tags-completion-table
13499 (if (eq major-mode 'org-mode)
13500 (org-get-buffer-tags)
13501 (org-global-tags-completion-table))))
13502 (org-icompleting-read
13503 "Tag: " 'org-tags-completion-function nil nil nil
13504 'org-tags-history))
13505 (progn
13506 (message "[s]et or [r]emove? ")
13507 (equal (read-char-exclusive) ?r))))
13508 (if (fboundp 'deactivate-mark) (deactivate-mark))
13509 (let ((agendap (equal major-mode 'org-agenda-mode))
13510 l1 l2 m buf pos newhead (cnt 0))
13511 (goto-char end)
13512 (setq l2 (1- (org-current-line)))
13513 (goto-char beg)
13514 (setq l1 (org-current-line))
13515 (loop for l from l1 to l2 do
13516 (org-goto-line l)
13517 (setq m (get-text-property (point) 'org-hd-marker))
13518 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13519 (and agendap m))
13520 (setq buf (if agendap (marker-buffer m) (current-buffer))
13521 pos (if agendap m (point)))
13522 (with-current-buffer buf
13523 (save-excursion
13524 (save-restriction
13525 (goto-char pos)
13526 (setq cnt (1+ cnt))
13527 (org-toggle-tag tag (if off 'off 'on))
13528 (setq newhead (org-get-heading)))))
13529 (and agendap (org-agenda-change-all-lines newhead m))))
13530 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13532 (defun org-tags-completion-function (string predicate &optional flag)
13533 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13534 (confirm (lambda (x) (stringp (car x)))))
13535 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13536 (setq s1 (match-string 1 string)
13537 s2 (match-string 2 string))
13538 (setq s1 "" s2 string))
13539 (cond
13540 ((eq flag nil)
13541 ;; try completion
13542 (setq rtn (try-completion s2 ctable confirm))
13543 (if (stringp rtn)
13544 (setq rtn
13545 (concat s1 s2 (substring rtn (length s2))
13546 (if (and org-add-colon-after-tag-completion
13547 (assoc rtn ctable))
13548 ":" ""))))
13549 rtn)
13550 ((eq flag t)
13551 ;; all-completions
13552 (all-completions s2 ctable confirm)
13554 ((eq flag 'lambda)
13555 ;; exact match?
13556 (assoc s2 ctable)))
13559 (defun org-fast-tag-insert (kwd tags face &optional end)
13560 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13561 (insert (format "%-12s" (concat kwd ":"))
13562 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13563 (or end "")))
13565 (defun org-fast-tag-show-exit (flag)
13566 (save-excursion
13567 (org-goto-line 3)
13568 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13569 (replace-match ""))
13570 (when flag
13571 (end-of-line 1)
13572 (org-move-to-column (- (window-width) 19) t)
13573 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13575 (defun org-set-current-tags-overlay (current prefix)
13576 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13577 (if (featurep 'xemacs)
13578 (org-overlay-display org-tags-overlay (concat prefix s)
13579 'secondary-selection)
13580 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13581 (org-overlay-display org-tags-overlay (concat prefix s)))))
13583 (defvar org-last-tag-selection-key nil)
13584 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13585 "Fast tag selection with single keys.
13586 CURRENT is the current list of tags in the headline, INHERITED is the
13587 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13588 possibly with grouping information. TODO-TABLE is a similar table with
13589 TODO keywords, should these have keys assigned to them.
13590 If the keys are nil, a-z are automatically assigned.
13591 Returns the new tags string, or nil to not change the current settings."
13592 (let* ((fulltable (append table todo-table))
13593 (maxlen (apply 'max (mapcar
13594 (lambda (x)
13595 (if (stringp (car x)) (string-width (car x)) 0))
13596 fulltable)))
13597 (buf (current-buffer))
13598 (expert (eq org-fast-tag-selection-single-key 'expert))
13599 (buffer-tags nil)
13600 (fwidth (+ maxlen 3 1 3))
13601 (ncol (/ (- (window-width) 4) fwidth))
13602 (i-face 'org-done)
13603 (c-face 'org-todo)
13604 tg cnt e c char c1 c2 ntable tbl rtn
13605 ov-start ov-end ov-prefix
13606 (exit-after-next org-fast-tag-selection-single-key)
13607 (done-keywords org-done-keywords)
13608 groups ingroup)
13609 (save-excursion
13610 (beginning-of-line 1)
13611 (if (looking-at
13612 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13613 (setq ov-start (match-beginning 1)
13614 ov-end (match-end 1)
13615 ov-prefix "")
13616 (setq ov-start (1- (point-at-eol))
13617 ov-end (1+ ov-start))
13618 (skip-chars-forward "^\n\r")
13619 (setq ov-prefix
13620 (concat
13621 (buffer-substring (1- (point)) (point))
13622 (if (> (current-column) org-tags-column)
13624 (make-string (- org-tags-column (current-column)) ?\ ))))))
13625 (move-overlay org-tags-overlay ov-start ov-end)
13626 (save-window-excursion
13627 (if expert
13628 (set-buffer (get-buffer-create " *Org tags*"))
13629 (delete-other-windows)
13630 (split-window-vertically)
13631 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13632 (erase-buffer)
13633 (org-set-local 'org-done-keywords done-keywords)
13634 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13635 (org-fast-tag-insert "Current" current c-face "\n\n")
13636 (org-fast-tag-show-exit exit-after-next)
13637 (org-set-current-tags-overlay current ov-prefix)
13638 (setq tbl fulltable char ?a cnt 0)
13639 (while (setq e (pop tbl))
13640 (cond
13641 ((equal (car e) :startgroup)
13642 (push '() groups) (setq ingroup t)
13643 (when (not (= cnt 0))
13644 (setq cnt 0)
13645 (insert "\n"))
13646 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13647 ((equal (car e) :endgroup)
13648 (setq ingroup nil cnt 0)
13649 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13650 ((equal e '(:newline))
13651 (when (not (= cnt 0))
13652 (setq cnt 0)
13653 (insert "\n")
13654 (setq e (car tbl))
13655 (while (equal (car tbl) '(:newline))
13656 (insert "\n")
13657 (setq tbl (cdr tbl)))))
13659 (setq tg (copy-sequence (car e)) c2 nil)
13660 (if (cdr e)
13661 (setq c (cdr e))
13662 ;; automatically assign a character.
13663 (setq c1 (string-to-char
13664 (downcase (substring
13665 tg (if (= (string-to-char tg) ?@) 1 0)))))
13666 (if (or (rassoc c1 ntable) (rassoc c1 table))
13667 (while (or (rassoc char ntable) (rassoc char table))
13668 (setq char (1+ char)))
13669 (setq c2 c1))
13670 (setq c (or c2 char)))
13671 (if ingroup (push tg (car groups)))
13672 (setq tg (org-add-props tg nil 'face
13673 (cond
13674 ((not (assoc tg table))
13675 (org-get-todo-face tg))
13676 ((member tg current) c-face)
13677 ((member tg inherited) i-face)
13678 (t nil))))
13679 (if (and (= cnt 0) (not ingroup)) (insert " "))
13680 (insert "[" c "] " tg (make-string
13681 (- fwidth 4 (length tg)) ?\ ))
13682 (push (cons tg c) ntable)
13683 (when (= (setq cnt (1+ cnt)) ncol)
13684 (insert "\n")
13685 (if ingroup (insert " "))
13686 (setq cnt 0)))))
13687 (setq ntable (nreverse ntable))
13688 (insert "\n")
13689 (goto-char (point-min))
13690 (if (not expert) (org-fit-window-to-buffer))
13691 (setq rtn
13692 (catch 'exit
13693 (while t
13694 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13695 (if (not groups) "no " "")
13696 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13697 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13698 (setq org-last-tag-selection-key c)
13699 (cond
13700 ((= c ?\r) (throw 'exit t))
13701 ((= c ?!)
13702 (setq groups (not groups))
13703 (goto-char (point-min))
13704 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13705 ((= c ?\C-c)
13706 (if (not expert)
13707 (org-fast-tag-show-exit
13708 (setq exit-after-next (not exit-after-next)))
13709 (setq expert nil)
13710 (delete-other-windows)
13711 (set-window-buffer (split-window-vertically) " *Org tags*")
13712 (org-switch-to-buffer-other-window " *Org tags*")
13713 (org-fit-window-to-buffer)))
13714 ((or (= c ?\C-g)
13715 (and (= c ?q) (not (rassoc c ntable))))
13716 (org-detach-overlay org-tags-overlay)
13717 (setq quit-flag t))
13718 ((= c ?\ )
13719 (setq current nil)
13720 (if exit-after-next (setq exit-after-next 'now)))
13721 ((= c ?\t)
13722 (condition-case nil
13723 (setq tg (org-icompleting-read
13724 "Tag: "
13725 (or buffer-tags
13726 (with-current-buffer buf
13727 (org-get-buffer-tags)))))
13728 (quit (setq tg "")))
13729 (when (string-match "\\S-" tg)
13730 (add-to-list 'buffer-tags (list tg))
13731 (if (member tg current)
13732 (setq current (delete tg current))
13733 (push tg current)))
13734 (if exit-after-next (setq exit-after-next 'now)))
13735 ((setq e (rassoc c todo-table) tg (car e))
13736 (with-current-buffer buf
13737 (save-excursion (org-todo tg)))
13738 (if exit-after-next (setq exit-after-next 'now)))
13739 ((setq e (rassoc c ntable) tg (car e))
13740 (if (member tg current)
13741 (setq current (delete tg current))
13742 (loop for g in groups do
13743 (if (member tg g)
13744 (mapc (lambda (x)
13745 (setq current (delete x current)))
13746 g)))
13747 (push tg current))
13748 (if exit-after-next (setq exit-after-next 'now))))
13750 ;; Create a sorted list
13751 (setq current
13752 (sort current
13753 (lambda (a b)
13754 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13755 (if (eq exit-after-next 'now) (throw 'exit t))
13756 (goto-char (point-min))
13757 (beginning-of-line 2)
13758 (delete-region (point) (point-at-eol))
13759 (org-fast-tag-insert "Current" current c-face)
13760 (org-set-current-tags-overlay current ov-prefix)
13761 (while (re-search-forward
13762 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13763 (setq tg (match-string 1))
13764 (add-text-properties
13765 (match-beginning 1) (match-end 1)
13766 (list 'face
13767 (cond
13768 ((member tg current) c-face)
13769 ((member tg inherited) i-face)
13770 (t (get-text-property (match-beginning 1) 'face))))))
13771 (goto-char (point-min)))))
13772 (org-detach-overlay org-tags-overlay)
13773 (if rtn
13774 (mapconcat 'identity current ":")
13775 nil))))
13777 (defun org-get-tags-string ()
13778 "Get the TAGS string in the current headline."
13779 (unless (org-at-heading-p t)
13780 (error "Not on a heading"))
13781 (save-excursion
13782 (beginning-of-line 1)
13783 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13784 (org-match-string-no-properties 1)
13785 "")))
13787 (defun org-get-tags ()
13788 "Get the list of tags specified in the current headline."
13789 (org-split-string (org-get-tags-string) ":"))
13791 (defun org-get-buffer-tags ()
13792 "Get a table of all tags used in the buffer, for completion."
13793 (let (tags)
13794 (save-excursion
13795 (goto-char (point-min))
13796 (while (re-search-forward
13797 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13798 (when (equal (char-after (point-at-bol 0)) ?*)
13799 (mapc (lambda (x) (add-to-list 'tags x))
13800 (org-split-string (org-match-string-no-properties 1) ":")))))
13801 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13802 (mapcar 'list tags)))
13804 ;;;; The mapping API
13806 ;;;###autoload
13807 (defun org-map-entries (func &optional match scope &rest skip)
13808 "Call FUNC at each headline selected by MATCH in SCOPE.
13810 FUNC is a function or a lisp form. The function will be called without
13811 arguments, with the cursor positioned at the beginning of the headline.
13812 The return values of all calls to the function will be collected and
13813 returned as a list.
13815 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13816 does not need to preserve point. After evaluation, the cursor will be
13817 moved to the end of the line (presumably of the headline of the
13818 processed entry) and search continues from there. Under some
13819 circumstances, this may not produce the wanted results. For example,
13820 if you have removed (e.g. archived) the current (sub)tree it could
13821 mean that the next entry will be skipped entirely. In such cases, you
13822 can specify the position from where search should continue by making
13823 FUNC set the variable `org-map-continue-from' to the desired buffer
13824 position.
13826 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13827 Only headlines that are matched by this query will be considered during
13828 the iteration. When MATCH is nil or t, all headlines will be
13829 visited by the iteration.
13831 SCOPE determines the scope of this command. It can be any of:
13833 nil The current buffer, respecting the restriction if any
13834 tree The subtree started with the entry at point
13835 region The entries within the active region, if any
13836 region-start-level
13837 The entries within the active region, but only those at
13838 the same level than the first one.
13839 file The current buffer, without restriction
13840 file-with-archives
13841 The current buffer, and any archives associated with it
13842 agenda All agenda files
13843 agenda-with-archives
13844 All agenda files with any archive files associated with them
13845 \(file1 file2 ...)
13846 If this is a list, all files in the list will be scanned
13848 The remaining args are treated as settings for the skipping facilities of
13849 the scanner. The following items can be given here:
13851 archive skip trees with the archive tag.
13852 comment skip trees with the COMMENT keyword
13853 function or Emacs Lisp form:
13854 will be used as value for `org-agenda-skip-function', so whenever
13855 the function returns t, FUNC will not be called for that
13856 entry and search will continue from the point where the
13857 function leaves it.
13859 If your function needs to retrieve the tags including inherited tags
13860 at the *current* entry, you can use the value of the variable
13861 `org-scanner-tags' which will be much faster than getting the value
13862 with `org-get-tags-at'. If your function gets properties with
13863 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13864 to t around the call to `org-entry-properties' to get the same speedup.
13865 Note that if your function moves around to retrieve tags and properties at
13866 a *different* entry, you cannot use these techniques."
13867 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13868 (not (org-region-active-p)))
13869 (let* ((org-agenda-archives-mode nil) ; just to make sure
13870 (org-agenda-skip-archived-trees (memq 'archive skip))
13871 (org-agenda-skip-comment-trees (memq 'comment skip))
13872 (org-agenda-skip-function
13873 (car (org-delete-all '(comment archive) skip)))
13874 (org-tags-match-list-sublevels t)
13875 (start-level (eq scope 'region-start-level))
13876 matcher file res
13877 org-todo-keywords-for-agenda
13878 org-done-keywords-for-agenda
13879 org-todo-keyword-alist-for-agenda
13880 org-drawers-for-agenda
13881 org-tag-alist-for-agenda)
13883 (cond
13884 ((eq match t) (setq matcher t))
13885 ((eq match nil) (setq matcher t))
13886 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13888 (save-excursion
13889 (save-restriction
13890 (cond ((eq scope 'tree)
13891 (org-back-to-heading t)
13892 (org-narrow-to-subtree)
13893 (setq scope nil))
13894 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13895 (org-region-active-p))
13896 ;; If needed, set start-level to a string like "2"
13897 (when start-level
13898 (save-excursion
13899 (goto-char (region-beginning))
13900 (unless (org-at-heading-p) (outline-next-heading))
13901 (setq start-level (org-current-level))))
13902 (narrow-to-region (region-beginning)
13903 (save-excursion
13904 (goto-char (region-end))
13905 (unless (and (bolp) (org-at-heading-p))
13906 (outline-next-heading))
13907 (point)))
13908 (setq scope nil)))
13910 (if (not scope)
13911 (progn
13912 (org-prepare-agenda-buffers
13913 (list (buffer-file-name (current-buffer))))
13914 (setq res (org-scan-tags func matcher nil start-level)))
13915 ;; Get the right scope
13916 (cond
13917 ((and scope (listp scope) (symbolp (car scope)))
13918 (setq scope (eval scope)))
13919 ((eq scope 'agenda)
13920 (setq scope (org-agenda-files t)))
13921 ((eq scope 'agenda-with-archives)
13922 (setq scope (org-agenda-files t))
13923 (setq scope (org-add-archive-files scope)))
13924 ((eq scope 'file)
13925 (setq scope (list (buffer-file-name))))
13926 ((eq scope 'file-with-archives)
13927 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13928 (org-prepare-agenda-buffers scope)
13929 (while (setq file (pop scope))
13930 (with-current-buffer (org-find-base-buffer-visiting file)
13931 (save-excursion
13932 (save-restriction
13933 (widen)
13934 (goto-char (point-min))
13935 (setq res (append res (org-scan-tags func matcher))))))))))
13936 res)))
13938 ;;;; Properties
13940 ;;; Setting and retrieving properties
13942 (defconst org-special-properties
13943 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13944 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13945 "The special properties valid in Org-mode.
13947 These are properties that are not defined in the property drawer,
13948 but in some other way.")
13950 (defconst org-default-properties
13951 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13952 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13953 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13954 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13955 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13956 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13957 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13958 "Some properties that are used by Org-mode for various purposes.
13959 Being in this list makes sure that they are offered for completion.")
13961 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13962 "Regular expression matching the first line of a property drawer.")
13964 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13965 "Regular expression matching the last line of a property drawer.")
13967 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13968 "Regular expression matching the first line of a property drawer.")
13970 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13971 "Regular expression matching the first line of a property drawer.")
13973 (defconst org-property-drawer-re
13974 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13975 org-property-end-re "\\)\n?")
13976 "Matches an entire property drawer.")
13978 (defconst org-clock-drawer-re
13979 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13980 org-property-end-re "\\)\n?")
13981 "Matches an entire clock drawer.")
13983 (defsubst org-re-property (property)
13984 "Return a regexp matching PROPERTY.
13985 Match group 1 will be set to the value "
13986 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13988 (defun org-property-action ()
13989 "Do an action on properties."
13990 (interactive)
13991 (let (c)
13992 (org-at-property-p)
13993 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13994 (setq c (read-char-exclusive))
13995 (cond
13996 ((equal c ?s)
13997 (call-interactively 'org-set-property))
13998 ((equal c ?d)
13999 (call-interactively 'org-delete-property))
14000 ((equal c ?D)
14001 (call-interactively 'org-delete-property-globally))
14002 ((equal c ?c)
14003 (call-interactively 'org-compute-property-at-point))
14004 (t (error "No such property action %c" c)))))
14006 (defun org-set-effort (&optional value)
14007 "Set the effort property of the current entry.
14008 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14009 allowed value."
14010 (interactive "P")
14011 (if (equal value 0) (setq value 10))
14012 (let* ((completion-ignore-case t)
14013 (prop org-effort-property)
14014 (cur (org-entry-get nil prop))
14015 (allowed (org-property-get-allowed-values nil prop 'table))
14016 (existing (mapcar 'list (org-property-values prop)))
14018 (val (cond
14019 ((stringp value) value)
14020 ((and allowed (integerp value))
14021 (or (car (nth (1- value) allowed))
14022 (car (org-last allowed))))
14023 (allowed
14024 (message "Select 1-9,0, [RET%s]: %s"
14025 (if cur (concat "=" cur) "")
14026 (mapconcat 'car allowed " "))
14027 (setq rpl (read-char-exclusive))
14028 (if (equal rpl ?\r)
14030 (setq rpl (- rpl ?0))
14031 (if (equal rpl 0) (setq rpl 10))
14032 (if (and (> rpl 0) (<= rpl (length allowed)))
14033 (car (nth (1- rpl) allowed))
14034 (org-completing-read "Effort: " allowed nil))))
14036 (let (org-completion-use-ido org-completion-use-iswitchb)
14037 (org-completing-read
14038 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14039 (concat "[" cur "]") "")
14040 ": ")
14041 existing nil nil "" nil cur))))))
14042 (unless (equal (org-entry-get nil prop) val)
14043 (org-entry-put nil prop val))
14044 (message "%s is now %s" prop val)))
14046 (defun org-at-property-p ()
14047 "Is cursor inside a property drawer?"
14048 (save-excursion
14049 (beginning-of-line 1)
14050 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14051 (save-match-data ;; Used by calling procedures
14052 (let ((p (point))
14053 (range (unless (org-before-first-heading-p)
14054 (org-get-property-block))))
14055 (and range (<= (car range) p) (< p (cdr range))))))))
14057 (defun org-get-property-block (&optional beg end force)
14058 "Return the (beg . end) range of the body of the property drawer.
14059 BEG and END can be beginning and end of subtree, if not given
14060 they will be found.
14061 If the drawer does not exist and FORCE is non-nil, create the drawer."
14062 (catch 'exit
14063 (save-excursion
14064 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14065 (end (or end (progn (outline-next-heading) (point)))))
14066 (goto-char beg)
14067 (if (re-search-forward org-property-start-re end t)
14068 (setq beg (1+ (match-end 0)))
14069 (if force
14070 (save-excursion
14071 (org-insert-property-drawer)
14072 (setq end (progn (outline-next-heading) (point))))
14073 (throw 'exit nil))
14074 (goto-char beg)
14075 (if (re-search-forward org-property-start-re end t)
14076 (setq beg (1+ (match-end 0)))))
14077 (if (re-search-forward org-property-end-re end t)
14078 (setq end (match-beginning 0))
14079 (or force (throw 'exit nil))
14080 (goto-char beg)
14081 (setq end beg)
14082 (org-indent-line-function)
14083 (insert ":END:\n"))
14084 (cons beg end)))))
14086 (defun org-entry-properties (&optional pom which specific)
14087 "Get all properties of the entry at point-or-marker POM.
14088 This includes the TODO keyword, the tags, time strings for deadline,
14089 scheduled, and clocking, and any additional properties defined in the
14090 entry. The return value is an alist, keys may occur multiple times
14091 if the property key was used several times.
14092 POM may also be nil, in which case the current entry is used.
14093 If WHICH is nil or `all', get all properties. If WHICH is
14094 `special' or `standard', only get that subclass. If WHICH
14095 is a string only get exactly this property. SPECIFIC can be a string, the
14096 specific property we are interested in. Specifying it can speed
14097 things up because then unnecessary parsing is avoided."
14098 (setq which (or which 'all))
14099 (org-with-point-at pom
14100 (let ((clockstr (substring org-clock-string 0 -1))
14101 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14102 (case-fold-search nil)
14103 beg end range props sum-props key key1 value string clocksum)
14104 (save-excursion
14105 (when (condition-case nil
14106 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14107 (error nil))
14108 (setq beg (point))
14109 (setq sum-props (get-text-property (point) 'org-summaries))
14110 (setq clocksum (get-text-property (point) :org-clock-minutes))
14111 (outline-next-heading)
14112 (setq end (point))
14113 (when (memq which '(all special))
14114 ;; Get the special properties, like TODO and tags
14115 (goto-char beg)
14116 (when (and (or (not specific) (string= specific "TODO"))
14117 (looking-at org-todo-line-regexp) (match-end 2))
14118 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14119 (when (and (or (not specific) (string= specific "PRIORITY"))
14120 (looking-at org-priority-regexp))
14121 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14122 (when (or (not specific) (string= specific "FILE"))
14123 (push (cons "FILE" buffer-file-name) props))
14124 (when (and (or (not specific) (string= specific "TAGS"))
14125 (setq value (org-get-tags-string))
14126 (string-match "\\S-" value))
14127 (push (cons "TAGS" value) props))
14128 (when (and (or (not specific) (string= specific "ALLTAGS"))
14129 (setq value (org-get-tags-at)))
14130 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14131 ":"))
14132 props))
14133 (when (or (not specific) (string= specific "BLOCKED"))
14134 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14135 (when (or (not specific)
14136 (member specific
14137 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14138 "TIMESTAMP" "TIMESTAMP_IA")))
14139 (catch 'match
14140 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14141 (setq key (if (match-end 1)
14142 (substring (org-match-string-no-properties 1)
14143 0 -1))
14144 string (if (equal key clockstr)
14145 (org-no-properties
14146 (org-trim
14147 (buffer-substring
14148 (match-beginning 3) (goto-char
14149 (point-at-eol)))))
14150 (substring (org-match-string-no-properties 3)
14151 1 -1)))
14152 ;; Get the correct property name from the key. This is
14153 ;; necessary if the user has configured time keywords.
14154 (setq key1 (concat key ":"))
14155 (cond
14156 ((not key)
14157 (setq key
14158 (if (= (char-after (match-beginning 3)) ?\[)
14159 "TIMESTAMP_IA" "TIMESTAMP")))
14160 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14161 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14162 ((equal key1 org-closed-string) (setq key "CLOSED"))
14163 ((equal key1 org-clock-string) (setq key "CLOCK")))
14164 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14165 (progn
14166 (push (cons key string) props)
14167 ;; no need to search further if match is found
14168 (throw 'match t))
14169 (when (or (equal key "CLOCK") (not (assoc key props)))
14170 (push (cons key string) props))))))
14173 (when (memq which '(all standard))
14174 ;; Get the standard properties, like :PROP: ...
14175 (setq range (org-get-property-block beg end))
14176 (when range
14177 (goto-char (car range))
14178 (while (re-search-forward
14179 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14180 (cdr range) t)
14181 (setq key (org-match-string-no-properties 1)
14182 value (org-trim (or (org-match-string-no-properties 2) "")))
14183 (unless (member key excluded)
14184 (push (cons key (or value "")) props)))))
14185 (if clocksum
14186 (push (cons "CLOCKSUM"
14187 (org-columns-number-to-string (/ (float clocksum) 60.)
14188 'add_times))
14189 props))
14190 (unless (assoc "CATEGORY" props)
14191 (push (cons "CATEGORY" (org-get-category)) props))
14192 (append sum-props (nreverse props)))))))
14194 (defun org-entry-get (pom property &optional inherit literal-nil)
14195 "Get value of PROPERTY for entry at point-or-marker POM.
14196 If INHERIT is non-nil and the entry does not have the property,
14197 then also check higher levels of the hierarchy.
14198 If INHERIT is the symbol `selective', use inheritance only if the setting
14199 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14200 If the property is present but empty, the return value is the empty string.
14201 If the property is not present at all, nil is returned.
14203 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14204 do not interpret it as the list atom nil. This is used for inheritance
14205 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14206 (org-with-point-at pom
14207 (if (and inherit (if (eq inherit 'selective)
14208 (org-property-inherit-p property)
14210 (org-entry-get-with-inheritance property literal-nil)
14211 (if (member property org-special-properties)
14212 ;; We need a special property. Use `org-entry-properties' to
14213 ;; retrieve it, but specify the wanted property
14214 (cdr (assoc property (org-entry-properties nil 'special property)))
14215 (let ((range (unless (org-before-first-heading-p)
14216 (org-get-property-block)))
14217 (props (list (or (assoc property org-file-properties)
14218 (assoc property org-global-properties)
14219 (assoc property org-global-properties-fixed))))
14220 val)
14221 (flet ((ap (key)
14222 (when (re-search-forward
14223 (org-re-property key) (cdr range) t)
14224 (setq props
14225 (org-update-property-plist
14227 (if (match-end 1)
14228 (org-match-string-no-properties 1) "")
14229 props)))))
14230 (when (and range (goto-char (car range)))
14231 (ap property)
14232 (goto-char (car range))
14233 (while (ap (concat property "+")))
14234 (setq val (cdr (assoc property props)))
14235 (when val (if literal-nil val (org-not-nil val))))))))))
14237 (defun org-property-or-variable-value (var &optional inherit)
14238 "Check if there is a property fixing the value of VAR.
14239 If yes, return this value. If not, return the current value of the variable."
14240 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14241 (if (and prop (stringp prop) (string-match "\\S-" prop))
14242 (read prop)
14243 (symbol-value var))))
14245 (defun org-entry-delete (pom property)
14246 "Delete the property PROPERTY from entry at point-or-marker POM."
14247 (org-with-point-at pom
14248 (if (member property org-special-properties)
14249 nil ; cannot delete these properties.
14250 (let ((range (org-get-property-block)))
14251 (if (and range
14252 (goto-char (car range))
14253 (re-search-forward
14254 (org-re-property property)
14255 (cdr range) t))
14256 (progn
14257 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14259 nil)))))
14261 ;; Multi-values properties are properties that contain multiple values
14262 ;; These values are assumed to be single words, separated by whitespace.
14263 (defun org-entry-add-to-multivalued-property (pom property value)
14264 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14265 (let* ((old (org-entry-get pom property))
14266 (values (and old (org-split-string old "[ \t]"))))
14267 (setq value (org-entry-protect-space value))
14268 (unless (member value values)
14269 (setq values (cons value values))
14270 (org-entry-put pom property
14271 (mapconcat 'identity values " ")))))
14273 (defun org-entry-remove-from-multivalued-property (pom property value)
14274 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14275 (let* ((old (org-entry-get pom property))
14276 (values (and old (org-split-string old "[ \t]"))))
14277 (setq value (org-entry-protect-space value))
14278 (when (member value values)
14279 (setq values (delete value values))
14280 (org-entry-put pom property
14281 (mapconcat 'identity values " ")))))
14283 (defun org-entry-member-in-multivalued-property (pom property value)
14284 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14285 (let* ((old (org-entry-get pom property))
14286 (values (and old (org-split-string old "[ \t]"))))
14287 (setq value (org-entry-protect-space value))
14288 (member value values)))
14290 (defun org-entry-get-multivalued-property (pom property)
14291 "Return a list of values in a multivalued property."
14292 (let* ((value (org-entry-get pom property))
14293 (values (and value (org-split-string value "[ \t]"))))
14294 (mapcar 'org-entry-restore-space values)))
14296 (defun org-entry-put-multivalued-property (pom property &rest values)
14297 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14298 VALUES should be a list of strings. Spaces will be protected."
14299 (org-entry-put pom property
14300 (mapconcat 'org-entry-protect-space values " "))
14301 (let* ((value (org-entry-get pom property))
14302 (values (and value (org-split-string value "[ \t]"))))
14303 (mapcar 'org-entry-restore-space values)))
14305 (defun org-entry-protect-space (s)
14306 "Protect spaces and newline in string S."
14307 (while (string-match " " s)
14308 (setq s (replace-match "%20" t t s)))
14309 (while (string-match "\n" s)
14310 (setq s (replace-match "%0A" t t s)))
14313 (defun org-entry-restore-space (s)
14314 "Restore spaces and newline in string S."
14315 (while (string-match "%20" s)
14316 (setq s (replace-match " " t t s)))
14317 (while (string-match "%0A" s)
14318 (setq s (replace-match "\n" t t s)))
14321 (defvar org-entry-property-inherited-from (make-marker)
14322 "Marker pointing to the entry from where a property was inherited.
14323 Each call to `org-entry-get-with-inheritance' will set this marker to the
14324 location of the entry where the inheritance search matched. If there was
14325 no match, the marker will point nowhere.
14326 Note that also `org-entry-get' calls this function, if the INHERIT flag
14327 is set.")
14329 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14330 "Get entry property, and search higher levels if not present.
14331 The search will stop at the first ancestor which has the property defined.
14332 If the value found is \"nil\", return nil to show that the property
14333 should be considered as undefined (this is the meaning of nil here).
14334 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14335 (move-marker org-entry-property-inherited-from nil)
14336 (let (tmp)
14337 (unless (org-before-first-heading-p)
14338 (save-excursion
14339 (save-restriction
14340 (widen)
14341 (catch 'ex
14342 (while t
14343 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14344 (org-back-to-heading t)
14345 (move-marker org-entry-property-inherited-from (point))
14346 (throw 'ex tmp))
14347 (or (org-up-heading-safe) (throw 'ex nil)))))))
14348 (setq tmp (or tmp
14349 (cdr (assoc property org-file-properties))
14350 (cdr (assoc property org-global-properties))
14351 (cdr (assoc property org-global-properties-fixed))))
14352 (if literal-nil tmp (org-not-nil tmp))))
14354 (defvar org-property-changed-functions nil
14355 "Hook called when the value of a property has changed.
14356 Each hook function should accept two arguments, the name of the property
14357 and the new value.")
14359 (defun org-entry-put (pom property value)
14360 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14361 (org-with-point-at pom
14362 (org-back-to-heading t)
14363 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14364 range)
14365 (cond
14366 ((equal property "TODO")
14367 (when (and (stringp value) (string-match "\\S-" value)
14368 (not (member value org-todo-keywords-1)))
14369 (error "\"%s\" is not a valid TODO state" value))
14370 (if (or (not value)
14371 (not (string-match "\\S-" value)))
14372 (setq value 'none))
14373 (org-todo value)
14374 (org-set-tags nil 'align))
14375 ((equal property "PRIORITY")
14376 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14377 (string-to-char value) ?\ ))
14378 (org-set-tags nil 'align))
14379 ((equal property "SCHEDULED")
14380 (if (re-search-forward org-scheduled-time-regexp end t)
14381 (cond
14382 ((eq value 'earlier) (org-timestamp-change -1 'day))
14383 ((eq value 'later) (org-timestamp-change 1 'day))
14384 (t (call-interactively 'org-schedule)))
14385 (call-interactively 'org-schedule)))
14386 ((equal property "DEADLINE")
14387 (if (re-search-forward org-deadline-time-regexp end t)
14388 (cond
14389 ((eq value 'earlier) (org-timestamp-change -1 'day))
14390 ((eq value 'later) (org-timestamp-change 1 'day))
14391 (t (call-interactively 'org-deadline)))
14392 (call-interactively 'org-deadline)))
14393 ((member property org-special-properties)
14394 (error "The %s property can not yet be set with `org-entry-put'"
14395 property))
14396 (t ; a non-special property
14397 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14398 (setq range (org-get-property-block beg end 'force))
14399 (goto-char (car range))
14400 (if (re-search-forward
14401 (org-re-property property) (cdr range) t)
14402 (progn
14403 (delete-region (match-beginning 0) (match-end 0))
14404 (goto-char (match-beginning 0)))
14405 (goto-char (cdr range))
14406 (insert "\n")
14407 (backward-char 1)
14408 (org-indent-line-function))
14409 (insert ":" property ":")
14410 (and value (insert " " value))
14411 (org-indent-line-function)))))
14412 (run-hook-with-args 'org-property-changed-functions property value)))
14414 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14415 "Get all property keys in the current buffer.
14416 With INCLUDE-SPECIALS, also list the special properties that reflect things
14417 like tags and TODO state.
14418 With INCLUDE-DEFAULTS, also include properties that has special meaning
14419 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14420 and others.
14421 With INCLUDE-COLUMNS, also include property names given in COLUMN
14422 formats in the current buffer."
14423 (let (rtn range cfmt s p)
14424 (save-excursion
14425 (save-restriction
14426 (widen)
14427 (goto-char (point-min))
14428 (while (re-search-forward org-property-start-re nil t)
14429 (setq range (org-get-property-block))
14430 (goto-char (car range))
14431 (while (re-search-forward
14432 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14433 (cdr range) t)
14434 (add-to-list 'rtn (org-match-string-no-properties 1)))
14435 (outline-next-heading))))
14437 (when include-specials
14438 (setq rtn (append org-special-properties rtn)))
14440 (when include-defaults
14441 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14442 (add-to-list 'rtn org-effort-property))
14444 (when include-columns
14445 (save-excursion
14446 (save-restriction
14447 (widen)
14448 (goto-char (point-min))
14449 (while (re-search-forward
14450 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14451 nil t)
14452 (setq cfmt (match-string 2) s 0)
14453 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14454 cfmt s)
14455 (setq s (match-end 0)
14456 p (match-string 1 cfmt))
14457 (unless (or (equal p "ITEM")
14458 (member p org-special-properties))
14459 (add-to-list 'rtn (match-string 1 cfmt))))))))
14461 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14463 (defun org-property-values (key)
14464 "Return a list of all values of property KEY in the current buffer."
14465 (save-excursion
14466 (save-restriction
14467 (widen)
14468 (goto-char (point-min))
14469 (let ((re (org-re-property key))
14470 values)
14471 (while (re-search-forward re nil t)
14472 (add-to-list 'values (org-trim (match-string 1))))
14473 (delete "" values)))))
14475 (defun org-insert-property-drawer ()
14476 "Insert a property drawer into the current entry."
14477 (org-back-to-heading t)
14478 (looking-at org-outline-regexp)
14479 (let ((indent (if org-adapt-indentation
14480 (- (match-end 0) (match-beginning 0))
14482 (beg (point))
14483 (re (concat "^[ \t]*" org-keyword-time-regexp))
14484 end hiddenp)
14485 (outline-next-heading)
14486 (setq end (point))
14487 (goto-char beg)
14488 (while (re-search-forward re end t))
14489 (setq hiddenp (outline-invisible-p))
14490 (end-of-line 1)
14491 (and (equal (char-after) ?\n) (forward-char 1))
14492 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14493 (if (member (match-string 1) '("CLOCK:" ":END:"))
14494 ;; just skip this line
14495 (beginning-of-line 2)
14496 ;; Drawer start, find the end
14497 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14498 (beginning-of-line 1)))
14499 (org-skip-over-state-notes)
14500 (skip-chars-backward " \t\n\r")
14501 (if (eq (char-before) ?*) (forward-char 1))
14502 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14503 (beginning-of-line 0)
14504 (org-indent-to-column indent)
14505 (beginning-of-line 2)
14506 (org-indent-to-column indent)
14507 (beginning-of-line 0)
14508 (if hiddenp
14509 (save-excursion
14510 (org-back-to-heading t)
14511 (hide-entry))
14512 (org-flag-drawer t))))
14514 (defun org-insert-drawer (&optional arg drawer)
14515 "Insert a drawer at point.
14517 Optional argument DRAWER, when non-nil, is a string representing
14518 drawer's name. Otherwise, the user is prompted for a name.
14520 If a region is active, insert the drawer around that region
14521 instead.
14523 Point is left between drawer's boundaries."
14524 (interactive "P")
14525 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14526 "LOGBOOK"))
14527 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14528 ;; internally by Org. They are meant to be inserted
14529 ;; automatically.
14530 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14531 ;; Remove system drawers from list. Note: For some reason,
14532 ;; `org-completing-read' ignores the predicate while
14533 ;; `completing-read' handles it fine.
14534 (drawer (if arg "PROPERTIES"
14535 (or drawer
14536 (completing-read
14537 "Drawer: " org-drawers
14538 (lambda (d) (not (member d system-drawers))))))))
14539 (cond
14540 ;; With C-u, fall back on `org-insert-property-drawer'
14541 (arg (org-insert-property-drawer))
14542 ;; With an active region, insert a drawer at point.
14543 ((not (org-region-active-p))
14544 (progn
14545 (unless (bolp) (insert "\n"))
14546 (insert (format ":%s:\n\n:END:\n" drawer))
14547 (forward-line -2)))
14548 ;; Otherwise, insert the drawer at point
14550 (let ((rbeg (region-beginning))
14551 (rend (copy-marker (region-end))))
14552 (unwind-protect
14553 (progn
14554 (goto-char rbeg)
14555 (beginning-of-line)
14556 (when (save-excursion
14557 (re-search-forward org-outline-regexp-bol rend t))
14558 (error "Drawers cannot contain headlines"))
14559 ;; Position point at the beginning of the first
14560 ;; non-blank line in region. Insert drawer's opening
14561 ;; there, then indent it.
14562 (org-skip-whitespace)
14563 (beginning-of-line)
14564 (insert ":" drawer ":\n")
14565 (forward-line -1)
14566 (indent-for-tab-command)
14567 ;; Move point to the beginning of the first blank line
14568 ;; after the last non-blank line in region. Insert
14569 ;; drawer's closing, then indent it.
14570 (goto-char rend)
14571 (skip-chars-backward " \r\t\n")
14572 (insert "\n:END:")
14573 (indent-for-tab-command)
14574 (unless (eolp) (insert "\n")))
14575 ;; Clear marker, whatever the outcome of insertion is.
14576 (set-marker rend nil)))))))
14578 (defvar org-property-set-functions-alist nil
14579 "Property set function alist.
14580 Each entry should have the following format:
14582 (PROPERTY . READ-FUNCTION)
14584 The read function will be called with the same argument as
14585 `org-completing-read'.")
14587 (defun org-set-property-function (property)
14588 "Get the function that should be used to set PROPERTY.
14589 This is computed according to `org-property-set-functions-alist'."
14590 (or (cdr (assoc property org-property-set-functions-alist))
14591 'org-completing-read))
14593 (defun org-read-property-value (property)
14594 "Read PROPERTY value from user."
14595 (let* ((completion-ignore-case t)
14596 (allowed (org-property-get-allowed-values nil property 'table))
14597 (cur (org-entry-get nil property))
14598 (prompt (concat property " value"
14599 (if (and cur (string-match "\\S-" cur))
14600 (concat " [" cur "]") "") ": "))
14601 (set-function (org-set-property-function property))
14602 (val (if allowed
14603 (funcall set-function prompt allowed nil
14604 (not (get-text-property 0 'org-unrestricted
14605 (caar allowed))))
14606 (let (org-completion-use-ido org-completion-use-iswitchb)
14607 (funcall set-function prompt
14608 (mapcar 'list (org-property-values property))
14609 nil nil "" nil cur)))))
14610 (if (equal val "")
14612 val)))
14614 (defvar org-last-set-property nil)
14615 (defun org-read-property-name ()
14616 "Read a property name."
14617 (let* ((completion-ignore-case t)
14618 (keys (org-buffer-property-keys nil t t))
14619 (default-prop (or (save-excursion
14620 (save-match-data
14621 (beginning-of-line)
14622 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14623 (null (string= (match-string 1) "END"))
14624 (match-string 1))))
14625 org-last-set-property))
14626 (property (org-icompleting-read
14627 (concat "Property"
14628 (if default-prop (concat " [" default-prop "]") "")
14629 ": ")
14630 (mapcar 'list keys)
14631 nil nil nil nil
14632 default-prop
14634 (if (member property keys)
14635 property
14636 (or (cdr (assoc (downcase property)
14637 (mapcar (lambda (x) (cons (downcase x) x))
14638 keys)))
14639 property))))
14641 (defun org-set-property (property value)
14642 "In the current entry, set PROPERTY to VALUE.
14643 When called interactively, this will prompt for a property name, offering
14644 completion on existing and default properties. And then it will prompt
14645 for a value, offering completion either on allowed values (via an inherited
14646 xxx_ALL property) or on existing values in other instances of this property
14647 in the current file."
14648 (interactive (list nil nil))
14649 (let* ((property (or property (org-read-property-name)))
14650 (value (or value (org-read-property-value property)))
14651 (fn (assoc property org-properties-postprocess-alist)))
14652 (setq org-last-set-property property)
14653 ;; Possibly postprocess the inserted value:
14654 (when fn (setq value (funcall (cadr fn) value)))
14655 (unless (equal (org-entry-get nil property) value)
14656 (org-entry-put nil property value))))
14658 (defun org-delete-property (property)
14659 "In the current entry, delete PROPERTY."
14660 (interactive
14661 (let* ((completion-ignore-case t)
14662 (prop (org-icompleting-read "Property: "
14663 (org-entry-properties nil 'standard))))
14664 (list prop)))
14665 (message "Property %s %s" property
14666 (if (org-entry-delete nil property)
14667 "deleted"
14668 "was not present in the entry")))
14670 (defun org-delete-property-globally (property)
14671 "Remove PROPERTY globally, from all entries."
14672 (interactive
14673 (let* ((completion-ignore-case t)
14674 (prop (org-icompleting-read
14675 "Globally remove property: "
14676 (mapcar 'list (org-buffer-property-keys)))))
14677 (list prop)))
14678 (save-excursion
14679 (save-restriction
14680 (widen)
14681 (goto-char (point-min))
14682 (let ((cnt 0))
14683 (while (re-search-forward
14684 (org-re-property property)
14685 nil t)
14686 (setq cnt (1+ cnt))
14687 (replace-match ""))
14688 (message "Property \"%s\" removed from %d entries" property cnt)))))
14690 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14692 (defun org-compute-property-at-point ()
14693 "Compute the property at point.
14694 This looks for an enclosing column format, extracts the operator and
14695 then applies it to the property in the column format's scope."
14696 (interactive)
14697 (unless (org-at-property-p)
14698 (error "Not at a property"))
14699 (let ((prop (org-match-string-no-properties 2)))
14700 (org-columns-get-format-and-top-level)
14701 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14702 (error "No operator defined for property %s" prop))
14703 (org-columns-compute prop)))
14705 (defvar org-property-allowed-value-functions nil
14706 "Hook for functions supplying allowed values for a specific property.
14707 The functions must take a single argument, the name of the property, and
14708 return a flat list of allowed values. If \":ETC\" is one of
14709 the values, this means that these values are intended as defaults for
14710 completion, but that other values should be allowed too.
14711 The functions must return nil if they are not responsible for this
14712 property.")
14714 (defun org-property-get-allowed-values (pom property &optional table)
14715 "Get allowed values for the property PROPERTY.
14716 When TABLE is non-nil, return an alist that can directly be used for
14717 completion."
14718 (let (vals)
14719 (cond
14720 ((equal property "TODO")
14721 (setq vals (org-with-point-at pom
14722 (append org-todo-keywords-1 '("")))))
14723 ((equal property "PRIORITY")
14724 (let ((n org-lowest-priority))
14725 (while (>= n org-highest-priority)
14726 (push (char-to-string n) vals)
14727 (setq n (1- n)))))
14728 ((member property org-special-properties))
14729 ((setq vals (run-hook-with-args-until-success
14730 'org-property-allowed-value-functions property)))
14732 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14733 (when (and vals (string-match "\\S-" vals))
14734 (setq vals (car (read-from-string (concat "(" vals ")"))))
14735 (setq vals (mapcar (lambda (x)
14736 (cond ((stringp x) x)
14737 ((numberp x) (number-to-string x))
14738 ((symbolp x) (symbol-name x))
14739 (t "???")))
14740 vals)))))
14741 (when (member ":ETC" vals)
14742 (setq vals (remove ":ETC" vals))
14743 (org-add-props (car vals) '(org-unrestricted t)))
14744 (if table (mapcar 'list vals) vals)))
14746 (defun org-property-previous-allowed-value (&optional previous)
14747 "Switch to the next allowed value for this property."
14748 (interactive)
14749 (org-property-next-allowed-value t))
14751 (defun org-property-next-allowed-value (&optional previous)
14752 "Switch to the next allowed value for this property."
14753 (interactive)
14754 (unless (org-at-property-p)
14755 (error "Not at a property"))
14756 (let* ((key (match-string 2))
14757 (value (match-string 3))
14758 (allowed (or (org-property-get-allowed-values (point) key)
14759 (and (member value '("[ ]" "[-]" "[X]"))
14760 '("[ ]" "[X]"))))
14761 nval)
14762 (unless allowed
14763 (error "Allowed values for this property have not been defined"))
14764 (if previous (setq allowed (reverse allowed)))
14765 (if (member value allowed)
14766 (setq nval (car (cdr (member value allowed)))))
14767 (setq nval (or nval (car allowed)))
14768 (if (equal nval value)
14769 (error "Only one allowed value for this property"))
14770 (org-at-property-p)
14771 (replace-match (concat " :" key ": " nval) t t)
14772 (org-indent-line-function)
14773 (beginning-of-line 1)
14774 (skip-chars-forward " \t")
14775 (run-hook-with-args 'org-property-changed-functions key nval)))
14777 (defun org-find-olp (path &optional this-buffer)
14778 "Return a marker pointing to the entry at outline path OLP.
14779 If anything goes wrong, throw an error.
14780 You can wrap this call to catch the error like this:
14782 (condition-case msg
14783 (org-mobile-locate-entry (match-string 4))
14784 (error (nth 1 msg)))
14786 The return value will then be either a string with the error message,
14787 or a marker if everything is OK.
14789 If THIS-BUFFER is set, the outline path does not contain a file,
14790 only headings."
14791 (let* ((file (if this-buffer buffer-file-name (pop path)))
14792 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14793 (level 1)
14794 (lmin 1)
14795 (lmax 1)
14796 limit re end found pos heading cnt flevel)
14797 (unless buffer (error "File not found :%s" file))
14798 (with-current-buffer buffer
14799 (save-excursion
14800 (save-restriction
14801 (widen)
14802 (setq limit (point-max))
14803 (goto-char (point-min))
14804 (while (setq heading (pop path))
14805 (setq re (format org-complex-heading-regexp-format
14806 (regexp-quote heading)))
14807 (setq cnt 0 pos (point))
14808 (while (re-search-forward re end t)
14809 (setq level (- (match-end 1) (match-beginning 1)))
14810 (if (and (>= level lmin) (<= level lmax))
14811 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14812 (when (= cnt 0) (error "Heading not found on level %d: %s"
14813 lmax heading))
14814 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14815 lmax heading))
14816 (goto-char found)
14817 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14818 (setq end (save-excursion (org-end-of-subtree t t))))
14819 (when (org-at-heading-p)
14820 (move-marker (make-marker) (point))))))))
14822 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14823 "Find node HEADING in BUFFER.
14824 Return a marker to the heading if it was found, or nil if not.
14825 If POS-ONLY is set, return just the position instead of a marker.
14827 The heading text must match exact, but it may have a TODO keyword,
14828 a priority cookie and tags in the standard locations."
14829 (with-current-buffer (or buffer (current-buffer))
14830 (save-excursion
14831 (save-restriction
14832 (widen)
14833 (goto-char (point-min))
14834 (let (case-fold-search)
14835 (if (re-search-forward
14836 (format org-complex-heading-regexp-format
14837 (regexp-quote heading)) nil t)
14838 (if pos-only
14839 (match-beginning 0)
14840 (move-marker (make-marker) (match-beginning 0)))))))))
14842 (defun org-find-exact-heading-in-directory (heading &optional dir)
14843 "Find Org node headline HEADING in all .org files in directory DIR.
14844 When the target headline is found, return a marker to this location."
14845 (let ((files (directory-files (or dir default-directory)
14846 nil "\\`[^.#].*\\.org\\'"))
14847 file visiting m buffer)
14848 (catch 'found
14849 (while (setq file (pop files))
14850 (message "trying %s" file)
14851 (setq visiting (org-find-base-buffer-visiting file))
14852 (setq buffer (or visiting (find-file-noselect file)))
14853 (setq m (org-find-exact-headline-in-buffer
14854 heading buffer))
14855 (when (and (not m) (not visiting)) (kill-buffer buffer))
14856 (and m (throw 'found m))))))
14858 (defun org-find-entry-with-id (ident)
14859 "Locate the entry that contains the ID property with exact value IDENT.
14860 IDENT can be a string, a symbol or a number, this function will search for
14861 the string representation of it.
14862 Return the position where this entry starts, or nil if there is no such entry."
14863 (interactive "sID: ")
14864 (let ((id (cond
14865 ((stringp ident) ident)
14866 ((symbol-name ident) (symbol-name ident))
14867 ((numberp ident) (number-to-string ident))
14868 (t (error "IDENT %s must be a string, symbol or number" ident))))
14869 (case-fold-search nil))
14870 (save-excursion
14871 (save-restriction
14872 (widen)
14873 (goto-char (point-min))
14874 (when (re-search-forward
14875 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14876 nil t)
14877 (org-back-to-heading t)
14878 (point))))))
14880 ;;;; Timestamps
14882 (defvar org-last-changed-timestamp nil)
14883 (defvar org-last-inserted-timestamp nil
14884 "The last time stamp inserted with `org-insert-time-stamp'.")
14885 (defvar org-time-was-given) ; dynamically scoped parameter
14886 (defvar org-end-time-was-given) ; dynamically scoped parameter
14887 (defvar org-ts-what) ; dynamically scoped parameter
14889 (defun org-time-stamp (arg &optional inactive)
14890 "Prompt for a date/time and insert a time stamp.
14891 If the user specifies a time like HH:MM, or if this command is called
14892 with a prefix argument, the time stamp will contain date and time.
14893 Otherwise, only the date will be included. All parts of a date not
14894 specified by the user will be filled in from the current date/time.
14895 So if you press just return without typing anything, the time stamp
14896 will represent the current date/time. If there is already a timestamp
14897 at the cursor, it will be modified."
14898 (interactive "P")
14899 (let* ((ts nil)
14900 (default-time
14901 ;; Default time is either today, or, when entering a range,
14902 ;; the range start.
14903 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14904 (save-excursion
14905 (re-search-backward
14906 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14907 (- (point) 20) t)))
14908 (apply 'encode-time (org-parse-time-string (match-string 1)))
14909 (current-time)))
14910 (default-input (and ts (org-get-compact-tod ts)))
14911 (repeater (save-excursion
14912 (save-match-data
14913 (beginning-of-line)
14914 (when (re-search-forward
14915 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14916 (save-excursion (progn (end-of-line) (point))) t)
14917 (match-string 0)))))
14918 org-time-was-given org-end-time-was-given time)
14919 (cond
14920 ((and (org-at-timestamp-p t)
14921 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14922 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14923 (insert "--")
14924 (setq time (let ((this-command this-command))
14925 (org-read-date arg 'totime nil nil
14926 default-time default-input inactive)))
14927 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14928 ((org-at-timestamp-p t)
14929 (setq time (let ((this-command this-command))
14930 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14931 (when (org-at-timestamp-p t) ; just to get the match data
14932 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14933 (replace-match "")
14934 (setq org-last-changed-timestamp
14935 (org-insert-time-stamp
14936 time (or org-time-was-given arg)
14937 inactive nil nil (list org-end-time-was-given)))
14938 (when repeater (goto-char (1- (point))) (insert " " repeater)
14939 (setq org-last-changed-timestamp
14940 (concat (substring org-last-inserted-timestamp 0 -1)
14941 " " repeater ">"))))
14942 (message "Timestamp updated"))
14944 (setq time (let ((this-command this-command))
14945 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14946 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14947 nil nil (list org-end-time-was-given))))))
14949 ;; FIXME: can we use this for something else, like computing time differences?
14950 (defun org-get-compact-tod (s)
14951 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14952 (let* ((t1 (match-string 1 s))
14953 (h1 (string-to-number (match-string 2 s)))
14954 (m1 (string-to-number (match-string 3 s)))
14955 (t2 (and (match-end 4) (match-string 5 s)))
14956 (h2 (and t2 (string-to-number (match-string 6 s))))
14957 (m2 (and t2 (string-to-number (match-string 7 s))))
14958 dh dm)
14959 (if (not t2)
14961 (setq dh (- h2 h1) dm (- m2 m1))
14962 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14963 (concat t1 "+" (number-to-string dh)
14964 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14966 (defun org-time-stamp-inactive (&optional arg)
14967 "Insert an inactive time stamp.
14968 An inactive time stamp is enclosed in square brackets instead of angle
14969 brackets. It is inactive in the sense that it does not trigger agenda entries,
14970 does not link to the calendar and cannot be changed with the S-cursor keys.
14971 So these are more for recording a certain time/date."
14972 (interactive "P")
14973 (org-time-stamp arg 'inactive))
14975 (defvar org-date-ovl (make-overlay 1 1))
14976 (overlay-put org-date-ovl 'face 'org-warning)
14977 (org-detach-overlay org-date-ovl)
14979 (defvar org-ans1) ; dynamically scoped parameter
14980 (defvar org-ans2) ; dynamically scoped parameter
14982 (defvar org-plain-time-of-day-regexp) ; defined below
14984 (defvar org-overriding-default-time nil) ; dynamically scoped
14985 (defvar org-read-date-overlay nil)
14986 (defvar org-dcst nil) ; dynamically scoped
14987 (defvar org-read-date-history nil)
14988 (defvar org-read-date-final-answer nil)
14989 (defvar org-read-date-analyze-futurep nil)
14990 (defvar org-read-date-analyze-forced-year nil)
14991 (defvar org-read-date-inactive)
14993 (defun org-read-date (&optional with-time to-time from-string prompt
14994 default-time default-input inactive)
14995 "Read a date, possibly a time, and make things smooth for the user.
14996 The prompt will suggest to enter an ISO date, but you can also enter anything
14997 which will at least partially be understood by `parse-time-string'.
14998 Unrecognized parts of the date will default to the current day, month, year,
14999 hour and minute. If this command is called to replace a timestamp at point,
15000 or to enter the second timestamp of a range, the default time is taken
15001 from the existing stamp. Furthermore, the command prefers the future,
15002 so if you are giving a date where the year is not given, and the day-month
15003 combination is already past in the current year, it will assume you
15004 mean next year. For details, see the manual. A few examples:
15006 3-2-5 --> 2003-02-05
15007 feb 15 --> currentyear-02-15
15008 2/15 --> currentyear-02-15
15009 sep 12 9 --> 2009-09-12
15010 12:45 --> today 12:45
15011 22 sept 0:34 --> currentyear-09-22 0:34
15012 12 --> currentyear-currentmonth-12
15013 Fri --> nearest Friday (today or later)
15014 etc.
15016 Furthermore you can specify a relative date by giving, as the *first* thing
15017 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15018 change in days weeks, months, years.
15019 With a single plus or minus, the date is relative to today. With a double
15020 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15021 +4d --> four days from today
15022 +4 --> same as above
15023 +2w --> two weeks from today
15024 ++5 --> five days from default date
15026 The function understands only English month and weekday abbreviations,
15027 but this can be configured with the variables `parse-time-months' and
15028 `parse-time-weekdays'.
15030 While prompting, a calendar is popped up - you can also select the
15031 date with the mouse (button 1). The calendar shows a period of three
15032 months. To scroll it to other months, use the keys `>' and `<'.
15033 If you don't like the calendar, turn it off with
15034 \(setq org-read-date-popup-calendar nil)
15036 With optional argument TO-TIME, the date will immediately be converted
15037 to an internal time.
15038 With an optional argument WITH-TIME, the prompt will suggest to also
15039 insert a time. Note that when WITH-TIME is not set, you can still
15040 enter a time, and this function will inform the calling routine about
15041 this change. The calling routine may then choose to change the format
15042 used to insert the time stamp into the buffer to include the time.
15043 With optional argument FROM-STRING, read from this string instead from
15044 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15045 the time/date that is used for everything that is not specified by the
15046 user."
15047 (require 'parse-time)
15048 (let* ((org-time-stamp-rounding-minutes
15049 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15050 (org-dcst org-display-custom-times)
15051 (ct (org-current-time))
15052 (def (or org-overriding-default-time default-time ct))
15053 (defdecode (decode-time def))
15054 (dummy (progn
15055 (when (< (nth 2 defdecode) org-extend-today-until)
15056 (setcar (nthcdr 2 defdecode) -1)
15057 (setcar (nthcdr 1 defdecode) 59)
15058 (setq def (apply 'encode-time defdecode)
15059 defdecode (decode-time def)))))
15060 (calendar-frame-setup nil)
15061 (calendar-setup nil)
15062 (calendar-move-hook nil)
15063 (calendar-view-diary-initially-flag nil)
15064 (calendar-view-holidays-initially-flag nil)
15065 (timestr (format-time-string
15066 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15067 (prompt (concat (if prompt (concat prompt " ") "")
15068 (format "Date+time [%s]: " timestr)))
15069 ans (org-ans0 "") org-ans1 org-ans2 final)
15071 (cond
15072 (from-string (setq ans from-string))
15073 (org-read-date-popup-calendar
15074 (save-excursion
15075 (save-window-excursion
15076 (calendar)
15077 (unwind-protect
15078 (progn
15079 (calendar-forward-day (- (time-to-days def)
15080 (calendar-absolute-from-gregorian
15081 (calendar-current-date))))
15082 (org-eval-in-calendar nil t)
15083 (let* ((old-map (current-local-map))
15084 (map (copy-keymap calendar-mode-map))
15085 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15086 (org-defkey map (kbd "RET") 'org-calendar-select)
15087 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15088 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15089 (org-defkey minibuffer-local-map [(meta shift left)]
15090 (lambda () (interactive)
15091 (org-eval-in-calendar '(calendar-backward-month 1))))
15092 (org-defkey minibuffer-local-map [(meta shift right)]
15093 (lambda () (interactive)
15094 (org-eval-in-calendar '(calendar-forward-month 1))))
15095 (org-defkey minibuffer-local-map [(meta shift up)]
15096 (lambda () (interactive)
15097 (org-eval-in-calendar '(calendar-backward-year 1))))
15098 (org-defkey minibuffer-local-map [(meta shift down)]
15099 (lambda () (interactive)
15100 (org-eval-in-calendar '(calendar-forward-year 1))))
15101 (org-defkey minibuffer-local-map [?\e (shift left)]
15102 (lambda () (interactive)
15103 (org-eval-in-calendar '(calendar-backward-month 1))))
15104 (org-defkey minibuffer-local-map [?\e (shift right)]
15105 (lambda () (interactive)
15106 (org-eval-in-calendar '(calendar-forward-month 1))))
15107 (org-defkey minibuffer-local-map [?\e (shift up)]
15108 (lambda () (interactive)
15109 (org-eval-in-calendar '(calendar-backward-year 1))))
15110 (org-defkey minibuffer-local-map [?\e (shift down)]
15111 (lambda () (interactive)
15112 (org-eval-in-calendar '(calendar-forward-year 1))))
15113 (org-defkey minibuffer-local-map [(shift up)]
15114 (lambda () (interactive)
15115 (org-eval-in-calendar '(calendar-backward-week 1))))
15116 (org-defkey minibuffer-local-map [(shift down)]
15117 (lambda () (interactive)
15118 (org-eval-in-calendar '(calendar-forward-week 1))))
15119 (org-defkey minibuffer-local-map [(shift left)]
15120 (lambda () (interactive)
15121 (org-eval-in-calendar '(calendar-backward-day 1))))
15122 (org-defkey minibuffer-local-map [(shift right)]
15123 (lambda () (interactive)
15124 (org-eval-in-calendar '(calendar-forward-day 1))))
15125 (org-defkey minibuffer-local-map ">"
15126 (lambda () (interactive)
15127 (org-eval-in-calendar '(scroll-calendar-left 1))))
15128 (org-defkey minibuffer-local-map "<"
15129 (lambda () (interactive)
15130 (org-eval-in-calendar '(scroll-calendar-right 1))))
15131 (org-defkey minibuffer-local-map "\C-v"
15132 (lambda () (interactive)
15133 (org-eval-in-calendar
15134 '(calendar-scroll-left-three-months 1))))
15135 (org-defkey minibuffer-local-map "\M-v"
15136 (lambda () (interactive)
15137 (org-eval-in-calendar
15138 '(calendar-scroll-right-three-months 1))))
15139 (run-hooks 'org-read-date-minibuffer-setup-hook)
15140 (unwind-protect
15141 (progn
15142 (use-local-map map)
15143 (setq org-read-date-inactive inactive)
15144 (add-hook 'post-command-hook 'org-read-date-display)
15145 (setq org-ans0 (read-string prompt default-input
15146 'org-read-date-history nil))
15147 ;; org-ans0: from prompt
15148 ;; org-ans1: from mouse click
15149 ;; org-ans2: from calendar motion
15150 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15151 (remove-hook 'post-command-hook 'org-read-date-display)
15152 (use-local-map old-map)
15153 (when org-read-date-overlay
15154 (delete-overlay org-read-date-overlay)
15155 (setq org-read-date-overlay nil)))))
15156 (bury-buffer "*Calendar*")))))
15158 (t ; Naked prompt only
15159 (unwind-protect
15160 (setq ans (read-string prompt default-input
15161 'org-read-date-history timestr))
15162 (when org-read-date-overlay
15163 (delete-overlay org-read-date-overlay)
15164 (setq org-read-date-overlay nil)))))
15166 (setq final (org-read-date-analyze ans def defdecode))
15168 (when org-read-date-analyze-forced-year
15169 (message "Year was forced into %s"
15170 (if org-read-date-force-compatible-dates
15171 "compatible range (1970-2037)"
15172 "range representable on this machine"))
15173 (ding))
15175 ;; One round trip to get rid of 34th of August and stuff like that....
15176 (setq final (decode-time (apply 'encode-time final)))
15178 (setq org-read-date-final-answer ans)
15180 (if to-time
15181 (apply 'encode-time final)
15182 (if (and (boundp 'org-time-was-given) org-time-was-given)
15183 (format "%04d-%02d-%02d %02d:%02d"
15184 (nth 5 final) (nth 4 final) (nth 3 final)
15185 (nth 2 final) (nth 1 final))
15186 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15188 (defvar def)
15189 (defvar defdecode)
15190 (defvar with-time)
15191 (defun org-read-date-display ()
15192 "Display the current date prompt interpretation in the minibuffer."
15193 (when org-read-date-display-live
15194 (when org-read-date-overlay
15195 (delete-overlay org-read-date-overlay))
15196 (let ((p (point)))
15197 (end-of-line 1)
15198 (while (not (equal (buffer-substring
15199 (max (point-min) (- (point) 4)) (point))
15200 " "))
15201 (insert " "))
15202 (goto-char p))
15203 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15204 " " (or org-ans1 org-ans2)))
15205 (org-end-time-was-given nil)
15206 (f (org-read-date-analyze ans def defdecode))
15207 (fmts (if org-dcst
15208 org-time-stamp-custom-formats
15209 org-time-stamp-formats))
15210 (fmt (if (or with-time
15211 (and (boundp 'org-time-was-given) org-time-was-given))
15212 (cdr fmts)
15213 (car fmts)))
15214 (txt (format-time-string fmt (apply 'encode-time f)))
15215 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15216 (txt (concat "=> " txt)))
15217 (when (and org-end-time-was-given
15218 (string-match org-plain-time-of-day-regexp txt))
15219 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15220 org-end-time-was-given
15221 (substring txt (match-end 0)))))
15222 (when org-read-date-analyze-futurep
15223 (setq txt (concat txt " (=>F)")))
15224 (setq org-read-date-overlay
15225 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15226 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15228 (defun org-read-date-analyze (ans def defdecode)
15229 "Analyze the combined answer of the date prompt."
15230 ;; FIXME: cleanup and comment
15231 (let ((nowdecode (decode-time (current-time)))
15232 delta deltan deltaw deltadef year month day
15233 hour minute second wday pm h2 m2 tl wday1
15234 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15235 (setq org-read-date-analyze-futurep nil
15236 org-read-date-analyze-forced-year nil)
15237 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15238 (setq ans "+0"))
15240 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15241 (setq ans (replace-match "" t t ans)
15242 deltan (car delta)
15243 deltaw (nth 1 delta)
15244 deltadef (nth 2 delta)))
15246 ;; Check if there is an iso week date in there
15247 ;; If yes, store the info and postpone interpreting it until the rest
15248 ;; of the parsing is done
15249 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15250 (setq iso-year (if (match-end 1)
15251 (org-small-year-to-year
15252 (string-to-number (match-string 1 ans))))
15253 iso-weekday (if (match-end 3)
15254 (string-to-number (match-string 3 ans)))
15255 iso-week (string-to-number (match-string 2 ans)))
15256 (setq ans (replace-match "" t t ans)))
15258 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15259 (when (string-match
15260 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15261 (setq year (if (match-end 2)
15262 (string-to-number (match-string 2 ans))
15263 (progn (setq kill-year t)
15264 (string-to-number (format-time-string "%Y"))))
15265 month (string-to-number (match-string 3 ans))
15266 day (string-to-number (match-string 4 ans)))
15267 (if (< year 100) (setq year (+ 2000 year)))
15268 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15269 t nil ans)))
15271 ;; Help matching dotted european dates
15272 (when (string-match
15273 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15274 (setq year (if (match-end 3)
15275 (string-to-number (match-string 3 ans))
15276 (progn (setq kill-year t)
15277 (string-to-number (format-time-string "%Y"))))
15278 day (string-to-number (match-string 1 ans))
15279 month (string-to-number (match-string 2 ans))
15280 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15281 t nil ans)))
15283 ;; Help matching american dates, like 5/30 or 5/30/7
15284 (when (string-match
15285 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15286 (setq year (if (match-end 4)
15287 (string-to-number (match-string 4 ans))
15288 (progn (setq kill-year t)
15289 (string-to-number (format-time-string "%Y"))))
15290 month (string-to-number (match-string 1 ans))
15291 day (string-to-number (match-string 2 ans)))
15292 (if (< year 100) (setq year (+ 2000 year)))
15293 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15294 t nil ans)))
15295 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15296 ;; If there is a time with am/pm, and *no* time without it, we convert
15297 ;; so that matching will be successful.
15298 (loop for i from 1 to 2 do ; twice, for end time as well
15299 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15300 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15301 (setq hour (string-to-number (match-string 1 ans))
15302 minute (if (match-end 3)
15303 (string-to-number (match-string 3 ans))
15305 pm (equal ?p
15306 (string-to-char (downcase (match-string 4 ans)))))
15307 (if (and (= hour 12) (not pm))
15308 (setq hour 0)
15309 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15310 (setq ans (replace-match (format "%02d:%02d" hour minute)
15311 t t ans))))
15313 ;; Check if a time range is given as a duration
15314 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15315 (setq hour (string-to-number (match-string 1 ans))
15316 h2 (+ hour (string-to-number (match-string 3 ans)))
15317 minute (string-to-number (match-string 2 ans))
15318 m2 (+ minute (if (match-end 5) (string-to-number
15319 (match-string 5 ans))0)))
15320 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15321 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15322 t t ans)))
15324 ;; Check if there is a time range
15325 (when (boundp 'org-end-time-was-given)
15326 (setq org-time-was-given nil)
15327 (when (and (string-match org-plain-time-of-day-regexp ans)
15328 (match-end 8))
15329 (setq org-end-time-was-given (match-string 8 ans))
15330 (setq ans (concat (substring ans 0 (match-beginning 7))
15331 (substring ans (match-end 7))))))
15333 (setq tl (parse-time-string ans)
15334 day (or (nth 3 tl) (nth 3 defdecode))
15335 month (or (nth 4 tl)
15336 (if (and org-read-date-prefer-future
15337 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15338 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15339 (nth 4 defdecode)))
15340 year (or (and (not kill-year) (nth 5 tl))
15341 (if (and org-read-date-prefer-future
15342 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15343 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15344 (nth 5 defdecode)))
15345 hour (or (nth 2 tl) (nth 2 defdecode))
15346 minute (or (nth 1 tl) (nth 1 defdecode))
15347 second (or (nth 0 tl) 0)
15348 wday (nth 6 tl))
15350 (when (and (eq org-read-date-prefer-future 'time)
15351 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15352 (equal day (nth 3 nowdecode))
15353 (equal month (nth 4 nowdecode))
15354 (equal year (nth 5 nowdecode))
15355 (nth 2 tl)
15356 (or (< (nth 2 tl) (nth 2 nowdecode))
15357 (and (= (nth 2 tl) (nth 2 nowdecode))
15358 (nth 1 tl)
15359 (< (nth 1 tl) (nth 1 nowdecode)))))
15360 (setq day (1+ day)
15361 futurep t))
15363 ;; Special date definitions below
15364 (cond
15365 (iso-week
15366 ;; There was an iso week
15367 (require 'cal-iso)
15368 (setq futurep nil)
15369 (setq year (or iso-year year)
15370 day (or iso-weekday wday 1)
15371 wday nil ; to make sure that the trigger below does not match
15372 iso-date (calendar-gregorian-from-absolute
15373 (calendar-absolute-from-iso
15374 (list iso-week day year))))
15375 ; FIXME: Should we also push ISO weeks into the future?
15376 ; (when (and org-read-date-prefer-future
15377 ; (not iso-year)
15378 ; (< (calendar-absolute-from-gregorian iso-date)
15379 ; (time-to-days (current-time))))
15380 ; (setq year (1+ year)
15381 ; iso-date (calendar-gregorian-from-absolute
15382 ; (calendar-absolute-from-iso
15383 ; (list iso-week day year)))))
15384 (setq month (car iso-date)
15385 year (nth 2 iso-date)
15386 day (nth 1 iso-date)))
15387 (deltan
15388 (setq futurep nil)
15389 (unless deltadef
15390 (let ((now (decode-time (current-time))))
15391 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15392 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15393 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15394 ((equal deltaw "m") (setq month (+ month deltan)))
15395 ((equal deltaw "y") (setq year (+ year deltan)))))
15396 ((and wday (not (nth 3 tl)))
15397 (setq futurep nil)
15398 ;; Weekday was given, but no day, so pick that day in the week
15399 ;; on or after the derived date.
15400 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15401 (unless (equal wday wday1)
15402 (setq day (+ day (% (- wday wday1 -7) 7))))))
15403 (if (and (boundp 'org-time-was-given)
15404 (nth 2 tl))
15405 (setq org-time-was-given t))
15406 (if (< year 100) (setq year (+ 2000 year)))
15407 ;; Check of the date is representable
15408 (if org-read-date-force-compatible-dates
15409 (progn
15410 (if (< year 1970)
15411 (setq year 1970 org-read-date-analyze-forced-year t))
15412 (if (> year 2037)
15413 (setq year 2037 org-read-date-analyze-forced-year t)))
15414 (condition-case nil
15415 (ignore (encode-time second minute hour day month year))
15416 (error
15417 (setq year (nth 5 defdecode))
15418 (setq org-read-date-analyze-forced-year t))))
15419 (setq org-read-date-analyze-futurep futurep)
15420 (list second minute hour day month year)))
15422 (defvar parse-time-weekdays)
15424 (defun org-read-date-get-relative (s today default)
15425 "Check string S for special relative date string.
15426 TODAY and DEFAULT are internal times, for today and for a default.
15427 Return shift list (N what def-flag)
15428 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15429 N is the number of WHATs to shift.
15430 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15431 the DEFAULT date rather than TODAY."
15432 (require 'parse-time)
15433 (when (and
15434 (string-match
15435 (concat
15436 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15437 "\\([0-9]+\\)?"
15438 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15439 "\\([ \t]\\|$\\)") s)
15440 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15441 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15442 (string-to-char (substring (match-string 1 s) -1))
15443 ?+))
15444 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15445 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15446 (what (if (match-end 3) (match-string 3 s) "d"))
15447 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15448 (date (if rel default today))
15449 (wday (nth 6 (decode-time date)))
15450 delta)
15451 (if wday1
15452 (progn
15453 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15454 (if (= dir ?-) (setq delta (- delta 7)))
15455 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15456 (list delta "d" rel))
15457 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15459 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15460 "Turn a user-specified date into the internal representation.
15461 The internal representation needed by the calendar is (month day year).
15462 This is a wrapper to handle the brain-dead convention in calendar that
15463 user function argument order change dependent on argument order."
15464 (if (boundp 'calendar-date-style)
15465 (cond
15466 ((eq calendar-date-style 'american)
15467 (list arg1 arg2 arg3))
15468 ((eq calendar-date-style 'european)
15469 (list arg2 arg1 arg3))
15470 ((eq calendar-date-style 'iso)
15471 (list arg2 arg3 arg1)))
15472 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15473 (if (org-bound-and-true-p european-calendar-style)
15474 (list arg2 arg1 arg3)
15475 (list arg1 arg2 arg3)))))
15477 (defun org-eval-in-calendar (form &optional keepdate)
15478 "Eval FORM in the calendar window and return to current window.
15479 Also, store the cursor date in variable org-ans2."
15480 (let ((sf (selected-frame))
15481 (sw (selected-window)))
15482 (select-window (get-buffer-window "*Calendar*" t))
15483 (eval form)
15484 (when (and (not keepdate) (calendar-cursor-to-date))
15485 (let* ((date (calendar-cursor-to-date))
15486 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15487 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15488 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15489 (select-window sw)
15490 (org-select-frame-set-input-focus sf)))
15492 (defun org-calendar-select ()
15493 "Return to `org-read-date' with the date currently selected.
15494 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15495 (interactive)
15496 (when (calendar-cursor-to-date)
15497 (let* ((date (calendar-cursor-to-date))
15498 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15499 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15500 (if (active-minibuffer-window) (exit-minibuffer))))
15502 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15503 "Insert a date stamp for the date given by the internal TIME.
15504 WITH-HM means use the stamp format that includes the time of the day.
15505 INACTIVE means use square brackets instead of angular ones, so that the
15506 stamp will not contribute to the agenda.
15507 PRE and POST are optional strings to be inserted before and after the
15508 stamp.
15509 The command returns the inserted time stamp."
15510 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15511 stamp)
15512 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15513 (insert-before-markers (or pre ""))
15514 (when (listp extra)
15515 (setq extra (car extra))
15516 (if (and (stringp extra)
15517 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15518 (setq extra (format "-%02d:%02d"
15519 (string-to-number (match-string 1 extra))
15520 (string-to-number (match-string 2 extra))))
15521 (setq extra nil)))
15522 (when extra
15523 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15524 (insert-before-markers (setq stamp (format-time-string fmt time)))
15525 (insert-before-markers (or post ""))
15526 (setq org-last-inserted-timestamp stamp)))
15528 (defun org-toggle-time-stamp-overlays ()
15529 "Toggle the use of custom time stamp formats."
15530 (interactive)
15531 (setq org-display-custom-times (not org-display-custom-times))
15532 (unless org-display-custom-times
15533 (let ((p (point-min)) (bmp (buffer-modified-p)))
15534 (while (setq p (next-single-property-change p 'display))
15535 (if (and (get-text-property p 'display)
15536 (eq (get-text-property p 'face) 'org-date))
15537 (remove-text-properties
15538 p (setq p (next-single-property-change p 'display))
15539 '(display t))))
15540 (set-buffer-modified-p bmp)))
15541 (if (featurep 'xemacs)
15542 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15543 (org-restart-font-lock)
15544 (setq org-table-may-need-update t)
15545 (if org-display-custom-times
15546 (message "Time stamps are overlaid with custom format")
15547 (message "Time stamp overlays removed")))
15549 (defun org-display-custom-time (beg end)
15550 "Overlay modified time stamp format over timestamp between BEG and END."
15551 (let* ((ts (buffer-substring beg end))
15552 t1 w1 with-hm tf time str w2 (off 0))
15553 (save-match-data
15554 (setq t1 (org-parse-time-string ts t))
15555 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15556 (setq off (- (match-end 0) (match-beginning 0)))))
15557 (setq end (- end off))
15558 (setq w1 (- end beg)
15559 with-hm (and (nth 1 t1) (nth 2 t1))
15560 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15561 time (org-fix-decoded-time t1)
15562 str (org-add-props
15563 (format-time-string
15564 (substring tf 1 -1) (apply 'encode-time time))
15565 nil 'mouse-face 'highlight)
15566 w2 (length str))
15567 (if (not (= w2 w1))
15568 (add-text-properties (1+ beg) (+ 2 beg)
15569 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15570 (if (featurep 'xemacs)
15571 (progn
15572 (put-text-property beg end 'invisible t)
15573 (put-text-property beg end 'end-glyph (make-glyph str)))
15574 (put-text-property beg end 'display str))))
15576 (defun org-translate-time (string)
15577 "Translate all timestamps in STRING to custom format.
15578 But do this only if the variable `org-display-custom-times' is set."
15579 (when org-display-custom-times
15580 (save-match-data
15581 (let* ((start 0)
15582 (re org-ts-regexp-both)
15583 t1 with-hm inactive tf time str beg end)
15584 (while (setq start (string-match re string start))
15585 (setq beg (match-beginning 0)
15586 end (match-end 0)
15587 t1 (save-match-data
15588 (org-parse-time-string (substring string beg end) t))
15589 with-hm (and (nth 1 t1) (nth 2 t1))
15590 inactive (equal (substring string beg (1+ beg)) "[")
15591 tf (funcall (if with-hm 'cdr 'car)
15592 org-time-stamp-custom-formats)
15593 time (org-fix-decoded-time t1)
15594 str (format-time-string
15595 (concat
15596 (if inactive "[" "<") (substring tf 1 -1)
15597 (if inactive "]" ">"))
15598 (apply 'encode-time time))
15599 string (replace-match str t t string)
15600 start (+ start (length str)))))))
15601 string)
15603 (defun org-fix-decoded-time (time)
15604 "Set 0 instead of nil for the first 6 elements of time.
15605 Don't touch the rest."
15606 (let ((n 0))
15607 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15609 (defun org-days-to-time (timestamp-string)
15610 "Difference between TIMESTAMP-STRING and now in days."
15611 (- (time-to-days (org-time-string-to-time timestamp-string))
15612 (time-to-days (current-time))))
15614 (defun org-deadline-close (timestamp-string &optional ndays)
15615 "Is the time in TIMESTAMP-STRING close to the current date?"
15616 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15617 (and (< (org-days-to-time timestamp-string) ndays)
15618 (not (org-entry-is-done-p))))
15620 (defun org-get-wdays (ts)
15621 "Get the deadline lead time appropriate for timestring TS."
15622 (cond
15623 ((<= org-deadline-warning-days 0)
15624 ;; 0 or negative, enforce this value no matter what
15625 (- org-deadline-warning-days))
15626 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15627 ;; lead time is specified.
15628 (floor (* (string-to-number (match-string 1 ts))
15629 (cdr (assoc (match-string 2 ts)
15630 '(("d" . 1) ("w" . 7)
15631 ("m" . 30.4) ("y" . 365.25)))))))
15632 ;; go for the default.
15633 (t org-deadline-warning-days)))
15635 (defun org-calendar-select-mouse (ev)
15636 "Return to `org-read-date' with the date currently selected.
15637 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15638 (interactive "e")
15639 (mouse-set-point ev)
15640 (when (calendar-cursor-to-date)
15641 (let* ((date (calendar-cursor-to-date))
15642 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15643 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15644 (if (active-minibuffer-window) (exit-minibuffer))))
15646 (defun org-check-deadlines (ndays)
15647 "Check if there are any deadlines due or past due.
15648 A deadline is considered due if it happens within `org-deadline-warning-days'
15649 days from today's date. If the deadline appears in an entry marked DONE,
15650 it is not shown. The prefix arg NDAYS can be used to test that many
15651 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15652 (interactive "P")
15653 (let* ((org-warn-days
15654 (cond
15655 ((equal ndays '(4)) 100000)
15656 (ndays (prefix-numeric-value ndays))
15657 (t (abs org-deadline-warning-days))))
15658 (case-fold-search nil)
15659 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15660 (callback
15661 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15663 (message "%d deadlines past-due or due within %d days"
15664 (org-occur regexp nil callback)
15665 org-warn-days)))
15667 (defun org-check-before-date (date)
15668 "Check if there are deadlines or scheduled entries before DATE."
15669 (interactive (list (org-read-date)))
15670 (let ((case-fold-search nil)
15671 (regexp (concat "\\<\\(" org-deadline-string
15672 "\\|" org-scheduled-string
15673 "\\) *<\\([^>]+\\)>"))
15674 (callback
15675 (lambda () (time-less-p
15676 (org-time-string-to-time (match-string 2))
15677 (org-time-string-to-time date)))))
15678 (message "%d entries before %s"
15679 (org-occur regexp nil callback) date)))
15681 (defun org-check-after-date (date)
15682 "Check if there are deadlines or scheduled entries after DATE."
15683 (interactive (list (org-read-date)))
15684 (let ((case-fold-search nil)
15685 (regexp (concat "\\<\\(" org-deadline-string
15686 "\\|" org-scheduled-string
15687 "\\) *<\\([^>]+\\)>"))
15688 (callback
15689 (lambda () (not
15690 (time-less-p
15691 (org-time-string-to-time (match-string 2))
15692 (org-time-string-to-time date))))))
15693 (message "%d entries after %s"
15694 (org-occur regexp nil callback) date)))
15696 (defun org-check-dates-range (start-date end-date)
15697 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15698 (interactive (list (org-read-date nil nil nil "Range starts")
15699 (org-read-date nil nil nil "Range end")))
15700 (let ((case-fold-search nil)
15701 (regexp (concat "\\<\\(" org-deadline-string
15702 "\\|" org-scheduled-string
15703 "\\) *<\\([^>]+\\)>"))
15704 (callback
15705 (lambda ()
15706 (let ((match (match-string 2)))
15707 (and
15708 (not (time-less-p
15709 (org-time-string-to-time match)
15710 (org-time-string-to-time start-date)))
15711 (time-less-p
15712 (org-time-string-to-time match)
15713 (org-time-string-to-time end-date)))))))
15714 (message "%d entries between %s and %s"
15715 (org-occur regexp nil callback) start-date end-date)))
15717 (defun org-evaluate-time-range (&optional to-buffer)
15718 "Evaluate a time range by computing the difference between start and end.
15719 Normally the result is just printed in the echo area, but with prefix arg
15720 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15721 If the time range is actually in a table, the result is inserted into the
15722 next column.
15723 For time difference computation, a year is assumed to be exactly 365
15724 days in order to avoid rounding problems."
15725 (interactive "P")
15727 (org-clock-update-time-maybe)
15728 (save-excursion
15729 (unless (org-at-date-range-p t)
15730 (goto-char (point-at-bol))
15731 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15732 (if (not (org-at-date-range-p t))
15733 (error "Not at a time-stamp range, and none found in current line")))
15734 (let* ((ts1 (match-string 1))
15735 (ts2 (match-string 2))
15736 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15737 (match-end (match-end 0))
15738 (time1 (org-time-string-to-time ts1))
15739 (time2 (org-time-string-to-time ts2))
15740 (t1 (org-float-time time1))
15741 (t2 (org-float-time time2))
15742 (diff (abs (- t2 t1)))
15743 (negative (< (- t2 t1) 0))
15744 ;; (ys (floor (* 365 24 60 60)))
15745 (ds (* 24 60 60))
15746 (hs (* 60 60))
15747 (fy "%dy %dd %02d:%02d")
15748 (fy1 "%dy %dd")
15749 (fd "%dd %02d:%02d")
15750 (fd1 "%dd")
15751 (fh "%02d:%02d")
15752 y d h m align)
15753 (if havetime
15754 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15756 d (floor (/ diff ds)) diff (mod diff ds)
15757 h (floor (/ diff hs)) diff (mod diff hs)
15758 m (floor (/ diff 60)))
15759 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15761 d (floor (+ (/ diff ds) 0.5))
15762 h 0 m 0))
15763 (if (not to-buffer)
15764 (message "%s" (org-make-tdiff-string y d h m))
15765 (if (org-at-table-p)
15766 (progn
15767 (goto-char match-end)
15768 (setq align t)
15769 (and (looking-at " *|") (goto-char (match-end 0))))
15770 (goto-char match-end))
15771 (if (looking-at
15772 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15773 (replace-match ""))
15774 (if negative (insert " -"))
15775 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15776 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15777 (insert " " (format fh h m))))
15778 (if align (org-table-align))
15779 (message "Time difference inserted")))))
15781 (defun org-make-tdiff-string (y d h m)
15782 (let ((fmt "")
15783 (l nil))
15784 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15785 l (push y l)))
15786 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15787 l (push d l)))
15788 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15789 l (push h l)))
15790 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15791 l (push m l)))
15792 (apply 'format fmt (nreverse l))))
15794 (defun org-time-string-to-time (s &optional buffer pos)
15795 (condition-case errdata
15796 (apply 'encode-time (org-parse-time-string s))
15797 (error (error "Bad timestamp `%s'%s\nError was: %s"
15798 s (if (not (and buffer pos))
15800 (format " at %d in buffer `%s'" pos buffer))
15801 (cdr errdata)))))
15803 (defun org-time-string-to-seconds (s)
15804 (org-float-time (org-time-string-to-time s)))
15806 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15807 "Convert a time stamp to an absolute day number.
15808 If there is a specifier for a cyclic time stamp, get the closest date to
15809 DAYNR.
15810 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15811 The variable date is bound by the calendar when this is called."
15812 (cond
15813 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15814 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15815 daynr
15816 (+ daynr 1000)))
15817 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15818 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15819 (time-to-days (current-time))) (match-string 0 s)
15820 prefer show-all))
15821 (t (time-to-days
15822 (condition-case errdata
15823 (apply 'encode-time (org-parse-time-string s))
15824 (error (error "Bad timestamp `%s'%s\nError was: %s"
15825 s (if (not (and buffer pos))
15827 (format " at %d in buffer `%s'" pos buffer))
15828 (cdr errdata))))))))
15830 (defun org-days-to-iso-week (days)
15831 "Return the iso week number."
15832 (require 'cal-iso)
15833 (car (calendar-iso-from-absolute days)))
15835 (defun org-small-year-to-year (year)
15836 "Convert 2-digit years into 4-digit years.
15837 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15838 The year 2000 cannot be abbreviated. Any year larger than 99
15839 is returned unchanged."
15840 (if (< year 38)
15841 (setq year (+ 2000 year))
15842 (if (< year 100)
15843 (setq year (+ 1900 year))))
15844 year)
15846 (defun org-time-from-absolute (d)
15847 "Return the time corresponding to date D.
15848 D may be an absolute day number, or a calendar-type list (month day year)."
15849 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15850 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15852 (defun org-calendar-holiday ()
15853 "List of holidays, for Diary display in Org-mode."
15854 (require 'holidays)
15855 (let ((hl (funcall
15856 (if (fboundp 'calendar-check-holidays)
15857 'calendar-check-holidays 'check-calendar-holidays) date)))
15858 (if hl (mapconcat 'identity hl "; "))))
15860 (defun org-diary-sexp-entry (sexp entry date)
15861 "Process a SEXP diary ENTRY for DATE."
15862 (require 'diary-lib)
15863 (let ((result (if calendar-debug-sexp
15864 (let ((stack-trace-on-error t))
15865 (eval (car (read-from-string sexp))))
15866 (condition-case nil
15867 (eval (car (read-from-string sexp)))
15868 (error
15869 (beep)
15870 (message "Bad sexp at line %d in %s: %s"
15871 (org-current-line)
15872 (buffer-file-name) sexp)
15873 (sleep-for 2))))))
15874 (cond ((stringp result) (split-string result "; "))
15875 ((and (consp result)
15876 (not (consp (cdr result)))
15877 (stringp (cdr result))) (cdr result))
15878 ((and (consp result)
15879 (stringp (car result))) result)
15880 (result entry)
15881 (t nil))))
15883 (defun org-diary-to-ical-string (frombuf)
15884 "Get iCalendar entries from diary entries in buffer FROMBUF.
15885 This uses the icalendar.el library."
15886 (let* ((tmpdir (if (featurep 'xemacs)
15887 (temp-directory)
15888 temporary-file-directory))
15889 (tmpfile (make-temp-name
15890 (expand-file-name "orgics" tmpdir)))
15891 buf rtn b e)
15892 (with-current-buffer frombuf
15893 (icalendar-export-region (point-min) (point-max) tmpfile)
15894 (setq buf (find-buffer-visiting tmpfile))
15895 (set-buffer buf)
15896 (goto-char (point-min))
15897 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15898 (setq b (match-beginning 0)))
15899 (goto-char (point-max))
15900 (if (re-search-backward "^END:VEVENT" nil t)
15901 (setq e (match-end 0)))
15902 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15903 (kill-buffer buf)
15904 (delete-file tmpfile)
15905 rtn))
15907 (defun org-closest-date (start current change prefer show-all)
15908 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15909 When PREFER is `past', return a date that is either CURRENT or past.
15910 When PREFER is `future', return a date that is either CURRENT or future.
15911 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15912 ;; Make the proper lists from the dates
15913 (catch 'exit
15914 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15915 dn dw sday cday n1 n2 n0
15916 d m y y1 y2 date1 date2 nmonths nm ny m2)
15918 (setq start (org-date-to-gregorian start)
15919 current (org-date-to-gregorian
15920 (if show-all
15921 current
15922 (time-to-days (current-time))))
15923 sday (calendar-absolute-from-gregorian start)
15924 cday (calendar-absolute-from-gregorian current))
15926 (if (<= cday sday) (throw 'exit sday))
15928 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15929 (setq dn (string-to-number (match-string 1 change))
15930 dw (cdr (assoc (match-string 2 change) a1)))
15931 (error "Invalid change specifier: %s" change))
15932 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15933 (cond
15934 ((eq dw 'day)
15935 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15936 n2 (+ n1 dn)))
15937 ((eq dw 'year)
15938 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15939 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15940 (setq date1 (list m d y1)
15941 n1 (calendar-absolute-from-gregorian date1)
15942 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15943 n2 (calendar-absolute-from-gregorian date2)))
15944 ((eq dw 'month)
15945 ;; approx number of month between the two dates
15946 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15947 ;; How often does dn fit in there?
15948 (setq d (nth 1 start) m (car start) y (nth 2 start)
15949 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15950 m (+ m nm)
15951 ny (floor (/ m 12))
15952 y (+ y ny)
15953 m (- m (* ny 12)))
15954 (while (> m 12) (setq m (- m 12) y (1+ y)))
15955 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15956 (setq m2 (+ m dn) y2 y)
15957 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15958 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15959 (while (<= n2 cday)
15960 (setq n1 n2 m m2 y y2)
15961 (setq m2 (+ m dn) y2 y)
15962 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15963 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15964 ;; Make sure n1 is the earlier date
15965 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15966 (if show-all
15967 (cond
15968 ((eq prefer 'past) (if (= cday n2) n2 n1))
15969 ((eq prefer 'future) (if (= cday n1) n1 n2))
15970 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15971 (cond
15972 ((eq prefer 'past) (if (= cday n2) n2 n1))
15973 ((eq prefer 'future) (if (= cday n1) n1 n2))
15974 (t (if (= cday n1) n1 n2)))))))
15976 (defun org-date-to-gregorian (date)
15977 "Turn any specification of DATE into a Gregorian date for the calendar."
15978 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15979 ((and (listp date) (= (length date) 3)) date)
15980 ((stringp date)
15981 (setq date (org-parse-time-string date))
15982 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15983 ((listp date)
15984 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15986 (defun org-parse-time-string (s &optional nodefault)
15987 "Parse the standard Org-mode time string.
15988 This should be a lot faster than the normal `parse-time-string'.
15989 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15990 hour and minute fields will be nil if not given."
15991 (if (string-match org-ts-regexp0 s)
15992 (list 0
15993 (if (or (match-beginning 8) (not nodefault))
15994 (string-to-number (or (match-string 8 s) "0")))
15995 (if (or (match-beginning 7) (not nodefault))
15996 (string-to-number (or (match-string 7 s) "0")))
15997 (string-to-number (match-string 4 s))
15998 (string-to-number (match-string 3 s))
15999 (string-to-number (match-string 2 s))
16000 nil nil nil)
16001 (error "Not a standard Org-mode time string: %s" s)))
16003 (defun org-timestamp-up (&optional arg)
16004 "Increase the date item at the cursor by one.
16005 If the cursor is on the year, change the year. If it is on the month,
16006 the day or the time, change that.
16007 With prefix ARG, change by that many units."
16008 (interactive "p")
16009 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16011 (defun org-timestamp-down (&optional arg)
16012 "Decrease the date item at the cursor by one.
16013 If the cursor is on the year, change the year. If it is on the month,
16014 the day or the time, change that.
16015 With prefix ARG, change by that many units."
16016 (interactive "p")
16017 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16019 (defun org-timestamp-up-day (&optional arg)
16020 "Increase the date in the time stamp by one day.
16021 With prefix ARG, change that many days."
16022 (interactive "p")
16023 (if (and (not (org-at-timestamp-p t))
16024 (org-at-heading-p))
16025 (org-todo 'up)
16026 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16028 (defun org-timestamp-down-day (&optional arg)
16029 "Decrease the date in the time stamp by one day.
16030 With prefix ARG, change that many days."
16031 (interactive "p")
16032 (if (and (not (org-at-timestamp-p t))
16033 (org-at-heading-p))
16034 (org-todo 'down)
16035 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16037 (defun org-at-timestamp-p (&optional inactive-ok)
16038 "Determine if the cursor is in or at a timestamp."
16039 (interactive)
16040 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16041 (pos (point))
16042 (ans (or (looking-at tsr)
16043 (save-excursion
16044 (skip-chars-backward "^[<\n\r\t")
16045 (if (> (point) (point-min)) (backward-char 1))
16046 (and (looking-at tsr)
16047 (> (- (match-end 0) pos) -1))))))
16048 (and ans
16049 (boundp 'org-ts-what)
16050 (setq org-ts-what
16051 (cond
16052 ((= pos (match-beginning 0)) 'bracket)
16053 ;; Point is considered to be "on the bracket" whether
16054 ;; it's really on it or right after it.
16055 ((or (= pos (1- (match-end 0)))
16056 (= pos (match-end 0))) 'bracket)
16057 ((org-pos-in-match-range pos 2) 'year)
16058 ((org-pos-in-match-range pos 3) 'month)
16059 ((org-pos-in-match-range pos 7) 'hour)
16060 ((org-pos-in-match-range pos 8) 'minute)
16061 ((or (org-pos-in-match-range pos 4)
16062 (org-pos-in-match-range pos 5)) 'day)
16063 ((and (> pos (or (match-end 8) (match-end 5)))
16064 (< pos (match-end 0)))
16065 (- pos (or (match-end 8) (match-end 5))))
16066 (t 'day))))
16067 ans))
16069 (defun org-toggle-timestamp-type ()
16070 "Toggle the type (<active> or [inactive]) of a time stamp."
16071 (interactive)
16072 (when (org-at-timestamp-p t)
16073 (let ((beg (match-beginning 0)) (end (match-end 0))
16074 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16075 (save-excursion
16076 (goto-char beg)
16077 (while (re-search-forward "[][<>]" end t)
16078 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16079 t t)))
16080 (message "Timestamp is now %sactive"
16081 (if (equal (char-after beg) ?<) "" "in")))))
16083 (defun org-timestamp-change (n &optional what updown)
16084 "Change the date in the time stamp at point.
16085 The date will be changed by N times WHAT. WHAT can be `day', `month',
16086 `year', `minute', `second'. If WHAT is not given, the cursor position
16087 in the timestamp determines what will be changed."
16088 (let ((origin (point)) origin-cat
16089 with-hm inactive
16090 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16091 org-ts-what
16092 extra rem
16093 ts time time0)
16094 (if (not (org-at-timestamp-p t))
16095 (error "Not at a timestamp"))
16096 (if (and (not what) (eq org-ts-what 'bracket))
16097 (org-toggle-timestamp-type)
16098 ;; Point isn't on brackets. Remember the part of the time-stamp
16099 ;; the point was in. Indeed, size of time-stamps may change,
16100 ;; but point must be kept in the same category nonetheless.
16101 (setq origin-cat org-ts-what)
16102 (if (and (not what) (not (eq org-ts-what 'day))
16103 org-display-custom-times
16104 (get-text-property (point) 'display)
16105 (not (get-text-property (1- (point)) 'display)))
16106 (setq org-ts-what 'day))
16107 (setq org-ts-what (or what org-ts-what)
16108 inactive (= (char-after (match-beginning 0)) ?\[)
16109 ts (match-string 0))
16110 (replace-match "")
16111 (if (string-match
16112 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16114 (setq extra (match-string 1 ts)))
16115 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16116 (setq with-hm t))
16117 (setq time0 (org-parse-time-string ts))
16118 (when (and updown
16119 (eq org-ts-what 'minute)
16120 (not current-prefix-arg))
16121 ;; This looks like s-up and s-down. Change by one rounding step.
16122 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16123 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16124 (setcar (cdr time0) (+ (nth 1 time0)
16125 (if (> n 0) (- rem) (- dm rem))))))
16126 (setq time
16127 (encode-time (or (car time0) 0)
16128 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16129 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16130 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16131 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16132 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16133 (nthcdr 6 time0)))
16134 (when (and (member org-ts-what '(hour minute))
16135 extra
16136 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16137 (setq extra (org-modify-ts-extra
16138 extra
16139 (if (eq org-ts-what 'hour) 2 5)
16140 n dm)))
16141 (when (integerp org-ts-what)
16142 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16143 (if (eq what 'calendar)
16144 (let ((cal-date (org-get-date-from-calendar)))
16145 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16146 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16147 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16148 (setcar time0 (or (car time0) 0))
16149 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16150 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16151 (setq time (apply 'encode-time time0))))
16152 ;; Insert the new time-stamp, and ensure point stays in the same
16153 ;; category as before (i.e. not after the last position in that
16154 ;; category).
16155 (let ((pos (point)))
16156 ;; Stay before inserted string. `save-excursion' is of no use.
16157 (setq org-last-changed-timestamp
16158 (org-insert-time-stamp time with-hm inactive nil nil extra))
16159 (goto-char pos))
16160 (save-match-data
16161 (looking-at org-ts-regexp3)
16162 (goto-char (cond
16163 ;; `day' category ends before `hour' if any, or at
16164 ;; the end of the day name.
16165 ((eq origin-cat 'day)
16166 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16167 ((eq origin-cat 'hour) (min (match-end 7) origin))
16168 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16169 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16170 ;; `year' and `month' have both fixed size: point
16171 ;; couldn't have moved into another part.
16172 (t origin))))
16173 ;; Update clock if on a CLOCK line.
16174 (org-clock-update-time-maybe)
16175 ;; Try to recenter the calendar window, if any.
16176 (if (and org-calendar-follow-timestamp-change
16177 (get-buffer-window "*Calendar*" t)
16178 (memq org-ts-what '(day month year)))
16179 (org-recenter-calendar (time-to-days time))))))
16181 (defun org-modify-ts-extra (s pos n dm)
16182 "Change the different parts of the lead-time and repeat fields in timestamp."
16183 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16184 ng h m new rem)
16185 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16186 (cond
16187 ((or (org-pos-in-match-range pos 2)
16188 (org-pos-in-match-range pos 3))
16189 (setq m (string-to-number (match-string 3 s))
16190 h (string-to-number (match-string 2 s)))
16191 (if (org-pos-in-match-range pos 2)
16192 (setq h (+ h n))
16193 (setq n (* dm (org-no-warnings (signum n))))
16194 (when (not (= 0 (setq rem (% m dm))))
16195 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16196 (setq m (+ m n)))
16197 (if (< m 0) (setq m (+ m 60) h (1- h)))
16198 (if (> m 59) (setq m (- m 60) h (1+ h)))
16199 (setq h (min 24 (max 0 h)))
16200 (setq ng 1 new (format "-%02d:%02d" h m)))
16201 ((org-pos-in-match-range pos 6)
16202 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16203 ((org-pos-in-match-range pos 5)
16204 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16206 ((org-pos-in-match-range pos 9)
16207 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16208 ((org-pos-in-match-range pos 8)
16209 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16211 (when ng
16212 (setq s (concat
16213 (substring s 0 (match-beginning ng))
16215 (substring s (match-end ng))))))
16218 (defun org-recenter-calendar (date)
16219 "If the calendar is visible, recenter it to DATE."
16220 (let ((cwin (get-buffer-window "*Calendar*" t)))
16221 (when cwin
16222 (let ((calendar-move-hook nil))
16223 (with-selected-window cwin
16224 (calendar-goto-date (if (listp date) date
16225 (calendar-gregorian-from-absolute date))))))))
16227 (defun org-goto-calendar (&optional arg)
16228 "Go to the Emacs calendar at the current date.
16229 If there is a time stamp in the current line, go to that date.
16230 A prefix ARG can be used to force the current date."
16231 (interactive "P")
16232 (let ((tsr org-ts-regexp) diff
16233 (calendar-move-hook nil)
16234 (calendar-view-holidays-initially-flag nil)
16235 (calendar-view-diary-initially-flag nil))
16236 (if (or (org-at-timestamp-p)
16237 (save-excursion
16238 (beginning-of-line 1)
16239 (looking-at (concat ".*" tsr))))
16240 (let ((d1 (time-to-days (current-time)))
16241 (d2 (time-to-days
16242 (org-time-string-to-time (match-string 1)))))
16243 (setq diff (- d2 d1))))
16244 (calendar)
16245 (calendar-goto-today)
16246 (if (and diff (not arg)) (calendar-forward-day diff))))
16248 (defun org-get-date-from-calendar ()
16249 "Return a list (month day year) of date at point in calendar."
16250 (with-current-buffer "*Calendar*"
16251 (save-match-data
16252 (calendar-cursor-to-date))))
16254 (defun org-date-from-calendar ()
16255 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16256 If there is already a time stamp at the cursor position, update it."
16257 (interactive)
16258 (if (org-at-timestamp-p t)
16259 (org-timestamp-change 0 'calendar)
16260 (let ((cal-date (org-get-date-from-calendar)))
16261 (org-insert-time-stamp
16262 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16264 (defun org-minutes-to-hh:mm-string (m)
16265 "Compute H:MM from a number of minutes."
16266 (let ((h (/ m 60)))
16267 (setq m (- m (* 60 h)))
16268 (format org-time-clocksum-format h m)))
16270 (defun org-hh:mm-string-to-minutes (s)
16271 "Convert a string H:MM to a number of minutes.
16272 If the string is just a number, interpret it as minutes.
16273 In fact, the first hh:mm or number in the string will be taken,
16274 there can be extra stuff in the string.
16275 If no number is found, the return value is 0."
16276 (cond
16277 ((integerp s) s)
16278 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16279 (+ (* (string-to-number (match-string 1 s)) 60)
16280 (string-to-number (match-string 2 s))))
16281 ((string-match "\\([0-9]+\\)" s)
16282 (string-to-number (match-string 1 s)))
16283 (t 0)))
16285 (defcustom org-effort-durations
16286 `(("h" . 60)
16287 ("d" . ,(* 60 8))
16288 ("w" . ,(* 60 8 5))
16289 ("m" . ,(* 60 8 5 4))
16290 ("y" . ,(* 60 8 5 40)))
16291 "Conversion factor to minutes for an effort modifier.
16293 Each entry has the form (MODIFIER . MINUTES).
16295 In an effort string, a number followed by MODIFIER is multiplied
16296 by the specified number of MINUTES to obtain an effort in
16297 minutes.
16299 For example, if the value of this variable is ((\"hours\" . 60)), then an
16300 effort string \"2hours\" is equivalent to 120 minutes."
16301 :group 'org-agenda
16302 :version "24.1"
16303 :type '(alist :key-type (string :tag "Modifier")
16304 :value-type (number :tag "Minutes")))
16306 (defun org-duration-string-to-minutes (s)
16307 "Convert a duration string S to minutes.
16309 A bare number is interpreted as minutes, modifiers can be set by
16310 customizing `org-effort-durations' (which see).
16312 Entries containing a colon are interpreted as H:MM by
16313 `org-hh:mm-string-to-minutes'."
16314 (let ((result 0)
16315 (re (concat "\\([0-9]+\\) *\\("
16316 (regexp-opt (mapcar 'car org-effort-durations))
16317 "\\)")))
16318 (while (string-match re s)
16319 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16320 (string-to-number (match-string 1 s))))
16321 (setq s (replace-match "" nil t s)))
16322 (incf result (org-hh:mm-string-to-minutes s))
16323 result))
16325 ;;;; Files
16327 (defun org-save-all-org-buffers ()
16328 "Save all Org-mode buffers without user confirmation."
16329 (interactive)
16330 (message "Saving all Org-mode buffers...")
16331 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16332 (when (featurep 'org-id) (org-id-locations-save))
16333 (message "Saving all Org-mode buffers... done"))
16335 (defun org-revert-all-org-buffers ()
16336 "Revert all Org-mode buffers.
16337 Prompt for confirmation when there are unsaved changes.
16338 Be sure you know what you are doing before letting this function
16339 overwrite your changes.
16341 This function is useful in a setup where one tracks org files
16342 with a version control system, to revert on one machine after pulling
16343 changes from another. I believe the procedure must be like this:
16345 1. M-x org-save-all-org-buffers
16346 2. Pull changes from the other machine, resolve conflicts
16347 3. M-x org-revert-all-org-buffers"
16348 (interactive)
16349 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16350 (error "Abort"))
16351 (save-excursion
16352 (save-window-excursion
16353 (mapc
16354 (lambda (b)
16355 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16356 (with-current-buffer b buffer-file-name))
16357 (org-pop-to-buffer-same-window b)
16358 (revert-buffer t 'no-confirm)))
16359 (buffer-list))
16360 (when (and (featurep 'org-id) org-id-track-globally)
16361 (org-id-locations-load)))))
16363 ;;;; Agenda files
16365 ;;;###autoload
16366 (defun org-switchb (&optional arg)
16367 "Switch between Org buffers.
16368 With one prefix argument, restrict available buffers to files.
16369 With two prefix arguments, restrict available buffers to agenda files.
16371 Defaults to `iswitchb' for buffer name completion.
16372 Set `org-completion-use-ido' to make it use ido instead."
16373 (interactive "P")
16374 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16375 ((equal arg '(16)) (org-buffer-list 'agenda))
16376 (t (org-buffer-list))))
16377 (org-completion-use-iswitchb org-completion-use-iswitchb)
16378 (org-completion-use-ido org-completion-use-ido))
16379 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16380 (setq org-completion-use-iswitchb t))
16381 (org-pop-to-buffer-same-window
16382 (org-icompleting-read "Org buffer: "
16383 (mapcar 'list (mapcar 'buffer-name blist))
16384 nil t))))
16386 ;;; Define some older names previously used for this functionality
16387 ;;;###autoload
16388 (defalias 'org-ido-switchb 'org-switchb)
16389 ;;;###autoload
16390 (defalias 'org-iswitchb 'org-switchb)
16392 (defun org-buffer-list (&optional predicate exclude-tmp)
16393 "Return a list of Org buffers.
16394 PREDICATE can be `export', `files' or `agenda'.
16396 export restrict the list to Export buffers.
16397 files restrict the list to buffers visiting Org files.
16398 agenda restrict the list to buffers visiting agenda files.
16400 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16401 (let* ((bfn nil)
16402 (agenda-files (and (eq predicate 'agenda)
16403 (mapcar 'file-truename (org-agenda-files t))))
16404 (filter
16405 (cond
16406 ((eq predicate 'files)
16407 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16408 ((eq predicate 'export)
16409 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16410 ((eq predicate 'agenda)
16411 (lambda (b)
16412 (with-current-buffer b
16413 (and (eq major-mode 'org-mode)
16414 (setq bfn (buffer-file-name b))
16415 (member (file-truename bfn) agenda-files)))))
16416 (t (lambda (b) (with-current-buffer b
16417 (or (eq major-mode 'org-mode)
16418 (string-match "\*Org .*Export"
16419 (buffer-name b)))))))))
16420 (delq nil
16421 (mapcar
16422 (lambda(b)
16423 (if (and (funcall filter b)
16424 (or (not exclude-tmp)
16425 (not (string-match "tmp" (buffer-name b)))))
16427 nil))
16428 (buffer-list)))))
16430 (defun org-agenda-files (&optional unrestricted archives)
16431 "Get the list of agenda files.
16432 Optional UNRESTRICTED means return the full list even if a restriction
16433 is currently in place.
16434 When ARCHIVES is t, include all archive files that are really being
16435 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16436 `org-agenda-archives-mode' is t."
16437 (let ((files
16438 (cond
16439 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16440 ((stringp org-agenda-files) (org-read-agenda-file-list))
16441 ((listp org-agenda-files) org-agenda-files)
16442 (t (error "Invalid value of `org-agenda-files'")))))
16443 (setq files (apply 'append
16444 (mapcar (lambda (f)
16445 (if (file-directory-p f)
16446 (directory-files
16447 f t org-agenda-file-regexp)
16448 (list f)))
16449 files)))
16450 (when org-agenda-skip-unavailable-files
16451 (setq files (delq nil
16452 (mapcar (function
16453 (lambda (file)
16454 (and (file-readable-p file) file)))
16455 files))))
16456 (when (or (eq archives t)
16457 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16458 (setq files (org-add-archive-files files)))
16459 files))
16461 (defun org-agenda-file-p (&optional file)
16462 "Return non-nil, if FILE is an agenda file.
16463 If FILE is omitted, use the file associated with the current
16464 buffer."
16465 (member (or file (buffer-file-name))
16466 (org-agenda-files t)))
16468 (defun org-edit-agenda-file-list ()
16469 "Edit the list of agenda files.
16470 Depending on setup, this either uses customize to edit the variable
16471 `org-agenda-files', or it visits the file that is holding the list. In the
16472 latter case, the buffer is set up in a way that saving it automatically kills
16473 the buffer and restores the previous window configuration."
16474 (interactive)
16475 (if (stringp org-agenda-files)
16476 (let ((cw (current-window-configuration)))
16477 (find-file org-agenda-files)
16478 (org-set-local 'org-window-configuration cw)
16479 (org-add-hook 'after-save-hook
16480 (lambda ()
16481 (set-window-configuration
16482 (prog1 org-window-configuration
16483 (kill-buffer (current-buffer))))
16484 (org-install-agenda-files-menu)
16485 (message "New agenda file list installed"))
16486 nil 'local)
16487 (message "%s" (substitute-command-keys
16488 "Edit list and finish with \\[save-buffer]")))
16489 (customize-variable 'org-agenda-files)))
16491 (defun org-store-new-agenda-file-list (list)
16492 "Set new value for the agenda file list and save it correctly."
16493 (if (stringp org-agenda-files)
16494 (let ((fe (org-read-agenda-file-list t)) b u)
16495 (while (setq b (find-buffer-visiting org-agenda-files))
16496 (kill-buffer b))
16497 (with-temp-file org-agenda-files
16498 (insert
16499 (mapconcat
16500 (lambda (f) ;; Keep un-expanded entries.
16501 (if (setq u (assoc f fe))
16502 (cdr u)
16504 list "\n")
16505 "\n")))
16506 (let ((org-mode-hook nil) (org-inhibit-startup t)
16507 (org-insert-mode-line-in-empty-file nil))
16508 (setq org-agenda-files list)
16509 (customize-save-variable 'org-agenda-files org-agenda-files))))
16511 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16512 "Read the list of agenda files from a file.
16513 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16514 filenames, used by `org-store-new-agenda-file-list' to write back
16515 un-expanded file names."
16516 (when (file-directory-p org-agenda-files)
16517 (error "`org-agenda-files' cannot be a single directory"))
16518 (when (stringp org-agenda-files)
16519 (with-temp-buffer
16520 (insert-file-contents org-agenda-files)
16521 (mapcar
16522 (lambda (f)
16523 (let ((e (expand-file-name (substitute-in-file-name f)
16524 org-directory)))
16525 (if pair-with-expansion
16526 (cons e f)
16527 e)))
16528 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16530 ;;;###autoload
16531 (defun org-cycle-agenda-files ()
16532 "Cycle through the files in `org-agenda-files'.
16533 If the current buffer visits an agenda file, find the next one in the list.
16534 If the current buffer does not, find the first agenda file."
16535 (interactive)
16536 (let* ((fs (org-agenda-files t))
16537 (files (append fs (list (car fs))))
16538 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16539 file)
16540 (unless files (error "No agenda files"))
16541 (catch 'exit
16542 (while (setq file (pop files))
16543 (if (equal (file-truename file) tcf)
16544 (when (car files)
16545 (find-file (car files))
16546 (throw 'exit t))))
16547 (find-file (car fs)))
16548 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16550 (defun org-agenda-file-to-front (&optional to-end)
16551 "Move/add the current file to the top of the agenda file list.
16552 If the file is not present in the list, it is added to the front. If it is
16553 present, it is moved there. With optional argument TO-END, add/move to the
16554 end of the list."
16555 (interactive "P")
16556 (let ((org-agenda-skip-unavailable-files nil)
16557 (file-alist (mapcar (lambda (x)
16558 (cons (file-truename x) x))
16559 (org-agenda-files t)))
16560 (ctf (file-truename buffer-file-name))
16561 x had)
16562 (setq x (assoc ctf file-alist) had x)
16564 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16565 (if to-end
16566 (setq file-alist (append (delq x file-alist) (list x)))
16567 (setq file-alist (cons x (delq x file-alist))))
16568 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16569 (org-install-agenda-files-menu)
16570 (message "File %s to %s of agenda file list"
16571 (if had "moved" "added") (if to-end "end" "front"))))
16573 (defun org-remove-file (&optional file)
16574 "Remove current file from the list of files in variable `org-agenda-files'.
16575 These are the files which are being checked for agenda entries.
16576 Optional argument FILE means use this file instead of the current."
16577 (interactive)
16578 (let* ((org-agenda-skip-unavailable-files nil)
16579 (file (or file buffer-file-name))
16580 (true-file (file-truename file))
16581 (afile (abbreviate-file-name file))
16582 (files (delq nil (mapcar
16583 (lambda (x)
16584 (if (equal true-file
16585 (file-truename x))
16586 nil x))
16587 (org-agenda-files t)))))
16588 (if (not (= (length files) (length (org-agenda-files t))))
16589 (progn
16590 (org-store-new-agenda-file-list files)
16591 (org-install-agenda-files-menu)
16592 (message "Removed file: %s" afile))
16593 (message "File was not in list: %s (not removed)" afile))))
16595 (defun org-file-menu-entry (file)
16596 (vector file (list 'find-file file) t))
16598 (defun org-check-agenda-file (file)
16599 "Make sure FILE exists. If not, ask user what to do."
16600 (when (not (file-exists-p file))
16601 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16602 (abbreviate-file-name file))
16603 (let ((r (downcase (read-char-exclusive))))
16604 (cond
16605 ((equal r ?r)
16606 (org-remove-file file)
16607 (throw 'nextfile t))
16608 (t (error "Abort"))))))
16610 (defun org-get-agenda-file-buffer (file)
16611 "Get a buffer visiting FILE. If the buffer needs to be created, add
16612 it to the list of buffers which might be released later."
16613 (let ((buf (org-find-base-buffer-visiting file)))
16614 (if buf
16615 buf ; just return it
16616 ;; Make a new buffer and remember it
16617 (setq buf (find-file-noselect file))
16618 (if buf (push buf org-agenda-new-buffers))
16619 buf)))
16621 (defun org-release-buffers (blist)
16622 "Release all buffers in list, asking the user for confirmation when needed.
16623 When a buffer is unmodified, it is just killed. When modified, it is saved
16624 \(if the user agrees) and then killed."
16625 (let (buf file)
16626 (while (setq buf (pop blist))
16627 (setq file (buffer-file-name buf))
16628 (when (and (buffer-modified-p buf)
16629 file
16630 (y-or-n-p (format "Save file %s? " file)))
16631 (with-current-buffer buf (save-buffer)))
16632 (kill-buffer buf))))
16634 (defun org-prepare-agenda-buffers (files)
16635 "Create buffers for all agenda files, protect archived trees and comments."
16636 (interactive)
16637 (let ((pa '(:org-archived t))
16638 (pc '(:org-comment t))
16639 (pall '(:org-archived t :org-comment t))
16640 (inhibit-read-only t)
16641 (rea (concat ":" org-archive-tag ":"))
16642 bmp file re)
16643 (save-excursion
16644 (save-restriction
16645 (while (setq file (pop files))
16646 (catch 'nextfile
16647 (if (bufferp file)
16648 (set-buffer file)
16649 (org-check-agenda-file file)
16650 (set-buffer (org-get-agenda-file-buffer file)))
16651 (widen)
16652 (setq bmp (buffer-modified-p))
16653 (org-refresh-category-properties)
16654 (setq org-todo-keywords-for-agenda
16655 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16656 (setq org-done-keywords-for-agenda
16657 (append org-done-keywords-for-agenda org-done-keywords))
16658 (setq org-todo-keyword-alist-for-agenda
16659 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16660 (setq org-drawers-for-agenda
16661 (append org-drawers-for-agenda org-drawers))
16662 (setq org-tag-alist-for-agenda
16663 (append org-tag-alist-for-agenda org-tag-alist))
16665 (save-excursion
16666 (remove-text-properties (point-min) (point-max) pall)
16667 (when org-agenda-skip-archived-trees
16668 (goto-char (point-min))
16669 (while (re-search-forward rea nil t)
16670 (if (org-at-heading-p t)
16671 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16672 (goto-char (point-min))
16673 (setq re (format org-heading-keyword-regexp-format
16674 org-comment-string))
16675 (while (re-search-forward re nil t)
16676 (add-text-properties
16677 (match-beginning 0) (org-end-of-subtree t) pc)))
16678 (set-buffer-modified-p bmp)))))
16679 (setq org-todo-keywords-for-agenda
16680 (org-uniquify org-todo-keywords-for-agenda))
16681 (setq org-todo-keyword-alist-for-agenda
16682 (org-uniquify org-todo-keyword-alist-for-agenda)
16683 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16685 ;;;; Embedded LaTeX
16687 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16688 "Keymap for the minor `org-cdlatex-mode'.")
16690 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16691 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16692 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16693 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16694 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16696 (defvar org-cdlatex-texmathp-advice-is-done nil
16697 "Flag remembering if we have applied the advice to texmathp already.")
16699 (define-minor-mode org-cdlatex-mode
16700 "Toggle the minor `org-cdlatex-mode'.
16701 This mode supports entering LaTeX environment and math in LaTeX fragments
16702 in Org-mode.
16703 \\{org-cdlatex-mode-map}"
16704 nil " OCDL" nil
16705 (when org-cdlatex-mode
16706 (require 'cdlatex)
16707 (run-hooks 'cdlatex-mode-hook)
16708 (cdlatex-compute-tables))
16709 (unless org-cdlatex-texmathp-advice-is-done
16710 (setq org-cdlatex-texmathp-advice-is-done t)
16711 (defadvice texmathp (around org-math-always-on activate)
16712 "Always return t in org-mode buffers.
16713 This is because we want to insert math symbols without dollars even outside
16714 the LaTeX math segments. If Orgmode thinks that point is actually inside
16715 an embedded LaTeX fragment, let texmathp do its job.
16716 \\[org-cdlatex-mode-map]"
16717 (interactive)
16718 (let (p)
16719 (cond
16720 ((not (eq major-mode 'org-mode)) ad-do-it)
16721 ((eq this-command 'cdlatex-math-symbol)
16722 (setq ad-return-value t
16723 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16725 (let ((p (org-inside-LaTeX-fragment-p)))
16726 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16727 (setq ad-return-value t
16728 texmathp-why '("Org-mode embedded math" . 0))
16729 (if p ad-do-it)))))))))
16731 (defun turn-on-org-cdlatex ()
16732 "Unconditionally turn on `org-cdlatex-mode'."
16733 (org-cdlatex-mode 1))
16735 (defun org-inside-LaTeX-fragment-p ()
16736 "Test if point is inside a LaTeX fragment.
16737 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16738 sequence appearing also before point.
16739 Even though the matchers for math are configurable, this function assumes
16740 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16741 delimiters are skipped when they have been removed by customization.
16742 The return value is nil, or a cons cell with the delimiter and the
16743 position of this delimiter.
16745 This function does a reasonably good job, but can locally be fooled by
16746 for example currency specifications. For example it will assume being in
16747 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16748 fragments that are properly closed, but during editing, we have to live
16749 with the uncertainty caused by missing closing delimiters. This function
16750 looks only before point, not after."
16751 (catch 'exit
16752 (let ((pos (point))
16753 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16754 (lim (progn
16755 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16756 (point)))
16757 dd-on str (start 0) m re)
16758 (goto-char pos)
16759 (when dodollar
16760 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16761 re (nth 1 (assoc "$" org-latex-regexps)))
16762 (while (string-match re str start)
16763 (cond
16764 ((= (match-end 0) (length str))
16765 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16766 ((= (match-end 0) (- (length str) 5))
16767 (throw 'exit nil))
16768 (t (setq start (match-end 0))))))
16769 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16770 (goto-char pos)
16771 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16772 (and (match-beginning 2) (throw 'exit nil))
16773 ;; count $$
16774 (while (re-search-backward "\\$\\$" lim t)
16775 (setq dd-on (not dd-on)))
16776 (goto-char pos)
16777 (if dd-on (cons "$$" m))))))
16779 (defun org-inside-latex-macro-p ()
16780 "Is point inside a LaTeX macro or its arguments?"
16781 (save-match-data
16782 (org-in-regexp
16783 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16785 (defun org-try-cdlatex-tab ()
16786 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16787 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16788 - inside a LaTeX fragment, or
16789 - after the first word in a line, where an abbreviation expansion could
16790 insert a LaTeX environment."
16791 (when org-cdlatex-mode
16792 (cond
16793 ;; Before any word on the line: No expansion possible.
16794 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16795 ;; Just after first word on the line: Expand it. Make sure it
16796 ;; cannot happen on headlines, though.
16797 ((save-excursion
16798 (skip-chars-backward "a-zA-Z0-9*")
16799 (skip-chars-backward " \t")
16800 (and (bolp) (not (org-at-heading-p))))
16801 (cdlatex-tab) t)
16802 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16804 (defun org-cdlatex-underscore-caret (&optional arg)
16805 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16806 Revert to the normal definition outside of these fragments."
16807 (interactive "P")
16808 (if (org-inside-LaTeX-fragment-p)
16809 (call-interactively 'cdlatex-sub-superscript)
16810 (let (org-cdlatex-mode)
16811 (call-interactively (key-binding (vector last-input-event))))))
16813 (defun org-cdlatex-math-modify (&optional arg)
16814 "Execute `cdlatex-math-modify' in LaTeX fragments.
16815 Revert to the normal definition outside of these fragments."
16816 (interactive "P")
16817 (if (org-inside-LaTeX-fragment-p)
16818 (call-interactively 'cdlatex-math-modify)
16819 (let (org-cdlatex-mode)
16820 (call-interactively (key-binding (vector last-input-event))))))
16822 (defvar org-latex-fragment-image-overlays nil
16823 "List of overlays carrying the images of latex fragments.")
16824 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16826 (defun org-remove-latex-fragment-image-overlays ()
16827 "Remove all overlays with LaTeX fragment images in current buffer."
16828 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16829 (setq org-latex-fragment-image-overlays nil))
16831 (defun org-preview-latex-fragment (&optional subtree)
16832 "Preview the LaTeX fragment at point, or all locally or globally.
16833 If the cursor is in a LaTeX fragment, create the image and overlay
16834 it over the source code. If there is no fragment at point, display
16835 all fragments in the current text, from one headline to the next. With
16836 prefix SUBTREE, display all fragments in the current subtree. With a
16837 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16838 the cursor is before the first headline,
16839 display all fragments in the buffer.
16840 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16841 (interactive "P")
16842 (unless buffer-file-name
16843 (error "Can't preview LaTeX fragment in a non-file buffer"))
16844 (org-remove-latex-fragment-image-overlays)
16845 (save-excursion
16846 (save-restriction
16847 (let (beg end at msg)
16848 (cond
16849 ((or (equal subtree '(16))
16850 (not (save-excursion
16851 (re-search-backward org-outline-regexp-bol nil t))))
16852 (setq beg (point-min) end (point-max)
16853 msg "Creating images for buffer...%s"))
16854 ((equal subtree '(4))
16855 (org-back-to-heading)
16856 (setq beg (point) end (org-end-of-subtree t)
16857 msg "Creating images for subtree...%s"))
16859 (if (setq at (org-inside-LaTeX-fragment-p))
16860 (goto-char (max (point-min) (- (cdr at) 2)))
16861 (org-back-to-heading))
16862 (setq beg (point) end (progn (outline-next-heading) (point))
16863 msg (if at "Creating image...%s"
16864 "Creating images for entry...%s"))))
16865 (message msg "")
16866 (narrow-to-region beg end)
16867 (goto-char beg)
16868 (org-format-latex
16869 (concat "ltxpng/" (file-name-sans-extension
16870 (file-name-nondirectory
16871 buffer-file-name)))
16872 default-directory 'overlays msg at 'forbuffer 'dvipng)
16873 (message msg "done. Use `C-c C-c' to remove images.")))))
16875 (defvar org-latex-regexps
16876 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16877 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16878 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16879 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16880 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16881 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16882 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16883 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16884 "Regular expressions for matching embedded LaTeX.")
16886 (defvar org-export-have-math nil) ;; dynamic scoping
16887 (defun org-format-latex (prefix &optional dir overlays msg at
16888 forbuffer processing-type)
16889 "Replace LaTeX fragments with links to an image, and produce images.
16890 Some of the options can be changed using the variable
16891 `org-format-latex-options'."
16892 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16893 (let* ((prefixnodir (file-name-nondirectory prefix))
16894 (absprefix (expand-file-name prefix dir))
16895 (todir (file-name-directory absprefix))
16896 (opt org-format-latex-options)
16897 (matchers (plist-get opt :matchers))
16898 (re-list org-latex-regexps)
16899 (org-format-latex-header-extra
16900 (plist-get (org-infile-export-plist) :latex-header-extra))
16901 (cnt 0) txt hash link beg end re e checkdir
16902 executables-checked string
16903 m n block-type block linkfile movefile ov)
16904 ;; Check the different regular expressions
16905 (while (setq e (pop re-list))
16906 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16907 block (if block-type "\n\n" ""))
16908 (when (member m matchers)
16909 (goto-char (point-min))
16910 (while (re-search-forward re nil t)
16911 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16912 (not (get-text-property (match-beginning n)
16913 'org-protected))
16914 (or (not overlays)
16915 (not (eq (get-char-property (match-beginning n)
16916 'org-overlay-type)
16917 'org-latex-overlay))))
16918 (setq org-export-have-math t)
16919 (cond
16920 ((eq processing-type 'verbatim)
16921 ;; Leave the text verbatim, just protect it
16922 (add-text-properties (match-beginning n) (match-end n)
16923 '(org-protected t)))
16924 ((eq processing-type 'mathjax)
16925 ;; Prepare for MathJax processing
16926 (setq string (match-string n))
16927 (if (member m '("$" "$1"))
16928 (save-excursion
16929 (delete-region (match-beginning n) (match-end n))
16930 (goto-char (match-beginning n))
16931 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16932 "\\)")
16933 '(org-protected t))))
16934 (add-text-properties (match-beginning n) (match-end n)
16935 '(org-protected t))))
16936 ((eq processing-type 'dvipng)
16937 ;; Process to an image
16938 (setq txt (match-string n)
16939 beg (match-beginning n) end (match-end n)
16940 cnt (1+ cnt))
16941 (let (print-length print-level) ; make sure full list is printed
16942 (setq hash (sha1 (prin1-to-string
16943 (list org-format-latex-header
16944 org-format-latex-header-extra
16945 org-export-latex-default-packages-alist
16946 org-export-latex-packages-alist
16947 org-format-latex-options
16948 forbuffer txt)))
16949 linkfile (format "%s_%s.png" prefix hash)
16950 movefile (format "%s_%s.png" absprefix hash)))
16951 (setq link (concat block "[[file:" linkfile "]]" block))
16952 (if msg (message msg cnt))
16953 (goto-char beg)
16954 (unless checkdir ; make sure the directory exists
16955 (setq checkdir t)
16956 (or (file-directory-p todir) (make-directory todir t)))
16958 (unless executables-checked
16959 (org-check-external-command
16960 "latex" "needed to convert LaTeX fragments to images")
16961 (org-check-external-command
16962 "dvipng" "needed to convert LaTeX fragments to images")
16963 (setq executables-checked t))
16965 (unless (file-exists-p movefile)
16966 (org-create-formula-image
16967 txt movefile opt forbuffer))
16968 (if overlays
16969 (progn
16970 (mapc (lambda (o)
16971 (if (eq (overlay-get o 'org-overlay-type)
16972 'org-latex-overlay)
16973 (delete-overlay o)))
16974 (overlays-in beg end))
16975 (setq ov (make-overlay beg end))
16976 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16977 (if (featurep 'xemacs)
16978 (progn
16979 (overlay-put ov 'invisible t)
16980 (overlay-put
16981 ov 'end-glyph
16982 (make-glyph (vector 'png :file movefile))))
16983 (overlay-put
16984 ov 'display
16985 (list 'image :type 'png :file movefile :ascent 'center)))
16986 (push ov org-latex-fragment-image-overlays)
16987 (goto-char end))
16988 (delete-region beg end)
16989 (insert (org-add-props link
16990 (list 'org-latex-src
16991 (replace-regexp-in-string
16992 "\"" "" txt)
16993 'org-latex-src-embed-type
16994 (if block-type 'paragraph 'character))))))
16995 ((eq processing-type 'mathml)
16996 ;; Process to MathML
16997 (unless executables-checked
16998 (unless (save-match-data (org-format-latex-mathml-available-p))
16999 (error "LaTeX to MathML converter not configured"))
17000 (setq executables-checked t))
17001 (setq txt (match-string n)
17002 beg (match-beginning n) end (match-end n)
17003 cnt (1+ cnt))
17004 (if msg (message msg cnt))
17005 (goto-char beg)
17006 (delete-region beg end)
17007 (insert (org-format-latex-as-mathml
17008 txt block-type prefix dir)))
17010 (error "Unknown conversion type %s for latex fragments"
17011 processing-type)))))))))
17013 (declare-function format-spec "format-spec" (format specification))
17015 (defun org-create-math-formula (latex-frag &optional mathml-file)
17016 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17017 Use `org-latex-to-mathml-convert-command'. If the conversion is
17018 sucessful, return the portion between \"<math...> </math>\"
17019 elements otherwise return nil. When MATHML-FILE is specified,
17020 write the results in to that file. When invoked as an
17021 interactive command, prompt for LATEX-FRAG, with initial value
17022 set to the current active region and echo the results for user
17023 inspection."
17024 (interactive (list (let ((frag (when (region-active-p)
17025 (buffer-substring-no-properties
17026 (region-beginning) (region-end)))))
17027 (read-string "LaTeX Fragment: " frag nil frag))))
17028 (unless latex-frag (error "Invalid latex-frag"))
17029 (let* ((tmp-in-file (file-relative-name
17030 (make-temp-name (expand-file-name "ltxmathml-in"))))
17031 (ignore (write-region latex-frag nil tmp-in-file))
17032 (tmp-out-file (file-relative-name
17033 (make-temp-name (expand-file-name "ltxmathml-out"))))
17034 (cmd (format-spec
17035 org-latex-to-mathml-convert-command
17036 `((?j . ,(shell-quote-argument
17037 (expand-file-name org-latex-to-mathml-jar-file)))
17038 (?I . ,(shell-quote-argument tmp-in-file))
17039 (?o . ,(shell-quote-argument tmp-out-file)))))
17040 mathml shell-command-output)
17041 (when (org-called-interactively-p 'any)
17042 (unless (org-format-latex-mathml-available-p)
17043 (error "LaTeX to MathML converter not configured")))
17044 (message "Running %s" cmd)
17045 (setq shell-command-output (shell-command-to-string cmd))
17046 (setq mathml
17047 (when (file-readable-p tmp-out-file)
17048 (with-current-buffer (find-file-noselect tmp-out-file t)
17049 (goto-char (point-min))
17050 (when (re-search-forward
17051 (concat
17052 (regexp-quote
17053 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17054 "\\(.\\|\n\\)*"
17055 (regexp-quote "</math>")) nil t)
17056 (prog1 (match-string 0) (kill-buffer))))))
17057 (cond
17058 (mathml
17059 (setq mathml
17060 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17061 (when mathml-file
17062 (write-region mathml nil mathml-file))
17063 (when (org-called-interactively-p 'any)
17064 (message mathml)))
17065 ((message "LaTeX to MathML conversion failed")
17066 (message shell-command-output)))
17067 (delete-file tmp-in-file)
17068 (when (file-exists-p tmp-out-file)
17069 (delete-file tmp-out-file))
17070 mathml))
17072 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17073 prefix &optional dir)
17074 "Use `org-create-math-formula' but check local cache first."
17075 (let* ((absprefix (expand-file-name prefix dir))
17076 (print-length nil) (print-level nil)
17077 (formula-id (concat
17078 "formula-"
17079 (sha1
17080 (prin1-to-string
17081 (list latex-frag
17082 org-latex-to-mathml-convert-command)))))
17083 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17084 (formula-cache-dir (file-name-directory formula-cache)))
17086 (unless (file-directory-p formula-cache-dir)
17087 (make-directory formula-cache-dir t))
17089 (unless (file-exists-p formula-cache)
17090 (org-create-math-formula latex-frag formula-cache))
17092 (if (file-exists-p formula-cache)
17093 ;; Successful conversion. Return the link to MathML file.
17094 (org-add-props
17095 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17096 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17097 'org-latex-src-embed-type (if latex-frag-type
17098 'paragraph 'character)))
17099 ;; Failed conversion. Return the LaTeX fragment verbatim
17100 (add-text-properties
17101 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17102 latex-frag)))
17104 ;; This function borrows from Ganesh Swami's latex2png.el
17105 (defun org-create-formula-image (string tofile options buffer)
17106 "This calls dvipng."
17107 (require 'org-latex)
17108 (let* ((tmpdir (if (featurep 'xemacs)
17109 (temp-directory)
17110 temporary-file-directory))
17111 (texfilebase (make-temp-name
17112 (expand-file-name "orgtex" tmpdir)))
17113 (texfile (concat texfilebase ".tex"))
17114 (dvifile (concat texfilebase ".dvi"))
17115 (pngfile (concat texfilebase ".png"))
17116 (fnh (if (featurep 'xemacs)
17117 (font-height (get-face-font 'default))
17118 (face-attribute 'default :height nil)))
17119 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17120 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17121 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17122 "Black"))
17123 (bg (or (plist-get options (if buffer :background :html-background))
17124 "Transparent")))
17125 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17126 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17127 (with-temp-file texfile
17128 (insert (org-splice-latex-header
17129 org-format-latex-header
17130 org-export-latex-default-packages-alist
17131 org-export-latex-packages-alist t
17132 org-format-latex-header-extra))
17133 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17134 (require 'org-latex)
17135 (org-export-latex-fix-inputenc))
17136 (let ((dir default-directory))
17137 (condition-case nil
17138 (progn
17139 (cd tmpdir)
17140 (call-process "latex" nil nil nil texfile))
17141 (error nil))
17142 (cd dir))
17143 (if (not (file-exists-p dvifile))
17144 (progn (message "Failed to create dvi file from %s" texfile) nil)
17145 (condition-case nil
17146 (call-process "dvipng" nil nil nil
17147 "-fg" fg "-bg" bg
17148 "-D" dpi
17149 ;;"-x" scale "-y" scale
17150 "-T" "tight"
17151 "-o" pngfile
17152 dvifile)
17153 (error nil))
17154 (if (not (file-exists-p pngfile))
17155 (if org-format-latex-signal-error
17156 (error "Failed to create png file from %s" texfile)
17157 (message "Failed to create png file from %s" texfile)
17158 nil)
17159 ;; Use the requested file name and clean up
17160 (copy-file pngfile tofile 'replace)
17161 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17162 (delete-file (concat texfilebase e)))
17163 pngfile))))
17165 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17166 "Fill a LaTeX header template TPL.
17167 In the template, the following place holders will be recognized:
17169 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17170 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17171 [PACKAGES] \\usepackage statements for PKG
17172 [NO-PACKAGES] do not include PKG
17173 [EXTRA] the string EXTRA
17174 [NO-EXTRA] do not include EXTRA
17176 For backward compatibility, if both the positive and the negative place
17177 holder is missing, the positive one (without the \"NO-\") will be
17178 assumed to be present at the end of the template.
17179 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17180 EXTRA is a string.
17181 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17182 (let (rpl (end ""))
17183 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17184 (setq rpl (if (or (match-end 1) (not def-pkg))
17185 "" (org-latex-packages-to-string def-pkg snippets-p t))
17186 tpl (replace-match rpl t t tpl))
17187 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17189 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17190 (setq rpl (if (or (match-end 1) (not pkg))
17191 "" (org-latex-packages-to-string pkg snippets-p t))
17192 tpl (replace-match rpl t t tpl))
17193 (if pkg (setq end
17194 (concat end "\n"
17195 (org-latex-packages-to-string pkg snippets-p)))))
17197 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17198 (setq rpl (if (or (match-end 1) (not extra))
17199 "" (concat extra "\n"))
17200 tpl (replace-match rpl t t tpl))
17201 (if (and extra (string-match "\\S-" extra))
17202 (setq end (concat end "\n" extra))))
17204 (if (string-match "\\S-" end)
17205 (concat tpl "\n" end)
17206 tpl)))
17208 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17209 "Turn an alist of packages into a string with the \\usepackage macros."
17210 (setq pkg (mapconcat (lambda(p)
17211 (cond
17212 ((stringp p) p)
17213 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17214 (format "%% Package %s omitted" (cadr p)))
17215 ((equal "" (car p))
17216 (format "\\usepackage{%s}" (cadr p)))
17218 (format "\\usepackage[%s]{%s}"
17219 (car p) (cadr p)))))
17221 "\n"))
17222 (if newline (concat pkg "\n") pkg))
17224 (defun org-dvipng-color (attr)
17225 "Return an rgb color specification for dvipng."
17226 (apply 'format "rgb %s %s %s"
17227 (mapcar 'org-normalize-color
17228 (color-values (face-attribute 'default attr nil)))))
17230 (defun org-normalize-color (value)
17231 "Return string to be used as color value for an RGB component."
17232 (format "%g" (/ value 65535.0)))
17234 ;; Image display
17237 (defvar org-inline-image-overlays nil)
17238 (make-variable-buffer-local 'org-inline-image-overlays)
17240 (defun org-toggle-inline-images (&optional include-linked)
17241 "Toggle the display of inline images.
17242 INCLUDE-LINKED is passed to `org-display-inline-images'."
17243 (interactive "P")
17244 (if org-inline-image-overlays
17245 (progn
17246 (org-remove-inline-images)
17247 (message "Inline image display turned off"))
17248 (org-display-inline-images include-linked)
17249 (if org-inline-image-overlays
17250 (message "%d images displayed inline"
17251 (length org-inline-image-overlays))
17252 (message "No images to display inline"))))
17254 (defun org-display-inline-images (&optional include-linked refresh beg end)
17255 "Display inline images.
17256 Normally only links without a description part are inlined, because this
17257 is how it will work for export. When INCLUDE-LINKED is set, also links
17258 with a description part will be inlined. This can be nice for a quick
17259 look at those images, but it does not reflect what exported files will look
17260 like.
17261 When REFRESH is set, refresh existing images between BEG and END.
17262 This will create new image displays only if necessary.
17263 BEG and END default to the buffer boundaries."
17264 (interactive "P")
17265 (unless refresh
17266 (org-remove-inline-images)
17267 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17268 (save-excursion
17269 (save-restriction
17270 (widen)
17271 (setq beg (or beg (point-min)) end (or end (point-max)))
17272 (goto-char (point-min))
17273 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17274 (substring (org-image-file-name-regexp) 0 -2)
17275 "\\)\\]" (if include-linked "" "\\]")))
17276 old file ov img)
17277 (while (re-search-forward re end t)
17278 (setq old (get-char-property-and-overlay (match-beginning 1)
17279 'org-image-overlay))
17280 (setq file (expand-file-name
17281 (concat (or (match-string 3) "") (match-string 4))))
17282 (when (file-exists-p file)
17283 (if (and (car-safe old) refresh)
17284 (image-refresh (overlay-get (cdr old) 'display))
17285 (setq img (save-match-data (create-image file)))
17286 (when img
17287 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17288 (overlay-put ov 'display img)
17289 (overlay-put ov 'face 'default)
17290 (overlay-put ov 'org-image-overlay t)
17291 (overlay-put ov 'modification-hooks
17292 (list 'org-display-inline-modification-hook))
17293 (push ov org-inline-image-overlays)))))))))
17295 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17296 "Remove inline-display overlay if a corresponding region is modified."
17297 (let ((inhibit-modification-hooks t))
17298 (when (and ov after)
17299 (delete ov org-inline-image-overlays)
17300 (delete-overlay ov))))
17302 (defun org-remove-inline-images ()
17303 "Remove inline display of images."
17304 (interactive)
17305 (mapc 'delete-overlay org-inline-image-overlays)
17306 (setq org-inline-image-overlays nil))
17308 ;;;; Key bindings
17310 ;; Outline functions from `outline-mode-prefix-map'
17311 ;; that can be remapped in Org:
17312 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17313 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17314 (define-key org-mode-map [remap outline-forward-same-level]
17315 'org-forward-same-level)
17316 (define-key org-mode-map [remap outline-backward-same-level]
17317 'org-backward-same-level)
17318 (define-key org-mode-map [remap show-branches]
17319 'org-kill-note-or-show-branches)
17320 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17321 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17322 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17324 ;; Outline functions from `outline-mode-prefix-map'
17325 ;; that can not be remapped in Org:
17326 ;; - the column "key binding" shows whether the Outline function is still
17327 ;; available in Org mode on the same key that it has been bound to in
17328 ;; Outline mode:
17329 ;; - "overridden": key used for a different functionality in Org mode
17330 ;; - else: key still bound to the same Outline function in Org mode
17331 ;; | Outline function | key binding | Org replacement |
17332 ;; |------------------------------------+-------------+-----------------------|
17333 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17334 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17335 ;; | `show-children' | `C-c C-i' | visibility cycling |
17336 ;; | `hide-subtree' | overridden | visibility cycling |
17337 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17338 ;; | `hide-body' | overridden | no replacement |
17339 ;; | `show-all' | overridden | no replacement |
17340 ;; | `hide-entry' | overridden | visibility cycling |
17341 ;; | `show-entry' | overridden | no replacement |
17342 ;; | `hide-leaves' | overridden | no replacement |
17343 ;; | `hide-sublevels' | overridden | no replacement |
17344 ;; | `hide-other' | overridden | no replacement |
17345 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17346 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17348 ;; Make `C-c C-x' a prefix key
17349 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17351 ;; TAB key with modifiers
17352 (org-defkey org-mode-map "\C-i" 'org-cycle)
17353 (org-defkey org-mode-map [(tab)] 'org-cycle)
17354 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17355 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17356 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17357 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17358 ;; The following line is necessary under Suse GNU/Linux
17359 (unless (featurep 'xemacs)
17360 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17361 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17362 (define-key org-mode-map [backtab] 'org-shifttab)
17364 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17365 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17366 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17368 ;; Cursor keys with modifiers
17369 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17370 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17371 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17372 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17374 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17375 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17376 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17377 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17379 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17380 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17381 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17382 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17384 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17385 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17386 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17387 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17389 ;; Babel keys
17390 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17391 (mapc (lambda (pair)
17392 (define-key org-babel-map (car pair) (cdr pair)))
17393 org-babel-key-bindings)
17395 ;;; Extra keys for tty access.
17396 ;; We only set them when really needed because otherwise the
17397 ;; menus don't show the simple keys
17399 (when (or org-use-extra-keys
17400 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17401 (not window-system))
17402 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17403 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17404 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17405 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17406 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17407 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17408 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17409 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17410 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17411 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17412 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17413 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17414 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17415 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17416 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17417 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17418 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17419 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17420 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17421 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17422 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17423 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17424 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17425 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17426 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17427 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17428 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17429 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17431 ;; All the other keys
17433 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17434 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17435 (if (boundp 'narrow-map)
17436 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17437 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17438 (if (boundp 'narrow-map)
17439 (org-defkey narrow-map "b" 'org-narrow-to-block)
17440 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17441 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17442 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17443 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17444 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17445 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17446 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17447 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17448 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17449 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17450 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17451 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17452 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17453 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17454 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17455 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17456 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17457 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17458 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17459 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17460 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17461 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17462 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17463 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17464 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17465 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17466 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17467 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17468 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17469 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17470 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17471 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17472 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17473 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17474 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17475 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17476 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17477 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17478 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17479 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17480 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17481 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17482 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17483 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17484 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17485 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17486 (org-defkey org-mode-map "\C-c^" 'org-sort)
17487 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17488 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17489 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17490 (org-defkey org-mode-map "\C-m" 'org-return)
17491 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17492 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17493 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17494 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17495 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17496 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17497 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17498 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17499 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17500 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17501 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17502 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17503 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17504 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17505 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17506 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17507 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17508 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17509 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17510 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17511 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17512 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17513 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17515 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17516 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17517 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17518 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17520 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17521 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17522 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17523 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17524 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17525 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17526 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17527 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17528 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17529 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17530 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17531 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17532 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17533 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17534 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17535 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17536 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17537 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17539 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17540 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17541 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17542 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17543 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17545 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17547 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17549 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17550 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17552 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17555 (when (featurep 'xemacs)
17556 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17559 (defconst org-speed-commands-default
17561 ("Outline Navigation")
17562 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17563 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17564 ("f" . (org-speed-move-safe 'org-forward-same-level))
17565 ("b" . (org-speed-move-safe 'org-backward-same-level))
17566 ("u" . (org-speed-move-safe 'outline-up-heading))
17567 ("j" . org-goto)
17568 ("g" . (org-refile t))
17569 ("Outline Visibility")
17570 ("c" . org-cycle)
17571 ("C" . org-shifttab)
17572 (" " . org-display-outline-path)
17573 ("Outline Structure Editing")
17574 ("U" . org-shiftmetaup)
17575 ("D" . org-shiftmetadown)
17576 ("r" . org-metaright)
17577 ("l" . org-metaleft)
17578 ("R" . org-shiftmetaright)
17579 ("L" . org-shiftmetaleft)
17580 ("i" . (progn (forward-char 1) (call-interactively
17581 'org-insert-heading-respect-content)))
17582 ("^" . org-sort)
17583 ("w" . org-refile)
17584 ("a" . org-archive-subtree-default-with-confirmation)
17585 ("." . org-mark-subtree)
17586 ("Clock Commands")
17587 ("I" . org-clock-in)
17588 ("O" . org-clock-out)
17589 ("Meta Data Editing")
17590 ("t" . org-todo)
17591 ("0" . (org-priority ?\ ))
17592 ("1" . (org-priority ?A))
17593 ("2" . (org-priority ?B))
17594 ("3" . (org-priority ?C))
17595 (";" . org-set-tags-command)
17596 ("e" . org-set-effort)
17597 ("Agenda Views etc")
17598 ("v" . org-agenda)
17599 ("/" . org-sparse-tree)
17600 ("Misc")
17601 ("o" . org-open-at-point)
17602 ("?" . org-speed-command-help)
17603 ("<" . (org-agenda-set-restriction-lock 'subtree))
17604 (">" . (org-agenda-remove-restriction-lock))
17606 "The default speed commands.")
17608 (defun org-print-speed-command (e)
17609 (if (> (length (car e)) 1)
17610 (progn
17611 (princ "\n")
17612 (princ (car e))
17613 (princ "\n")
17614 (princ (make-string (length (car e)) ?-))
17615 (princ "\n"))
17616 (princ (car e))
17617 (princ " ")
17618 (if (symbolp (cdr e))
17619 (princ (symbol-name (cdr e)))
17620 (prin1 (cdr e)))
17621 (princ "\n")))
17623 (defun org-speed-command-help ()
17624 "Show the available speed commands."
17625 (interactive)
17626 (if (not org-use-speed-commands)
17627 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17628 (with-output-to-temp-buffer "*Help*"
17629 (princ "User-defined Speed commands\n===========================\n")
17630 (mapc 'org-print-speed-command org-speed-commands-user)
17631 (princ "\n")
17632 (princ "Built-in Speed commands\n=======================\n")
17633 (mapc 'org-print-speed-command org-speed-commands-default))
17634 (with-current-buffer "*Help*"
17635 (setq truncate-lines t))))
17637 (defun org-speed-move-safe (cmd)
17638 "Execute CMD, but make sure that the cursor always ends up in a headline.
17639 If not, return to the original position and throw an error."
17640 (interactive)
17641 (let ((pos (point)))
17642 (call-interactively cmd)
17643 (unless (and (bolp) (org-at-heading-p))
17644 (goto-char pos)
17645 (error "Boundary reached while executing %s" cmd))))
17647 (defvar org-self-insert-command-undo-counter 0)
17649 (defvar org-table-auto-blank-field) ; defined in org-table.el
17650 (defvar org-speed-command nil)
17652 (defun org-speed-command-default-hook (keys)
17653 "Hook for activating single-letter speed commands.
17654 `org-speed-commands-default' specifies a minimal command set.
17655 Use `org-speed-commands-user' for further customization."
17656 (when (or (and (bolp) (looking-at org-outline-regexp))
17657 (and (functionp org-use-speed-commands)
17658 (funcall org-use-speed-commands)))
17659 (cdr (assoc keys (append org-speed-commands-user
17660 org-speed-commands-default)))))
17662 (defun org-babel-speed-command-hook (keys)
17663 "Hook for activating single-letter code block commands."
17664 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17665 (cdr (assoc keys org-babel-key-bindings))))
17667 (defcustom org-speed-command-hook
17668 '(org-speed-command-default-hook org-babel-speed-command-hook)
17669 "Hook for activating speed commands at strategic locations.
17670 Hook functions are called in sequence until a valid handler is
17671 found.
17673 Each hook takes a single argument, a user-pressed command key
17674 which is also a `self-insert-command' from the global map.
17676 Within the hook, examine the cursor position and the command key
17677 and return nil or a valid handler as appropriate. Handler could
17678 be one of an interactive command, a function, or a form.
17680 Set `org-use-speed-commands' to non-nil value to enable this
17681 hook. The default setting is `org-speed-command-default-hook'."
17682 :group 'org-structure
17683 :version "24.1"
17684 :type 'hook)
17686 (defun org-self-insert-command (N)
17687 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17688 If the cursor is in a table looking at whitespace, the whitespace is
17689 overwritten, and the table is not marked as requiring realignment."
17690 (interactive "p")
17691 (org-check-before-invisible-edit 'insert)
17692 (cond
17693 ((and org-use-speed-commands
17694 (setq org-speed-command
17695 (run-hook-with-args-until-success
17696 'org-speed-command-hook (this-command-keys))))
17697 (cond
17698 ((commandp org-speed-command)
17699 (setq this-command org-speed-command)
17700 (call-interactively org-speed-command))
17701 ((functionp org-speed-command)
17702 (funcall org-speed-command))
17703 ((and org-speed-command (listp org-speed-command))
17704 (eval org-speed-command))
17705 (t (let (org-use-speed-commands)
17706 (call-interactively 'org-self-insert-command)))))
17707 ((and
17708 (org-table-p)
17709 (progn
17710 ;; check if we blank the field, and if that triggers align
17711 (and (featurep 'org-table) org-table-auto-blank-field
17712 (member last-command
17713 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17714 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17715 ;; got extra space, this field does not determine column width
17716 (let (org-table-may-need-update) (org-table-blank-field))
17717 ;; no extra space, this field may determine column width
17718 (org-table-blank-field)))
17720 (eq N 1)
17721 (looking-at "[^|\n]* |"))
17722 (let (org-table-may-need-update)
17723 (goto-char (1- (match-end 0)))
17724 (delete-char -1)
17725 (goto-char (match-beginning 0))
17726 (self-insert-command N)))
17728 (setq org-table-may-need-update t)
17729 (self-insert-command N)
17730 (org-fix-tags-on-the-fly)
17731 (if org-self-insert-cluster-for-undo
17732 (if (not (eq last-command 'org-self-insert-command))
17733 (setq org-self-insert-command-undo-counter 1)
17734 (if (>= org-self-insert-command-undo-counter 20)
17735 (setq org-self-insert-command-undo-counter 1)
17736 (and (> org-self-insert-command-undo-counter 0)
17737 buffer-undo-list (listp buffer-undo-list)
17738 (not (cadr buffer-undo-list)) ; remove nil entry
17739 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17740 (setq org-self-insert-command-undo-counter
17741 (1+ org-self-insert-command-undo-counter))))))))
17743 (defun org-check-before-invisible-edit (kind)
17744 "Check is editing if kind KIND would be dangerous with invisible text around.
17745 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17746 ;; First, try to get out of here as quickly as possible, to reduce overhead
17747 (if (and org-catch-invisible-edits
17748 (or (not (boundp 'visible-mode)) (not visible-mode))
17749 (or (get-char-property (point) 'invisible)
17750 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17751 ;; OK, we need to take a closer look
17752 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17753 (invisible-before-point (if (bobp) nil (get-char-property
17754 (1- (point)) 'invisible)))
17755 (border-and-ok-direction
17757 ;; Check if we are acting predictably before invisible text
17758 (and invisible-at-point (not invisible-before-point)
17759 (memq kind '(insert delete-backward)))
17760 ;; Check if we are acting predictably after invisible text
17761 ;; This works not well, and I have turned it off. It seems
17762 ;; better to always show and stop after invisible text.
17763 ;; (and (not invisible-at-point) invisible-before-point
17764 ;; (memq kind '(insert delete)))
17767 (when (or (memq invisible-at-point '(outline org-hide-block))
17768 (memq invisible-before-point '(outline org-hide-block)))
17769 (if (eq org-catch-invisible-edits 'error)
17770 (error "Editing in invisible areas is prohibited - make visible first"))
17771 ;; Make the area visible
17772 (save-excursion
17773 (if invisible-before-point
17774 (goto-char (previous-single-char-property-change
17775 (point) 'invisible)))
17776 (org-cycle))
17777 (cond
17778 ((eq org-catch-invisible-edits 'show)
17779 ;; That's it, we do the edit after showing
17780 (message
17781 "Unfolding invisible region around point before editing")
17782 (sit-for 1))
17783 ((and (eq org-catch-invisible-edits 'smart)
17784 border-and-ok-direction)
17785 (message "Unfolding invisible region around point before editing"))
17787 ;; Don't do the edit, make the user repeat it in full visibility
17788 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17790 (defun org-fix-tags-on-the-fly ()
17791 (when (and (equal (char-after (point-at-bol)) ?*)
17792 (org-at-heading-p))
17793 (org-align-tags-here org-tags-column)))
17795 (defun org-delete-backward-char (N)
17796 "Like `delete-backward-char', insert whitespace at field end in tables.
17797 When deleting backwards, in tables this function will insert whitespace in
17798 front of the next \"|\" separator, to keep the table aligned. The table will
17799 still be marked for re-alignment if the field did fill the entire column,
17800 because, in this case the deletion might narrow the column."
17801 (interactive "p")
17802 (org-check-before-invisible-edit 'delete-backward)
17803 (if (and (org-table-p)
17804 (eq N 1)
17805 (string-match "|" (buffer-substring (point-at-bol) (point)))
17806 (looking-at ".*?|"))
17807 (let ((pos (point))
17808 (noalign (looking-at "[^|\n\r]* |"))
17809 (c org-table-may-need-update))
17810 (backward-delete-char N)
17811 (if (not overwrite-mode)
17812 (progn
17813 (skip-chars-forward "^|")
17814 (insert " ")
17815 (goto-char (1- pos))))
17816 ;; noalign: if there were two spaces at the end, this field
17817 ;; does not determine the width of the column.
17818 (if noalign (setq org-table-may-need-update c)))
17819 (backward-delete-char N)
17820 (org-fix-tags-on-the-fly)))
17822 (defun org-delete-char (N)
17823 "Like `delete-char', but insert whitespace at field end in tables.
17824 When deleting characters, in tables this function will insert whitespace in
17825 front of the next \"|\" separator, to keep the table aligned. The table will
17826 still be marked for re-alignment if the field did fill the entire column,
17827 because, in this case the deletion might narrow the column."
17828 (interactive "p")
17829 (org-check-before-invisible-edit 'delete)
17830 (if (and (org-table-p)
17831 (not (bolp))
17832 (not (= (char-after) ?|))
17833 (eq N 1))
17834 (if (looking-at ".*?|")
17835 (let ((pos (point))
17836 (noalign (looking-at "[^|\n\r]* |"))
17837 (c org-table-may-need-update))
17838 (replace-match (concat
17839 (substring (match-string 0) 1 -1)
17840 " |"))
17841 (goto-char pos)
17842 ;; noalign: if there were two spaces at the end, this field
17843 ;; does not determine the width of the column.
17844 (if noalign (setq org-table-may-need-update c)))
17845 (delete-char N))
17846 (delete-char N)
17847 (org-fix-tags-on-the-fly)))
17849 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17850 (put 'org-self-insert-command 'delete-selection t)
17851 (put 'orgtbl-self-insert-command 'delete-selection t)
17852 (put 'org-delete-char 'delete-selection 'supersede)
17853 (put 'org-delete-backward-char 'delete-selection 'supersede)
17854 (put 'org-yank 'delete-selection 'yank)
17856 ;; Make `flyspell-mode' delay after some commands
17857 (put 'org-self-insert-command 'flyspell-delayed t)
17858 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17859 (put 'org-delete-char 'flyspell-delayed t)
17860 (put 'org-delete-backward-char 'flyspell-delayed t)
17862 ;; Make pabbrev-mode expand after org-mode commands
17863 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17864 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17866 ;; How to do this: Measure non-white length of current string
17867 ;; If equal to column width, we should realign.
17869 (defun org-remap (map &rest commands)
17870 "In MAP, remap the functions given in COMMANDS.
17871 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17872 (let (new old)
17873 (while commands
17874 (setq old (pop commands) new (pop commands))
17875 (if (fboundp 'command-remapping)
17876 (org-defkey map (vector 'remap old) new)
17877 (substitute-key-definition old new map global-map)))))
17879 (when (eq org-enable-table-editor 'optimized)
17880 ;; If the user wants maximum table support, we need to hijack
17881 ;; some standard editing functions
17882 (org-remap org-mode-map
17883 'self-insert-command 'org-self-insert-command
17884 'delete-char 'org-delete-char
17885 'delete-backward-char 'org-delete-backward-char)
17886 (org-defkey org-mode-map "|" 'org-force-self-insert))
17888 (defvar org-ctrl-c-ctrl-c-hook nil
17889 "Hook for functions attaching themselves to `C-c C-c'.
17891 This can be used to add additional functionality to the C-c C-c
17892 key which executes context-dependent commands. This hook is run
17893 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17894 run after the last test.
17896 Each function will be called with no arguments. The function
17897 must check if the context is appropriate for it to act. If yes,
17898 it should do its thing and then return a non-nil value. If the
17899 context is wrong, just do nothing and return nil.")
17901 (defvar org-ctrl-c-ctrl-c-final-hook nil
17902 "Hook for functions attaching themselves to `C-c C-c'.
17904 This can be used to add additional functionality to the C-c C-c
17905 key which executes context-dependent commands. This hook is run
17906 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17907 before the first test.
17909 Each function will be called with no arguments. The function
17910 must check if the context is appropriate for it to act. If yes,
17911 it should do its thing and then return a non-nil value. If the
17912 context is wrong, just do nothing and return nil.")
17914 (defvar org-tab-first-hook nil
17915 "Hook for functions to attach themselves to TAB.
17916 See `org-ctrl-c-ctrl-c-hook' for more information.
17917 This hook runs as the first action when TAB is pressed, even before
17918 `org-cycle' messes around with the `outline-regexp' to cater for
17919 inline tasks and plain list item folding.
17920 If any function in this hook returns t, any other actions that
17921 would have been caused by TAB (such as table field motion or visibility
17922 cycling) will not occur.")
17924 (defvar org-tab-after-check-for-table-hook nil
17925 "Hook for functions to attach themselves to TAB.
17926 See `org-ctrl-c-ctrl-c-hook' for more information.
17927 This hook runs after it has been established that the cursor is not in a
17928 table, but before checking if the cursor is in a headline or if global cycling
17929 should be done.
17930 If any function in this hook returns t, not other actions like visibility
17931 cycling will be done.")
17933 (defvar org-tab-after-check-for-cycling-hook nil
17934 "Hook for functions to attach themselves to TAB.
17935 See `org-ctrl-c-ctrl-c-hook' for more information.
17936 This hook runs after it has been established that not table field motion and
17937 not visibility should be done because of current context. This is probably
17938 the place where a package like yasnippets can hook in.")
17940 (defvar org-tab-before-tab-emulation-hook nil
17941 "Hook for functions to attach themselves to TAB.
17942 See `org-ctrl-c-ctrl-c-hook' for more information.
17943 This hook runs after every other options for TAB have been exhausted, but
17944 before indentation and \t insertion takes place.")
17946 (defvar org-metaleft-hook nil
17947 "Hook for functions attaching themselves to `M-left'.
17948 See `org-ctrl-c-ctrl-c-hook' for more information.")
17949 (defvar org-metaright-hook nil
17950 "Hook for functions attaching themselves to `M-right'.
17951 See `org-ctrl-c-ctrl-c-hook' for more information.")
17952 (defvar org-metaup-hook nil
17953 "Hook for functions attaching themselves to `M-up'.
17954 See `org-ctrl-c-ctrl-c-hook' for more information.")
17955 (defvar org-metadown-hook nil
17956 "Hook for functions attaching themselves to `M-down'.
17957 See `org-ctrl-c-ctrl-c-hook' for more information.")
17958 (defvar org-shiftmetaleft-hook nil
17959 "Hook for functions attaching themselves to `M-S-left'.
17960 See `org-ctrl-c-ctrl-c-hook' for more information.")
17961 (defvar org-shiftmetaright-hook nil
17962 "Hook for functions attaching themselves to `M-S-right'.
17963 See `org-ctrl-c-ctrl-c-hook' for more information.")
17964 (defvar org-shiftmetaup-hook nil
17965 "Hook for functions attaching themselves to `M-S-up'.
17966 See `org-ctrl-c-ctrl-c-hook' for more information.")
17967 (defvar org-shiftmetadown-hook nil
17968 "Hook for functions attaching themselves to `M-S-down'.
17969 See `org-ctrl-c-ctrl-c-hook' for more information.")
17970 (defvar org-metareturn-hook nil
17971 "Hook for functions attaching themselves to `M-RET'.
17972 See `org-ctrl-c-ctrl-c-hook' for more information.")
17973 (defvar org-shiftup-hook nil
17974 "Hook for functions attaching themselves to `S-up'.
17975 See `org-ctrl-c-ctrl-c-hook' for more information.")
17976 (defvar org-shiftup-final-hook nil
17977 "Hook for functions attaching themselves to `S-up'.
17978 This one runs after all other options except shift-select have been excluded.
17979 See `org-ctrl-c-ctrl-c-hook' for more information.")
17980 (defvar org-shiftdown-hook nil
17981 "Hook for functions attaching themselves to `S-down'.
17982 See `org-ctrl-c-ctrl-c-hook' for more information.")
17983 (defvar org-shiftdown-final-hook nil
17984 "Hook for functions attaching themselves to `S-down'.
17985 This one runs after all other options except shift-select have been excluded.
17986 See `org-ctrl-c-ctrl-c-hook' for more information.")
17987 (defvar org-shiftleft-hook nil
17988 "Hook for functions attaching themselves to `S-left'.
17989 See `org-ctrl-c-ctrl-c-hook' for more information.")
17990 (defvar org-shiftleft-final-hook nil
17991 "Hook for functions attaching themselves to `S-left'.
17992 This one runs after all other options except shift-select have been excluded.
17993 See `org-ctrl-c-ctrl-c-hook' for more information.")
17994 (defvar org-shiftright-hook nil
17995 "Hook for functions attaching themselves to `S-right'.
17996 See `org-ctrl-c-ctrl-c-hook' for more information.")
17997 (defvar org-shiftright-final-hook nil
17998 "Hook for functions attaching themselves to `S-right'.
17999 This one runs after all other options except shift-select have been excluded.
18000 See `org-ctrl-c-ctrl-c-hook' for more information.")
18002 (defun org-modifier-cursor-error ()
18003 "Throw an error, a modified cursor command was applied in wrong context."
18004 (error "This command is active in special context like tables, headlines or items"))
18006 (defun org-shiftselect-error ()
18007 "Throw an error because Shift-Cursor command was applied in wrong context."
18008 (if (and (boundp 'shift-select-mode) shift-select-mode)
18009 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18010 (error "This command works only in special context like headlines or timestamps")))
18012 (defun org-call-for-shift-select (cmd)
18013 (let ((this-command-keys-shift-translated t))
18014 (call-interactively cmd)))
18016 (defun org-shifttab (&optional arg)
18017 "Global visibility cycling or move to previous table field.
18018 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18019 on context.
18020 See the individual commands for more information."
18021 (interactive "P")
18022 (cond
18023 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18024 ((integerp arg)
18025 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18026 (message "Content view to level: %d" arg)
18027 (org-content (prefix-numeric-value arg2))
18028 (setq org-cycle-global-status 'overview)))
18029 (t (call-interactively 'org-global-cycle))))
18031 (defun org-shiftmetaleft ()
18032 "Promote subtree or delete table column.
18033 Calls `org-promote-subtree', `org-outdent-item',
18034 or `org-table-delete-column', depending on context.
18035 See the individual commands for more information."
18036 (interactive)
18037 (cond
18038 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18039 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18040 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18041 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18042 (t (org-modifier-cursor-error))))
18044 (defun org-shiftmetaright ()
18045 "Demote subtree or insert table column.
18046 Calls `org-demote-subtree', `org-indent-item',
18047 or `org-table-insert-column', depending on context.
18048 See the individual commands for more information."
18049 (interactive)
18050 (cond
18051 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18052 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18053 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18054 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18055 (t (org-modifier-cursor-error))))
18057 (defun org-shiftmetaup (&optional arg)
18058 "Move subtree up or kill table row.
18059 Calls `org-move-subtree-up' or `org-table-kill-row' or
18060 `org-move-item-up' depending on context. See the individual commands
18061 for more information."
18062 (interactive "P")
18063 (cond
18064 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18065 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18066 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18067 ((org-at-item-p) (call-interactively 'org-move-item-up))
18068 (t (org-modifier-cursor-error))))
18070 (defun org-shiftmetadown (&optional arg)
18071 "Move subtree down or insert table row.
18072 Calls `org-move-subtree-down' or `org-table-insert-row' or
18073 `org-move-item-down', depending on context. See the individual
18074 commands for more information."
18075 (interactive "P")
18076 (cond
18077 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18078 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18079 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18080 ((org-at-item-p) (call-interactively 'org-move-item-down))
18081 (t (org-modifier-cursor-error))))
18083 (defsubst org-hidden-tree-error ()
18084 (error
18085 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18087 (defun org-metaleft (&optional arg)
18088 "Promote heading or move table column to left.
18089 Calls `org-do-promote' or `org-table-move-column', depending on context.
18090 With no specific context, calls the Emacs default `backward-word'.
18091 See the individual commands for more information."
18092 (interactive "P")
18093 (cond
18094 ((run-hook-with-args-until-success 'org-metaleft-hook))
18095 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18096 ((org-with-limited-levels
18097 (or (org-at-heading-p)
18098 (and (org-region-active-p)
18099 (save-excursion
18100 (goto-char (region-beginning))
18101 (org-at-heading-p)))))
18102 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18103 (call-interactively 'org-do-promote))
18104 ;; At an inline task.
18105 ((org-at-heading-p)
18106 (call-interactively 'org-inlinetask-promote))
18107 ((or (org-at-item-p)
18108 (and (org-region-active-p)
18109 (save-excursion
18110 (goto-char (region-beginning))
18111 (org-at-item-p))))
18112 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18113 (call-interactively 'org-outdent-item))
18114 (t (call-interactively 'backward-word))))
18116 (defun org-metaright (&optional arg)
18117 "Demote a subtree, a list item or move table column to right.
18118 In front of a drawer or a block keyword, indent it correctly.
18119 With no specific context, calls the Emacs default `forward-word'.
18120 See the individual commands for more information."
18121 (interactive "P")
18122 (cond
18123 ((run-hook-with-args-until-success 'org-metaright-hook))
18124 ((org-at-table-p) (call-interactively 'org-table-move-column))
18125 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18126 ((org-at-block-p) (call-interactively 'org-indent-block))
18127 ((org-with-limited-levels
18128 (or (org-at-heading-p)
18129 (and (org-region-active-p)
18130 (save-excursion
18131 (goto-char (region-beginning))
18132 (org-at-heading-p)))))
18133 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18134 (call-interactively 'org-do-demote))
18135 ;; At an inline task.
18136 ((org-at-heading-p)
18137 (call-interactively 'org-inlinetask-demote))
18138 ((or (org-at-item-p)
18139 (and (org-region-active-p)
18140 (save-excursion
18141 (goto-char (region-beginning))
18142 (org-at-item-p))))
18143 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18144 (call-interactively 'org-indent-item))
18145 (t (call-interactively 'forward-word))))
18147 (defun org-check-for-hidden (what)
18148 "Check if there are hidden headlines/items in the current visual line.
18149 WHAT can be either `headlines' or `items'. If the current line is
18150 an outline or item heading and it has a folded subtree below it,
18151 this function returns t, nil otherwise."
18152 (let ((re (cond
18153 ((eq what 'headlines) org-outline-regexp-bol)
18154 ((eq what 'items) (org-item-beginning-re))
18155 (t (error "This should not happen"))))
18156 beg end)
18157 (save-excursion
18158 (catch 'exit
18159 (unless (org-region-active-p)
18160 (setq beg (point-at-bol))
18161 (beginning-of-line 2)
18162 (while (and (not (eobp)) ;; this is like `next-line'
18163 (get-char-property (1- (point)) 'invisible))
18164 (beginning-of-line 2))
18165 (setq end (point))
18166 (goto-char beg)
18167 (goto-char (point-at-eol))
18168 (setq end (max end (point)))
18169 (while (re-search-forward re end t)
18170 (if (get-char-property (match-beginning 0) 'invisible)
18171 (throw 'exit t))))
18172 nil))))
18174 (defun org-metaup (&optional arg)
18175 "Move subtree up or move table row up.
18176 Calls `org-move-subtree-up' or `org-table-move-row' or
18177 `org-move-item-up', depending on context. See the individual commands
18178 for more information."
18179 (interactive "P")
18180 (cond
18181 ((run-hook-with-args-until-success 'org-metaup-hook))
18182 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18183 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18184 ((org-at-item-p) (call-interactively 'org-move-item-up))
18185 (t (transpose-lines 1) (beginning-of-line -1))))
18187 (defun org-metadown (&optional arg)
18188 "Move subtree down or move table row down.
18189 Calls `org-move-subtree-down' or `org-table-move-row' or
18190 `org-move-item-down', depending on context. See the individual
18191 commands for more information."
18192 (interactive "P")
18193 (cond
18194 ((run-hook-with-args-until-success 'org-metadown-hook))
18195 ((org-at-table-p) (call-interactively 'org-table-move-row))
18196 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18197 ((org-at-item-p) (call-interactively 'org-move-item-down))
18198 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18200 (defun org-shiftup (&optional arg)
18201 "Increase item in timestamp or increase priority of current headline.
18202 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18203 depending on context. See the individual commands for more information."
18204 (interactive "P")
18205 (cond
18206 ((run-hook-with-args-until-success 'org-shiftup-hook))
18207 ((and org-support-shift-select (org-region-active-p))
18208 (org-call-for-shift-select 'previous-line))
18209 ((org-at-timestamp-p t)
18210 (call-interactively (if org-edit-timestamp-down-means-later
18211 'org-timestamp-down 'org-timestamp-up)))
18212 ((and (not (eq org-support-shift-select 'always))
18213 org-enable-priority-commands
18214 (org-at-heading-p))
18215 (call-interactively 'org-priority-up))
18216 ((and (not org-support-shift-select) (org-at-item-p))
18217 (call-interactively 'org-previous-item))
18218 ((org-clocktable-try-shift 'up arg))
18219 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18220 (org-support-shift-select
18221 (org-call-for-shift-select 'previous-line))
18222 (t (org-shiftselect-error))))
18224 (defun org-shiftdown (&optional arg)
18225 "Decrease item in timestamp or decrease priority of current headline.
18226 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18227 depending on context. See the individual commands for more information."
18228 (interactive "P")
18229 (cond
18230 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18231 ((and org-support-shift-select (org-region-active-p))
18232 (org-call-for-shift-select 'next-line))
18233 ((org-at-timestamp-p t)
18234 (call-interactively (if org-edit-timestamp-down-means-later
18235 'org-timestamp-up 'org-timestamp-down)))
18236 ((and (not (eq org-support-shift-select 'always))
18237 org-enable-priority-commands
18238 (org-at-heading-p))
18239 (call-interactively 'org-priority-down))
18240 ((and (not org-support-shift-select) (org-at-item-p))
18241 (call-interactively 'org-next-item))
18242 ((org-clocktable-try-shift 'down arg))
18243 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18244 (org-support-shift-select
18245 (org-call-for-shift-select 'next-line))
18246 (t (org-shiftselect-error))))
18248 (defun org-shiftright (&optional arg)
18249 "Cycle the thing at point or in the current line, depending on context.
18250 Depending on context, this does one of the following:
18252 - switch a timestamp at point one day into the future
18253 - on a headline, switch to the next TODO keyword.
18254 - on an item, switch entire list to the next bullet type
18255 - on a property line, switch to the next allowed value
18256 - on a clocktable definition line, move time block into the future"
18257 (interactive "P")
18258 (cond
18259 ((run-hook-with-args-until-success 'org-shiftright-hook))
18260 ((and org-support-shift-select (org-region-active-p))
18261 (org-call-for-shift-select 'forward-char))
18262 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18263 ((and (not (eq org-support-shift-select 'always))
18264 (org-at-heading-p))
18265 (let ((org-inhibit-logging
18266 (not org-treat-S-cursor-todo-selection-as-state-change))
18267 (org-inhibit-blocking
18268 (not org-treat-S-cursor-todo-selection-as-state-change)))
18269 (org-call-with-arg 'org-todo 'right)))
18270 ((or (and org-support-shift-select
18271 (not (eq org-support-shift-select 'always))
18272 (org-at-item-bullet-p))
18273 (and (not org-support-shift-select) (org-at-item-p)))
18274 (org-call-with-arg 'org-cycle-list-bullet nil))
18275 ((and (not (eq org-support-shift-select 'always))
18276 (org-at-property-p))
18277 (call-interactively 'org-property-next-allowed-value))
18278 ((org-clocktable-try-shift 'right arg))
18279 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18280 (org-support-shift-select
18281 (org-call-for-shift-select 'forward-char))
18282 (t (org-shiftselect-error))))
18284 (defun org-shiftleft (&optional arg)
18285 "Cycle the thing at point or in the current line, depending on context.
18286 Depending on context, this does one of the following:
18288 - switch a timestamp at point one day into the past
18289 - on a headline, switch to the previous TODO keyword.
18290 - on an item, switch entire list to the previous bullet type
18291 - on a property line, switch to the previous allowed value
18292 - on a clocktable definition line, move time block into the past"
18293 (interactive "P")
18294 (cond
18295 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18296 ((and org-support-shift-select (org-region-active-p))
18297 (org-call-for-shift-select 'backward-char))
18298 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18299 ((and (not (eq org-support-shift-select 'always))
18300 (org-at-heading-p))
18301 (let ((org-inhibit-logging
18302 (not org-treat-S-cursor-todo-selection-as-state-change))
18303 (org-inhibit-blocking
18304 (not org-treat-S-cursor-todo-selection-as-state-change)))
18305 (org-call-with-arg 'org-todo 'left)))
18306 ((or (and org-support-shift-select
18307 (not (eq org-support-shift-select 'always))
18308 (org-at-item-bullet-p))
18309 (and (not org-support-shift-select) (org-at-item-p)))
18310 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18311 ((and (not (eq org-support-shift-select 'always))
18312 (org-at-property-p))
18313 (call-interactively 'org-property-previous-allowed-value))
18314 ((org-clocktable-try-shift 'left arg))
18315 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18316 (org-support-shift-select
18317 (org-call-for-shift-select 'backward-char))
18318 (t (org-shiftselect-error))))
18320 (defun org-shiftcontrolright ()
18321 "Switch to next TODO set."
18322 (interactive)
18323 (cond
18324 ((and org-support-shift-select (org-region-active-p))
18325 (org-call-for-shift-select 'forward-word))
18326 ((and (not (eq org-support-shift-select 'always))
18327 (org-at-heading-p))
18328 (org-call-with-arg 'org-todo 'nextset))
18329 (org-support-shift-select
18330 (org-call-for-shift-select 'forward-word))
18331 (t (org-shiftselect-error))))
18333 (defun org-shiftcontrolleft ()
18334 "Switch to previous TODO set."
18335 (interactive)
18336 (cond
18337 ((and org-support-shift-select (org-region-active-p))
18338 (org-call-for-shift-select 'backward-word))
18339 ((and (not (eq org-support-shift-select 'always))
18340 (org-at-heading-p))
18341 (org-call-with-arg 'org-todo 'previousset))
18342 (org-support-shift-select
18343 (org-call-for-shift-select 'backward-word))
18344 (t (org-shiftselect-error))))
18346 (defun org-shiftcontrolup ()
18347 "Change timestamps synchronously up in CLOCK log lines."
18348 (interactive)
18349 (cond ((and (not org-support-shift-select)
18350 (org-at-clock-log-p)
18351 (org-at-timestamp-p t))
18352 (org-clock-timestamps-up))
18353 (t (org-shiftselect-error))))
18355 (defun org-shiftcontroldown ()
18356 "Change timestamps synchronously down in CLOCK log lines."
18357 (interactive)
18358 (cond ((and (not org-support-shift-select)
18359 (org-at-clock-log-p)
18360 (org-at-timestamp-p t))
18361 (org-clock-timestamps-down))
18362 (t (org-shiftselect-error))))
18364 (defun org-ctrl-c-ret ()
18365 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18366 (interactive)
18367 (cond
18368 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18369 (t (call-interactively 'org-insert-heading))))
18371 (defun org-find-visible ()
18372 (let ((s (point)))
18373 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18374 (get-char-property s 'invisible)))
18376 (defun org-find-invisible ()
18377 (let ((s (point)))
18378 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18379 (not (get-char-property s 'invisible))))
18382 (defun org-copy-visible (beg end)
18383 "Copy the visible parts of the region."
18384 (interactive "r")
18385 (let (snippets s)
18386 (save-excursion
18387 (save-restriction
18388 (narrow-to-region beg end)
18389 (setq s (goto-char (point-min)))
18390 (while (not (= (point) (point-max)))
18391 (goto-char (org-find-invisible))
18392 (push (buffer-substring s (point)) snippets)
18393 (setq s (goto-char (org-find-visible))))))
18394 (kill-new (apply 'concat (nreverse snippets)))))
18396 (defun org-copy-special ()
18397 "Copy region in table or copy current subtree.
18398 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18399 See the individual commands for more information."
18400 (interactive)
18401 (call-interactively
18402 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18404 (defun org-cut-special ()
18405 "Cut region in table or cut current subtree.
18406 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18407 See the individual commands for more information."
18408 (interactive)
18409 (call-interactively
18410 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18412 (defun org-paste-special (arg)
18413 "Paste rectangular region into table, or past subtree relative to level.
18414 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18415 See the individual commands for more information."
18416 (interactive "P")
18417 (if (org-at-table-p)
18418 (org-table-paste-rectangle)
18419 (org-paste-subtree arg)))
18421 (defun org-edit-special (&optional arg)
18422 "Call a special editor for the stuff at point.
18423 When at a table, call the formula editor with `org-table-edit-formulas'.
18424 When at the first line of an src example, call `org-edit-src-code'.
18425 When in an #+include line, visit the include file. Otherwise call
18426 `ffap' to visit the file at point."
18427 (interactive)
18428 ;; possibly prep session before editing source
18429 (when arg
18430 (let* ((info (org-babel-get-src-block-info))
18431 (lang (nth 0 info))
18432 (params (nth 2 info))
18433 (session (cdr (assoc :session params))))
18434 (when (and info session) ;; we are in a source-code block with a session
18435 (funcall
18436 (intern (concat "org-babel-prep-session:" lang)) session params))))
18437 (cond ;; proceed with `org-edit-special'
18438 ((save-excursion
18439 (beginning-of-line 1)
18440 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18441 (find-file (org-trim (match-string 1))))
18442 ((org-edit-src-code))
18443 ((org-edit-fixed-width-region))
18444 ((org-at-table.el-p)
18445 (org-edit-src-code))
18446 ((or (org-at-table-p)
18447 (save-excursion
18448 (beginning-of-line 1)
18449 (looking-at "[ \t]*#\\+TBLFM:")))
18450 (call-interactively 'org-table-edit-formulas))
18451 (t (call-interactively 'ffap))))
18453 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18454 (defun org-ctrl-c-ctrl-c (&optional arg)
18455 "Set tags in headline, or update according to changed information at point.
18457 This command does many different things, depending on context:
18459 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18460 this is what we do.
18462 - If the cursor is on a statistics cookie, update it.
18464 - If the cursor is in a headline, prompt for tags and insert them
18465 into the current line, aligned to `org-tags-column'. When called
18466 with prefix arg, realign all tags in the current buffer.
18468 - If the cursor is in one of the special #+KEYWORD lines, this
18469 triggers scanning the buffer for these lines and updating the
18470 information.
18472 - If the cursor is inside a table, realign the table. This command
18473 works even if the automatic table editor has been turned off.
18475 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18476 the entire table.
18478 - If the cursor is at a footnote reference or definition, jump to
18479 the corresponding definition or references, respectively.
18481 - If the cursor is a the beginning of a dynamic block, update it.
18483 - If the current buffer is a capture buffer, close note and file it.
18485 - If the cursor is on a <<<target>>>, update radio targets and
18486 corresponding links in this buffer.
18488 - If the cursor is on a numbered item in a plain list, renumber the
18489 ordered list.
18491 - If the cursor is on a checkbox, toggle it.
18493 - If the cursor is on a code block, evaluate it. The variable
18494 `org-confirm-babel-evaluate' can be used to control prompting
18495 before code block evaluation, by default every code block
18496 evaluation requires confirmation. Code block evaluation can be
18497 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18498 (interactive "P")
18499 (let ((org-enable-table-editor t))
18500 (cond
18501 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18502 org-occur-highlights
18503 org-latex-fragment-image-overlays)
18504 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18505 (org-remove-occur-highlights)
18506 (org-remove-latex-fragment-image-overlays)
18507 (message "Temporary highlights/overlays removed from current buffer"))
18508 ((and (local-variable-p 'org-finish-function (current-buffer))
18509 (fboundp org-finish-function))
18510 (funcall org-finish-function))
18511 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18512 ((org-in-regexp org-ts-regexp-both)
18513 (org-timestamp-change 0 'day))
18514 ((or (looking-at org-property-start-re)
18515 (org-at-property-p))
18516 (call-interactively 'org-property-action))
18517 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18518 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18519 (or (org-at-heading-p) (org-at-item-p)))
18520 (call-interactively 'org-update-statistics-cookies))
18521 ((org-at-heading-p) (call-interactively 'org-set-tags))
18522 ((org-at-table.el-p)
18523 (message "Use C-c ' to edit table.el tables"))
18524 ((org-at-table-p)
18525 (org-table-maybe-eval-formula)
18526 (if arg
18527 (call-interactively 'org-table-recalculate)
18528 (org-table-maybe-recalculate-line))
18529 (call-interactively 'org-table-align)
18530 (orgtbl-send-table 'maybe))
18531 ((or (org-footnote-at-reference-p)
18532 (org-footnote-at-definition-p))
18533 (call-interactively 'org-footnote-action))
18534 ((org-at-item-checkbox-p)
18535 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18536 ;; list only if at top item.
18537 (let* ((cbox (match-string 1))
18538 (struct (org-list-struct))
18539 (old-struct (copy-tree struct))
18540 (parents (org-list-parents-alist struct))
18541 (orderedp (org-entry-get nil "ORDERED"))
18542 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18543 block-item)
18544 ;; Use a light version of `org-toggle-checkbox' to avoid
18545 ;; computing list structure twice.
18546 (let ((new-box (cond
18547 ((equal arg '(16)) "[-]")
18548 ((equal arg '(4)) nil)
18549 ((equal "[X]" cbox) "[ ]")
18550 (t "[X]"))))
18551 (if (and firstp arg)
18552 ;; If at first item of sub-list, remove check-box from
18553 ;; every item at the same level.
18554 (mapc
18555 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18556 (org-list-get-all-items
18557 (point-at-bol) struct (org-list-prevs-alist struct)))
18558 (org-list-set-checkbox (point-at-bol) struct new-box)))
18559 ;; Replicate `org-list-write-struct', while grabbing a return
18560 ;; value from `org-list-struct-fix-box'.
18561 (org-list-struct-fix-ind struct parents 2)
18562 (org-list-struct-fix-item-end struct)
18563 (let ((prevs (org-list-prevs-alist struct)))
18564 (org-list-struct-fix-bul struct prevs)
18565 (org-list-struct-fix-ind struct parents)
18566 (setq block-item
18567 (org-list-struct-fix-box struct parents prevs orderedp)))
18568 (org-list-struct-apply-struct struct old-struct)
18569 (org-update-checkbox-count-maybe)
18570 (when block-item
18571 (message
18572 "Checkboxes were removed due to unchecked box at line %d"
18573 (org-current-line block-item)))
18574 (when firstp (org-list-send-list 'maybe))))
18575 ((org-at-item-p)
18576 ;; Cursor at an item: repair list. Do checkbox related actions
18577 ;; only if function was called with an argument. Send list only
18578 ;; if at top item.
18579 (let* ((struct (org-list-struct))
18580 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18581 old-struct)
18582 (when arg
18583 (setq old-struct (copy-tree struct))
18584 (if firstp
18585 ;; If at first item of sub-list, add check-box to every
18586 ;; item at the same level.
18587 (mapc
18588 (lambda (pos)
18589 (unless (org-list-get-checkbox pos struct)
18590 (org-list-set-checkbox pos struct "[ ]")))
18591 (org-list-get-all-items
18592 (point-at-bol) struct (org-list-prevs-alist struct)))
18593 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18594 (org-list-write-struct
18595 struct (org-list-parents-alist struct) old-struct)
18596 (when arg (org-update-checkbox-count-maybe))
18597 (when firstp (org-list-send-list 'maybe))))
18598 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18599 ;; Dynamic block
18600 (beginning-of-line 1)
18601 (save-excursion (org-update-dblock)))
18602 ((save-excursion
18603 (beginning-of-line 1)
18604 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18605 (cond
18606 ((equal (match-string 1) "TBLFM")
18607 ;; Recalculate the table before this line
18608 (save-excursion
18609 (beginning-of-line 1)
18610 (skip-chars-backward " \r\n\t")
18611 (if (org-at-table-p)
18612 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18614 (let ((org-inhibit-startup-visibility-stuff t)
18615 (org-startup-align-all-tables nil))
18616 (when (boundp 'org-table-coordinate-overlays)
18617 (mapc 'delete-overlay org-table-coordinate-overlays)
18618 (setq org-table-coordinate-overlays nil))
18619 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18620 (message "Local setup has been refreshed"))))
18621 ((org-clock-update-time-maybe))
18623 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18624 (error "C-c C-c can do nothing useful at this location"))))))
18626 (defun org-mode-restart ()
18627 "Restart Org-mode, to scan again for special lines.
18628 Also updates the keyword regular expressions."
18629 (interactive)
18630 (org-mode)
18631 (message "Org-mode restarted"))
18633 (defun org-kill-note-or-show-branches ()
18634 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18635 (interactive)
18636 (if (not org-finish-function)
18637 (progn
18638 (hide-subtree)
18639 (call-interactively 'show-branches))
18640 (let ((org-note-abort t))
18641 (funcall org-finish-function))))
18643 (defun org-return (&optional indent)
18644 "Goto next table row or insert a newline.
18645 Calls `org-table-next-row' or `newline', depending on context.
18646 See the individual commands for more information."
18647 (interactive)
18648 (cond
18649 ((or (bobp) (org-in-src-block-p))
18650 (if indent (newline-and-indent) (newline)))
18651 ((org-at-table-p)
18652 (org-table-justify-field-maybe)
18653 (call-interactively 'org-table-next-row))
18654 ;; when `newline-and-indent' is called within a list, make sure
18655 ;; text moved stays inside the item.
18656 ((and (org-in-item-p) indent)
18657 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18658 (progn
18659 (save-match-data (newline))
18660 (org-indent-line-to (length (match-string 0))))
18661 (let ((ind (org-get-indentation)))
18662 (newline)
18663 (if (org-looking-back org-list-end-re)
18664 (org-indent-line-function)
18665 (org-indent-line-to ind)))))
18666 ((and org-return-follows-link
18667 (let ((tprop (get-text-property (point) 'face)))
18668 (or (eq tprop 'org-link)
18669 (and (listp tprop) (memq 'org-link tprop)))))
18670 (call-interactively 'org-open-at-point))
18671 ((and (org-at-heading-p)
18672 (looking-at
18673 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18674 (org-show-entry)
18675 (end-of-line 1)
18676 (newline))
18677 (t (if indent (newline-and-indent) (newline)))))
18679 (defun org-return-indent ()
18680 "Goto next table row or insert a newline and indent.
18681 Calls `org-table-next-row' or `newline-and-indent', depending on
18682 context. See the individual commands for more information."
18683 (interactive)
18684 (org-return t))
18686 (defun org-ctrl-c-star ()
18687 "Compute table, or change heading status of lines.
18688 Calls `org-table-recalculate' or `org-toggle-heading',
18689 depending on context."
18690 (interactive)
18691 (cond
18692 ((org-at-table-p)
18693 (call-interactively 'org-table-recalculate))
18695 ;; Convert all lines in region to list items
18696 (call-interactively 'org-toggle-heading))))
18698 (defun org-ctrl-c-minus ()
18699 "Insert separator line in table or modify bullet status of line.
18700 Also turns a plain line or a region of lines into list items.
18701 Calls `org-table-insert-hline', `org-toggle-item', or
18702 `org-cycle-list-bullet', depending on context."
18703 (interactive)
18704 (cond
18705 ((org-at-table-p)
18706 (call-interactively 'org-table-insert-hline))
18707 ((org-region-active-p)
18708 (call-interactively 'org-toggle-item))
18709 ((org-in-item-p)
18710 (call-interactively 'org-cycle-list-bullet))
18712 (call-interactively 'org-toggle-item))))
18714 (defun org-toggle-item (arg)
18715 "Convert headings or normal lines to items, items to normal lines.
18716 If there is no active region, only the current line is considered.
18718 If the first non blank line in the region is an headline, convert
18719 all headlines to items, shifting text accordingly.
18721 If it is an item, convert all items to normal lines.
18723 If it is normal text, change region into an item. With a prefix
18724 argument ARG, change each line in region into an item."
18725 (interactive "P")
18726 (let ((shift-text
18727 (function
18728 ;; Shift text in current section to IND, from point to END.
18729 ;; The function leaves point to END line.
18730 (lambda (ind end)
18731 (let ((min-i 1000) (end (copy-marker end)))
18732 ;; First determine the minimum indentation (MIN-I) of
18733 ;; the text.
18734 (save-excursion
18735 (catch 'exit
18736 (while (< (point) end)
18737 (let ((i (org-get-indentation)))
18738 (cond
18739 ;; Skip blank lines and inline tasks.
18740 ((looking-at "^[ \t]*$"))
18741 ((looking-at org-outline-regexp-bol))
18742 ;; We can't find less than 0 indentation.
18743 ((zerop i) (throw 'exit (setq min-i 0)))
18744 ((< i min-i) (setq min-i i))))
18745 (forward-line))))
18746 ;; Then indent each line so that a line indented to
18747 ;; MIN-I becomes indented to IND. Ignore blank lines
18748 ;; and inline tasks in the process.
18749 (let ((delta (- ind min-i)))
18750 (while (< (point) end)
18751 (unless (or (looking-at "^[ \t]*$")
18752 (looking-at org-outline-regexp-bol))
18753 (org-indent-line-to (+ (org-get-indentation) delta)))
18754 (forward-line)))))))
18755 (skip-blanks
18756 (function
18757 ;; Return beginning of first non-blank line, starting from
18758 ;; line at POS.
18759 (lambda (pos)
18760 (save-excursion
18761 (goto-char pos)
18762 (skip-chars-forward " \r\t\n")
18763 (point-at-bol)))))
18764 beg end)
18765 ;; Determine boundaries of changes.
18766 (if (org-region-active-p)
18767 (setq beg (funcall skip-blanks (region-beginning))
18768 end (copy-marker (region-end)))
18769 (setq beg (funcall skip-blanks (point-at-bol))
18770 end (copy-marker (point-at-eol))))
18771 ;; Depending on the starting line, choose an action on the text
18772 ;; between BEG and END.
18773 (org-with-limited-levels
18774 (save-excursion
18775 (goto-char beg)
18776 (cond
18777 ;; Case 1. Start at an item: de-itemize. Note that it only
18778 ;; happens when a region is active: `org-ctrl-c-minus'
18779 ;; would call `org-cycle-list-bullet' otherwise.
18780 ((org-at-item-p)
18781 (while (< (point) end)
18782 (when (org-at-item-p)
18783 (skip-chars-forward " \t")
18784 (delete-region (point) (match-end 0)))
18785 (forward-line)))
18786 ;; Case 2. Start at an heading: convert to items.
18787 ((org-at-heading-p)
18788 (let* ((bul (org-list-bullet-string "-"))
18789 (bul-len (length bul))
18790 ;; Indentation of the first heading. It should be
18791 ;; relative to the indentation of its parent, if any.
18792 (start-ind (save-excursion
18793 (cond
18794 ((not org-adapt-indentation) 0)
18795 ((not (outline-previous-heading)) 0)
18796 (t (length (match-string 0))))))
18797 ;; Level of first heading. Further headings will be
18798 ;; compared to it to determine hierarchy in the list.
18799 (ref-level (org-reduced-level (org-outline-level))))
18800 (while (< (point) end)
18801 (let* ((level (org-reduced-level (org-outline-level)))
18802 (delta (max 0 (- level ref-level))))
18803 ;; If current headline is less indented than the first
18804 ;; one, set it as reference, in order to preserve
18805 ;; subtrees.
18806 (when (< level ref-level) (setq ref-level level))
18807 (replace-match bul t t)
18808 (org-indent-line-to (+ start-ind (* delta bul-len)))
18809 ;; Ensure all text down to END (or SECTION-END) belongs
18810 ;; to the newly created item.
18811 (let ((section-end (save-excursion
18812 (or (outline-next-heading) (point)))))
18813 (forward-line)
18814 (funcall shift-text
18815 (+ start-ind (* (1+ delta) bul-len))
18816 (min end section-end)))))))
18817 ;; Case 3. Normal line with ARG: turn each non-item line into
18818 ;; an item.
18819 (arg
18820 (while (< (point) end)
18821 (unless (or (org-at-heading-p) (org-at-item-p))
18822 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18823 (replace-match
18824 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18825 (forward-line)))
18826 ;; Case 4. Normal line without ARG: make the first line of
18827 ;; region an item, and shift indentation of others
18828 ;; lines to set them as item's body.
18829 (t (let* ((bul (org-list-bullet-string "-"))
18830 (bul-len (length bul))
18831 (ref-ind (org-get-indentation)))
18832 (skip-chars-forward " \t")
18833 (insert bul)
18834 (forward-line)
18835 (while (< (point) end)
18836 ;; Ensure that lines less indented than first one
18837 ;; still get included in item body.
18838 (funcall shift-text
18839 (+ ref-ind bul-len)
18840 (min end (save-excursion (or (outline-next-heading)
18841 (point)))))
18842 (forward-line)))))))))
18844 (defun org-toggle-heading (&optional nstars)
18845 "Convert headings to normal text, or items or text to headings.
18846 If there is no active region, only the current line is considered.
18848 If the first non blank line is an headline, remove the stars from
18849 all headlines in the region.
18851 If it is a plain list item, turn all plain list items into headings.
18853 If it is a normal line, turn each and every normal line (i.e. not
18854 an heading or an item) in the region into a heading.
18856 When converting a line into a heading, the number of stars is chosen
18857 such that the lines become children of the current entry. However,
18858 when a prefix argument is given, its value determines the number of
18859 stars to add."
18860 (interactive "P")
18861 (let ((skip-blanks
18862 (function
18863 ;; Return beginning of first non-blank line, starting from
18864 ;; line at POS.
18865 (lambda (pos)
18866 (save-excursion
18867 (goto-char pos)
18868 (skip-chars-forward " \r\t\n")
18869 (point-at-bol)))))
18870 beg end)
18871 ;; Determine boundaries of changes. If region ends at a bol, do
18872 ;; not consider the last line to be in the region.
18873 (if (org-region-active-p)
18874 (setq beg (funcall skip-blanks (region-beginning))
18875 end (copy-marker (save-excursion
18876 (goto-char (region-end))
18877 (if (bolp) (point) (point-at-eol)))))
18878 (setq beg (funcall skip-blanks (point-at-bol))
18879 end (copy-marker (point-at-eol))))
18880 ;; Ensure inline tasks don't count as headings.
18881 (org-with-limited-levels
18882 (save-excursion
18883 (goto-char beg)
18884 (cond
18885 ;; Case 1. Started at an heading: de-star headings.
18886 ((org-at-heading-p)
18887 (while (< (point) end)
18888 (when (org-at-heading-p t)
18889 (looking-at org-outline-regexp) (replace-match ""))
18890 (forward-line)))
18891 ;; Case 2. Started at an item: change items into headlines.
18892 ;; One star will be added by `org-list-to-subtree'.
18893 ((org-at-item-p)
18894 (let* ((stars (make-string
18895 (if nstars
18896 ;; subtract the star that will be added again by
18897 ;; `org-list-to-subtree'
18898 (1- (prefix-numeric-value current-prefix-arg))
18899 (or (org-current-level) 0))
18900 ?*))
18901 (add-stars
18902 (cond (nstars "") ; stars from prefix only
18903 ((equal stars "") "") ; before first heading
18904 (org-odd-levels-only "*") ; inside heading, odd
18905 (t "")))) ; inside heading, oddeven
18906 (while (< (point) end)
18907 (when (org-at-item-p)
18908 ;; Pay attention to cases when region ends before list.
18909 (let* ((struct (org-list-struct))
18910 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18911 (save-restriction
18912 (narrow-to-region (point) list-end)
18913 (insert
18914 (org-list-to-subtree
18915 (org-list-parse-list t)
18916 '(:istart (concat stars add-stars (funcall get-stars depth))
18917 :icount (concat stars add-stars (funcall get-stars depth))))))))
18918 (forward-line))))
18919 ;; Case 3. Started at normal text: make every line an heading,
18920 ;; skipping headlines and items.
18921 (t (let* ((stars (make-string
18922 (if nstars
18923 (prefix-numeric-value current-prefix-arg)
18924 (or (org-current-level) 0))
18925 ?*))
18926 (add-stars
18927 (cond (nstars "") ; stars from prefix only
18928 ((equal stars "") "*") ; before first heading
18929 (org-odd-levels-only "**") ; inside heading, odd
18930 (t "*"))) ; inside heading, oddeven
18931 (rpl (concat stars add-stars " ")))
18932 (while (< (point) end)
18933 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18934 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18935 (replace-match (concat rpl (match-string 2))))
18936 (forward-line)))))))))
18938 (defun org-meta-return (&optional arg)
18939 "Insert a new heading or wrap a region in a table.
18940 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18941 See the individual commands for more information."
18942 (interactive "P")
18943 (cond
18944 ((run-hook-with-args-until-success 'org-metareturn-hook))
18945 ((or (org-at-drawer-p) (org-at-property-p))
18946 (newline-and-indent))
18947 ((org-at-table-p)
18948 (call-interactively 'org-table-wrap-region))
18949 (t (call-interactively 'org-insert-heading))))
18951 ;;; Menu entries
18953 ;; Define the Org-mode menus
18954 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18955 '("Tbl"
18956 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18957 ["Next Field" org-cycle (org-at-table-p)]
18958 ["Previous Field" org-shifttab (org-at-table-p)]
18959 ["Next Row" org-return (org-at-table-p)]
18960 "--"
18961 ["Blank Field" org-table-blank-field (org-at-table-p)]
18962 ["Edit Field" org-table-edit-field (org-at-table-p)]
18963 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18964 "--"
18965 ("Column"
18966 ["Move Column Left" org-metaleft (org-at-table-p)]
18967 ["Move Column Right" org-metaright (org-at-table-p)]
18968 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18969 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18970 ("Row"
18971 ["Move Row Up" org-metaup (org-at-table-p)]
18972 ["Move Row Down" org-metadown (org-at-table-p)]
18973 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18974 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18975 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18976 "--"
18977 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18978 ("Rectangle"
18979 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18980 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18981 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18982 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18983 "--"
18984 ("Calculate"
18985 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18986 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18987 ["Edit Formulas" org-edit-special (org-at-table-p)]
18988 "--"
18989 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18990 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18991 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18992 "--"
18993 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18994 "--"
18995 ["Sum Column/Rectangle" org-table-sum
18996 (or (org-at-table-p) (org-region-active-p))]
18997 ["Which Column?" org-table-current-column (org-at-table-p)])
18998 ["Debug Formulas"
18999 org-table-toggle-formula-debugger
19000 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19001 ["Show Col/Row Numbers"
19002 org-table-toggle-coordinate-overlays
19003 :style toggle
19004 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19005 "--"
19006 ["Create" org-table-create (and (not (org-at-table-p))
19007 org-enable-table-editor)]
19008 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19009 ["Import from File" org-table-import (not (org-at-table-p))]
19010 ["Export to File" org-table-export (org-at-table-p)]
19011 "--"
19012 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19014 (easy-menu-define org-org-menu org-mode-map "Org menu"
19015 '("Org"
19016 ("Show/Hide"
19017 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19018 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19019 ["Sparse Tree..." org-sparse-tree t]
19020 ["Reveal Context" org-reveal t]
19021 ["Show All" show-all t]
19022 "--"
19023 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19024 "--"
19025 ["New Heading" org-insert-heading t]
19026 ("Navigate Headings"
19027 ["Up" outline-up-heading t]
19028 ["Next" outline-next-visible-heading t]
19029 ["Previous" outline-previous-visible-heading t]
19030 ["Next Same Level" outline-forward-same-level t]
19031 ["Previous Same Level" outline-backward-same-level t]
19032 "--"
19033 ["Jump" org-goto t])
19034 ("Edit Structure"
19035 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19036 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19037 "--"
19038 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19039 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19040 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19041 "--"
19042 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19043 "--"
19044 ["Copy visible text" org-copy-visible t]
19045 "--"
19046 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19047 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19048 ["Demote Heading" org-metaright (not (org-at-table-p))]
19049 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19050 "--"
19051 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19052 "--"
19053 ["Convert to odd levels" org-convert-to-odd-levels t]
19054 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19055 ("Editing"
19056 ["Emphasis..." org-emphasize t]
19057 ["Edit Source Example" org-edit-special t]
19058 "--"
19059 ["Footnote new/jump" org-footnote-action t]
19060 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19061 ("Archive"
19062 ["Archive (default method)" org-archive-subtree-default t]
19063 "--"
19064 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19065 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19066 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19068 "--"
19069 ("Hyperlinks"
19070 ["Store Link (Global)" org-store-link t]
19071 ["Find existing link to here" org-occur-link-in-agenda-files t]
19072 ["Insert Link" org-insert-link t]
19073 ["Follow Link" org-open-at-point t]
19074 "--"
19075 ["Next link" org-next-link t]
19076 ["Previous link" org-previous-link t]
19077 "--"
19078 ["Descriptive Links"
19079 org-toggle-link-display
19080 :style radio
19081 :selected org-descriptive-links
19083 ["Literal Links"
19084 org-toggle-link-display
19085 :style radio
19086 :selected (not org-descriptive-links)])
19087 "--"
19088 ("TODO Lists"
19089 ["TODO/DONE/-" org-todo t]
19090 ("Select keyword"
19091 ["Next keyword" org-shiftright (org-at-heading-p)]
19092 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19093 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19094 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19095 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19096 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19097 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19098 "--"
19099 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19100 :selected org-enforce-todo-dependencies :style toggle :active t]
19101 "Settings for tree at point"
19102 ["Do Children sequentially" org-toggle-ordered-property :style radio
19103 :selected (org-entry-get nil "ORDERED")
19104 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19105 ["Do Children parallel" org-toggle-ordered-property :style radio
19106 :selected (not (org-entry-get nil "ORDERED"))
19107 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19108 "--"
19109 ["Set Priority" org-priority t]
19110 ["Priority Up" org-shiftup t]
19111 ["Priority Down" org-shiftdown t]
19112 "--"
19113 ["Get news from all feeds" org-feed-update-all t]
19114 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19115 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19116 ("TAGS and Properties"
19117 ["Set Tags" org-set-tags-command t]
19118 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19119 "--"
19120 ["Set property" org-set-property t]
19121 ["Column view of properties" org-columns t]
19122 ["Insert Column View DBlock" org-insert-columns-dblock t])
19123 ("Dates and Scheduling"
19124 ["Timestamp" org-time-stamp t]
19125 ["Timestamp (inactive)" org-time-stamp-inactive t]
19126 ("Change Date"
19127 ["1 Day Later" org-shiftright t]
19128 ["1 Day Earlier" org-shiftleft t]
19129 ["1 ... Later" org-shiftup t]
19130 ["1 ... Earlier" org-shiftdown t])
19131 ["Compute Time Range" org-evaluate-time-range t]
19132 ["Schedule Item" org-schedule t]
19133 ["Deadline" org-deadline t]
19134 "--"
19135 ["Custom time format" org-toggle-time-stamp-overlays
19136 :style radio :selected org-display-custom-times]
19137 "--"
19138 ["Goto Calendar" org-goto-calendar t]
19139 ["Date from Calendar" org-date-from-calendar t]
19140 "--"
19141 ["Start/Restart Timer" org-timer-start t]
19142 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19143 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19144 ["Insert Timer String" org-timer t]
19145 ["Insert Timer Item" org-timer-item t])
19146 ("Logging work"
19147 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19148 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19149 ["Clock out" org-clock-out t]
19150 ["Clock cancel" org-clock-cancel t]
19151 "--"
19152 ["Mark as default task" org-clock-mark-default-task t]
19153 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19154 ["Goto running clock" org-clock-goto t]
19155 "--"
19156 ["Display times" org-clock-display t]
19157 ["Create clock table" org-clock-report t]
19158 "--"
19159 ["Record DONE time"
19160 (progn (setq org-log-done (not org-log-done))
19161 (message "Switching to %s will %s record a timestamp"
19162 (car org-done-keywords)
19163 (if org-log-done "automatically" "not")))
19164 :style toggle :selected org-log-done])
19165 "--"
19166 ["Agenda Command..." org-agenda t]
19167 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19168 ("File List for Agenda")
19169 ("Special views current file"
19170 ["TODO Tree" org-show-todo-tree t]
19171 ["Check Deadlines" org-check-deadlines t]
19172 ["Timeline" org-timeline t]
19173 ["Tags/Property tree" org-match-sparse-tree t])
19174 "--"
19175 ["Export/Publish..." org-export t]
19176 ("LaTeX"
19177 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19178 :selected org-cdlatex-mode]
19179 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19180 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19181 ["Modify math symbol" org-cdlatex-math-modify
19182 (org-inside-LaTeX-fragment-p)]
19183 ["Insert citation" org-reftex-citation t]
19184 "--"
19185 ["Template for BEAMER" org-insert-beamer-options-template t])
19186 "--"
19187 ("MobileOrg"
19188 ["Push Files and Views" org-mobile-push t]
19189 ["Get Captured and Flagged" org-mobile-pull t]
19190 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19191 "--"
19192 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19193 "--"
19194 ("Documentation"
19195 ["Show Version" org-version t]
19196 ["Info Documentation" org-info t])
19197 ("Customize"
19198 ["Browse Org Group" org-customize t]
19199 "--"
19200 ["Expand This Menu" org-create-customize-menu
19201 (fboundp 'customize-menu-create)])
19202 ["Send bug report" org-submit-bug-report t]
19203 "--"
19204 ("Refresh/Reload"
19205 ["Refresh setup current buffer" org-mode-restart t]
19206 ["Reload Org (after update)" org-reload t]
19207 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19210 (defun org-info (&optional node)
19211 "Read documentation for Org-mode in the info system.
19212 With optional NODE, go directly to that node."
19213 (interactive)
19214 (info (format "(org)%s" (or node ""))))
19216 ;;;###autoload
19217 (defun org-submit-bug-report ()
19218 "Submit a bug report on Org-mode via mail.
19220 Don't hesitate to report any problems or inaccurate documentation.
19222 If you don't have setup sending mail from (X)Emacs, please copy the
19223 output buffer into your mail program, as it gives us important
19224 information about your Org-mode version and configuration."
19225 (interactive)
19226 (require 'reporter)
19227 (org-load-modules-maybe)
19228 (org-require-autoloaded-modules)
19229 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19230 (reporter-submit-bug-report
19231 "emacs-orgmode@gnu.org"
19232 (org-version)
19233 (let (list)
19234 (save-window-excursion
19235 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19236 (delete-other-windows)
19237 (erase-buffer)
19238 (insert "You are about to submit a bug report to the Org-mode mailing list.
19240 We would like to add your full Org-mode and Outline configuration to the
19241 bug report. This greatly simplifies the work of the maintainer and
19242 other experts on the mailing list.
19244 HOWEVER, some variables you have customized may contain private
19245 information. The names of customers, colleagues, or friends, might
19246 appear in the form of file names, tags, todo states, or search strings.
19247 If you answer yes to the prompt, you might want to check and remove
19248 such private information before sending the email.")
19249 (add-text-properties (point-min) (point-max) '(face org-warning))
19250 (when (yes-or-no-p "Include your Org-mode configuration ")
19251 (mapatoms
19252 (lambda (v)
19253 (and (boundp v)
19254 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19255 (or (and (symbol-value v)
19256 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19257 (and
19258 (get v 'custom-type) (get v 'standard-value)
19259 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19260 (push v list)))))
19261 (kill-buffer (get-buffer "*Warn about privacy*"))
19262 list))
19263 nil nil
19264 "Remember to cover the basics, that is, what you expected to happen and
19265 what in fact did happen. You don't know how to make a good report? See
19267 http://orgmode.org/manual/Feedback.html#Feedback
19269 Your bug report will be posted to the Org-mode mailing list.
19270 ------------------------------------------------------------------------")
19271 (save-excursion
19272 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19273 (replace-match "\\1Bug: \\3 [\\2]")))))
19276 (defun org-install-agenda-files-menu ()
19277 (let ((bl (buffer-list)))
19278 (save-excursion
19279 (while bl
19280 (set-buffer (pop bl))
19281 (if (eq major-mode 'org-mode) (setq bl nil)))
19282 (when (eq major-mode 'org-mode)
19283 (easy-menu-change
19284 '("Org") "File List for Agenda"
19285 (append
19286 (list
19287 ["Edit File List" (org-edit-agenda-file-list) t]
19288 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19289 ["Remove Current File from List" org-remove-file t]
19290 ["Cycle through agenda files" org-cycle-agenda-files t]
19291 ["Occur in all agenda files" org-occur-in-agenda-files t]
19292 "--")
19293 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19295 ;;;; Documentation
19297 ;;;###autoload
19298 (defun org-require-autoloaded-modules ()
19299 (interactive)
19300 (mapc 'require
19301 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19302 org-docbook org-exp org-html org-icalendar
19303 org-id org-latex
19304 org-publish org-remember org-table
19305 org-timer org-xoxo)))
19307 ;;;###autoload
19308 (defun org-reload (&optional uncompiled)
19309 "Reload all org lisp files.
19310 With prefix arg UNCOMPILED, load the uncompiled versions."
19311 (interactive "P")
19312 (require 'find-func)
19313 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19314 (dir-org (file-name-directory (org-find-library-name "org")))
19315 (dir-org-contrib (ignore-errors
19316 (file-name-directory
19317 (org-find-library-name "org-contribdir"))))
19318 (babel-files
19319 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19320 (append (list nil "comint" "eval" "exp" "keys"
19321 "lob" "ref" "table" "tangle")
19322 (delq nil
19323 (mapcar
19324 (lambda (lang)
19325 (when (cdr lang) (symbol-name (car lang))))
19326 org-babel-load-languages)))))
19327 (files
19328 (append (directory-files dir-org t file-re)
19329 babel-files
19330 (and dir-org-contrib
19331 (directory-files dir-org-contrib t file-re))))
19332 (remove-re (concat (if (featurep 'xemacs)
19333 "org-colview" "org-colview-xemacs")
19334 "\\'")))
19335 (setq files (mapcar 'file-name-sans-extension files))
19336 (setq files (mapcar
19337 (lambda (x) (if (string-match remove-re x) nil x))
19338 files))
19339 (setq files (delq nil files))
19340 (mapc
19341 (lambda (f)
19342 (when (featurep (intern (file-name-nondirectory f)))
19343 (if (and (not uncompiled)
19344 (file-exists-p (concat f ".elc")))
19345 (load (concat f ".elc") nil nil t)
19346 (load (concat f ".el") nil nil t))))
19347 files))
19348 (org-version))
19350 ;;;###autoload
19351 (defun org-customize ()
19352 "Call the customize function with org as argument."
19353 (interactive)
19354 (org-load-modules-maybe)
19355 (org-require-autoloaded-modules)
19356 (customize-browse 'org))
19358 (defun org-create-customize-menu ()
19359 "Create a full customization menu for Org-mode, insert it into the menu."
19360 (interactive)
19361 (org-load-modules-maybe)
19362 (org-require-autoloaded-modules)
19363 (if (fboundp 'customize-menu-create)
19364 (progn
19365 (easy-menu-change
19366 '("Org") "Customize"
19367 `(["Browse Org group" org-customize t]
19368 "--"
19369 ,(customize-menu-create 'org)
19370 ["Set" Custom-set t]
19371 ["Save" Custom-save t]
19372 ["Reset to Current" Custom-reset-current t]
19373 ["Reset to Saved" Custom-reset-saved t]
19374 ["Reset to Standard Settings" Custom-reset-standard t]))
19375 (message "\"Org\"-menu now contains full customization menu"))
19376 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19378 ;;;; Miscellaneous stuff
19380 ;;; Generally useful functions
19382 (defun org-get-at-bol (property)
19383 "Get text property PROPERTY at beginning of line."
19384 (get-text-property (point-at-bol) property))
19386 (defun org-find-text-property-in-string (prop s)
19387 "Return the first non-nil value of property PROP in string S."
19388 (or (get-text-property 0 prop s)
19389 (get-text-property (or (next-single-property-change 0 prop s) 0)
19390 prop s)))
19392 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19393 "Display the given MESSAGE as a warning."
19394 (if (fboundp 'display-warning)
19395 (display-warning 'org message
19396 (if (featurep 'xemacs) 'warning :warning))
19397 (let ((buf (get-buffer-create "*Org warnings*")))
19398 (with-current-buffer buf
19399 (goto-char (point-max))
19400 (insert "Warning (Org): " message)
19401 (unless (bolp)
19402 (newline)))
19403 (display-buffer buf)
19404 (sit-for 0))))
19406 (defun org-eval (form)
19407 "Eval FORM and return result."
19408 (condition-case error
19409 (eval form)
19410 (error (format "%%![Error: %s]" error))))
19412 (defun org-in-clocktable-p ()
19413 "Check if the cursor is in a clocktable."
19414 (let ((pos (point)) start)
19415 (save-excursion
19416 (end-of-line 1)
19417 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19418 (setq start (match-beginning 0))
19419 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19420 (>= (match-end 0) pos)
19421 start))))
19423 (defun org-in-commented-line ()
19424 "Is point in a line starting with `#'?"
19425 (equal (char-after (point-at-bol)) ?#))
19427 (defun org-in-indented-comment-line ()
19428 "Is point in a line starting with `#' after some white space?"
19429 (save-excursion
19430 (save-match-data
19431 (goto-char (point-at-bol))
19432 (looking-at "[ \t]*#"))))
19434 (defun org-in-verbatim-emphasis ()
19435 (save-match-data
19436 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19438 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19439 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19440 (if (and marker (marker-buffer marker)
19441 (buffer-live-p (marker-buffer marker)))
19442 (progn
19443 (org-pop-to-buffer-same-window (marker-buffer marker))
19444 (if (or (> marker (point-max)) (< marker (point-min)))
19445 (widen))
19446 (goto-char marker)
19447 (org-show-context 'org-goto))
19448 (if bookmark
19449 (bookmark-jump bookmark)
19450 (error "Cannot find location"))))
19452 (defun org-quote-csv-field (s)
19453 "Quote field for inclusion in CSV material."
19454 (if (string-match "[\",]" s)
19455 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19458 (defun org-force-self-insert (N)
19459 "Needed to enforce self-insert under remapping."
19460 (interactive "p")
19461 (self-insert-command N))
19463 (defun org-string-width (s)
19464 "Compute width of string, ignoring invisible characters.
19465 This ignores character with invisibility property `org-link', and also
19466 characters with property `org-cwidth', because these will become invisible
19467 upon the next fontification round."
19468 (let (b l)
19469 (when (or (eq t buffer-invisibility-spec)
19470 (assq 'org-link buffer-invisibility-spec))
19471 (while (setq b (text-property-any 0 (length s)
19472 'invisible 'org-link s))
19473 (setq s (concat (substring s 0 b)
19474 (substring s (or (next-single-property-change
19475 b 'invisible s) (length s)))))))
19476 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19477 (setq s (concat (substring s 0 b)
19478 (substring s (or (next-single-property-change
19479 b 'org-cwidth s) (length s))))))
19480 (setq l (string-width s) b -1)
19481 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19482 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19485 (defun org-shorten-string (s maxlength)
19486 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19487 If the string is shorter or has length MAXLENGTH, just return the
19488 original string. If it is longer, the functions finds a space in the
19489 string, breaks this string off at that locations and adds three dots
19490 as ellipsis. Including the ellipsis, the string will not be longer
19491 than MAXLENGTH. If finding a good breaking point in the string does
19492 not work, the string is just chopped off in the middle of a word
19493 if necessary."
19494 (if (<= (length s) maxlength)
19496 (let* ((n (max (- maxlength 4) 1))
19497 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19498 (if (string-match re s)
19499 (concat (match-string 1 s) "...")
19500 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19502 (defun org-get-indentation (&optional line)
19503 "Get the indentation of the current line, interpreting tabs.
19504 When LINE is given, assume it represents a line and compute its indentation."
19505 (if line
19506 (if (string-match "^ *" (org-remove-tabs line))
19507 (match-end 0))
19508 (save-excursion
19509 (beginning-of-line 1)
19510 (skip-chars-forward " \t")
19511 (current-column))))
19513 (defun org-get-string-indentation (s)
19514 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19515 (let ((n -1) (i 0) (w tab-width) c)
19516 (catch 'exit
19517 (while (< (setq n (1+ n)) (length s))
19518 (setq c (aref s n))
19519 (cond ((= c ?\ ) (setq i (1+ i)))
19520 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19521 (t (throw 'exit t)))))
19524 (defun org-remove-tabs (s &optional width)
19525 "Replace tabulators in S with spaces.
19526 Assumes that s is a single line, starting in column 0."
19527 (setq width (or width tab-width))
19528 (while (string-match "\t" s)
19529 (setq s (replace-match
19530 (make-string
19531 (- (* width (/ (+ (match-beginning 0) width) width))
19532 (match-beginning 0)) ?\ )
19533 t t s)))
19536 (defun org-fix-indentation (line ind)
19537 "Fix indentation in LINE.
19538 IND is a cons cell with target and minimum indentation.
19539 If the current indentation in LINE is smaller than the minimum,
19540 leave it alone. If it is larger than ind, set it to the target."
19541 (let* ((l (org-remove-tabs line))
19542 (i (org-get-indentation l))
19543 (i1 (car ind)) (i2 (cdr ind)))
19544 (if (>= i i2) (setq l (substring line i2)))
19545 (if (> i1 0)
19546 (concat (make-string i1 ?\ ) l)
19547 l)))
19549 (defun org-remove-indentation (code &optional n)
19550 "Remove the maximum common indentation from the lines in CODE.
19551 N may optionally be the number of spaces to remove."
19552 (with-temp-buffer
19553 (insert code)
19554 (org-do-remove-indentation n)
19555 (buffer-string)))
19557 (defun org-do-remove-indentation (&optional n)
19558 "Remove the maximum common indentation from the buffer."
19559 (untabify (point-min) (point-max))
19560 (let ((min 10000) re)
19561 (if n
19562 (setq min n)
19563 (goto-char (point-min))
19564 (while (re-search-forward "^ *[^ \n]" nil t)
19565 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19566 (unless (or (= min 0) (= min 10000))
19567 (setq re (format "^ \\{%d\\}" min))
19568 (goto-char (point-min))
19569 (while (re-search-forward re nil t)
19570 (replace-match "")
19571 (end-of-line 1))
19572 min)))
19574 (defun org-fill-template (template alist)
19575 "Find each %key of ALIST in TEMPLATE and replace it."
19576 (let ((case-fold-search nil)
19577 entry key value)
19578 (setq alist (sort (copy-sequence alist)
19579 (lambda (a b) (< (length (car a)) (length (car b))))))
19580 (while (setq entry (pop alist))
19581 (setq template
19582 (replace-regexp-in-string
19583 (concat "%" (regexp-quote (car entry)))
19584 (cdr entry) template t t)))
19585 template))
19587 (defun org-base-buffer (buffer)
19588 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19589 (if (not buffer)
19590 buffer
19591 (or (buffer-base-buffer buffer)
19592 buffer)))
19594 (defun org-trim (s)
19595 "Remove whitespace at beginning and end of string."
19596 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19597 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19600 (defun org-wrap (string &optional width lines)
19601 "Wrap string to either a number of lines, or a width in characters.
19602 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19603 that costs. If there is a word longer than WIDTH, the text is actually
19604 wrapped to the length of that word.
19605 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19606 many lines, whatever width that takes.
19607 The return value is a list of lines, without newlines at the end."
19608 (let* ((words (org-split-string string "[ \t\n]+"))
19609 (maxword (apply 'max (mapcar 'org-string-width words)))
19610 w ll)
19611 (cond (width
19612 (org-do-wrap words (max maxword width)))
19613 (lines
19614 (setq w maxword)
19615 (setq ll (org-do-wrap words maxword))
19616 (if (<= (length ll) lines)
19618 (setq ll words)
19619 (while (> (length ll) lines)
19620 (setq w (1+ w))
19621 (setq ll (org-do-wrap words w)))
19622 ll))
19623 (t (error "Cannot wrap this")))))
19625 (defun org-do-wrap (words width)
19626 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19627 (let (lines line)
19628 (while words
19629 (setq line (pop words))
19630 (while (and words (< (+ (length line) (length (car words))) width))
19631 (setq line (concat line " " (pop words))))
19632 (setq lines (push line lines)))
19633 (nreverse lines)))
19635 (defun org-split-string (string &optional separators)
19636 "Splits STRING into substrings at SEPARATORS.
19637 No empty strings are returned if there are matches at the beginning
19638 and end of string."
19639 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19640 (start 0)
19641 notfirst
19642 (list nil))
19643 (while (and (string-match rexp string
19644 (if (and notfirst
19645 (= start (match-beginning 0))
19646 (< start (length string)))
19647 (1+ start) start))
19648 (< (match-beginning 0) (length string)))
19649 (setq notfirst t)
19650 (or (eq (match-beginning 0) 0)
19651 (and (eq (match-beginning 0) (match-end 0))
19652 (eq (match-beginning 0) start))
19653 (setq list
19654 (cons (substring string start (match-beginning 0))
19655 list)))
19656 (setq start (match-end 0)))
19657 (or (eq start (length string))
19658 (setq list
19659 (cons (substring string start)
19660 list)))
19661 (nreverse list)))
19663 (defun org-quote-vert (s)
19664 "Replace \"|\" with \"\\vert\"."
19665 (while (string-match "|" s)
19666 (setq s (replace-match "\\vert" t t s)))
19669 (defun org-uuidgen-p (s)
19670 "Is S an ID created by UUIDGEN?"
19671 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19673 (defun org-in-src-block-p nil
19674 "Whether point is in a code source block."
19675 (let (ov)
19676 (when (setq ov (overlays-at (point)))
19677 (memq 'org-block-background
19678 (overlay-properties
19679 (car ov))))))
19681 (defun org-context ()
19682 "Return a list of contexts of the current cursor position.
19683 If several contexts apply, all are returned.
19684 Each context entry is a list with a symbol naming the context, and
19685 two positions indicating start and end of the context. Possible
19686 contexts are:
19688 :headline anywhere in a headline
19689 :headline-stars on the leading stars in a headline
19690 :todo-keyword on a TODO keyword (including DONE) in a headline
19691 :tags on the TAGS in a headline
19692 :priority on the priority cookie in a headline
19693 :item on the first line of a plain list item
19694 :item-bullet on the bullet/number of a plain list item
19695 :checkbox on the checkbox in a plain list item
19696 :table in an org-mode table
19697 :table-special on a special filed in a table
19698 :table-table in a table.el table
19699 :clocktable in a clocktable
19700 :src-block in a source block
19701 :link on a hyperlink
19702 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19703 :target on a <<target>>
19704 :radio-target on a <<<radio-target>>>
19705 :latex-fragment on a LaTeX fragment
19706 :latex-preview on a LaTeX fragment with overlaid preview image
19708 This function expects the position to be visible because it uses font-lock
19709 faces as a help to recognize the following contexts: :table-special, :link,
19710 and :keyword."
19711 (let* ((f (get-text-property (point) 'face))
19712 (faces (if (listp f) f (list f)))
19713 (case-fold-search t)
19714 (p (point)) clist o)
19715 ;; First the large context
19716 (cond
19717 ((org-at-heading-p t)
19718 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19719 (when (progn
19720 (beginning-of-line 1)
19721 (looking-at org-todo-line-tags-regexp))
19722 (push (org-point-in-group p 1 :headline-stars) clist)
19723 (push (org-point-in-group p 2 :todo-keyword) clist)
19724 (push (org-point-in-group p 4 :tags) clist))
19725 (goto-char p)
19726 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19727 (if (looking-at "\\[#[A-Z0-9]\\]")
19728 (push (org-point-in-group p 0 :priority) clist)))
19730 ((org-at-item-p)
19731 (push (org-point-in-group p 2 :item-bullet) clist)
19732 (push (list :item (point-at-bol)
19733 (save-excursion (org-end-of-item) (point)))
19734 clist)
19735 (and (org-at-item-checkbox-p)
19736 (push (org-point-in-group p 0 :checkbox) clist)))
19738 ((org-at-table-p)
19739 (push (list :table (org-table-begin) (org-table-end)) clist)
19740 (if (memq 'org-formula faces)
19741 (push (list :table-special
19742 (previous-single-property-change p 'face)
19743 (next-single-property-change p 'face)) clist)))
19744 ((org-at-table-p 'any)
19745 (push (list :table-table) clist)))
19746 (goto-char p)
19748 ;; New the "medium" contexts: clocktables, source blocks
19749 (cond ((org-in-clocktable-p)
19750 (push (list :clocktable
19751 (and (or (looking-at "#\\+BEGIN: clocktable")
19752 (search-backward "#+BEGIN: clocktable" nil t))
19753 (match-beginning 0))
19754 (and (re-search-forward "#\\+END:?" nil t)
19755 (match-end 0))) clist))
19756 ((org-in-src-block-p)
19757 (push (list :src-block
19758 (and (or (looking-at "#\\+BEGIN_SRC")
19759 (search-backward "#+BEGIN_SRC" nil t))
19760 (match-beginning 0))
19761 (and (search-forward "#+END_SRC" nil t)
19762 (match-beginning 0))) clist)))
19763 (goto-char p)
19765 ;; Now the small context
19766 (cond
19767 ((org-at-timestamp-p)
19768 (push (org-point-in-group p 0 :timestamp) clist))
19769 ((memq 'org-link faces)
19770 (push (list :link
19771 (previous-single-property-change p 'face)
19772 (next-single-property-change p 'face)) clist))
19773 ((memq 'org-special-keyword faces)
19774 (push (list :keyword
19775 (previous-single-property-change p 'face)
19776 (next-single-property-change p 'face)) clist))
19777 ((org-at-target-p)
19778 (push (org-point-in-group p 0 :target) clist)
19779 (goto-char (1- (match-beginning 0)))
19780 (if (looking-at org-radio-target-regexp)
19781 (push (org-point-in-group p 0 :radio-target) clist))
19782 (goto-char p))
19783 ((setq o (car (delq nil
19784 (mapcar
19785 (lambda (x)
19786 (if (memq x org-latex-fragment-image-overlays) x))
19787 (overlays-at (point))))))
19788 (push (list :latex-fragment
19789 (overlay-start o) (overlay-end o)) clist)
19790 (push (list :latex-preview
19791 (overlay-start o) (overlay-end o)) clist))
19792 ((org-inside-LaTeX-fragment-p)
19793 ;; FIXME: positions wrong.
19794 (push (list :latex-fragment (point) (point)) clist)))
19796 (setq clist (nreverse (delq nil clist)))
19797 clist))
19799 ;; FIXME: Compare with at-regexp-p Do we need both?
19800 (defun org-in-regexp (re &optional nlines visually)
19801 "Check if point is inside a match of regexp.
19802 Normally only the current line is checked, but you can include NLINES extra
19803 lines both before and after point into the search.
19804 If VISUALLY is set, require that the cursor is not after the match but
19805 really on, so that the block visually is on the match."
19806 (catch 'exit
19807 (let ((pos (point))
19808 (eol (point-at-eol (+ 1 (or nlines 0))))
19809 (inc (if visually 1 0)))
19810 (save-excursion
19811 (beginning-of-line (- 1 (or nlines 0)))
19812 (while (re-search-forward re eol t)
19813 (if (and (<= (match-beginning 0) pos)
19814 (>= (+ inc (match-end 0)) pos))
19815 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19817 (defun org-at-regexp-p (regexp)
19818 "Is point inside a match of REGEXP in the current line?"
19819 (catch 'exit
19820 (save-excursion
19821 (let ((pos (point)) (end (point-at-eol)))
19822 (beginning-of-line 1)
19823 (while (re-search-forward regexp end t)
19824 (if (and (<= (match-beginning 0) pos)
19825 (>= (match-end 0) pos))
19826 (throw 'exit t)))
19827 nil))))
19829 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19830 "Non-nil when point is between matches of START-RE and END-RE.
19832 Also return a non-nil value when point is on one of the matches.
19834 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19835 buffer positions. Default values are the positions of headlines
19836 surrounding the point.
19838 The functions returns a cons cell whose car (resp. cdr) is the
19839 position before START-RE (resp. after END-RE)."
19840 (save-match-data
19841 (let ((pos (point))
19842 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19843 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19844 beg end)
19845 (save-excursion
19846 ;; Point is on a block when on START-RE or if START-RE can be
19847 ;; found before it...
19848 (and (or (org-at-regexp-p start-re)
19849 (re-search-backward start-re limit-up t))
19850 (setq beg (match-beginning 0))
19851 ;; ... and END-RE after it...
19852 (goto-char (match-end 0))
19853 (re-search-forward end-re limit-down t)
19854 (> (setq end (match-end 0)) pos)
19855 ;; ... without another START-RE in-between.
19856 (goto-char (match-beginning 0))
19857 (not (re-search-backward start-re (1+ beg) t))
19858 ;; Return value.
19859 (cons beg end))))))
19861 (defun org-in-block-p (names)
19862 "Non-nil when point belongs to a block whose name belongs to NAMES.
19864 NAMES is a list of strings containing names of blocks.
19866 Return first block name matched, or nil. Beware that in case of
19867 nested blocks, the returned name may not belong to the closest
19868 block from point."
19869 (save-match-data
19870 (catch 'exit
19871 (let ((case-fold-search t)
19872 (lim-up (save-excursion (outline-previous-heading)))
19873 (lim-down (save-excursion (outline-next-heading))))
19874 (mapc (lambda (name)
19875 (let ((n (regexp-quote name)))
19876 (when (org-between-regexps-p
19877 (concat "^[ \t]*#\\+begin_" n)
19878 (concat "^[ \t]*#\\+end_" n)
19879 lim-up lim-down)
19880 (throw 'exit n))))
19881 names))
19882 nil)))
19884 (defun org-occur-in-agenda-files (regexp &optional nlines)
19885 "Call `multi-occur' with buffers for all agenda files."
19886 (interactive "sOrg-files matching: \np")
19887 (let* ((files (org-agenda-files))
19888 (tnames (mapcar 'file-truename files))
19889 (extra org-agenda-text-search-extra-files)
19891 (when (eq (car extra) 'agenda-archives)
19892 (setq extra (cdr extra))
19893 (setq files (org-add-archive-files files)))
19894 (while (setq f (pop extra))
19895 (unless (member (file-truename f) tnames)
19896 (add-to-list 'files f 'append)
19897 (add-to-list 'tnames (file-truename f) 'append)))
19898 (multi-occur
19899 (mapcar (lambda (x)
19900 (with-current-buffer
19901 (or (get-file-buffer x) (find-file-noselect x))
19902 (widen)
19903 (current-buffer)))
19904 files)
19905 regexp)))
19907 (if (boundp 'occur-mode-find-occurrence-hook)
19908 ;; Emacs 23
19909 (add-hook 'occur-mode-find-occurrence-hook
19910 (lambda ()
19911 (when (eq major-mode 'org-mode)
19912 (org-reveal))))
19913 ;; Emacs 22
19914 (defadvice occur-mode-goto-occurrence
19915 (after org-occur-reveal activate)
19916 (and (eq major-mode 'org-mode) (org-reveal)))
19917 (defadvice occur-mode-goto-occurrence-other-window
19918 (after org-occur-reveal activate)
19919 (and (eq major-mode 'org-mode) (org-reveal)))
19920 (defadvice occur-mode-display-occurrence
19921 (after org-occur-reveal activate)
19922 (when (eq major-mode 'org-mode)
19923 (let ((pos (occur-mode-find-occurrence)))
19924 (with-current-buffer (marker-buffer pos)
19925 (save-excursion
19926 (goto-char pos)
19927 (org-reveal)))))))
19929 (defun org-occur-link-in-agenda-files ()
19930 "Create a link and search for it in the agendas.
19931 The link is not stored in `org-stored-links', it is just created
19932 for the search purpose."
19933 (interactive)
19934 (let ((link (condition-case nil
19935 (org-store-link nil)
19936 (error "Unable to create a link to here"))))
19937 (org-occur-in-agenda-files (regexp-quote link))))
19939 (defun org-uniquify (list)
19940 "Remove duplicate elements from LIST."
19941 (let (res)
19942 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19943 res))
19945 (defun org-delete-all (elts list)
19946 "Remove all elements in ELTS from LIST."
19947 (while elts
19948 (setq list (delete (pop elts) list)))
19949 list)
19951 (defun org-count (cl-item cl-seq)
19952 "Count the number of occurrences of ITEM in SEQ.
19953 Taken from `count' in cl-seq.el with all keyword arguments removed."
19954 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19955 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19956 (while (< cl-start cl-end)
19957 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19958 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19959 (setq cl-start (1+ cl-start)))
19960 cl-count))
19962 (defun org-remove-if (predicate seq)
19963 "Remove everything from SEQ that fulfills PREDICATE."
19964 (let (res e)
19965 (while seq
19966 (setq e (pop seq))
19967 (if (not (funcall predicate e)) (push e res)))
19968 (nreverse res)))
19970 (defun org-remove-if-not (predicate seq)
19971 "Remove everything from SEQ that does not fulfill PREDICATE."
19972 (let (res e)
19973 (while seq
19974 (setq e (pop seq))
19975 (if (funcall predicate e) (push e res)))
19976 (nreverse res)))
19978 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19979 "Reduce two-argument FUNCTION across SEQ.
19980 Taken from `reduce' in cl-seq.el with all keyword arguments but
19981 \":initial-value\" removed."
19982 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19983 (cadr (memq :initial-value cl-keys)))
19984 (cl-seq (pop cl-seq))
19985 (t (funcall cl-func)))))
19986 (while cl-seq
19987 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19988 cl-accum))
19990 (defun org-back-over-empty-lines ()
19991 "Move backwards over whitespace, to the beginning of the first empty line.
19992 Returns the number of empty lines passed."
19993 (let ((pos (point)))
19994 (if (cdr (assoc 'heading org-blank-before-new-entry))
19995 (skip-chars-backward " \t\n\r")
19996 (unless (eobp)
19997 (forward-line -1)))
19998 (beginning-of-line 2)
19999 (goto-char (min (point) pos))
20000 (count-lines (point) pos)))
20002 (defun org-skip-whitespace ()
20003 (skip-chars-forward " \t\n\r"))
20005 (defun org-point-in-group (point group &optional context)
20006 "Check if POINT is in match-group GROUP.
20007 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20008 match. If the match group does not exist or point is not inside it,
20009 return nil."
20010 (and (match-beginning group)
20011 (>= point (match-beginning group))
20012 (<= point (match-end group))
20013 (if context
20014 (list context (match-beginning group) (match-end group))
20015 t)))
20017 (defun org-switch-to-buffer-other-window (&rest args)
20018 "Switch to buffer in a second window on the current frame.
20019 In particular, do not allow pop-up frames.
20020 Returns the newly created buffer."
20021 (let (pop-up-frames special-display-buffer-names special-display-regexps
20022 special-display-function)
20023 (apply 'switch-to-buffer-other-window args)))
20025 (defun org-combine-plists (&rest plists)
20026 "Create a single property list from all plists in PLISTS.
20027 The process starts by copying the first list, and then setting properties
20028 from the other lists. Settings in the last list are the most significant
20029 ones and overrule settings in the other lists."
20030 (let ((rtn (copy-sequence (pop plists)))
20031 p v ls)
20032 (while plists
20033 (setq ls (pop plists))
20034 (while ls
20035 (setq p (pop ls) v (pop ls))
20036 (setq rtn (plist-put rtn p v))))
20037 rtn))
20039 (defun org-move-line-down (arg)
20040 "Move the current line down. With prefix argument, move it past ARG lines."
20041 (interactive "p")
20042 (let ((col (current-column))
20043 beg end pos)
20044 (beginning-of-line 1) (setq beg (point))
20045 (beginning-of-line 2) (setq end (point))
20046 (beginning-of-line (+ 1 arg))
20047 (setq pos (move-marker (make-marker) (point)))
20048 (insert (delete-and-extract-region beg end))
20049 (goto-char pos)
20050 (org-move-to-column col)))
20052 (defun org-move-line-up (arg)
20053 "Move the current line up. With prefix argument, move it past ARG lines."
20054 (interactive "p")
20055 (let ((col (current-column))
20056 beg end pos)
20057 (beginning-of-line 1) (setq beg (point))
20058 (beginning-of-line 2) (setq end (point))
20059 (beginning-of-line (- arg))
20060 (setq pos (move-marker (make-marker) (point)))
20061 (insert (delete-and-extract-region beg end))
20062 (goto-char pos)
20063 (org-move-to-column col)))
20065 (defun org-replace-escapes (string table)
20066 "Replace %-escapes in STRING with values in TABLE.
20067 TABLE is an association list with keys like \"%a\" and string values.
20068 The sequences in STRING may contain normal field width and padding information,
20069 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20070 so values can contain further %-escapes if they are define later in TABLE."
20071 (let ((tbl (copy-alist table))
20072 (case-fold-search nil)
20073 (pchg 0)
20074 e re rpl)
20075 (while (setq e (pop tbl))
20076 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20077 (when (and (cdr e) (string-match re (cdr e)))
20078 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20079 (safe "SREF"))
20080 (add-text-properties 0 3 (list 'sref sref) safe)
20081 (setcdr e (replace-match safe t t (cdr e)))))
20082 (while (string-match re string)
20083 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20084 (cdr e)))
20085 (setq string (replace-match rpl t t string))))
20086 (while (setq pchg (next-property-change pchg string))
20087 (let ((sref (get-text-property pchg 'sref string)))
20088 (when (and sref (string-match "SREF" string pchg))
20089 (setq string (replace-match sref t t string)))))
20090 string))
20092 (defun org-sublist (list start end)
20093 "Return a section of LIST, from START to END.
20094 Counting starts at 1."
20095 (let (rtn (c start))
20096 (setq list (nthcdr (1- start) list))
20097 (while (and list (<= c end))
20098 (push (pop list) rtn)
20099 (setq c (1+ c)))
20100 (nreverse rtn)))
20102 (defun org-find-base-buffer-visiting (file)
20103 "Like `find-buffer-visiting' but always return the base buffer and
20104 not an indirect buffer."
20105 (let ((buf (or (get-file-buffer file)
20106 (find-buffer-visiting file))))
20107 (if buf
20108 (or (buffer-base-buffer buf) buf)
20109 nil)))
20111 (defun org-image-file-name-regexp (&optional extensions)
20112 "Return regexp matching the file names of images.
20113 If EXTENSIONS is given, only match these."
20114 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20115 (image-file-name-regexp)
20116 (let ((image-file-name-extensions
20117 (or extensions
20118 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20119 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20120 (concat "\\."
20121 (regexp-opt (nconc (mapcar 'upcase
20122 image-file-name-extensions)
20123 image-file-name-extensions)
20125 "\\'"))))
20127 (defun org-file-image-p (file &optional extensions)
20128 "Return non-nil if FILE is an image."
20129 (save-match-data
20130 (string-match (org-image-file-name-regexp extensions) file)))
20132 (defun org-get-cursor-date ()
20133 "Return the date at cursor in as a time.
20134 This works in the calendar and in the agenda, anywhere else it just
20135 returns the current time."
20136 (let (date day defd)
20137 (cond
20138 ((eq major-mode 'calendar-mode)
20139 (setq date (calendar-cursor-to-date)
20140 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20141 ((eq major-mode 'org-agenda-mode)
20142 (setq day (get-text-property (point) 'day))
20143 (if day
20144 (setq date (calendar-gregorian-from-absolute day)
20145 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20146 (nth 2 date))))))
20147 (or defd (current-time))))
20149 (defvar org-agenda-action-marker (make-marker)
20150 "Marker pointing to the entry for the next agenda action.")
20152 (defun org-mark-entry-for-agenda-action ()
20153 "Mark the current entry as target of an agenda action.
20154 Agenda actions are actions executed from the agenda with the key `k',
20155 which make use of the date at the cursor."
20156 (interactive)
20157 (move-marker org-agenda-action-marker
20158 (save-excursion (org-back-to-heading t) (point))
20159 (current-buffer))
20160 (message
20161 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20163 (defun org-mark-subtree ()
20164 "Mark the current subtree.
20165 This puts point at the start of the current subtree, and mark at the end.
20167 If point is in an inline task, mark that task instead."
20168 (interactive)
20169 (let ((inline-task-p
20170 (and (featurep 'org-inlinetask)
20171 (org-inlinetask-in-task-p)))
20172 (beg))
20173 ;; Get beginning of subtree
20174 (cond
20175 (inline-task-p (org-inlinetask-goto-beginning))
20176 ((org-at-heading-p) (beginning-of-line))
20177 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20178 (setq beg (point))
20179 ;; Get end of it
20180 (if inline-task-p
20181 (org-inlinetask-goto-end)
20182 (org-end-of-subtree))
20183 ;; Mark zone
20184 (push-mark (point) nil t)
20185 (goto-char beg)))
20187 ;;; Paragraph filling stuff.
20188 ;; We want this to be just right, so use the full arsenal.
20190 (defun org-indent-line-function ()
20191 "Indent line depending on context."
20192 (interactive)
20193 (let* ((pos (point))
20194 (itemp (org-at-item-p))
20195 (case-fold-search t)
20196 (org-drawer-regexp (or org-drawer-regexp "\000"))
20197 (inline-task-p (and (featurep 'org-inlinetask)
20198 (org-inlinetask-in-task-p)))
20199 (inline-re (and inline-task-p
20200 (org-inlinetask-outline-regexp)))
20201 column)
20202 (beginning-of-line 1)
20203 (cond
20204 ;; Comments
20205 ((looking-at "# ") (setq column 0))
20206 ;; Headings
20207 ((looking-at org-outline-regexp) (setq column 0))
20208 ;; Included files
20209 ((looking-at "#\\+include:") (setq column 0))
20210 ;; Footnote definition
20211 ((looking-at org-footnote-definition-re) (setq column 0))
20212 ;; Literal examples
20213 ((looking-at "[ \t]*:\\( \\|$\\)")
20214 (setq column (org-get-indentation))) ; do nothing
20215 ;; Lists
20216 ((ignore-errors (goto-char (org-in-item-p)))
20217 (setq column (if itemp
20218 (org-get-indentation)
20219 (org-list-item-body-column (point))))
20220 (goto-char pos))
20221 ;; Drawers
20222 ((and (looking-at "[ \t]*:END:")
20223 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20224 (save-excursion
20225 (goto-char (1- (match-beginning 1)))
20226 (setq column (current-column))))
20227 ;; Special blocks
20228 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20229 (save-excursion
20230 (re-search-backward
20231 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20232 (setq column (org-get-indentation (match-string 0))))
20233 ((and (not (looking-at "[ \t]*#\\+begin_"))
20234 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20235 (save-excursion
20236 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20237 (setq column
20238 (cond ((equal (downcase (match-string 1)) "src")
20239 ;; src blocks: let `org-edit-src-exit' handle them
20240 (org-get-indentation))
20241 ((equal (downcase (match-string 1)) "example")
20242 (max (org-get-indentation)
20243 (org-get-indentation (match-string 0))))
20245 (org-get-indentation (match-string 0))))))
20246 ;; This line has nothing special, look at the previous relevant
20247 ;; line to compute indentation
20249 (beginning-of-line 0)
20250 (while (and (not (bobp))
20251 (not (looking-at org-drawer-regexp))
20252 ;; When point started in an inline task, do not move
20253 ;; above task starting line.
20254 (not (and inline-task-p (looking-at inline-re)))
20255 ;; Skip drawers, blocks, empty lines, verbatim,
20256 ;; comments, tables, footnotes definitions, lists,
20257 ;; inline tasks.
20258 (or (and (looking-at "[ \t]*:END:")
20259 (re-search-backward org-drawer-regexp nil t))
20260 (and (looking-at "[ \t]*#\\+end_")
20261 (re-search-backward "[ \t]*#\\+begin_"nil t))
20262 (looking-at "[ \t]*[\n:#|]")
20263 (looking-at org-footnote-definition-re)
20264 (and (ignore-errors (goto-char (org-in-item-p)))
20265 (goto-char
20266 (org-list-get-top-point (org-list-struct))))
20267 (and (not inline-task-p)
20268 (featurep 'org-inlinetask)
20269 (org-inlinetask-in-task-p)
20270 (or (org-inlinetask-goto-beginning) t))))
20271 (beginning-of-line 0))
20272 (cond
20273 ;; There was an heading above.
20274 ((looking-at "\\*+[ \t]+")
20275 (if (not org-adapt-indentation)
20276 (setq column 0)
20277 (goto-char (match-end 0))
20278 (setq column (current-column))))
20279 ;; A drawer had started and is unfinished
20280 ((looking-at org-drawer-regexp)
20281 (goto-char (1- (match-beginning 1)))
20282 (setq column (current-column)))
20283 ;; Else, nothing noticeable found: get indentation and go on.
20284 (t (setq column (org-get-indentation))))))
20285 ;; Now apply indentation and move cursor accordingly
20286 (goto-char pos)
20287 (if (<= (current-column) (current-indentation))
20288 (org-indent-line-to column)
20289 (save-excursion (org-indent-line-to column)))
20290 ;; Special polishing for properties, see `org-property-format'
20291 (setq column (current-column))
20292 (beginning-of-line 1)
20293 (if (looking-at
20294 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20295 (replace-match (concat (match-string 1)
20296 (format org-property-format
20297 (match-string 2) (match-string 3)))
20298 t t))
20299 (org-move-to-column column)))
20301 (defun org-indent-drawer ()
20302 "Indent the drawer at point."
20303 (interactive)
20304 (let ((p (point))
20305 (e (and (save-excursion (re-search-forward ":END:" nil t))
20306 (match-end 0)))
20307 (folded
20308 (save-excursion
20309 (end-of-line)
20310 (when (overlays-at (point))
20311 (member 'invisible (overlay-properties
20312 (car (overlays-at (point)))))))))
20313 (when folded (org-cycle))
20314 (indent-for-tab-command)
20315 (while (and (move-beginning-of-line 2) (< (point) e))
20316 (indent-for-tab-command))
20317 (goto-char p)
20318 (when folded (org-cycle)))
20319 (message "Drawer at point indented"))
20321 (defun org-indent-block ()
20322 "Indent the block at point."
20323 (interactive)
20324 (let ((p (point))
20325 (case-fold-search t)
20326 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20327 (match-end 0)))
20328 (folded
20329 (save-excursion
20330 (end-of-line)
20331 (when (overlays-at (point))
20332 (member 'invisible (overlay-properties
20333 (car (overlays-at (point)))))))))
20334 (when folded (org-cycle))
20335 (indent-for-tab-command)
20336 (while (and (move-beginning-of-line 2) (< (point) e))
20337 (indent-for-tab-command))
20338 (goto-char p)
20339 (when folded (org-cycle)))
20340 (message "Block at point indented"))
20342 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20343 "Variable to store copy of `adaptive-fill-regexp'.
20344 Since `adaptive-fill-regexp' is set to never match, we need to
20345 store a backup of its value before entering `org-mode' so that
20346 the functionality can be provided as a fall-back.")
20348 (defun org-set-autofill-regexps ()
20349 (interactive)
20350 ;; In the paragraph separator we include headlines, because filling
20351 ;; text in a line directly attached to a headline would otherwise
20352 ;; fill the headline as well.
20353 (org-set-local 'comment-start-skip "^#+[ \t]*")
20354 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20355 ;; The paragraph starter includes hand-formatted lists.
20356 (org-set-local
20357 'paragraph-start
20358 (concat
20359 "\f" "\\|"
20360 "[ ]*$" "\\|"
20361 org-outline-regexp "\\|"
20362 "[ \t]*#" "\\|"
20363 (org-item-re) "\\|"
20364 "[ \t]*[:|]" "\\|"
20365 "\\$\\$" "\\|"
20366 "\\\\\\(begin\\|end\\|[][]\\)"))
20367 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20368 ;; But only if the user has not turned off tables or fixed-width regions
20369 (org-set-local
20370 'auto-fill-inhibit-regexp
20371 (concat org-outline-regexp
20372 "\\|#\\+"
20373 "\\|[ \t]*" org-keyword-time-regexp
20374 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20375 (concat
20376 "\\|[ \t]*["
20377 (if org-enable-table-editor "|" "")
20378 (if org-enable-fixed-width-editor ":" "")
20379 "]"))))
20380 ;; We use our own fill-paragraph function, to make sure that tables
20381 ;; and fixed-width regions are not wrapped. That function will pass
20382 ;; through to `fill-paragraph' when appropriate.
20383 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20384 ;; Prevent auto-fill from inserting unwanted new items.
20385 (if (boundp 'fill-nobreak-predicate)
20386 (org-set-local
20387 'fill-nobreak-predicate
20388 (org-uniquify
20389 (append fill-nobreak-predicate
20390 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20391 ;; Adaptive filling: To get full control, first make sure that
20392 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20393 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20394 (org-set-local 'org-adaptive-fill-regexp-backup
20395 adaptive-fill-regexp))
20396 (org-set-local 'adaptive-fill-regexp "\000")
20397 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20398 (org-set-local 'adaptive-fill-function
20399 'org-adaptive-fill-function)
20400 (org-set-local
20401 'align-mode-rules-list
20402 '((org-in-buffer-settings
20403 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20404 (modes . '(org-mode))))))
20406 (defun org-fill-item-nobreak-p ()
20407 "Non-nil when a line break at point would insert a new item."
20408 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20410 (defun org-fill-line-break-nobreak-p ()
20411 "Non-nil when a line break at point would create an Org line break."
20412 (save-excursion
20413 (skip-chars-backward "[ \t]")
20414 (skip-chars-backward "\\\\")
20415 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20417 (defun org-fill-paragraph (&optional justify)
20418 "Re-align a table, pass through to fill-paragraph if no table."
20419 (let ((table-p (org-at-table-p))
20420 (table.el-p (org-at-table.el-p))
20421 (itemp (org-in-item-p)))
20422 (cond ((and (equal (char-after (point-at-bol)) ?*)
20423 (save-excursion (goto-char (point-at-bol))
20424 (looking-at org-outline-regexp)))
20425 t) ; skip headlines
20426 (table.el-p t) ; skip table.el tables
20427 (table-p (org-table-align) t) ; align Org tables
20428 (itemp ; align text in items
20429 (let* ((struct (save-excursion (goto-char itemp)
20430 (org-list-struct)))
20431 (parents (org-list-parents-alist struct))
20432 (children (org-list-get-children itemp struct parents))
20433 beg end prev next prefix)
20434 ;; Determine in which part of item point is: before
20435 ;; first child, after last child, between two
20436 ;; sub-lists, or simply in item if there's no child.
20437 (cond
20438 ((not children)
20439 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20440 beg itemp
20441 end (org-list-get-item-end itemp struct)))
20442 ((< (point) (setq next (car children)))
20443 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20444 beg itemp
20445 end next))
20446 ((> (point) (setq prev (car (last children))))
20447 (setq beg (org-list-get-item-end prev struct)
20448 end (org-list-get-item-end itemp struct)
20449 prefix (save-excursion
20450 (goto-char beg)
20451 (skip-chars-forward " \t")
20452 (make-string (current-column) ?\ ))))
20453 (t (catch 'exit
20454 (while (setq next (pop children))
20455 (if (> (point) next)
20456 (setq prev next)
20457 (setq beg (org-list-get-item-end prev struct)
20458 end next
20459 prefix (save-excursion
20460 (goto-char beg)
20461 (skip-chars-forward " \t")
20462 (make-string (current-column) ?\ )))
20463 (throw 'exit nil))))))
20464 ;; Use `fill-paragraph' with buffer narrowed to item
20465 ;; without any child, and with our computed PREFIX.
20466 (flet ((fill-context-prefix (from to &optional flr) prefix))
20467 (save-restriction
20468 (narrow-to-region beg end)
20469 (save-excursion (fill-paragraph justify)))) t))
20470 ;; Special case where point is not in a list but is on
20471 ;; a paragraph adjacent to a list: make sure this paragraph
20472 ;; doesn't get merged with the end of the list by narrowing
20473 ;; buffer first.
20474 ((save-excursion (forward-paragraph -1)
20475 (setq itemp (org-in-item-p)))
20476 (let ((struct (save-excursion (goto-char itemp)
20477 (org-list-struct))))
20478 (save-restriction
20479 (narrow-to-region (org-list-get-bottom-point struct)
20480 (save-excursion (forward-paragraph 1)
20481 (point)))
20482 (fill-paragraph justify) t)))
20483 ;; Else simply call `fill-paragraph'.
20484 (t nil))))
20486 ;; For reference, this is the default value of adaptive-fill-regexp
20487 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20489 (defun org-adaptive-fill-function ()
20490 "Return a fill prefix for org-mode files."
20491 (let (itemp)
20492 (save-excursion
20493 (cond
20494 ;; Comment line
20495 ((looking-at "#[ \t]+")
20496 (match-string-no-properties 0))
20497 ;; Plain list item
20498 ((org-at-item-p)
20499 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20500 ;; Point is in a list after `backward-paragraph': original
20501 ;; point wasn't in the list, or filling would have been taken
20502 ;; care of by `org-auto-fill-function', but the list and the
20503 ;; real paragraph are not separated by a blank line. Thus, move
20504 ;; point after the list to go back to real paragraph and
20505 ;; determine fill-prefix.
20506 ((setq itemp (org-in-item-p))
20507 (goto-char itemp)
20508 (let* ((struct (org-list-struct))
20509 (bottom (org-list-get-bottom-point struct)))
20510 (goto-char bottom)
20511 (make-string (org-get-indentation) ?\ )))
20512 ;; Other text
20513 ((looking-at org-adaptive-fill-regexp-backup)
20514 (match-string-no-properties 0))))))
20516 (defun org-auto-fill-function ()
20517 "Auto-fill function."
20518 (let (itemp prefix)
20519 ;; When in a list, compute an appropriate fill-prefix and make
20520 ;; sure it will be used by `do-auto-fill'.
20521 (if (setq itemp (org-in-item-p))
20522 (progn
20523 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20524 (flet ((fill-context-prefix (from to &optional flr) prefix))
20525 (do-auto-fill)))
20526 ;; Else just use `do-auto-fill'.
20527 (do-auto-fill))))
20529 ;;; Other stuff.
20531 (defun org-toggle-fixed-width-section (arg)
20532 "Toggle the fixed-width export.
20533 If there is no active region, the QUOTE keyword at the current headline is
20534 inserted or removed. When present, it causes the text between this headline
20535 and the next to be exported as fixed-width text, and unmodified.
20536 If there is an active region, this command adds or removes a colon as the
20537 first character of this line. If the first character of a line is a colon,
20538 this line is also exported in fixed-width font."
20539 (interactive "P")
20540 (let* ((cc 0)
20541 (regionp (org-region-active-p))
20542 (beg (if regionp (region-beginning) (point)))
20543 (end (if regionp (region-end)))
20544 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20545 (case-fold-search nil)
20546 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20547 off)
20548 (if regionp
20549 (save-excursion
20550 (goto-char beg)
20551 (setq cc (current-column))
20552 (beginning-of-line 1)
20553 (setq off (looking-at re))
20554 (while (> nlines 0)
20555 (setq nlines (1- nlines))
20556 (beginning-of-line 1)
20557 (cond
20558 (arg
20559 (org-move-to-column cc t)
20560 (insert ": \n")
20561 (forward-line -1))
20562 ((and off (looking-at re))
20563 (replace-match "" t t nil 1))
20564 ((not off) (org-move-to-column cc t) (insert ": ")))
20565 (forward-line 1)))
20566 (save-excursion
20567 (org-back-to-heading)
20568 (cond
20569 ((looking-at (format org-heading-keyword-regexp-format
20570 org-quote-string))
20571 (goto-char (match-end 1))
20572 (looking-at (concat " +" org-quote-string))
20573 (replace-match "" t t)
20574 (when (eolp) (insert " ")))
20575 ((looking-at org-outline-regexp)
20576 (goto-char (match-end 0))
20577 (insert org-quote-string " ")))))))
20579 (defun org-reftex-citation ()
20580 "Use reftex-citation to insert a citation into the buffer.
20581 This looks for a line like
20583 #+BIBLIOGRAPHY: foo plain option:-d
20585 and derives from it that foo.bib is the bibliography file relevant
20586 for this document. It then installs the necessary environment for RefTeX
20587 to work in this buffer and calls `reftex-citation' to insert a citation
20588 into the buffer.
20590 Export of such citations to both LaTeX and HTML is handled by the contributed
20591 package org-exp-bibtex by Taru Karttunen."
20592 (interactive)
20593 (let ((reftex-docstruct-symbol 'rds)
20594 (reftex-cite-format "\\cite{%l}")
20595 rds bib)
20596 (save-excursion
20597 (save-restriction
20598 (widen)
20599 (let ((case-fold-search t)
20600 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20601 (if (not (save-excursion
20602 (or (re-search-forward re nil t)
20603 (re-search-backward re nil t))))
20604 (error "No bibliography defined in file")
20605 (setq bib (concat (match-string 1) ".bib")
20606 rds (list (list 'bib bib)))))))
20607 (call-interactively 'reftex-citation)))
20609 ;;;; Functions extending outline functionality
20611 (defun org-beginning-of-line (&optional arg)
20612 "Go to the beginning of the current line. If that is invisible, continue
20613 to a visible line beginning. This makes the function of C-a more intuitive.
20614 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20615 first attempt, and only move to after the tags when the cursor is already
20616 beyond the end of the headline."
20617 (interactive "P")
20618 (let ((pos (point))
20619 (special (if (consp org-special-ctrl-a/e)
20620 (car org-special-ctrl-a/e)
20621 org-special-ctrl-a/e))
20622 refpos)
20623 (if (org-bound-and-true-p line-move-visual)
20624 (beginning-of-visual-line 1)
20625 (beginning-of-line 1))
20626 (if (and arg (fboundp 'move-beginning-of-line))
20627 (call-interactively 'move-beginning-of-line)
20628 (if (bobp)
20630 (backward-char 1)
20631 (if (org-truely-invisible-p)
20632 (while (and (not (bobp)) (org-truely-invisible-p))
20633 (backward-char 1)
20634 (beginning-of-line 1))
20635 (forward-char 1))))
20636 (when special
20637 (cond
20638 ((and (looking-at org-complex-heading-regexp)
20639 (= (char-after (match-end 1)) ?\ ))
20640 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20641 (point-at-eol)))
20642 (goto-char
20643 (if (eq special t)
20644 (cond ((> pos refpos) refpos)
20645 ((= pos (point)) refpos)
20646 (t (point)))
20647 (cond ((> pos (point)) (point))
20648 ((not (eq last-command this-command)) (point))
20649 (t refpos)))))
20650 ((org-at-item-p)
20651 ;; Being at an item and not looking at an the item means point
20652 ;; was previously moved to beginning of a visual line, whiche
20653 ;; doesn't contain the item. Therefore, do nothing special,
20654 ;; just stay here.
20655 (when (looking-at org-list-full-item-re)
20656 ;; Set special position at first white space character after
20657 ;; bullet, and check-box, if any.
20658 (let ((after-bullet
20659 (let ((box (match-end 3)))
20660 (if (not box) (match-end 1)
20661 (let ((after (char-after box)))
20662 (if (and after (= after ? )) (1+ box) box))))))
20663 ;; Special case: Move point to special position when
20664 ;; currently after it or at beginning of line.
20665 (if (eq special t)
20666 (when (or (> pos after-bullet) (= (point) pos))
20667 (goto-char after-bullet))
20668 ;; Reversed case: Move point to special position when
20669 ;; point was already at beginning of line and command is
20670 ;; repeated.
20671 (when (and (= (point) pos) (eq last-command this-command))
20672 (goto-char after-bullet))))))))
20673 (org-no-warnings
20674 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20676 (defun org-end-of-line (&optional arg)
20677 "Go to the end of the line.
20678 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20679 first attempt, and only move to after the tags when the cursor is already
20680 beyond the end of the headline."
20681 (interactive "P")
20682 (let ((special (if (consp org-special-ctrl-a/e)
20683 (cdr org-special-ctrl-a/e)
20684 org-special-ctrl-a/e)))
20685 (cond
20686 ((or (not special) arg
20687 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20688 (call-interactively
20689 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20690 ((fboundp 'move-end-of-line) 'move-end-of-line)
20691 (t 'end-of-line))))
20692 ((org-at-heading-p)
20693 (let ((pos (point)))
20694 (beginning-of-line 1)
20695 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20696 (if (eq special t)
20697 (if (or (< pos (match-beginning 1))
20698 (= pos (match-end 0)))
20699 (goto-char (match-beginning 1))
20700 (goto-char (match-end 0)))
20701 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20702 (goto-char (match-end 0))
20703 (goto-char (match-beginning 1))))
20704 (call-interactively (if (fboundp 'move-end-of-line)
20705 'move-end-of-line
20706 'end-of-line)))))
20707 ((org-at-drawer-p)
20708 (move-end-of-line 1)
20709 (when (overlays-at (1- (point))) (backward-char 1)))
20710 ;; At an item: Move before any hidden text.
20711 (t (call-interactively
20712 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20713 ((fboundp 'move-end-of-line) 'move-end-of-line)
20714 (t 'end-of-line)))))
20715 (org-no-warnings
20716 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20718 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20719 (define-key org-mode-map "\C-e" 'org-end-of-line)
20721 (defun org-backward-sentence (&optional arg)
20722 "Go to beginning of sentence, or beginning of table field.
20723 This will call `backward-sentence' or `org-table-beginning-of-field',
20724 depending on context."
20725 (interactive "P")
20726 (cond
20727 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20728 (t (call-interactively 'backward-sentence))))
20730 (defun org-forward-sentence (&optional arg)
20731 "Go to end of sentence, or end of table field.
20732 This will call `forward-sentence' or `org-table-end-of-field',
20733 depending on context."
20734 (interactive "P")
20735 (cond
20736 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20737 (t (call-interactively 'forward-sentence))))
20739 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20740 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20742 (defun org-kill-line (&optional arg)
20743 "Kill line, to tags or end of line."
20744 (interactive "P")
20745 (cond
20746 ((or (not org-special-ctrl-k)
20747 (bolp)
20748 (not (org-at-heading-p)))
20749 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20750 org-ctrl-k-protect-subtree)
20751 (if (or (eq org-ctrl-k-protect-subtree 'error)
20752 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20753 (error "C-k aborted - would kill hidden subtree")))
20754 (call-interactively
20755 (if visual-line-mode 'kill-visual-line 'kill-line)))
20756 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20757 (kill-region (point) (match-beginning 1))
20758 (org-set-tags nil t))
20759 (t (kill-region (point) (point-at-eol)))))
20761 (define-key org-mode-map "\C-k" 'org-kill-line)
20763 (defun org-yank (&optional arg)
20764 "Yank. If the kill is a subtree, treat it specially.
20765 This command will look at the current kill and check if is a single
20766 subtree, or a series of subtrees[1]. If it passes the test, and if the
20767 cursor is at the beginning of a line or after the stars of a currently
20768 empty headline, then the yank is handled specially. How exactly depends
20769 on the value of the following variables, both set by default.
20771 org-yank-folded-subtrees
20772 When set, the subtree(s) will be folded after insertion, but only
20773 if doing so would now swallow text after the yanked text.
20775 org-yank-adjusted-subtrees
20776 When set, the subtree will be promoted or demoted in order to
20777 fit into the local outline tree structure, which means that the level
20778 will be adjusted so that it becomes the smaller one of the two
20779 *visible* surrounding headings.
20781 Any prefix to this command will cause `yank' to be called directly with
20782 no special treatment. In particular, a simple \\[universal-argument] prefix \
20783 will just
20784 plainly yank the text as it is.
20786 \[1] The test checks if the first non-white line is a heading
20787 and if there are no other headings with fewer stars."
20788 (interactive "P")
20789 (org-yank-generic 'yank arg))
20791 (defun org-yank-generic (command arg)
20792 "Perform some yank-like command.
20794 This function implements the behavior described in the `org-yank'
20795 documentation. However, it has been generalized to work for any
20796 interactive command with similar behavior."
20798 ;; pretend to be command COMMAND
20799 (setq this-command command)
20801 (if arg
20802 (call-interactively command)
20804 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20805 (and (org-kill-is-subtree-p)
20806 (or (bolp)
20807 (and (looking-at "[ \t]*$")
20808 (string-match
20809 "\\`\\*+\\'"
20810 (buffer-substring (point-at-bol) (point)))))))
20811 swallowp)
20812 (cond
20813 ((and subtreep org-yank-folded-subtrees)
20814 (let ((beg (point))
20815 end)
20816 (if (and subtreep org-yank-adjusted-subtrees)
20817 (org-paste-subtree nil nil 'for-yank)
20818 (call-interactively command))
20820 (setq end (point))
20821 (goto-char beg)
20822 (when (and (bolp) subtreep
20823 (not (setq swallowp
20824 (org-yank-folding-would-swallow-text beg end))))
20825 (org-with-limited-levels
20826 (or (looking-at org-outline-regexp)
20827 (re-search-forward org-outline-regexp-bol end t))
20828 (while (and (< (point) end) (looking-at org-outline-regexp))
20829 (hide-subtree)
20830 (org-cycle-show-empty-lines 'folded)
20831 (condition-case nil
20832 (outline-forward-same-level 1)
20833 (error (goto-char end))))))
20834 (when swallowp
20835 (message
20836 "Inserted text not folded because that would swallow text"))
20838 (goto-char end)
20839 (skip-chars-forward " \t\n\r")
20840 (beginning-of-line 1)
20841 (push-mark beg 'nomsg)))
20842 ((and subtreep org-yank-adjusted-subtrees)
20843 (let ((beg (point-at-bol)))
20844 (org-paste-subtree nil nil 'for-yank)
20845 (push-mark beg 'nomsg)))
20847 (call-interactively command))))))
20849 (defun org-yank-folding-would-swallow-text (beg end)
20850 "Would hide-subtree at BEG swallow any text after END?"
20851 (let (level)
20852 (org-with-limited-levels
20853 (save-excursion
20854 (goto-char beg)
20855 (when (or (looking-at org-outline-regexp)
20856 (re-search-forward org-outline-regexp-bol end t))
20857 (setq level (org-outline-level)))
20858 (goto-char end)
20859 (skip-chars-forward " \t\r\n\v\f")
20860 (if (or (eobp)
20861 (and (bolp) (looking-at org-outline-regexp)
20862 (<= (org-outline-level) level)))
20863 nil ; Nothing would be swallowed
20864 t))))) ; something would swallow
20866 (define-key org-mode-map "\C-y" 'org-yank)
20868 (defun org-truely-invisible-p ()
20869 "Check if point is at a character currently not visible.
20870 This version does not only check the character property, but also
20871 `visible-mode'."
20872 ;; Early versions of noutline don't have `outline-invisible-p'.
20873 (if (org-bound-and-true-p visible-mode)
20875 (outline-invisible-p)))
20877 (defun org-invisible-p2 ()
20878 "Check if point is at a character currently not visible."
20879 (save-excursion
20880 (if (and (eolp) (not (bobp))) (backward-char 1))
20881 ;; Early versions of noutline don't have `outline-invisible-p'.
20882 (outline-invisible-p)))
20884 (defun org-back-to-heading (&optional invisible-ok)
20885 "Call `outline-back-to-heading', but provide a better error message."
20886 (condition-case nil
20887 (outline-back-to-heading invisible-ok)
20888 (error (error "Before first headline at position %d in buffer %s"
20889 (point) (current-buffer)))))
20891 (defun org-beginning-of-defun ()
20892 "Go to the beginning of the subtree, i.e. back to the heading."
20893 (org-back-to-heading))
20894 (defun org-end-of-defun ()
20895 "Go to the end of the subtree."
20896 (org-end-of-subtree nil t))
20898 (defun org-before-first-heading-p ()
20899 "Before first heading?"
20900 (save-excursion
20901 (end-of-line)
20902 (null (re-search-backward org-outline-regexp-bol nil t))))
20904 (defun org-at-heading-p (&optional ignored)
20905 (outline-on-heading-p t))
20906 ;; Compatibility alias with Org versions < 7.8.03
20907 (defalias 'org-on-heading-p 'org-at-heading-p)
20909 (defun org-at-drawer-p nil
20910 "Is cursor at a drawer keyword?"
20911 (save-excursion
20912 (move-beginning-of-line 1)
20913 (looking-at org-drawer-regexp)))
20915 (defun org-at-block-p nil
20916 "Is cursor at a block keyword?"
20917 (save-excursion
20918 (move-beginning-of-line 1)
20919 (looking-at org-block-regexp)))
20921 (defun org-point-at-end-of-empty-headline ()
20922 "If point is at the end of an empty headline, return t, else nil.
20923 If the heading only contains a TODO keyword, it is still still considered
20924 empty."
20925 (and (looking-at "[ \t]*$")
20926 (save-excursion
20927 (beginning-of-line 1)
20928 (let ((case-fold-search nil))
20929 (looking-at org-todo-line-regexp)))
20930 (string= (match-string 3) "")))
20932 (defun org-at-heading-or-item-p ()
20933 (or (org-at-heading-p) (org-at-item-p)))
20935 (defun org-at-target-p ()
20936 (or (org-in-regexp org-radio-target-regexp)
20937 (org-in-regexp org-target-regexp)))
20938 ;; Compatibility alias with Org versions < 7.8.03
20939 (defalias 'org-on-target-p 'org-at-target-p)
20941 (defun org-up-heading-all (arg)
20942 "Move to the heading line of which the present line is a subheading.
20943 This function considers both visible and invisible heading lines.
20944 With argument, move up ARG levels."
20945 (if (fboundp 'outline-up-heading-all)
20946 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20947 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20949 (defun org-up-heading-safe ()
20950 "Move to the heading line of which the present line is a subheading.
20951 This version will not throw an error. It will return the level of the
20952 headline found, or nil if no higher level is found.
20954 Also, this function will be a lot faster than `outline-up-heading',
20955 because it relies on stars being the outline starters. This can really
20956 make a significant difference in outlines with very many siblings."
20957 (let (start-level re)
20958 (org-back-to-heading t)
20959 (setq start-level (funcall outline-level))
20960 (if (equal start-level 1)
20962 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20963 (if (re-search-backward re nil t)
20964 (funcall outline-level)))))
20966 (defun org-first-sibling-p ()
20967 "Is this heading the first child of its parents?"
20968 (interactive)
20969 (let ((re org-outline-regexp-bol)
20970 level l)
20971 (unless (org-at-heading-p t)
20972 (error "Not at a heading"))
20973 (setq level (funcall outline-level))
20974 (save-excursion
20975 (if (not (re-search-backward re nil t))
20977 (setq l (funcall outline-level))
20978 (< l level)))))
20980 (defun org-goto-sibling (&optional previous)
20981 "Goto the next sibling, even if it is invisible.
20982 When PREVIOUS is set, go to the previous sibling instead. Returns t
20983 when a sibling was found. When none is found, return nil and don't
20984 move point."
20985 (let ((fun (if previous 're-search-backward 're-search-forward))
20986 (pos (point))
20987 (re org-outline-regexp-bol)
20988 level l)
20989 (when (condition-case nil (org-back-to-heading t) (error nil))
20990 (setq level (funcall outline-level))
20991 (catch 'exit
20992 (or previous (forward-char 1))
20993 (while (funcall fun re nil t)
20994 (setq l (funcall outline-level))
20995 (when (< l level) (goto-char pos) (throw 'exit nil))
20996 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20997 (goto-char pos)
20998 nil))))
21000 (defun org-show-siblings ()
21001 "Show all siblings of the current headline."
21002 (save-excursion
21003 (while (org-goto-sibling) (org-flag-heading nil)))
21004 (save-excursion
21005 (while (org-goto-sibling 'previous)
21006 (org-flag-heading nil))))
21008 (defun org-goto-first-child ()
21009 "Goto the first child, even if it is invisible.
21010 Return t when a child was found. Otherwise don't move point and
21011 return nil."
21012 (let (level (pos (point)) (re org-outline-regexp-bol))
21013 (when (condition-case nil (org-back-to-heading t) (error nil))
21014 (setq level (outline-level))
21015 (forward-char 1)
21016 (if (and (re-search-forward re nil t) (> (outline-level) level))
21017 (progn (goto-char (match-beginning 0)) t)
21018 (goto-char pos) nil))))
21020 (defun org-show-hidden-entry ()
21021 "Show an entry where even the heading is hidden."
21022 (save-excursion
21023 (org-show-entry)))
21025 (defun org-flag-heading (flag &optional entry)
21026 "Flag the current heading. FLAG non-nil means make invisible.
21027 When ENTRY is non-nil, show the entire entry."
21028 (save-excursion
21029 (org-back-to-heading t)
21030 ;; Check if we should show the entire entry
21031 (if entry
21032 (progn
21033 (org-show-entry)
21034 (save-excursion
21035 (and (outline-next-heading)
21036 (org-flag-heading nil))))
21037 (outline-flag-region (max (point-min) (1- (point)))
21038 (save-excursion (outline-end-of-heading) (point))
21039 flag))))
21041 (defun org-get-next-sibling ()
21042 "Move to next heading of the same level, and return point.
21043 If there is no such heading, return nil.
21044 This is like outline-next-sibling, but invisible headings are ok."
21045 (let ((level (funcall outline-level)))
21046 (outline-next-heading)
21047 (while (and (not (eobp)) (> (funcall outline-level) level))
21048 (outline-next-heading))
21049 (if (or (eobp) (< (funcall outline-level) level))
21051 (point))))
21053 (defun org-get-last-sibling ()
21054 "Move to previous heading of the same level, and return point.
21055 If there is no such heading, return nil."
21056 (let ((opoint (point))
21057 (level (funcall outline-level)))
21058 (outline-previous-heading)
21059 (when (and (/= (point) opoint) (outline-on-heading-p t))
21060 (while (and (> (funcall outline-level) level)
21061 (not (bobp)))
21062 (outline-previous-heading))
21063 (if (< (funcall outline-level) level)
21065 (point)))))
21067 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21068 ;; This contains an exact copy of the original function, but it uses
21069 ;; `org-back-to-heading', to make it work also in invisible
21070 ;; trees. And is uses an invisible-OK argument.
21071 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21072 ;; Furthermore, when used inside Org, finding the end of a large subtree
21073 ;; with many children and grandchildren etc, this can be much faster
21074 ;; than the outline version.
21075 (org-back-to-heading invisible-OK)
21076 (let ((first t)
21077 (level (funcall outline-level)))
21078 (if (and (eq major-mode 'org-mode) (< level 1000))
21079 ;; A true heading (not a plain list item), in Org-mode
21080 ;; This means we can easily find the end by looking
21081 ;; only for the right number of stars. Using a regexp to do
21082 ;; this is so much faster than using a Lisp loop.
21083 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21084 (forward-char 1)
21085 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21086 ;; something else, do it the slow way
21087 (while (and (not (eobp))
21088 (or first (> (funcall outline-level) level)))
21089 (setq first nil)
21090 (outline-next-heading)))
21091 (unless to-heading
21092 (if (memq (preceding-char) '(?\n ?\^M))
21093 (progn
21094 ;; Go to end of line before heading
21095 (forward-char -1)
21096 (if (memq (preceding-char) '(?\n ?\^M))
21097 ;; leave blank line before heading
21098 (forward-char -1))))))
21099 (point))
21101 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21102 "Use Org version in org-mode, for dramatic speed-up."
21103 (if (eq major-mode 'org-mode)
21104 (progn
21105 (org-end-of-subtree nil t)
21106 (unless (eobp) (backward-char 1)))
21107 ad-do-it))
21109 (defun org-end-of-meta-data-and-drawers ()
21110 "Jump to the first text after meta data and drawers in the current entry.
21111 This will move over empty lines, lines with planning time stamps,
21112 clocking lines, and drawers."
21113 (org-back-to-heading t)
21114 (let ((end (save-excursion (outline-next-heading) (point)))
21115 (re (concat "\\(" org-drawer-regexp "\\)"
21116 "\\|" "[ \t]*" org-keyword-time-regexp)))
21117 (forward-line 1)
21118 (while (re-search-forward re end t)
21119 (if (not (match-end 1))
21120 ;; empty or planning line
21121 (forward-line 1)
21122 ;; a drawer, find the end
21123 (re-search-forward "^[ \t]*:END:" end 'move)
21124 (forward-line 1)))
21125 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21126 (point)))
21128 (defun org-forward-same-level (arg &optional invisible-ok)
21129 "Move forward to the arg'th subheading at same level as this one.
21130 Stop at the first and last subheadings of a superior heading.
21131 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21132 it wil also look at invisible ones."
21133 (interactive "p")
21134 (org-back-to-heading invisible-ok)
21135 (org-at-heading-p)
21136 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21137 (re (format "^\\*\\{1,%d\\} " level))
21139 (forward-char 1)
21140 (while (> arg 0)
21141 (while (and (re-search-forward re nil 'move)
21142 (setq l (- (match-end 0) (match-beginning 0) 1))
21143 (= l level)
21144 (not invisible-ok)
21145 (progn (backward-char 1) (outline-invisible-p)))
21146 (if (< l level) (setq arg 1)))
21147 (setq arg (1- arg)))
21148 (beginning-of-line 1)))
21150 (defun org-backward-same-level (arg &optional invisible-ok)
21151 "Move backward to the arg'th subheading at same level as this one.
21152 Stop at the first and last subheadings of a superior heading."
21153 (interactive "p")
21154 (org-back-to-heading)
21155 (org-at-heading-p)
21156 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21157 (re (format "^\\*\\{1,%d\\} " level))
21159 (while (> arg 0)
21160 (while (and (re-search-backward re nil 'move)
21161 (setq l (- (match-end 0) (match-beginning 0) 1))
21162 (= l level)
21163 (not invisible-ok)
21164 (outline-invisible-p))
21165 (if (< l level) (setq arg 1)))
21166 (setq arg (1- arg)))))
21168 (defun org-show-subtree ()
21169 "Show everything after this heading at deeper levels."
21170 (outline-flag-region
21171 (point)
21172 (save-excursion
21173 (org-end-of-subtree t t))
21174 nil))
21176 (defun org-show-entry ()
21177 "Show the body directly following this heading.
21178 Show the heading too, if it is currently invisible."
21179 (interactive)
21180 (save-excursion
21181 (condition-case nil
21182 (progn
21183 (org-back-to-heading t)
21184 (outline-flag-region
21185 (max (point-min) (1- (point)))
21186 (save-excursion
21187 (if (re-search-forward
21188 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21189 (match-beginning 1)
21190 (point-max)))
21191 nil)
21192 (org-cycle-hide-drawers 'children))
21193 (error nil))))
21195 (defun org-make-options-regexp (kwds &optional extra)
21196 "Make a regular expression for keyword lines."
21197 (concat
21199 "#?[ \t]*\\+\\("
21200 (mapconcat 'regexp-quote kwds "\\|")
21201 (if extra (concat "\\|" extra))
21202 "\\):[ \t]*"
21203 "\\(.*\\)"))
21205 ;; Make isearch reveal the necessary context
21206 (defun org-isearch-end ()
21207 "Reveal context after isearch exits."
21208 (when isearch-success ; only if search was successful
21209 (if (featurep 'xemacs)
21210 ;; Under XEmacs, the hook is run in the correct place,
21211 ;; we directly show the context.
21212 (org-show-context 'isearch)
21213 ;; In Emacs the hook runs *before* restoring the overlays.
21214 ;; So we have to use a one-time post-command-hook to do this.
21215 ;; (Emacs 22 has a special variable, see function `org-mode')
21216 (unless (and (boundp 'isearch-mode-end-hook-quit)
21217 isearch-mode-end-hook-quit)
21218 ;; Only when the isearch was not quitted.
21219 (org-add-hook 'post-command-hook 'org-isearch-post-command
21220 'append 'local)))))
21222 (defun org-isearch-post-command ()
21223 "Remove self from hook, and show context."
21224 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21225 (org-show-context 'isearch))
21228 ;;;; Integration with and fixes for other packages
21230 ;;; Imenu support
21232 (defvar org-imenu-markers nil
21233 "All markers currently used by Imenu.")
21234 (make-variable-buffer-local 'org-imenu-markers)
21236 (defun org-imenu-new-marker (&optional pos)
21237 "Return a new marker for use by Imenu, and remember the marker."
21238 (let ((m (make-marker)))
21239 (move-marker m (or pos (point)))
21240 (push m org-imenu-markers)
21243 (defun org-imenu-get-tree ()
21244 "Produce the index for Imenu."
21245 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21246 (setq org-imenu-markers nil)
21247 (let* ((n org-imenu-depth)
21248 (re (concat "^" (org-get-limited-outline-regexp)))
21249 (subs (make-vector (1+ n) nil))
21250 (last-level 0)
21251 m level head)
21252 (save-excursion
21253 (save-restriction
21254 (widen)
21255 (goto-char (point-max))
21256 (while (re-search-backward re nil t)
21257 (setq level (org-reduced-level (funcall outline-level)))
21258 (when (<= level n)
21259 (looking-at org-complex-heading-regexp)
21260 (setq head (org-link-display-format
21261 (org-match-string-no-properties 4))
21262 m (org-imenu-new-marker))
21263 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21264 (if (>= level last-level)
21265 (push (cons head m) (aref subs level))
21266 (push (cons head (aref subs (1+ level))) (aref subs level))
21267 (loop for i from (1+ level) to n do (aset subs i nil)))
21268 (setq last-level level)))))
21269 (aref subs 1)))
21271 (eval-after-load "imenu"
21272 '(progn
21273 (add-hook 'imenu-after-jump-hook
21274 (lambda ()
21275 (if (eq major-mode 'org-mode)
21276 (org-show-context 'org-goto))))))
21278 (defun org-link-display-format (link)
21279 "Replace a link with either the description, or the link target
21280 if no description is present"
21281 (save-match-data
21282 (if (string-match org-bracket-link-analytic-regexp link)
21283 (replace-match (if (match-end 5)
21284 (match-string 5 link)
21285 (concat (match-string 1 link)
21286 (match-string 3 link)))
21287 nil t link)
21288 link)))
21290 (defun org-toggle-link-display ()
21291 "Toggle the literal or descriptive display of links."
21292 (interactive)
21293 (if org-descriptive-links
21294 (progn (org-remove-from-invisibility-spec '(org-link))
21295 (org-restart-font-lock)
21296 (setq org-descriptive-links nil))
21297 (progn (add-to-invisibility-spec '(org-link))
21298 (org-restart-font-lock)
21299 (setq org-descriptive-links t))))
21301 ;; Speedbar support
21303 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21304 "Overlay marking the agenda restriction line in speedbar.")
21305 (overlay-put org-speedbar-restriction-lock-overlay
21306 'face 'org-agenda-restriction-lock)
21307 (overlay-put org-speedbar-restriction-lock-overlay
21308 'help-echo "Agendas are currently limited to this item.")
21309 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21311 (defun org-speedbar-set-agenda-restriction ()
21312 "Restrict future agenda commands to the location at point in speedbar.
21313 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21314 (interactive)
21315 (require 'org-agenda)
21316 (let (p m tp np dir txt)
21317 (cond
21318 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21319 'org-imenu t))
21320 (setq m (get-text-property p 'org-imenu-marker))
21321 (with-current-buffer (marker-buffer m)
21322 (goto-char m)
21323 (org-agenda-set-restriction-lock 'subtree)))
21324 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21325 'speedbar-function 'speedbar-find-file))
21326 (setq tp (previous-single-property-change
21327 (1+ p) 'speedbar-function)
21328 np (next-single-property-change
21329 tp 'speedbar-function)
21330 dir (speedbar-line-directory)
21331 txt (buffer-substring-no-properties (or tp (point-min))
21332 (or np (point-max))))
21333 (with-current-buffer (find-file-noselect
21334 (let ((default-directory dir))
21335 (expand-file-name txt)))
21336 (unless (eq major-mode 'org-mode)
21337 (error "Cannot restrict to non-Org-mode file"))
21338 (org-agenda-set-restriction-lock 'file)))
21339 (t (error "Don't know how to restrict Org-mode's agenda")))
21340 (move-overlay org-speedbar-restriction-lock-overlay
21341 (point-at-bol) (point-at-eol))
21342 (setq current-prefix-arg nil)
21343 (org-agenda-maybe-redo)))
21345 (eval-after-load "speedbar"
21346 '(progn
21347 (speedbar-add-supported-extension ".org")
21348 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21349 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21350 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21351 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21352 (add-hook 'speedbar-visiting-tag-hook
21353 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21355 ;;; Fixes and Hacks for problems with other packages
21357 ;; Make flyspell not check words in links, to not mess up our keymap
21358 (defun org-mode-flyspell-verify ()
21359 "Don't let flyspell put overlays at active buttons, or on
21360 {todo,all-time,additional-option-like}-keywords."
21361 (let ((pos (max (1- (point)) (point-min)))
21362 (word (thing-at-point 'word)))
21363 (and (not (get-text-property pos 'keymap))
21364 (not (get-text-property pos 'org-no-flyspell))
21365 (not (member word org-todo-keywords-1))
21366 (not (member word org-all-time-keywords))
21367 (not (member word org-additional-option-like-keywords)))))
21369 (defun org-remove-flyspell-overlays-in (beg end)
21370 "Remove flyspell overlays in region."
21371 (and (org-bound-and-true-p flyspell-mode)
21372 (fboundp 'flyspell-delete-region-overlays)
21373 (flyspell-delete-region-overlays beg end))
21374 (add-text-properties beg end '(org-no-flyspell t)))
21376 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21377 (eval-after-load "bookmark"
21378 '(if (boundp 'bookmark-after-jump-hook)
21379 ;; We can use the hook
21380 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21381 ;; Hook not available, use advice
21382 (defadvice bookmark-jump (after org-make-visible activate)
21383 "Make the position visible."
21384 (org-bookmark-jump-unhide))))
21386 ;; Make sure saveplace shows the location if it was hidden
21387 (eval-after-load "saveplace"
21388 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21389 "Make the position visible."
21390 (org-bookmark-jump-unhide)))
21392 ;; Make sure ecb shows the location if it was hidden
21393 (eval-after-load "ecb"
21394 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21395 "Make hierarchy visible when jumping into location from ECB tree buffer."
21396 (if (eq major-mode 'org-mode)
21397 (org-show-context))))
21399 (defun org-bookmark-jump-unhide ()
21400 "Unhide the current position, to show the bookmark location."
21401 (and (eq major-mode 'org-mode)
21402 (or (outline-invisible-p)
21403 (save-excursion (goto-char (max (point-min) (1- (point))))
21404 (outline-invisible-p)))
21405 (org-show-context 'bookmark-jump)))
21407 ;; Make session.el ignore our circular variable
21408 (eval-after-load "session"
21409 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21411 ;;;; Experimental code
21413 (defun org-closed-in-range ()
21414 "Sparse tree of items closed in a certain time range.
21415 Still experimental, may disappear in the future."
21416 (interactive)
21417 ;; Get the time interval from the user.
21418 (let* ((time1 (org-float-time
21419 (org-read-date nil 'to-time nil "Starting date: ")))
21420 (time2 (org-float-time
21421 (org-read-date nil 'to-time nil "End date:")))
21422 ;; callback function
21423 (callback (lambda ()
21424 (let ((time
21425 (org-float-time
21426 (apply 'encode-time
21427 (org-parse-time-string
21428 (match-string 1))))))
21429 ;; check if time in interval
21430 (and (>= time time1) (<= time time2))))))
21431 ;; make tree, check each match with the callback
21432 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21434 ;;;; Finish up
21436 (provide 'org)
21438 (run-hooks 'org-load-hook)
21440 ;;; org.el ends here