Remove maint.mk and maint-targets.mk from repository
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob8add2f1ccf8fddc9e9dd420d320a5f525224b569
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
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'format-spec)
80 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
81 (when (fboundp 'defvaralias)
82 (unless (boundp 'calendar-view-holidays-initially-flag)
83 (defvaralias 'calendar-view-holidays-initially-flag
84 'view-calendar-holidays-initially))
85 (unless (boundp 'calendar-view-diary-initially-flag)
86 (defvaralias 'calendar-view-diary-initially-flag
87 'view-diary-entries-initially))
88 (unless (boundp 'diary-fancy-buffer)
89 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
91 (require 'outline) (require 'noutline)
92 ;; Other stuff we need.
93 (require 'time-date)
94 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
95 (require 'easymenu)
96 (require 'overlay)
98 (require 'org-macs)
99 (require 'org-entities)
100 (require 'org-compat)
101 (require 'org-faces)
102 (require 'org-list)
103 (require 'org-pcomplete)
104 (require 'org-src)
105 (require 'org-footnote)
107 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
108 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
109 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
111 (declare-function org-at-clock-log-p "org-clock" ())
112 (declare-function org-clock-timestamps-up "org-clock" ())
113 (declare-function org-clock-timestamps-down "org-clock" ())
114 (declare-function find-library-name "find-func")
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 (defvaralias 'org-version 'org-release)
213 ;;;###autoload
214 (defun org-version (&optional here)
215 "Show the org-mode version in the echo area.
216 With prefix arg HERE, insert it at point."
217 (interactive "P")
218 (let* ((origin default-directory)
219 (version (if (boundp 'org-release) org-release "N/A"))
220 (git-version (if (boundp 'org-git-version) org-git-version "N/A"))
221 (org-install (ignore-errors (find-library-name "org-install"))))
222 (setq version (format "Org-mode version %s (%s @ %s)"
223 version
224 git-version
225 (if org-install org-install "org-install.el can not be found!")))
226 (if here (insert version))
227 (message version)))
229 ;;; Compatibility constants
231 ;;; The custom variables
233 (defgroup org nil
234 "Outline-based notes management and organizer."
235 :tag "Org"
236 :group 'outlines
237 :group 'calendar)
239 (defcustom org-mode-hook nil
240 "Mode hook for Org-mode, run after the mode was turned on."
241 :group 'org
242 :type 'hook)
244 (defcustom org-load-hook nil
245 "Hook that is run after org.el has been loaded."
246 :group 'org
247 :type 'hook)
249 (defcustom org-log-buffer-setup-hook nil
250 "Hook that is run after an Org log buffer is created."
251 :group 'org
252 :version "24.1"
253 :type 'hook)
255 (defvar org-modules) ; defined below
256 (defvar org-modules-loaded nil
257 "Have the modules been loaded already?")
259 (defun org-load-modules-maybe (&optional force)
260 "Load all extensions listed in `org-modules'."
261 (when (or force (not org-modules-loaded))
262 (mapc (lambda (ext)
263 (condition-case nil (require ext)
264 (error (message "Problems while trying to load feature `%s'" ext))))
265 org-modules)
266 (setq org-modules-loaded t)))
268 (defun org-set-modules (var value)
269 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
270 (set var value)
271 (when (featurep 'org)
272 (org-load-modules-maybe 'force)))
274 (when (org-bound-and-true-p org-modules)
275 (let ((a (member 'org-infojs org-modules)))
276 (and a (setcar a 'org-jsinfo))))
278 (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)
279 "Modules that should always be loaded together with org.el.
280 If a description starts with <C>, the file is not part of Emacs
281 and loading it will require that you have downloaded and properly installed
282 the org-mode distribution.
284 You can also use this system to load external packages (i.e. neither Org
285 core modules, nor modules from the CONTRIB directory). Just add symbols
286 to the end of the list. If the package is called org-xyz.el, then you need
287 to add the symbol `xyz', and the package must have a call to
289 (provide 'org-xyz)"
290 :group 'org
291 :set 'org-set-modules
292 :type
293 '(set :greedy t
294 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
295 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
296 (const :tag " crypt: Encryption of subtrees" org-crypt)
297 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
298 (const :tag " docview: Links to doc-view buffers" org-docview)
299 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
300 (const :tag " id: Global IDs for identifying entries" org-id)
301 (const :tag " info: Links to Info nodes" org-info)
302 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
303 (const :tag " habit: Track your consistency with habits" org-habit)
304 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
305 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
306 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
307 (const :tag " mew Links to Mew folders/messages" org-mew)
308 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
309 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
310 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
311 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
312 (const :tag " vm: Links to VM folders/messages" org-vm)
313 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
314 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
315 (const :tag " mouse: Additional mouse support" org-mouse)
316 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
318 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
319 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
320 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
321 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
322 (const :tag "C collector: Collect properties into tables" org-collector)
323 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
324 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
325 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
326 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
327 (const :tag "C eval: Include command output as text" org-eval)
328 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
329 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
330 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
331 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
332 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
334 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
336 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
337 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
338 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
339 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
340 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
341 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
342 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
343 (const :tag "C mtags: Support for muse-like tags" org-mtags)
344 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
345 (const :tag "C registry: A registry for Org-mode links" org-registry)
346 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
347 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
348 (const :tag "C secretary: Team management with org-mode" org-secretary)
349 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
350 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
351 (const :tag "C track: Keep up with Org-mode development" org-track)
352 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
353 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
354 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
356 (defcustom org-support-shift-select nil
357 "Non-nil means make shift-cursor commands select text when possible.
359 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
360 start selecting a region, or enlarge regions started in this way.
361 In Org-mode, in special contexts, these same keys are used for
362 other purposes, important enough to compete with shift selection.
363 Org tries to balance these needs by supporting `shift-select-mode'
364 outside these special contexts, under control of this variable.
366 The default of this variable is nil, to avoid confusing behavior. Shifted
367 cursor keys will then execute Org commands in the following contexts:
368 - on a headline, changing TODO state (left/right) and priority (up/down)
369 - on a time stamp, changing the time
370 - in a plain list item, changing the bullet type
371 - in a property definition line, switching between allowed values
372 - in the BEGIN line of a clock table (changing the time block).
373 Outside these contexts, the commands will throw an error.
375 When this variable is t and the cursor is not in a special
376 context, Org-mode will support shift-selection for making and
377 enlarging regions. To make this more effective, the bullet
378 cycling will no longer happen anywhere in an item line, but only
379 if the cursor is exactly on the bullet.
381 If you set this variable to the symbol `always', then the keys
382 will not be special in headlines, property lines, and item lines,
383 to make shift selection work there as well. If this is what you
384 want, you can use the following alternative commands: `C-c C-t'
385 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
386 can be used to switch TODO sets, `C-c -' to cycle item bullet
387 types, and properties can be edited by hand or in column view.
389 However, when the cursor is on a timestamp, shift-cursor commands
390 will still edit the time stamp - this is just too good to give up.
392 XEmacs user should have this variable set to nil, because
393 `shift-select-mode' is in Emacs 23 or later only."
394 :group 'org
395 :type '(choice
396 (const :tag "Never" nil)
397 (const :tag "When outside special context" t)
398 (const :tag "Everywhere except timestamps" always)))
400 (defcustom org-loop-over-headlines-in-active-region nil
401 "Shall some commands act upon headlines in the active region?
403 When set to `t', some commands will be performed in all headlines
404 within the active region.
406 When set to `start-level', some commands will be performed in all
407 headlines within the active region, provided that these headlines
408 are of the same level than the first one.
410 When set to a string, those commands will be performed on the
411 matching headlines within the active region. Such string must be
412 a tags/property/todo match as it is used in the agenda tags view.
414 The list of commands is: `org-schedule', `org-deadline',
415 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
416 `org-archive-to-archive-sibling'. The archiving commands skip
417 already archived entries."
418 :type '(choice (const :tag "Don't loop" nil)
419 (const :tag "All headlines in active region" t)
420 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
421 (string :tag "Tags/Property/Todo matcher"))
422 :version "24.1"
423 :group 'org-todo
424 :group 'org-archive)
426 (defgroup org-startup nil
427 "Options concerning startup of Org-mode."
428 :tag "Org Startup"
429 :group 'org)
431 (defcustom org-startup-folded t
432 "Non-nil means entering Org-mode will switch to OVERVIEW.
433 This can also be configured on a per-file basis by adding one of
434 the following lines anywhere in the buffer:
436 #+STARTUP: fold (or `overview', this is equivalent)
437 #+STARTUP: nofold (or `showall', this is equivalent)
438 #+STARTUP: content
439 #+STARTUP: showeverything"
440 :group 'org-startup
441 :type '(choice
442 (const :tag "nofold: show all" nil)
443 (const :tag "fold: overview" t)
444 (const :tag "content: all headlines" content)
445 (const :tag "show everything, even drawers" showeverything)))
447 (defcustom org-startup-truncated t
448 "Non-nil means entering Org-mode will set `truncate-lines'.
449 This is useful since some lines containing links can be very long and
450 uninteresting. Also tables look terrible when wrapped."
451 :group 'org-startup
452 :type 'boolean)
454 (defcustom org-startup-indented nil
455 "Non-nil means turn on `org-indent-mode' on startup.
456 This can also be configured on a per-file basis by adding one of
457 the following lines anywhere in the buffer:
459 #+STARTUP: indent
460 #+STARTUP: noindent"
461 :group 'org-structure
462 :type '(choice
463 (const :tag "Not" nil)
464 (const :tag "Globally (slow on startup in large files)" t)))
466 (defcustom org-use-sub-superscripts t
467 "Non-nil means interpret \"_\" and \"^\" for export.
468 When this option is turned on, you can use TeX-like syntax for sub- and
469 superscripts. Several characters after \"_\" or \"^\" will be
470 considered as a single item - so grouping with {} is normally not
471 needed. For example, the following things will be parsed as single
472 sub- or superscripts.
474 10^24 or 10^tau several digits will be considered 1 item.
475 10^-12 or 10^-tau a leading sign with digits or a word
476 x^2-y^3 will be read as x^2 - y^3, because items are
477 terminated by almost any nonword/nondigit char.
478 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
480 Still, ambiguity is possible - so when in doubt use {} to enclose the
481 sub/superscript. If you set this variable to the symbol `{}',
482 the braces are *required* in order to trigger interpretations as
483 sub/superscript. This can be helpful in documents that need \"_\"
484 frequently in plain text.
486 Not all export backends support this, but HTML does.
488 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
489 :group 'org-startup
490 :group 'org-export-translation
491 :version "24.1"
492 :type '(choice
493 (const :tag "Always interpret" t)
494 (const :tag "Only with braces" {})
495 (const :tag "Never interpret" nil)))
497 (if (fboundp 'defvaralias)
498 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
501 (defcustom org-startup-with-beamer-mode nil
502 "Non-nil means turn on `org-beamer-mode' on startup.
503 This can also be configured on a per-file basis by adding one of
504 the following lines anywhere in the buffer:
506 #+STARTUP: beamer"
507 :group 'org-startup
508 :version "24.1"
509 :type 'boolean)
511 (defcustom org-startup-align-all-tables nil
512 "Non-nil means align all tables when visiting a file.
513 This is useful when the column width in tables is forced with <N> cookies
514 in table fields. Such tables will look correct only after the first re-align.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
517 #+STARTUP: align
518 #+STARTUP: noalign"
519 :group 'org-startup
520 :type 'boolean)
522 (defcustom org-startup-with-inline-images nil
523 "Non-nil means show inline images when loading a new Org file.
524 This can also be configured on a per-file basis by adding one of
525 the following lines anywhere in the buffer:
526 #+STARTUP: inlineimages
527 #+STARTUP: noinlineimages"
528 :group 'org-startup
529 :version "24.1"
530 :type 'boolean)
532 (defcustom org-insert-mode-line-in-empty-file nil
533 "Non-nil means insert the first line setting Org-mode in empty files.
534 When the function `org-mode' is called interactively in an empty file, this
535 normally means that the file name does not automatically trigger Org-mode.
536 To ensure that the file will always be in Org-mode in the future, a
537 line enforcing Org-mode will be inserted into the buffer, if this option
538 has been set."
539 :group 'org-startup
540 :type 'boolean)
542 (defcustom org-replace-disputed-keys nil
543 "Non-nil means use alternative key bindings for some keys.
544 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
545 These keys are also used by other packages like shift-selection-mode'
546 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
547 If you want to use Org-mode together with one of these other modes,
548 or more generally if you would like to move some Org-mode commands to
549 other keys, set this variable and configure the keys with the variable
550 `org-disputed-keys'.
552 This option is only relevant at load-time of Org-mode, and must be set
553 *before* org.el is loaded. Changing it requires a restart of Emacs to
554 become effective."
555 :group 'org-startup
556 :type 'boolean)
558 (defcustom org-use-extra-keys nil
559 "Non-nil means use extra key sequence definitions for certain commands.
560 This happens automatically if you run XEmacs or if `window-system'
561 is nil. This variable lets you do the same manually. You must
562 set it before loading org.
564 Example: on Carbon Emacs 22 running graphically, with an external
565 keyboard on a Powerbook, the default way of setting M-left might
566 not work for either Alt or ESC. Setting this variable will make
567 it work for ESC."
568 :group 'org-startup
569 :type 'boolean)
571 (if (fboundp 'defvaralias)
572 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
574 (defcustom org-disputed-keys
575 '(([(shift up)] . [(meta p)])
576 ([(shift down)] . [(meta n)])
577 ([(shift left)] . [(meta -)])
578 ([(shift right)] . [(meta +)])
579 ([(control shift right)] . [(meta shift +)])
580 ([(control shift left)] . [(meta shift -)]))
581 "Keys for which Org-mode and other modes compete.
582 This is an alist, cars are the default keys, second element specifies
583 the alternative to use when `org-replace-disputed-keys' is t.
585 Keys can be specified in any syntax supported by `define-key'.
586 The value of this option takes effect only at Org-mode's startup,
587 therefore you'll have to restart Emacs to apply it after changing."
588 :group 'org-startup
589 :type 'alist)
591 (defun org-key (key)
592 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
593 Or return the original if not disputed.
594 Also apply the translations defined in `org-xemacs-key-equivalents'."
595 (when org-replace-disputed-keys
596 (let* ((nkey (key-description key))
597 (x (org-find-if (lambda (x)
598 (equal (key-description (car x)) nkey))
599 org-disputed-keys)))
600 (setq key (if x (cdr x) key))))
601 (when (featurep 'xemacs)
602 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
603 key)
605 (defun org-find-if (predicate seq)
606 (catch 'exit
607 (while seq
608 (if (funcall predicate (car seq))
609 (throw 'exit (car seq))
610 (pop seq)))))
612 (defun org-defkey (keymap key def)
613 "Define a key, possibly translated, as returned by `org-key'."
614 (define-key keymap (org-key key) def))
616 (defcustom org-ellipsis nil
617 "The ellipsis to use in the Org-mode outline.
618 When nil, just use the standard three dots. When a string, use that instead,
619 When a face, use the standard 3 dots, but with the specified face.
620 The change affects only Org-mode (which will then use its own display table).
621 Changing this requires executing `M-x org-mode' in a buffer to become
622 effective."
623 :group 'org-startup
624 :type '(choice (const :tag "Default" nil)
625 (face :tag "Face" :value org-warning)
626 (string :tag "String" :value "...#")))
628 (defvar org-display-table nil
629 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
631 (defgroup org-keywords nil
632 "Keywords in Org-mode."
633 :tag "Org Keywords"
634 :group 'org)
636 (defcustom org-deadline-string "DEADLINE:"
637 "String to mark deadline entries.
638 A deadline is this string, followed by a time stamp. Should be a word,
639 terminated by a colon. You can insert a schedule keyword and
640 a timestamp with \\[org-deadline].
641 Changes become only effective after restarting Emacs."
642 :group 'org-keywords
643 :type 'string)
645 (defcustom org-scheduled-string "SCHEDULED:"
646 "String to mark scheduled TODO entries.
647 A schedule is this string, followed by a time stamp. Should be a word,
648 terminated by a colon. You can insert a schedule keyword and
649 a timestamp with \\[org-schedule].
650 Changes become only effective after restarting Emacs."
651 :group 'org-keywords
652 :type 'string)
654 (defcustom org-closed-string "CLOSED:"
655 "String used as the prefix for timestamps logging closing a TODO entry."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-clock-string "CLOCK:"
660 "String used as prefix for timestamps clocking work hours on an item."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-comment-string "COMMENT"
665 "Entries starting with this keyword will never be exported.
666 An entry can be toggled between COMMENT and normal with
667 \\[org-toggle-comment].
668 Changes become only effective after restarting Emacs."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-quote-string "QUOTE"
673 "Entries starting with this keyword will be exported in fixed-width font.
674 Quoting applies only to the text in the entry following the headline, and does
675 not extend beyond the next headline, even if that is lower level.
676 An entry can be toggled between QUOTE and normal with
677 \\[org-toggle-fixed-width-section]."
678 :group 'org-keywords
679 :type 'string)
681 (defconst org-repeat-re
682 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
683 "Regular expression for specifying repeated events.
684 After a match, group 1 contains the repeat expression.")
686 (defgroup org-structure nil
687 "Options concerning the general structure of Org-mode files."
688 :tag "Org Structure"
689 :group 'org)
691 (defgroup org-reveal-location nil
692 "Options about how to make context of a location visible."
693 :tag "Org Reveal Location"
694 :group 'org-structure)
696 (defconst org-context-choice
697 '(choice
698 (const :tag "Always" t)
699 (const :tag "Never" nil)
700 (repeat :greedy t :tag "Individual contexts"
701 (cons
702 (choice :tag "Context"
703 (const agenda)
704 (const org-goto)
705 (const occur-tree)
706 (const tags-tree)
707 (const link-search)
708 (const mark-goto)
709 (const bookmark-jump)
710 (const isearch)
711 (const default))
712 (boolean))))
713 "Contexts for the reveal options.")
715 (defcustom org-show-hierarchy-above '((default . t))
716 "Non-nil means show full hierarchy when revealing a location.
717 Org-mode often shows locations in an org-mode file which might have
718 been invisible before. When this is set, the hierarchy of headings
719 above the exposed location is shown.
720 Turning this off for example for sparse trees makes them very compact.
721 Instead of t, this can also be an alist specifying this option for different
722 contexts. Valid contexts are
723 agenda when exposing an entry from the agenda
724 org-goto when using the command `org-goto' on key C-c C-j
725 occur-tree when using the command `org-occur' on key C-c /
726 tags-tree when constructing a sparse tree based on tags matches
727 link-search when exposing search matches associated with a link
728 mark-goto when exposing the jump goal of a mark
729 bookmark-jump when exposing a bookmark location
730 isearch when exiting from an incremental search
731 default default for all contexts not set explicitly"
732 :group 'org-reveal-location
733 :type org-context-choice)
735 (defcustom org-show-following-heading '((default . nil))
736 "Non-nil means show following heading when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the heading following the
739 match is shown.
740 Turning this off for example for sparse trees makes them very compact,
741 but makes it harder to edit the location of the match. In such a case,
742 use the command \\[org-reveal] to show more context.
743 Instead of t, this can also be an alist specifying this option for different
744 contexts. See `org-show-hierarchy-above' for valid contexts."
745 :group 'org-reveal-location
746 :type org-context-choice)
748 (defcustom org-show-siblings '((default . nil) (isearch t))
749 "Non-nil means show all sibling heading when revealing a location.
750 Org-mode often shows locations in an org-mode file which might have
751 been invisible before. When this is set, the sibling of the current entry
752 heading are all made visible. If `org-show-hierarchy-above' is t,
753 the same happens on each level of the hierarchy above the current entry.
755 By default this is on for the isearch context, off for all other contexts.
756 Turning this off for example for sparse trees makes them very compact,
757 but makes it harder to edit the location of the match. In such a case,
758 use the command \\[org-reveal] to show more context.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. See `org-show-hierarchy-above' for valid contexts."
761 :group 'org-reveal-location
762 :type org-context-choice)
764 (defcustom org-show-entry-below '((default . nil))
765 "Non-nil means show the entry below a headline when revealing a location.
766 Org-mode often shows locations in an org-mode file which might have
767 been invisible before. When this is set, the text below the headline that is
768 exposed is also shown.
770 By default this is off for all contexts.
771 Instead of t, this can also be an alist specifying this option for different
772 contexts. See `org-show-hierarchy-above' for valid contexts."
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-indirect-buffer-display 'other-window
777 "How should indirect tree buffers be displayed?
778 This applies to indirect buffers created with the commands
779 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
780 Valid values are:
781 current-window Display in the current window
782 other-window Just display in another window.
783 dedicated-frame Create one new frame, and re-use it each time.
784 new-frame Make a new frame each time. Note that in this case
785 previously-made indirect buffers are kept, and you need to
786 kill these buffers yourself."
787 :group 'org-structure
788 :group 'org-agenda-windows
789 :type '(choice
790 (const :tag "In current window" current-window)
791 (const :tag "In current frame, other window" other-window)
792 (const :tag "Each time a new frame" new-frame)
793 (const :tag "One dedicated frame" dedicated-frame)))
795 (defcustom org-use-speed-commands nil
796 "Non-nil means activate single letter commands at beginning of a headline.
797 This may also be a function to test for appropriate locations where speed
798 commands should be active."
799 :group 'org-structure
800 :type '(choice
801 (const :tag "Never" nil)
802 (const :tag "At beginning of headline stars" t)
803 (function)))
805 (defcustom org-speed-commands-user nil
806 "Alist of additional speed commands.
807 This list will be checked before `org-speed-commands-default'
808 when the variable `org-use-speed-commands' is non-nil
809 and when the cursor is at the beginning of a headline.
810 The car if each entry is a string with a single letter, which must
811 be assigned to `self-insert-command' in the global map.
812 The cdr is either a command to be called interactively, a function
813 to be called, or a form to be evaluated.
814 An entry that is just a list with a single string will be interpreted
815 as a descriptive headline that will be added when listing the speed
816 commands in the Help buffer using the `?' speed command."
817 :group 'org-structure
818 :type '(repeat :value ("k" . ignore)
819 (choice :value ("k" . ignore)
820 (list :tag "Descriptive Headline" (string :tag "Headline"))
821 (cons :tag "Letter and Command"
822 (string :tag "Command letter")
823 (choice
824 (function)
825 (sexp))))))
827 (defgroup org-cycle nil
828 "Options concerning visibility cycling in Org-mode."
829 :tag "Org Cycle"
830 :group 'org-structure)
832 (defcustom org-cycle-skip-children-state-if-no-children t
833 "Non-nil means skip CHILDREN state in entries that don't have any."
834 :group 'org-cycle
835 :type 'boolean)
837 (defcustom org-cycle-max-level nil
838 "Maximum level which should still be subject to visibility cycling.
839 Levels higher than this will, for cycling, be treated as text, not a headline.
840 When `org-odd-levels-only' is set, a value of N in this variable actually
841 means 2N-1 stars as the limiting headline.
842 When nil, cycle all levels.
843 Note that the limiting level of cycling is also influenced by
844 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
845 `org-inlinetask-min-level' is, cycling will be limited to levels one less
846 than its value."
847 :group 'org-cycle
848 :type '(choice
849 (const :tag "No limit" nil)
850 (integer :tag "Maximum level")))
852 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
853 "Names of drawers. Drawers are not opened by cycling on the headline above.
854 Drawers only open with a TAB on the drawer line itself. A drawer looks like
855 this:
856 :DRAWERNAME:
857 .....
858 :END:
859 The drawer \"PROPERTIES\" is special for capturing properties through
860 the property API.
862 Drawers can be defined on the per-file basis with a line like:
864 #+DRAWERS: HIDDEN STATE PROPERTIES"
865 :group 'org-structure
866 :group 'org-cycle
867 :type '(repeat (string :tag "Drawer Name")))
869 (defcustom org-hide-block-startup nil
870 "Non-nil means entering Org-mode will fold all blocks.
871 This can also be set in on a per-file basis with
873 #+STARTUP: hideblocks
874 #+STARTUP: showblocks"
875 :group 'org-startup
876 :group 'org-cycle
877 :type 'boolean)
879 (defcustom org-cycle-global-at-bob nil
880 "Cycle globally if cursor is at beginning of buffer and not at a headline.
881 This makes it possible to do global cycling without having to use S-TAB or
882 \\[universal-argument] TAB. For this special case to work, the first line \
883 of the buffer
884 must not be a headline - it may be empty or some other text. When used in
885 this way, `org-cycle-hook' is disables temporarily, to make sure the
886 cursor stays at the beginning of the buffer.
887 When this option is nil, don't do anything special at the beginning
888 of the buffer."
889 :group 'org-cycle
890 :type 'boolean)
892 (defcustom org-cycle-level-after-item/entry-creation t
893 "Non-nil means cycle entry level or item indentation in new empty entries.
895 When the cursor is at the end of an empty headline, i.e with only stars
896 and maybe a TODO keyword, TAB will then switch the entry to become a child,
897 and then all possible ancestor states, before returning to the original state.
898 This makes data entry extremely fast: M-RET to create a new headline,
899 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
901 When the cursor is at the end of an empty plain list item, one TAB will
902 make it a subitem, two or more tabs will back up to make this an item
903 higher up in the item hierarchy."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-emulate-tab t
908 "Where should `org-cycle' emulate TAB.
909 nil Never
910 white Only in completely white lines
911 whitestart Only at the beginning of lines, before the first non-white char
912 t Everywhere except in headlines
913 exc-hl-bol Everywhere except at the start of a headline
914 If TAB is used in a place where it does not emulate TAB, the current subtree
915 visibility is cycled."
916 :group 'org-cycle
917 :type '(choice (const :tag "Never" nil)
918 (const :tag "Only in completely white lines" white)
919 (const :tag "Before first char in a line" whitestart)
920 (const :tag "Everywhere except in headlines" t)
921 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
924 (defcustom org-cycle-separator-lines 2
925 "Number of empty lines needed to keep an empty line between collapsed trees.
926 If you leave an empty line between the end of a subtree and the following
927 headline, this empty line is hidden when the subtree is folded.
928 Org-mode will leave (exactly) one empty line visible if the number of
929 empty lines is equal or larger to the number given in this variable.
930 So the default 2 means at least 2 empty lines after the end of a subtree
931 are needed to produce free space between a collapsed subtree and the
932 following headline.
934 If the number is negative, and the number of empty lines is at least -N,
935 all empty lines are shown.
937 Special case: when 0, never leave empty lines in collapsed view."
938 :group 'org-cycle
939 :type 'integer)
940 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
942 (defcustom org-pre-cycle-hook nil
943 "Hook that is run before visibility cycling is happening.
944 The function(s) in this hook must accept a single argument which indicates
945 the new state that will be set right after running this hook. The
946 argument is a symbol. Before a global state change, it can have the values
947 `overview', `content', or `all'. Before a local state change, it can have
948 the values `folded', `children', or `subtree'."
949 :group 'org-cycle
950 :type 'hook)
952 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
953 org-cycle-hide-drawers
954 org-cycle-show-empty-lines
955 org-optimize-window-after-visibility-change)
956 "Hook that is run after `org-cycle' has changed the buffer visibility.
957 The function(s) in this hook must accept a single argument which indicates
958 the new state that was set by the most recent `org-cycle' command. The
959 argument is a symbol. After a global state change, it can have the values
960 `overview', `content', or `all'. After a local state change, it can have
961 the values `folded', `children', or `subtree'."
962 :group 'org-cycle
963 :type 'hook)
965 (defgroup org-edit-structure nil
966 "Options concerning structure editing in Org-mode."
967 :tag "Org Edit Structure"
968 :group 'org-structure)
970 (defcustom org-odd-levels-only nil
971 "Non-nil means skip even levels and only use odd levels for the outline.
972 This has the effect that two stars are being added/taken away in
973 promotion/demotion commands. It also influences how levels are
974 handled by the exporters.
975 Changing it requires restart of `font-lock-mode' to become effective
976 for fontification also in regions already fontified.
977 You may also set this on a per-file basis by adding one of the following
978 lines to the buffer:
980 #+STARTUP: odd
981 #+STARTUP: oddeven"
982 :group 'org-edit-structure
983 :group 'org-appearance
984 :type 'boolean)
986 (defcustom org-adapt-indentation t
987 "Non-nil means adapt indentation to outline node level.
989 When this variable is set, Org assumes that you write outlines by
990 indenting text in each node to align with the headline (after the stars).
991 The following issues are influenced by this variable:
993 - When this is set and the *entire* text in an entry is indented, the
994 indentation is increased by one space in a demotion command, and
995 decreased by one in a promotion command. If any line in the entry
996 body starts with text at column 0, indentation is not changed at all.
998 - Property drawers and planning information is inserted indented when
999 this variable s set. When nil, they will not be indented.
1001 - TAB indents a line relative to context. The lines below a headline
1002 will be indented when this variable is set.
1004 Note that this is all about true indentation, by adding and removing
1005 space characters. See also `org-indent.el' which does level-dependent
1006 indentation in a virtual way, i.e. at display time in Emacs."
1007 :group 'org-edit-structure
1008 :type 'boolean)
1010 (defcustom org-special-ctrl-a/e nil
1011 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1013 When t, `C-a' will bring back the cursor to the beginning of the
1014 headline text, i.e. after the stars and after a possible TODO
1015 keyword. In an item, this will be the position after bullet and
1016 check-box, if any. When the cursor is already at that position,
1017 another `C-a' will bring it to the beginning of the line.
1019 `C-e' will jump to the end of the headline, ignoring the presence
1020 of tags in the headline. A second `C-e' will then jump to the
1021 true end of the line, after any tags. This also means that, when
1022 this variable is non-nil, `C-e' also will never jump beyond the
1023 end of the heading of a folded section, i.e. not after the
1024 ellipses.
1026 When set to the symbol `reversed', the first `C-a' or `C-e' works
1027 normally, going to the true line boundary first. Only a directly
1028 following, identical keypress will bring the cursor to the
1029 special positions.
1031 This may also be a cons cell where the behavior for `C-a' and
1032 `C-e' is set separately."
1033 :group 'org-edit-structure
1034 :type '(choice
1035 (const :tag "off" nil)
1036 (const :tag "on: after stars/bullet and before tags first" t)
1037 (const :tag "reversed: true line boundary first" reversed)
1038 (cons :tag "Set C-a and C-e separately"
1039 (choice :tag "Special C-a"
1040 (const :tag "off" nil)
1041 (const :tag "on: after stars/bullet first" t)
1042 (const :tag "reversed: before stars/bullet first" reversed))
1043 (choice :tag "Special C-e"
1044 (const :tag "off" nil)
1045 (const :tag "on: before tags first" t)
1046 (const :tag "reversed: after tags first" reversed)))))
1047 (if (fboundp 'defvaralias)
1048 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1050 (defcustom org-special-ctrl-k nil
1051 "Non-nil means `C-k' will behave specially in headlines.
1052 When nil, `C-k' will call the default `kill-line' command.
1053 When t, the following will happen while the cursor is in the headline:
1055 - When the cursor is at the beginning of a headline, kill the entire
1056 line and possible the folded subtree below the line.
1057 - When in the middle of the headline text, kill the headline up to the tags.
1058 - When after the headline text, kill the tags."
1059 :group 'org-edit-structure
1060 :type 'boolean)
1062 (defcustom org-ctrl-k-protect-subtree nil
1063 "Non-nil means, do not delete a hidden subtree with C-k.
1064 When set to the symbol `error', simply throw an error when C-k is
1065 used to kill (part-of) a headline that has hidden text behind it.
1066 Any other non-nil value will result in a query to the user, if it is
1067 OK to kill that hidden subtree. When nil, kill without remorse."
1068 :group 'org-edit-structure
1069 :version "24.1"
1070 :type '(choice
1071 (const :tag "Do not protect hidden subtrees" nil)
1072 (const :tag "Protect hidden subtrees with a security query" t)
1073 (const :tag "Never kill a hidden subtree with C-k" error)))
1075 (defcustom org-catch-invisible-edits nil
1076 "Check if in invisible region before inserting or deleting a character.
1077 Valid values are:
1079 nil Do not check, so just do invisible edits.
1080 error Throw an error and do nothing.
1081 show Make point visible, and do the requested edit.
1082 show-and-error Make point visible, then throw an error and abort the edit.
1083 smart Make point visible, and do insertion/deletion if it is
1084 adjacent to visible text and the change feels predictable.
1085 Never delete a previously invisible character or add in the
1086 middle or right after an invisible region. Basically, this
1087 allows insertion and backward-delete right before ellipses.
1088 FIXME: maybe in this case we should not even show?"
1089 :group 'org-edit-structure
1090 :version "24.1"
1091 :type '(choice
1092 (const :tag "Do not check" nil)
1093 (const :tag "Throw error when trying to edit" error)
1094 (const :tag "Unhide, but do not do the edit" show-and-error)
1095 (const :tag "Show invisible part and do the edit" show)
1096 (const :tag "Be smart and do the right thing" smart)))
1098 (defcustom org-yank-folded-subtrees t
1099 "Non-nil means when yanking subtrees, fold them.
1100 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1101 it starts with a heading and all other headings in it are either children
1102 or siblings, then fold all the subtrees. However, do this only if no
1103 text after the yank would be swallowed into a folded tree by this action."
1104 :group 'org-edit-structure
1105 :type 'boolean)
1107 (defcustom org-yank-adjusted-subtrees nil
1108 "Non-nil means when yanking subtrees, adjust the level.
1109 With this setting, `org-paste-subtree' is used to insert the subtree, see
1110 this function for details."
1111 :group 'org-edit-structure
1112 :type 'boolean)
1114 (defcustom org-M-RET-may-split-line '((default . t))
1115 "Non-nil means M-RET will split the line at the cursor position.
1116 When nil, it will go to the end of the line before making a
1117 new line.
1118 You may also set this option in a different way for different
1119 contexts. Valid contexts are:
1121 headline when creating a new headline
1122 item when creating a new item
1123 table in a table field
1124 default the value to be used for all contexts not explicitly
1125 customized"
1126 :group 'org-structure
1127 :group 'org-table
1128 :type '(choice
1129 (const :tag "Always" t)
1130 (const :tag "Never" nil)
1131 (repeat :greedy t :tag "Individual contexts"
1132 (cons
1133 (choice :tag "Context"
1134 (const headline)
1135 (const item)
1136 (const table)
1137 (const default))
1138 (boolean)))))
1141 (defcustom org-insert-heading-respect-content nil
1142 "Non-nil means insert new headings after the current subtree.
1143 When nil, the new heading is created directly after the current line.
1144 The commands \\[org-insert-heading-respect-content] and
1145 \\[org-insert-todo-heading-respect-content] turn this variable on
1146 for the duration of the command."
1147 :group 'org-structure
1148 :type 'boolean)
1150 (defcustom org-blank-before-new-entry '((heading . auto)
1151 (plain-list-item . auto))
1152 "Should `org-insert-heading' leave a blank line before new heading/item?
1153 The value is an alist, with `heading' and `plain-list-item' as CAR,
1154 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1155 which case Org will look at the surrounding headings/items and try to
1156 make an intelligent decision whether to insert a blank line or not.
1158 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1159 set, the setting here is ignored and no empty line is inserted, to avoid
1160 breaking the list structure."
1161 :group 'org-edit-structure
1162 :type '(list
1163 (cons (const heading)
1164 (choice (const :tag "Never" nil)
1165 (const :tag "Always" t)
1166 (const :tag "Auto" auto)))
1167 (cons (const plain-list-item)
1168 (choice (const :tag "Never" nil)
1169 (const :tag "Always" t)
1170 (const :tag "Auto" auto)))))
1172 (defcustom org-insert-heading-hook nil
1173 "Hook being run after inserting a new heading."
1174 :group 'org-edit-structure
1175 :type 'hook)
1177 (defcustom org-enable-fixed-width-editor t
1178 "Non-nil means lines starting with \":\" are treated as fixed-width.
1179 This currently only means they are never auto-wrapped.
1180 When nil, such lines will be treated like ordinary lines.
1181 See also the QUOTE keyword."
1182 :group 'org-edit-structure
1183 :type 'boolean)
1185 (defcustom org-goto-auto-isearch t
1186 "Non-nil means typing characters in `org-goto' starts incremental search."
1187 :group 'org-edit-structure
1188 :type 'boolean)
1190 (defgroup org-sparse-trees nil
1191 "Options concerning sparse trees in Org-mode."
1192 :tag "Org Sparse Trees"
1193 :group 'org-structure)
1195 (defcustom org-highlight-sparse-tree-matches t
1196 "Non-nil means highlight all matches that define a sparse tree.
1197 The highlights will automatically disappear the next time the buffer is
1198 changed by an edit command."
1199 :group 'org-sparse-trees
1200 :type 'boolean)
1202 (defcustom org-remove-highlights-with-change t
1203 "Non-nil means any change to the buffer will remove temporary highlights.
1204 Such highlights are created by `org-occur' and `org-clock-display'.
1205 When nil, `C-c C-c needs to be used to get rid of the highlights.
1206 The highlights created by `org-preview-latex-fragment' always need
1207 `C-c C-c' to be removed."
1208 :group 'org-sparse-trees
1209 :group 'org-time
1210 :type 'boolean)
1213 (defcustom org-occur-hook '(org-first-headline-recenter)
1214 "Hook that is run after `org-occur' has constructed a sparse tree.
1215 This can be used to recenter the window to show as much of the structure
1216 as possible."
1217 :group 'org-sparse-trees
1218 :type 'hook)
1220 (defgroup org-imenu-and-speedbar nil
1221 "Options concerning imenu and speedbar in Org-mode."
1222 :tag "Org Imenu and Speedbar"
1223 :group 'org-structure)
1225 (defcustom org-imenu-depth 2
1226 "The maximum level for Imenu access to Org-mode headlines.
1227 This also applied for speedbar access."
1228 :group 'org-imenu-and-speedbar
1229 :type 'integer)
1231 (defgroup org-table nil
1232 "Options concerning tables in Org-mode."
1233 :tag "Org Table"
1234 :group 'org)
1236 (defcustom org-enable-table-editor 'optimized
1237 "Non-nil means lines starting with \"|\" are handled by the table editor.
1238 When nil, such lines will be treated like ordinary lines.
1240 When equal to the symbol `optimized', the table editor will be optimized to
1241 do the following:
1242 - Automatic overwrite mode in front of whitespace in table fields.
1243 This makes the structure of the table stay in tact as long as the edited
1244 field does not exceed the column width.
1245 - Minimize the number of realigns. Normally, the table is aligned each time
1246 TAB or RET are pressed to move to another field. With optimization this
1247 happens only if changes to a field might have changed the column width.
1248 Optimization requires replacing the functions `self-insert-command',
1249 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1250 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1251 very good at guessing when a re-align will be necessary, but you can always
1252 force one with \\[org-ctrl-c-ctrl-c].
1254 If you would like to use the optimized version in Org-mode, but the
1255 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1257 This variable can be used to turn on and off the table editor during a session,
1258 but in order to toggle optimization, a restart is required.
1260 See also the variable `org-table-auto-blank-field'."
1261 :group 'org-table
1262 :type '(choice
1263 (const :tag "off" nil)
1264 (const :tag "on" t)
1265 (const :tag "on, optimized" optimized)))
1267 (defcustom org-self-insert-cluster-for-undo t
1268 "Non-nil means cluster self-insert commands for undo when possible.
1269 If this is set, then, like in the Emacs command loop, 20 consecutive
1270 characters will be undone together.
1271 This is configurable, because there is some impact on typing performance."
1272 :group 'org-table
1273 :type 'boolean)
1275 (defcustom org-table-tab-recognizes-table.el t
1276 "Non-nil means TAB will automatically notice a table.el table.
1277 When it sees such a table, it moves point into it and - if necessary -
1278 calls `table-recognize-table'."
1279 :group 'org-table-editing
1280 :type 'boolean)
1282 (defgroup org-link nil
1283 "Options concerning links in Org-mode."
1284 :tag "Org Link"
1285 :group 'org)
1287 (defvar org-link-abbrev-alist-local nil
1288 "Buffer-local version of `org-link-abbrev-alist', which see.
1289 The value of this is taken from the #+LINK lines.")
1290 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1292 (defcustom org-link-abbrev-alist nil
1293 "Alist of link abbreviations.
1294 The car of each element is a string, to be replaced at the start of a link.
1295 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1296 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1298 [[linkkey:tag][description]]
1300 The 'linkkey' must be a word word, starting with a letter, followed
1301 by letters, numbers, '-' or '_'.
1303 If REPLACE is a string, the tag will simply be appended to create the link.
1304 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1305 the placeholder \"%h\" will cause a url-encoded version of the tag to
1306 be inserted at that point (see the function `url-hexify-string').
1308 REPLACE may also be a function that will be called with the tag as the
1309 only argument to create the link, which should be returned as a string.
1311 See the manual for examples."
1312 :group 'org-link
1313 :type '(repeat
1314 (cons
1315 (string :tag "Protocol")
1316 (choice
1317 (string :tag "Format")
1318 (function)))))
1320 (defcustom org-descriptive-links t
1321 "Non-nil means Org will display descriptive links.
1322 E.g. [[http://orgmode.org][Org website]] will be displayed as
1323 \"Org Website\", hiding the link itself and just displaying its
1324 description. When set to `nil', Org will display the full links
1325 literally.
1327 You can interactively set the value of this variable by calling
1328 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1329 :group 'org-link
1330 :type 'boolean)
1332 (defcustom org-link-file-path-type 'adaptive
1333 "How the path name in file links should be stored.
1334 Valid values are:
1336 relative Relative to the current directory, i.e. the directory of the file
1337 into which the link is being inserted.
1338 absolute Absolute path, if possible with ~ for home directory.
1339 noabbrev Absolute path, no abbreviation of home directory.
1340 adaptive Use relative path for files in the current directory and sub-
1341 directories of it. For other files, use an absolute path."
1342 :group 'org-link
1343 :type '(choice
1344 (const relative)
1345 (const absolute)
1346 (const noabbrev)
1347 (const adaptive)))
1349 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1350 "Types of links that should be activated in Org-mode files.
1351 This is a list of symbols, each leading to the activation of a certain link
1352 type. In principle, it does not hurt to turn on most link types - there may
1353 be a small gain when turning off unused link types. The types are:
1355 bracket The recommended [[link][description]] or [[link]] links with hiding.
1356 angle Links in angular brackets that may contain whitespace like
1357 <bbdb:Carsten Dominik>.
1358 plain Plain links in normal text, no whitespace, like http://google.com.
1359 radio Text that is matched by a radio target, see manual for details.
1360 tag Tag settings in a headline (link to tag search).
1361 date Time stamps (link to calendar).
1362 footnote Footnote labels.
1364 Changing this variable requires a restart of Emacs to become effective."
1365 :group 'org-link
1366 :type '(set :greedy t
1367 (const :tag "Double bracket links" bracket)
1368 (const :tag "Angular bracket links" angle)
1369 (const :tag "Plain text links" plain)
1370 (const :tag "Radio target matches" radio)
1371 (const :tag "Tags" tag)
1372 (const :tag "Timestamps" date)
1373 (const :tag "Footnotes" footnote)))
1375 (defcustom org-make-link-description-function nil
1376 "Function to use to generate link descriptions from links.
1377 If nil the link location will be used. This function must take
1378 two parameters; the first is the link and the second the
1379 description `org-insert-link' has generated, and should return the
1380 description to use."
1381 :group 'org-link
1382 :type 'function)
1384 (defgroup org-link-store nil
1385 "Options concerning storing links in Org-mode."
1386 :tag "Org Store Link"
1387 :group 'org-link)
1389 (defcustom org-email-link-description-format "Email %c: %.30s"
1390 "Format of the description part of a link to an email or usenet message.
1391 The following %-escapes will be replaced by corresponding information:
1393 %F full \"From\" field
1394 %f name, taken from \"From\" field, address if no name
1395 %T full \"To\" field
1396 %t first name in \"To\" field, address if no name
1397 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1398 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1399 %s subject
1400 %d date
1401 %m message-id.
1403 You may use normal field width specification between the % and the letter.
1404 This is for example useful to limit the length of the subject.
1406 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1407 :group 'org-link-store
1408 :type 'string)
1410 (defcustom org-from-is-user-regexp
1411 (let (r1 r2)
1412 (when (and user-mail-address (not (string= user-mail-address "")))
1413 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1414 (when (and user-full-name (not (string= user-full-name "")))
1415 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1416 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1417 "Regexp matched against the \"From:\" header of an email or usenet message.
1418 It should match if the message is from the user him/herself."
1419 :group 'org-link-store
1420 :type 'regexp)
1422 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1423 "Non-nil means storing a link to an Org file will use entry IDs.
1425 Note that before this variable is even considered, org-id must be loaded,
1426 so please customize `org-modules' and turn it on.
1428 The variable can have the following values:
1430 t Create an ID if needed to make a link to the current entry.
1432 create-if-interactive
1433 If `org-store-link' is called directly (interactively, as a user
1434 command), do create an ID to support the link. But when doing the
1435 job for remember, only use the ID if it already exists. The
1436 purpose of this setting is to avoid proliferation of unwanted
1437 IDs, just because you happen to be in an Org file when you
1438 call `org-remember' that automatically and preemptively
1439 creates a link. If you do want to get an ID link in a remember
1440 template to an entry not having an ID, create it first by
1441 explicitly creating a link to it, using `C-c C-l' first.
1443 create-if-interactive-and-no-custom-id
1444 Like create-if-interactive, but do not create an ID if there is
1445 a CUSTOM_ID property defined in the entry. This is the default.
1447 use-existing
1448 Use existing ID, do not create one.
1450 nil Never use an ID to make a link, instead link using a text search for
1451 the headline text."
1452 :group 'org-link-store
1453 :type '(choice
1454 (const :tag "Create ID to make link" t)
1455 (const :tag "Create if storing link interactively"
1456 create-if-interactive)
1457 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1458 create-if-interactive-and-no-custom-id)
1459 (const :tag "Only use existing" use-existing)
1460 (const :tag "Do not use ID to create link" nil)))
1462 (defcustom org-context-in-file-links t
1463 "Non-nil means file links from `org-store-link' contain context.
1464 A search string will be added to the file name with :: as separator and
1465 used to find the context when the link is activated by the command
1466 `org-open-at-point'. When this option is t, the entire active region
1467 will be placed in the search string of the file link. If set to a
1468 positive integer, only the first n lines of context will be stored.
1470 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1471 negates this setting for the duration of the command."
1472 :group 'org-link-store
1473 :type '(choice boolean integer))
1475 (defcustom org-keep-stored-link-after-insertion nil
1476 "Non-nil means keep link in list for entire session.
1478 The command `org-store-link' adds a link pointing to the current
1479 location to an internal list. These links accumulate during a session.
1480 The command `org-insert-link' can be used to insert links into any
1481 Org-mode file (offering completion for all stored links). When this
1482 option is nil, every link which has been inserted once using \\[org-insert-link]
1483 will be removed from the list, to make completing the unused links
1484 more efficient."
1485 :group 'org-link-store
1486 :type 'boolean)
1488 (defgroup org-link-follow nil
1489 "Options concerning following links in Org-mode."
1490 :tag "Org Follow Link"
1491 :group 'org-link)
1493 (defcustom org-link-translation-function nil
1494 "Function to translate links with different syntax to Org syntax.
1495 This can be used to translate links created for example by the Planner
1496 or emacs-wiki packages to Org syntax.
1497 The function must accept two parameters, a TYPE containing the link
1498 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1499 which is everything after the link protocol. It should return a cons
1500 with possibly modified values of type and path.
1501 Org contains a function for this, so if you set this variable to
1502 `org-translate-link-from-planner', you should be able follow many
1503 links created by planner."
1504 :group 'org-link-follow
1505 :type 'function)
1507 (defcustom org-follow-link-hook nil
1508 "Hook that is run after a link has been followed."
1509 :group 'org-link-follow
1510 :type 'hook)
1512 (defcustom org-tab-follows-link nil
1513 "Non-nil means on links TAB will follow the link.
1514 Needs to be set before org.el is loaded.
1515 This really should not be used, it does not make sense, and the
1516 implementation is bad."
1517 :group 'org-link-follow
1518 :type 'boolean)
1520 (defcustom org-return-follows-link nil
1521 "Non-nil means on links RET will follow the link."
1522 :group 'org-link-follow
1523 :type 'boolean)
1525 (defcustom org-mouse-1-follows-link
1526 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1527 "Non-nil means mouse-1 on a link will follow the link.
1528 A longer mouse click will still set point. Does not work on XEmacs.
1529 Needs to be set before org.el is loaded."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-mark-ring-length 4
1534 "Number of different positions to be recorded in the ring.
1535 Changing this requires a restart of Emacs to work correctly."
1536 :group 'org-link-follow
1537 :type 'integer)
1539 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1540 "Non-nil means internal links in Org files must exactly match a headline.
1541 When nil, the link search tries to match a phrase with all words
1542 in the search text."
1543 :group 'org-link-follow
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Use fuzzy text search" nil)
1547 (const :tag "Match only exact headline" t)
1548 (const :tag "Match exact headline or query to create it"
1549 query-to-create)))
1551 (defcustom org-link-frame-setup
1552 '((vm . vm-visit-folder-other-frame)
1553 (vm-imap . vm-visit-imap-folder-other-frame)
1554 (gnus . org-gnus-no-new-news)
1555 (file . find-file-other-window)
1556 (wl . wl-other-frame))
1557 "Setup the frame configuration for following links.
1558 When following a link with Emacs, it may often be useful to display
1559 this link in another window or frame. This variable can be used to
1560 set this up for the different types of links.
1561 For VM, use any of
1562 `vm-visit-folder'
1563 `vm-visit-folder-other-window'
1564 `vm-visit-folder-other-frame'
1565 For Gnus, use any of
1566 `gnus'
1567 `gnus-other-frame'
1568 `org-gnus-no-new-news'
1569 For FILE, use any of
1570 `find-file'
1571 `find-file-other-window'
1572 `find-file-other-frame'
1573 For Wanderlust use any of
1574 `wl'
1575 `wl-other-frame'
1576 For the calendar, use the variable `calendar-setup'.
1577 For BBDB, it is currently only possible to display the matches in
1578 another window."
1579 :group 'org-link-follow
1580 :type '(list
1581 (cons (const vm)
1582 (choice
1583 (const vm-visit-folder)
1584 (const vm-visit-folder-other-window)
1585 (const vm-visit-folder-other-frame)))
1586 (cons (const gnus)
1587 (choice
1588 (const gnus)
1589 (const gnus-other-frame)
1590 (const org-gnus-no-new-news)))
1591 (cons (const file)
1592 (choice
1593 (const find-file)
1594 (const find-file-other-window)
1595 (const find-file-other-frame)))
1596 (cons (const wl)
1597 (choice
1598 (const wl)
1599 (const wl-other-frame)))))
1601 (defcustom org-display-internal-link-with-indirect-buffer nil
1602 "Non-nil means use indirect buffer to display infile links.
1603 Activating internal links (from one location in a file to another location
1604 in the same file) normally just jumps to the location. When the link is
1605 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1606 is displayed in
1607 another window. When this option is set, the other window actually displays
1608 an indirect buffer clone of the current buffer, to avoid any visibility
1609 changes to the current buffer."
1610 :group 'org-link-follow
1611 :type 'boolean)
1613 (defcustom org-open-non-existing-files nil
1614 "Non-nil means `org-open-file' will open non-existing files.
1615 When nil, an error will be generated.
1616 This variable applies only to external applications because they
1617 might choke on non-existing files. If the link is to a file that
1618 will be opened in Emacs, the variable is ignored."
1619 :group 'org-link-follow
1620 :type 'boolean)
1622 (defcustom org-open-directory-means-index-dot-org nil
1623 "Non-nil means a link to a directory really means to index.org.
1624 When nil, following a directory link will run dired or open a finder/explorer
1625 window on that directory."
1626 :group 'org-link-follow
1627 :type 'boolean)
1629 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1630 "Function and arguments to call for following mailto links.
1631 This is a list with the first element being a Lisp function, and the
1632 remaining elements being arguments to the function. In string arguments,
1633 %a will be replaced by the address, and %s will be replaced by the subject
1634 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1635 :group 'org-link-follow
1636 :type '(choice
1637 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1638 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1639 (const :tag "message-mail" (message-mail "%a" "%s"))
1640 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1642 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1643 "Non-nil means ask for confirmation before executing shell links.
1644 Shell links can be dangerous: just think about a link
1646 [[shell:rm -rf ~/*][Google Search]]
1648 This link would show up in your Org-mode document as \"Google Search\",
1649 but really it would remove your entire home directory.
1650 Therefore we advise against setting this variable to nil.
1651 Just change it to `y-or-n-p' if you want to confirm with a
1652 single keystroke rather than having to type \"yes\"."
1653 :group 'org-link-follow
1654 :type '(choice
1655 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1656 (const :tag "with y-or-n (faster)" y-or-n-p)
1657 (const :tag "no confirmation (dangerous)" nil)))
1658 (put 'org-confirm-shell-link-function
1659 'safe-local-variable
1660 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1662 (defcustom org-confirm-shell-link-not-regexp ""
1663 "A regexp to skip confirmation for shell links."
1664 :group 'org-link-follow
1665 :version "24.1"
1666 :type 'regexp)
1668 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1670 Elisp links can be dangerous: just think about a link
1672 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1682 (const :tag "with y-or-n (faster)" y-or-n-p)
1683 (const :tag "no confirmation (dangerous)" nil)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1688 (defcustom org-confirm-elisp-link-not-regexp ""
1689 "A regexp to skip confirmation for Elisp links."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type 'regexp)
1694 (defconst org-file-apps-defaults-gnu
1695 '((remote . emacs)
1696 (system . mailcap)
1697 (t . mailcap))
1698 "Default file applications on a UNIX or GNU/Linux system.
1699 See `org-file-apps'.")
1701 (defconst org-file-apps-defaults-macosx
1702 '((remote . emacs)
1703 (t . "open %s")
1704 (system . "open %s")
1705 ("ps.gz" . "gv %s")
1706 ("eps.gz" . "gv %s")
1707 ("dvi" . "xdvi %s")
1708 ("fig" . "xfig %s"))
1709 "Default file applications on a MacOS X system.
1710 The system \"open\" is known as a default, but we use X11 applications
1711 for some files for which the OS does not have a good default.
1712 See `org-file-apps'.")
1714 (defconst org-file-apps-defaults-windowsnt
1715 (list
1716 '(remote . emacs)
1717 (cons t
1718 (list (if (featurep 'xemacs)
1719 'mswindows-shell-execute
1720 'w32-shell-execute)
1721 "open" 'file))
1722 (cons 'system
1723 (list (if (featurep 'xemacs)
1724 'mswindows-shell-execute
1725 'w32-shell-execute)
1726 "open" 'file)))
1727 "Default file applications on a Windows NT system.
1728 The system \"open\" is used for most files.
1729 See `org-file-apps'.")
1731 (defcustom org-file-apps
1733 (auto-mode . emacs)
1734 ("\\.mm\\'" . default)
1735 ("\\.x?html?\\'" . default)
1736 ("\\.pdf\\'" . default)
1738 "External applications for opening `file:path' items in a document.
1739 Org-mode uses system defaults for different file types, but
1740 you can use this variable to set the application for a given file
1741 extension. The entries in this list are cons cells where the car identifies
1742 files and the cdr the corresponding command. Possible values for the
1743 file identifier are
1744 \"string\" A string as a file identifier can be interpreted in different
1745 ways, depending on its contents:
1747 - Alphanumeric characters only:
1748 Match links with this file extension.
1749 Example: (\"pdf\" . \"evince %s\")
1750 to open PDFs with evince.
1752 - Regular expression: Match links where the
1753 filename matches the regexp. If you want to
1754 use groups here, use shy groups.
1756 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1757 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1758 to open *.html and *.xhtml with firefox.
1760 - Regular expression which contains (non-shy) groups:
1761 Match links where the whole link, including \"::\", and
1762 anything after that, matches the regexp.
1763 In a custom command string, %1, %2, etc. are replaced with
1764 the parts of the link that were matched by the groups.
1765 For backwards compatibility, if a command string is given
1766 that does not use any of the group matches, this case is
1767 handled identically to the second one (i.e. match against
1768 file name only).
1769 In a custom lisp form, you can access the group matches with
1770 (match-string n link).
1772 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1773 to open [[file:document.pdf::5]] with evince at page 5.
1775 `directory' Matches a directory
1776 `remote' Matches a remote file, accessible through tramp or efs.
1777 Remote files most likely should be visited through Emacs
1778 because external applications cannot handle such paths.
1779 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1780 so all files Emacs knows how to handle. Using this with
1781 command `emacs' will open most files in Emacs. Beware that this
1782 will also open html files inside Emacs, unless you add
1783 (\"html\" . default) to the list as well.
1784 t Default for files not matched by any of the other options.
1785 `system' The system command to open files, like `open' on Windows
1786 and Mac OS X, and mailcap under GNU/Linux. This is the command
1787 that will be selected if you call `C-c C-o' with a double
1788 \\[universal-argument] \\[universal-argument] prefix.
1790 Possible values for the command are:
1791 `emacs' The file will be visited by the current Emacs process.
1792 `default' Use the default application for this file type, which is the
1793 association for t in the list, most likely in the system-specific
1794 part.
1795 This can be used to overrule an unwanted setting in the
1796 system-specific variable.
1797 `system' Use the system command for opening files, like \"open\".
1798 This command is specified by the entry whose car is `system'.
1799 Most likely, the system-specific version of this variable
1800 does define this command, but you can overrule/replace it
1801 here.
1802 string A command to be executed by a shell; %s will be replaced
1803 by the path to the file.
1804 sexp A Lisp form which will be evaluated. The file path will
1805 be available in the Lisp variable `file'.
1806 For more examples, see the system specific constants
1807 `org-file-apps-defaults-macosx'
1808 `org-file-apps-defaults-windowsnt'
1809 `org-file-apps-defaults-gnu'."
1810 :group 'org-link-follow
1811 :type '(repeat
1812 (cons (choice :value ""
1813 (string :tag "Extension")
1814 (const :tag "System command to open files" system)
1815 (const :tag "Default for unrecognized files" t)
1816 (const :tag "Remote file" remote)
1817 (const :tag "Links to a directory" directory)
1818 (const :tag "Any files that have Emacs modes"
1819 auto-mode))
1820 (choice :value ""
1821 (const :tag "Visit with Emacs" emacs)
1822 (const :tag "Use default" default)
1823 (const :tag "Use the system command" system)
1824 (string :tag "Command")
1825 (sexp :tag "Lisp form")))))
1829 (defgroup org-refile nil
1830 "Options concerning refiling entries in Org-mode."
1831 :tag "Org Refile"
1832 :group 'org)
1834 (defcustom org-directory "~/org"
1835 "Directory with org files.
1836 This is just a default location to look for Org files. There is no need
1837 at all to put your files into this directory. It is only used in the
1838 following situations:
1840 1. When a remember template specifies a target file that is not an
1841 absolute path. The path will then be interpreted relative to
1842 `org-directory'
1843 2. When a remember note is filed away in an interactive way (when exiting the
1844 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1845 with `org-directory' as the default path."
1846 :group 'org-refile
1847 :group 'org-remember
1848 :type 'directory)
1850 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1851 "Default target for storing notes.
1852 Used as a fall back file for org-remember.el and org-capture.el, for
1853 templates that do not specify a target file."
1854 :group 'org-refile
1855 :group 'org-remember
1856 :type '(choice
1857 (const :tag "Default from remember-data-file" nil)
1858 file))
1860 (defcustom org-goto-interface 'outline
1861 "The default interface to be used for `org-goto'.
1862 Allowed values are:
1863 outline The interface shows an outline of the relevant file
1864 and the correct heading is found by moving through
1865 the outline or by searching with incremental search.
1866 outline-path-completion Headlines in the current buffer are offered via
1867 completion. This is the interface also used by
1868 the refile command."
1869 :group 'org-refile
1870 :type '(choice
1871 (const :tag "Outline" outline)
1872 (const :tag "Outline-path-completion" outline-path-completion)))
1874 (defcustom org-goto-max-level 5
1875 "Maximum target level when running `org-goto' with refile interface."
1876 :group 'org-refile
1877 :type 'integer)
1879 (defcustom org-reverse-note-order nil
1880 "Non-nil means store new notes at the beginning of a file or entry.
1881 When nil, new notes will be filed to the end of a file or entry.
1882 This can also be a list with cons cells of regular expressions that
1883 are matched against file names, and values."
1884 :group 'org-remember
1885 :group 'org-refile
1886 :type '(choice
1887 (const :tag "Reverse always" t)
1888 (const :tag "Reverse never" nil)
1889 (repeat :tag "By file name regexp"
1890 (cons regexp boolean))))
1892 (defcustom org-log-refile nil
1893 "Information to record when a task is refiled.
1895 Possible values are:
1897 nil Don't add anything
1898 time Add a time stamp to the task
1899 note Prompt for a note and add it with template `org-log-note-headings'
1901 This option can also be set with on a per-file-basis with
1903 #+STARTUP: nologrefile
1904 #+STARTUP: logrefile
1905 #+STARTUP: lognoterefile
1907 You can have local logging settings for a subtree by setting the LOGGING
1908 property to one or more of these keywords.
1910 When bulk-refiling from the agenda, the value `note' is forbidden and
1911 will temporarily be changed to `time'."
1912 :group 'org-refile
1913 :group 'org-progress
1914 :version "24.1"
1915 :type '(choice
1916 (const :tag "No logging" nil)
1917 (const :tag "Record timestamp" time)
1918 (const :tag "Record timestamp with note." note)))
1920 (defcustom org-refile-targets nil
1921 "Targets for refiling entries with \\[org-refile].
1922 This is a list of cons cells. Each cell contains:
1923 - a specification of the files to be considered, either a list of files,
1924 or a symbol whose function or variable value will be used to retrieve
1925 a file name or a list of file names. If you use `org-agenda-files' for
1926 that, all agenda files will be scanned for targets. Nil means consider
1927 headings in the current buffer.
1928 - A specification of how to find candidate refile targets. This may be
1929 any of:
1930 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1931 This tag has to be present in all target headlines, inheritance will
1932 not be considered.
1933 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1934 todo keyword.
1935 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1936 headlines that are refiling targets.
1937 - a cons cell (:level . N). Any headline of level N is considered a target.
1938 Note that, when `org-odd-levels-only' is set, level corresponds to
1939 order in hierarchy, not to the number of stars.
1940 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1941 Note that, when `org-odd-levels-only' is set, level corresponds to
1942 order in hierarchy, not to the number of stars.
1944 Each element of this list generates a set of possible targets.
1945 The union of these sets is presented (with completion) to
1946 the user by `org-refile'.
1948 You can set the variable `org-refile-target-verify-function' to a function
1949 to verify each headline found by the simple criteria above.
1951 When this variable is nil, all top-level headlines in the current buffer
1952 are used, equivalent to the value `((nil . (:level . 1))'."
1953 :group 'org-refile
1954 :type '(repeat
1955 (cons
1956 (choice :value org-agenda-files
1957 (const :tag "All agenda files" org-agenda-files)
1958 (const :tag "Current buffer" nil)
1959 (function) (variable) (file))
1960 (choice :tag "Identify target headline by"
1961 (cons :tag "Specific tag" (const :value :tag) (string))
1962 (cons :tag "TODO keyword" (const :value :todo) (string))
1963 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1964 (cons :tag "Level number" (const :value :level) (integer))
1965 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1967 (defcustom org-refile-target-verify-function nil
1968 "Function to verify if the headline at point should be a refile target.
1969 The function will be called without arguments, with point at the
1970 beginning of the headline. It should return t and leave point
1971 where it is if the headline is a valid target for refiling.
1973 If the target should not be selected, the function must return nil.
1974 In addition to this, it may move point to a place from where the search
1975 should be continued. For example, the function may decide that the entire
1976 subtree of the current entry should be excluded and move point to the end
1977 of the subtree."
1978 :group 'org-refile
1979 :type 'function)
1981 (defcustom org-refile-use-cache nil
1982 "Non-nil means cache refile targets to speed up the process.
1983 The cache for a particular file will be updated automatically when
1984 the buffer has been killed, or when any of the marker used for flagging
1985 refile targets no longer points at a live buffer.
1986 If you have added new entries to a buffer that might themselves be targets,
1987 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1988 find that easier, `C-u C-u C-u C-c C-w'."
1989 :group 'org-refile
1990 :version "24.1"
1991 :type 'boolean)
1993 (defcustom org-refile-use-outline-path nil
1994 "Non-nil means provide refile targets as paths.
1995 So a level 3 headline will be available as level1/level2/level3.
1997 When the value is `file', also include the file name (without directory)
1998 into the path. In this case, you can also stop the completion after
1999 the file name, to get entries inserted as top level in the file.
2001 When `full-file-path', include the full file path."
2002 :group 'org-refile
2003 :type '(choice
2004 (const :tag "Not" nil)
2005 (const :tag "Yes" t)
2006 (const :tag "Start with file name" file)
2007 (const :tag "Start with full file path" full-file-path)))
2009 (defcustom org-outline-path-complete-in-steps t
2010 "Non-nil means complete the outline path in hierarchical steps.
2011 When Org-mode uses the refile interface to select an outline path
2012 \(see variable `org-refile-use-outline-path'), the completion of
2013 the path can be done is a single go, or if can be done in steps down
2014 the headline hierarchy. Going in steps is probably the best if you
2015 do not use a special completion package like `ido' or `icicles'.
2016 However, when using these packages, going in one step can be very
2017 fast, while still showing the whole path to the entry."
2018 :group 'org-refile
2019 :type 'boolean)
2021 (defcustom org-refile-allow-creating-parent-nodes nil
2022 "Non-nil means allow to create new nodes as refile targets.
2023 New nodes are then created by adding \"/new node name\" to the completion
2024 of an existing node. When the value of this variable is `confirm',
2025 new node creation must be confirmed by the user (recommended)
2026 When nil, the completion must match an existing entry.
2028 Note that, if the new heading is not seen by the criteria
2029 listed in `org-refile-targets', multiple instances of the same
2030 heading would be created by trying again to file under the new
2031 heading."
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Never" nil)
2035 (const :tag "Always" t)
2036 (const :tag "Prompt for confirmation" confirm)))
2038 (defcustom org-refile-active-region-within-subtree nil
2039 "Non-nil means also refile active region within a subtree.
2041 By default `org-refile' doesn't allow refiling regions if they
2042 don't contain a set of subtrees, but it might be convenient to
2043 do so sometimes: in that case, the first line of the region is
2044 converted to a headline before refiling."
2045 :group 'org-refile
2046 :version "24.1"
2047 :type 'boolean)
2049 (defgroup org-todo nil
2050 "Options concerning TODO items in Org-mode."
2051 :tag "Org TODO"
2052 :group 'org)
2054 (defgroup org-progress nil
2055 "Options concerning Progress logging in Org-mode."
2056 :tag "Org Progress"
2057 :group 'org-time)
2059 (defvar org-todo-interpretation-widgets
2060 '((:tag "Sequence (cycling hits every state)" sequence)
2061 (:tag "Type (cycling directly to DONE)" type))
2062 "The available interpretation symbols for customizing `org-todo-keywords'.
2063 Interested libraries should add to this list.")
2065 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2066 "List of TODO entry keyword sequences and their interpretation.
2067 \\<org-mode-map>This is a list of sequences.
2069 Each sequence starts with a symbol, either `sequence' or `type',
2070 indicating if the keywords should be interpreted as a sequence of
2071 action steps, or as different types of TODO items. The first
2072 keywords are states requiring action - these states will select a headline
2073 for inclusion into the global TODO list Org-mode produces. If one of
2074 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2075 signify that no further action is necessary. If \"|\" is not found,
2076 the last keyword is treated as the only DONE state of the sequence.
2078 The command \\[org-todo] cycles an entry through these states, and one
2079 additional state where no keyword is present. For details about this
2080 cycling, see the manual.
2082 TODO keywords and interpretation can also be set on a per-file basis with
2083 the special #+SEQ_TODO and #+TYP_TODO lines.
2085 Each keyword can optionally specify a character for fast state selection
2086 \(in combination with the variable `org-use-fast-todo-selection')
2087 and specifiers for state change logging, using the same syntax
2088 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2089 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2090 indicates to record a time stamp each time this state is selected.
2092 Each keyword may also specify if a timestamp or a note should be
2093 recorded when entering or leaving the state, by adding additional
2094 characters in the parenthesis after the keyword. This looks like this:
2095 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2096 record only the time of the state change. With X and Y being either
2097 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2098 Y when leaving the state if and only if the *target* state does not
2099 define X. You may omit any of the fast-selection key or X or /Y,
2100 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2102 For backward compatibility, this variable may also be just a list
2103 of keywords - in this case the interpretation (sequence or type) will be
2104 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2105 :group 'org-todo
2106 :group 'org-keywords
2107 :type '(choice
2108 (repeat :tag "Old syntax, just keywords"
2109 (string :tag "Keyword"))
2110 (repeat :tag "New syntax"
2111 (cons
2112 (choice
2113 :tag "Interpretation"
2114 ;;Quick and dirty way to see
2115 ;;`org-todo-interpretations'. This takes the
2116 ;;place of item arguments
2117 :convert-widget
2118 (lambda (widget)
2119 (widget-put widget
2120 :args (mapcar
2121 #'(lambda (x)
2122 (widget-convert
2123 (cons 'const x)))
2124 org-todo-interpretation-widgets))
2125 widget))
2126 (repeat
2127 (string :tag "Keyword"))))))
2129 (defvar org-todo-keywords-1 nil
2130 "All TODO and DONE keywords active in a buffer.")
2131 (make-variable-buffer-local 'org-todo-keywords-1)
2132 (defvar org-todo-keywords-for-agenda nil)
2133 (defvar org-done-keywords-for-agenda nil)
2134 (defvar org-drawers-for-agenda nil)
2135 (defvar org-todo-keyword-alist-for-agenda nil)
2136 (defvar org-tag-alist-for-agenda nil)
2137 (defvar org-agenda-contributing-files nil)
2138 (defvar org-not-done-keywords nil)
2139 (make-variable-buffer-local 'org-not-done-keywords)
2140 (defvar org-done-keywords nil)
2141 (make-variable-buffer-local 'org-done-keywords)
2142 (defvar org-todo-heads nil)
2143 (make-variable-buffer-local 'org-todo-heads)
2144 (defvar org-todo-sets nil)
2145 (make-variable-buffer-local 'org-todo-sets)
2146 (defvar org-todo-log-states nil)
2147 (make-variable-buffer-local 'org-todo-log-states)
2148 (defvar org-todo-kwd-alist nil)
2149 (make-variable-buffer-local 'org-todo-kwd-alist)
2150 (defvar org-todo-key-alist nil)
2151 (make-variable-buffer-local 'org-todo-key-alist)
2152 (defvar org-todo-key-trigger nil)
2153 (make-variable-buffer-local 'org-todo-key-trigger)
2155 (defcustom org-todo-interpretation 'sequence
2156 "Controls how TODO keywords are interpreted.
2157 This variable is in principle obsolete and is only used for
2158 backward compatibility, if the interpretation of todo keywords is
2159 not given already in `org-todo-keywords'. See that variable for
2160 more information."
2161 :group 'org-todo
2162 :group 'org-keywords
2163 :type '(choice (const sequence)
2164 (const type)))
2166 (defcustom org-use-fast-todo-selection t
2167 "Non-nil means use the fast todo selection scheme with C-c C-t.
2168 This variable describes if and under what circumstances the cycling
2169 mechanism for TODO keywords will be replaced by a single-key, direct
2170 selection scheme.
2172 When nil, fast selection is never used.
2174 When the symbol `prefix', it will be used when `org-todo' is called with
2175 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2176 in an agenda buffer.
2178 When t, fast selection is used by default. In this case, the prefix
2179 argument forces cycling instead.
2181 In all cases, the special interface is only used if access keys have actually
2182 been assigned by the user, i.e. if keywords in the configuration are followed
2183 by a letter in parenthesis, like TODO(t)."
2184 :group 'org-todo
2185 :type '(choice
2186 (const :tag "Never" nil)
2187 (const :tag "By default" t)
2188 (const :tag "Only with C-u C-c C-t" prefix)))
2190 (defcustom org-provide-todo-statistics t
2191 "Non-nil means update todo statistics after insert and toggle.
2192 ALL-HEADLINES means update todo statistics by including headlines
2193 with no TODO keyword as well, counting them as not done.
2194 A list of TODO keywords means the same, but skip keywords that are
2195 not in this list.
2197 When this is set, todo statistics is updated in the parent of the
2198 current entry each time a todo state is changed."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Yes, only for TODO entries" t)
2202 (const :tag "Yes, including all entries" 'all-headlines)
2203 (repeat :tag "Yes, for TODOs in this list"
2204 (string :tag "TODO keyword"))
2205 (other :tag "No TODO statistics" nil)))
2207 (defcustom org-hierarchical-todo-statistics t
2208 "Non-nil means TODO statistics covers just direct children.
2209 When nil, all entries in the subtree are considered.
2210 This has only an effect if `org-provide-todo-statistics' is set.
2211 To set this to nil for only a single subtree, use a COOKIE_DATA
2212 property and include the word \"recursive\" into the value."
2213 :group 'org-todo
2214 :type 'boolean)
2216 (defcustom org-after-todo-state-change-hook nil
2217 "Hook which is run after the state of a TODO item was changed.
2218 The new state (a string with a TODO keyword, or nil) is available in the
2219 Lisp variable `org-state'."
2220 :group 'org-todo
2221 :type 'hook)
2223 (defvar org-blocker-hook nil
2224 "Hook for functions that are allowed to block a state change.
2226 Each function gets as its single argument a property list, see
2227 `org-trigger-hook' for more information about this list.
2229 If any of the functions in this hook returns nil, the state change
2230 is blocked.")
2232 (defvar org-trigger-hook nil
2233 "Hook for functions that are triggered by a state change.
2235 Each function gets as its single argument a property list with at least
2236 the following elements:
2238 (:type type-of-change :position pos-at-entry-start
2239 :from old-state :to new-state)
2241 Depending on the type, more properties may be present.
2243 This mechanism is currently implemented for:
2245 TODO state changes
2246 ------------------
2247 :type todo-state-change
2248 :from previous state (keyword as a string), or nil, or a symbol
2249 'todo' or 'done', to indicate the general type of state.
2250 :to new state, like in :from")
2252 (defcustom org-enforce-todo-dependencies nil
2253 "Non-nil means undone TODO entries will block switching the parent to DONE.
2254 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2255 be blocked if any prior sibling is not yet done.
2256 Finally, if the parent is blocked because of ordered siblings of its own,
2257 the child will also be blocked."
2258 :set (lambda (var val)
2259 (set var val)
2260 (if val
2261 (add-hook 'org-blocker-hook
2262 'org-block-todo-from-children-or-siblings-or-parent)
2263 (remove-hook 'org-blocker-hook
2264 'org-block-todo-from-children-or-siblings-or-parent)))
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-enforce-todo-checkbox-dependencies nil
2269 "Non-nil means unchecked boxes will block switching the parent to DONE.
2270 When this is nil, checkboxes have no influence on switching TODO states.
2271 When non-nil, you first need to check off all check boxes before the TODO
2272 entry can be switched to DONE.
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-checkboxes)
2281 (remove-hook 'org-blocker-hook
2282 'org-block-todo-from-checkboxes)))
2283 :group 'org-todo
2284 :type 'boolean)
2286 (defcustom org-treat-insert-todo-heading-as-state-change nil
2287 "Non-nil means inserting a TODO heading is treated as state change.
2288 So when the command \\[org-insert-todo-heading] is used, state change
2289 logging will apply if appropriate. When nil, the new TODO item will
2290 be inserted directly, and no logging will take place."
2291 :group 'org-todo
2292 :type 'boolean)
2294 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2295 "Non-nil means switching TODO states with S-cursor counts as state change.
2296 This is the default behavior. However, setting this to nil allows a
2297 convenient way to select a TODO state and bypass any logging associated
2298 with that."
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-todo-state-tags-triggers nil
2303 "Tag changes that should be triggered by TODO state changes.
2304 This is a list. Each entry is
2306 (state-change (tag . flag) .......)
2308 State-change can be a string with a state, and empty string to indicate the
2309 state that has no TODO keyword, or it can be one of the symbols `todo'
2310 or `done', meaning any not-done or done state, respectively."
2311 :group 'org-todo
2312 :group 'org-tags
2313 :type '(repeat
2314 (cons (choice :tag "When changing to"
2315 (const :tag "Not-done state" todo)
2316 (const :tag "Done state" done)
2317 (string :tag "State"))
2318 (repeat
2319 (cons :tag "Tag action"
2320 (string :tag "Tag")
2321 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2323 (defcustom org-log-done nil
2324 "Information to record when a task moves to the DONE state.
2326 Possible values are:
2328 nil Don't add anything, just change the keyword
2329 time Add a time stamp to the task
2330 note Prompt for a note and add it with template `org-log-note-headings'
2332 This option can also be set with on a per-file-basis with
2334 #+STARTUP: nologdone
2335 #+STARTUP: logdone
2336 #+STARTUP: lognotedone
2338 You can have local logging settings for a subtree by setting the LOGGING
2339 property to one or more of these keywords."
2340 :group 'org-todo
2341 :group 'org-progress
2342 :type '(choice
2343 (const :tag "No logging" nil)
2344 (const :tag "Record CLOSED timestamp" time)
2345 (const :tag "Record CLOSED timestamp with note." note)))
2347 ;; Normalize old uses of org-log-done.
2348 (cond
2349 ((eq org-log-done t) (setq org-log-done 'time))
2350 ((and (listp org-log-done) (memq 'done org-log-done))
2351 (setq org-log-done 'note)))
2353 (defcustom org-log-reschedule nil
2354 "Information to record when the scheduling date of a tasks is modified.
2356 Possible values are:
2358 nil Don't add anything, just change the date
2359 time Add a time stamp to the task
2360 note Prompt for a note and add it with template `org-log-note-headings'
2362 This option can also be set with on a per-file-basis with
2364 #+STARTUP: nologreschedule
2365 #+STARTUP: logreschedule
2366 #+STARTUP: lognotereschedule"
2367 :group 'org-todo
2368 :group 'org-progress
2369 :type '(choice
2370 (const :tag "No logging" nil)
2371 (const :tag "Record timestamp" time)
2372 (const :tag "Record timestamp with note." note)))
2374 (defcustom org-log-redeadline nil
2375 "Information to record when the deadline date of a tasks is modified.
2377 Possible values are:
2379 nil Don't add anything, just change the date
2380 time Add a time stamp to the task
2381 note Prompt for a note and add it with template `org-log-note-headings'
2383 This option can also be set with on a per-file-basis with
2385 #+STARTUP: nologredeadline
2386 #+STARTUP: logredeadline
2387 #+STARTUP: lognoteredeadline
2389 You can have local logging settings for a subtree by setting the LOGGING
2390 property to one or more of these keywords."
2391 :group 'org-todo
2392 :group 'org-progress
2393 :type '(choice
2394 (const :tag "No logging" nil)
2395 (const :tag "Record timestamp" time)
2396 (const :tag "Record timestamp with note." note)))
2398 (defcustom org-log-note-clock-out nil
2399 "Non-nil means record a note when clocking out of an item.
2400 This can also be configured on a per-file basis by adding one of
2401 the following lines anywhere in the buffer:
2403 #+STARTUP: lognoteclock-out
2404 #+STARTUP: nolognoteclock-out"
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type 'boolean)
2409 (defcustom org-log-done-with-time t
2410 "Non-nil means the CLOSED time stamp will contain date and time.
2411 When nil, only the date will be recorded."
2412 :group 'org-progress
2413 :type 'boolean)
2415 (defcustom org-log-note-headings
2416 '((done . "CLOSING NOTE %t")
2417 (state . "State %-12s from %-12S %t")
2418 (note . "Note taken on %t")
2419 (reschedule . "Rescheduled from %S on %t")
2420 (delschedule . "Not scheduled, was %S on %t")
2421 (redeadline . "New deadline from %S on %t")
2422 (deldeadline . "Removed deadline, was %S on %t")
2423 (refile . "Refiled on %t")
2424 (clock-out . ""))
2425 "Headings for notes added to entries.
2426 The value is an alist, with the car being a symbol indicating the note
2427 context, and the cdr is the heading to be used. The heading may also be the
2428 empty string.
2429 %t in the heading will be replaced by a time stamp.
2430 %T will be an active time stamp instead the default inactive one
2431 %d will be replaced by a short-format time stamp.
2432 %D will be replaced by an active short-format time stamp.
2433 %s will be replaced by the new TODO state, in double quotes.
2434 %S will be replaced by the old TODO state, in double quotes.
2435 %u will be replaced by the user name.
2436 %U will be replaced by the full user name.
2438 In fact, it is not a good idea to change the `state' entry, because
2439 agenda log mode depends on the format of these entries."
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type '(list :greedy t
2443 (cons (const :tag "Heading when closing an item" done) string)
2444 (cons (const :tag
2445 "Heading when changing todo state (todo sequence only)"
2446 state) string)
2447 (cons (const :tag "Heading when just taking a note" note) string)
2448 (cons (const :tag "Heading when clocking out" clock-out) string)
2449 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2450 (cons (const :tag "Heading when rescheduling" reschedule) string)
2451 (cons (const :tag "Heading when changing deadline" redeadline) string)
2452 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2453 (cons (const :tag "Heading when refiling" refile) string)))
2455 (unless (assq 'note org-log-note-headings)
2456 (push '(note . "%t") org-log-note-headings))
2458 (defcustom org-log-into-drawer nil
2459 "Non-nil means insert state change notes and time stamps into a drawer.
2460 When nil, state changes notes will be inserted after the headline and
2461 any scheduling and clock lines, but not inside a drawer.
2463 The value of this variable should be the name of the drawer to use.
2464 LOGBOOK is proposed as the default drawer for this purpose, you can
2465 also set this to a string to define the drawer of your choice.
2467 A value of t is also allowed, representing \"LOGBOOK\".
2469 If this variable is set, `org-log-state-notes-insert-after-drawers'
2470 will be ignored.
2472 You can set the property LOG_INTO_DRAWER to overrule this setting for
2473 a subtree."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(choice
2477 (const :tag "Not into a drawer" nil)
2478 (const :tag "LOGBOOK" t)
2479 (string :tag "Other")))
2481 (if (fboundp 'defvaralias)
2482 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2484 (defun org-log-into-drawer ()
2485 "Return the value of `org-log-into-drawer', but let properties overrule.
2486 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2487 used instead of the default value."
2488 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2489 (cond
2490 ((or (not p) (equal p "nil")) org-log-into-drawer)
2491 ((equal p "t") "LOGBOOK")
2492 (t p))))
2494 (defcustom org-log-state-notes-insert-after-drawers nil
2495 "Non-nil means insert state change notes after any drawers in entry.
2496 Only the drawers that *immediately* follow the headline and the
2497 deadline/scheduled line are skipped.
2498 When nil, insert notes right after the heading and perhaps the line
2499 with deadline/scheduling if present.
2501 This variable will have no effect if `org-log-into-drawer' is
2502 set."
2503 :group 'org-todo
2504 :group 'org-progress
2505 :type 'boolean)
2507 (defcustom org-log-states-order-reversed t
2508 "Non-nil means the latest state note will be directly after heading.
2509 When nil, the state change notes will be ordered according to time."
2510 :group 'org-todo
2511 :group 'org-progress
2512 :type 'boolean)
2514 (defcustom org-todo-repeat-to-state nil
2515 "The TODO state to which a repeater should return the repeating task.
2516 By default this is the first task in a TODO sequence, or the previous state
2517 in a TODO_TYP set. But you can specify another task here.
2518 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2519 :group 'org-todo
2520 :version "24.1"
2521 :type '(choice (const :tag "Head of sequence" nil)
2522 (string :tag "Specific state")))
2524 (defcustom org-log-repeat 'time
2525 "Non-nil means record moving through the DONE state when triggering repeat.
2526 An auto-repeating task is immediately switched back to TODO when
2527 marked DONE. If you are not logging state changes (by adding \"@\"
2528 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2529 record a closing note, there will be no record of the task moving
2530 through DONE. This variable forces taking a note anyway.
2532 nil Don't force a record
2533 time Record a time stamp
2534 note Record a note
2536 This option can also be set with on a per-file-basis with
2538 #+STARTUP: logrepeat
2539 #+STARTUP: lognoterepeat
2540 #+STARTUP: nologrepeat
2542 You can have local logging settings for a subtree by setting the LOGGING
2543 property to one or more of these keywords."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type '(choice
2547 (const :tag "Don't force a record" nil)
2548 (const :tag "Force recording the DONE state" time)
2549 (const :tag "Force recording a note with the DONE state" note)))
2552 (defgroup org-priorities nil
2553 "Priorities in Org-mode."
2554 :tag "Org Priorities"
2555 :group 'org-todo)
2557 (defcustom org-enable-priority-commands t
2558 "Non-nil means priority commands are active.
2559 When nil, these commands will be disabled, so that you never accidentally
2560 set a priority."
2561 :group 'org-priorities
2562 :type 'boolean)
2564 (defcustom org-highest-priority ?A
2565 "The highest priority of TODO items. A character like ?A, ?B etc.
2566 Must have a smaller ASCII number than `org-lowest-priority'."
2567 :group 'org-priorities
2568 :type 'character)
2570 (defcustom org-lowest-priority ?C
2571 "The lowest priority of TODO items. A character like ?A, ?B etc.
2572 Must have a larger ASCII number than `org-highest-priority'."
2573 :group 'org-priorities
2574 :type 'character)
2576 (defcustom org-default-priority ?B
2577 "The default priority of TODO items.
2578 This is the priority an item gets if no explicit priority is given.
2579 When starting to cycle on an empty priority the first step in the cycle
2580 depends on `org-priority-start-cycle-with-default'. The resulting first
2581 step priority must not exceed the range from `org-highest-priority' to
2582 `org-lowest-priority' which means that `org-default-priority' has to be
2583 in this range exclusive or inclusive the range boundaries. Else the
2584 first step refuses to set the default and the second will fall back
2585 to (depending on the command used) the highest or lowest priority."
2586 :group 'org-priorities
2587 :type 'character)
2589 (defcustom org-priority-start-cycle-with-default t
2590 "Non-nil means start with default priority when starting to cycle.
2591 When this is nil, the first step in the cycle will be (depending on the
2592 command used) one higher or lower than the default priority.
2593 See also `org-default-priority'."
2594 :group 'org-priorities
2595 :type 'boolean)
2597 (defcustom org-get-priority-function nil
2598 "Function to extract the priority from a string.
2599 The string is normally the headline. If this is nil Org computes the
2600 priority from the priority cookie like [#A] in the headline. It returns
2601 an integer, increasing by 1000 for each priority level.
2602 The user can set a different function here, which should take a string
2603 as an argument and return the numeric priority."
2604 :group 'org-priorities
2605 :version "24.1"
2606 :type 'function)
2608 (defgroup org-time nil
2609 "Options concerning time stamps and deadlines in Org-mode."
2610 :tag "Org Time"
2611 :group 'org)
2613 (defcustom org-insert-labeled-timestamps-at-point nil
2614 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2615 When nil, these labeled time stamps are forces into the second line of an
2616 entry, just after the headline. When scheduling from the global TODO list,
2617 the time stamp will always be forced into the second line."
2618 :group 'org-time
2619 :type 'boolean)
2621 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2622 "Formats for `format-time-string' which are used for time stamps.
2623 It is not recommended to change this constant.")
2625 (defcustom org-time-stamp-rounding-minutes '(0 5)
2626 "Number of minutes to round time stamps to.
2627 These are two values, the first applies when first creating a time stamp.
2628 The second applies when changing it with the commands `S-up' and `S-down'.
2629 When changing the time stamp, this means that it will change in steps
2630 of N minutes, as given by the second value.
2632 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2633 numbers should be factors of 60, so for example 5, 10, 15.
2635 When this is larger than 1, you can still force an exact time stamp by using
2636 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2637 and by using a prefix arg to `S-up/down' to specify the exact number
2638 of minutes to shift."
2639 :group 'org-time
2640 :get #'(lambda (var) ; Make sure both elements are there
2641 (if (integerp (default-value var))
2642 (list (default-value var) 5)
2643 (default-value var)))
2644 :type '(list
2645 (integer :tag "when inserting times")
2646 (integer :tag "when modifying times")))
2648 ;; Normalize old customizations of this variable.
2649 (when (integerp org-time-stamp-rounding-minutes)
2650 (setq org-time-stamp-rounding-minutes
2651 (list org-time-stamp-rounding-minutes
2652 org-time-stamp-rounding-minutes)))
2654 (defcustom org-display-custom-times nil
2655 "Non-nil means overlay custom formats over all time stamps.
2656 The formats are defined through the variable `org-time-stamp-custom-formats'.
2657 To turn this on on a per-file basis, insert anywhere in the file:
2658 #+STARTUP: customtime"
2659 :group 'org-time
2660 :set 'set-default
2661 :type 'sexp)
2662 (make-variable-buffer-local 'org-display-custom-times)
2664 (defcustom org-time-stamp-custom-formats
2665 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2666 "Custom formats for time stamps. See `format-time-string' for the syntax.
2667 These are overlaid over the default ISO format if the variable
2668 `org-display-custom-times' is set. Time like %H:%M should be at the
2669 end of the second format. The custom formats are also honored by export
2670 commands, if custom time display is turned on at the time of export."
2671 :group 'org-time
2672 :type 'sexp)
2674 (defun org-time-stamp-format (&optional long inactive)
2675 "Get the right format for a time string."
2676 (let ((f (if long (cdr org-time-stamp-formats)
2677 (car org-time-stamp-formats))))
2678 (if inactive
2679 (concat "[" (substring f 1 -1) "]")
2680 f)))
2682 (defcustom org-time-clocksum-format "%d:%02d"
2683 "The format string used when creating CLOCKSUM lines.
2684 This is also used when org-mode generates a time duration."
2685 :group 'org-time
2686 :type 'string)
2688 (defcustom org-time-clocksum-use-fractional nil
2689 "If non-nil, \\[org-clock-display] uses fractional times.
2690 org-mode generates a time duration."
2691 :group 'org-time
2692 :type 'boolean)
2694 (defcustom org-time-clocksum-fractional-format "%.2f"
2695 "The format string used when creating CLOCKSUM lines, or when
2696 org-mode generates a time duration."
2697 :group 'org-time
2698 :type 'string)
2700 (defcustom org-deadline-warning-days 14
2701 "No. of days before expiration during which a deadline becomes active.
2702 This variable governs the display in sparse trees and in the agenda.
2703 When 0 or negative, it means use this number (the absolute value of it)
2704 even if a deadline has a different individual lead time specified.
2706 Custom commands can set this variable in the options section."
2707 :group 'org-time
2708 :group 'org-agenda-daily/weekly
2709 :type 'integer)
2711 (defcustom org-read-date-prefer-future t
2712 "Non-nil means assume future for incomplete date input from user.
2713 This affects the following situations:
2714 1. The user gives a month but not a year.
2715 For example, if it is April and you enter \"feb 2\", this will be read
2716 as Feb 2, *next* year. \"May 5\", however, will be this year.
2717 2. The user gives a day, but no month.
2718 For example, if today is the 15th, and you enter \"3\", Org-mode will
2719 read this as the third of *next* month. However, if you enter \"17\",
2720 it will be considered as *this* month.
2722 If you set this variable to the symbol `time', then also the following
2723 will work:
2725 3. If the user gives a time, but no day. If the time is before now,
2726 to will be interpreted as tomorrow.
2728 Currently none of this works for ISO week specifications.
2730 When this option is nil, the current day, month and year will always be
2731 used as defaults.
2733 See also `org-agenda-jump-prefer-future'."
2734 :group 'org-time
2735 :type '(choice
2736 (const :tag "Never" nil)
2737 (const :tag "Check month and day" t)
2738 (const :tag "Check month, day, and time" time)))
2740 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2741 "Should the agenda jump command prefer the future for incomplete dates?
2742 The default is to do the same as configured in `org-read-date-prefer-future'.
2743 But you can also set a deviating value here.
2744 This may t or nil, or the symbol `org-read-date-prefer-future'."
2745 :group 'org-agenda
2746 :group 'org-time
2747 :version "24.1"
2748 :type '(choice
2749 (const :tag "Use org-read-date-prefer-future"
2750 org-read-date-prefer-future)
2751 (const :tag "Never" nil)
2752 (const :tag "Always" t)))
2754 (defcustom org-read-date-force-compatible-dates t
2755 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2757 Depending on the system Emacs is running on, certain dates cannot
2758 be represented with the type used internally to represent time.
2759 Dates between 1970-1-1 and 2038-1-1 can always be represented
2760 correctly. Some systems allow for earlier dates, some for later,
2761 some for both. One way to find out it to insert any date into an
2762 Org buffer, putting the cursor on the year and hitting S-up and
2763 S-down to test the range.
2765 When this variable is set to t, the date/time prompt will not let
2766 you specify dates outside the 1970-2037 range, so it is certain that
2767 these dates will work in whatever version of Emacs you are
2768 running, and also that you can move a file from one Emacs implementation
2769 to another. WHenever Org is forcing the year for you, it will display
2770 a message and beep.
2772 When this variable is nil, Org will check if the date is
2773 representable in the specific Emacs implementation you are using.
2774 If not, it will force a year, usually the current year, and beep
2775 to remind you. Currently this setting is not recommended because
2776 the likelihood that you will open your Org files in an Emacs that
2777 has limited date range is not negligible.
2779 A workaround for this problem is to use diary sexp dates for time
2780 stamps outside of this range."
2781 :group 'org-time
2782 :version "24.1"
2783 :type 'boolean)
2785 (defcustom org-read-date-display-live t
2786 "Non-nil means display current interpretation of date prompt live.
2787 This display will be in an overlay, in the minibuffer."
2788 :group 'org-time
2789 :type 'boolean)
2791 (defcustom org-read-date-popup-calendar t
2792 "Non-nil means pop up a calendar when prompting for a date.
2793 In the calendar, the date can be selected with mouse-1. However, the
2794 minibuffer will also be active, and you can simply enter the date as well.
2795 When nil, only the minibuffer will be available."
2796 :group 'org-time
2797 :type 'boolean)
2798 (if (fboundp 'defvaralias)
2799 (defvaralias 'org-popup-calendar-for-date-prompt
2800 'org-read-date-popup-calendar))
2802 (defcustom org-read-date-minibuffer-setup-hook nil
2803 "Hook to be used to set up keys for the date/time interface.
2804 Add key definitions to `minibuffer-local-map', which will be a temporary
2805 copy."
2806 :group 'org-time
2807 :type 'hook)
2809 (defcustom org-extend-today-until 0
2810 "The hour when your day really ends. Must be an integer.
2811 This has influence for the following applications:
2812 - When switching the agenda to \"today\". It it is still earlier than
2813 the time given here, the day recognized as TODAY is actually yesterday.
2814 - When a date is read from the user and it is still before the time given
2815 here, the current date and time will be assumed to be yesterday, 23:59.
2816 Also, timestamps inserted in remember templates follow this rule.
2818 IMPORTANT: This is a feature whose implementation is and likely will
2819 remain incomplete. Really, it is only here because past midnight seems to
2820 be the favorite working time of John Wiegley :-)"
2821 :group 'org-time
2822 :type 'integer)
2824 (defcustom org-use-effective-time nil
2825 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2826 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2827 \"effective time\" of any timestamps between midnight and 8am will be
2828 23:59 of the previous day."
2829 :group 'org-time
2830 :version "24.1"
2831 :type 'boolean)
2833 (defcustom org-edit-timestamp-down-means-later nil
2834 "Non-nil means S-down will increase the time in a time stamp.
2835 When nil, S-up will increase."
2836 :group 'org-time
2837 :type 'boolean)
2839 (defcustom org-calendar-follow-timestamp-change t
2840 "Non-nil means make the calendar window follow timestamp changes.
2841 When a timestamp is modified and the calendar window is visible, it will be
2842 moved to the new date."
2843 :group 'org-time
2844 :type 'boolean)
2846 (defgroup org-tags nil
2847 "Options concerning tags in Org-mode."
2848 :tag "Org Tags"
2849 :group 'org)
2851 (defcustom org-tag-alist nil
2852 "List of tags allowed in Org-mode files.
2853 When this list is nil, Org-mode will base TAG input on what is already in the
2854 buffer.
2855 The value of this variable is an alist, the car of each entry must be a
2856 keyword as a string, the cdr may be a character that is used to select
2857 that tag through the fast-tag-selection interface.
2858 See the manual for details."
2859 :group 'org-tags
2860 :type '(repeat
2861 (choice
2862 (cons (string :tag "Tag name")
2863 (character :tag "Access char"))
2864 (list :tag "Start radio group"
2865 (const :startgroup)
2866 (option (string :tag "Group description")))
2867 (list :tag "End radio group"
2868 (const :endgroup)
2869 (option (string :tag "Group description")))
2870 (const :tag "New line" (:newline)))))
2872 (defcustom org-tag-persistent-alist nil
2873 "List of tags that will always appear in all Org-mode files.
2874 This is in addition to any in buffer settings or customizations
2875 of `org-tag-alist'.
2876 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2877 The value of this variable is an alist, the car of each entry must be a
2878 keyword as a string, the cdr may be a character that is used to select
2879 that tag through the fast-tag-selection interface.
2880 See the manual for details.
2881 To disable these tags on a per-file basis, insert anywhere in the file:
2882 #+STARTUP: noptag"
2883 :group 'org-tags
2884 :type '(repeat
2885 (choice
2886 (cons (string :tag "Tag name")
2887 (character :tag "Access char"))
2888 (const :tag "Start radio group" (:startgroup))
2889 (const :tag "End radio group" (:endgroup))
2890 (const :tag "New line" (:newline)))))
2892 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2893 "If non-nil, always offer completion for all tags of all agenda files.
2894 Instead of customizing this variable directly, you might want to
2895 set it locally for capture buffers, because there no list of
2896 tags in that file can be created dynamically (there are none).
2898 (add-hook 'org-capture-mode-hook
2899 (lambda ()
2900 (set (make-local-variable
2901 'org-complete-tags-always-offer-all-agenda-tags)
2902 t)))"
2903 :group 'org-tags
2904 :version "24.1"
2905 :type 'boolean)
2907 (defvar org-file-tags nil
2908 "List of tags that can be inherited by all entries in the file.
2909 The tags will be inherited if the variable `org-use-tag-inheritance'
2910 says they should be.
2911 This variable is populated from #+FILETAGS lines.")
2913 (defcustom org-use-fast-tag-selection 'auto
2914 "Non-nil means use fast tag selection scheme.
2915 This is a special interface to select and deselect tags with single keys.
2916 When nil, fast selection is never used.
2917 When the symbol `auto', fast selection is used if and only if selection
2918 characters for tags have been configured, either through the variable
2919 `org-tag-alist' or through a #+TAGS line in the buffer.
2920 When t, fast selection is always used and selection keys are assigned
2921 automatically if necessary."
2922 :group 'org-tags
2923 :type '(choice
2924 (const :tag "Always" t)
2925 (const :tag "Never" nil)
2926 (const :tag "When selection characters are configured" 'auto)))
2928 (defcustom org-fast-tag-selection-single-key nil
2929 "Non-nil means fast tag selection exits after first change.
2930 When nil, you have to press RET to exit it.
2931 During fast tag selection, you can toggle this flag with `C-c'.
2932 This variable can also have the value `expert'. In this case, the window
2933 displaying the tags menu is not even shown, until you press C-c again."
2934 :group 'org-tags
2935 :type '(choice
2936 (const :tag "No" nil)
2937 (const :tag "Yes" t)
2938 (const :tag "Expert" expert)))
2940 (defvar org-fast-tag-selection-include-todo nil
2941 "Non-nil means fast tags selection interface will also offer TODO states.
2942 This is an undocumented feature, you should not rely on it.")
2944 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2945 "The column to which tags should be indented in a headline.
2946 If this number is positive, it specifies the column. If it is negative,
2947 it means that the tags should be flushright to that column. For example,
2948 -80 works well for a normal 80 character screen.
2949 When 0, place tags directly after headline text, with only one space in
2950 between."
2951 :group 'org-tags
2952 :type 'integer)
2954 (defcustom org-auto-align-tags t
2955 "Non-nil keeps tags aligned when modifying headlines.
2956 Some operations (i.e. demoting) change the length of a headline and
2957 therefore shift the tags around. With this option turned on, after
2958 each such operation the tags are again aligned to `org-tags-column'."
2959 :group 'org-tags
2960 :type 'boolean)
2962 (defcustom org-use-tag-inheritance t
2963 "Non-nil means tags in levels apply also for sublevels.
2964 When nil, only the tags directly given in a specific line apply there.
2965 This may also be a list of tags that should be inherited, or a regexp that
2966 matches tags that should be inherited. Additional control is possible
2967 with the variable `org-tags-exclude-from-inheritance' which gives an
2968 explicit list of tags to be excluded from inheritance., even if the value of
2969 `org-use-tag-inheritance' would select it for inheritance.
2971 If this option is t, a match early-on in a tree can lead to a large
2972 number of matches in the subtree when constructing the agenda or creating
2973 a sparse tree. If you only want to see the first match in a tree during
2974 a search, check out the variable `org-tags-match-list-sublevels'."
2975 :group 'org-tags
2976 :type '(choice
2977 (const :tag "Not" nil)
2978 (const :tag "Always" t)
2979 (repeat :tag "Specific tags" (string :tag "Tag"))
2980 (regexp :tag "Tags matched by regexp")))
2982 (defcustom org-tags-exclude-from-inheritance nil
2983 "List of tags that should never be inherited.
2984 This is a way to exclude a few tags from inheritance. For way to do
2985 the opposite, to actively allow inheritance for selected tags,
2986 see the variable `org-use-tag-inheritance'."
2987 :group 'org-tags
2988 :type '(repeat (string :tag "Tag")))
2990 (defun org-tag-inherit-p (tag)
2991 "Check if TAG is one that should be inherited."
2992 (cond
2993 ((member tag org-tags-exclude-from-inheritance) nil)
2994 ((eq org-use-tag-inheritance t) t)
2995 ((not org-use-tag-inheritance) nil)
2996 ((stringp org-use-tag-inheritance)
2997 (string-match org-use-tag-inheritance tag))
2998 ((listp org-use-tag-inheritance)
2999 (member tag org-use-tag-inheritance))
3000 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3002 (defcustom org-tags-match-list-sublevels t
3003 "Non-nil means list also sublevels of headlines matching a search.
3004 This variable applies to tags/property searches, and also to stuck
3005 projects because this search is based on a tags match as well.
3007 When set to the symbol `indented', sublevels are indented with
3008 leading dots.
3010 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3011 the sublevels of a headline matching a tag search often also match
3012 the same search. Listing all of them can create very long lists.
3013 Setting this variable to nil causes subtrees of a match to be skipped.
3015 This variable is semi-obsolete and probably should always be true. It
3016 is better to limit inheritance to certain tags using the variables
3017 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3018 :group 'org-tags
3019 :type '(choice
3020 (const :tag "No, don't list them" nil)
3021 (const :tag "Yes, do list them" t)
3022 (const :tag "List them, indented with leading dots" indented)))
3024 (defcustom org-tags-sort-function nil
3025 "When set, tags are sorted using this function as a comparator."
3026 :group 'org-tags
3027 :type '(choice
3028 (const :tag "No sorting" nil)
3029 (const :tag "Alphabetical" string<)
3030 (const :tag "Reverse alphabetical" string>)
3031 (function :tag "Custom function" nil)))
3033 (defvar org-tags-history nil
3034 "History of minibuffer reads for tags.")
3035 (defvar org-last-tags-completion-table nil
3036 "The last used completion table for tags.")
3037 (defvar org-after-tags-change-hook nil
3038 "Hook that is run after the tags in a line have changed.")
3040 (defgroup org-properties nil
3041 "Options concerning properties in Org-mode."
3042 :tag "Org Properties"
3043 :group 'org)
3045 (defcustom org-property-format "%-10s %s"
3046 "How property key/value pairs should be formatted by `indent-line'.
3047 When `indent-line' hits a property definition, it will format the line
3048 according to this format, mainly to make sure that the values are
3049 lined-up with respect to each other."
3050 :group 'org-properties
3051 :type 'string)
3053 (defcustom org-properties-postprocess-alist nil
3054 "Alist of properties and functions to adjust inserted values.
3055 Elements of this alist must be of the form
3057 ([string] [function])
3059 where [string] must be a property name and [function] must be a
3060 lambda expression: this lambda expression must take one argument,
3061 the value to adjust, and return the new value as a string.
3063 For example, this element will allow the property \"Remaining\"
3064 to be updated wrt the relation between the \"Effort\" property
3065 and the clock summary:
3067 ((\"Remaining\" (lambda(value)
3068 (let ((clocksum (org-clock-sum-current-item))
3069 (effort (org-duration-string-to-minutes
3070 (org-entry-get (point) \"Effort\"))))
3071 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3072 :group 'org-properties
3073 :version "24.1"
3074 :type 'alist)
3076 (defcustom org-use-property-inheritance nil
3077 "Non-nil means properties apply also for sublevels.
3079 This setting is chiefly used during property searches. Turning it on can
3080 cause significant overhead when doing a search, which is why it is not
3081 on by default.
3083 When nil, only the properties directly given in the current entry count.
3084 When t, every property is inherited. The value may also be a list of
3085 properties that should have inheritance, or a regular expression matching
3086 properties that should be inherited.
3088 However, note that some special properties use inheritance under special
3089 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3090 and the properties ending in \"_ALL\" when they are used as descriptor
3091 for valid values of a property.
3093 Note for programmers:
3094 When querying an entry with `org-entry-get', you can control if inheritance
3095 should be used. By default, `org-entry-get' looks only at the local
3096 properties. You can request inheritance by setting the inherit argument
3097 to t (to force inheritance) or to `selective' (to respect the setting
3098 in this variable)."
3099 :group 'org-properties
3100 :type '(choice
3101 (const :tag "Not" nil)
3102 (const :tag "Always" t)
3103 (repeat :tag "Specific properties" (string :tag "Property"))
3104 (regexp :tag "Properties matched by regexp")))
3106 (defun org-property-inherit-p (property)
3107 "Check if PROPERTY is one that should be inherited."
3108 (cond
3109 ((eq org-use-property-inheritance t) t)
3110 ((not org-use-property-inheritance) nil)
3111 ((stringp org-use-property-inheritance)
3112 (string-match org-use-property-inheritance property))
3113 ((listp org-use-property-inheritance)
3114 (member property org-use-property-inheritance))
3115 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3117 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3118 "The default column format, if no other format has been defined.
3119 This variable can be set on the per-file basis by inserting a line
3121 #+COLUMNS: %25ITEM ....."
3122 :group 'org-properties
3123 :type 'string)
3125 (defcustom org-columns-ellipses ".."
3126 "The ellipses to be used when a field in column view is truncated.
3127 When this is the empty string, as many characters as possible are shown,
3128 but then there will be no visual indication that the field has been truncated.
3129 When this is a string of length N, the last N characters of a truncated
3130 field are replaced by this string. If the column is narrower than the
3131 ellipses string, only part of the ellipses string will be shown."
3132 :group 'org-properties
3133 :type 'string)
3135 (defcustom org-columns-modify-value-for-display-function nil
3136 "Function that modifies values for display in column view.
3137 For example, it can be used to cut out a certain part from a time stamp.
3138 The function must take 2 arguments:
3140 column-title The title of the column (*not* the property name)
3141 value The value that should be modified.
3143 The function should return the value that should be displayed,
3144 or nil if the normal value should be used."
3145 :group 'org-properties
3146 :type 'function)
3148 (defcustom org-effort-property "Effort"
3149 "The property that is being used to keep track of effort estimates.
3150 Effort estimates given in this property need to have the format H:MM."
3151 :group 'org-properties
3152 :group 'org-progress
3153 :type '(string :tag "Property"))
3155 (defconst org-global-properties-fixed
3156 '(("VISIBILITY_ALL" . "folded children content all")
3157 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3158 "List of property/value pairs that can be inherited by any entry.
3160 These are fixed values, for the preset properties. The user variable
3161 that can be used to add to this list is `org-global-properties'.
3163 The entries in this list are cons cells where the car is a property
3164 name and cdr is a string with the value. If the value represents
3165 multiple items like an \"_ALL\" property, separate the items by
3166 spaces.")
3168 (defcustom org-global-properties nil
3169 "List of property/value pairs that can be inherited by any entry.
3171 This list will be combined with the constant `org-global-properties-fixed'.
3173 The entries in this list are cons cells where the car is a property
3174 name and cdr is a string with the value.
3176 You can set buffer-local values for the same purpose in the variable
3177 `org-file-properties' this by adding lines like
3179 #+PROPERTY: NAME VALUE"
3180 :group 'org-properties
3181 :type '(repeat
3182 (cons (string :tag "Property")
3183 (string :tag "Value"))))
3185 (defvar org-file-properties nil
3186 "List of property/value pairs that can be inherited by any entry.
3187 Valid for the current buffer.
3188 This variable is populated from #+PROPERTY lines.")
3189 (make-variable-buffer-local 'org-file-properties)
3191 (defgroup org-agenda nil
3192 "Options concerning agenda views in Org-mode."
3193 :tag "Org Agenda"
3194 :group 'org)
3196 (defvar org-category nil
3197 "Variable used by org files to set a category for agenda display.
3198 Such files should use a file variable to set it, for example
3200 # -*- mode: org; org-category: \"ELisp\"
3202 or contain a special line
3204 #+CATEGORY: ELisp
3206 If the file does not specify a category, then file's base name
3207 is used instead.")
3208 (make-variable-buffer-local 'org-category)
3209 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3211 (defcustom org-agenda-files nil
3212 "The files to be used for agenda display.
3213 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3214 \\[org-remove-file]. You can also use customize to edit the list.
3216 If an entry is a directory, all files in that directory that are matched by
3217 `org-agenda-file-regexp' will be part of the file list.
3219 If the value of the variable is not a list but a single file name, then
3220 the list of agenda files is actually stored and maintained in that file, one
3221 agenda file per line. In this file paths can be given relative to
3222 `org-directory'. Tilde expansion and environment variable substitution
3223 are also made."
3224 :group 'org-agenda
3225 :type '(choice
3226 (repeat :tag "List of files and directories" file)
3227 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3229 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3230 "Regular expression to match files for `org-agenda-files'.
3231 If any element in the list in that variable contains a directory instead
3232 of a normal file, all files in that directory that are matched by this
3233 regular expression will be included."
3234 :group 'org-agenda
3235 :type 'regexp)
3237 (defcustom org-agenda-text-search-extra-files nil
3238 "List of extra files to be searched by text search commands.
3239 These files will be search in addition to the agenda files by the
3240 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3241 Note that these files will only be searched for text search commands,
3242 not for the other agenda views like todo lists, tag searches or the weekly
3243 agenda. This variable is intended to list notes and possibly archive files
3244 that should also be searched by these two commands.
3245 In fact, if the first element in the list is the symbol `agenda-archives',
3246 than all archive files of all agenda files will be added to the search
3247 scope."
3248 :group 'org-agenda
3249 :type '(set :greedy t
3250 (const :tag "Agenda Archives" agenda-archives)
3251 (repeat :inline t (file))))
3253 (if (fboundp 'defvaralias)
3254 (defvaralias 'org-agenda-multi-occur-extra-files
3255 'org-agenda-text-search-extra-files))
3257 (defcustom org-agenda-skip-unavailable-files nil
3258 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3259 A nil value means to remove them, after a query, from the list."
3260 :group 'org-agenda
3261 :type 'boolean)
3263 (defcustom org-calendar-to-agenda-key [?c]
3264 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3265 The command `org-calendar-goto-agenda' will be bound to this key. The
3266 default is the character `c' because then `c' can be used to switch back and
3267 forth between agenda and calendar."
3268 :group 'org-agenda
3269 :type 'sexp)
3271 (defcustom org-calendar-agenda-action-key [?k]
3272 "The key to be installed in `calendar-mode-map' for agenda-action.
3273 The command `org-agenda-action' will be bound to this key. The
3274 default is the character `k' because we use the same key in the agenda."
3275 :group 'org-agenda
3276 :type 'sexp)
3278 (defcustom org-calendar-insert-diary-entry-key [?i]
3279 "The key to be installed in `calendar-mode-map' for adding diary entries.
3280 This option is irrelevant until `org-agenda-diary-file' has been configured
3281 to point to an Org-mode file. When that is the case, the command
3282 `org-agenda-diary-entry' will be bound to the key given here, by default
3283 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3284 if you want to continue doing this, you need to change this to a different
3285 key."
3286 :group 'org-agenda
3287 :type 'sexp)
3289 (defcustom org-agenda-diary-file 'diary-file
3290 "File to which to add new entries with the `i' key in agenda and calendar.
3291 When this is the symbol `diary-file', the functionality in the Emacs
3292 calendar will be used to add entries to the `diary-file'. But when this
3293 points to a file, `org-agenda-diary-entry' will be used instead."
3294 :group 'org-agenda
3295 :type '(choice
3296 (const :tag "The standard Emacs diary file" diary-file)
3297 (file :tag "Special Org file diary entries")))
3299 (eval-after-load "calendar"
3300 '(progn
3301 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3302 'org-calendar-goto-agenda)
3303 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3304 'org-agenda-action)
3305 (add-hook 'calendar-mode-hook
3306 (lambda ()
3307 (unless (eq org-agenda-diary-file 'diary-file)
3308 (define-key calendar-mode-map
3309 org-calendar-insert-diary-entry-key
3310 'org-agenda-diary-entry))))))
3312 (defgroup org-latex nil
3313 "Options for embedding LaTeX code into Org-mode."
3314 :tag "Org LaTeX"
3315 :group 'org)
3317 (defcustom org-format-latex-options
3318 '(:foreground default :background default :scale 1.0
3319 :html-foreground "Black" :html-background "Transparent"
3320 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3321 "Options for creating images from LaTeX fragments.
3322 This is a property list with the following properties:
3323 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3324 `default' means use the foreground of the default face.
3325 :background the background color, or \"Transparent\".
3326 `default' means use the background of the default face.
3327 :scale a scaling factor for the size of the images, to get more pixels
3328 :html-foreground, :html-background, :html-scale
3329 the same numbers for HTML export.
3330 :matchers a list indicating which matchers should be used to
3331 find LaTeX fragments. Valid members of this list are:
3332 \"begin\" find environments
3333 \"$1\" find single characters surrounded by $.$
3334 \"$\" find math expressions surrounded by $...$
3335 \"$$\" find math expressions surrounded by $$....$$
3336 \"\\(\" find math expressions surrounded by \\(...\\)
3337 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3338 :group 'org-latex
3339 :type 'plist)
3341 (defcustom org-format-latex-signal-error t
3342 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3343 When nil, just push out a message."
3344 :group 'org-latex
3345 :version "24.1"
3346 :type 'boolean)
3348 (defcustom org-latex-to-mathml-jar-file nil
3349 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3350 Use this to specify additional executable file say a jar file.
3352 When using MathToWeb as the converter, specify the full-path to
3353 your mathtoweb.jar file."
3354 :group 'org-latex
3355 :version "24.1"
3356 :type '(choice
3357 (const :tag "None" nil)
3358 (file :tag "JAR file" :must-match t)))
3360 (defcustom org-latex-to-mathml-convert-command nil
3361 "Command to convert LaTeX fragments to MathML.
3362 Replace format-specifiers in the command as noted below and use
3363 `shell-command' to convert LaTeX to MathML.
3364 %j: Executable file in fully expanded form as specified by
3365 `org-latex-to-mathml-jar-file'.
3366 %I: Input LaTeX file in fully expanded form
3367 %o: Output MathML file
3368 This command is used by `org-create-math-formula'.
3370 When using MathToWeb as the converter, set this to
3371 \"java -jar %j -unicode -force -df %o %I\"."
3372 :group 'org-latex
3373 :version "24.1"
3374 :type '(choice
3375 (const :tag "None" nil)
3376 (string :tag "\nShell command")))
3378 (defun org-format-latex-mathml-available-p ()
3379 "Return t if `org-latex-to-mathml-convert-command' is usable."
3380 (save-match-data
3381 (when (and (boundp 'org-latex-to-mathml-convert-command)
3382 org-latex-to-mathml-convert-command)
3383 (let ((executable (car (split-string
3384 org-latex-to-mathml-convert-command))))
3385 (when (executable-find executable)
3386 (if (string-match
3387 "%j" org-latex-to-mathml-convert-command)
3388 (file-readable-p org-latex-to-mathml-jar-file)
3389 t))))))
3391 (defcustom org-format-latex-header "\\documentclass{article}
3392 \\usepackage[usenames]{color}
3393 \\usepackage{amsmath}
3394 \\usepackage[mathscr]{eucal}
3395 \\pagestyle{empty} % do not remove
3396 \[PACKAGES]
3397 \[DEFAULT-PACKAGES]
3398 % The settings below are copied from fullpage.sty
3399 \\setlength{\\textwidth}{\\paperwidth}
3400 \\addtolength{\\textwidth}{-3cm}
3401 \\setlength{\\oddsidemargin}{1.5cm}
3402 \\addtolength{\\oddsidemargin}{-2.54cm}
3403 \\setlength{\\evensidemargin}{\\oddsidemargin}
3404 \\setlength{\\textheight}{\\paperheight}
3405 \\addtolength{\\textheight}{-\\headheight}
3406 \\addtolength{\\textheight}{-\\headsep}
3407 \\addtolength{\\textheight}{-\\footskip}
3408 \\addtolength{\\textheight}{-3cm}
3409 \\setlength{\\topmargin}{1.5cm}
3410 \\addtolength{\\topmargin}{-2.54cm}"
3411 "The document header used for processing LaTeX fragments.
3412 It is imperative that this header make sure that no page number
3413 appears on the page. The package defined in the variables
3414 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3415 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3416 will be appended."
3417 :group 'org-latex
3418 :type 'string)
3420 (defvar org-format-latex-header-extra nil)
3422 (defun org-set-packages-alist (var val)
3423 "Set the packages alist and make sure it has 3 elements per entry."
3424 (set var (mapcar (lambda (x)
3425 (if (and (consp x) (= (length x) 2))
3426 (list (car x) (nth 1 x) t)
3428 val)))
3430 (defun org-get-packages-alist (var)
3432 "Get the packages alist and make sure it has 3 elements per entry."
3433 (mapcar (lambda (x)
3434 (if (and (consp x) (= (length x) 2))
3435 (list (car x) (nth 1 x) t)
3437 (default-value var)))
3439 ;; The following variables are defined here because is it also used
3440 ;; when formatting latex fragments. Originally it was part of the
3441 ;; LaTeX exporter, which is why the name includes "export".
3442 (defcustom org-export-latex-default-packages-alist
3443 '(("AUTO" "inputenc" t)
3444 ("T1" "fontenc" t)
3445 ("" "fixltx2e" nil)
3446 ("" "graphicx" t)
3447 ("" "longtable" nil)
3448 ("" "float" nil)
3449 ("" "wrapfig" nil)
3450 ("" "soul" t)
3451 ("" "textcomp" t)
3452 ("" "marvosym" t)
3453 ("" "wasysym" t)
3454 ("" "latexsym" t)
3455 ("" "amssymb" t)
3456 ("" "hyperref" nil)
3457 "\\tolerance=1000"
3459 "Alist of default packages to be inserted in the header.
3460 Change this only if one of the packages here causes an incompatibility
3461 with another package you are using.
3462 The packages in this list are needed by one part or another of Org-mode
3463 to function properly.
3465 - inputenc, fontenc: for basic font and character selection
3466 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3467 for interpreting the entities in `org-entities'. You can skip some of these
3468 packages if you don't use any of the symbols in it.
3469 - graphicx: for including images
3470 - float, wrapfig: for figure placement
3471 - longtable: for long tables
3472 - hyperref: for cross references
3474 Therefore you should not modify this variable unless you know what you
3475 are doing. The one reason to change it anyway is that you might be loading
3476 some other package that conflicts with one of the default packages.
3477 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3478 If SNIPPET-FLAG is t, the package also needs to be included when
3479 compiling LaTeX snippets into images for inclusion into HTML."
3480 :group 'org-export-latex
3481 :set 'org-set-packages-alist
3482 :get 'org-get-packages-alist
3483 :version "24.1"
3484 :type '(repeat
3485 (choice
3486 (list :tag "options/package pair"
3487 (string :tag "options")
3488 (string :tag "package")
3489 (boolean :tag "Snippet"))
3490 (string :tag "A line of LaTeX"))))
3492 (defcustom org-export-latex-packages-alist nil
3493 "Alist of packages to be inserted in every LaTeX header.
3494 These will be inserted after `org-export-latex-default-packages-alist'.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3496 SNIPPET-FLAG, when t, indicates that this package is also needed when
3497 turning LaTeX snippets into images for inclusion into HTML.
3498 Make sure that you only list packages here which:
3499 - you want in every file
3500 - do not conflict with the default packages in
3501 `org-export-latex-default-packages-alist'
3502 - do not conflict with the setup in `org-format-latex-header'."
3503 :group 'org-export-latex
3504 :set 'org-set-packages-alist
3505 :get 'org-get-packages-alist
3506 :type '(repeat
3507 (choice
3508 (list :tag "options/package pair"
3509 (string :tag "options")
3510 (string :tag "package")
3511 (boolean :tag "Snippet"))
3512 (string :tag "A line of LaTeX"))))
3515 (defgroup org-appearance nil
3516 "Settings for Org-mode appearance."
3517 :tag "Org Appearance"
3518 :group 'org)
3520 (defcustom org-level-color-stars-only nil
3521 "Non-nil means fontify only the stars in each headline.
3522 When nil, the entire headline is fontified.
3523 Changing it requires restart of `font-lock-mode' to become effective
3524 also in regions already fontified."
3525 :group 'org-appearance
3526 :type 'boolean)
3528 (defcustom org-hide-leading-stars nil
3529 "Non-nil means hide the first N-1 stars in a headline.
3530 This works by using the face `org-hide' for these stars. This
3531 face is white for a light background, and black for a dark
3532 background. You may have to customize the face `org-hide' to
3533 make this work.
3534 Changing it requires restart of `font-lock-mode' to become effective
3535 also in regions already fontified.
3536 You may also set this on a per-file basis by adding one of the following
3537 lines to the buffer:
3539 #+STARTUP: hidestars
3540 #+STARTUP: showstars"
3541 :group 'org-appearance
3542 :type 'boolean)
3544 (defcustom org-hidden-keywords nil
3545 "List of symbols corresponding to keywords to be hidden the org buffer.
3546 For example, a value '(title) for this list will make the document's title
3547 appear in the buffer without the initial #+TITLE: keyword."
3548 :group 'org-appearance
3549 :version "24.1"
3550 :type '(set (const :tag "#+AUTHOR" author)
3551 (const :tag "#+DATE" date)
3552 (const :tag "#+EMAIL" email)
3553 (const :tag "#+TITLE" title)))
3555 (defcustom org-fontify-done-headline nil
3556 "Non-nil means change the face of a headline if it is marked DONE.
3557 Normally, only the TODO/DONE keyword indicates the state of a headline.
3558 When this is non-nil, the headline after the keyword is set to the
3559 `org-headline-done' as an additional indication."
3560 :group 'org-appearance
3561 :type 'boolean)
3563 (defcustom org-fontify-emphasized-text t
3564 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3565 Changing this variable requires a restart of Emacs to take effect."
3566 :group 'org-appearance
3567 :type 'boolean)
3569 (defcustom org-fontify-whole-heading-line nil
3570 "Non-nil means fontify the whole line for headings.
3571 This is useful when setting a background color for the
3572 org-level-* faces."
3573 :group 'org-appearance
3574 :type 'boolean)
3576 (defcustom org-highlight-latex-fragments-and-specials nil
3577 "Non-nil means fontify what is treated specially by the exporters."
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hide-emphasis-markers nil
3582 "Non-nil mean font-lock should hide the emphasis marker characters."
3583 :group 'org-appearance
3584 :type 'boolean)
3586 (defcustom org-pretty-entities nil
3587 "Non-nil means show entities as UTF8 characters.
3588 When nil, the \\name form remains in the buffer."
3589 :group 'org-appearance
3590 :version "24.1"
3591 :type 'boolean)
3593 (defcustom org-pretty-entities-include-sub-superscripts t
3594 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3595 :group 'org-appearance
3596 :version "24.1"
3597 :type 'boolean)
3599 (defvar org-emph-re nil
3600 "Regular expression for matching emphasis.
3601 After a match, the match groups contain these elements:
3602 0 The match of the full regular expression, including the characters
3603 before and after the proper match
3604 1 The character before the proper match, or empty at beginning of line
3605 2 The proper match, including the leading and trailing markers
3606 3 The leading marker like * or /, indicating the type of highlighting
3607 4 The text between the emphasis markers, not including the markers
3608 5 The character after the match, empty at the end of a line")
3609 (defvar org-verbatim-re nil
3610 "Regular expression for matching verbatim text.")
3611 (defvar org-emphasis-regexp-components) ; defined just below
3612 (defvar org-emphasis-alist) ; defined just below
3613 (defun org-set-emph-re (var val)
3614 "Set variable and compute the emphasis regular expression."
3615 (set var val)
3616 (when (and (boundp 'org-emphasis-alist)
3617 (boundp 'org-emphasis-regexp-components)
3618 org-emphasis-alist org-emphasis-regexp-components)
3619 (let* ((e org-emphasis-regexp-components)
3620 (pre (car e))
3621 (post (nth 1 e))
3622 (border (nth 2 e))
3623 (body (nth 3 e))
3624 (nl (nth 4 e))
3625 (body1 (concat body "*?"))
3626 (markers (mapconcat 'car org-emphasis-alist ""))
3627 (vmarkers (mapconcat
3628 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3629 org-emphasis-alist "")))
3630 ;; make sure special characters appear at the right position in the class
3631 (if (string-match "\\^" markers)
3632 (setq markers (concat (replace-match "" t t markers) "^")))
3633 (if (string-match "-" markers)
3634 (setq markers (concat (replace-match "" t t markers) "-")))
3635 (if (string-match "\\^" vmarkers)
3636 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3637 (if (string-match "-" vmarkers)
3638 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3639 (if (> nl 0)
3640 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3641 (int-to-string nl) "\\}")))
3642 ;; Make the regexp
3643 (setq org-emph-re
3644 (concat "\\([" pre "]\\|^\\)"
3645 "\\("
3646 "\\([" markers "]\\)"
3647 "\\("
3648 "[^" border "]\\|"
3649 "[^" border "]"
3650 body1
3651 "[^" border "]"
3652 "\\)"
3653 "\\3\\)"
3654 "\\([" post "]\\|$\\)"))
3655 (setq org-verbatim-re
3656 (concat "\\([" pre "]\\|^\\)"
3657 "\\("
3658 "\\([" vmarkers "]\\)"
3659 "\\("
3660 "[^" border "]\\|"
3661 "[^" border "]"
3662 body1
3663 "[^" border "]"
3664 "\\)"
3665 "\\3\\)"
3666 "\\([" post "]\\|$\\)")))))
3668 (defcustom org-emphasis-regexp-components
3669 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3670 "Components used to build the regular expression for emphasis.
3671 This is a list with five entries. Terminology: In an emphasis string
3672 like \" *strong word* \", we call the initial space PREMATCH, the final
3673 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3674 and \"trong wor\" is the body. The different components in this variable
3675 specify what is allowed/forbidden in each part:
3677 pre Chars allowed as prematch. Beginning of line will be allowed too.
3678 post Chars allowed as postmatch. End of line will be allowed too.
3679 border The chars *forbidden* as border characters.
3680 body-regexp A regexp like \".\" to match a body character. Don't use
3681 non-shy groups here, and don't allow newline here.
3682 newline The maximum number of newlines allowed in an emphasis exp.
3684 Use customize to modify this, or restart Emacs after changing it."
3685 :group 'org-appearance
3686 :set 'org-set-emph-re
3687 :type '(list
3688 (sexp :tag "Allowed chars in pre ")
3689 (sexp :tag "Allowed chars in post ")
3690 (sexp :tag "Forbidden chars in border ")
3691 (sexp :tag "Regexp for body ")
3692 (integer :tag "number of newlines allowed")
3693 (option (boolean :tag "Please ignore this button"))))
3695 (defcustom org-emphasis-alist
3696 `(("*" bold "<b>" "</b>")
3697 ("/" italic "<i>" "</i>")
3698 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3699 ("=" org-code "<code>" "</code>" verbatim)
3700 ("~" org-verbatim "<code>" "</code>" verbatim)
3701 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3702 "<del>" "</del>")
3704 "Special syntax for emphasized text.
3705 Text starting and ending with a special character will be emphasized, for
3706 example *bold*, _underlined_ and /italic/. This variable sets the marker
3707 characters, the face to be used by font-lock for highlighting in Org-mode
3708 Emacs buffers, and the HTML tags to be used for this.
3709 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3710 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group 'org-appearance
3713 :set 'org-set-emph-re
3714 :type '(repeat
3715 (list
3716 (string :tag "Marker character")
3717 (choice
3718 (face :tag "Font-lock-face")
3719 (plist :tag "Face property list"))
3720 (string :tag "HTML start tag")
3721 (string :tag "HTML end tag")
3722 (option (const verbatim)))))
3724 (defvar org-protecting-blocks
3725 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3726 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3727 This is needed for font-lock setup.")
3729 ;;; Miscellaneous options
3731 (defgroup org-completion nil
3732 "Completion in Org-mode."
3733 :tag "Org Completion"
3734 :group 'org)
3736 (defcustom org-completion-use-ido nil
3737 "Non-nil means use ido completion wherever possible.
3738 Note that `ido-mode' must be active for this variable to be relevant.
3739 If you decide to turn this variable on, you might well want to turn off
3740 `org-outline-path-complete-in-steps'.
3741 See also `org-completion-use-iswitchb'."
3742 :group 'org-completion
3743 :type 'boolean)
3745 (defcustom org-completion-use-iswitchb nil
3746 "Non-nil means use iswitchb completion wherever possible.
3747 Note that `iswitchb-mode' must be active for this variable to be relevant.
3748 If you decide to turn this variable on, you might well want to turn off
3749 `org-outline-path-complete-in-steps'.
3750 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3751 :group 'org-completion
3752 :type 'boolean)
3754 (defcustom org-completion-fallback-command 'hippie-expand
3755 "The expansion command called by \\[pcomplete] in normal context.
3756 Normal means, no org-mode-specific context."
3757 :group 'org-completion
3758 :type 'function)
3760 ;;; Functions and variables from their packages
3761 ;; Declared here to avoid compiler warnings
3763 ;; XEmacs only
3764 (defvar outline-mode-menu-heading)
3765 (defvar outline-mode-menu-show)
3766 (defvar outline-mode-menu-hide)
3767 (defvar zmacs-regions) ; XEmacs regions
3769 ;; Emacs only
3770 (defvar mark-active)
3772 ;; Various packages
3773 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3774 (declare-function calendar-forward-day "cal-move" (arg))
3775 (declare-function calendar-goto-date "cal-move" (date))
3776 (declare-function calendar-goto-today "cal-move" ())
3777 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3778 (defvar calc-embedded-close-formula)
3779 (defvar calc-embedded-open-formula)
3780 (declare-function cdlatex-tab "ext:cdlatex" ())
3781 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3782 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3783 (defvar font-lock-unfontify-region-function)
3784 (declare-function iswitchb-read-buffer "iswitchb"
3785 (prompt &optional default require-match start matches-set))
3786 (defvar iswitchb-temp-buflist)
3787 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3788 (defvar org-agenda-tags-todo-honor-ignore-options)
3789 (declare-function org-agenda-skip "org-agenda" ())
3790 (declare-function
3791 org-agenda-format-item "org-agenda"
3792 (extra txt &optional category tags dotime noprefix remove-re habitp))
3793 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3794 (declare-function org-agenda-change-all-lines "org-agenda"
3795 (newhead hdmarker &optional fixface just-this))
3796 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3797 (declare-function org-agenda-maybe-redo "org-agenda" ())
3798 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3799 (beg end))
3800 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3801 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3802 "org-agenda" (&optional end))
3803 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3804 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3805 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3806 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3807 (declare-function org-indent-mode "org-indent" (&optional arg))
3808 (declare-function parse-time-string "parse-time" (string))
3809 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3810 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3811 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3812 (defvar remember-data-file)
3813 (defvar texmathp-why)
3814 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3815 (declare-function table--at-cell-p "table" (position &optional object at-column))
3817 (defvar w3m-current-url)
3818 (defvar w3m-current-title)
3820 (defvar org-latex-regexps)
3822 ;;; Autoload and prepare some org modules
3824 ;; Some table stuff that needs to be defined here, because it is used
3825 ;; by the functions setting up org-mode or checking for table context.
3827 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3828 "Detect an org-type or table-type table.")
3829 (defconst org-table-line-regexp "^[ \t]*|"
3830 "Detect an org-type table line.")
3831 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3832 "Detect an org-type table line.")
3833 (defconst org-table-hline-regexp "^[ \t]*|-"
3834 "Detect an org-type table hline.")
3835 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3836 "Detect a table-type table hline.")
3837 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3838 "Detect the first line outside a table when searching from within it.
3839 This works for both table types.")
3841 ;; Autoload the functions in org-table.el that are needed by functions here.
3843 (eval-and-compile
3844 (org-autoload "org-table"
3845 '(org-table-align org-table-begin org-table-blank-field
3846 org-table-convert org-table-convert-region org-table-copy-down
3847 org-table-copy-region org-table-create
3848 org-table-create-or-convert-from-region
3849 org-table-create-with-table.el org-table-current-dline
3850 org-table-cut-region org-table-delete-column org-table-edit-field
3851 org-table-edit-formulas org-table-end org-table-eval-formula
3852 org-table-export org-table-field-info
3853 org-table-get-stored-formulas org-table-goto-column
3854 org-table-hline-and-move org-table-import org-table-insert-column
3855 org-table-insert-hline org-table-insert-row org-table-iterate
3856 org-table-justify-field-maybe org-table-kill-row
3857 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3858 org-table-move-column org-table-move-column-left
3859 org-table-move-column-right org-table-move-row
3860 org-table-move-row-down org-table-move-row-up
3861 org-table-next-field org-table-next-row org-table-paste-rectangle
3862 org-table-previous-field org-table-recalculate
3863 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3864 org-table-toggle-coordinate-overlays
3865 org-table-toggle-formula-debugger org-table-wrap-region
3866 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3867 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3868 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3870 (defun org-at-table-p (&optional table-type)
3871 "Return t if the cursor is inside an org-type table.
3872 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3873 (if org-enable-table-editor
3874 (save-excursion
3875 (beginning-of-line 1)
3876 (looking-at (if table-type org-table-any-line-regexp
3877 org-table-line-regexp)))
3878 nil))
3879 (defsubst org-table-p () (org-at-table-p))
3881 (defun org-at-table.el-p ()
3882 "Return t if and only if we are at a table.el table."
3883 (and (org-at-table-p 'any)
3884 (save-excursion
3885 (goto-char (org-table-begin 'any))
3886 (looking-at org-table1-hline-regexp))))
3887 (defun org-table-recognize-table.el ()
3888 "If there is a table.el table nearby, recognize it and move into it."
3889 (if org-table-tab-recognizes-table.el
3890 (if (org-at-table.el-p)
3891 (progn
3892 (beginning-of-line 1)
3893 (if (looking-at org-table-dataline-regexp)
3895 (if (looking-at org-table1-hline-regexp)
3896 (progn
3897 (beginning-of-line 2)
3898 (if (looking-at org-table-any-border-regexp)
3899 (beginning-of-line -1)))))
3900 (if (re-search-forward "|" (org-table-end t) t)
3901 (progn
3902 (require 'table)
3903 (if (table--at-cell-p (point))
3905 (message "recognizing table.el table...")
3906 (table-recognize-table)
3907 (message "recognizing table.el table...done")))
3908 (error "This should not happen"))
3910 nil)
3911 nil))
3913 (defun org-at-table-hline-p ()
3914 "Return t if the cursor is inside a hline in a table."
3915 (if org-enable-table-editor
3916 (save-excursion
3917 (beginning-of-line 1)
3918 (looking-at org-table-hline-regexp))
3919 nil))
3921 (defvar org-table-clean-did-remove-column nil)
3923 (defun org-table-map-tables (function &optional quietly)
3924 "Apply FUNCTION to the start of all tables in the buffer."
3925 (save-excursion
3926 (save-restriction
3927 (widen)
3928 (goto-char (point-min))
3929 (while (re-search-forward org-table-any-line-regexp nil t)
3930 (unless quietly
3931 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3932 (beginning-of-line 1)
3933 (when (and (looking-at org-table-line-regexp)
3934 ;; Exclude tables in src/example/verbatim/clocktable blocks
3935 (not (org-in-block-p '("src" "example"))))
3936 (save-excursion (funcall function))
3937 (or (looking-at org-table-line-regexp)
3938 (forward-char 1)))
3939 (re-search-forward org-table-any-border-regexp nil 1))))
3940 (unless quietly (message "Mapping tables: done")))
3942 ;; Declare and autoload functions from org-exp.el & Co
3944 (declare-function org-default-export-plist "org-exp")
3945 (declare-function org-infile-export-plist "org-exp")
3946 (declare-function org-get-current-options "org-exp")
3947 (eval-and-compile
3948 (org-autoload "org-exp"
3949 '(org-export org-export-visible
3950 org-insert-export-options-template
3951 org-table-clean-before-export))
3952 (org-autoload "org-ascii"
3953 '(org-export-as-ascii org-export-ascii-preprocess
3954 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3955 org-export-region-as-ascii))
3956 (org-autoload "org-latex"
3957 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3958 org-replace-region-by-latex org-export-region-as-latex
3959 org-export-as-latex org-export-as-pdf
3960 org-export-as-pdf-and-open))
3961 (org-autoload "org-html"
3962 '(org-export-as-html-and-open
3963 org-export-as-html-batch org-export-as-html-to-buffer
3964 org-replace-region-by-html org-export-region-as-html
3965 org-export-as-html))
3966 (org-autoload "org-docbook"
3967 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3968 org-replace-region-by-docbook org-export-region-as-docbook
3969 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3970 org-export-as-docbook))
3971 (org-autoload "org-icalendar"
3972 '(org-export-icalendar-this-file
3973 org-export-icalendar-all-agenda-files
3974 org-export-icalendar-combine-agenda-files))
3975 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3976 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3978 ;; Declare and autoload functions from org-agenda.el
3980 (eval-and-compile
3981 (org-autoload "org-agenda"
3982 '(org-agenda org-agenda-list org-search-view
3983 org-todo-list org-tags-view org-agenda-list-stuck-projects
3984 org-diary org-agenda-to-appt
3985 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3987 ;; Autoload org-remember
3989 (eval-and-compile
3990 (org-autoload "org-remember"
3991 '(org-remember-insinuate org-remember-annotation
3992 org-remember-apply-template org-remember org-remember-handler)))
3994 (eval-and-compile
3995 (org-autoload "org-capture"
3996 '(org-capture org-capture-insert-template-here
3997 org-capture-import-remember-templates)))
3999 ;; Autoload org-clock.el
4001 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4002 (beg end))
4003 (declare-function org-clock-update-mode-line "org-clock" ())
4004 (declare-function org-resolve-clocks "org-clock"
4005 (&optional also-non-dangling-p prompt last-valid))
4006 (defvar org-clock-start-time)
4007 (defvar org-clock-marker (make-marker)
4008 "Marker recording the last clock-in.")
4009 (defvar org-clock-hd-marker (make-marker)
4010 "Marker recording the last clock-in, but the headline position.")
4011 (defvar org-clock-heading ""
4012 "The heading of the current clock entry.")
4013 (defun org-clock-is-active ()
4014 "Return non-nil if clock is currently running.
4015 The return value is actually the clock marker."
4016 (marker-buffer org-clock-marker))
4018 (eval-and-compile
4019 (org-autoload
4020 "org-clock"
4021 '(org-clock-in org-clock-out org-clock-cancel
4022 org-clock-goto org-clock-sum org-clock-display
4023 org-clock-remove-overlays org-clock-report
4024 org-clocktable-shift org-dblock-write:clocktable
4025 org-get-clocktable org-resolve-clocks)))
4027 (defun org-clock-update-time-maybe ()
4028 "If this is a CLOCK line, update it and return t.
4029 Otherwise, return nil."
4030 (interactive)
4031 (save-excursion
4032 (beginning-of-line 1)
4033 (skip-chars-forward " \t")
4034 (when (looking-at org-clock-string)
4035 (let ((re (concat "[ \t]*" org-clock-string
4036 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4037 "\\([ \t]*=>.*\\)?\\)?"))
4038 ts te h m s neg)
4039 (cond
4040 ((not (looking-at re))
4041 nil)
4042 ((not (match-end 2))
4043 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4044 (> org-clock-marker (point))
4045 (<= org-clock-marker (point-at-eol)))
4046 ;; The clock is running here
4047 (setq org-clock-start-time
4048 (apply 'encode-time
4049 (org-parse-time-string (match-string 1))))
4050 (org-clock-update-mode-line)))
4052 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4053 (end-of-line 1)
4054 (setq ts (match-string 1)
4055 te (match-string 3))
4056 (setq s (- (org-float-time
4057 (apply 'encode-time (org-parse-time-string te)))
4058 (org-float-time
4059 (apply 'encode-time (org-parse-time-string ts))))
4060 neg (< s 0)
4061 s (abs s)
4062 h (floor (/ s 3600))
4063 s (- s (* 3600 h))
4064 m (floor (/ s 60))
4065 s (- s (* 60 s)))
4066 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4067 t))))))
4069 (defun org-check-running-clock ()
4070 "Check if the current buffer contains the running clock.
4071 If yes, offer to stop it and to save the buffer with the changes."
4072 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4073 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4074 (buffer-name))))
4075 (org-clock-out)
4076 (when (y-or-n-p "Save changed buffer?")
4077 (save-buffer))))
4079 (defun org-clocktable-try-shift (dir n)
4080 "Check if this line starts a clock table, if yes, shift the time block."
4081 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4082 (org-clocktable-shift dir n)))
4084 ;; Autoload org-timer.el
4086 (eval-and-compile
4087 (org-autoload
4088 "org-timer"
4089 '(org-timer-start org-timer org-timer-item
4090 org-timer-change-times-in-region
4091 org-timer-set-timer
4092 org-timer-reset-timers
4093 org-timer-show-remaining-time)))
4095 ;; Autoload org-feed.el
4097 (eval-and-compile
4098 (org-autoload
4099 "org-feed"
4100 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4103 ;; Autoload org-indent.el
4105 ;; Define the variable already here, to make sure we have it.
4106 (defvar org-indent-mode nil
4107 "Non-nil if Org-Indent mode is enabled.
4108 Use the command `org-indent-mode' to change this variable.")
4110 (eval-and-compile
4111 (org-autoload
4112 "org-indent"
4113 '(org-indent-mode)))
4115 ;; Autoload org-mobile.el
4117 (eval-and-compile
4118 (org-autoload
4119 "org-mobile"
4120 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4122 ;; Autoload archiving code
4123 ;; The stuff that is needed for cycling and tags has to be defined here.
4125 (defgroup org-archive nil
4126 "Options concerning archiving in Org-mode."
4127 :tag "Org Archive"
4128 :group 'org-structure)
4130 (defcustom org-archive-location "%s_archive::"
4131 "The location where subtrees should be archived.
4133 The value of this variable is a string, consisting of two parts,
4134 separated by a double-colon. The first part is a filename and
4135 the second part is a headline.
4137 When the filename is omitted, archiving happens in the same file.
4138 %s in the filename will be replaced by the current file
4139 name (without the directory part). Archiving to a different file
4140 is useful to keep archived entries from contributing to the
4141 Org-mode Agenda.
4143 The archived entries will be filed as subtrees of the specified
4144 headline. When the headline is omitted, the subtrees are simply
4145 filed away at the end of the file, as top-level entries. Also in
4146 the heading you can use %s to represent the file name, this can be
4147 useful when using the same archive for a number of different files.
4149 Here are a few examples:
4150 \"%s_archive::\"
4151 If the current file is Projects.org, archive in file
4152 Projects.org_archive, as top-level trees. This is the default.
4154 \"::* Archived Tasks\"
4155 Archive in the current file, under the top-level headline
4156 \"* Archived Tasks\".
4158 \"~/org/archive.org::\"
4159 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4161 \"~/org/archive.org::* From %s\"
4162 Archive in file ~/org/archive.org (absolute path), under headlines
4163 \"From FILENAME\" where file name is the current file name.
4165 \"basement::** Finished Tasks\"
4166 Archive in file ./basement (relative path), as level 3 trees
4167 below the level 2 heading \"** Finished Tasks\".
4169 You may set this option on a per-file basis by adding to the buffer a
4170 line like
4172 #+ARCHIVE: basement::** Finished Tasks
4174 You may also define it locally for a subtree by setting an ARCHIVE property
4175 in the entry. If such a property is found in an entry, or anywhere up
4176 the hierarchy, it will be used."
4177 :group 'org-archive
4178 :type 'string)
4180 (defcustom org-archive-tag "ARCHIVE"
4181 "The tag that marks a subtree as archived.
4182 An archived subtree does not open during visibility cycling, and does
4183 not contribute to the agenda listings.
4184 After changing this, font-lock must be restarted in the relevant buffers to
4185 get the proper fontification."
4186 :group 'org-archive
4187 :group 'org-keywords
4188 :type 'string)
4190 (defcustom org-agenda-skip-archived-trees t
4191 "Non-nil means the agenda will skip any items located in archived trees.
4192 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4193 variable is no longer recommended, you should leave it at the value t.
4194 Instead, use the key `v' to cycle the archives-mode in the agenda."
4195 :group 'org-archive
4196 :group 'org-agenda-skip
4197 :type 'boolean)
4199 (defcustom org-columns-skip-archived-trees t
4200 "Non-nil means ignore archived trees when creating column view."
4201 :group 'org-archive
4202 :group 'org-properties
4203 :type 'boolean)
4205 (defcustom org-cycle-open-archived-trees nil
4206 "Non-nil means `org-cycle' will open archived trees.
4207 An archived tree is a tree marked with the tag ARCHIVE.
4208 When nil, archived trees will stay folded. You can still open them with
4209 normal outline commands like `show-all', but not with the cycling commands."
4210 :group 'org-archive
4211 :group 'org-cycle
4212 :type 'boolean)
4214 (defcustom org-sparse-tree-open-archived-trees nil
4215 "Non-nil means sparse tree construction shows matches in archived trees.
4216 When nil, matches in these trees are highlighted, but the trees are kept in
4217 collapsed state."
4218 :group 'org-archive
4219 :group 'org-sparse-trees
4220 :type 'boolean)
4222 (defun org-cycle-hide-archived-subtrees (state)
4223 "Re-hide all archived subtrees after a visibility state change."
4224 (when (and (not org-cycle-open-archived-trees)
4225 (not (memq state '(overview folded))))
4226 (save-excursion
4227 (let* ((globalp (memq state '(contents all)))
4228 (beg (if globalp (point-min) (point)))
4229 (end (if globalp (point-max) (org-end-of-subtree t))))
4230 (org-hide-archived-subtrees beg end)
4231 (goto-char beg)
4232 (if (looking-at (concat ".*:" org-archive-tag ":"))
4233 (message "%s" (substitute-command-keys
4234 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4236 (defun org-force-cycle-archived ()
4237 "Cycle subtree even if it is archived."
4238 (interactive)
4239 (setq this-command 'org-cycle)
4240 (let ((org-cycle-open-archived-trees t))
4241 (call-interactively 'org-cycle)))
4243 (defun org-hide-archived-subtrees (beg end)
4244 "Re-hide all archived subtrees after a visibility state change."
4245 (save-excursion
4246 (let* ((re (concat ":" org-archive-tag ":")))
4247 (goto-char beg)
4248 (while (re-search-forward re end t)
4249 (when (org-at-heading-p)
4250 (org-flag-subtree t)
4251 (org-end-of-subtree t))))))
4253 (defun org-flag-subtree (flag)
4254 (save-excursion
4255 (org-back-to-heading t)
4256 (outline-end-of-heading)
4257 (outline-flag-region (point)
4258 (progn (org-end-of-subtree t) (point))
4259 flag)))
4261 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4263 (eval-and-compile
4264 (org-autoload "org-archive"
4265 '(org-add-archive-files org-archive-subtree
4266 org-archive-to-archive-sibling org-toggle-archive-tag
4267 org-archive-subtree-default
4268 org-archive-subtree-default-with-confirmation)))
4270 ;; Autoload Column View Code
4272 (declare-function org-columns-number-to-string "org-colview")
4273 (declare-function org-columns-get-format-and-top-level "org-colview")
4274 (declare-function org-columns-compute "org-colview")
4276 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4277 '(org-columns-number-to-string org-columns-get-format-and-top-level
4278 org-columns-compute org-agenda-columns org-columns-remove-overlays
4279 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4281 ;; Autoload ID code
4283 (declare-function org-id-store-link "org-id")
4284 (declare-function org-id-locations-load "org-id")
4285 (declare-function org-id-locations-save "org-id")
4286 (defvar org-id-track-globally)
4287 (org-autoload "org-id"
4288 '(org-id-get-create org-id-new org-id-copy org-id-get
4289 org-id-get-with-outline-path-completion
4290 org-id-get-with-outline-drilling org-id-store-link
4291 org-id-goto org-id-find org-id-store-link))
4293 ;; Autoload Plotting Code
4295 (org-autoload "org-plot"
4296 '(org-plot/gnuplot))
4298 ;;; Variables for pre-computed regular expressions, all buffer local
4300 (defvar org-drawer-regexp nil
4301 "Matches first line of a hidden block.")
4302 (make-variable-buffer-local 'org-drawer-regexp)
4303 (defvar org-todo-regexp nil
4304 "Matches any of the TODO state keywords.")
4305 (make-variable-buffer-local 'org-todo-regexp)
4306 (defvar org-not-done-regexp nil
4307 "Matches any of the TODO state keywords except the last one.")
4308 (make-variable-buffer-local 'org-not-done-regexp)
4309 (defvar org-not-done-heading-regexp nil
4310 "Matches a TODO headline that is not done.")
4311 (make-variable-buffer-local 'org-not-done-regexp)
4312 (defvar org-todo-line-regexp nil
4313 "Matches a headline and puts TODO state into group 2 if present.")
4314 (make-variable-buffer-local 'org-todo-line-regexp)
4315 (defvar org-complex-heading-regexp nil
4316 "Matches a headline and puts everything into groups:
4317 group 1: the stars
4318 group 2: The todo keyword, maybe
4319 group 3: Priority cookie
4320 group 4: True headline
4321 group 5: Tags")
4322 (make-variable-buffer-local 'org-complex-heading-regexp)
4323 (defvar org-complex-heading-regexp-format nil
4324 "Printf format to make regexp to match an exact headline.
4325 This regexp will match the headline of any node which has the
4326 exact headline text that is put into the format, but may have any
4327 TODO state, priority and tags.")
4328 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4329 (defvar org-todo-line-tags-regexp nil
4330 "Matches a headline and puts TODO state into group 2 if present.
4331 Also put tags into group 4 if tags are present.")
4332 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4333 (defvar org-ds-keyword-length 12
4334 "Maximum length of the Deadline and SCHEDULED keywords.")
4335 (make-variable-buffer-local 'org-ds-keyword-length)
4336 (defvar org-deadline-regexp nil
4337 "Matches the DEADLINE keyword.")
4338 (make-variable-buffer-local 'org-deadline-regexp)
4339 (defvar org-deadline-time-regexp nil
4340 "Matches the DEADLINE keyword together with a time stamp.")
4341 (make-variable-buffer-local 'org-deadline-time-regexp)
4342 (defvar org-deadline-line-regexp nil
4343 "Matches the DEADLINE keyword and the rest of the line.")
4344 (make-variable-buffer-local 'org-deadline-line-regexp)
4345 (defvar org-scheduled-regexp nil
4346 "Matches the SCHEDULED keyword.")
4347 (make-variable-buffer-local 'org-scheduled-regexp)
4348 (defvar org-scheduled-time-regexp nil
4349 "Matches the SCHEDULED keyword together with a time stamp.")
4350 (make-variable-buffer-local 'org-scheduled-time-regexp)
4351 (defvar org-closed-time-regexp nil
4352 "Matches the CLOSED keyword together with a time stamp.")
4353 (make-variable-buffer-local 'org-closed-time-regexp)
4355 (defvar org-keyword-time-regexp nil
4356 "Matches any of the 4 keywords, together with the time stamp.")
4357 (make-variable-buffer-local 'org-keyword-time-regexp)
4358 (defvar org-keyword-time-not-clock-regexp nil
4359 "Matches any of the 3 keywords, together with the time stamp.")
4360 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4361 (defvar org-maybe-keyword-time-regexp nil
4362 "Matches a timestamp, possibly preceded by a keyword.")
4363 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4364 (defvar org-planning-or-clock-line-re nil
4365 "Matches a line with planning or clock info.")
4366 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4367 (defvar org-all-time-keywords nil
4368 "List of time keywords.")
4369 (make-variable-buffer-local 'org-all-time-keywords)
4371 (defconst org-plain-time-of-day-regexp
4372 (concat
4373 "\\(\\<[012]?[0-9]"
4374 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4375 "\\(--?"
4376 "\\(\\<[012]?[0-9]"
4377 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4378 "\\)?")
4379 "Regular expression to match a plain time or time range.
4380 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4381 groups carry important information:
4382 0 the full match
4383 1 the first time, range or not
4384 8 the second time, if it is a range.")
4386 (defconst org-plain-time-extension-regexp
4387 (concat
4388 "\\(\\<[012]?[0-9]"
4389 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4390 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4391 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4392 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4393 groups carry important information:
4394 0 the full match
4395 7 hours of duration
4396 9 minutes of duration")
4398 (defconst org-stamp-time-of-day-regexp
4399 (concat
4400 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4401 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4402 "\\(--?"
4403 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4404 "Regular expression to match a timestamp time or time range.
4405 After a match, the following groups carry important information:
4406 0 the full match
4407 1 date plus weekday, for back referencing to make sure both times are on the same day
4408 2 the first time, range or not
4409 4 the second time, if it is a range.")
4411 (defconst org-startup-options
4412 '(("fold" org-startup-folded t)
4413 ("overview" org-startup-folded t)
4414 ("nofold" org-startup-folded nil)
4415 ("showall" org-startup-folded nil)
4416 ("showeverything" org-startup-folded showeverything)
4417 ("content" org-startup-folded content)
4418 ("indent" org-startup-indented t)
4419 ("noindent" org-startup-indented nil)
4420 ("hidestars" org-hide-leading-stars t)
4421 ("showstars" org-hide-leading-stars nil)
4422 ("odd" org-odd-levels-only t)
4423 ("oddeven" org-odd-levels-only nil)
4424 ("align" org-startup-align-all-tables t)
4425 ("noalign" org-startup-align-all-tables nil)
4426 ("inlineimages" org-startup-with-inline-images t)
4427 ("noinlineimages" org-startup-with-inline-images nil)
4428 ("customtime" org-display-custom-times t)
4429 ("logdone" org-log-done time)
4430 ("lognotedone" org-log-done note)
4431 ("nologdone" org-log-done nil)
4432 ("lognoteclock-out" org-log-note-clock-out t)
4433 ("nolognoteclock-out" org-log-note-clock-out nil)
4434 ("logrepeat" org-log-repeat state)
4435 ("lognoterepeat" org-log-repeat note)
4436 ("nologrepeat" org-log-repeat nil)
4437 ("logreschedule" org-log-reschedule time)
4438 ("lognotereschedule" org-log-reschedule note)
4439 ("nologreschedule" org-log-reschedule nil)
4440 ("logredeadline" org-log-redeadline time)
4441 ("lognoteredeadline" org-log-redeadline note)
4442 ("nologredeadline" org-log-redeadline nil)
4443 ("logrefile" org-log-refile time)
4444 ("lognoterefile" org-log-refile note)
4445 ("nologrefile" org-log-refile nil)
4446 ("fninline" org-footnote-define-inline t)
4447 ("nofninline" org-footnote-define-inline nil)
4448 ("fnlocal" org-footnote-section nil)
4449 ("fnauto" org-footnote-auto-label t)
4450 ("fnprompt" org-footnote-auto-label nil)
4451 ("fnconfirm" org-footnote-auto-label confirm)
4452 ("fnplain" org-footnote-auto-label plain)
4453 ("fnadjust" org-footnote-auto-adjust t)
4454 ("nofnadjust" org-footnote-auto-adjust nil)
4455 ("constcgs" constants-unit-system cgs)
4456 ("constSI" constants-unit-system SI)
4457 ("noptag" org-tag-persistent-alist nil)
4458 ("hideblocks" org-hide-block-startup t)
4459 ("nohideblocks" org-hide-block-startup nil)
4460 ("beamer" org-startup-with-beamer-mode t)
4461 ("entitiespretty" org-pretty-entities t)
4462 ("entitiesplain" org-pretty-entities nil))
4463 "Variable associated with STARTUP options for org-mode.
4464 Each element is a list of three items: The startup options as written
4465 in the #+STARTUP line, the corresponding variable, and the value to
4466 set this variable to if the option is found. An optional forth element PUSH
4467 means to push this value onto the list in the variable.")
4469 (defun org-update-property-plist (key val props)
4470 "Update PROPS with KEY and VAL."
4471 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4472 (key (if appending (substring key 0 (- (length key) 1)) key))
4473 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4474 (previous (cdr (assoc key props))))
4475 (if appending
4476 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4477 (cons (cons key val) remainder))))
4479 (defconst org-block-regexp
4480 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4481 "Regular expression for hiding blocks.")
4482 (defconst org-heading-keyword-regexp-format
4483 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4484 "Printf format for a regexp matching an headline with some keyword.
4485 This regexp will match the headline of any node which has the
4486 exact keyword that is put into the format. The keyword isn't in
4487 any group by default, but the stars and the body are.")
4488 (defconst org-heading-keyword-maybe-regexp-format
4489 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4490 "Printf format for a regexp matching an headline, possibly with some keyword.
4491 This regexp can match any headline with the specified keyword, or
4492 without a keyword. The keyword isn't in any group by default,
4493 but the stars and the body are.")
4495 (defun org-set-regexps-and-options ()
4496 "Precompute regular expressions for current buffer."
4497 (when (eq major-mode 'org-mode)
4498 (org-set-local 'org-todo-kwd-alist nil)
4499 (org-set-local 'org-todo-key-alist nil)
4500 (org-set-local 'org-todo-key-trigger nil)
4501 (org-set-local 'org-todo-keywords-1 nil)
4502 (org-set-local 'org-done-keywords nil)
4503 (org-set-local 'org-todo-heads nil)
4504 (org-set-local 'org-todo-sets nil)
4505 (org-set-local 'org-todo-log-states nil)
4506 (org-set-local 'org-file-properties nil)
4507 (org-set-local 'org-file-tags nil)
4508 (let ((re (org-make-options-regexp
4509 '("CATEGORY" "TODO" "COLUMNS"
4510 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4511 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4512 "OPTIONS")
4513 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4514 (splitre "[ \t]+")
4515 (scripts org-use-sub-superscripts)
4516 kwds kws0 kwsa key log value cat arch tags const links hw dws
4517 tail sep kws1 prio props ftags drawers beamer-p
4518 ext-setup-or-nil setup-contents (start 0))
4519 (save-excursion
4520 (save-restriction
4521 (widen)
4522 (goto-char (point-min))
4523 (while (or (and ext-setup-or-nil
4524 (string-match re ext-setup-or-nil start)
4525 (setq start (match-end 0)))
4526 (and (setq ext-setup-or-nil nil start 0)
4527 (re-search-forward re nil t)))
4528 (setq key (upcase (match-string 1 ext-setup-or-nil))
4529 value (org-match-string-no-properties 2 ext-setup-or-nil))
4530 (if (stringp value) (setq value (org-trim value)))
4531 (cond
4532 ((equal key "CATEGORY")
4533 (setq cat value))
4534 ((member key '("SEQ_TODO" "TODO"))
4535 (push (cons 'sequence (org-split-string value splitre)) kwds))
4536 ((equal key "TYP_TODO")
4537 (push (cons 'type (org-split-string value splitre)) kwds))
4538 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4539 ;; general TODO-like setup
4540 (push (cons (intern (downcase (match-string 1 key)))
4541 (org-split-string value splitre)) kwds))
4542 ((equal key "TAGS")
4543 (setq tags (append tags (if tags '("\\n") nil)
4544 (org-split-string value splitre))))
4545 ((equal key "COLUMNS")
4546 (org-set-local 'org-columns-default-format value))
4547 ((equal key "LINK")
4548 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4549 (push (cons (match-string 1 value)
4550 (org-trim (match-string 2 value)))
4551 links)))
4552 ((equal key "PRIORITIES")
4553 (setq prio (org-split-string value " +")))
4554 ((equal key "PROPERTY")
4555 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4556 (setq props (org-update-property-plist (match-string 1 value)
4557 (match-string 2 value)
4558 props))))
4559 ((equal key "FILETAGS")
4560 (when (string-match "\\S-" value)
4561 (setq ftags
4562 (append
4563 ftags
4564 (apply 'append
4565 (mapcar (lambda (x) (org-split-string x ":"))
4566 (org-split-string value)))))))
4567 ((equal key "DRAWERS")
4568 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4569 ((equal key "CONSTANTS")
4570 (setq const (append const (org-split-string value splitre))))
4571 ((equal key "STARTUP")
4572 (let ((opts (org-split-string value splitre))
4573 l var val)
4574 (while (setq l (pop opts))
4575 (when (setq l (assoc l org-startup-options))
4576 (setq var (nth 1 l) val (nth 2 l))
4577 (if (not (nth 3 l))
4578 (set (make-local-variable var) val)
4579 (if (not (listp (symbol-value var)))
4580 (set (make-local-variable var) nil))
4581 (set (make-local-variable var) (symbol-value var))
4582 (add-to-list var val))))))
4583 ((equal key "ARCHIVE")
4584 (setq arch value)
4585 (remove-text-properties 0 (length arch)
4586 '(face t fontified t) arch))
4587 ((equal key "LATEX_CLASS")
4588 (setq beamer-p (equal value "beamer")))
4589 ((equal key "OPTIONS")
4590 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4591 (setq scripts (read (match-string 2 value)))))
4592 ((equal key "SETUPFILE")
4593 (setq setup-contents (org-file-contents
4594 (expand-file-name
4595 (org-remove-double-quotes value))
4596 'noerror))
4597 (if (not ext-setup-or-nil)
4598 (setq ext-setup-or-nil setup-contents start 0)
4599 (setq ext-setup-or-nil
4600 (concat (substring ext-setup-or-nil 0 start)
4601 "\n" setup-contents "\n"
4602 (substring ext-setup-or-nil start)))))))
4603 ;; search for property blocks
4604 (goto-char (point-min))
4605 (while (re-search-forward org-block-regexp nil t)
4606 (when (equal "PROPERTY" (upcase (match-string 1)))
4607 (setq value (replace-regexp-in-string
4608 "[\n\r]" " " (match-string 4)))
4609 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4610 (setq props (org-update-property-plist (match-string 1 value)
4611 (match-string 2 value)
4612 props)))))))
4613 (org-set-local 'org-use-sub-superscripts scripts)
4614 (when cat
4615 (org-set-local 'org-category (intern cat))
4616 (push (cons "CATEGORY" cat) props))
4617 (when prio
4618 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4619 (setq prio (mapcar 'string-to-char prio))
4620 (org-set-local 'org-highest-priority (nth 0 prio))
4621 (org-set-local 'org-lowest-priority (nth 1 prio))
4622 (org-set-local 'org-default-priority (nth 2 prio)))
4623 (and props (org-set-local 'org-file-properties (nreverse props)))
4624 (and ftags (org-set-local 'org-file-tags
4625 (mapcar 'org-add-prop-inherited ftags)))
4626 (and drawers (org-set-local 'org-drawers drawers))
4627 (and arch (org-set-local 'org-archive-location arch))
4628 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4629 ;; Process the TODO keywords
4630 (unless kwds
4631 ;; Use the global values as if they had been given locally.
4632 (setq kwds (default-value 'org-todo-keywords))
4633 (if (stringp (car kwds))
4634 (setq kwds (list (cons org-todo-interpretation
4635 (default-value 'org-todo-keywords)))))
4636 (setq kwds (reverse kwds)))
4637 (setq kwds (nreverse kwds))
4638 (let (inter kws kw)
4639 (while (setq kws (pop kwds))
4640 (let ((kws (or
4641 (run-hook-with-args-until-success
4642 'org-todo-setup-filter-hook kws)
4643 kws)))
4644 (setq inter (pop kws) sep (member "|" kws)
4645 kws0 (delete "|" (copy-sequence kws))
4646 kwsa nil
4647 kws1 (mapcar
4648 (lambda (x)
4649 ;; 1 2
4650 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4651 (progn
4652 (setq kw (match-string 1 x)
4653 key (and (match-end 2) (match-string 2 x))
4654 log (org-extract-log-state-settings x))
4655 (push (cons kw (and key (string-to-char key))) kwsa)
4656 (and log (push log org-todo-log-states))
4658 (error "Invalid TODO keyword %s" x)))
4659 kws0)
4660 kwsa (if kwsa (append '((:startgroup))
4661 (nreverse kwsa)
4662 '((:endgroup))))
4663 hw (car kws1)
4664 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4665 tail (list inter hw (car dws) (org-last dws))))
4666 (add-to-list 'org-todo-heads hw 'append)
4667 (push kws1 org-todo-sets)
4668 (setq org-done-keywords (append org-done-keywords dws nil))
4669 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4670 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4671 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4672 (setq org-todo-sets (nreverse org-todo-sets)
4673 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4674 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4675 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4676 ;; Process the constants
4677 (when const
4678 (let (e cst)
4679 (while (setq e (pop const))
4680 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4681 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4682 (setq org-table-formula-constants-local cst)))
4684 ;; Process the tags.
4685 (when tags
4686 (let (e tgs)
4687 (while (setq e (pop tags))
4688 (cond
4689 ((equal e "{") (push '(:startgroup) tgs))
4690 ((equal e "}") (push '(:endgroup) tgs))
4691 ((equal e "\\n") (push '(:newline) tgs))
4692 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4693 (push (cons (match-string 1 e)
4694 (string-to-char (match-string 2 e)))
4695 tgs))
4696 (t (push (list e) tgs))))
4697 (org-set-local 'org-tag-alist nil)
4698 (while (setq e (pop tgs))
4699 (or (and (stringp (car e))
4700 (assoc (car e) org-tag-alist))
4701 (push e org-tag-alist)))))
4703 ;; Compute the regular expressions and other local variables.
4704 ;; Using `org-outline-regexp-bol' would complicate them much,
4705 ;; because of the fixed white space at the end of that string.
4706 (if (not org-done-keywords)
4707 (setq org-done-keywords (and org-todo-keywords-1
4708 (list (org-last org-todo-keywords-1)))))
4709 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4710 (length org-scheduled-string)
4711 (length org-clock-string)
4712 (length org-closed-string)))
4713 org-drawer-regexp
4714 (concat "^[ \t]*:\\("
4715 (mapconcat 'regexp-quote org-drawers "\\|")
4716 "\\):[ \t]*$")
4717 org-not-done-keywords
4718 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4719 org-todo-regexp
4720 (concat "\\("
4721 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4722 "\\)")
4723 org-not-done-regexp
4724 (concat "\\("
4725 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4726 "\\)")
4727 org-not-done-heading-regexp
4728 (format org-heading-keyword-regexp-format org-not-done-regexp)
4729 org-todo-line-regexp
4730 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4731 org-complex-heading-regexp
4732 (concat "^\\(\\*+\\)"
4733 "\\(?: +" org-todo-regexp "\\)?"
4734 "\\(?: +\\(\\[#.\\]\\)\\)?"
4735 "\\(?: +\\(.*?\\)\\)?"
4736 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4737 "[ \t]*$")
4738 org-complex-heading-regexp-format
4739 (concat "^\\(\\*+\\)"
4740 "\\(?: +" org-todo-regexp "\\)?"
4741 "\\(?: +\\(\\[#.\\]\\)\\)?"
4742 "\\(?: +"
4743 ;; Stats cookies can be stuck to body.
4744 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4745 "\\(%s\\)"
4746 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4747 "\\)"
4748 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4749 "[ \t]*$")
4750 org-todo-line-tags-regexp
4751 (concat "^\\(\\*+\\)"
4752 "\\(?: +" org-todo-regexp "\\)?"
4753 "\\(?: +\\(.*?\\)\\)?"
4754 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4755 "[ \t]*$")
4756 org-deadline-regexp (concat "\\<" org-deadline-string)
4757 org-deadline-time-regexp
4758 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4759 org-deadline-line-regexp
4760 (concat "\\<\\(" org-deadline-string "\\).*")
4761 org-scheduled-regexp
4762 (concat "\\<" org-scheduled-string)
4763 org-scheduled-time-regexp
4764 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4765 org-closed-time-regexp
4766 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4767 org-keyword-time-regexp
4768 (concat "\\<\\(" org-scheduled-string
4769 "\\|" org-deadline-string
4770 "\\|" org-closed-string
4771 "\\|" org-clock-string "\\)"
4772 " *[[<]\\([^]>]+\\)[]>]")
4773 org-keyword-time-not-clock-regexp
4774 (concat "\\<\\(" org-scheduled-string
4775 "\\|" org-deadline-string
4776 "\\|" org-closed-string
4777 "\\)"
4778 " *[[<]\\([^]>]+\\)[]>]")
4779 org-maybe-keyword-time-regexp
4780 (concat "\\(\\<\\(" org-scheduled-string
4781 "\\|" org-deadline-string
4782 "\\|" org-closed-string
4783 "\\|" org-clock-string "\\)\\)?"
4784 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4785 org-planning-or-clock-line-re
4786 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4787 "\\|" org-deadline-string
4788 "\\|" org-closed-string "\\|" org-clock-string
4789 "\\)\\>\\)")
4790 org-all-time-keywords
4791 (mapcar (lambda (w) (substring w 0 -1))
4792 (list org-scheduled-string org-deadline-string
4793 org-clock-string org-closed-string))
4795 (org-compute-latex-and-specials-regexp)
4796 (org-set-font-lock-defaults))))
4798 (defun org-file-contents (file &optional noerror)
4799 "Return the contents of FILE, as a string."
4800 (if (or (not file)
4801 (not (file-readable-p file)))
4802 (if noerror
4803 (progn
4804 (message "Cannot read file \"%s\"" file)
4805 (ding) (sit-for 2)
4807 (error "Cannot read file \"%s\"" file))
4808 (with-temp-buffer
4809 (insert-file-contents file)
4810 (buffer-string))))
4812 (defun org-extract-log-state-settings (x)
4813 "Extract the log state setting from a TODO keyword string.
4814 This will extract info from a string like \"WAIT(w@/!)\"."
4815 (let (kw key log1 log2)
4816 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4817 (setq kw (match-string 1 x)
4818 key (and (match-end 2) (match-string 2 x))
4819 log1 (and (match-end 3) (match-string 3 x))
4820 log2 (and (match-end 4) (match-string 4 x)))
4821 (and (or log1 log2)
4822 (list kw
4823 (and log1 (if (equal log1 "!") 'time 'note))
4824 (and log2 (if (equal log2 "!") 'time 'note)))))))
4826 (defun org-remove-keyword-keys (list)
4827 "Remove a pair of parenthesis at the end of each string in LIST."
4828 (mapcar (lambda (x)
4829 (if (string-match "(.*)$" x)
4830 (substring x 0 (match-beginning 0))
4832 list))
4834 (defun org-assign-fast-keys (alist)
4835 "Assign fast keys to a keyword-key alist.
4836 Respect keys that are already there."
4837 (let (new e (alt ?0))
4838 (while (setq e (pop alist))
4839 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4840 (cdr e)) ;; Key already assigned.
4841 (push e new)
4842 (let ((clist (string-to-list (downcase (car e))))
4843 (used (append new alist)))
4844 (when (= (car clist) ?@)
4845 (pop clist))
4846 (while (and clist (rassoc (car clist) used))
4847 (pop clist))
4848 (unless clist
4849 (while (rassoc alt used)
4850 (incf alt)))
4851 (push (cons (car e) (or (car clist) alt)) new))))
4852 (nreverse new)))
4854 ;;; Some variables used in various places
4856 (defvar org-window-configuration nil
4857 "Used in various places to store a window configuration.")
4858 (defvar org-selected-window nil
4859 "Used in various places to store a window configuration.")
4860 (defvar org-finish-function nil
4861 "Function to be called when `C-c C-c' is used.
4862 This is for getting out of special buffers like remember.")
4865 ;; FIXME: Occasionally check by commenting these, to make sure
4866 ;; no other functions uses these, forgetting to let-bind them.
4867 (defvar entry)
4868 (defvar org-last-state)
4869 (defvar date)
4871 ;; Defined somewhere in this file, but used before definition.
4872 (defvar org-entities) ;; defined in org-entities.el
4873 (defvar org-struct-menu)
4874 (defvar org-org-menu)
4875 (defvar org-tbl-menu)
4877 ;;;; Define the Org-mode
4879 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4880 (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"))
4883 ;; We use a before-change function to check if a table might need
4884 ;; an update.
4885 (defvar org-table-may-need-update t
4886 "Indicates that a table might need an update.
4887 This variable is set by `org-before-change-function'.
4888 `org-table-align' sets it back to nil.")
4889 (defun org-before-change-function (beg end)
4890 "Every change indicates that a table might need an update."
4891 (setq org-table-may-need-update t))
4892 (defvar org-mode-map)
4893 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4894 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4895 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4896 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4897 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4898 (defvar org-table-buffer-is-an nil)
4900 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4901 ;; some places -- e.g. see the macro org-with-limited-levels.
4903 ;; In Org buffers, the value of `outline-regexp' is that of
4904 ;; `org-outline-regexp'. The only function still directly relying on
4905 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4906 ;; job when `orgstruct-mode' is active.
4907 (defvar org-outline-regexp "\\*+ "
4908 "Regexp to match Org headlines.")
4909 (defconst org-outline-regexp-bol "^\\*+ "
4910 "Regexp to match Org headlines.
4911 This is similar to `org-outline-regexp' but additionally makes
4912 sure that we are at the beginning of the line.")
4914 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4915 "Matches an headline, putting stars and text into groups.
4916 Stars are put in group 1 and the trimmed body in group 2.")
4918 (defvar bidi-paragraph-direction)
4919 (defvar buffer-face-mode-face)
4921 ;;;###autoload
4922 (define-derived-mode org-mode outline-mode "Org"
4923 "Outline-based notes management and organizer, alias
4924 \"Carsten's outline-mode for keeping track of everything.\"
4926 Org-mode develops organizational tasks around a NOTES file which
4927 contains information about projects as plain text. Org-mode is
4928 implemented on top of outline-mode, which is ideal to keep the content
4929 of large files well structured. It supports ToDo items, deadlines and
4930 time stamps, which magically appear in the diary listing of the Emacs
4931 calendar. Tables are easily created with a built-in table editor.
4932 Plain text URL-like links connect to websites, emails (VM), Usenet
4933 messages (Gnus), BBDB entries, and any files related to the project.
4934 For printing and sharing of notes, an Org-mode file (or a part of it)
4935 can be exported as a structured ASCII or HTML file.
4937 The following commands are available:
4939 \\{org-mode-map}"
4941 ;; Get rid of Outline menus, they are not needed
4942 ;; Need to do this here because define-derived-mode sets up
4943 ;; the keymap so late. Still, it is a waste to call this each time
4944 ;; we switch another buffer into org-mode.
4945 (if (featurep 'xemacs)
4946 (when (boundp 'outline-mode-menu-heading)
4947 ;; Assume this is Greg's port, it uses easymenu
4948 (easy-menu-remove outline-mode-menu-heading)
4949 (easy-menu-remove outline-mode-menu-show)
4950 (easy-menu-remove outline-mode-menu-hide))
4951 (define-key org-mode-map [menu-bar headings] 'undefined)
4952 (define-key org-mode-map [menu-bar hide] 'undefined)
4953 (define-key org-mode-map [menu-bar show] 'undefined))
4955 (org-load-modules-maybe)
4956 (easy-menu-add org-org-menu)
4957 (easy-menu-add org-tbl-menu)
4958 (org-install-agenda-files-menu)
4959 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4960 (add-to-invisibility-spec '(org-cwidth))
4961 (add-to-invisibility-spec '(org-hide-block . t))
4962 (when (featurep 'xemacs)
4963 (org-set-local 'line-move-ignore-invisible t))
4964 (org-set-local 'outline-regexp org-outline-regexp)
4965 (org-set-local 'outline-level 'org-outline-level)
4966 (setq bidi-paragraph-direction 'left-to-right)
4967 (when (and org-ellipsis
4968 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4969 (fboundp 'make-glyph-code))
4970 (unless org-display-table
4971 (setq org-display-table (make-display-table)))
4972 (set-display-table-slot
4973 org-display-table 4
4974 (vconcat (mapcar
4975 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4976 org-ellipsis)))
4977 (if (stringp org-ellipsis) org-ellipsis "..."))))
4978 (setq buffer-display-table org-display-table))
4979 (org-set-regexps-and-options)
4980 (when (and org-tag-faces (not org-tags-special-faces-re))
4981 ;; tag faces set outside customize.... force initialization.
4982 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4983 ;; Calc embedded
4984 (org-set-local 'calc-embedded-open-mode "# ")
4985 (modify-syntax-entry ?@ "w")
4986 (if org-startup-truncated (setq truncate-lines t))
4987 (org-set-local 'font-lock-unfontify-region-function
4988 'org-unfontify-region)
4989 ;; Activate before-change-function
4990 (org-set-local 'org-table-may-need-update t)
4991 (org-add-hook 'before-change-functions 'org-before-change-function nil
4992 'local)
4993 ;; Check for running clock before killing a buffer
4994 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4995 ;; Paragraphs and auto-filling
4996 (org-set-autofill-regexps)
4997 (setq indent-line-function 'org-indent-line-function)
4998 (org-update-radio-target-regexp)
4999 ;; Beginning/end of defun
5000 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5001 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5002 ;; Next error for sparse trees
5003 (org-set-local 'next-error-function 'org-occur-next-match)
5004 ;; Make sure dependence stuff works reliably, even for users who set it
5005 ;; too late :-(
5006 (if org-enforce-todo-dependencies
5007 (add-hook 'org-blocker-hook
5008 'org-block-todo-from-children-or-siblings-or-parent)
5009 (remove-hook 'org-blocker-hook
5010 'org-block-todo-from-children-or-siblings-or-parent))
5011 (if org-enforce-todo-checkbox-dependencies
5012 (add-hook 'org-blocker-hook
5013 'org-block-todo-from-checkboxes)
5014 (remove-hook 'org-blocker-hook
5015 'org-block-todo-from-checkboxes))
5017 ;; Comment characters
5018 (org-set-local 'comment-start "#")
5019 (org-set-local 'comment-padding " ")
5021 ;; Align options lines
5022 (org-set-local
5023 'align-mode-rules-list
5024 '((org-in-buffer-settings
5025 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5026 (modes . '(org-mode)))))
5028 ;; Imenu
5029 (org-set-local 'imenu-create-index-function
5030 'org-imenu-get-tree)
5032 ;; Make isearch reveal context
5033 (if (or (featurep 'xemacs)
5034 (not (boundp 'outline-isearch-open-invisible-function)))
5035 ;; Emacs 21 and XEmacs make use of the hook
5036 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5037 ;; Emacs 22 deals with this through a special variable
5038 (org-set-local 'outline-isearch-open-invisible-function
5039 (lambda (&rest ignore) (org-show-context 'isearch))))
5041 ;; Turn on org-beamer-mode?
5042 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5044 ;; Setup the pcomplete hooks
5045 (set (make-local-variable 'pcomplete-command-completion-function)
5046 'org-pcomplete-initial)
5047 (set (make-local-variable 'pcomplete-command-name-function)
5048 'org-command-at-point)
5049 (set (make-local-variable 'pcomplete-default-completion-function)
5050 'ignore)
5051 (set (make-local-variable 'pcomplete-parse-arguments-function)
5052 'org-parse-arguments)
5053 (set (make-local-variable 'pcomplete-termination-string) "")
5054 (when (>= emacs-major-version 23)
5055 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5057 ;; If empty file that did not turn on org-mode automatically, make it to.
5058 (if (and org-insert-mode-line-in-empty-file
5059 (org-called-interactively-p 'any)
5060 (= (point-min) (point-max)))
5061 (insert "# -*- mode: org -*-\n\n"))
5062 (unless org-inhibit-startup
5063 (when org-startup-align-all-tables
5064 (let ((bmp (buffer-modified-p)))
5065 (org-table-map-tables 'org-table-align 'quietly)
5066 (set-buffer-modified-p bmp)))
5067 (when org-startup-with-inline-images
5068 (org-display-inline-images))
5069 (when org-startup-indented
5070 (require 'org-indent)
5071 (org-indent-mode 1))
5072 (unless org-inhibit-startup-visibility-stuff
5073 (org-set-startup-visibility))))
5075 (when (fboundp 'abbrev-table-put)
5076 (abbrev-table-put org-mode-abbrev-table
5077 :parents (list text-mode-abbrev-table)))
5079 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5081 (defun org-current-time ()
5082 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5083 (if (> (car org-time-stamp-rounding-minutes) 1)
5084 (let ((r (car org-time-stamp-rounding-minutes))
5085 (time (decode-time)))
5086 (apply 'encode-time
5087 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5088 (nthcdr 2 time))))
5089 (current-time)))
5091 (defun org-today ()
5092 "Return today date, considering `org-extend-today-until'."
5093 (time-to-days
5094 (time-subtract (current-time)
5095 (list 0 (* 3600 org-extend-today-until) 0))))
5097 ;;;; Font-Lock stuff, including the activators
5099 (defvar org-mouse-map (make-sparse-keymap))
5100 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5101 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5102 (when org-mouse-1-follows-link
5103 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5104 (when org-tab-follows-link
5105 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5106 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5108 (require 'font-lock)
5110 (defconst org-non-link-chars "]\t\n\r<>")
5111 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5112 "shell" "elisp" "doi" "message"))
5113 (defvar org-link-types-re nil
5114 "Matches a link that has a url-like prefix like \"http:\"")
5115 (defvar org-link-re-with-space nil
5116 "Matches a link with spaces, optional angular brackets around it.")
5117 (defvar org-link-re-with-space2 nil
5118 "Matches a link with spaces, optional angular brackets around it.")
5119 (defvar org-link-re-with-space3 nil
5120 "Matches a link with spaces, only for internal part in bracket links.")
5121 (defvar org-angle-link-re nil
5122 "Matches link with angular brackets, spaces are allowed.")
5123 (defvar org-plain-link-re nil
5124 "Matches plain link, without spaces.")
5125 (defvar org-bracket-link-regexp nil
5126 "Matches a link in double brackets.")
5127 (defvar org-bracket-link-analytic-regexp nil
5128 "Regular expression used to analyze links.
5129 Here is what the match groups contain after a match:
5130 1: http:
5131 2: http
5132 3: path
5133 4: [desc]
5134 5: desc")
5135 (defvar org-bracket-link-analytic-regexp++ nil
5136 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5137 (defvar org-any-link-re nil
5138 "Regular expression matching any link.")
5140 (defcustom org-match-sexp-depth 3
5141 "Number of stacked braces for sub/superscript matching.
5142 This has to be set before loading org.el to be effective."
5143 :group 'org-export-translation ; ??????????????????????????/
5144 :type 'integer)
5146 (defun org-create-multibrace-regexp (left right n)
5147 "Create a regular expression which will match a balanced sexp.
5148 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5149 as single character strings.
5150 The regexp returned will match the entire expression including the
5151 delimiters. It will also define a single group which contains the
5152 match except for the outermost delimiters. The maximum depth of
5153 stacked delimiters is N. Escaping delimiters is not possible."
5154 (let* ((nothing (concat "[^" left right "]*?"))
5155 (or "\\|")
5156 (re nothing)
5157 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5158 (while (> n 1)
5159 (setq n (1- n)
5160 re (concat re or next)
5161 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5162 (concat left "\\(" re "\\)" right)))
5164 (defvar org-match-substring-regexp
5165 (concat
5166 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5167 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5168 "\\|"
5169 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5170 "\\|"
5171 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5172 "The regular expression matching a sub- or superscript.")
5174 (defvar org-match-substring-with-braces-regexp
5175 (concat
5176 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5177 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5178 "\\)")
5179 "The regular expression matching a sub- or superscript, forcing braces.")
5181 (defun org-make-link-regexps ()
5182 "Update the link regular expressions.
5183 This should be called after the variable `org-link-types' has changed."
5184 (setq org-link-types-re
5185 (concat
5186 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5187 org-link-re-with-space
5188 (concat
5189 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5190 "\\([^" org-non-link-chars " ]"
5191 "[^" org-non-link-chars "]*"
5192 "[^" org-non-link-chars " ]\\)>?")
5193 org-link-re-with-space2
5194 (concat
5195 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5196 "\\([^" org-non-link-chars " ]"
5197 "[^\t\n\r]*"
5198 "[^" org-non-link-chars " ]\\)>?")
5199 org-link-re-with-space3
5200 (concat
5201 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5202 "\\([^" org-non-link-chars " ]"
5203 "[^\t\n\r]*\\)")
5204 org-angle-link-re
5205 (concat
5206 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5207 "\\([^" org-non-link-chars " ]"
5208 "[^" org-non-link-chars "]*"
5209 "\\)>")
5210 org-plain-link-re
5211 (concat
5212 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5214 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5215 org-bracket-link-regexp
5216 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5217 org-bracket-link-analytic-regexp
5218 (concat
5219 "\\[\\["
5220 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5221 "\\([^]]+\\)"
5222 "\\]"
5223 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5224 "\\]")
5225 org-bracket-link-analytic-regexp++
5226 (concat
5227 "\\[\\["
5228 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5229 "\\([^]]+\\)"
5230 "\\]"
5231 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5232 "\\]")
5233 org-any-link-re
5234 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5235 org-angle-link-re "\\)\\|\\("
5236 org-plain-link-re "\\)")))
5238 (org-make-link-regexps)
5240 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5241 "Regular expression for fast time stamp matching.")
5242 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5243 "Regular expression for fast time stamp matching.")
5244 (defconst org-ts-regexp0
5245 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5246 "Regular expression matching time strings for analysis.
5247 This one does not require the space after the date, so it can be used
5248 on a string that terminates immediately after the date.")
5249 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5250 "Regular expression matching time strings for analysis.")
5251 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5252 "Regular expression matching time stamps, with groups.")
5253 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5254 "Regular expression matching time stamps (also [..]), with groups.")
5255 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5256 "Regular expression matching a time stamp range.")
5257 (defconst org-tr-regexp-both
5258 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5259 "Regular expression matching a time stamp range.")
5260 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5261 org-ts-regexp "\\)?")
5262 "Regular expression matching a time stamp or time stamp range.")
5263 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5264 org-ts-regexp-both "\\)?")
5265 "Regular expression matching a time stamp or time stamp range.
5266 The time stamps may be either active or inactive.")
5268 (defvar org-emph-face nil)
5270 (defun org-do-emphasis-faces (limit)
5271 "Run through the buffer and add overlays to emphasized strings."
5272 (let (rtn a)
5273 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5274 (if (not (= (char-after (match-beginning 3))
5275 (char-after (match-beginning 4))))
5276 (progn
5277 (setq rtn t)
5278 (setq a (assoc (match-string 3) org-emphasis-alist))
5279 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5280 'face
5281 (nth 1 a))
5282 (and (nth 4 a)
5283 (org-remove-flyspell-overlays-in
5284 (match-beginning 0) (match-end 0)))
5285 (add-text-properties (match-beginning 2) (match-end 2)
5286 '(font-lock-multiline t org-emphasis t))
5287 (when org-hide-emphasis-markers
5288 (add-text-properties (match-end 4) (match-beginning 5)
5289 '(invisible org-link))
5290 (add-text-properties (match-beginning 3) (match-end 3)
5291 '(invisible org-link)))))
5292 (backward-char 1))
5293 rtn))
5295 (defun org-emphasize (&optional char)
5296 "Insert or change an emphasis, i.e. a font like bold or italic.
5297 If there is an active region, change that region to a new emphasis.
5298 If there is no region, just insert the marker characters and position
5299 the cursor between them.
5300 CHAR should be either the marker character, or the first character of the
5301 HTML tag associated with that emphasis. If CHAR is a space, the means
5302 to remove the emphasis of the selected region.
5303 If char is not given (for example in an interactive call) it
5304 will be prompted for."
5305 (interactive)
5306 (let ((eal org-emphasis-alist) e det
5307 (erc org-emphasis-regexp-components)
5308 (prompt "")
5309 (string "") beg end move tag c s)
5310 (if (org-region-active-p)
5311 (setq beg (region-beginning) end (region-end)
5312 string (buffer-substring beg end))
5313 (setq move t))
5315 (while (setq e (pop eal))
5316 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5317 c (aref tag 0))
5318 (push (cons c (string-to-char (car e))) det)
5319 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5320 (substring tag 1)))))
5321 (setq det (nreverse det))
5322 (unless char
5323 (message "%s" (concat "Emphasis marker or tag:" prompt))
5324 (setq char (read-char-exclusive)))
5325 (setq char (or (cdr (assoc char det)) char))
5326 (if (equal char ?\ )
5327 (setq s "" move nil)
5328 (unless (assoc (char-to-string char) org-emphasis-alist)
5329 (error "No such emphasis marker: \"%c\"" char))
5330 (setq s (char-to-string char)))
5331 (while (and (> (length string) 1)
5332 (equal (substring string 0 1) (substring string -1))
5333 (assoc (substring string 0 1) org-emphasis-alist))
5334 (setq string (substring string 1 -1)))
5335 (setq string (concat s string s))
5336 (if beg (delete-region beg end))
5337 (unless (or (bolp)
5338 (string-match (concat "[" (nth 0 erc) "\n]")
5339 (char-to-string (char-before (point)))))
5340 (insert " "))
5341 (unless (or (eobp)
5342 (string-match (concat "[" (nth 1 erc) "\n]")
5343 (char-to-string (char-after (point)))))
5344 (insert " ") (backward-char 1))
5345 (insert string)
5346 (and move (backward-char 1))))
5348 (defconst org-nonsticky-props
5349 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5351 (defsubst org-rear-nonsticky-at (pos)
5352 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5354 (defun org-activate-plain-links (limit)
5355 "Run through the buffer and add overlays to links."
5356 (catch 'exit
5357 (let (f)
5358 (if (re-search-forward org-plain-link-re limit t)
5359 (progn
5360 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5361 (setq f (get-text-property (match-beginning 0) 'face))
5362 (if (or (eq f 'org-tag)
5363 (and (listp f) (memq 'org-tag f)))
5365 (add-text-properties (match-beginning 0) (match-end 0)
5366 (list 'mouse-face 'highlight
5367 'face 'org-link
5368 'keymap org-mouse-map))
5369 (org-rear-nonsticky-at (match-end 0)))
5370 t)))))
5372 (defun org-activate-code (limit)
5373 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5374 (progn
5375 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5376 (remove-text-properties (match-beginning 0) (match-end 0)
5377 '(display t invisible t intangible t))
5378 t)))
5380 (defcustom org-src-fontify-natively nil
5381 "When non-nil, fontify code in code blocks."
5382 :type 'boolean
5383 :version "24.1"
5384 :group 'org-appearance
5385 :group 'org-babel)
5387 (defun org-fontify-meta-lines-and-blocks (limit)
5388 (condition-case nil
5389 (org-fontify-meta-lines-and-blocks-1 limit)
5390 (error (message "org-mode fontification error"))))
5392 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5393 "Fontify #+ lines and blocks, in the correct ways."
5394 (let ((case-fold-search t))
5395 (if (re-search-forward
5396 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5397 limit t)
5398 (let ((beg (match-beginning 0))
5399 (block-start (match-end 0))
5400 (block-end nil)
5401 (lang (match-string 7))
5402 (beg1 (line-beginning-position 2))
5403 (dc1 (downcase (match-string 2)))
5404 (dc3 (downcase (match-string 3)))
5405 end end1 quoting block-type ovl)
5406 (cond
5407 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5408 ;; a single line of backend-specific content
5409 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5410 (remove-text-properties (match-beginning 0) (match-end 0)
5411 '(display t invisible t intangible t))
5412 (add-text-properties (match-beginning 1) (match-end 3)
5413 '(font-lock-fontified t face org-meta-line))
5414 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5415 '(font-lock-fontified t face org-block))
5416 ; for backend-specific code
5418 ((and (match-end 4) (equal dc3 "begin"))
5419 ;; Truly a block
5420 (setq block-type (downcase (match-string 5))
5421 quoting (member block-type org-protecting-blocks))
5422 (when (re-search-forward
5423 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5424 nil t) ;; on purpose, we look further than LIMIT
5425 (setq end (min (point-max) (match-end 0))
5426 end1 (min (point-max) (1- (match-beginning 0))))
5427 (setq block-end (match-beginning 0))
5428 (when quoting
5429 (remove-text-properties beg end
5430 '(display t invisible t intangible t)))
5431 (add-text-properties
5432 beg end
5433 '(font-lock-fontified t font-lock-multiline t))
5434 (add-text-properties beg beg1 '(face org-meta-line))
5435 (add-text-properties end1 (min (point-max) (1+ end))
5436 '(face org-meta-line)) ; for end_src
5437 (cond
5438 ((and lang (not (string= lang "")) org-src-fontify-natively)
5439 (org-src-font-lock-fontify-block lang block-start block-end)
5440 ;; remove old background overlays
5441 (mapc (lambda (ov)
5442 (if (eq (overlay-get ov 'face) 'org-block-background)
5443 (delete-overlay ov)))
5444 (overlays-at (/ (+ beg1 block-end) 2)))
5445 ;; add a background overlay
5446 (setq ovl (make-overlay beg1 block-end))
5447 (overlay-put ovl 'face 'org-block-background)
5448 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5449 (quoting
5450 (add-text-properties beg1 (min (point-max) (1+ end1))
5451 '(face org-block))) ; end of source block
5452 ((not org-fontify-quote-and-verse-blocks))
5453 ((string= block-type "quote")
5454 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5455 ((string= block-type "verse")
5456 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5457 (add-text-properties beg beg1 '(face org-block-begin-line))
5458 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5459 '(face org-block-end-line))
5461 ((member dc1 '("title:" "author:" "email:" "date:"))
5462 (add-text-properties
5463 beg (match-end 3)
5464 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5465 '(font-lock-fontified t invisible t)
5466 '(font-lock-fontified t face org-document-info-keyword)))
5467 (add-text-properties
5468 (match-beginning 6) (match-end 6)
5469 (if (string-equal dc1 "title:")
5470 '(font-lock-fontified t face org-document-title)
5471 '(font-lock-fontified t face org-document-info))))
5472 ((not (member (char-after beg) '(?\ ?\t)))
5473 ;; just any other in-buffer setting, but not indented
5474 (add-text-properties
5475 beg (match-end 0)
5476 '(font-lock-fontified t face org-meta-line))
5478 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5479 "orgtbl:" "tblfm:" "tblname:" "results:"
5480 "call:" "header:" "headers:" "name:"))
5481 (and (match-end 4) (equal dc3 "attr")))
5482 (add-text-properties
5483 beg (match-end 0)
5484 '(font-lock-fontified t face org-meta-line))
5486 ((member dc3 '(" " ""))
5487 (add-text-properties
5488 beg (match-end 0)
5489 '(font-lock-fontified t face font-lock-comment-face)))
5490 (t nil))))))
5492 (defun org-strip-protective-commas (beg end)
5493 "Strip protective commas between BEG and END in the current buffer."
5494 (interactive "r")
5495 (save-excursion
5496 (save-match-data
5497 (goto-char beg)
5498 (let ((front-line (save-excursion
5499 (re-search-forward
5500 "[^[:space:]]" end t)
5501 (goto-char (match-beginning 0))
5502 (current-column))))
5503 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5504 (goto-char (match-beginning 1))
5505 (when (= (current-column) front-line)
5506 (replace-match "" nil nil nil 1)))))))
5508 (defun org-activate-angle-links (limit)
5509 "Run through the buffer and add overlays to links."
5510 (if (re-search-forward org-angle-link-re limit t)
5511 (progn
5512 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5513 (add-text-properties (match-beginning 0) (match-end 0)
5514 (list 'mouse-face 'highlight
5515 'keymap org-mouse-map))
5516 (org-rear-nonsticky-at (match-end 0))
5517 t)))
5519 (defun org-activate-footnote-links (limit)
5520 "Run through the buffer and add overlays to footnotes."
5521 (let ((fn (org-footnote-next-reference-or-definition limit)))
5522 (when fn
5523 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5524 (org-remove-flyspell-overlays-in beg end)
5525 (add-text-properties beg end
5526 (list 'mouse-face 'highlight
5527 'keymap org-mouse-map
5528 'help-echo
5529 (if (= (point-at-bol) beg)
5530 "Footnote definition"
5531 "Footnote reference")
5532 'font-lock-fontified t
5533 'font-lock-multiline t
5534 'face 'org-footnote))))))
5536 (defun org-activate-bracket-links (limit)
5537 "Run through the buffer and add overlays to bracketed links."
5538 (if (re-search-forward org-bracket-link-regexp limit t)
5539 (let* ((help (concat "LINK: "
5540 (org-match-string-no-properties 1)))
5541 ;; FIXME: above we should remove the escapes.
5542 ;; but that requires another match, protecting match data,
5543 ;; a lot of overhead for font-lock.
5544 (ip (org-maybe-intangible
5545 (list 'invisible 'org-link
5546 'keymap org-mouse-map 'mouse-face 'highlight
5547 'font-lock-multiline t 'help-echo help)))
5548 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5549 'font-lock-multiline t 'help-echo help)))
5550 ;; We need to remove the invisible property here. Table narrowing
5551 ;; may have made some of this invisible.
5552 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5553 (remove-text-properties (match-beginning 0) (match-end 0)
5554 '(invisible nil))
5555 (if (match-end 3)
5556 (progn
5557 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5558 (org-rear-nonsticky-at (match-beginning 3))
5559 (add-text-properties (match-beginning 3) (match-end 3) vp)
5560 (org-rear-nonsticky-at (match-end 3))
5561 (add-text-properties (match-end 3) (match-end 0) ip)
5562 (org-rear-nonsticky-at (match-end 0)))
5563 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5564 (org-rear-nonsticky-at (match-beginning 1))
5565 (add-text-properties (match-beginning 1) (match-end 1) vp)
5566 (org-rear-nonsticky-at (match-end 1))
5567 (add-text-properties (match-end 1) (match-end 0) ip)
5568 (org-rear-nonsticky-at (match-end 0)))
5569 t)))
5571 (defun org-activate-dates (limit)
5572 "Run through the buffer and add overlays to dates."
5573 (if (re-search-forward org-tsr-regexp-both limit t)
5574 (progn
5575 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5576 (add-text-properties (match-beginning 0) (match-end 0)
5577 (list 'mouse-face 'highlight
5578 'keymap org-mouse-map))
5579 (org-rear-nonsticky-at (match-end 0))
5580 (when org-display-custom-times
5581 (if (match-end 3)
5582 (org-display-custom-time (match-beginning 3) (match-end 3)))
5583 (org-display-custom-time (match-beginning 1) (match-end 1)))
5584 t)))
5586 (defvar org-target-link-regexp nil
5587 "Regular expression matching radio targets in plain text.")
5588 (make-variable-buffer-local 'org-target-link-regexp)
5589 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5590 "Regular expression matching a link target.")
5591 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5592 "Regular expression matching a radio target.")
5593 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5594 "Regular expression matching any target.")
5596 (defun org-activate-target-links (limit)
5597 "Run through the buffer and add overlays to target matches."
5598 (when org-target-link-regexp
5599 (let ((case-fold-search t))
5600 (if (re-search-forward org-target-link-regexp limit t)
5601 (progn
5602 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5603 (add-text-properties (match-beginning 0) (match-end 0)
5604 (list 'mouse-face 'highlight
5605 'keymap org-mouse-map
5606 'help-echo "Radio target link"
5607 'org-linked-text t))
5608 (org-rear-nonsticky-at (match-end 0))
5609 t)))))
5611 (defun org-update-radio-target-regexp ()
5612 "Find all radio targets in this file and update the regular expression."
5613 (interactive)
5614 (when (memq 'radio org-activate-links)
5615 (setq org-target-link-regexp
5616 (org-make-target-link-regexp (org-all-targets 'radio)))
5617 (org-restart-font-lock)))
5619 (defun org-hide-wide-columns (limit)
5620 (let (s e)
5621 (setq s (text-property-any (point) (or limit (point-max))
5622 'org-cwidth t))
5623 (when s
5624 (setq e (next-single-property-change s 'org-cwidth))
5625 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5626 (goto-char e)
5627 t)))
5629 (defvar org-latex-and-specials-regexp nil
5630 "Regular expression for highlighting export special stuff.")
5631 (defvar org-match-substring-regexp)
5632 (defvar org-match-substring-with-braces-regexp)
5634 ;; This should be with the exporter code, but we also use if for font-locking
5635 (defconst org-export-html-special-string-regexps
5636 '(("\\\\-" . "&shy;")
5637 ("---\\([^-]\\)" . "&mdash;\\1")
5638 ("--\\([^-]\\)" . "&ndash;\\1")
5639 ("\\.\\.\\." . "&hellip;"))
5640 "Regular expressions for special string conversion.")
5643 (defun org-compute-latex-and-specials-regexp ()
5644 "Compute regular expression for stuff treated specially by exporters."
5645 (if (not org-highlight-latex-fragments-and-specials)
5646 (org-set-local 'org-latex-and-specials-regexp nil)
5647 (require 'org-exp)
5648 (let*
5649 ((matchers (plist-get org-format-latex-options :matchers))
5650 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5651 org-latex-regexps)))
5652 (org-export-allow-BIND nil)
5653 (options (org-combine-plists (org-default-export-plist)
5654 (org-infile-export-plist)))
5655 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5656 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5657 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5658 (org-export-html-expand (plist-get options :expand-quoted-html))
5659 (org-export-with-special-strings (plist-get options :special-strings))
5660 (re-sub
5661 (cond
5662 ((equal org-export-with-sub-superscripts '{})
5663 (list org-match-substring-with-braces-regexp))
5664 (org-export-with-sub-superscripts
5665 (list org-match-substring-regexp))
5666 (t nil)))
5667 (re-latex
5668 (if org-export-with-LaTeX-fragments
5669 (mapcar (lambda (x) (nth 1 x)) latexs)))
5670 (re-macros
5671 (if org-export-with-TeX-macros
5672 (list (concat "\\\\"
5673 (regexp-opt
5674 (append
5676 (delq nil
5677 (mapcar 'car-safe
5678 (append org-entities-user
5679 org-entities)))
5680 (if (boundp 'org-latex-entities)
5681 (mapcar (lambda (x)
5682 (or (car-safe x) x))
5683 org-latex-entities)
5684 nil))
5685 'words))) ; FIXME
5687 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5688 (re-special (if org-export-with-special-strings
5689 (mapcar (lambda (x) (car x))
5690 org-export-html-special-string-regexps)))
5691 (re-rest
5692 (delq nil
5693 (list
5694 (if org-export-html-expand "@<[^>\n]+>")
5695 ))))
5696 (org-set-local
5697 'org-latex-and-specials-regexp
5698 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5699 re-rest) "\\|")))))
5701 (defun org-do-latex-and-special-faces (limit)
5702 "Run through the buffer and add overlays to links."
5703 (when org-latex-and-specials-regexp
5704 (let (rtn d)
5705 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5706 limit t))
5707 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5708 'face))
5709 '(org-code org-verbatim underline)))
5710 (progn
5711 (setq rtn t
5712 d (cond ((member (char-after (1+ (match-beginning 0)))
5713 '(?_ ?^)) 1)
5714 (t 0)))
5715 (font-lock-prepend-text-property
5716 (+ d (match-beginning 0)) (match-end 0)
5717 'face 'org-latex-and-export-specials)
5718 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5719 '(font-lock-multiline t)))))
5720 rtn)))
5722 (defun org-restart-font-lock ()
5723 "Restart `font-lock-mode', to force refontification."
5724 (when (and (boundp 'font-lock-mode) font-lock-mode)
5725 (font-lock-mode -1)
5726 (font-lock-mode 1)))
5728 (defun org-all-targets (&optional radio)
5729 "Return a list of all targets in this file.
5730 With optional argument RADIO, only find radio targets."
5731 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5732 rtn)
5733 (save-excursion
5734 (goto-char (point-min))
5735 (while (re-search-forward re nil t)
5736 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5737 rtn)))
5739 (defun org-make-target-link-regexp (targets)
5740 "Make regular expression matching all strings in TARGETS.
5741 The regular expression finds the targets also if there is a line break
5742 between words."
5743 (and targets
5744 (concat
5745 "\\<\\("
5746 (mapconcat
5747 (lambda (x)
5748 (setq x (regexp-quote x))
5749 (while (string-match " +" x)
5750 (setq x (replace-match "\\s-+" t t x)))
5752 targets
5753 "\\|")
5754 "\\)\\>")))
5756 (defun org-activate-tags (limit)
5757 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5758 (progn
5759 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5760 (add-text-properties (match-beginning 1) (match-end 1)
5761 (list 'mouse-face 'highlight
5762 'keymap org-mouse-map))
5763 (org-rear-nonsticky-at (match-end 1))
5764 t)))
5766 (defun org-outline-level ()
5767 "Compute the outline level of the heading at point.
5768 This function assumes that the cursor is at the beginning of a line matched
5769 by `outline-regexp'. Otherwise it returns garbage.
5770 If this is called at a normal headline, the level is the number of stars.
5771 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5772 (save-excursion
5773 (looking-at org-outline-regexp)
5774 (1- (- (match-end 0) (match-beginning 0)))))
5776 (defvar org-font-lock-keywords nil)
5778 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5779 "Regular expression matching a property line.")
5781 (defvar org-font-lock-hook nil
5782 "Functions to be called for special font lock stuff.")
5784 (defvar org-font-lock-set-keywords-hook nil
5785 "Functions that can manipulate `org-font-lock-extra-keywords'.
5786 This is called after `org-font-lock-extra-keywords' is defined, but before
5787 it is installed to be used by font lock. This can be useful if something
5788 needs to be inserted at a specific position in the font-lock sequence.")
5790 (defun org-font-lock-hook (limit)
5791 (run-hook-with-args 'org-font-lock-hook limit))
5793 (defun org-set-font-lock-defaults ()
5794 (let* ((em org-fontify-emphasized-text)
5795 (lk org-activate-links)
5796 (org-font-lock-extra-keywords
5797 (list
5798 ;; Call the hook
5799 '(org-font-lock-hook)
5800 ;; Headlines
5801 `(,(if org-fontify-whole-heading-line
5802 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5803 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5804 (1 (org-get-level-face 1))
5805 (2 (org-get-level-face 2))
5806 (3 (org-get-level-face 3)))
5807 ;; Table lines
5808 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5809 (1 'org-table t))
5810 ;; Table internals
5811 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5812 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5813 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5814 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5815 ;; Drawers
5816 (list org-drawer-regexp '(0 'org-special-keyword t))
5817 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5818 ;; Properties
5819 (list org-property-re
5820 '(1 'org-special-keyword t)
5821 '(3 'org-property-value t))
5822 ;; Links
5823 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5824 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5825 (if (memq 'plain lk) '(org-activate-plain-links))
5826 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5827 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5828 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5829 (if (memq 'footnote lk) '(org-activate-footnote-links))
5830 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5831 '(org-hide-wide-columns (0 nil append))
5832 ;; TODO keyword
5833 (list (format org-heading-keyword-regexp-format
5834 org-todo-regexp)
5835 '(2 (org-get-todo-face 2) t))
5836 ;; DONE
5837 (if org-fontify-done-headline
5838 (list (format org-heading-keyword-regexp-format
5839 (concat
5840 "\\(?:"
5841 (mapconcat 'regexp-quote org-done-keywords "\\|")
5842 "\\)"))
5843 '(2 'org-headline-done t))
5844 nil)
5845 ;; Priorities
5846 '(org-font-lock-add-priority-faces)
5847 ;; Tags
5848 '(org-font-lock-add-tag-faces)
5849 ;; Special keywords
5850 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5851 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5852 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5853 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5854 ;; Emphasis
5855 (if em
5856 (if (featurep 'xemacs)
5857 '(org-do-emphasis-faces (0 nil append))
5858 '(org-do-emphasis-faces)))
5859 ;; Checkboxes
5860 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5861 1 'org-checkbox prepend)
5862 (if (cdr (assq 'checkbox org-list-automatic-rules))
5863 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5864 (0 (org-get-checkbox-statistics-face) t)))
5865 ;; Description list items
5866 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5867 1 'bold prepend)
5868 ;; ARCHIVEd headings
5869 (list (concat
5870 org-outline-regexp-bol
5871 "\\(.*:" org-archive-tag ":.*\\)")
5872 '(1 'org-archived prepend))
5873 ;; Specials
5874 '(org-do-latex-and-special-faces)
5875 '(org-fontify-entities)
5876 '(org-raise-scripts)
5877 ;; Code
5878 '(org-activate-code (1 'org-code t))
5879 ;; COMMENT
5880 (list (format org-heading-keyword-regexp-format
5881 (concat "\\("
5882 org-comment-string "\\|" org-quote-string
5883 "\\)"))
5884 '(2 'org-special-keyword t))
5885 '("^#.*" (0 'font-lock-comment-face t))
5886 ;; Blocks and meta lines
5887 '(org-fontify-meta-lines-and-blocks)
5889 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5890 (run-hooks 'org-font-lock-set-keywords-hook)
5891 ;; Now set the full font-lock-keywords
5892 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5893 (org-set-local 'font-lock-defaults
5894 '(org-font-lock-keywords t nil nil backward-paragraph))
5895 (kill-local-variable 'font-lock-keywords) nil))
5897 (defun org-toggle-pretty-entities ()
5898 "Toggle the composition display of entities as UTF8 characters."
5899 (interactive)
5900 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5901 (org-restart-font-lock)
5902 (if org-pretty-entities
5903 (message "Entities are displayed as UTF8 characters")
5904 (save-restriction
5905 (widen)
5906 (org-decompose-region (point-min) (point-max))
5907 (message "Entities are displayed plain"))))
5909 (defun org-fontify-entities (limit)
5910 "Find an entity to fontify."
5911 (let (ee)
5912 (when org-pretty-entities
5913 (catch 'match
5914 (while (re-search-forward
5915 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5916 limit t)
5917 (if (and (not (org-in-indented-comment-line))
5918 (setq ee (org-entity-get (match-string 1)))
5919 (= (length (nth 6 ee)) 1))
5920 (progn
5921 (add-text-properties
5922 (match-beginning 0) (match-end 1)
5923 (list 'font-lock-fontified t))
5924 (compose-region (match-beginning 0) (match-end 1)
5925 (nth 6 ee) nil)
5926 (backward-char 1)
5927 (throw 'match t))))
5928 nil))))
5930 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5931 "Fontify string S like in Org-mode."
5932 (with-temp-buffer
5933 (insert s)
5934 (let ((org-odd-levels-only odd-levels))
5935 (org-mode)
5936 (font-lock-fontify-buffer)
5937 (buffer-string))))
5939 (defvar org-m nil)
5940 (defvar org-l nil)
5941 (defvar org-f nil)
5942 (defun org-get-level-face (n)
5943 "Get the right face for match N in font-lock matching of headlines."
5944 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5945 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5946 (if org-cycle-level-faces
5947 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5948 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5949 (cond
5950 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5951 ((eq n 2) org-f)
5952 (t (if org-level-color-stars-only nil org-f))))
5955 (defun org-get-todo-face (kwd)
5956 "Get the right face for a TODO keyword KWD.
5957 If KWD is a number, get the corresponding match group."
5958 (if (numberp kwd) (setq kwd (match-string kwd)))
5959 (or (org-face-from-face-or-color
5960 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5961 (and (member kwd org-done-keywords) 'org-done)
5962 'org-todo))
5964 (defun org-face-from-face-or-color (context inherit face-or-color)
5965 "Create a face list that inherits INHERIT, but sets the foreground color.
5966 When FACE-OR-COLOR is not a string, just return it."
5967 (if (stringp face-or-color)
5968 (list :inherit inherit
5969 (cdr (assoc context org-faces-easy-properties))
5970 face-or-color)
5971 face-or-color))
5973 (defun org-font-lock-add-tag-faces (limit)
5974 "Add the special tag faces."
5975 (when (and org-tag-faces org-tags-special-faces-re)
5976 (while (re-search-forward org-tags-special-faces-re limit t)
5977 (add-text-properties (match-beginning 1) (match-end 1)
5978 (list 'face (org-get-tag-face 1)
5979 'font-lock-fontified t))
5980 (backward-char 1))))
5982 (defun org-font-lock-add-priority-faces (limit)
5983 "Add the special priority faces."
5984 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5985 (add-text-properties
5986 (match-beginning 0) (match-end 0)
5987 (list 'face (or (org-face-from-face-or-color
5988 'priority 'org-special-keyword
5989 (cdr (assoc (char-after (match-beginning 1))
5990 org-priority-faces)))
5991 'org-special-keyword)
5992 'font-lock-fontified t))))
5994 (defun org-get-tag-face (kwd)
5995 "Get the right face for a TODO keyword KWD.
5996 If KWD is a number, get the corresponding match group."
5997 (if (numberp kwd) (setq kwd (match-string kwd)))
5998 (or (org-face-from-face-or-color
5999 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6000 'org-tag))
6002 (defun org-unfontify-region (beg end &optional maybe_loudly)
6003 "Remove fontification and activation overlays from links."
6004 (font-lock-default-unfontify-region beg end)
6005 (let* ((buffer-undo-list t)
6006 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6007 (inhibit-modification-hooks t)
6008 deactivate-mark buffer-file-name buffer-file-truename)
6009 (org-decompose-region beg end)
6010 (remove-text-properties beg end
6011 '(mouse-face t keymap t org-linked-text t
6012 invisible t intangible t
6013 org-no-flyspell t org-emphasis t))
6014 (org-remove-font-lock-display-properties beg end)))
6016 (defconst org-script-display '(((raise -0.3) (height 0.7))
6017 ((raise 0.3) (height 0.7))
6018 ((raise -0.5))
6019 ((raise 0.5)))
6020 "Display properties for showing superscripts and subscripts.")
6022 (defun org-remove-font-lock-display-properties (beg end)
6023 "Remove specific display properties that have been added by font lock.
6024 The will remove the raise properties that are used to show superscripts
6025 and subscripts."
6026 (let (next prop)
6027 (while (< beg end)
6028 (setq next (next-single-property-change beg 'display nil end)
6029 prop (get-text-property beg 'display))
6030 (if (member prop org-script-display)
6031 (put-text-property beg next 'display nil))
6032 (setq beg next))))
6034 (defun org-raise-scripts (limit)
6035 "Add raise properties to sub/superscripts."
6036 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6037 (if (re-search-forward
6038 (if (eq org-use-sub-superscripts t)
6039 org-match-substring-regexp
6040 org-match-substring-with-braces-regexp)
6041 limit t)
6042 (let* ((pos (point)) table-p comment-p
6043 (mpos (match-beginning 3))
6044 (emph-p (get-text-property mpos 'org-emphasis))
6045 (link-p (get-text-property mpos 'mouse-face))
6046 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6047 (goto-char (point-at-bol))
6048 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6049 comment-p (org-looking-at-p "[ \t]*#"))
6050 (goto-char pos)
6051 ;; FIXME: Should we go back one character here, for a_b^c
6052 ;; (goto-char (1- pos)) ;????????????????????
6053 (if (or comment-p emph-p link-p keyw-p)
6055 (put-text-property (match-beginning 3) (match-end 0)
6056 'display
6057 (if (equal (char-after (match-beginning 2)) ?^)
6058 (nth (if table-p 3 1) org-script-display)
6059 (nth (if table-p 2 0) org-script-display)))
6060 (add-text-properties (match-beginning 2) (match-end 2)
6061 (list 'invisible t
6062 'org-dwidth t 'org-dwidth-n 1))
6063 (if (and (eq (char-after (match-beginning 3)) ?{)
6064 (eq (char-before (match-end 3)) ?}))
6065 (progn
6066 (add-text-properties
6067 (match-beginning 3) (1+ (match-beginning 3))
6068 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6069 (add-text-properties
6070 (1- (match-end 3)) (match-end 3)
6071 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6072 t)))))
6074 ;;;; Visibility cycling, including org-goto and indirect buffer
6076 ;;; Cycling
6078 (defvar org-cycle-global-status nil)
6079 (make-variable-buffer-local 'org-cycle-global-status)
6080 (defvar org-cycle-subtree-status nil)
6081 (make-variable-buffer-local 'org-cycle-subtree-status)
6083 ;;;###autoload
6085 (defvar org-inlinetask-min-level)
6087 (defun org-cycle (&optional arg)
6088 "TAB-action and visibility cycling for Org-mode.
6090 This is the command invoked in Org-mode by the TAB key. Its main purpose
6091 is outline visibility cycling, but it also invokes other actions
6092 in special contexts.
6094 - When this function is called with a prefix argument, rotate the entire
6095 buffer through 3 states (global cycling)
6096 1. OVERVIEW: Show only top-level headlines.
6097 2. CONTENTS: Show all headlines of all levels, but no body text.
6098 3. SHOW ALL: Show everything.
6099 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6100 determined by the variable `org-startup-folded', and by any VISIBILITY
6101 properties in the buffer.
6102 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6103 including any drawers.
6105 - When inside a table, re-align the table and move to the next field.
6107 - When point is at the beginning of a headline, rotate the subtree started
6108 by this line through 3 different states (local cycling)
6109 1. FOLDED: Only the main headline is shown.
6110 2. CHILDREN: The main headline and the direct children are shown.
6111 From this state, you can move to one of the children
6112 and zoom in further.
6113 3. SUBTREE: Show the entire subtree, including body text.
6114 If there is no subtree, switch directly from CHILDREN to FOLDED.
6116 - When point is at the beginning of an empty headline and the variable
6117 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6118 of the headline by demoting and promoting it to likely levels. This
6119 speeds up creation document structure by pressing TAB once or several
6120 times right after creating a new headline.
6122 - When there is a numeric prefix, go up to a heading with level ARG, do
6123 a `show-subtree' and return to the previous cursor position. If ARG
6124 is negative, go up that many levels.
6126 - When point is not at the beginning of a headline, execute the global
6127 binding for TAB, which is re-indenting the line. See the option
6128 `org-cycle-emulate-tab' for details.
6130 - Special case: if point is at the beginning of the buffer and there is
6131 no headline in line 1, this function will act as if called with prefix arg
6132 (C-u TAB, same as S-TAB) also when called without prefix arg.
6133 But only if also the variable `org-cycle-global-at-bob' is t."
6134 (interactive "P")
6135 (org-load-modules-maybe)
6136 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6137 (and org-cycle-level-after-item/entry-creation
6138 (or (org-cycle-level)
6139 (org-cycle-item-indentation))))
6140 (let* ((limit-level
6141 (or org-cycle-max-level
6142 (and (boundp 'org-inlinetask-min-level)
6143 org-inlinetask-min-level
6144 (1- org-inlinetask-min-level))))
6145 (nstars (and limit-level
6146 (if org-odd-levels-only
6147 (and limit-level (1- (* limit-level 2)))
6148 limit-level)))
6149 (org-outline-regexp
6150 (if (not (eq major-mode 'org-mode))
6151 outline-regexp
6152 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6153 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6154 (not (looking-at org-outline-regexp))))
6155 (org-cycle-hook
6156 (if bob-special
6157 (delq 'org-optimize-window-after-visibility-change
6158 (copy-sequence org-cycle-hook))
6159 org-cycle-hook))
6160 (pos (point)))
6162 (if (or bob-special (equal arg '(4)))
6163 ;; special case: use global cycling
6164 (setq arg t))
6166 (cond
6168 ((equal arg '(16))
6169 (setq last-command 'dummy)
6170 (org-set-startup-visibility)
6171 (message "Startup visibility, plus VISIBILITY properties"))
6173 ((equal arg '(64))
6174 (show-all)
6175 (message "Entire buffer visible, including drawers"))
6177 ;; Table: enter it or move to the next field.
6178 ((org-at-table-p 'any)
6179 (if (org-at-table.el-p)
6180 (message "Use C-c ' to edit table.el tables")
6181 (if arg (org-table-edit-field t)
6182 (org-table-justify-field-maybe)
6183 (call-interactively 'org-table-next-field))))
6185 ((run-hook-with-args-until-success
6186 'org-tab-after-check-for-table-hook))
6188 ;; Global cycling: delegate to `org-cycle-internal-global'.
6189 ((eq arg t) (org-cycle-internal-global))
6191 ;; Drawers: delegate to `org-flag-drawer'.
6192 ((and org-drawers org-drawer-regexp
6193 (save-excursion
6194 (beginning-of-line 1)
6195 (looking-at org-drawer-regexp)))
6196 (org-flag-drawer ; toggle block visibility
6197 (not (get-char-property (match-end 0) 'invisible))))
6199 ;; Show-subtree, ARG levels up from here.
6200 ((integerp arg)
6201 (save-excursion
6202 (org-back-to-heading)
6203 (outline-up-heading (if (< arg 0) (- arg)
6204 (- (funcall outline-level) arg)))
6205 (org-show-subtree)))
6207 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6208 ((and (featurep 'org-inlinetask)
6209 (org-inlinetask-at-task-p)
6210 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6211 (org-inlinetask-toggle-visibility))
6213 ((org-try-cdlatex-tab))
6215 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6216 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6217 (save-excursion (beginning-of-line 1)
6218 (looking-at org-outline-regexp)))
6219 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6220 (org-cycle-internal-local))
6222 ;; From there: TAB emulation and template completion.
6223 (buffer-read-only (org-back-to-heading))
6225 ((run-hook-with-args-until-success
6226 'org-tab-after-check-for-cycling-hook))
6228 ((org-try-structure-completion))
6230 ((run-hook-with-args-until-success
6231 'org-tab-before-tab-emulation-hook))
6233 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6234 (or (not (bolp))
6235 (not (looking-at org-outline-regexp))))
6236 (call-interactively (global-key-binding "\t")))
6238 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6239 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6240 (or (and (eq org-cycle-emulate-tab 'white)
6241 (= (match-end 0) (point-at-eol)))
6242 (and (eq org-cycle-emulate-tab 'whitestart)
6243 (>= (match-end 0) pos))))
6245 (eq org-cycle-emulate-tab t))
6246 (call-interactively (global-key-binding "\t")))
6248 (t (save-excursion
6249 (org-back-to-heading)
6250 (org-cycle)))))))
6252 (defun org-cycle-internal-global ()
6253 "Do the global cycling action."
6254 ;; Hack to avoid display of messages for .org attachments in Gnus
6255 (let ((ga (string-match "\\*fontification" (buffer-name))))
6256 (cond
6257 ((and (eq last-command this-command)
6258 (eq org-cycle-global-status 'overview))
6259 ;; We just created the overview - now do table of contents
6260 ;; This can be slow in very large buffers, so indicate action
6261 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6262 (unless ga (message "CONTENTS..."))
6263 (org-content)
6264 (unless ga (message "CONTENTS...done"))
6265 (setq org-cycle-global-status 'contents)
6266 (run-hook-with-args 'org-cycle-hook 'contents))
6268 ((and (eq last-command this-command)
6269 (eq org-cycle-global-status 'contents))
6270 ;; We just showed the table of contents - now show everything
6271 (run-hook-with-args 'org-pre-cycle-hook 'all)
6272 (show-all)
6273 (unless ga (message "SHOW ALL"))
6274 (setq org-cycle-global-status 'all)
6275 (run-hook-with-args 'org-cycle-hook 'all))
6278 ;; Default action: go to overview
6279 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6280 (org-overview)
6281 (unless ga (message "OVERVIEW"))
6282 (setq org-cycle-global-status 'overview)
6283 (run-hook-with-args 'org-cycle-hook 'overview)))))
6285 (defun org-cycle-internal-local ()
6286 "Do the local cycling action."
6287 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6288 ;; First, determine end of headline (EOH), end of subtree or item
6289 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6290 (save-excursion
6291 (if (org-at-item-p)
6292 (progn
6293 (beginning-of-line)
6294 (setq struct (org-list-struct))
6295 (setq eoh (point-at-eol))
6296 (setq eos (org-list-get-item-end-before-blank (point) struct))
6297 (setq has-children (org-list-has-child-p (point) struct)))
6298 (org-back-to-heading)
6299 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6300 (setq eos (save-excursion
6301 (org-end-of-subtree t)
6302 (unless (eobp)
6303 (skip-chars-forward " \t\n"))
6304 (if (eobp) (point) (1- (point)))))
6305 (setq has-children
6306 (or (save-excursion
6307 (let ((level (funcall outline-level)))
6308 (outline-next-heading)
6309 (and (org-at-heading-p t)
6310 (> (funcall outline-level) level))))
6311 (save-excursion
6312 (org-list-search-forward (org-item-beginning-re) eos t)))))
6313 ;; Determine end invisible part of buffer (EOL)
6314 (beginning-of-line 2)
6315 ;; XEmacs doesn't have `next-single-char-property-change'
6316 (if (featurep 'xemacs)
6317 (while (and (not (eobp)) ;; this is like `next-line'
6318 (get-char-property (1- (point)) 'invisible))
6319 (beginning-of-line 2))
6320 (while (and (not (eobp)) ;; this is like `next-line'
6321 (get-char-property (1- (point)) 'invisible))
6322 (goto-char (next-single-char-property-change (point) 'invisible))
6323 (and (eolp) (beginning-of-line 2))))
6324 (setq eol (point)))
6325 ;; Find out what to do next and set `this-command'
6326 (cond
6327 ((= eos eoh)
6328 ;; Nothing is hidden behind this heading
6329 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6330 (message "EMPTY ENTRY")
6331 (setq org-cycle-subtree-status nil)
6332 (save-excursion
6333 (goto-char eos)
6334 (outline-next-heading)
6335 (if (outline-invisible-p) (org-flag-heading nil))))
6336 ((and (or (>= eol eos)
6337 (not (string-match "\\S-" (buffer-substring eol eos))))
6338 (or has-children
6339 (not (setq children-skipped
6340 org-cycle-skip-children-state-if-no-children))))
6341 ;; Entire subtree is hidden in one line: children view
6342 (run-hook-with-args 'org-pre-cycle-hook 'children)
6343 (if (org-at-item-p)
6344 (org-list-set-item-visibility (point-at-bol) struct 'children)
6345 (org-show-entry)
6346 (org-with-limited-levels (show-children))
6347 ;; FIXME: This slows down the func way too much.
6348 ;; How keep drawers hidden in subtree anyway?
6349 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6350 ;; (org-cycle-hide-drawers 'subtree))
6352 ;; Fold every list in subtree to top-level items.
6353 (when (eq org-cycle-include-plain-lists 'integrate)
6354 (save-excursion
6355 (org-back-to-heading)
6356 (while (org-list-search-forward (org-item-beginning-re) eos t)
6357 (beginning-of-line 1)
6358 (let* ((struct (org-list-struct))
6359 (prevs (org-list-prevs-alist struct))
6360 (end (org-list-get-bottom-point struct)))
6361 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6362 (org-list-get-all-items (point) struct prevs))
6363 (goto-char end))))))
6364 (message "CHILDREN")
6365 (save-excursion
6366 (goto-char eos)
6367 (outline-next-heading)
6368 (if (outline-invisible-p) (org-flag-heading nil)))
6369 (setq org-cycle-subtree-status 'children)
6370 (run-hook-with-args 'org-cycle-hook 'children))
6371 ((or children-skipped
6372 (and (eq last-command this-command)
6373 (eq org-cycle-subtree-status 'children)))
6374 ;; We just showed the children, or no children are there,
6375 ;; now show everything.
6376 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6377 (outline-flag-region eoh eos nil)
6378 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6379 (setq org-cycle-subtree-status 'subtree)
6380 (run-hook-with-args 'org-cycle-hook 'subtree))
6382 ;; Default action: hide the subtree.
6383 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6384 (outline-flag-region eoh eos t)
6385 (message "FOLDED")
6386 (setq org-cycle-subtree-status 'folded)
6387 (run-hook-with-args 'org-cycle-hook 'folded)))))
6389 ;;;###autoload
6390 (defun org-global-cycle (&optional arg)
6391 "Cycle the global visibility. For details see `org-cycle'.
6392 With \\[universal-argument] prefix arg, switch to startup visibility.
6393 With a numeric prefix, show all headlines up to that level."
6394 (interactive "P")
6395 (let ((org-cycle-include-plain-lists
6396 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6397 (cond
6398 ((integerp arg)
6399 (show-all)
6400 (hide-sublevels arg)
6401 (setq org-cycle-global-status 'contents))
6402 ((equal arg '(4))
6403 (org-set-startup-visibility)
6404 (message "Startup visibility, plus VISIBILITY properties."))
6406 (org-cycle '(4))))))
6408 (defun org-set-startup-visibility ()
6409 "Set the visibility required by startup options and properties."
6410 (cond
6411 ((eq org-startup-folded t)
6412 (org-cycle '(4)))
6413 ((eq org-startup-folded 'content)
6414 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6415 (org-cycle '(4)) (org-cycle '(4)))))
6416 (unless (eq org-startup-folded 'showeverything)
6417 (if org-hide-block-startup (org-hide-block-all))
6418 (org-set-visibility-according-to-property 'no-cleanup)
6419 (org-cycle-hide-archived-subtrees 'all)
6420 (org-cycle-hide-drawers 'all)
6421 (org-cycle-show-empty-lines t)))
6423 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6424 "Switch subtree visibilities according to :VISIBILITY: property."
6425 (interactive)
6426 (let (org-show-entry-below state)
6427 (save-excursion
6428 (goto-char (point-min))
6429 (while (re-search-forward
6430 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6431 nil t)
6432 (setq state (match-string 1))
6433 (save-excursion
6434 (org-back-to-heading t)
6435 (hide-subtree)
6436 (org-reveal)
6437 (cond
6438 ((equal state '("fold" "folded"))
6439 (hide-subtree))
6440 ((equal state "children")
6441 (org-show-hidden-entry)
6442 (show-children))
6443 ((equal state "content")
6444 (save-excursion
6445 (save-restriction
6446 (org-narrow-to-subtree)
6447 (org-content))))
6448 ((member state '("all" "showall"))
6449 (show-subtree)))))
6450 (unless no-cleanup
6451 (org-cycle-hide-archived-subtrees 'all)
6452 (org-cycle-hide-drawers 'all)
6453 (org-cycle-show-empty-lines 'all)))))
6455 ;; This function uses outline-regexp instead of the more fundamental
6456 ;; org-outline-regexp so that org-cycle-global works outside of Org
6457 ;; buffers, where outline-regexp is needed.
6458 (defun org-overview ()
6459 "Switch to overview mode, showing only top-level headlines.
6460 Really, this shows all headlines with level equal or greater than the level
6461 of the first headline in the buffer. This is important, because if the
6462 first headline is not level one, then (hide-sublevels 1) gives confusing
6463 results."
6464 (interactive)
6465 (let ((level (save-excursion
6466 (goto-char (point-min))
6467 (if (re-search-forward (concat "^" outline-regexp) nil t)
6468 (progn
6469 (goto-char (match-beginning 0))
6470 (funcall outline-level))))))
6471 (and level (hide-sublevels level))))
6473 (defun org-content (&optional arg)
6474 "Show all headlines in the buffer, like a table of contents.
6475 With numerical argument N, show content up to level N."
6476 (interactive "P")
6477 (save-excursion
6478 ;; Visit all headings and show their offspring
6479 (and (integerp arg) (org-overview))
6480 (goto-char (point-max))
6481 (catch 'exit
6482 (while (and (progn (condition-case nil
6483 (outline-previous-visible-heading 1)
6484 (error (goto-char (point-min))))
6486 (looking-at org-outline-regexp))
6487 (if (integerp arg)
6488 (show-children (1- arg))
6489 (show-branches))
6490 (if (bobp) (throw 'exit nil))))))
6493 (defun org-optimize-window-after-visibility-change (state)
6494 "Adjust the window after a change in outline visibility.
6495 This function is the default value of the hook `org-cycle-hook'."
6496 (when (get-buffer-window (current-buffer))
6497 (cond
6498 ((eq state 'content) nil)
6499 ((eq state 'all) nil)
6500 ((eq state 'folded) nil)
6501 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6502 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6504 (defun org-remove-empty-overlays-at (pos)
6505 "Remove outline overlays that do not contain non-white stuff."
6506 (mapc
6507 (lambda (o)
6508 (and (eq 'outline (overlay-get o 'invisible))
6509 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6510 (overlay-end o))))
6511 (delete-overlay o)))
6512 (overlays-at pos)))
6514 (defun org-clean-visibility-after-subtree-move ()
6515 "Fix visibility issues after moving a subtree."
6516 ;; First, find a reasonable region to look at:
6517 ;; Start two siblings above, end three below
6518 (let* ((beg (save-excursion
6519 (and (org-get-last-sibling)
6520 (org-get-last-sibling))
6521 (point)))
6522 (end (save-excursion
6523 (and (org-get-next-sibling)
6524 (org-get-next-sibling)
6525 (org-get-next-sibling))
6526 (if (org-at-heading-p)
6527 (point-at-eol)
6528 (point))))
6529 (level (looking-at "\\*+"))
6530 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6531 (save-excursion
6532 (save-restriction
6533 (narrow-to-region beg end)
6534 (when re
6535 ;; Properly fold already folded siblings
6536 (goto-char (point-min))
6537 (while (re-search-forward re nil t)
6538 (if (and (not (outline-invisible-p))
6539 (save-excursion
6540 (goto-char (point-at-eol)) (outline-invisible-p)))
6541 (hide-entry))))
6542 (org-cycle-show-empty-lines 'overview)
6543 (org-cycle-hide-drawers 'overview)))))
6545 (defun org-cycle-show-empty-lines (state)
6546 "Show empty lines above all visible headlines.
6547 The region to be covered depends on STATE when called through
6548 `org-cycle-hook'. Lisp program can use t for STATE to get the
6549 entire buffer covered. Note that an empty line is only shown if there
6550 are at least `org-cycle-separator-lines' empty lines before the headline."
6551 (when (not (= org-cycle-separator-lines 0))
6552 (save-excursion
6553 (let* ((n (abs org-cycle-separator-lines))
6554 (re (cond
6555 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6556 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6557 (t (let ((ns (number-to-string (- n 2))))
6558 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6559 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6560 beg end b e)
6561 (cond
6562 ((memq state '(overview contents t))
6563 (setq beg (point-min) end (point-max)))
6564 ((memq state '(children folded))
6565 (setq beg (point) end (progn (org-end-of-subtree t t)
6566 (beginning-of-line 2)
6567 (point)))))
6568 (when beg
6569 (goto-char beg)
6570 (while (re-search-forward re end t)
6571 (unless (get-char-property (match-end 1) 'invisible)
6572 (setq e (match-end 1))
6573 (if (< org-cycle-separator-lines 0)
6574 (setq b (save-excursion
6575 (goto-char (match-beginning 0))
6576 (org-back-over-empty-lines)
6577 (if (save-excursion
6578 (goto-char (max (point-min) (1- (point))))
6579 (org-at-heading-p))
6580 (1- (point))
6581 (point))))
6582 (setq b (match-beginning 1)))
6583 (outline-flag-region b e nil)))))))
6584 ;; Never hide empty lines at the end of the file.
6585 (save-excursion
6586 (goto-char (point-max))
6587 (outline-previous-heading)
6588 (outline-end-of-heading)
6589 (if (and (looking-at "[ \t\n]+")
6590 (= (match-end 0) (point-max)))
6591 (outline-flag-region (point) (match-end 0) nil))))
6593 (defun org-show-empty-lines-in-parent ()
6594 "Move to the parent and re-show empty lines before visible headlines."
6595 (save-excursion
6596 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6597 (org-cycle-show-empty-lines context))))
6599 (defun org-files-list ()
6600 "Return `org-agenda-files' list, plus all open org-mode files.
6601 This is useful for operations that need to scan all of a user's
6602 open and agenda-wise Org files."
6603 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6604 (dolist (buf (buffer-list))
6605 (with-current-buffer buf
6606 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6607 (let ((file (expand-file-name (buffer-file-name))))
6608 (unless (member file files)
6609 (push file files))))))
6610 files))
6612 (defsubst org-entry-beginning-position ()
6613 "Return the beginning position of the current entry."
6614 (save-excursion (outline-back-to-heading t) (point)))
6616 (defsubst org-entry-end-position ()
6617 "Return the end position of the current entry."
6618 (save-excursion (outline-next-heading) (point)))
6620 (defun org-cycle-hide-drawers (state)
6621 "Re-hide all drawers after a visibility state change."
6622 (when (and (eq major-mode 'org-mode)
6623 (not (memq state '(overview folded contents))))
6624 (save-excursion
6625 (let* ((globalp (memq state '(contents all)))
6626 (beg (if globalp (point-min) (point)))
6627 (end (if globalp (point-max)
6628 (if (eq state 'children)
6629 (save-excursion (outline-next-heading) (point))
6630 (org-end-of-subtree t)))))
6631 (goto-char beg)
6632 (while (re-search-forward org-drawer-regexp end t)
6633 (org-flag-drawer t))))))
6635 (defun org-flag-drawer (flag)
6636 (save-excursion
6637 (beginning-of-line 1)
6638 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6639 (let ((b (match-end 0)))
6640 (if (re-search-forward
6641 "^[ \t]*:END:"
6642 (save-excursion (outline-next-heading) (point)) t)
6643 (outline-flag-region b (point-at-eol) flag)
6644 (error ":END: line missing at position %s" b))))))
6646 (defun org-subtree-end-visible-p ()
6647 "Is the end of the current subtree visible?"
6648 (pos-visible-in-window-p
6649 (save-excursion (org-end-of-subtree t) (point))))
6651 (defun org-first-headline-recenter (&optional N)
6652 "Move cursor to the first headline and recenter the headline.
6653 Optional argument N means put the headline into the Nth line of the window."
6654 (goto-char (point-min))
6655 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6656 (beginning-of-line)
6657 (recenter (prefix-numeric-value N))))
6659 ;;; Saving and restoring visibility
6661 (defun org-outline-overlay-data (&optional use-markers)
6662 "Return a list of the locations of all outline overlays.
6663 These are overlays with the `invisible' property value `outline'.
6664 The return value is a list of cons cells, with start and stop
6665 positions for each overlay.
6666 If USE-MARKERS is set, return the positions as markers."
6667 (let (beg end)
6668 (save-excursion
6669 (save-restriction
6670 (widen)
6671 (delq nil
6672 (mapcar (lambda (o)
6673 (when (eq (overlay-get o 'invisible) 'outline)
6674 (setq beg (overlay-start o)
6675 end (overlay-end o))
6676 (and beg end (> end beg)
6677 (if use-markers
6678 (cons (move-marker (make-marker) beg)
6679 (move-marker (make-marker) end))
6680 (cons beg end)))))
6681 (overlays-in (point-min) (point-max))))))))
6683 (defun org-set-outline-overlay-data (data)
6684 "Create visibility overlays for all positions in DATA.
6685 DATA should have been made by `org-outline-overlay-data'."
6686 (let (o)
6687 (save-excursion
6688 (save-restriction
6689 (widen)
6690 (show-all)
6691 (mapc (lambda (c)
6692 (outline-flag-region (car c) (cdr c) t))
6693 data)))))
6695 ;;; Folding of blocks
6697 (defvar org-hide-block-overlays nil
6698 "Overlays hiding blocks.")
6699 (make-variable-buffer-local 'org-hide-block-overlays)
6701 (defun org-block-map (function &optional start end)
6702 "Call FUNCTION at the head of all source blocks in the current buffer.
6703 Optional arguments START and END can be used to limit the range."
6704 (let ((start (or start (point-min)))
6705 (end (or end (point-max))))
6706 (save-excursion
6707 (goto-char start)
6708 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6709 (save-excursion
6710 (save-match-data
6711 (goto-char (match-beginning 0))
6712 (funcall function)))))))
6714 (defun org-hide-block-toggle-all ()
6715 "Toggle the visibility of all blocks in the current buffer."
6716 (org-block-map #'org-hide-block-toggle))
6718 (defun org-hide-block-all ()
6719 "Fold all blocks in the current buffer."
6720 (interactive)
6721 (org-show-block-all)
6722 (org-block-map #'org-hide-block-toggle-maybe))
6724 (defun org-show-block-all ()
6725 "Unfold all blocks in the current buffer."
6726 (interactive)
6727 (mapc 'delete-overlay org-hide-block-overlays)
6728 (setq org-hide-block-overlays nil))
6730 (defun org-hide-block-toggle-maybe ()
6731 "Toggle visibility of block at point."
6732 (interactive)
6733 (let ((case-fold-search t))
6734 (if (save-excursion
6735 (beginning-of-line 1)
6736 (looking-at org-block-regexp))
6737 (progn (org-hide-block-toggle)
6738 t) ;; to signal that we took action
6739 nil))) ;; to signal that we did not
6741 (defun org-hide-block-toggle (&optional force)
6742 "Toggle the visibility of the current block."
6743 (interactive)
6744 (save-excursion
6745 (beginning-of-line)
6746 (if (re-search-forward org-block-regexp nil t)
6747 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6748 (end (match-end 0)) ;; end of entire body
6750 (if (memq t (mapcar (lambda (overlay)
6751 (eq (overlay-get overlay 'invisible)
6752 'org-hide-block))
6753 (overlays-at start)))
6754 (if (or (not force) (eq force 'off))
6755 (mapc (lambda (ov)
6756 (when (member ov org-hide-block-overlays)
6757 (setq org-hide-block-overlays
6758 (delq ov org-hide-block-overlays)))
6759 (when (eq (overlay-get ov 'invisible)
6760 'org-hide-block)
6761 (delete-overlay ov)))
6762 (overlays-at start)))
6763 (setq ov (make-overlay start end))
6764 (overlay-put ov 'invisible 'org-hide-block)
6765 ;; make the block accessible to isearch
6766 (overlay-put
6767 ov 'isearch-open-invisible
6768 (lambda (ov)
6769 (when (member ov org-hide-block-overlays)
6770 (setq org-hide-block-overlays
6771 (delq ov org-hide-block-overlays)))
6772 (when (eq (overlay-get ov 'invisible)
6773 'org-hide-block)
6774 (delete-overlay ov))))
6775 (push ov org-hide-block-overlays)))
6776 (error "Not looking at a source block"))))
6778 ;; org-tab-after-check-for-cycling-hook
6779 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6780 ;; Remove overlays when changing major mode
6781 (add-hook 'org-mode-hook
6782 (lambda () (org-add-hook 'change-major-mode-hook
6783 'org-show-block-all 'append 'local)))
6785 ;;; Org-goto
6787 (defvar org-goto-window-configuration nil)
6788 (defvar org-goto-marker nil)
6789 (defvar org-goto-map
6790 (let ((map (make-sparse-keymap)))
6791 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6792 (while (setq cmd (pop cmds))
6793 (substitute-key-definition cmd cmd map global-map)))
6794 (suppress-keymap map)
6795 (org-defkey map "\C-m" 'org-goto-ret)
6796 (org-defkey map [(return)] 'org-goto-ret)
6797 (org-defkey map [(left)] 'org-goto-left)
6798 (org-defkey map [(right)] 'org-goto-right)
6799 (org-defkey map [(control ?g)] 'org-goto-quit)
6800 (org-defkey map "\C-i" 'org-cycle)
6801 (org-defkey map [(tab)] 'org-cycle)
6802 (org-defkey map [(down)] 'outline-next-visible-heading)
6803 (org-defkey map [(up)] 'outline-previous-visible-heading)
6804 (if org-goto-auto-isearch
6805 (if (fboundp 'define-key-after)
6806 (define-key-after map [t] 'org-goto-local-auto-isearch)
6807 nil)
6808 (org-defkey map "q" 'org-goto-quit)
6809 (org-defkey map "n" 'outline-next-visible-heading)
6810 (org-defkey map "p" 'outline-previous-visible-heading)
6811 (org-defkey map "f" 'outline-forward-same-level)
6812 (org-defkey map "b" 'outline-backward-same-level)
6813 (org-defkey map "u" 'outline-up-heading))
6814 (org-defkey map "/" 'org-occur)
6815 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6816 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6817 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6818 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6819 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6820 map))
6822 (defconst org-goto-help
6823 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6824 RET=jump to location [Q]uit and return to previous location
6825 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6827 (defvar org-goto-start-pos) ; dynamically scoped parameter
6829 ;; FIXME: Docstring does not mention both interfaces
6830 (defun org-goto (&optional alternative-interface)
6831 "Look up a different location in the current file, keeping current visibility.
6833 When you want look-up or go to a different location in a document, the
6834 fastest way is often to fold the entire buffer and then dive into the tree.
6835 This method has the disadvantage, that the previous location will be folded,
6836 which may not be what you want.
6838 This command works around this by showing a copy of the current buffer
6839 in an indirect buffer, in overview mode. You can dive into the tree in
6840 that copy, use org-occur and incremental search to find a location.
6841 When pressing RET or `Q', the command returns to the original buffer in
6842 which the visibility is still unchanged. After RET it will also jump to
6843 the location selected in the indirect buffer and expose the headline
6844 hierarchy above."
6845 (interactive "P")
6846 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6847 (org-refile-use-outline-path t)
6848 (org-refile-target-verify-function nil)
6849 (interface
6850 (if (not alternative-interface)
6851 org-goto-interface
6852 (if (eq org-goto-interface 'outline)
6853 'outline-path-completion
6854 'outline)))
6855 (org-goto-start-pos (point))
6856 (selected-point
6857 (if (eq interface 'outline)
6858 (car (org-get-location (current-buffer) org-goto-help))
6859 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6860 (org-refile-check-position pa)
6861 (nth 3 pa)))))
6862 (if selected-point
6863 (progn
6864 (org-mark-ring-push org-goto-start-pos)
6865 (goto-char selected-point)
6866 (if (or (outline-invisible-p) (org-invisible-p2))
6867 (org-show-context 'org-goto)))
6868 (message "Quit"))))
6870 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6871 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6872 (defvar org-goto-local-auto-isearch-map) ; defined below
6874 (defun org-get-location (buf help)
6875 "Let the user select a location in the Org-mode buffer BUF.
6876 This function uses a recursive edit. It returns the selected position
6877 or nil."
6878 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6879 (isearch-hide-immediately nil)
6880 (isearch-search-fun-function
6881 (lambda () 'org-goto-local-search-headings))
6882 (org-goto-selected-point org-goto-exit-command)
6883 (pop-up-frames nil)
6884 (special-display-buffer-names nil)
6885 (special-display-regexps nil)
6886 (special-display-function nil))
6887 (save-excursion
6888 (save-window-excursion
6889 (delete-other-windows)
6890 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6891 (org-pop-to-buffer-same-window
6892 (condition-case nil
6893 (make-indirect-buffer (current-buffer) "*org-goto*")
6894 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6895 (with-output-to-temp-buffer "*Help*"
6896 (princ help))
6897 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6898 (setq buffer-read-only nil)
6899 (let ((org-startup-truncated t)
6900 (org-startup-folded nil)
6901 (org-startup-align-all-tables nil))
6902 (org-mode)
6903 (org-overview))
6904 (setq buffer-read-only t)
6905 (if (and (boundp 'org-goto-start-pos)
6906 (integer-or-marker-p org-goto-start-pos))
6907 (let ((org-show-hierarchy-above t)
6908 (org-show-siblings t)
6909 (org-show-following-heading t))
6910 (goto-char org-goto-start-pos)
6911 (and (outline-invisible-p) (org-show-context)))
6912 (goto-char (point-min)))
6913 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6914 (message "Select location and press RET")
6915 (use-local-map org-goto-map)
6916 (recursive-edit)
6918 (kill-buffer "*org-goto*")
6919 (cons org-goto-selected-point org-goto-exit-command)))
6921 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6922 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6923 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6924 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6926 (defun org-goto-local-search-headings (string bound noerror)
6927 "Search and make sure that any matches are in headlines."
6928 (catch 'return
6929 (while (if isearch-forward
6930 (search-forward string bound noerror)
6931 (search-backward string bound noerror))
6932 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6933 (and (member :headline context)
6934 (not (member :tags context))))
6935 (throw 'return (point))))))
6937 (defun org-goto-local-auto-isearch ()
6938 "Start isearch."
6939 (interactive)
6940 (goto-char (point-min))
6941 (let ((keys (this-command-keys)))
6942 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6943 (isearch-mode t)
6944 (isearch-process-search-char (string-to-char keys)))))
6946 (defun org-goto-ret (&optional arg)
6947 "Finish `org-goto' by going to the new location."
6948 (interactive "P")
6949 (setq org-goto-selected-point (point)
6950 org-goto-exit-command 'return)
6951 (throw 'exit nil))
6953 (defun org-goto-left ()
6954 "Finish `org-goto' by going to the new location."
6955 (interactive)
6956 (if (org-at-heading-p)
6957 (progn
6958 (beginning-of-line 1)
6959 (setq org-goto-selected-point (point)
6960 org-goto-exit-command 'left)
6961 (throw 'exit nil))
6962 (error "Not on a heading")))
6964 (defun org-goto-right ()
6965 "Finish `org-goto' by going to the new location."
6966 (interactive)
6967 (if (org-at-heading-p)
6968 (progn
6969 (setq org-goto-selected-point (point)
6970 org-goto-exit-command 'right)
6971 (throw 'exit nil))
6972 (error "Not on a heading")))
6974 (defun org-goto-quit ()
6975 "Finish `org-goto' without cursor motion."
6976 (interactive)
6977 (setq org-goto-selected-point nil)
6978 (setq org-goto-exit-command 'quit)
6979 (throw 'exit nil))
6981 ;;; Indirect buffer display of subtrees
6983 (defvar org-indirect-dedicated-frame nil
6984 "This is the frame being used for indirect tree display.")
6985 (defvar org-last-indirect-buffer nil)
6987 (defun org-tree-to-indirect-buffer (&optional arg)
6988 "Create indirect buffer and narrow it to current subtree.
6989 With numerical prefix ARG, go up to this level and then take that tree.
6990 If ARG is negative, go up that many levels.
6991 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6992 indirect buffer previously made with this command, to avoid proliferation of
6993 indirect buffers. However, when you call the command with a \
6994 \\[universal-argument] prefix, or
6995 when `org-indirect-buffer-display' is `new-frame', the last buffer
6996 is kept so that you can work with several indirect buffers at the same time.
6997 If `org-indirect-buffer-display' is `dedicated-frame', the \
6998 \\[universal-argument] prefix also
6999 requests that a new frame be made for the new buffer, so that the dedicated
7000 frame is not changed."
7001 (interactive "P")
7002 (let ((cbuf (current-buffer))
7003 (cwin (selected-window))
7004 (pos (point))
7005 beg end level heading ibuf)
7006 (save-excursion
7007 (org-back-to-heading t)
7008 (when (numberp arg)
7009 (setq level (org-outline-level))
7010 (if (< arg 0) (setq arg (+ level arg)))
7011 (while (> (setq level (org-outline-level)) arg)
7012 (outline-up-heading 1 t)))
7013 (setq beg (point)
7014 heading (org-get-heading))
7015 (org-end-of-subtree t t)
7016 (if (org-at-heading-p) (backward-char 1))
7017 (setq end (point)))
7018 (if (and (buffer-live-p org-last-indirect-buffer)
7019 (not (eq org-indirect-buffer-display 'new-frame))
7020 (not arg))
7021 (kill-buffer org-last-indirect-buffer))
7022 (setq ibuf (org-get-indirect-buffer cbuf)
7023 org-last-indirect-buffer ibuf)
7024 (cond
7025 ((or (eq org-indirect-buffer-display 'new-frame)
7026 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7027 (select-frame (make-frame))
7028 (delete-other-windows)
7029 (org-pop-to-buffer-same-window ibuf)
7030 (org-set-frame-title heading))
7031 ((eq org-indirect-buffer-display 'dedicated-frame)
7032 (raise-frame
7033 (select-frame (or (and org-indirect-dedicated-frame
7034 (frame-live-p org-indirect-dedicated-frame)
7035 org-indirect-dedicated-frame)
7036 (setq org-indirect-dedicated-frame (make-frame)))))
7037 (delete-other-windows)
7038 (org-pop-to-buffer-same-window ibuf)
7039 (org-set-frame-title (concat "Indirect: " heading)))
7040 ((eq org-indirect-buffer-display 'current-window)
7041 (org-pop-to-buffer-same-window ibuf))
7042 ((eq org-indirect-buffer-display 'other-window)
7043 (pop-to-buffer ibuf))
7044 (t (error "Invalid value")))
7045 (if (featurep 'xemacs)
7046 (save-excursion (org-mode) (turn-on-font-lock)))
7047 (narrow-to-region beg end)
7048 (show-all)
7049 (goto-char pos)
7050 (run-hook-with-args 'org-cycle-hook 'all)
7051 (and (window-live-p cwin) (select-window cwin))))
7053 (defun org-get-indirect-buffer (&optional buffer)
7054 (setq buffer (or buffer (current-buffer)))
7055 (let ((n 1) (base (buffer-name buffer)) bname)
7056 (while (buffer-live-p
7057 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7058 (setq n (1+ n)))
7059 (condition-case nil
7060 (make-indirect-buffer buffer bname 'clone)
7061 (error (make-indirect-buffer buffer bname)))))
7063 (defun org-set-frame-title (title)
7064 "Set the title of the current frame to the string TITLE."
7065 ;; FIXME: how to name a single frame in XEmacs???
7066 (unless (featurep 'xemacs)
7067 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7069 ;;;; Structure editing
7071 ;;; Inserting headlines
7073 (defun org-previous-line-empty-p ()
7074 (save-excursion
7075 (and (not (bobp))
7076 (or (beginning-of-line 0) t)
7077 (save-match-data
7078 (looking-at "[ \t]*$")))))
7080 (defun org-insert-heading (&optional force-heading invisible-ok)
7081 "Insert a new heading or item with same depth at point.
7082 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7083 If point is at the beginning of a headline, insert a sibling before the
7084 current headline. If point is not at the beginning, split the line,
7085 create the new headline with the text in the current line after point
7086 \(but see also the variable `org-M-RET-may-split-line').
7088 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7089 This is important for non-interactive uses of the command."
7090 (interactive "P")
7091 (if (or (= (buffer-size) 0)
7092 (and (not (save-excursion
7093 (and (ignore-errors (org-back-to-heading invisible-ok))
7094 (org-at-heading-p))))
7095 (or force-heading (not (org-in-item-p)))))
7096 (progn
7097 (insert "\n* ")
7098 (run-hooks 'org-insert-heading-hook))
7099 (when (or force-heading (not (org-insert-item)))
7100 (let* ((empty-line-p nil)
7101 (level nil)
7102 (on-heading (org-at-heading-p))
7103 (head (save-excursion
7104 (condition-case nil
7105 (progn
7106 (org-back-to-heading invisible-ok)
7107 (when (and (not on-heading)
7108 (featurep 'org-inlinetask)
7109 (integerp org-inlinetask-min-level)
7110 (>= (length (match-string 0))
7111 org-inlinetask-min-level))
7112 ;; Find a heading level before the inline task
7113 (while (and (setq level (org-up-heading-safe))
7114 (>= level org-inlinetask-min-level)))
7115 (if (org-at-heading-p)
7116 (org-back-to-heading invisible-ok)
7117 (error "This should not happen")))
7118 (setq empty-line-p (org-previous-line-empty-p))
7119 (match-string 0))
7120 (error "*"))))
7121 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7122 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7123 pos hide-previous previous-pos)
7124 (cond
7125 ((and (org-at-heading-p) (bolp)
7126 (or (bobp)
7127 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7128 ;; insert before the current line
7129 (open-line (if blank 2 1)))
7130 ((and (bolp)
7131 (not org-insert-heading-respect-content)
7132 (or (bobp)
7133 (save-excursion
7134 (backward-char 1) (not (outline-invisible-p)))))
7135 ;; insert right here
7136 nil)
7138 ;; somewhere in the line
7139 (save-excursion
7140 (setq previous-pos (point-at-bol))
7141 (end-of-line)
7142 (setq hide-previous (outline-invisible-p)))
7143 (and org-insert-heading-respect-content (org-show-subtree))
7144 (let ((split
7145 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7146 (save-excursion
7147 (let ((p (point)))
7148 (goto-char (point-at-bol))
7149 (and (looking-at org-complex-heading-regexp)
7150 (match-beginning 4)
7151 (> p (match-beginning 4)))))))
7152 tags pos)
7153 (cond
7154 (org-insert-heading-respect-content
7155 (org-end-of-subtree nil t)
7156 (when (featurep 'org-inlinetask)
7157 (while (and (not (eobp))
7158 (looking-at "\\(\\*+\\)[ \t]+")
7159 (>= (length (match-string 1))
7160 org-inlinetask-min-level))
7161 (org-end-of-subtree nil t)))
7162 (or (bolp) (newline))
7163 (or (org-previous-line-empty-p)
7164 (and blank (newline)))
7165 (open-line 1))
7166 ((org-at-heading-p)
7167 (when hide-previous
7168 (show-children)
7169 (org-show-entry))
7170 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7171 (setq tags (and (match-end 2) (match-string 2)))
7172 (and (match-end 1)
7173 (delete-region (match-beginning 1) (match-end 1)))
7174 (setq pos (point-at-bol))
7175 (or split (end-of-line 1))
7176 (delete-horizontal-space)
7177 (if (string-match "\\`\\*+\\'"
7178 (buffer-substring (point-at-bol) (point)))
7179 (insert " "))
7180 (newline (if blank 2 1))
7181 (when tags
7182 (save-excursion
7183 (goto-char pos)
7184 (end-of-line 1)
7185 (insert " " tags)
7186 (org-set-tags nil 'align))))
7188 (or split (end-of-line 1))
7189 (newline (if blank 2 1)))))))
7190 (insert head) (just-one-space)
7191 (setq pos (point))
7192 (end-of-line 1)
7193 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7194 (when (and org-insert-heading-respect-content hide-previous)
7195 (save-excursion
7196 (goto-char previous-pos)
7197 (hide-subtree)))
7198 (run-hooks 'org-insert-heading-hook)))))
7200 (defun org-get-heading (&optional no-tags no-todo)
7201 "Return the heading of the current entry, without the stars.
7202 When NO-TAGS is non-nil, don't include tags.
7203 When NO-TODO is non-nil, don't include TODO keywords."
7204 (save-excursion
7205 (org-back-to-heading t)
7206 (cond
7207 ((and no-tags no-todo)
7208 (looking-at org-complex-heading-regexp)
7209 (match-string 4))
7210 (no-tags
7211 (looking-at (concat org-outline-regexp
7212 "\\(.*?\\)"
7213 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7214 (match-string 1))
7215 (no-todo
7216 (looking-at org-todo-line-regexp)
7217 (match-string 3))
7218 (t (looking-at org-heading-regexp)
7219 (match-string 2)))))
7221 (defun org-heading-components ()
7222 "Return the components of the current heading.
7223 This is a list with the following elements:
7224 - the level as an integer
7225 - the reduced level, different if `org-odd-levels-only' is set.
7226 - the TODO keyword, or nil
7227 - the priority character, like ?A, or nil if no priority is given
7228 - the headline text itself, or the tags string if no headline text
7229 - the tags string, or nil."
7230 (save-excursion
7231 (org-back-to-heading t)
7232 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7233 (list (length (match-string 1))
7234 (org-reduced-level (length (match-string 1)))
7235 (org-match-string-no-properties 2)
7236 (and (match-end 3) (aref (match-string 3) 2))
7237 (org-match-string-no-properties 4)
7238 (org-match-string-no-properties 5)))))
7240 (defun org-get-entry ()
7241 "Get the entry text, after heading, entire subtree."
7242 (save-excursion
7243 (org-back-to-heading t)
7244 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7246 (defun org-insert-heading-after-current ()
7247 "Insert a new heading with same level as current, after current subtree."
7248 (interactive)
7249 (org-back-to-heading)
7250 (org-insert-heading)
7251 (org-move-subtree-down)
7252 (end-of-line 1))
7254 (defun org-insert-heading-respect-content ()
7255 (interactive)
7256 (let ((org-insert-heading-respect-content t))
7257 (org-insert-heading t)))
7259 (defun org-insert-todo-heading-respect-content (&optional force-state)
7260 (interactive "P")
7261 (let ((org-insert-heading-respect-content t))
7262 (org-insert-todo-heading force-state t)))
7264 (defun org-insert-todo-heading (arg &optional force-heading)
7265 "Insert a new heading with the same level and TODO state as current heading.
7266 If the heading has no TODO state, or if the state is DONE, use the first
7267 state (TODO by default). Also with prefix arg, force first state."
7268 (interactive "P")
7269 (when (or force-heading (not (org-insert-item 'checkbox)))
7270 (org-insert-heading force-heading)
7271 (save-excursion
7272 (org-back-to-heading)
7273 (outline-previous-heading)
7274 (looking-at org-todo-line-regexp))
7275 (let*
7276 ((new-mark-x
7277 (if (or arg
7278 (not (match-beginning 2))
7279 (member (match-string 2) org-done-keywords))
7280 (car org-todo-keywords-1)
7281 (match-string 2)))
7282 (new-mark
7284 (run-hook-with-args-until-success
7285 'org-todo-get-default-hook new-mark-x nil)
7286 new-mark-x)))
7287 (beginning-of-line 1)
7288 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7289 (if org-treat-insert-todo-heading-as-state-change
7290 (org-todo new-mark)
7291 (insert new-mark " "))))
7292 (when org-provide-todo-statistics
7293 (org-update-parent-todo-statistics))))
7295 (defun org-insert-subheading (arg)
7296 "Insert a new subheading and demote it.
7297 Works for outline headings and for plain lists alike."
7298 (interactive "P")
7299 (org-insert-heading arg)
7300 (cond
7301 ((org-at-heading-p) (org-do-demote))
7302 ((org-at-item-p) (org-indent-item))))
7304 (defun org-insert-todo-subheading (arg)
7305 "Insert a new subheading with TODO keyword or checkbox and demote it.
7306 Works for outline headings and for plain lists alike."
7307 (interactive "P")
7308 (org-insert-todo-heading arg)
7309 (cond
7310 ((org-at-heading-p) (org-do-demote))
7311 ((org-at-item-p) (org-indent-item))))
7313 ;;; Promotion and Demotion
7315 (defvar org-after-demote-entry-hook nil
7316 "Hook run after an entry has been demoted.
7317 The cursor will be at the beginning of the entry.
7318 When a subtree is being demoted, the hook will be called for each node.")
7320 (defvar org-after-promote-entry-hook nil
7321 "Hook run after an entry has been promoted.
7322 The cursor will be at the beginning of the entry.
7323 When a subtree is being promoted, the hook will be called for each node.")
7325 (defun org-promote-subtree ()
7326 "Promote the entire subtree.
7327 See also `org-promote'."
7328 (interactive)
7329 (save-excursion
7330 (org-with-limited-levels (org-map-tree 'org-promote)))
7331 (org-fix-position-after-promote))
7333 (defun org-demote-subtree ()
7334 "Demote the entire subtree. See `org-demote'.
7335 See also `org-promote'."
7336 (interactive)
7337 (save-excursion
7338 (org-with-limited-levels (org-map-tree 'org-demote)))
7339 (org-fix-position-after-promote))
7342 (defun org-do-promote ()
7343 "Promote the current heading higher up the tree.
7344 If the region is active in `transient-mark-mode', promote all headings
7345 in the region."
7346 (interactive)
7347 (save-excursion
7348 (if (org-region-active-p)
7349 (org-map-region 'org-promote (region-beginning) (region-end))
7350 (org-promote)))
7351 (org-fix-position-after-promote))
7353 (defun org-do-demote ()
7354 "Demote the current heading lower down the tree.
7355 If the region is active in `transient-mark-mode', demote all headings
7356 in the region."
7357 (interactive)
7358 (save-excursion
7359 (if (org-region-active-p)
7360 (org-map-region 'org-demote (region-beginning) (region-end))
7361 (org-demote)))
7362 (org-fix-position-after-promote))
7364 (defun org-fix-position-after-promote ()
7365 "Make sure that after pro/demotion cursor position is right."
7366 (let ((pos (point)))
7367 (when (save-excursion
7368 (beginning-of-line 1)
7369 (looking-at org-todo-line-regexp)
7370 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7371 (cond ((eobp) (insert " "))
7372 ((eolp) (insert " "))
7373 ((equal (char-after) ?\ ) (forward-char 1))))))
7375 (defun org-current-level ()
7376 "Return the level of the current entry, or nil if before the first headline.
7377 The level is the number of stars at the beginning of the headline."
7378 (save-excursion
7379 (org-with-limited-levels
7380 (if (ignore-errors (org-back-to-heading t))
7381 (funcall outline-level)))))
7383 (defun org-get-previous-line-level ()
7384 "Return the outline depth of the last headline before the current line.
7385 Returns 0 for the first headline in the buffer, and nil if before the
7386 first headline."
7387 (let ((current-level (org-current-level))
7388 (prev-level (when (> (line-number-at-pos) 1)
7389 (save-excursion
7390 (beginning-of-line 0)
7391 (org-current-level)))))
7392 (cond ((null current-level) nil) ; Before first headline
7393 ((null prev-level) 0) ; At first headline
7394 (prev-level))))
7396 (defun org-reduced-level (l)
7397 "Compute the effective level of a heading.
7398 This takes into account the setting of `org-odd-levels-only'."
7399 (cond
7400 ((zerop l) 0)
7401 (org-odd-levels-only (1+ (floor (/ l 2))))
7402 (t l)))
7404 (defun org-level-increment ()
7405 "Return the number of stars that will be added or removed at a
7406 time to headlines when structure editing, based on the value of
7407 `org-odd-levels-only'."
7408 (if org-odd-levels-only 2 1))
7410 (defun org-get-valid-level (level &optional change)
7411 "Rectify a level change under the influence of `org-odd-levels-only'
7412 LEVEL is a current level, CHANGE is by how much the level should be
7413 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7414 even level numbers will become the next higher odd number."
7415 (if org-odd-levels-only
7416 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7417 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7418 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7419 (max 1 (+ level (or change 0)))))
7421 (if (boundp 'define-obsolete-function-alias)
7422 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7423 (define-obsolete-function-alias 'org-get-legal-level
7424 'org-get-valid-level)
7425 (define-obsolete-function-alias 'org-get-legal-level
7426 'org-get-valid-level "23.1")))
7428 (defun org-promote ()
7429 "Promote the current heading higher up the tree.
7430 If the region is active in `transient-mark-mode', promote all headings
7431 in the region."
7432 (org-back-to-heading t)
7433 (let* ((level (save-match-data (funcall outline-level)))
7434 (after-change-functions (remove 'flyspell-after-change-function
7435 after-change-functions))
7436 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7437 (diff (abs (- level (length up-head) -1))))
7438 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7439 (replace-match up-head nil t)
7440 ;; Fixup tag positioning
7441 (and org-auto-align-tags (org-set-tags nil t))
7442 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7443 (run-hooks 'org-after-promote-entry-hook)))
7445 (defun org-demote ()
7446 "Demote the current heading lower down the tree.
7447 If the region is active in `transient-mark-mode', demote all headings
7448 in the region."
7449 (org-back-to-heading t)
7450 (let* ((level (save-match-data (funcall outline-level)))
7451 (after-change-functions (remove 'flyspell-after-change-function
7452 after-change-functions))
7453 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7454 (diff (abs (- level (length down-head) -1))))
7455 (replace-match down-head nil t)
7456 ;; Fixup tag positioning
7457 (and org-auto-align-tags (org-set-tags nil t))
7458 (if org-adapt-indentation (org-fixup-indentation diff))
7459 (run-hooks 'org-after-demote-entry-hook)))
7461 (defun org-cycle-level ()
7462 "Cycle the level of an empty headline through possible states.
7463 This goes first to child, then to parent, level, then up the hierarchy.
7464 After top level, it switches back to sibling level."
7465 (interactive)
7466 (let ((org-adapt-indentation nil))
7467 (when (org-point-at-end-of-empty-headline)
7468 (setq this-command 'org-cycle-level) ; Only needed for caching
7469 (let ((cur-level (org-current-level))
7470 (prev-level (org-get-previous-line-level)))
7471 (cond
7472 ;; If first headline in file, promote to top-level.
7473 ((= prev-level 0)
7474 (loop repeat (/ (- cur-level 1) (org-level-increment))
7475 do (org-do-promote)))
7476 ;; If same level as prev, demote one.
7477 ((= prev-level cur-level)
7478 (org-do-demote))
7479 ;; If parent is top-level, promote to top level if not already.
7480 ((= prev-level 1)
7481 (loop repeat (/ (- cur-level 1) (org-level-increment))
7482 do (org-do-promote)))
7483 ;; If top-level, return to prev-level.
7484 ((= cur-level 1)
7485 (loop repeat (/ (- prev-level 1) (org-level-increment))
7486 do (org-do-demote)))
7487 ;; If less than prev-level, promote one.
7488 ((< cur-level prev-level)
7489 (org-do-promote))
7490 ;; If deeper than prev-level, promote until higher than
7491 ;; prev-level.
7492 ((> cur-level prev-level)
7493 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7494 do (org-do-promote))))
7495 t))))
7497 (defun org-map-tree (fun)
7498 "Call FUN for every heading underneath the current one."
7499 (org-back-to-heading)
7500 (let ((level (funcall outline-level)))
7501 (save-excursion
7502 (funcall fun)
7503 (while (and (progn
7504 (outline-next-heading)
7505 (> (funcall outline-level) level))
7506 (not (eobp)))
7507 (funcall fun)))))
7509 (defun org-map-region (fun beg end)
7510 "Call FUN for every heading between BEG and END."
7511 (let ((org-ignore-region t))
7512 (save-excursion
7513 (setq end (copy-marker end))
7514 (goto-char beg)
7515 (if (and (re-search-forward org-outline-regexp-bol nil t)
7516 (< (point) end))
7517 (funcall fun))
7518 (while (and (progn
7519 (outline-next-heading)
7520 (< (point) end))
7521 (not (eobp)))
7522 (funcall fun)))))
7524 (defvar org-property-end-re) ; silence byte-compiler
7525 (defun org-fixup-indentation (diff)
7526 "Change the indentation in the current entry by DIFF.
7527 However, if any line in the current entry has no indentation, or if it
7528 would end up with no indentation after the change, nothing at all is done."
7529 (save-excursion
7530 (let ((end (save-excursion (outline-next-heading)
7531 (point-marker)))
7532 (prohibit (if (> diff 0)
7533 "^\\S-"
7534 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7535 col)
7536 (unless (save-excursion (end-of-line 1)
7537 (re-search-forward prohibit end t))
7538 (while (and (< (point) end)
7539 (re-search-forward "^[ \t]+" end t))
7540 (goto-char (match-end 0))
7541 (setq col (current-column))
7542 (if (< diff 0) (replace-match ""))
7543 (org-indent-to-column (+ diff col))))
7544 (move-marker end nil))))
7546 (defun org-convert-to-odd-levels ()
7547 "Convert an org-mode file with all levels allowed to one with odd levels.
7548 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7549 level 5 etc."
7550 (interactive)
7551 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7552 (let ((outline-level 'org-outline-level)
7553 (org-odd-levels-only nil) n)
7554 (save-excursion
7555 (goto-char (point-min))
7556 (while (re-search-forward "^\\*\\*+ " nil t)
7557 (setq n (- (length (match-string 0)) 2))
7558 (while (>= (setq n (1- n)) 0)
7559 (org-demote))
7560 (end-of-line 1))))))
7562 (defun org-convert-to-oddeven-levels ()
7563 "Convert an org-mode file with only odd levels to one with odd/even levels.
7564 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7565 file contains a section with an even level, conversion would
7566 destroy the structure of the file. An error is signaled in this
7567 case."
7568 (interactive)
7569 (goto-char (point-min))
7570 ;; First check if there are no even levels
7571 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7572 (org-show-context t)
7573 (error "Not all levels are odd in this file. Conversion not possible"))
7574 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7575 (let ((outline-regexp org-outline-regexp)
7576 (outline-level 'org-outline-level)
7577 (org-odd-levels-only nil) n)
7578 (save-excursion
7579 (goto-char (point-min))
7580 (while (re-search-forward "^\\*\\*+ " nil t)
7581 (setq n (/ (1- (length (match-string 0))) 2))
7582 (while (>= (setq n (1- n)) 0)
7583 (org-promote))
7584 (end-of-line 1))))))
7586 (defun org-tr-level (n)
7587 "Make N odd if required."
7588 (if org-odd-levels-only (1+ (/ n 2)) n))
7590 ;;; Vertical tree motion, cutting and pasting of subtrees
7592 (defun org-move-subtree-up (&optional arg)
7593 "Move the current subtree up past ARG headlines of the same level."
7594 (interactive "p")
7595 (org-move-subtree-down (- (prefix-numeric-value arg))))
7597 (defun org-move-subtree-down (&optional arg)
7598 "Move the current subtree down past ARG headlines of the same level."
7599 (interactive "p")
7600 (setq arg (prefix-numeric-value arg))
7601 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7602 'org-get-last-sibling))
7603 (ins-point (make-marker))
7604 (cnt (abs arg))
7605 (col (current-column))
7606 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7607 ;; Select the tree
7608 (org-back-to-heading)
7609 (setq beg0 (point))
7610 (save-excursion
7611 (setq ne-beg (org-back-over-empty-lines))
7612 (setq beg (point)))
7613 (save-match-data
7614 (save-excursion (outline-end-of-heading)
7615 (setq folded (outline-invisible-p)))
7616 (outline-end-of-subtree))
7617 (outline-next-heading)
7618 (setq ne-end (org-back-over-empty-lines))
7619 (setq end (point))
7620 (goto-char beg0)
7621 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7622 ;; include less whitespace
7623 (save-excursion
7624 (goto-char beg)
7625 (forward-line (- ne-beg ne-end))
7626 (setq beg (point))))
7627 ;; Find insertion point, with error handling
7628 (while (> cnt 0)
7629 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7630 (progn (goto-char beg0)
7631 (error "Cannot move past superior level or buffer limit")))
7632 (setq cnt (1- cnt)))
7633 (if (> arg 0)
7634 ;; Moving forward - still need to move over subtree
7635 (progn (org-end-of-subtree t t)
7636 (save-excursion
7637 (org-back-over-empty-lines)
7638 (or (bolp) (newline)))))
7639 (setq ne-ins (org-back-over-empty-lines))
7640 (move-marker ins-point (point))
7641 (setq txt (buffer-substring beg end))
7642 (org-save-markers-in-region beg end)
7643 (delete-region beg end)
7644 (org-remove-empty-overlays-at beg)
7645 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7646 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7647 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7648 (let ((bbb (point)))
7649 (insert-before-markers txt)
7650 (org-reinstall-markers-in-region bbb)
7651 (move-marker ins-point bbb))
7652 (or (bolp) (insert "\n"))
7653 (setq ins-end (point))
7654 (goto-char ins-point)
7655 (org-skip-whitespace)
7656 (when (and (< arg 0)
7657 (org-first-sibling-p)
7658 (> ne-ins ne-beg))
7659 ;; Move whitespace back to beginning
7660 (save-excursion
7661 (goto-char ins-end)
7662 (let ((kill-whole-line t))
7663 (kill-line (- ne-ins ne-beg)) (point)))
7664 (insert (make-string (- ne-ins ne-beg) ?\n)))
7665 (move-marker ins-point nil)
7666 (if folded
7667 (hide-subtree)
7668 (org-show-entry)
7669 (show-children)
7670 (org-cycle-hide-drawers 'children))
7671 (org-clean-visibility-after-subtree-move)
7672 ;; move back to the initial column we were at
7673 (move-to-column col)))
7675 (defvar org-subtree-clip ""
7676 "Clipboard for cut and paste of subtrees.
7677 This is actually only a copy of the kill, because we use the normal kill
7678 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7680 (defvar org-subtree-clip-folded nil
7681 "Was the last copied subtree folded?
7682 This is used to fold the tree back after pasting.")
7684 (defun org-cut-subtree (&optional n)
7685 "Cut the current subtree into the clipboard.
7686 With prefix arg N, cut this many sequential subtrees.
7687 This is a short-hand for marking the subtree and then cutting it."
7688 (interactive "p")
7689 (org-copy-subtree n 'cut))
7691 (defun org-copy-subtree (&optional n cut force-store-markers)
7692 "Cut the current subtree into the clipboard.
7693 With prefix arg N, cut this many sequential subtrees.
7694 This is a short-hand for marking the subtree and then copying it.
7695 If CUT is non-nil, actually cut the subtree.
7696 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7697 of some markers in the region, even if CUT is non-nil. This is
7698 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7699 (interactive "p")
7700 (let (beg end folded (beg0 (point)))
7701 (if (org-called-interactively-p 'any)
7702 (org-back-to-heading nil) ; take what looks like a subtree
7703 (org-back-to-heading t)) ; take what is really there
7704 (org-back-over-empty-lines)
7705 (setq beg (point))
7706 (skip-chars-forward " \t\r\n")
7707 (save-match-data
7708 (save-excursion (outline-end-of-heading)
7709 (setq folded (outline-invisible-p)))
7710 (condition-case nil
7711 (org-forward-same-level (1- n) t)
7712 (error nil))
7713 (org-end-of-subtree t t))
7714 (org-back-over-empty-lines)
7715 (setq end (point))
7716 (goto-char beg0)
7717 (when (> end beg)
7718 (setq org-subtree-clip-folded folded)
7719 (when (or cut force-store-markers)
7720 (org-save-markers-in-region beg end))
7721 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7722 (setq org-subtree-clip (current-kill 0))
7723 (message "%s: Subtree(s) with %d characters"
7724 (if cut "Cut" "Copied")
7725 (length org-subtree-clip)))))
7727 (defun org-paste-subtree (&optional level tree for-yank)
7728 "Paste the clipboard as a subtree, with modification of headline level.
7729 The entire subtree is promoted or demoted in order to match a new headline
7730 level.
7732 If the cursor is at the beginning of a headline, the same level as
7733 that headline is used to paste the tree
7735 If not, the new level is derived from the *visible* headings
7736 before and after the insertion point, and taken to be the inferior headline
7737 level of the two. So if the previous visible heading is level 3 and the
7738 next is level 4 (or vice versa), level 4 will be used for insertion.
7739 This makes sure that the subtree remains an independent subtree and does
7740 not swallow low level entries.
7742 You can also force a different level, either by using a numeric prefix
7743 argument, or by inserting the heading marker by hand. For example, if the
7744 cursor is after \"*****\", then the tree will be shifted to level 5.
7746 If optional TREE is given, use this text instead of the kill ring.
7748 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7749 move back over whitespace before inserting, and move point to the end of
7750 the inserted text when done."
7751 (interactive "P")
7752 (setq tree (or tree (and kill-ring (current-kill 0))))
7753 (unless (org-kill-is-subtree-p tree)
7754 (error "%s"
7755 (substitute-command-keys
7756 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7757 (org-with-limited-levels
7758 (let* ((visp (not (outline-invisible-p)))
7759 (txt tree)
7760 (^re_ "\\(\\*+\\)[ \t]*")
7761 (old-level (if (string-match org-outline-regexp-bol txt)
7762 (- (match-end 0) (match-beginning 0) 1)
7763 -1))
7764 (force-level (cond (level (prefix-numeric-value level))
7765 ((and (looking-at "[ \t]*$")
7766 (string-match
7767 "^\\*+$" (buffer-substring
7768 (point-at-bol) (point))))
7769 (- (match-end 1) (match-beginning 1)))
7770 ((and (bolp)
7771 (looking-at org-outline-regexp))
7772 (- (match-end 0) (point) 1))
7773 (t nil)))
7774 (previous-level (save-excursion
7775 (condition-case nil
7776 (progn
7777 (outline-previous-visible-heading 1)
7778 (if (looking-at ^re_)
7779 (- (match-end 0) (match-beginning 0) 1)
7781 (error 1))))
7782 (next-level (save-excursion
7783 (condition-case nil
7784 (progn
7785 (or (looking-at org-outline-regexp)
7786 (outline-next-visible-heading 1))
7787 (if (looking-at ^re_)
7788 (- (match-end 0) (match-beginning 0) 1)
7790 (error 1))))
7791 (new-level (or force-level (max previous-level next-level)))
7792 (shift (if (or (= old-level -1)
7793 (= new-level -1)
7794 (= old-level new-level))
7796 (- new-level old-level)))
7797 (delta (if (> shift 0) -1 1))
7798 (func (if (> shift 0) 'org-demote 'org-promote))
7799 (org-odd-levels-only nil)
7800 beg end newend)
7801 ;; Remove the forced level indicator
7802 (if force-level
7803 (delete-region (point-at-bol) (point)))
7804 ;; Paste
7805 (beginning-of-line (if (bolp) 1 2))
7806 (unless for-yank (org-back-over-empty-lines))
7807 (setq beg (point))
7808 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7809 (insert-before-markers txt)
7810 (unless (string-match "\n\\'" txt) (insert "\n"))
7811 (setq newend (point))
7812 (org-reinstall-markers-in-region beg)
7813 (setq end (point))
7814 (goto-char beg)
7815 (skip-chars-forward " \t\n\r")
7816 (setq beg (point))
7817 (if (and (outline-invisible-p) visp)
7818 (save-excursion (outline-show-heading)))
7819 ;; Shift if necessary
7820 (unless (= shift 0)
7821 (save-restriction
7822 (narrow-to-region beg end)
7823 (while (not (= shift 0))
7824 (org-map-region func (point-min) (point-max))
7825 (setq shift (+ delta shift)))
7826 (goto-char (point-min))
7827 (setq newend (point-max))))
7828 (when (or (org-called-interactively-p 'interactive) for-yank)
7829 (message "Clipboard pasted as level %d subtree" new-level))
7830 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7831 kill-ring
7832 (eq org-subtree-clip (current-kill 0))
7833 org-subtree-clip-folded)
7834 ;; The tree was folded before it was killed/copied
7835 (hide-subtree))
7836 (and for-yank (goto-char newend)))))
7838 (defun org-kill-is-subtree-p (&optional txt)
7839 "Check if the current kill is an outline subtree, or a set of trees.
7840 Returns nil if kill does not start with a headline, or if the first
7841 headline level is not the largest headline level in the tree.
7842 So this will actually accept several entries of equal levels as well,
7843 which is OK for `org-paste-subtree'.
7844 If optional TXT is given, check this string instead of the current kill."
7845 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7846 (re (org-get-limited-outline-regexp))
7847 (^re (concat "^" re))
7848 (start-level (and kill
7849 (string-match
7850 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7851 kill)
7852 (- (match-end 2) (match-beginning 2) 1)))
7853 (start (1+ (or (match-beginning 2) -1))))
7854 (if (not start-level)
7855 (progn
7856 nil) ;; does not even start with a heading
7857 (catch 'exit
7858 (while (setq start (string-match ^re kill (1+ start)))
7859 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7860 (throw 'exit nil)))
7861 t))))
7863 (defvar org-markers-to-move nil
7864 "Markers that should be moved with a cut-and-paste operation.
7865 Those markers are stored together with their positions relative to
7866 the start of the region.")
7868 (defun org-save-markers-in-region (beg end)
7869 "Check markers in region.
7870 If these markers are between BEG and END, record their position relative
7871 to BEG, so that after moving the block of text, we can put the markers back
7872 into place.
7873 This function gets called just before an entry or tree gets cut from the
7874 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7875 called immediately, to move the markers with the entries."
7876 (setq org-markers-to-move nil)
7877 (when (featurep 'org-clock)
7878 (org-clock-save-markers-for-cut-and-paste beg end))
7879 (when (featurep 'org-agenda)
7880 (org-agenda-save-markers-for-cut-and-paste beg end)))
7882 (defun org-check-and-save-marker (marker beg end)
7883 "Check if MARKER is between BEG and END.
7884 If yes, remember the marker and the distance to BEG."
7885 (when (and (marker-buffer marker)
7886 (equal (marker-buffer marker) (current-buffer)))
7887 (if (and (>= marker beg) (< marker end))
7888 (push (cons marker (- marker beg)) org-markers-to-move))))
7890 (defun org-reinstall-markers-in-region (beg)
7891 "Move all remembered markers to their position relative to BEG."
7892 (mapc (lambda (x)
7893 (move-marker (car x) (+ beg (cdr x))))
7894 org-markers-to-move)
7895 (setq org-markers-to-move nil))
7897 (defun org-narrow-to-subtree ()
7898 "Narrow buffer to the current subtree."
7899 (interactive)
7900 (save-excursion
7901 (save-match-data
7902 (org-with-limited-levels
7903 (narrow-to-region
7904 (progn (org-back-to-heading t) (point))
7905 (progn (org-end-of-subtree t t)
7906 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7907 (point)))))))
7909 (defun org-narrow-to-block ()
7910 "Narrow buffer to the current block."
7911 (interactive)
7912 (let* ((case-fold-search t)
7913 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7914 "^[ \t]*#\\+end_.*")))
7915 (if blockp
7916 (narrow-to-region (car blockp) (cdr blockp))
7917 (error "Not in a block"))))
7919 (eval-when-compile
7920 (defvar org-property-drawer-re))
7922 (defvar org-property-start-re) ;; defined below
7923 (defun org-clone-subtree-with-time-shift (n &optional shift)
7924 "Clone the task (subtree) at point N times.
7925 The clones will be inserted as siblings.
7927 In interactive use, the user will be prompted for the number of
7928 clones to be produced, and for a time SHIFT, which may be a
7929 repeater as used in time stamps, for example `+3d'.
7931 When a valid repeater is given and the entry contains any time
7932 stamps, the clones will become a sequence in time, with time
7933 stamps in the subtree shifted for each clone produced. If SHIFT
7934 is nil or the empty string, time stamps will be left alone. The
7935 ID property of the original subtree is removed.
7937 If the original subtree did contain time stamps with a repeater,
7938 the following will happen:
7939 - the repeater will be removed in each clone
7940 - an additional clone will be produced, with the current, unshifted
7941 date(s) in the entry.
7942 - the original entry will be placed *after* all the clones, with
7943 repeater intact.
7944 - the start days in the repeater in the original entry will be shifted
7945 to past the last clone.
7946 In this way you can spell out a number of instances of a repeating task,
7947 and still retain the repeater to cover future instances of the task."
7948 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7949 (let (beg end template task idprop
7950 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7951 (drawer-re org-drawer-regexp))
7952 (if (not (and (integerp n) (> n 0)))
7953 (error "Invalid number of replications %s" n))
7954 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7955 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7956 shift)))
7957 (error "Invalid shift specification %s" shift))
7958 (when doshift
7959 (setq shift-n (string-to-number (match-string 1 shift))
7960 shift-what (cdr (assoc (match-string 2 shift)
7961 '(("d" . day) ("w" . week)
7962 ("m" . month) ("y" . year))))))
7963 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7964 (setq nmin 1 nmax n)
7965 (org-back-to-heading t)
7966 (setq beg (point))
7967 (setq idprop (org-entry-get nil "ID"))
7968 (org-end-of-subtree t t)
7969 (or (bolp) (insert "\n"))
7970 (setq end (point))
7971 (setq template (buffer-substring beg end))
7972 (when (and doshift
7973 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7974 (delete-region beg end)
7975 (setq end beg)
7976 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7977 (goto-char end)
7978 (loop for n from nmin to nmax do
7979 ;; prepare clone
7980 (with-temp-buffer
7981 (insert template)
7982 (org-mode)
7983 (goto-char (point-min))
7984 (org-show-subtree)
7985 (and idprop (if org-clone-delete-id
7986 (org-entry-delete nil "ID")
7987 (org-id-get-create t)))
7988 (unless (= n 0)
7989 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7990 (kill-whole-line))
7991 (goto-char (point-min))
7992 (while (re-search-forward drawer-re nil t)
7993 (mapc (lambda (d)
7994 (org-remove-empty-drawer-at d (point))) org-drawers)))
7995 (goto-char (point-min))
7996 (when doshift
7997 (while (re-search-forward org-ts-regexp-both nil t)
7998 (org-timestamp-change (* n shift-n) shift-what))
7999 (unless (= n n-no-remove)
8000 (goto-char (point-min))
8001 (while (re-search-forward org-ts-regexp nil t)
8002 (save-excursion
8003 (goto-char (match-beginning 0))
8004 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8005 (delete-region (match-beginning 1) (match-end 1)))))))
8006 (setq task (buffer-string)))
8007 (insert task))
8008 (goto-char beg)))
8010 ;;; Outline Sorting
8012 (defun org-sort (with-case)
8013 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8014 Optional argument WITH-CASE means sort case-sensitively."
8015 (interactive "P")
8016 (cond
8017 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8018 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8020 (org-call-with-arg 'org-sort-entries with-case))))
8022 (defun org-sort-remove-invisible (s)
8023 (remove-text-properties 0 (length s) org-rm-props s)
8024 (while (string-match org-bracket-link-regexp s)
8025 (setq s (replace-match (if (match-end 2)
8026 (match-string 3 s)
8027 (match-string 1 s)) t t s)))
8030 (defvar org-priority-regexp) ; defined later in the file
8032 (defvar org-after-sorting-entries-or-items-hook nil
8033 "Hook that is run after a bunch of entries or items have been sorted.
8034 When children are sorted, the cursor is in the parent line when this
8035 hook gets called. When a region or a plain list is sorted, the cursor
8036 will be in the first entry of the sorted region/list.")
8038 (defun org-sort-entries
8039 (&optional with-case sorting-type getkey-func compare-func property)
8040 "Sort entries on a certain level of an outline tree.
8041 If there is an active region, the entries in the region are sorted.
8042 Else, if the cursor is before the first entry, sort the top-level items.
8043 Else, the children of the entry at point are sorted.
8045 Sorting can be alphabetically, numerically, by date/time as given by
8046 a time stamp, by a property or by priority.
8048 The command prompts for the sorting type unless it has been given to the
8049 function through the SORTING-TYPE argument, which needs to be a character,
8050 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8051 precise meaning of each character:
8053 n Numerically, by converting the beginning of the entry/item to a number.
8054 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8055 t By date/time, either the first active time stamp in the entry, or, if
8056 none exist, by the first inactive one.
8057 s By the scheduled date/time.
8058 d By deadline date/time.
8059 c By creation time, which is assumed to be the first inactive time stamp
8060 at the beginning of a line.
8061 p By priority according to the cookie.
8062 r By the value of a property.
8064 Capital letters will reverse the sort order.
8066 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8067 called with point at the beginning of the record. It must return either
8068 a string or a number that should serve as the sorting key for that record.
8070 Comparing entries ignores case by default. However, with an optional argument
8071 WITH-CASE, the sorting considers case as well."
8072 (interactive "P")
8073 (let ((case-func (if with-case 'identity 'downcase))
8074 start beg end stars re re2
8075 txt what tmp)
8076 ;; Find beginning and end of region to sort
8077 (cond
8078 ((org-region-active-p)
8079 ;; we will sort the region
8080 (setq end (region-end)
8081 what "region")
8082 (goto-char (region-beginning))
8083 (if (not (org-at-heading-p)) (outline-next-heading))
8084 (setq start (point)))
8085 ((or (org-at-heading-p)
8086 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8087 ;; we will sort the children of the current headline
8088 (org-back-to-heading)
8089 (setq start (point)
8090 end (progn (org-end-of-subtree t t)
8091 (or (bolp) (insert "\n"))
8092 (org-back-over-empty-lines)
8093 (point))
8094 what "children")
8095 (goto-char start)
8096 (show-subtree)
8097 (outline-next-heading))
8099 ;; we will sort the top-level entries in this file
8100 (goto-char (point-min))
8101 (or (org-at-heading-p) (outline-next-heading))
8102 (setq start (point))
8103 (goto-char (point-max))
8104 (beginning-of-line 1)
8105 (when (looking-at ".*?\\S-")
8106 ;; File ends in a non-white line
8107 (end-of-line 1)
8108 (insert "\n"))
8109 (setq end (point-max))
8110 (setq what "top-level")
8111 (goto-char start)
8112 (show-all)))
8114 (setq beg (point))
8115 (if (>= beg end) (error "Nothing to sort"))
8117 (looking-at "\\(\\*+\\)")
8118 (setq stars (match-string 1)
8119 re (concat "^" (regexp-quote stars) " +")
8120 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8121 txt (buffer-substring beg end))
8122 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8123 (if (and (not (equal stars "*")) (string-match re2 txt))
8124 (error "Region to sort contains a level above the first entry"))
8126 (unless sorting-type
8127 (message
8128 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8129 [t]ime [s]cheduled [d]eadline [c]reated
8130 A/N/T/S/D/C/P/O/F means reversed:"
8131 what)
8132 (setq sorting-type (read-char-exclusive))
8134 (and (= (downcase sorting-type) ?f)
8135 (setq getkey-func
8136 (org-icompleting-read "Sort using function: "
8137 obarray 'fboundp t nil nil))
8138 (setq getkey-func (intern getkey-func)))
8140 (and (= (downcase sorting-type) ?r)
8141 (setq property
8142 (org-icompleting-read "Property: "
8143 (mapcar 'list (org-buffer-property-keys t))
8144 nil t))))
8146 (message "Sorting entries...")
8148 (save-restriction
8149 (narrow-to-region start end)
8150 (let ((dcst (downcase sorting-type))
8151 (case-fold-search nil)
8152 (now (current-time)))
8153 (sort-subr
8154 (/= dcst sorting-type)
8155 ;; This function moves to the beginning character of the "record" to
8156 ;; be sorted.
8157 (lambda nil
8158 (if (re-search-forward re nil t)
8159 (goto-char (match-beginning 0))
8160 (goto-char (point-max))))
8161 ;; This function moves to the last character of the "record" being
8162 ;; sorted.
8163 (lambda nil
8164 (save-match-data
8165 (condition-case nil
8166 (outline-forward-same-level 1)
8167 (error
8168 (goto-char (point-max))))))
8169 ;; This function returns the value that gets sorted against.
8170 (lambda nil
8171 (cond
8172 ((= dcst ?n)
8173 (if (looking-at org-complex-heading-regexp)
8174 (string-to-number (match-string 4))
8175 nil))
8176 ((= dcst ?a)
8177 (if (looking-at org-complex-heading-regexp)
8178 (funcall case-func (match-string 4))
8179 nil))
8180 ((= dcst ?t)
8181 (let ((end (save-excursion (outline-next-heading) (point))))
8182 (if (or (re-search-forward org-ts-regexp end t)
8183 (re-search-forward org-ts-regexp-both end t))
8184 (org-time-string-to-seconds (match-string 0))
8185 (org-float-time now))))
8186 ((= dcst ?c)
8187 (let ((end (save-excursion (outline-next-heading) (point))))
8188 (if (re-search-forward
8189 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8190 end t)
8191 (org-time-string-to-seconds (match-string 0))
8192 (org-float-time now))))
8193 ((= dcst ?s)
8194 (let ((end (save-excursion (outline-next-heading) (point))))
8195 (if (re-search-forward org-scheduled-time-regexp end t)
8196 (org-time-string-to-seconds (match-string 1))
8197 (org-float-time now))))
8198 ((= dcst ?d)
8199 (let ((end (save-excursion (outline-next-heading) (point))))
8200 (if (re-search-forward org-deadline-time-regexp end t)
8201 (org-time-string-to-seconds (match-string 1))
8202 (org-float-time now))))
8203 ((= dcst ?p)
8204 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8205 (string-to-char (match-string 2))
8206 org-default-priority))
8207 ((= dcst ?r)
8208 (or (org-entry-get nil property) ""))
8209 ((= dcst ?o)
8210 (if (looking-at org-complex-heading-regexp)
8211 (- 9999 (length (member (match-string 2)
8212 org-todo-keywords-1)))))
8213 ((= dcst ?f)
8214 (if getkey-func
8215 (progn
8216 (setq tmp (funcall getkey-func))
8217 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8218 tmp)
8219 (error "Invalid key function `%s'" getkey-func)))
8220 (t (error "Invalid sorting type `%c'" sorting-type))))
8222 (cond
8223 ((= dcst ?a) 'string<)
8224 ((= dcst ?f) compare-func)
8225 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8226 (t nil)))))
8227 (run-hooks 'org-after-sorting-entries-or-items-hook)
8228 (message "Sorting entries...done")))
8230 (defun org-do-sort (table what &optional with-case sorting-type)
8231 "Sort TABLE of WHAT according to SORTING-TYPE.
8232 The user will be prompted for the SORTING-TYPE if the call to this
8233 function does not specify it. WHAT is only for the prompt, to indicate
8234 what is being sorted. The sorting key will be extracted from
8235 the car of the elements of the table.
8236 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8237 (unless sorting-type
8238 (message
8239 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8240 what)
8241 (setq sorting-type (read-char-exclusive)))
8242 (let ((dcst (downcase sorting-type))
8243 extractfun comparefun)
8244 ;; Define the appropriate functions
8245 (cond
8246 ((= dcst ?n)
8247 (setq extractfun 'string-to-number
8248 comparefun (if (= dcst sorting-type) '< '>)))
8249 ((= dcst ?a)
8250 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8251 (lambda(x) (downcase (org-sort-remove-invisible x))))
8252 comparefun (if (= dcst sorting-type)
8253 'string<
8254 (lambda (a b) (and (not (string< a b))
8255 (not (string= a b)))))))
8256 ((= dcst ?t)
8257 (setq extractfun
8258 (lambda (x)
8259 (if (or (string-match org-ts-regexp x)
8260 (string-match org-ts-regexp-both x))
8261 (org-float-time
8262 (org-time-string-to-time (match-string 0 x)))
8264 comparefun (if (= dcst sorting-type) '< '>)))
8265 (t (error "Invalid sorting type `%c'" sorting-type)))
8267 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8268 table)
8269 (lambda (a b) (funcall comparefun (car a) (car b))))))
8272 ;;; The orgstruct minor mode
8274 ;; Define a minor mode which can be used in other modes in order to
8275 ;; integrate the org-mode structure editing commands.
8277 ;; This is really a hack, because the org-mode structure commands use
8278 ;; keys which normally belong to the major mode. Here is how it
8279 ;; works: The minor mode defines all the keys necessary to operate the
8280 ;; structure commands, but wraps the commands into a function which
8281 ;; tests if the cursor is currently at a headline or a plain list
8282 ;; item. If that is the case, the structure command is used,
8283 ;; temporarily setting many Org-mode variables like regular
8284 ;; expressions for filling etc. However, when any of those keys is
8285 ;; used at a different location, function uses `key-binding' to look
8286 ;; up if the key has an associated command in another currently active
8287 ;; keymap (minor modes, major mode, global), and executes that
8288 ;; command. There might be problems if any of the keys is otherwise
8289 ;; used as a prefix key.
8291 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8292 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8293 ;; addresses this by checking explicitly for both bindings.
8295 (defvar orgstruct-mode-map (make-sparse-keymap)
8296 "Keymap for the minor `orgstruct-mode'.")
8298 (defvar org-local-vars nil
8299 "List of local variables, for use by `orgstruct-mode'.")
8301 ;;;###autoload
8302 (define-minor-mode orgstruct-mode
8303 "Toggle the minor mode `orgstruct-mode'.
8304 This mode is for using Org-mode structure commands in other
8305 modes. The following keys behave as if Org-mode were active, if
8306 the cursor is on a headline, or on a plain list item (both as
8307 defined by Org-mode).
8309 M-up Move entry/item up
8310 M-down Move entry/item down
8311 M-left Promote
8312 M-right Demote
8313 M-S-up Move entry/item up
8314 M-S-down Move entry/item down
8315 M-S-left Promote subtree
8316 M-S-right Demote subtree
8317 M-q Fill paragraph and items like in Org-mode
8318 C-c ^ Sort entries
8319 C-c - Cycle list bullet
8320 TAB Cycle item visibility
8321 M-RET Insert new heading/item
8322 S-M-RET Insert new TODO heading / Checkbox item
8323 C-c C-c Set tags / toggle checkbox"
8324 nil " OrgStruct" nil
8325 (org-load-modules-maybe)
8326 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8328 ;;;###autoload
8329 (defun turn-on-orgstruct ()
8330 "Unconditionally turn on `orgstruct-mode'."
8331 (orgstruct-mode 1))
8333 (defun orgstruct++-mode (&optional arg)
8334 "Toggle `orgstruct-mode', the enhanced version of it.
8335 In addition to setting orgstruct-mode, this also exports all indentation
8336 and autofilling variables from org-mode into the buffer. It will also
8337 recognize item context in multiline items.
8338 Note that turning off orgstruct-mode will *not* remove the
8339 indentation/paragraph settings. This can only be done by refreshing the
8340 major mode, for example with \\[normal-mode]."
8341 (interactive "P")
8342 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8343 (if (< arg 1)
8344 (orgstruct-mode -1)
8345 (orgstruct-mode 1)
8346 (let (var val)
8347 (mapc
8348 (lambda (x)
8349 (when (string-match
8350 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8351 (symbol-name (car x)))
8352 (setq var (car x) val (nth 1 x))
8353 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8354 org-local-vars)
8355 (org-set-local 'orgstruct-is-++ t))))
8357 (defvar orgstruct-is-++ nil
8358 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8359 (make-variable-buffer-local 'orgstruct-is-++)
8361 ;;;###autoload
8362 (defun turn-on-orgstruct++ ()
8363 "Unconditionally turn on `orgstruct++-mode'."
8364 (orgstruct++-mode 1))
8366 (defun orgstruct-error ()
8367 "Error when there is no default binding for a structure key."
8368 (interactive)
8369 (error "This key has no function outside structure elements"))
8371 (defun orgstruct-setup ()
8372 "Setup orgstruct keymaps."
8373 (let ((nfunc 0)
8374 (bindings
8375 (list
8376 '([(meta up)] org-metaup)
8377 '([(meta down)] org-metadown)
8378 '([(meta left)] org-metaleft)
8379 '([(meta right)] org-metaright)
8380 '([(meta shift up)] org-shiftmetaup)
8381 '([(meta shift down)] org-shiftmetadown)
8382 '([(meta shift left)] org-shiftmetaleft)
8383 '([(meta shift right)] org-shiftmetaright)
8384 '([?\e (up)] org-metaup)
8385 '([?\e (down)] org-metadown)
8386 '([?\e (left)] org-metaleft)
8387 '([?\e (right)] org-metaright)
8388 '([?\e (shift up)] org-shiftmetaup)
8389 '([?\e (shift down)] org-shiftmetadown)
8390 '([?\e (shift left)] org-shiftmetaleft)
8391 '([?\e (shift right)] org-shiftmetaright)
8392 '([(shift up)] org-shiftup)
8393 '([(shift down)] org-shiftdown)
8394 '([(shift left)] org-shiftleft)
8395 '([(shift right)] org-shiftright)
8396 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8397 '("\M-q" fill-paragraph)
8398 '("\C-c^" org-sort)
8399 '("\C-c-" org-cycle-list-bullet)))
8400 elt key fun cmd)
8401 (while (setq elt (pop bindings))
8402 (setq nfunc (1+ nfunc))
8403 (setq key (org-key (car elt))
8404 fun (nth 1 elt)
8405 cmd (orgstruct-make-binding fun nfunc key))
8406 (org-defkey orgstruct-mode-map key cmd))
8408 ;; Special treatment needed for TAB and RET
8409 (org-defkey orgstruct-mode-map [(tab)]
8410 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8411 (org-defkey orgstruct-mode-map "\C-i"
8412 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8414 (org-defkey orgstruct-mode-map "\M-\C-m"
8415 (orgstruct-make-binding 'org-insert-heading 105
8416 "\M-\C-m" [(meta return)]))
8417 (org-defkey orgstruct-mode-map [(meta return)]
8418 (orgstruct-make-binding 'org-insert-heading 106
8419 [(meta return)] "\M-\C-m"))
8421 (org-defkey orgstruct-mode-map [(shift meta return)]
8422 (orgstruct-make-binding 'org-insert-todo-heading 107
8423 [(meta return)] "\M-\C-m"))
8425 (org-defkey orgstruct-mode-map "\e\C-m"
8426 (orgstruct-make-binding 'org-insert-heading 108
8427 "\e\C-m" [?\e (return)]))
8428 (org-defkey orgstruct-mode-map [?\e (return)]
8429 (orgstruct-make-binding 'org-insert-heading 109
8430 [?\e (return)] "\e\C-m"))
8431 (org-defkey orgstruct-mode-map [?\e (shift return)]
8432 (orgstruct-make-binding 'org-insert-todo-heading 110
8433 [?\e (return)] "\e\C-m"))
8435 (unless org-local-vars
8436 (setq org-local-vars (org-get-local-variables)))
8440 (defun orgstruct-make-binding (fun n &rest keys)
8441 "Create a function for binding in the structure minor mode.
8442 FUN is the command to call inside a table. N is used to create a unique
8443 command name. KEYS are keys that should be checked in for a command
8444 to execute outside of tables."
8445 (eval
8446 (list 'defun
8447 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8448 '(arg)
8449 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8450 "Outside of structure, run the binding of `"
8451 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8452 "'.")
8453 '(interactive "p")
8454 (list 'if
8455 `(org-context-p 'headline 'item
8456 (and orgstruct-is-++
8457 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8458 'item-body))
8459 (list 'org-run-like-in-org-mode (list 'quote fun))
8460 (list 'let '(orgstruct-mode)
8461 (list 'call-interactively
8462 (append '(or)
8463 (mapcar (lambda (k)
8464 (list 'key-binding k))
8465 keys)
8466 '('orgstruct-error))))))))
8468 (defun org-context-p (&rest contexts)
8469 "Check if local context is any of CONTEXTS.
8470 Possible values in the list of contexts are `table', `headline', and `item'."
8471 (let ((pos (point)))
8472 (goto-char (point-at-bol))
8473 (prog1 (or (and (memq 'table contexts)
8474 (looking-at "[ \t]*|"))
8475 (and (memq 'headline contexts)
8476 (looking-at org-outline-regexp))
8477 (and (memq 'item contexts)
8478 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8479 (and (memq 'item-body contexts)
8480 (org-in-item-p)))
8481 (goto-char pos))))
8483 (defun org-get-local-variables ()
8484 "Return a list of all local variables in an org-mode buffer."
8485 (let (varlist)
8486 (with-current-buffer (get-buffer-create "*Org tmp*")
8487 (erase-buffer)
8488 (org-mode)
8489 (setq varlist (buffer-local-variables)))
8490 (kill-buffer "*Org tmp*")
8491 (delq nil
8492 (mapcar
8493 (lambda (x)
8494 (setq x
8495 (if (symbolp x)
8496 (list x)
8497 (list (car x) (list 'quote (cdr x)))))
8498 (if (string-match
8499 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8500 (symbol-name (car x)))
8501 x nil))
8502 varlist))))
8504 (defun org-clone-local-variables (from-buffer &optional regexp)
8505 "Clone local variables from FROM-BUFFER.
8506 Optional argument REGEXP selects variables to clone."
8507 (mapc
8508 (lambda (pair)
8509 (and (symbolp (car pair))
8510 (or (null regexp)
8511 (string-match regexp (symbol-name (car pair))))
8512 (set (make-local-variable (car pair))
8513 (cdr pair))))
8514 (buffer-local-variables from-buffer)))
8516 ;;;###autoload
8517 (defun org-run-like-in-org-mode (cmd)
8518 "Run a command, pretending that the current buffer is in Org-mode.
8519 This will temporarily bind local variables that are typically bound in
8520 Org-mode to the values they have in Org-mode, and then interactively
8521 call CMD."
8522 (org-load-modules-maybe)
8523 (unless org-local-vars
8524 (setq org-local-vars (org-get-local-variables)))
8525 (eval (list 'let org-local-vars
8526 (list 'call-interactively (list 'quote cmd)))))
8528 ;;;; Archiving
8530 (defun org-get-category (&optional pos force-refresh)
8531 "Get the category applying to position POS."
8532 (save-match-data
8533 (if force-refresh (org-refresh-category-properties))
8534 (let ((pos (or pos (point))))
8535 (or (get-text-property pos 'org-category)
8536 (progn (org-refresh-category-properties)
8537 (get-text-property pos 'org-category))))))
8539 (defun org-refresh-category-properties ()
8540 "Refresh category text properties in the buffer."
8541 (let ((def-cat (cond
8542 ((null org-category)
8543 (if buffer-file-name
8544 (file-name-sans-extension
8545 (file-name-nondirectory buffer-file-name))
8546 "???"))
8547 ((symbolp org-category) (symbol-name org-category))
8548 (t org-category)))
8549 beg end cat pos optionp)
8550 (org-unmodified
8551 (save-excursion
8552 (save-restriction
8553 (widen)
8554 (goto-char (point-min))
8555 (put-text-property (point) (point-max) 'org-category def-cat)
8556 (while (re-search-forward
8557 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8558 (setq pos (match-end 0)
8559 optionp (equal (char-after (match-beginning 0)) ?#)
8560 cat (org-trim (match-string 2)))
8561 (if optionp
8562 (setq beg (point-at-bol) end (point-max))
8563 (org-back-to-heading t)
8564 (setq beg (point) end (org-end-of-subtree t t)))
8565 (put-text-property beg end 'org-category cat)
8566 (put-text-property beg end 'org-category-position beg)
8567 (goto-char pos)))))))
8570 ;;;; Link Stuff
8572 ;;; Link abbreviations
8574 (defun org-link-expand-abbrev (link)
8575 "Apply replacements as defined in `org-link-abbrev-alist."
8576 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8577 (let* ((key (match-string 1 link))
8578 (as (or (assoc key org-link-abbrev-alist-local)
8579 (assoc key org-link-abbrev-alist)))
8580 (tag (and (match-end 2) (match-string 3 link)))
8581 rpl)
8582 (if (not as)
8583 link
8584 (setq rpl (cdr as))
8585 (cond
8586 ((symbolp rpl) (funcall rpl tag))
8587 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8588 ((string-match "%h" rpl)
8589 (replace-match (url-hexify-string (or tag "")) t t rpl))
8590 (t (concat rpl tag)))))
8591 link))
8593 ;;; Storing and inserting links
8595 (defvar org-insert-link-history nil
8596 "Minibuffer history for links inserted with `org-insert-link'.")
8598 (defvar org-stored-links nil
8599 "Contains the links stored with `org-store-link'.")
8601 (defvar org-store-link-plist nil
8602 "Plist with info about the most recently link created with `org-store-link'.")
8604 (defvar org-link-protocols nil
8605 "Link protocols added to Org-mode using `org-add-link-type'.")
8607 (defvar org-store-link-functions nil
8608 "List of functions that are called to create and store a link.
8609 Each function will be called in turn until one returns a non-nil
8610 value. Each function should check if it is responsible for creating
8611 this link (for example by looking at the major mode).
8612 If not, it must exit and return nil.
8613 If yes, it should return a non-nil value after a calling
8614 `org-store-link-props' with a list of properties and values.
8615 Special properties are:
8617 :type The link prefix, like \"http\". This must be given.
8618 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8619 This is obligatory as well.
8620 :description Optional default description for the second pair
8621 of brackets in an Org-mode link. The user can still change
8622 this when inserting this link into an Org-mode buffer.
8624 In addition to these, any additional properties can be specified
8625 and then used in remember templates.")
8627 (defun org-add-link-type (type &optional follow export)
8628 "Add TYPE to the list of `org-link-types'.
8629 Re-compute all regular expressions depending on `org-link-types'
8631 FOLLOW and EXPORT are two functions.
8633 FOLLOW should take the link path as the single argument and do whatever
8634 is necessary to follow the link, for example find a file or display
8635 a mail message.
8637 EXPORT should format the link path for export to one of the export formats.
8638 It should be a function accepting three arguments:
8640 path the path of the link, the text after the prefix (like \"http:\")
8641 desc the description of the link, if any, or a description added by
8642 org-export-normalize-links if there is none
8643 format the export format, a symbol like `html' or `latex' or `ascii'..
8645 The function may use the FORMAT information to return different values
8646 depending on the format. The return value will be put literally into
8647 the exported file. If the return value is nil, this means Org should
8648 do what it normally does with links which do not have EXPORT defined.
8650 Org-mode has a built-in default for exporting links. If you are happy with
8651 this default, there is no need to define an export function for the link
8652 type. For a simple example of an export function, see `org-bbdb.el'."
8653 (add-to-list 'org-link-types type t)
8654 (org-make-link-regexps)
8655 (if (assoc type org-link-protocols)
8656 (setcdr (assoc type org-link-protocols) (list follow export))
8657 (push (list type follow export) org-link-protocols)))
8659 (defvar org-agenda-buffer-name)
8661 ;;;###autoload
8662 (defun org-store-link (arg)
8663 "\\<org-mode-map>Store an org-link to the current location.
8664 This link is added to `org-stored-links' and can later be inserted
8665 into an org-buffer with \\[org-insert-link].
8667 For some link types, a prefix arg is interpreted:
8668 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8669 For file links, arg negates `org-context-in-file-links'."
8670 (interactive "P")
8671 (org-load-modules-maybe)
8672 (setq org-store-link-plist nil) ; reset
8673 (org-with-limited-levels
8674 (let (link cpltxt desc description search txt custom-id agenda-link)
8675 (cond
8677 ((run-hook-with-args-until-success 'org-store-link-functions)
8678 (setq link (plist-get org-store-link-plist :link)
8679 desc (or (plist-get org-store-link-plist :description) link)))
8681 ((org-src-edit-buffer-p)
8682 (let (label gc)
8683 (while (or (not label)
8684 (save-excursion
8685 (save-restriction
8686 (widen)
8687 (goto-char (point-min))
8688 (re-search-forward
8689 (regexp-quote (format org-coderef-label-format label))
8690 nil t))))
8691 (when label (message "Label exists already") (sit-for 2))
8692 (setq label (read-string "Code line label: " label)))
8693 (end-of-line 1)
8694 (setq link (format org-coderef-label-format label))
8695 (setq gc (- 79 (length link)))
8696 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8697 (insert link)
8698 (setq link (concat "(" label ")") desc nil)))
8700 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8701 ;; We are in the agenda, link to referenced location
8702 (let ((m (or (get-text-property (point) 'org-hd-marker)
8703 (get-text-property (point) 'org-marker))))
8704 (when m
8705 (org-with-point-at m
8706 (setq agenda-link
8707 (if (org-called-interactively-p 'any)
8708 (call-interactively 'org-store-link)
8709 (org-store-link nil)))))))
8711 ((eq major-mode 'calendar-mode)
8712 (let ((cd (calendar-cursor-to-date)))
8713 (setq link
8714 (format-time-string
8715 (car org-time-stamp-formats)
8716 (apply 'encode-time
8717 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8718 nil nil nil))))
8719 (org-store-link-props :type "calendar" :date cd)))
8721 ((eq major-mode 'w3-mode)
8722 (setq cpltxt (if (and (buffer-name)
8723 (not (string-match "Untitled" (buffer-name))))
8724 (buffer-name)
8725 (url-view-url t))
8726 link (org-make-link (url-view-url t)))
8727 (org-store-link-props :type "w3" :url (url-view-url t)))
8729 ((eq major-mode 'w3m-mode)
8730 (setq cpltxt (or w3m-current-title w3m-current-url)
8731 link (org-make-link w3m-current-url))
8732 (org-store-link-props :type "w3m" :url (url-view-url t)))
8734 ((setq search (run-hook-with-args-until-success
8735 'org-create-file-search-functions))
8736 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8737 "::" search))
8738 (setq cpltxt (or description link)))
8740 ((eq major-mode 'image-mode)
8741 (setq cpltxt (concat "file:"
8742 (abbreviate-file-name buffer-file-name))
8743 link (org-make-link cpltxt))
8744 (org-store-link-props :type "image" :file buffer-file-name))
8746 ((eq major-mode 'dired-mode)
8747 ;; link to the file in the current line
8748 (let ((file (dired-get-filename nil t)))
8749 (setq file (if file
8750 (abbreviate-file-name
8751 (expand-file-name (dired-get-filename nil t)))
8752 ;; otherwise, no file so use current directory.
8753 default-directory))
8754 (setq cpltxt (concat "file:" file)
8755 link (org-make-link cpltxt))))
8757 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8758 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8759 (cond
8760 ((org-in-regexp "<<\\(.*?\\)>>")
8761 (setq cpltxt
8762 (concat "file:"
8763 (abbreviate-file-name
8764 (buffer-file-name (buffer-base-buffer)))
8765 "::" (match-string 1))
8766 link (org-make-link cpltxt)))
8767 ((and (featurep 'org-id)
8768 (or (eq org-link-to-org-use-id t)
8769 (and (eq org-link-to-org-use-id 'create-if-interactive)
8770 (org-called-interactively-p 'any))
8771 (and (eq org-link-to-org-use-id
8772 'create-if-interactive-and-no-custom-id)
8773 (org-called-interactively-p 'any)
8774 (not custom-id))
8775 (and org-link-to-org-use-id
8776 (org-entry-get nil "ID"))))
8777 ;; We can make a link using the ID.
8778 (setq link (condition-case nil
8779 (prog1 (org-id-store-link)
8780 (setq desc (plist-get org-store-link-plist
8781 :description)))
8782 (error
8783 ;; probably before first headline, link to file only
8784 (concat "file:"
8785 (abbreviate-file-name
8786 (buffer-file-name (buffer-base-buffer))))))))
8788 ;; Just link to current headline
8789 (setq cpltxt (concat "file:"
8790 (abbreviate-file-name
8791 (buffer-file-name (buffer-base-buffer)))))
8792 ;; Add a context search string
8793 (when (org-xor org-context-in-file-links arg)
8794 (setq txt (cond
8795 ((org-at-heading-p) nil)
8796 ((org-region-active-p)
8797 (buffer-substring (region-beginning) (region-end)))
8798 (t nil)))
8799 (when (or (null txt) (string-match "\\S-" txt))
8800 (setq cpltxt
8801 (concat cpltxt "::"
8802 (condition-case nil
8803 (org-make-org-heading-search-string txt)
8804 (error "")))
8805 desc (or (nth 4 (ignore-errors
8806 (org-heading-components))) "NONE"))))
8807 (if (string-match "::\\'" cpltxt)
8808 (setq cpltxt (substring cpltxt 0 -2)))
8809 (setq link (org-make-link cpltxt)))))
8811 ((buffer-file-name (buffer-base-buffer))
8812 ;; Just link to this file here.
8813 (setq cpltxt (concat "file:"
8814 (abbreviate-file-name
8815 (buffer-file-name (buffer-base-buffer)))))
8816 ;; Add a context string
8817 (when (org-xor org-context-in-file-links arg)
8818 (setq txt (if (org-region-active-p)
8819 (buffer-substring (region-beginning) (region-end))
8820 (buffer-substring (point-at-bol) (point-at-eol))))
8821 ;; Only use search option if there is some text.
8822 (when (string-match "\\S-" txt)
8823 (setq cpltxt
8824 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8825 desc "NONE")))
8826 (setq link (org-make-link cpltxt)))
8828 ((org-called-interactively-p 'interactive)
8829 (error "Cannot link to a buffer which is not visiting a file"))
8831 (t (setq link nil)))
8833 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8834 (setq link (or link cpltxt)
8835 desc (or desc cpltxt))
8836 (if (equal desc "NONE") (setq desc nil))
8838 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8839 (progn
8840 (setq org-stored-links
8841 (cons (list link desc) org-stored-links))
8842 (message "Stored: %s" (or desc link))
8843 (when custom-id
8844 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8845 "::#" custom-id))
8846 (setq org-stored-links
8847 (cons (list link desc) org-stored-links))))
8848 (or agenda-link (and link (org-make-link-string link desc)))))))
8850 (defun org-store-link-props (&rest plist)
8851 "Store link properties, extract names and addresses."
8852 (let (x adr)
8853 (when (setq x (plist-get plist :from))
8854 (setq adr (mail-extract-address-components x))
8855 (setq plist (plist-put plist :fromname (car adr)))
8856 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8857 (when (setq x (plist-get plist :to))
8858 (setq adr (mail-extract-address-components x))
8859 (setq plist (plist-put plist :toname (car adr)))
8860 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8861 (let ((from (plist-get plist :from))
8862 (to (plist-get plist :to)))
8863 (when (and from to org-from-is-user-regexp)
8864 (setq plist
8865 (plist-put plist :fromto
8866 (if (string-match org-from-is-user-regexp from)
8867 (concat "to %t")
8868 (concat "from %f"))))))
8869 (setq org-store-link-plist plist))
8871 (defun org-add-link-props (&rest plist)
8872 "Add these properties to the link property list."
8873 (let (key value)
8874 (while plist
8875 (setq key (pop plist) value (pop plist))
8876 (setq org-store-link-plist
8877 (plist-put org-store-link-plist key value)))))
8879 (defun org-email-link-description (&optional fmt)
8880 "Return the description part of an email link.
8881 This takes information from `org-store-link-plist' and formats it
8882 according to FMT (default from `org-email-link-description-format')."
8883 (setq fmt (or fmt org-email-link-description-format))
8884 (let* ((p org-store-link-plist)
8885 (to (plist-get p :toaddress))
8886 (from (plist-get p :fromaddress))
8887 (table
8888 (list
8889 (cons "%c" (plist-get p :fromto))
8890 (cons "%F" (plist-get p :from))
8891 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8892 (cons "%T" (plist-get p :to))
8893 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8894 (cons "%s" (plist-get p :subject))
8895 (cons "%d" (plist-get p :date))
8896 (cons "%m" (plist-get p :message-id)))))
8897 (when (string-match "%c" fmt)
8898 ;; Check if the user wrote this message
8899 (if (and org-from-is-user-regexp from to
8900 (save-match-data (string-match org-from-is-user-regexp from)))
8901 (setq fmt (replace-match "to %t" t t fmt))
8902 (setq fmt (replace-match "from %f" t t fmt))))
8903 (org-replace-escapes fmt table)))
8905 (defun org-make-org-heading-search-string (&optional string heading)
8906 "Make search string for STRING or current headline."
8907 (interactive)
8908 (let ((s (or string (org-get-heading)))
8909 (lines org-context-in-file-links))
8910 (unless (and string (not heading))
8911 ;; We are using a headline, clean up garbage in there.
8912 (if (string-match org-todo-regexp s)
8913 (setq s (replace-match "" t t s)))
8914 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8915 (setq s (replace-match "" t t s)))
8916 (setq s (org-trim s))
8917 (if (string-match (concat "^\\(" org-quote-string "\\|"
8918 org-comment-string "\\)") s)
8919 (setq s (replace-match "" t t s)))
8920 (while (string-match org-ts-regexp s)
8921 (setq s (replace-match "" t t s))))
8922 (or string (setq s (concat "*" s))) ; Add * for headlines
8923 (when (and string (integerp lines) (> lines 0))
8924 (let ((slines (org-split-string s "\n")))
8925 (when (< lines (length slines))
8926 (setq s (mapconcat
8927 'identity
8928 (reverse (nthcdr (- (length slines) lines)
8929 (reverse slines))) "\n")))))
8930 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8932 (defun org-make-link (&rest strings)
8933 "Concatenate STRINGS."
8934 (apply 'concat strings))
8936 (defun org-make-link-string (link &optional description)
8937 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8938 (unless (string-match "\\S-" link)
8939 (error "Empty link"))
8940 (when (and description
8941 (stringp description)
8942 (not (string-match "\\S-" description)))
8943 (setq description nil))
8944 (when (stringp description)
8945 ;; Remove brackets from the description, they are fatal.
8946 (while (string-match "\\[" description)
8947 (setq description (replace-match "{" t t description)))
8948 (while (string-match "\\]" description)
8949 (setq description (replace-match "}" t t description))))
8950 (when (equal link description)
8951 ;; No description needed, it is identical
8952 (setq description nil))
8953 (when (and (not description)
8954 (not (string-match (org-image-file-name-regexp) link))
8955 (not (equal link (org-link-escape link))))
8956 (setq description (org-extract-attributes link)))
8957 (setq link
8958 (cond ((string-match (org-image-file-name-regexp) link) link)
8959 ((string-match org-link-types-re link)
8960 (concat (match-string 1 link)
8961 (org-link-escape (substring link (match-end 1)))))
8962 (t (org-link-escape link))))
8963 (concat "[[" link "]"
8964 (if description (concat "[" description "]") "")
8965 "]"))
8967 (defconst org-link-escape-chars
8968 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8969 "List of characters that should be escaped in link.
8970 This is the list that is used for internal purposes.")
8972 (defvar org-url-encoding-use-url-hexify nil)
8974 (defconst org-link-escape-chars-browser
8975 '(?\ )
8976 "List of escapes for characters that are problematic in links.
8977 This is the list that is used before handing over to the browser.")
8979 (defun org-link-escape (text &optional table merge)
8980 "Return percent escaped representation of TEXT.
8981 TEXT is a string with the text to escape.
8982 Optional argument TABLE is a list with characters that should be
8983 escaped. When nil, `org-link-escape-chars' is used.
8984 If optional argument MERGE is set, merge TABLE into
8985 `org-link-escape-chars'."
8986 (if (and org-url-encoding-use-url-hexify (not table))
8987 (url-hexify-string text)
8988 (cond
8989 ((and table merge)
8990 (mapc (lambda (defchr)
8991 (unless (member defchr table)
8992 (setq table (cons defchr table)))) org-link-escape-chars))
8993 ((null table)
8994 (setq table org-link-escape-chars)))
8995 (mapconcat
8996 (lambda (char)
8997 (if (or (member char table)
8998 (< char 32) (= char 37) (> char 126))
8999 (mapconcat (lambda (sequence-element)
9000 (format "%%%.2X" sequence-element))
9001 (or (encode-coding-char char 'utf-8)
9002 (error "Unable to percent escape character: %s"
9003 (char-to-string char))) "")
9004 (char-to-string char))) text "")))
9006 (defun org-link-unescape (str)
9007 "Unhex hexified Unicode strings as returned from the JavaScript function
9008 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9009 (unless (and (null str) (string= "" str))
9010 (let ((pos 0) (case-fold-search t) unhexed)
9011 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9012 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9013 (setq str (replace-match unhexed t t str))
9014 (setq pos (+ pos (length unhexed))))))
9015 str)
9017 (defun org-link-unescape-compound (hex)
9018 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9019 Note: this function also decodes single byte encodings like
9020 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9021 (save-match-data
9022 (let* ((bytes (cdr (split-string hex "%")))
9023 (ret "")
9024 (eat 0)
9025 (sum 0))
9026 (while bytes
9027 (let* ((val (string-to-number (pop bytes) 16))
9028 (shift-xor
9029 (if (= 0 eat)
9030 (cond
9031 ((>= val 252) (cons 6 252))
9032 ((>= val 248) (cons 5 248))
9033 ((>= val 240) (cons 4 240))
9034 ((>= val 224) (cons 3 224))
9035 ((>= val 192) (cons 2 192))
9036 (t (cons 0 0)))
9037 (cons 6 128))))
9038 (if (>= val 192) (setq eat (car shift-xor)))
9039 (setq val (logxor val (cdr shift-xor)))
9040 (setq sum (+ (lsh sum (car shift-xor)) val))
9041 (if (> eat 0) (setq eat (- eat 1)))
9042 (cond
9043 ((= 0 eat) ;multi byte
9044 (setq ret (concat ret (org-char-to-string sum)))
9045 (setq sum 0))
9046 ((not bytes) ; single byte(s)
9047 (setq ret (org-link-unescape-single-byte-sequence hex))))
9048 )) ;; end (while bytes
9049 ret )))
9051 (defun org-link-unescape-single-byte-sequence (hex)
9052 "Unhexify hex-encoded single byte character sequences."
9053 (mapconcat (lambda (byte)
9054 (char-to-string (string-to-number byte 16)))
9055 (cdr (split-string hex "%")) ""))
9057 (defun org-xor (a b)
9058 "Exclusive or."
9059 (if a (not b) b))
9061 (defun org-fixup-message-id-for-http (s)
9062 "Replace special characters in a message id, so it can be used in an http query."
9063 (when (string-match "%" s)
9064 (setq s (mapconcat (lambda (c)
9065 (if (eq c ?%)
9066 "%25"
9067 (char-to-string c)))
9068 s "")))
9069 (while (string-match "<" s)
9070 (setq s (replace-match "%3C" t t s)))
9071 (while (string-match ">" s)
9072 (setq s (replace-match "%3E" t t s)))
9073 (while (string-match "@" s)
9074 (setq s (replace-match "%40" t t s)))
9077 ;;;###autoload
9078 (defun org-insert-link-global ()
9079 "Insert a link like Org-mode does.
9080 This command can be called in any mode to insert a link in Org-mode syntax."
9081 (interactive)
9082 (org-load-modules-maybe)
9083 (org-run-like-in-org-mode 'org-insert-link))
9085 (defun org-insert-link (&optional complete-file link-location default-description)
9086 "Insert a link. At the prompt, enter the link.
9088 Completion can be used to insert any of the link protocol prefixes like
9089 http or ftp in use.
9091 The history can be used to select a link previously stored with
9092 `org-store-link'. When the empty string is entered (i.e. if you just
9093 press RET at the prompt), the link defaults to the most recently
9094 stored link. As SPC triggers completion in the minibuffer, you need to
9095 use M-SPC or C-q SPC to force the insertion of a space character.
9097 You will also be prompted for a description, and if one is given, it will
9098 be displayed in the buffer instead of the link.
9100 If there is already a link at point, this command will allow you to edit link
9101 and description parts.
9103 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9104 be selected using completion. The path to the file will be relative to the
9105 current directory if the file is in the current directory or a subdirectory.
9106 Otherwise, the link will be the absolute path as completed in the minibuffer
9107 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9108 option `org-link-file-path-type'.
9110 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9111 the current directory or below.
9113 With three \\[universal-argument] prefixes, negate the meaning of
9114 `org-keep-stored-link-after-insertion'.
9116 If `org-make-link-description-function' is non-nil, this function will be
9117 called with the link target, and the result will be the default
9118 link description.
9120 If the LINK-LOCATION parameter is non-nil, this value will be
9121 used as the link location instead of reading one interactively.
9123 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9124 be used as the default description."
9125 (interactive "P")
9126 (let* ((wcf (current-window-configuration))
9127 (region (if (org-region-active-p)
9128 (buffer-substring (region-beginning) (region-end))))
9129 (remove (and region (list (region-beginning) (region-end))))
9130 (desc region)
9131 tmphist ; byte-compile incorrectly complains about this
9132 (link link-location)
9133 entry file all-prefixes)
9134 (cond
9135 (link-location) ; specified by arg, just use it.
9136 ((org-in-regexp org-bracket-link-regexp 1)
9137 ;; We do have a link at point, and we are going to edit it.
9138 (setq remove (list (match-beginning 0) (match-end 0)))
9139 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9140 (setq link (read-string "Link: "
9141 (org-link-unescape
9142 (org-match-string-no-properties 1)))))
9143 ((or (org-in-regexp org-angle-link-re)
9144 (org-in-regexp org-plain-link-re))
9145 ;; Convert to bracket link
9146 (setq remove (list (match-beginning 0) (match-end 0))
9147 link (read-string "Link: "
9148 (org-remove-angle-brackets (match-string 0)))))
9149 ((member complete-file '((4) (16)))
9150 ;; Completing read for file names.
9151 (setq link (org-file-complete-link complete-file)))
9153 ;; Read link, with completion for stored links.
9154 (with-output-to-temp-buffer "*Org Links*"
9155 (princ "Insert a link.
9156 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9157 (when org-stored-links
9158 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9159 (princ (mapconcat
9160 (lambda (x)
9161 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9162 (reverse org-stored-links) "\n"))))
9163 (let ((cw (selected-window)))
9164 (select-window (get-buffer-window "*Org Links*" 'visible))
9165 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9166 (unless (pos-visible-in-window-p (point-max))
9167 (org-fit-window-to-buffer))
9168 (and (window-live-p cw) (select-window cw)))
9169 ;; Fake a link history, containing the stored links.
9170 (setq tmphist (append (mapcar 'car org-stored-links)
9171 org-insert-link-history))
9172 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9173 (mapcar 'car org-link-abbrev-alist)
9174 org-link-types))
9175 (unwind-protect
9176 (progn
9177 (setq link
9178 (let ((org-completion-use-ido nil)
9179 (org-completion-use-iswitchb nil))
9180 (org-completing-read
9181 "Link: "
9182 (append
9183 (mapcar (lambda (x) (list (concat x ":")))
9184 all-prefixes)
9185 (mapcar 'car org-stored-links))
9186 nil nil nil
9187 'tmphist
9188 (car (car org-stored-links)))))
9189 (if (not (string-match "\\S-" link))
9190 (error "No link selected"))
9191 (if (or (member link all-prefixes)
9192 (and (equal ":" (substring link -1))
9193 (member (substring link 0 -1) all-prefixes)
9194 (setq link (substring link 0 -1))))
9195 (setq link (org-link-try-special-completion link))))
9196 (set-window-configuration wcf)
9197 (kill-buffer "*Org Links*"))
9198 (setq entry (assoc link org-stored-links))
9199 (or entry (push link org-insert-link-history))
9200 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9201 (not org-keep-stored-link-after-insertion))
9202 (setq org-stored-links (delq (assoc link org-stored-links)
9203 org-stored-links)))
9204 (setq desc (or desc (nth 1 entry)))))
9206 (if (string-match org-plain-link-re link)
9207 ;; URL-like link, normalize the use of angular brackets.
9208 (setq link (org-make-link (org-remove-angle-brackets link))))
9210 ;; Check if we are linking to the current file with a search option
9211 ;; If yes, simplify the link by using only the search option.
9212 (when (and buffer-file-name
9213 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9214 (let* ((path (match-string 1 link))
9215 (case-fold-search nil)
9216 (search (match-string 2 link)))
9217 (save-match-data
9218 (if (equal (file-truename buffer-file-name) (file-truename path))
9219 ;; We are linking to this same file, with a search option
9220 (setq link search)))))
9222 ;; Check if we can/should use a relative path. If yes, simplify the link
9223 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9224 (let* ((type (match-string 1 link))
9225 (path (match-string 2 link))
9226 (origpath path)
9227 (case-fold-search nil))
9228 (cond
9229 ((or (eq org-link-file-path-type 'absolute)
9230 (equal complete-file '(16)))
9231 (setq path (abbreviate-file-name (expand-file-name path))))
9232 ((eq org-link-file-path-type 'noabbrev)
9233 (setq path (expand-file-name path)))
9234 ((eq org-link-file-path-type 'relative)
9235 (setq path (file-relative-name path)))
9237 (save-match-data
9238 (if (string-match (concat "^" (regexp-quote
9239 (expand-file-name
9240 (file-name-as-directory
9241 default-directory))))
9242 (expand-file-name path))
9243 ;; We are linking a file with relative path name.
9244 (setq path (substring (expand-file-name path)
9245 (match-end 0)))
9246 (setq path (abbreviate-file-name (expand-file-name path)))))))
9247 (setq link (concat type path))
9248 (if (equal desc origpath)
9249 (setq desc path))))
9251 (if org-make-link-description-function
9252 (setq desc (funcall org-make-link-description-function link desc))
9253 (if default-description (setq desc default-description)))
9255 (setq desc (read-string "Description: " desc))
9256 (unless (string-match "\\S-" desc) (setq desc nil))
9257 (if remove (apply 'delete-region remove))
9258 (insert (org-make-link-string link desc))))
9260 (defun org-link-try-special-completion (type)
9261 "If there is completion support for link type TYPE, offer it."
9262 (let ((fun (intern (concat "org-" type "-complete-link"))))
9263 (if (functionp fun)
9264 (funcall fun)
9265 (read-string "Link (no completion support): " (concat type ":")))))
9267 (defun org-file-complete-link (&optional arg)
9268 "Create a file link using completion."
9269 (let (file link)
9270 (setq file (read-file-name "File: "))
9271 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9272 (pwd1 (file-name-as-directory (abbreviate-file-name
9273 (expand-file-name ".")))))
9274 (cond
9275 ((equal arg '(16))
9276 (setq link (org-make-link
9277 "file:"
9278 (abbreviate-file-name (expand-file-name file)))))
9279 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9280 (setq link (org-make-link "file:" (match-string 1 file))))
9281 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9282 (expand-file-name file))
9283 (setq link (org-make-link
9284 "file:" (match-string 1 (expand-file-name file)))))
9285 (t (setq link (org-make-link "file:" file)))))
9286 link))
9288 (defun org-completing-read (&rest args)
9289 "Completing-read with SPACE being a normal character."
9290 (let ((enable-recursive-minibuffers t)
9291 (minibuffer-local-completion-map
9292 (copy-keymap minibuffer-local-completion-map)))
9293 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9294 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9295 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9296 (apply 'org-icompleting-read args)))
9298 (defun org-completing-read-no-i (&rest args)
9299 (let (org-completion-use-ido org-completion-use-iswitchb)
9300 (apply 'org-completing-read args)))
9302 (defun org-iswitchb-completing-read (prompt choices &rest args)
9303 "Use iswitch as a completing-read replacement to choose from choices.
9304 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9305 from."
9306 (let* ((iswitchb-use-virtual-buffers nil)
9307 (iswitchb-make-buflist-hook
9308 (lambda ()
9309 (setq iswitchb-temp-buflist choices))))
9310 (iswitchb-read-buffer prompt)))
9312 (defun org-icompleting-read (&rest args)
9313 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9314 (org-without-partial-completion
9315 (if (and org-completion-use-ido
9316 (fboundp 'ido-completing-read)
9317 (boundp 'ido-mode) ido-mode
9318 (listp (second args)))
9319 (let ((ido-enter-matching-directory nil))
9320 (apply 'ido-completing-read (concat (car args))
9321 (if (consp (car (nth 1 args)))
9322 (mapcar 'car (nth 1 args))
9323 (nth 1 args))
9324 (cddr args)))
9325 (if (and org-completion-use-iswitchb
9326 (boundp 'iswitchb-mode) iswitchb-mode
9327 (listp (second args)))
9328 (apply 'org-iswitchb-completing-read (concat (car args))
9329 (if (consp (car (nth 1 args)))
9330 (mapcar 'car (nth 1 args))
9331 (nth 1 args))
9332 (cddr args))
9333 (apply 'completing-read args)))))
9335 (defun org-extract-attributes (s)
9336 "Extract the attributes cookie from a string and set as text property."
9337 (let (a attr (start 0) key value)
9338 (save-match-data
9339 (when (string-match "{{\\([^}]+\\)}}$" s)
9340 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9341 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9342 (setq key (match-string 1 a) value (match-string 2 a)
9343 start (match-end 0)
9344 attr (plist-put attr (intern key) value))))
9345 (org-add-props s nil 'org-attr attr))
9348 (defun org-extract-attributes-from-string (tag)
9349 (let (key value attr)
9350 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9351 (setq key (match-string 1 tag) value (match-string 2 tag)
9352 tag (replace-match "" t t tag)
9353 attr (plist-put attr (intern key) value)))
9354 (cons tag attr)))
9356 (defun org-attributes-to-string (plist)
9357 "Format a property list into an HTML attribute list."
9358 (let ((s "") key value)
9359 (while plist
9360 (setq key (pop plist) value (pop plist))
9361 (and value
9362 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9365 ;;; Opening/following a link
9367 (defvar org-link-search-failed nil)
9369 (defvar org-open-link-functions nil
9370 "Hook for functions finding a plain text link.
9371 These functions must take a single argument, the link content.
9372 They will be called for links that look like [[link text][description]]
9373 when LINK TEXT does not have a protocol like \"http:\" and does not look
9374 like a filename (e.g. \"./blue.png\").
9376 These functions will be called *before* Org attempts to resolve the
9377 link by doing text searches in the current buffer - so if you want a
9378 link \"[[target]]\" to still find \"<<target>>\", your function should
9379 handle this as a special case.
9381 When the function does handle the link, it must return a non-nil value.
9382 If it decides that it is not responsible for this link, it must return
9383 nil to indicate that that Org-mode can continue with other options
9384 like exact and fuzzy text search.")
9386 (defun org-next-link ()
9387 "Move forward to the next link.
9388 If the link is in hidden text, expose it."
9389 (interactive)
9390 (when (and org-link-search-failed (eq this-command last-command))
9391 (goto-char (point-min))
9392 (message "Link search wrapped back to beginning of buffer"))
9393 (setq org-link-search-failed nil)
9394 (let* ((pos (point))
9395 (ct (org-context))
9396 (a (assoc :link ct)))
9397 (if a (goto-char (nth 2 a)))
9398 (if (re-search-forward org-any-link-re nil t)
9399 (progn
9400 (goto-char (match-beginning 0))
9401 (if (outline-invisible-p) (org-show-context)))
9402 (goto-char pos)
9403 (setq org-link-search-failed t)
9404 (error "No further link found"))))
9406 (defun org-previous-link ()
9407 "Move backward to the previous link.
9408 If the link is in hidden text, expose it."
9409 (interactive)
9410 (when (and org-link-search-failed (eq this-command last-command))
9411 (goto-char (point-max))
9412 (message "Link search wrapped back to end of buffer"))
9413 (setq org-link-search-failed nil)
9414 (let* ((pos (point))
9415 (ct (org-context))
9416 (a (assoc :link ct)))
9417 (if a (goto-char (nth 1 a)))
9418 (if (re-search-backward org-any-link-re nil t)
9419 (progn
9420 (goto-char (match-beginning 0))
9421 (if (outline-invisible-p) (org-show-context)))
9422 (goto-char pos)
9423 (setq org-link-search-failed t)
9424 (error "No further link found"))))
9426 (defun org-translate-link (s)
9427 "Translate a link string if a translation function has been defined."
9428 (if (and org-link-translation-function
9429 (fboundp org-link-translation-function)
9430 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9431 (progn
9432 (setq s (funcall org-link-translation-function
9433 (match-string 1) (match-string 2)))
9434 (concat (car s) ":" (cdr s)))
9437 (defun org-translate-link-from-planner (type path)
9438 "Translate a link from Emacs Planner syntax so that Org can follow it.
9439 This is still an experimental function, your mileage may vary."
9440 (cond
9441 ((member type '("http" "https" "news" "ftp"))
9442 ;; standard Internet links are the same.
9443 nil)
9444 ((and (equal type "irc") (string-match "^//" path))
9445 ;; Planner has two / at the beginning of an irc link, we have 1.
9446 ;; We should have zero, actually....
9447 (setq path (substring path 1)))
9448 ((and (equal type "lisp") (string-match "^/" path))
9449 ;; Planner has a slash, we do not.
9450 (setq type "elisp" path (substring path 1)))
9451 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9452 ;; A typical message link. Planner has the id after the final slash,
9453 ;; we separate it with a hash mark
9454 (setq path (concat (match-string 1 path) "#"
9455 (org-remove-angle-brackets (match-string 2 path)))))
9457 (cons type path))
9459 (defun org-find-file-at-mouse (ev)
9460 "Open file link or URL at mouse."
9461 (interactive "e")
9462 (mouse-set-point ev)
9463 (org-open-at-point 'in-emacs))
9465 (defun org-open-at-mouse (ev)
9466 "Open file link or URL at mouse.
9467 See the docstring of `org-open-file' for details."
9468 (interactive "e")
9469 (mouse-set-point ev)
9470 (if (eq major-mode 'org-agenda-mode)
9471 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9472 (org-open-at-point))
9474 (defvar org-window-config-before-follow-link nil
9475 "The window configuration before following a link.
9476 This is saved in case the need arises to restore it.")
9478 (defvar org-open-link-marker (make-marker)
9479 "Marker pointing to the location where `org-open-at-point; was called.")
9481 ;;;###autoload
9482 (defun org-open-at-point-global ()
9483 "Follow a link like Org-mode does.
9484 This command can be called in any mode to follow a link that has
9485 Org-mode syntax."
9486 (interactive)
9487 (org-run-like-in-org-mode 'org-open-at-point))
9489 ;;;###autoload
9490 (defun org-open-link-from-string (s &optional arg reference-buffer)
9491 "Open a link in the string S, as if it was in Org-mode."
9492 (interactive "sLink: \nP")
9493 (let ((reference-buffer (or reference-buffer (current-buffer))))
9494 (with-temp-buffer
9495 (let ((org-inhibit-startup (not reference-buffer)))
9496 (org-mode)
9497 (insert s)
9498 (goto-char (point-min))
9499 (when reference-buffer
9500 (setq org-link-abbrev-alist-local
9501 (with-current-buffer reference-buffer
9502 org-link-abbrev-alist-local)))
9503 (org-open-at-point arg reference-buffer)))))
9505 (defvar org-open-at-point-functions nil
9506 "Hook that is run when following a link at point.
9508 Functions in this hook must return t if they identify and follow
9509 a link at point. If they don't find anything interesting at point,
9510 they must return nil.")
9512 (defun org-open-at-point (&optional arg reference-buffer)
9513 "Open link at or after point.
9514 If there is no link at point, this function will search forward up to
9515 the end of the current line.
9516 Normally, files will be opened by an appropriate application. If the
9517 optional prefix argument ARG is non-nil, Emacs will visit the file.
9518 With a double prefix argument, try to open outside of Emacs, in the
9519 application the system uses for this file type."
9520 (interactive "P")
9521 ;; if in a code block, then open the block's results
9522 (unless (call-interactively #'org-babel-open-src-block-result)
9523 (org-load-modules-maybe)
9524 (move-marker org-open-link-marker (point))
9525 (setq org-window-config-before-follow-link (current-window-configuration))
9526 (org-remove-occur-highlights nil nil t)
9527 (cond
9528 ((and (org-at-heading-p)
9529 (not (org-in-regexp
9530 (concat org-plain-link-re "\\|"
9531 org-bracket-link-regexp "\\|"
9532 org-angle-link-re "\\|"
9533 "[ \t]:[^ \t\n]+:[ \t]*$")))
9534 (not (get-text-property (point) 'org-linked-text)))
9535 (or (org-offer-links-in-entry arg)
9536 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9537 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9538 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9539 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9540 (not (org-in-regexp org-bracket-link-regexp)))
9541 (org-footnote-action))
9543 (let (type path link line search (pos (point)))
9544 (catch 'match
9545 (save-excursion
9546 (skip-chars-forward "^]\n\r")
9547 (when (org-in-regexp org-bracket-link-regexp 1)
9548 (setq link (org-extract-attributes
9549 (org-link-unescape (org-match-string-no-properties 1))))
9550 (while (string-match " *\n *" link)
9551 (setq link (replace-match " " t t link)))
9552 (setq link (org-link-expand-abbrev link))
9553 (cond
9554 ((or (file-name-absolute-p link)
9555 (string-match "^\\.\\.?/" link))
9556 (setq type "file" path link))
9557 ((string-match org-link-re-with-space3 link)
9558 (setq type (match-string 1 link) path (match-string 2 link)))
9559 (t (setq type "thisfile" path link)))
9560 (throw 'match t)))
9562 (when (get-text-property (point) 'org-linked-text)
9563 (setq type "thisfile"
9564 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9565 (1+ (point)) (point))
9566 path (buffer-substring
9567 (or (previous-single-property-change pos 'org-linked-text)
9568 (point-min))
9569 (or (next-single-property-change pos 'org-linked-text)
9570 (point-max))))
9571 (throw 'match t))
9573 (save-excursion
9574 (when (or (org-in-regexp org-angle-link-re)
9575 (org-in-regexp org-plain-link-re))
9576 (setq type (match-string 1)
9577 path (org-link-unescape (match-string 2)))
9578 (throw 'match t)))
9579 (save-excursion
9580 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9581 (setq type "tags"
9582 path (match-string 1))
9583 (while (string-match ":" path)
9584 (setq path (replace-match "+" t t path)))
9585 (throw 'match t)))
9586 (when (org-in-regexp "<\\([^><\n]+\\)>")
9587 (setq type "tree-match"
9588 path (match-string 1))
9589 (throw 'match t)))
9590 (unless path
9591 (error "No link found"))
9593 ;; switch back to reference buffer
9594 ;; needed when if called in a temporary buffer through
9595 ;; org-open-link-from-string
9596 (with-current-buffer (or reference-buffer (current-buffer))
9598 ;; Remove any trailing spaces in path
9599 (if (string-match " +\\'" path)
9600 (setq path (replace-match "" t t path)))
9601 (if (and org-link-translation-function
9602 (fboundp org-link-translation-function))
9603 ;; Check if we need to translate the link
9604 (let ((tmp (funcall org-link-translation-function type path)))
9605 (setq type (car tmp) path (cdr tmp))))
9607 (cond
9609 ((assoc type org-link-protocols)
9610 (funcall (nth 1 (assoc type org-link-protocols)) path))
9612 ((equal type "mailto")
9613 (let ((cmd (car org-link-mailto-program))
9614 (args (cdr org-link-mailto-program)) args1
9615 (address path) (subject "") a)
9616 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9617 (setq address (match-string 1 path)
9618 subject (org-link-escape (match-string 2 path))))
9619 (while args
9620 (cond
9621 ((not (stringp (car args))) (push (pop args) args1))
9622 (t (setq a (pop args))
9623 (if (string-match "%a" a)
9624 (setq a (replace-match address t t a)))
9625 (if (string-match "%s" a)
9626 (setq a (replace-match subject t t a)))
9627 (push a args1))))
9628 (apply cmd (nreverse args1))))
9630 ((member type '("http" "https" "ftp" "news"))
9631 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9632 (org-link-escape
9633 path org-link-escape-chars-browser)
9634 path))))
9636 ((string= type "doi")
9637 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9638 (org-link-escape
9639 path org-link-escape-chars-browser)
9640 path))))
9642 ((member type '("message"))
9643 (browse-url (concat type ":" path)))
9645 ((string= type "tags")
9646 (org-tags-view arg path))
9648 ((string= type "tree-match")
9649 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9651 ((string= type "file")
9652 (if (string-match "::\\([0-9]+\\)\\'" path)
9653 (setq line (string-to-number (match-string 1 path))
9654 path (substring path 0 (match-beginning 0)))
9655 (if (string-match "::\\(.+\\)\\'" path)
9656 (setq search (match-string 1 path)
9657 path (substring path 0 (match-beginning 0)))))
9658 (if (string-match "[*?{]" (file-name-nondirectory path))
9659 (dired path)
9660 (org-open-file path arg line search)))
9662 ((string= type "shell")
9663 (let ((cmd path))
9664 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9665 (string-match org-confirm-shell-link-not-regexp cmd))
9666 (not org-confirm-shell-link-function)
9667 (funcall org-confirm-shell-link-function
9668 (format "Execute \"%s\" in shell? "
9669 (org-add-props cmd nil
9670 'face 'org-warning))))
9671 (progn
9672 (message "Executing %s" cmd)
9673 (shell-command cmd))
9674 (error "Abort"))))
9676 ((string= type "elisp")
9677 (let ((cmd path))
9678 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9679 (string-match org-confirm-elisp-link-not-regexp cmd))
9680 (not org-confirm-elisp-link-function)
9681 (funcall org-confirm-elisp-link-function
9682 (format "Execute \"%s\" as elisp? "
9683 (org-add-props cmd nil
9684 'face 'org-warning))))
9685 (message "%s => %s" cmd
9686 (if (equal (string-to-char cmd) ?\()
9687 (eval (read cmd))
9688 (call-interactively (read cmd))))
9689 (error "Abort"))))
9691 ((and (string= type "thisfile")
9692 (run-hook-with-args-until-success
9693 'org-open-link-functions path)))
9695 ((string= type "thisfile")
9696 (if arg
9697 (switch-to-buffer-other-window
9698 (org-get-buffer-for-internal-link (current-buffer)))
9699 (org-mark-ring-push))
9700 (let ((cmd `(org-link-search
9701 ,path
9702 ,(cond ((equal arg '(4)) ''occur)
9703 ((equal arg '(16)) ''org-occur)
9704 (t nil))
9705 ,pos)))
9706 (condition-case nil (let ((org-link-search-inhibit-query t))
9707 (eval cmd))
9708 (error (progn (widen) (eval cmd))))))
9711 (browse-url-at-point)))))))
9712 (move-marker org-open-link-marker nil)
9713 (run-hook-with-args 'org-follow-link-hook)))
9715 (defun org-offer-links-in-entry (&optional nth zero)
9716 "Offer links in the current entry and follow the selected link.
9717 If there is only one link, follow it immediately as well.
9718 If NTH is an integer, immediately pick the NTH link found.
9719 If ZERO is a string, check also this string for a link, and if
9720 there is one, offer it as link number zero."
9721 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9722 "\\(" org-angle-link-re "\\)\\|"
9723 "\\(" org-plain-link-re "\\)"))
9724 (cnt ?0)
9725 (in-emacs (if (integerp nth) nil nth))
9726 have-zero end links link c)
9727 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9728 (push (match-string 0 zero) links)
9729 (setq cnt (1- cnt) have-zero t))
9730 (save-excursion
9731 (org-back-to-heading t)
9732 (setq end (save-excursion (outline-next-heading) (point)))
9733 (while (re-search-forward re end t)
9734 (push (match-string 0) links))
9735 (setq links (org-uniquify (reverse links))))
9737 (cond
9738 ((null links)
9739 (message "No links"))
9740 ((equal (length links) 1)
9741 (setq link (list (car links))))
9742 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9743 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9744 (t ; we have to select a link
9745 (save-excursion
9746 (save-window-excursion
9747 (delete-other-windows)
9748 (with-output-to-temp-buffer "*Select Link*"
9749 (mapc (lambda (l)
9750 (if (not (string-match org-bracket-link-regexp l))
9751 (princ (format "[%c] %s\n" (incf cnt)
9752 (org-remove-angle-brackets l)))
9753 (if (match-end 3)
9754 (princ (format "[%c] %s (%s)\n" (incf cnt)
9755 (match-string 3 l) (match-string 1 l)))
9756 (princ (format "[%c] %s\n" (incf cnt)
9757 (match-string 1 l))))))
9758 links))
9759 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9760 (message "Select link to open, RET to open all:")
9761 (setq c (read-char-exclusive))
9762 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9763 (when (equal c ?q) (error "Abort"))
9764 (if (equal c ?\C-m)
9765 (setq link links)
9766 (setq nth (- c ?0))
9767 (if have-zero (setq nth (1+ nth)))
9768 (unless (and (integerp nth) (>= (length links) nth))
9769 (error "Invalid link selection"))
9770 (setq link (list (nth (1- nth) links))))))
9771 (if link
9772 (let ((buf (current-buffer)))
9773 (dolist (l link)
9774 (org-open-link-from-string l in-emacs buf))
9776 nil)))
9778 ;; Add special file links that specify the way of opening
9780 (org-add-link-type "file+sys" 'org-open-file-with-system)
9781 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9782 (defun org-open-file-with-system (path)
9783 "Open file at PATH using the system way of opening it."
9784 (org-open-file path 'system))
9785 (defun org-open-file-with-emacs (path)
9786 "Open file at PATH in Emacs."
9787 (org-open-file path 'emacs))
9788 (defun org-remove-file-link-modifiers ()
9789 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9790 (goto-char (point-min))
9791 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9792 (org-if-unprotected
9793 (replace-match "file:" t t))))
9794 (eval-after-load "org-exp"
9795 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9796 'org-remove-file-link-modifiers))
9798 ;;;; Time estimates
9800 (defun org-get-effort (&optional pom)
9801 "Get the effort estimate for the current entry."
9802 (org-entry-get pom org-effort-property))
9804 ;;; File search
9806 (defvar org-create-file-search-functions nil
9807 "List of functions to construct the right search string for a file link.
9808 These functions are called in turn with point at the location to
9809 which the link should point.
9811 A function in the hook should first test if it would like to
9812 handle this file type, for example by checking the `major-mode'
9813 or the file extension. If it decides not to handle this file, it
9814 should just return nil to give other functions a chance. If it
9815 does handle the file, it must return the search string to be used
9816 when following the link. The search string will be part of the
9817 file link, given after a double colon, and `org-open-at-point'
9818 will automatically search for it. If special measures must be
9819 taken to make the search successful, another function should be
9820 added to the companion hook `org-execute-file-search-functions',
9821 which see.
9823 A function in this hook may also use `setq' to set the variable
9824 `description' to provide a suggestion for the descriptive text to
9825 be used for this link when it gets inserted into an Org-mode
9826 buffer with \\[org-insert-link].")
9828 (defvar org-execute-file-search-functions nil
9829 "List of functions to execute a file search triggered by a link.
9831 Functions added to this hook must accept a single argument, the
9832 search string that was part of the file link, the part after the
9833 double colon. The function must first check if it would like to
9834 handle this search, for example by checking the `major-mode' or
9835 the file extension. If it decides not to handle this search, it
9836 should just return nil to give other functions a chance. If it
9837 does handle the search, it must return a non-nil value to keep
9838 other functions from trying.
9840 Each function can access the current prefix argument through the
9841 variable `current-prefix-argument'. Note that a single prefix is
9842 used to force opening a link in Emacs, so it may be good to only
9843 use a numeric or double prefix to guide the search function.
9845 In case this is needed, a function in this hook can also restore
9846 the window configuration before `org-open-at-point' was called using:
9848 (set-window-configuration org-window-config-before-follow-link)")
9850 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9851 (defun org-link-search (s &optional type avoid-pos stealth)
9852 "Search for a link search option.
9853 If S is surrounded by forward slashes, it is interpreted as a
9854 regular expression. In org-mode files, this will create an `org-occur'
9855 sparse tree. In ordinary files, `occur' will be used to list matches.
9856 If the current buffer is in `dired-mode', grep will be used to search
9857 in all files. If AVOID-POS is given, ignore matches near that position.
9859 When optional argument STEALTH is non-nil, do not modify
9860 visibility around point, thus ignoring
9861 `org-show-hierarchy-above', `org-show-following-heading' and
9862 `org-show-siblings' variables."
9863 (let ((case-fold-search t)
9864 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9865 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9866 (append '(("") (" ") ("\t") ("\n"))
9867 org-emphasis-alist)
9868 "\\|") "\\)"))
9869 (pos (point))
9870 (pre nil) (post nil)
9871 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9872 (cond
9873 ;; First check if there are any special search functions
9874 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9875 ;; Now try the builtin stuff
9876 ((and (equal (string-to-char s0) ?#)
9877 (> (length s0) 1)
9878 (save-excursion
9879 (goto-char (point-min))
9880 (and
9881 (re-search-forward
9882 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9883 (setq type 'dedicated
9884 pos (match-beginning 0))))
9885 ;; There is an exact target for this
9886 (goto-char pos)
9887 (org-back-to-heading t)))
9888 ((save-excursion
9889 (goto-char (point-min))
9890 (and
9891 (re-search-forward
9892 (concat "<<" (regexp-quote s0) ">>") nil t)
9893 (setq type 'dedicated
9894 pos (match-beginning 0))))
9895 ;; There is an exact target for this
9896 (goto-char pos))
9897 ((save-excursion
9898 (goto-char (point-min))
9899 (and
9900 (re-search-forward
9901 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9902 (setq type 'dedicated pos (match-beginning 0))))
9903 ;; Found an invisible target.
9904 (goto-char pos))
9905 ((save-excursion
9906 (goto-char (point-min))
9907 (and
9908 (re-search-forward
9909 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9910 (setq type 'dedicated pos (match-beginning 0))))
9911 ;; Found an element with a matching #+name affiliated keyword.
9912 (goto-char pos))
9913 ((and (string-match "^(\\(.*\\))$" s0)
9914 (save-excursion
9915 (goto-char (point-min))
9916 (and
9917 (re-search-forward
9918 (concat "[^[]" (regexp-quote
9919 (format org-coderef-label-format
9920 (match-string 1 s0))))
9921 nil t)
9922 (setq type 'dedicated
9923 pos (1+ (match-beginning 0))))))
9924 ;; There is a coderef target for this
9925 (goto-char pos))
9926 ((string-match "^/\\(.*\\)/$" s)
9927 ;; A regular expression
9928 (cond
9929 ((eq major-mode 'org-mode)
9930 (org-occur (match-string 1 s)))
9931 ;;((eq major-mode 'dired-mode)
9932 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9933 (t (org-do-occur (match-string 1 s)))))
9934 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9935 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9936 (goto-char (point-min))
9937 (cond
9938 ((let (case-fold-search)
9939 (re-search-forward (format org-complex-heading-regexp-format
9940 (regexp-quote s))
9941 nil t))
9942 ;; OK, found a match
9943 (setq type 'dedicated)
9944 (goto-char (match-beginning 0)))
9945 ((and (not org-link-search-inhibit-query)
9946 (eq org-link-search-must-match-exact-headline 'query-to-create)
9947 (y-or-n-p "No match - create this as a new heading? "))
9948 (goto-char (point-max))
9949 (or (bolp) (newline))
9950 (insert "* " s "\n")
9951 (beginning-of-line 0))
9953 (goto-char pos)
9954 (error "No match"))))
9956 ;; A normal search string
9957 (when (equal (string-to-char s) ?*)
9958 ;; Anchor on headlines, post may include tags.
9959 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9960 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9961 s (substring s 1)))
9962 (remove-text-properties
9963 0 (length s)
9964 '(face nil mouse-face nil keymap nil fontified nil) s)
9965 ;; Make a series of regular expressions to find a match
9966 (setq words (org-split-string s "[ \n\r\t]+")
9968 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9969 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9970 "\\)" markers)
9971 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9972 re2a (concat "[ \t\r\n]" re2a_)
9973 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9974 re4 (concat "[^a-zA-Z_]" re4_)
9976 re1 (concat pre re2 post)
9977 re3 (concat pre (if pre re4_ re4) post)
9978 re5 (concat pre ".*" re4)
9979 re2 (concat pre re2)
9980 re2a (concat pre (if pre re2a_ re2a))
9981 re4 (concat pre (if pre re4_ re4))
9982 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9983 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9984 re5 "\\)"
9986 (cond
9987 ((eq type 'org-occur) (org-occur reall))
9988 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9989 (t (goto-char (point-min))
9990 (setq type 'fuzzy)
9991 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9992 (org-search-not-self 1 re1 nil t)
9993 (org-search-not-self 1 re2 nil t)
9994 (org-search-not-self 1 re2a nil t)
9995 (org-search-not-self 1 re3 nil t)
9996 (org-search-not-self 1 re4 nil t)
9997 (org-search-not-self 1 re5 nil t)
9999 (goto-char (match-beginning 1))
10000 (goto-char pos)
10001 (error "No match"))))))
10002 (and (eq major-mode 'org-mode)
10003 (not stealth)
10004 (org-show-context 'link-search))
10005 type))
10007 (defun org-search-not-self (group &rest args)
10008 "Execute `re-search-forward', but only accept matches that do not
10009 enclose the position of `org-open-link-marker'."
10010 (let ((m org-open-link-marker))
10011 (catch 'exit
10012 (while (apply 're-search-forward args)
10013 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10014 (goto-char (match-end group))
10015 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10016 (> (match-beginning 0) (marker-position m))
10017 (< (match-end 0) (marker-position m)))
10018 (save-match-data
10019 (or (not (org-in-regexp
10020 org-bracket-link-analytic-regexp 1))
10021 (not (match-end 4)) ; no description
10022 (and (<= (match-beginning 4) (point))
10023 (>= (match-end 4) (point))))))
10024 (throw 'exit (point))))))))
10026 (defun org-get-buffer-for-internal-link (buffer)
10027 "Return a buffer to be used for displaying the link target of internal links."
10028 (cond
10029 ((not org-display-internal-link-with-indirect-buffer)
10030 buffer)
10031 ((string-match "(Clone)$" (buffer-name buffer))
10032 (message "Buffer is already a clone, not making another one")
10033 ;; we also do not modify visibility in this case
10034 buffer)
10035 (t ; make a new indirect buffer for displaying the link
10036 (let* ((bn (buffer-name buffer))
10037 (ibn (concat bn "(Clone)"))
10038 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10039 (with-current-buffer ib (org-overview))
10040 ib))))
10042 (defun org-do-occur (regexp &optional cleanup)
10043 "Call the Emacs command `occur'.
10044 If CLEANUP is non-nil, remove the printout of the regular expression
10045 in the *Occur* buffer. This is useful if the regex is long and not useful
10046 to read."
10047 (occur regexp)
10048 (when cleanup
10049 (let ((cwin (selected-window)) win beg end)
10050 (when (setq win (get-buffer-window "*Occur*"))
10051 (select-window win))
10052 (goto-char (point-min))
10053 (when (re-search-forward "match[a-z]+" nil t)
10054 (setq beg (match-end 0))
10055 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10056 (setq end (1- (match-beginning 0)))))
10057 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10058 (goto-char (point-min))
10059 (select-window cwin))))
10061 ;;; The mark ring for links jumps
10063 (defvar org-mark-ring nil
10064 "Mark ring for positions before jumps in Org-mode.")
10065 (defvar org-mark-ring-last-goto nil
10066 "Last position in the mark ring used to go back.")
10067 ;; Fill and close the ring
10068 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10069 (loop for i from 1 to org-mark-ring-length do
10070 (push (make-marker) org-mark-ring))
10071 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10072 org-mark-ring)
10074 (defun org-mark-ring-push (&optional pos buffer)
10075 "Put the current position or POS into the mark ring and rotate it."
10076 (interactive)
10077 (setq pos (or pos (point)))
10078 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10079 (move-marker (car org-mark-ring)
10080 (or pos (point))
10081 (or buffer (current-buffer)))
10082 (message "%s"
10083 (substitute-command-keys
10084 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10086 (defun org-mark-ring-goto (&optional n)
10087 "Jump to the previous position in the mark ring.
10088 With prefix arg N, jump back that many stored positions. When
10089 called several times in succession, walk through the entire ring.
10090 Org-mode commands jumping to a different position in the current file,
10091 or to another Org-mode file, automatically push the old position
10092 onto the ring."
10093 (interactive "p")
10094 (let (p m)
10095 (if (eq last-command this-command)
10096 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10097 (setq p org-mark-ring))
10098 (setq org-mark-ring-last-goto p)
10099 (setq m (car p))
10100 (org-pop-to-buffer-same-window (marker-buffer m))
10101 (goto-char m)
10102 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10104 (defun org-remove-angle-brackets (s)
10105 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10106 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10108 (defun org-add-angle-brackets (s)
10109 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10110 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10112 (defun org-remove-double-quotes (s)
10113 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10114 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10117 ;;; Following specific links
10119 (defun org-follow-timestamp-link ()
10120 (cond
10121 ((org-at-date-range-p t)
10122 (let ((org-agenda-start-on-weekday)
10123 (t1 (match-string 1))
10124 (t2 (match-string 2)))
10125 (setq t1 (time-to-days (org-time-string-to-time t1))
10126 t2 (time-to-days (org-time-string-to-time t2)))
10127 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10128 ((org-at-timestamp-p t)
10129 (org-agenda-list nil (time-to-days (org-time-string-to-time
10130 (substring (match-string 1) 0 10)))
10132 (t (error "This should not happen"))))
10135 ;;; Following file links
10136 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10137 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10138 (declare-function mailcap-mime-info
10139 "mailcap" (string &optional request no-decode))
10140 (defvar org-wait nil)
10141 (defun org-open-file (path &optional in-emacs line search)
10142 "Open the file at PATH.
10143 First, this expands any special file name abbreviations. Then the
10144 configuration variable `org-file-apps' is checked if it contains an
10145 entry for this file type, and if yes, the corresponding command is launched.
10147 If no application is found, Emacs simply visits the file.
10149 With optional prefix argument IN-EMACS, Emacs will visit the file.
10150 With a double \\[universal-argument] \\[universal-argument] \
10151 prefix arg, Org tries to avoid opening in Emacs
10152 and to use an external application to visit the file.
10154 Optional LINE specifies a line to go to, optional SEARCH a string
10155 to search for. If LINE or SEARCH is given, the file will be
10156 opened in Emacs, unless an entry from org-file-apps that makes
10157 use of groups in a regexp matches.
10159 If you want to change the way frames are used when following a
10160 link, please customize `org-link-frame-setup'.
10162 If the file does not exist, an error is thrown."
10163 (let* ((file (if (equal path "")
10164 buffer-file-name
10165 (substitute-in-file-name (expand-file-name path))))
10166 (file-apps (append org-file-apps (org-default-apps)))
10167 (apps (org-remove-if
10168 'org-file-apps-entry-match-against-dlink-p file-apps))
10169 (apps-dlink (org-remove-if-not
10170 'org-file-apps-entry-match-against-dlink-p file-apps))
10171 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10172 (dirp (if remp nil (file-directory-p file)))
10173 (file (if (and dirp org-open-directory-means-index-dot-org)
10174 (concat (file-name-as-directory file) "index.org")
10175 file))
10176 (a-m-a-p (assq 'auto-mode apps))
10177 (dfile (downcase file))
10178 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10179 (link (cond ((and (eq line nil)
10180 (eq search nil))
10181 file)
10182 (line
10183 (concat file "::" (number-to-string line)))
10184 (search
10185 (concat file "::" search))))
10186 (dlink (downcase link))
10187 (old-buffer (current-buffer))
10188 (old-pos (point))
10189 (old-mode major-mode)
10190 ext cmd link-match-data)
10191 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10192 (setq ext (match-string 1 dfile))
10193 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10194 (setq ext (match-string 1 dfile))))
10195 (cond
10196 ((member in-emacs '((16) system))
10197 (setq cmd (cdr (assoc 'system apps))))
10198 (in-emacs (setq cmd 'emacs))
10200 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10201 (and dirp (cdr (assoc 'directory apps)))
10202 ; first, try matching against apps-dlink
10203 ; if we get a match here, store the match data for later
10204 (let ((match (assoc-default dlink apps-dlink
10205 'string-match)))
10206 (if match
10207 (progn (setq link-match-data (match-data))
10208 match)
10209 (progn (setq in-emacs (or in-emacs line search))
10210 nil))) ; if we have no match in apps-dlink,
10211 ; always open the file in emacs if line or search
10212 ; is given (for backwards compatibility)
10213 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10214 'string-match)
10215 (cdr (assoc ext apps))
10216 (cdr (assoc t apps))))))
10217 (when (eq cmd 'system)
10218 (setq cmd (cdr (assoc 'system apps))))
10219 (when (eq cmd 'default)
10220 (setq cmd (cdr (assoc t apps))))
10221 (when (eq cmd 'mailcap)
10222 (require 'mailcap)
10223 (mailcap-parse-mailcaps)
10224 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10225 (command (mailcap-mime-info mime-type)))
10226 (if (stringp command)
10227 (setq cmd command)
10228 (setq cmd 'emacs))))
10229 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10230 (not (file-exists-p file))
10231 (not org-open-non-existing-files))
10232 (error "No such file: %s" file))
10233 (cond
10234 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10235 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10236 (while (string-match "['\"]%s['\"]" cmd)
10237 (setq cmd (replace-match "%s" t t cmd)))
10238 (while (string-match "%s" cmd)
10239 (setq cmd (replace-match
10240 (save-match-data
10241 (shell-quote-argument
10242 (convert-standard-filename file)))
10243 t t cmd)))
10245 ;; Replace "%1", "%2" etc. in command with group matches from regex
10246 (save-match-data
10247 (let ((match-index 1)
10248 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10249 (set-match-data link-match-data)
10250 (while (<= match-index number-of-groups)
10251 (let ((regex (concat "%" (number-to-string match-index)))
10252 (replace-with (match-string match-index dlink)))
10253 (while (string-match regex cmd)
10254 (setq cmd (replace-match replace-with t t cmd))))
10255 (setq match-index (+ match-index 1)))))
10257 (save-window-excursion
10258 (start-process-shell-command cmd nil cmd)
10259 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10261 ((or (stringp cmd)
10262 (eq cmd 'emacs))
10263 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10264 (widen)
10265 (if line (org-goto-line line)
10266 (if search (org-link-search search))))
10267 ((consp cmd)
10268 (let ((file (convert-standard-filename file)))
10269 (save-match-data
10270 (set-match-data link-match-data)
10271 (eval cmd))))
10272 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10273 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10274 (or (not (equal old-buffer (current-buffer)))
10275 (not (equal old-pos (point))))
10276 (org-mark-ring-push old-pos old-buffer))))
10278 (defun org-file-apps-entry-match-against-dlink-p (entry)
10279 "This function returns non-nil if `entry' uses a regular
10280 expression which should be matched against the whole link by
10281 org-open-file.
10283 It assumes that is the case when the entry uses a regular
10284 expression which has at least one grouping construct and the
10285 action is either a lisp form or a command string containing
10286 '%1', i.e. using at least one subexpression match as a
10287 parameter."
10288 (let ((selector (car entry))
10289 (action (cdr entry)))
10290 (if (stringp selector)
10291 (and (> (regexp-opt-depth selector) 0)
10292 (or (and (stringp action)
10293 (string-match "%[0-9]" action))
10294 (consp action)))
10295 nil)))
10297 (defun org-default-apps ()
10298 "Return the default applications for this operating system."
10299 (cond
10300 ((eq system-type 'darwin)
10301 org-file-apps-defaults-macosx)
10302 ((eq system-type 'windows-nt)
10303 org-file-apps-defaults-windowsnt)
10304 (t org-file-apps-defaults-gnu)))
10306 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10307 "Convert extensions to regular expressions in the cars of LIST.
10308 Also, weed out any non-string entries, because the return value is used
10309 only for regexp matching.
10310 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10311 point to the symbol `emacs', indicating that the file should
10312 be opened in Emacs."
10313 (append
10314 (delq nil
10315 (mapcar (lambda (x)
10316 (if (not (stringp (car x)))
10318 (if (string-match "\\W" (car x))
10320 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10321 list))
10322 (if add-auto-mode
10323 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10325 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10326 (defun org-file-remote-p (file)
10327 "Test whether FILE specifies a location on a remote system.
10328 Return non-nil if the location is indeed remote.
10330 For example, the filename \"/user@host:/foo\" specifies a location
10331 on the system \"/user@host:\"."
10332 (cond ((fboundp 'file-remote-p)
10333 (file-remote-p file))
10334 ((fboundp 'tramp-handle-file-remote-p)
10335 (tramp-handle-file-remote-p file))
10336 ((and (boundp 'ange-ftp-name-format)
10337 (string-match (car ange-ftp-name-format) file))
10339 (t nil)))
10342 ;;;; Refiling
10344 (defun org-get-org-file ()
10345 "Read a filename, with default directory `org-directory'."
10346 (let ((default (or org-default-notes-file remember-data-file)))
10347 (read-file-name (format "File name [%s]: " default)
10348 (file-name-as-directory org-directory)
10349 default)))
10351 (defun org-notes-order-reversed-p ()
10352 "Check if the current file should receive notes in reversed order."
10353 (cond
10354 ((not org-reverse-note-order) nil)
10355 ((eq t org-reverse-note-order) t)
10356 ((not (listp org-reverse-note-order)) nil)
10357 (t (catch 'exit
10358 (let ((all org-reverse-note-order)
10359 entry)
10360 (while (setq entry (pop all))
10361 (if (string-match (car entry) buffer-file-name)
10362 (throw 'exit (cdr entry))))
10363 nil)))))
10365 (defvar org-refile-target-table nil
10366 "The list of refile targets, created by `org-refile'.")
10368 (defvar org-agenda-new-buffers nil
10369 "Buffers created to visit agenda files.")
10371 (defvar org-refile-cache nil
10372 "Cache for refile targets.")
10374 (defvar org-refile-markers nil
10375 "All the markers used for caching refile locations.")
10377 (defun org-refile-marker (pos)
10378 "Get a new refile marker, but only if caching is in use."
10379 (if (not org-refile-use-cache)
10381 (let ((m (make-marker)))
10382 (move-marker m pos)
10383 (push m org-refile-markers)
10384 m)))
10386 (defun org-refile-cache-clear ()
10387 "Clear the refile cache and disable all the markers."
10388 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10389 (setq org-refile-markers nil)
10390 (setq org-refile-cache nil)
10391 (message "Refile cache has been cleared"))
10393 (defun org-refile-cache-check-set (set)
10394 "Check if all the markers in the cache still have live buffers."
10395 (let (marker)
10396 (catch 'exit
10397 (while (and set (setq marker (nth 3 (pop set))))
10398 ;; if org-refile-use-outline-path is 'file, marker may be nil
10399 (when (and marker (null (marker-buffer marker)))
10400 (message "not found") (sit-for 3)
10401 (throw 'exit nil)))
10402 t)))
10404 (defun org-refile-cache-put (set &rest identifiers)
10405 "Push the refile targets SET into the cache, under IDENTIFIERS."
10406 (let* ((key (sha1 (prin1-to-string identifiers)))
10407 (entry (assoc key org-refile-cache)))
10408 (if entry
10409 (setcdr entry set)
10410 (push (cons key set) org-refile-cache))))
10412 (defun org-refile-cache-get (&rest identifiers)
10413 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10414 (cond
10415 ((not org-refile-cache) nil)
10416 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10418 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10419 org-refile-cache))))
10420 (and set (org-refile-cache-check-set set) set)))))
10422 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10423 "Produce a table with refile targets."
10424 (let ((case-fold-search nil)
10425 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10426 (entries (or org-refile-targets '((nil . (:level . 1)))))
10427 targets tgs txt re files f desc descre fast-path-p level pos0)
10428 (message "Getting targets...")
10429 (with-current-buffer (or default-buffer (current-buffer))
10430 (while (setq entry (pop entries))
10431 (setq files (car entry) desc (cdr entry))
10432 (setq fast-path-p nil)
10433 (cond
10434 ((null files) (setq files (list (current-buffer))))
10435 ((eq files 'org-agenda-files)
10436 (setq files (org-agenda-files 'unrestricted)))
10437 ((and (symbolp files) (fboundp files))
10438 (setq files (funcall files)))
10439 ((and (symbolp files) (boundp files))
10440 (setq files (symbol-value files))))
10441 (if (stringp files) (setq files (list files)))
10442 (cond
10443 ((eq (car desc) :tag)
10444 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10445 ((eq (car desc) :todo)
10446 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10447 ((eq (car desc) :regexp)
10448 (setq descre (cdr desc)))
10449 ((eq (car desc) :level)
10450 (setq descre (concat "^\\*\\{" (number-to-string
10451 (if org-odd-levels-only
10452 (1- (* 2 (cdr desc)))
10453 (cdr desc)))
10454 "\\}[ \t]")))
10455 ((eq (car desc) :maxlevel)
10456 (setq fast-path-p t)
10457 (setq descre (concat "^\\*\\{1," (number-to-string
10458 (if org-odd-levels-only
10459 (1- (* 2 (cdr desc)))
10460 (cdr desc)))
10461 "\\}[ \t]")))
10462 (t (error "Bad refiling target description %s" desc)))
10463 (while (setq f (pop files))
10464 (with-current-buffer
10465 (if (bufferp f) f (org-get-agenda-file-buffer f))
10467 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10468 (progn
10469 (if (bufferp f) (setq f (buffer-file-name
10470 (buffer-base-buffer f))))
10471 (setq f (and f (expand-file-name f)))
10472 (if (eq org-refile-use-outline-path 'file)
10473 (push (list (file-name-nondirectory f) f nil nil) tgs))
10474 (save-excursion
10475 (save-restriction
10476 (widen)
10477 (goto-char (point-min))
10478 (while (re-search-forward descre nil t)
10479 (goto-char (setq pos0 (point-at-bol)))
10480 (catch 'next
10481 (when org-refile-target-verify-function
10482 (save-match-data
10483 (or (funcall org-refile-target-verify-function)
10484 (throw 'next t))))
10485 (when (and (looking-at org-complex-heading-regexp)
10486 (not (member (match-string 4) excluded-entries))
10487 (match-string 4))
10488 (setq level (org-reduced-level
10489 (- (match-end 1) (match-beginning 1)))
10490 txt (org-link-display-format (match-string 4))
10491 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10492 re (format org-complex-heading-regexp-format
10493 (regexp-quote (match-string 4))))
10494 (when org-refile-use-outline-path
10495 (setq txt (mapconcat
10496 'org-protect-slash
10497 (append
10498 (if (eq org-refile-use-outline-path
10499 'file)
10500 (list (file-name-nondirectory
10501 (buffer-file-name
10502 (buffer-base-buffer))))
10503 (if (eq org-refile-use-outline-path
10504 'full-file-path)
10505 (list (buffer-file-name
10506 (buffer-base-buffer)))))
10507 (org-get-outline-path fast-path-p
10508 level txt)
10509 (list txt))
10510 "/")))
10511 (push (list txt f re (org-refile-marker (point)))
10512 tgs)))
10513 (when (= (point) pos0)
10514 ;; verification function has not moved point
10515 (goto-char (point-at-eol))))))))
10516 (when org-refile-use-cache
10517 (org-refile-cache-put tgs (buffer-file-name) descre))
10518 (setq targets (append tgs targets))
10519 ))))
10520 (message "Getting targets...done")
10521 (nreverse targets)))
10523 (defun org-protect-slash (s)
10524 (while (string-match "/" s)
10525 (setq s (replace-match "\\" t t s)))
10528 (defvar org-olpa (make-vector 20 nil))
10530 (defun org-get-outline-path (&optional fastp level heading)
10531 "Return the outline path to the current entry, as a list.
10533 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10534 routine which makes outline path derivations for an entire file,
10535 avoiding backtracing. Refile target collection makes use of that."
10536 (if fastp
10537 (progn
10538 (if (> level 19)
10539 (error "Outline path failure, more than 19 levels"))
10540 (loop for i from level upto 19 do
10541 (aset org-olpa i nil))
10542 (prog1
10543 (delq nil (append org-olpa nil))
10544 (aset org-olpa level heading)))
10545 (let (rtn case-fold-search)
10546 (save-excursion
10547 (save-restriction
10548 (widen)
10549 (while (org-up-heading-safe)
10550 (when (looking-at org-complex-heading-regexp)
10551 (push (org-match-string-no-properties 4) rtn)))
10552 rtn)))))
10554 (defun org-format-outline-path (path &optional width prefix)
10555 "Format the outline path PATH for display.
10556 Width is the maximum number of characters that is available.
10557 Prefix is a prefix to be included in the returned string,
10558 such as the file name."
10559 (setq width (or width 79))
10560 (if prefix (setq width (- width (length prefix))))
10561 (if (not path)
10562 (or prefix "")
10563 (let* ((nsteps (length path))
10564 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10565 (maxwidth (if (<= total-width width)
10566 10000 ;; everything fits
10567 ;; we need to shorten the level headings
10568 (/ (- width nsteps) nsteps)))
10569 (org-odd-levels-only nil)
10570 (n 0)
10571 (total (1+ (length prefix))))
10572 (setq maxwidth (max maxwidth 10))
10573 (concat prefix
10574 (mapconcat
10575 (lambda (h)
10576 (setq n (1+ n))
10577 (if (and (= n nsteps) (< maxwidth 10000))
10578 (setq maxwidth (- total-width total)))
10579 (if (< (length h) maxwidth)
10580 (progn (setq total (+ total (length h) 1)) h)
10581 (setq h (substring h 0 (- maxwidth 2))
10582 total (+ total maxwidth 1))
10583 (if (string-match "[ \t]+\\'" h)
10584 (setq h (substring h 0 (match-beginning 0))))
10585 (setq h (concat h "..")))
10586 (org-add-props h nil 'face
10587 (nth (% (1- n) org-n-level-faces)
10588 org-level-faces))
10590 path "/")))))
10592 (defun org-display-outline-path (&optional file current)
10593 "Display the current outline path in the echo area."
10594 (interactive "P")
10595 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10596 (case-fold-search nil)
10597 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10598 (if current (setq path (append path
10599 (save-excursion
10600 (org-back-to-heading t)
10601 (if (looking-at org-complex-heading-regexp)
10602 (list (match-string 4)))))))
10603 (message "%s"
10604 (org-format-outline-path
10605 path
10606 (1- (frame-width))
10607 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10609 (defvar org-refile-history nil
10610 "History for refiling operations.")
10612 (defvar org-after-refile-insert-hook nil
10613 "Hook run after `org-refile' has inserted its stuff at the new location.
10614 Note that this is still *before* the stuff will be removed from
10615 the *old* location.")
10617 (defvar org-capture-last-stored-marker)
10618 (defun org-refile (&optional goto default-buffer rfloc)
10619 "Move the entry or entries at point to another heading.
10620 The list of target headings is compiled using the information in
10621 `org-refile-targets', which see.
10623 At the target location, the entry is filed as a subitem of the target
10624 heading. Depending on `org-reverse-note-order', the new subitem will
10625 either be the first or the last subitem.
10627 If there is an active region, all entries in that region will be moved.
10628 However, the region must fulfill the requirement that the first heading
10629 is the first one sets the top-level of the moved text - at most siblings
10630 below it are allowed.
10632 With prefix arg GOTO, the command will only visit the target location
10633 and not actually move anything.
10635 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10636 go to the location where the last refiling operation has put the subtree.
10637 With a prefix argument of `2', refile to the running clock.
10639 RFLOC can be a refile location obtained in a different way.
10641 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10643 If you are using target caching (see `org-refile-use-cache'),
10644 You have to clear the target cache in order to find new targets.
10645 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10646 prefix argument (`C-u C-u C-u C-c C-w')."
10648 (interactive "P")
10649 (if (member goto '(0 (64)))
10650 (org-refile-cache-clear)
10651 (let* ((cbuf (current-buffer))
10652 (regionp (org-region-active-p))
10653 (region-start (and regionp (region-beginning)))
10654 (region-end (and regionp (region-end)))
10655 (region-length (and regionp (- region-end region-start)))
10656 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10657 pos it nbuf file re level reversed)
10658 (setq last-command nil)
10659 (when regionp
10660 (goto-char region-start)
10661 (or (bolp) (goto-char (point-at-bol)))
10662 (setq region-start (point))
10663 (unless (or (org-kill-is-subtree-p
10664 (buffer-substring region-start region-end))
10665 (prog1 org-refile-active-region-within-subtree
10666 (org-toggle-heading)))
10667 (error "The region is not a (sequence of) subtree(s)")))
10668 (if (equal goto '(16))
10669 (org-refile-goto-last-stored)
10670 (when (or
10671 (and (equal goto 2)
10672 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10673 (prog1
10674 (setq it (list (or org-clock-heading "running clock")
10675 (buffer-file-name
10676 (marker-buffer org-clock-hd-marker))
10678 (marker-position org-clock-hd-marker)))
10679 (setq goto nil)))
10680 (setq it (or rfloc
10681 (let (heading-text)
10682 (save-excursion
10683 (unless goto
10684 (org-back-to-heading t)
10685 (setq heading-text
10686 (nth 4 (org-heading-components))))
10687 (org-refile-get-location
10688 (cond (goto "Goto")
10689 (regionp "Refile region to")
10690 (t (concat "Refile subtree \""
10691 heading-text "\" to")))
10692 default-buffer
10693 (and (not (equal '(4) goto))
10694 org-refile-allow-creating-parent-nodes)
10695 goto))))))
10696 (setq file (nth 1 it)
10697 re (nth 2 it)
10698 pos (nth 3 it))
10699 (if (and (not goto)
10701 (equal (buffer-file-name) file)
10702 (if regionp
10703 (and (>= pos region-start)
10704 (<= pos region-end))
10705 (and (>= pos (point))
10706 (< pos (save-excursion
10707 (org-end-of-subtree t t))))))
10708 (error "Cannot refile to position inside the tree or region"))
10710 (setq nbuf (or (find-buffer-visiting file)
10711 (find-file-noselect file)))
10712 (if goto
10713 (progn
10714 (org-pop-to-buffer-same-window nbuf)
10715 (goto-char pos)
10716 (org-show-context 'org-goto))
10717 (if regionp
10718 (progn
10719 (org-kill-new (buffer-substring region-start region-end))
10720 (org-save-markers-in-region region-start region-end))
10721 (org-copy-subtree 1 nil t))
10722 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10723 (find-file-noselect file)))
10724 (setq reversed (org-notes-order-reversed-p))
10725 (save-excursion
10726 (save-restriction
10727 (widen)
10728 (if pos
10729 (progn
10730 (goto-char pos)
10731 (looking-at org-outline-regexp)
10732 (setq level (org-get-valid-level (funcall outline-level) 1))
10733 (goto-char
10734 (if reversed
10735 (or (outline-next-heading) (point-max))
10736 (or (save-excursion (org-get-next-sibling))
10737 (org-end-of-subtree t t)
10738 (point-max)))))
10739 (setq level 1)
10740 (if (not reversed)
10741 (goto-char (point-max))
10742 (goto-char (point-min))
10743 (or (outline-next-heading) (goto-char (point-max)))))
10744 (if (not (bolp)) (newline))
10745 (org-paste-subtree level)
10746 (when org-log-refile
10747 (org-add-log-setup 'refile nil nil 'findpos
10748 org-log-refile)
10749 (unless (eq org-log-refile 'note)
10750 (save-excursion (org-add-log-note))))
10751 (and org-auto-align-tags (org-set-tags nil t))
10752 (bookmark-set "org-refile-last-stored")
10753 ;; If we are refiling for capture, make sure that the
10754 ;; last-capture pointers point here
10755 (when (org-bound-and-true-p org-refile-for-capture)
10756 (bookmark-set "org-capture-last-stored-marker")
10757 (move-marker org-capture-last-stored-marker (point)))
10758 (if (fboundp 'deactivate-mark) (deactivate-mark))
10759 (run-hooks 'org-after-refile-insert-hook))))
10760 (if regionp
10761 (delete-region (point) (+ (point) region-length))
10762 (org-cut-subtree))
10763 (when (featurep 'org-inlinetask)
10764 (org-inlinetask-remove-END-maybe))
10765 (setq org-markers-to-move nil)
10766 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10768 (defun org-refile-goto-last-stored ()
10769 "Go to the location where the last refile was stored."
10770 (interactive)
10771 (bookmark-jump "org-refile-last-stored")
10772 (message "This is the location of the last refile"))
10774 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10775 no-exclude)
10776 "Prompt the user for a refile location, using PROMPT.
10777 PROMPT should not be suffixed with a colon and a space, because
10778 this function appends the default value from
10779 `org-refile-history' automatically, if that is not empty.
10780 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10781 this is used for the GOTO interface."
10782 (let ((org-refile-targets org-refile-targets)
10783 (org-refile-use-outline-path org-refile-use-outline-path)
10784 excluded-entries)
10785 (when (and (eq major-mode 'org-mode)
10786 (not org-refile-use-cache)
10787 (not no-exclude))
10788 (org-map-tree
10789 (lambda()
10790 (setq excluded-entries
10791 (append excluded-entries (list (org-get-heading t t)))))))
10792 (setq org-refile-target-table
10793 (org-refile-get-targets default-buffer excluded-entries)))
10794 (unless org-refile-target-table
10795 (error "No refile targets"))
10796 (let* ((prompt (concat prompt
10797 (and (car org-refile-history)
10798 (concat " (default " (car org-refile-history) ")"))
10799 ": "))
10800 (cbuf (current-buffer))
10801 (partial-completion-mode nil)
10802 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10803 (cfunc (if (and org-refile-use-outline-path
10804 org-outline-path-complete-in-steps)
10805 'org-olpath-completing-read
10806 'org-icompleting-read))
10807 (extra (if org-refile-use-outline-path "/" ""))
10808 (filename (and cfn (expand-file-name cfn)))
10809 (tbl (mapcar
10810 (lambda (x)
10811 (if (and (not (member org-refile-use-outline-path
10812 '(file full-file-path)))
10813 (not (equal filename (nth 1 x))))
10814 (cons (concat (car x) extra " ("
10815 (file-name-nondirectory (nth 1 x)) ")")
10816 (cdr x))
10817 (cons (concat (car x) extra) (cdr x))))
10818 org-refile-target-table))
10819 (completion-ignore-case t)
10820 pa answ parent-target child parent old-hist)
10821 (setq old-hist org-refile-history)
10822 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10823 nil 'org-refile-history (car org-refile-history)))
10824 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10825 (org-refile-check-position pa)
10826 (if pa
10827 (progn
10828 (when (or (not org-refile-history)
10829 (not (eq old-hist org-refile-history))
10830 (not (equal (car pa) (car org-refile-history))))
10831 (setq org-refile-history
10832 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10833 org-refile-history
10834 (cdr org-refile-history))))
10835 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10836 (pop org-refile-history)))
10838 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10839 (progn
10840 (setq parent (match-string 1 answ)
10841 child (match-string 2 answ))
10842 (setq parent-target (or (assoc parent tbl)
10843 (assoc (concat parent "/") tbl)))
10844 (when (and parent-target
10845 (or (eq new-nodes t)
10846 (and (eq new-nodes 'confirm)
10847 (y-or-n-p (format "Create new node \"%s\"? "
10848 child)))))
10849 (org-refile-new-child parent-target child)))
10850 (error "Invalid target location")))))
10852 (declare-function org-string-nw-p "org-macs.el" (s))
10853 (defun org-refile-check-position (refile-pointer)
10854 "Check if the refile pointer matches the readline to which it points."
10855 (let* ((file (nth 1 refile-pointer))
10856 (re (nth 2 refile-pointer))
10857 (pos (nth 3 refile-pointer))
10858 buffer)
10859 (when (org-string-nw-p re)
10860 (setq buffer (if (markerp pos)
10861 (marker-buffer pos)
10862 (or (find-buffer-visiting file)
10863 (find-file-noselect file))))
10864 (with-current-buffer buffer
10865 (save-excursion
10866 (save-restriction
10867 (widen)
10868 (goto-char pos)
10869 (beginning-of-line 1)
10870 (unless (org-looking-at-p re)
10871 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10873 (defun org-refile-new-child (parent-target child)
10874 "Use refile target PARENT-TARGET to add new CHILD below it."
10875 (unless parent-target
10876 (error "Cannot find parent for new node"))
10877 (let ((file (nth 1 parent-target))
10878 (pos (nth 3 parent-target))
10879 level)
10880 (with-current-buffer (or (find-buffer-visiting file)
10881 (find-file-noselect file))
10882 (save-excursion
10883 (save-restriction
10884 (widen)
10885 (if pos
10886 (goto-char pos)
10887 (goto-char (point-max))
10888 (if (not (bolp)) (newline)))
10889 (when (looking-at org-outline-regexp)
10890 (setq level (funcall outline-level))
10891 (org-end-of-subtree t t))
10892 (org-back-over-empty-lines)
10893 (insert "\n" (make-string
10894 (if pos (org-get-valid-level level 1) 1) ?*)
10895 " " child "\n")
10896 (beginning-of-line 0)
10897 (list (concat (car parent-target) "/" child) file "" (point)))))))
10899 (defun org-olpath-completing-read (prompt collection &rest args)
10900 "Read an outline path like a file name."
10901 (let ((thetable collection)
10902 (org-completion-use-ido nil) ; does not work with ido.
10903 (org-completion-use-iswitchb nil)) ; or iswitchb
10904 (apply
10905 'org-icompleting-read prompt
10906 (lambda (string predicate &optional flag)
10907 (let (rtn r f (l (length string)))
10908 (cond
10909 ((eq flag nil)
10910 ;; try completion
10911 (try-completion string thetable))
10912 ((eq flag t)
10913 ;; all-completions
10914 (setq rtn (all-completions string thetable predicate))
10915 (mapcar
10916 (lambda (x)
10917 (setq r (substring x l))
10918 (if (string-match " ([^)]*)$" x)
10919 (setq f (match-string 0 x))
10920 (setq f ""))
10921 (if (string-match "/" r)
10922 (concat string (substring r 0 (match-end 0)) f)
10924 rtn))
10925 ((eq flag 'lambda)
10926 ;; exact match?
10927 (assoc string thetable)))
10929 args)))
10931 ;;;; Dynamic blocks
10933 (defun org-find-dblock (name)
10934 "Find the first dynamic block with name NAME in the buffer.
10935 If not found, stay at current position and return nil."
10936 (let (pos)
10937 (save-excursion
10938 (goto-char (point-min))
10939 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10940 nil t)
10941 (match-beginning 0))))
10942 (if pos (goto-char pos))
10943 pos))
10945 (defconst org-dblock-start-re
10946 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10947 "Matches the start line of a dynamic block, with parameters.")
10949 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10950 "Matches the end of a dynamic block.")
10952 (defun org-create-dblock (plist)
10953 "Create a dynamic block section, with parameters taken from PLIST.
10954 PLIST must contain a :name entry which is used as name of the block."
10955 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10956 (end-of-line 1)
10957 (newline))
10958 (let ((col (current-column))
10959 (name (plist-get plist :name)))
10960 (insert "#+BEGIN: " name)
10961 (while plist
10962 (if (eq (car plist) :name)
10963 (setq plist (cddr plist))
10964 (insert " " (prin1-to-string (pop plist)))))
10965 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10966 (beginning-of-line -2)))
10968 (defun org-prepare-dblock ()
10969 "Prepare dynamic block for refresh.
10970 This empties the block, puts the cursor at the insert position and returns
10971 the property list including an extra property :name with the block name."
10972 (unless (looking-at org-dblock-start-re)
10973 (error "Not at a dynamic block"))
10974 (let* ((begdel (1+ (match-end 0)))
10975 (name (org-no-properties (match-string 1)))
10976 (params (append (list :name name)
10977 (read (concat "(" (match-string 3) ")")))))
10978 (save-excursion
10979 (beginning-of-line 1)
10980 (skip-chars-forward " \t")
10981 (setq params (plist-put params :indentation-column (current-column))))
10982 (unless (re-search-forward org-dblock-end-re nil t)
10983 (error "Dynamic block not terminated"))
10984 (setq params
10985 (append params
10986 (list :content (buffer-substring
10987 begdel (match-beginning 0)))))
10988 (delete-region begdel (match-beginning 0))
10989 (goto-char begdel)
10990 (open-line 1)
10991 params))
10993 (defun org-map-dblocks (&optional command)
10994 "Apply COMMAND to all dynamic blocks in the current buffer.
10995 If COMMAND is not given, use `org-update-dblock'."
10996 (let ((cmd (or command 'org-update-dblock)))
10997 (save-excursion
10998 (goto-char (point-min))
10999 (while (re-search-forward org-dblock-start-re nil t)
11000 (goto-char (match-beginning 0))
11001 (save-excursion
11002 (condition-case nil
11003 (funcall cmd)
11004 (error (message "Error during update of dynamic block"))))
11005 (unless (re-search-forward org-dblock-end-re nil t)
11006 (error "Dynamic block not terminated"))))))
11008 (defun org-dblock-update (&optional arg)
11009 "User command for updating dynamic blocks.
11010 Update the dynamic block at point. With prefix ARG, update all dynamic
11011 blocks in the buffer."
11012 (interactive "P")
11013 (if arg
11014 (org-update-all-dblocks)
11015 (or (looking-at org-dblock-start-re)
11016 (org-beginning-of-dblock))
11017 (org-update-dblock)))
11019 (defun org-update-dblock ()
11020 "Update the dynamic block at point.
11021 This means to empty the block, parse for parameters and then call
11022 the correct writing function."
11023 (interactive)
11024 (save-window-excursion
11025 (let* ((pos (point))
11026 (line (org-current-line))
11027 (params (org-prepare-dblock))
11028 (name (plist-get params :name))
11029 (indent (plist-get params :indentation-column))
11030 (cmd (intern (concat "org-dblock-write:" name))))
11031 (message "Updating dynamic block `%s' at line %d..." name line)
11032 (funcall cmd params)
11033 (message "Updating dynamic block `%s' at line %d...done" name line)
11034 (goto-char pos)
11035 (when (and indent (> indent 0))
11036 (setq indent (make-string indent ?\ ))
11037 (save-excursion
11038 (org-beginning-of-dblock)
11039 (forward-line 1)
11040 (while (not (looking-at org-dblock-end-re))
11041 (insert indent)
11042 (beginning-of-line 2))
11043 (when (looking-at org-dblock-end-re)
11044 (and (looking-at "[ \t]+")
11045 (replace-match ""))
11046 (insert indent)))))))
11048 (defun org-beginning-of-dblock ()
11049 "Find the beginning of the dynamic block at point.
11050 Error if there is no such block at point."
11051 (let ((pos (point))
11052 beg)
11053 (end-of-line 1)
11054 (if (and (re-search-backward org-dblock-start-re nil t)
11055 (setq beg (match-beginning 0))
11056 (re-search-forward org-dblock-end-re nil t)
11057 (> (match-end 0) pos))
11058 (goto-char beg)
11059 (goto-char pos)
11060 (error "Not in a dynamic block"))))
11062 ;;;###autoload
11063 (defun org-update-all-dblocks ()
11064 "Update all dynamic blocks in the buffer.
11065 This function can be used in a hook."
11066 (interactive)
11067 (when (eq major-mode 'org-mode)
11068 (org-map-dblocks 'org-update-dblock)))
11071 ;;;; Completion
11073 (defconst org-additional-option-like-keywords
11074 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11075 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11076 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11077 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11078 "BEGIN:" "END:"
11079 "ORGTBL" "TBLFM:" "TBLNAME:"
11080 "BEGIN_EXAMPLE" "END_EXAMPLE"
11081 "BEGIN_QUOTE" "END_QUOTE"
11082 "BEGIN_VERSE" "END_VERSE"
11083 "BEGIN_CENTER" "END_CENTER"
11084 "BEGIN_SRC" "END_SRC"
11085 "BEGIN_RESULT" "END_RESULT"
11086 "NAME:" "RESULTS:"
11087 "HEADER:" "HEADERS:"
11088 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11089 "CAPTION:" "LABEL:"
11090 "SETUPFILE:"
11091 "INCLUDE:"
11092 "BIND:"
11093 "MACRO:"))
11095 (defcustom org-structure-template-alist
11097 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11098 "<src lang=\"?\">\n\n</src>")
11099 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11100 "<example>\n?\n</example>")
11101 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11102 "<quote>\n?\n</quote>")
11103 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11104 "<verse>\n?\n</verse>")
11105 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11106 "<center>\n?\n</center>")
11107 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11108 "<literal style=\"latex\">\n?\n</literal>")
11109 ("L" "#+LaTeX: "
11110 "<literal style=\"latex\">?</literal>")
11111 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11112 "<literal style=\"html\">\n?\n</literal>")
11113 ("H" "#+HTML: "
11114 "<literal style=\"html\">?</literal>")
11115 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11116 ("A" "#+ASCII: ")
11117 ("i" "#+INDEX: ?"
11118 "#+INDEX: ?")
11119 ("I" "#+INCLUDE %file ?"
11120 "<include file=%file markup=\"?\">")
11122 "Structure completion elements.
11123 This is a list of abbreviation keys and values. The value gets inserted
11124 if you type `<' followed by the key and then press the completion key,
11125 usually `M-TAB'. %file will be replaced by a file name after prompting
11126 for the file using completion. The cursor will be placed at the position
11127 of the `?` in the template.
11128 There are two templates for each key, the first uses the original Org syntax,
11129 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11130 the default when the /org-mtags.el/ module has been loaded. See also the
11131 variable `org-mtags-prefer-muse-templates'."
11132 :group 'org-completion
11133 :type '(repeat
11134 (string :tag "Key")
11135 (string :tag "Template")
11136 (string :tag "Muse Template")))
11138 (defun org-try-structure-completion ()
11139 "Try to complete a structure template before point.
11140 This looks for strings like \"<e\" on an otherwise empty line and
11141 expands them."
11142 (let ((l (buffer-substring (point-at-bol) (point)))
11144 (when (and (looking-at "[ \t]*$")
11145 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11146 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11147 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11148 (match-beginning 1)) a)
11149 t)))
11151 (defun org-complete-expand-structure-template (start cell)
11152 "Expand a structure template."
11153 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11154 (rpl (nth (if musep 2 1) cell))
11155 (ind ""))
11156 (delete-region start (point))
11157 (when (string-match "\\`#\\+" rpl)
11158 (cond
11159 ((bolp))
11160 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11161 (setq ind (buffer-substring (point-at-bol) (point))))
11162 (t (newline))))
11163 (setq start (point))
11164 (if (string-match "%file" rpl)
11165 (setq rpl (replace-match
11166 (concat
11167 "\""
11168 (save-match-data
11169 (abbreviate-file-name (read-file-name "Include file: ")))
11170 "\"")
11171 t t rpl)))
11172 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11173 (concat "\n" ind)))
11174 (insert rpl)
11175 (if (re-search-backward "\\?" start t) (delete-char 1))))
11177 ;;;; TODO, DEADLINE, Comments
11179 (defun org-toggle-comment ()
11180 "Change the COMMENT state of an entry."
11181 (interactive)
11182 (save-excursion
11183 (org-back-to-heading)
11184 (let (case-fold-search)
11185 (cond
11186 ((looking-at (format org-heading-keyword-regexp-format
11187 org-comment-string))
11188 (goto-char (match-end 1))
11189 (looking-at (concat " +" org-comment-string))
11190 (replace-match "" t t)
11191 (when (eolp) (insert " ")))
11192 ((looking-at org-outline-regexp)
11193 (goto-char (match-end 0))
11194 (insert org-comment-string " "))))))
11196 (defvar org-last-todo-state-is-todo nil
11197 "This is non-nil when the last TODO state change led to a TODO state.
11198 If the last change removed the TODO tag or switched to DONE, then
11199 this is nil.")
11201 (defvar org-setting-tags nil) ; dynamically skipped
11203 (defvar org-todo-setup-filter-hook nil
11204 "Hook for functions that pre-filter todo specs.
11205 Each function takes a todo spec and returns either nil or the spec
11206 transformed into canonical form." )
11208 (defvar org-todo-get-default-hook nil
11209 "Hook for functions that get a default item for todo.
11210 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11211 nil or a string to be used for the todo mark." )
11213 (defvar org-agenda-headline-snapshot-before-repeat)
11215 (defun org-current-effective-time ()
11216 "Return current time adjusted for `org-extend-today-until' variable"
11217 (let* ((ct (org-current-time))
11218 (dct (decode-time ct))
11219 (ct1
11220 (if (and org-use-effective-time
11221 (< (nth 2 dct) org-extend-today-until))
11222 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11223 ct)))
11224 ct1))
11226 (defun org-todo-yesterday (&optional arg)
11227 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11228 (interactive "P")
11229 (if (eq major-mode 'org-agenda-mode)
11230 (apply 'org-agenda-todo-yesterday arg)
11231 (let* ((hour (third (decode-time
11232 (org-current-time))))
11233 (org-extend-today-until (1+ hour)))
11234 (org-todo arg))))
11236 (defun org-todo (&optional arg)
11237 "Change the TODO state of an item.
11238 The state of an item is given by a keyword at the start of the heading,
11239 like
11240 *** TODO Write paper
11241 *** DONE Call mom
11243 The different keywords are specified in the variable `org-todo-keywords'.
11244 By default the available states are \"TODO\" and \"DONE\".
11245 So for this example: when the item starts with TODO, it is changed to DONE.
11246 When it starts with DONE, the DONE is removed. And when neither TODO nor
11247 DONE are present, add TODO at the beginning of the heading.
11249 With \\[universal-argument] prefix arg, use completion to determine the new \
11250 state.
11251 With numeric prefix arg, switch to that state.
11252 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11253 keywords (nextset).
11254 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11255 With a numeric prefix arg of 0, inhibit note taking for the change.
11257 For calling through lisp, arg is also interpreted in the following way:
11258 'none -> empty state
11259 \"\"(empty string) -> switch to empty state
11260 'done -> switch to DONE
11261 'nextset -> switch to the next set of keywords
11262 'previousset -> switch to the previous set of keywords
11263 \"WAITING\" -> switch to the specified keyword, but only if it
11264 really is a member of `org-todo-keywords'."
11265 (interactive "P")
11266 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11267 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11268 'region-start-level 'region))
11269 org-loop-over-headlines-in-active-region)
11270 (org-map-entries
11271 `(org-todo ,arg)
11272 org-loop-over-headlines-in-active-region
11273 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11274 (if (equal arg '(16)) (setq arg 'nextset))
11275 (let ((org-blocker-hook org-blocker-hook)
11276 (case-fold-search nil))
11277 (when (equal arg '(64))
11278 (setq arg nil org-blocker-hook nil))
11279 (when (and org-blocker-hook
11280 (or org-inhibit-blocking
11281 (org-entry-get nil "NOBLOCKING")))
11282 (setq org-blocker-hook nil))
11283 (save-excursion
11284 (catch 'exit
11285 (org-back-to-heading t)
11286 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11287 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11288 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11289 (let* ((match-data (match-data))
11290 (startpos (point-at-bol))
11291 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11292 (org-log-done org-log-done)
11293 (org-log-repeat org-log-repeat)
11294 (org-todo-log-states org-todo-log-states)
11295 (org-inhibit-logging
11296 (if (equal arg 0)
11297 (progn (setq arg nil) 'note) org-inhibit-logging))
11298 (this (match-string 1))
11299 (hl-pos (match-beginning 0))
11300 (head (org-get-todo-sequence-head this))
11301 (ass (assoc head org-todo-kwd-alist))
11302 (interpret (nth 1 ass))
11303 (done-word (nth 3 ass))
11304 (final-done-word (nth 4 ass))
11305 (org-last-state (or this ""))
11306 (completion-ignore-case t)
11307 (member (member this org-todo-keywords-1))
11308 (tail (cdr member))
11309 (org-state (cond
11310 ((and org-todo-key-trigger
11311 (or (and (equal arg '(4))
11312 (eq org-use-fast-todo-selection 'prefix))
11313 (and (not arg) org-use-fast-todo-selection
11314 (not (eq org-use-fast-todo-selection
11315 'prefix)))))
11316 ;; Use fast selection
11317 (org-fast-todo-selection))
11318 ((and (equal arg '(4))
11319 (or (not org-use-fast-todo-selection)
11320 (not org-todo-key-trigger)))
11321 ;; Read a state with completion
11322 (org-icompleting-read
11323 "State: " (mapcar (lambda(x) (list x))
11324 org-todo-keywords-1)
11325 nil t))
11326 ((eq arg 'right)
11327 (if this
11328 (if tail (car tail) nil)
11329 (car org-todo-keywords-1)))
11330 ((eq arg 'left)
11331 (if (equal member org-todo-keywords-1)
11333 (if this
11334 (nth (- (length org-todo-keywords-1)
11335 (length tail) 2)
11336 org-todo-keywords-1)
11337 (org-last org-todo-keywords-1))))
11338 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11339 (setq arg nil))) ; hack to fall back to cycling
11340 (arg
11341 ;; user or caller requests a specific state
11342 (cond
11343 ((equal arg "") nil)
11344 ((eq arg 'none) nil)
11345 ((eq arg 'done) (or done-word (car org-done-keywords)))
11346 ((eq arg 'nextset)
11347 (or (car (cdr (member head org-todo-heads)))
11348 (car org-todo-heads)))
11349 ((eq arg 'previousset)
11350 (let ((org-todo-heads (reverse org-todo-heads)))
11351 (or (car (cdr (member head org-todo-heads)))
11352 (car org-todo-heads))))
11353 ((car (member arg org-todo-keywords-1)))
11354 ((stringp arg)
11355 (error "State `%s' not valid in this file" arg))
11356 ((nth (1- (prefix-numeric-value arg))
11357 org-todo-keywords-1))))
11358 ((null member) (or head (car org-todo-keywords-1)))
11359 ((equal this final-done-word) nil) ;; -> make empty
11360 ((null tail) nil) ;; -> first entry
11361 ((memq interpret '(type priority))
11362 (if (eq this-command last-command)
11363 (car tail)
11364 (if (> (length tail) 0)
11365 (or done-word (car org-done-keywords))
11366 nil)))
11368 (car tail))))
11369 (org-state (or
11370 (run-hook-with-args-until-success
11371 'org-todo-get-default-hook org-state org-last-state)
11372 org-state))
11373 (next (if org-state (concat " " org-state " ") " "))
11374 (change-plist (list :type 'todo-state-change :from this :to org-state
11375 :position startpos))
11376 dolog now-done-p)
11377 (when org-blocker-hook
11378 (setq org-last-todo-state-is-todo
11379 (not (member this org-done-keywords)))
11380 (unless (save-excursion
11381 (save-match-data
11382 (org-with-wide-buffer
11383 (run-hook-with-args-until-failure
11384 'org-blocker-hook change-plist))))
11385 (if (org-called-interactively-p 'interactive)
11386 (error "TODO state change from %s to %s blocked" this org-state)
11387 ;; fail silently
11388 (message "TODO state change from %s to %s blocked" this org-state)
11389 (throw 'exit nil))))
11390 (store-match-data match-data)
11391 (replace-match next t t)
11392 (unless (pos-visible-in-window-p hl-pos)
11393 (message "TODO state changed to %s" (org-trim next)))
11394 (unless head
11395 (setq head (org-get-todo-sequence-head org-state)
11396 ass (assoc head org-todo-kwd-alist)
11397 interpret (nth 1 ass)
11398 done-word (nth 3 ass)
11399 final-done-word (nth 4 ass)))
11400 (when (memq arg '(nextset previousset))
11401 (message "Keyword-Set %d/%d: %s"
11402 (- (length org-todo-sets) -1
11403 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11404 (length org-todo-sets)
11405 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11406 (setq org-last-todo-state-is-todo
11407 (not (member org-state org-done-keywords)))
11408 (setq now-done-p (and (member org-state org-done-keywords)
11409 (not (member this org-done-keywords))))
11410 (and logging (org-local-logging logging))
11411 (when (and (or org-todo-log-states org-log-done)
11412 (not (eq org-inhibit-logging t))
11413 (not (memq arg '(nextset previousset))))
11414 ;; we need to look at recording a time and note
11415 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11416 (nth 2 (assoc this org-todo-log-states))))
11417 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11418 (setq dolog 'time))
11419 (when (and org-state
11420 (member org-state org-not-done-keywords)
11421 (not (member this org-not-done-keywords)))
11422 ;; This is now a todo state and was not one before
11423 ;; If there was a CLOSED time stamp, get rid of it.
11424 (org-add-planning-info nil nil 'closed))
11425 (when (and now-done-p org-log-done)
11426 ;; It is now done, and it was not done before
11427 (org-add-planning-info 'closed (org-current-effective-time))
11428 (if (and (not dolog) (eq 'note org-log-done))
11429 (org-add-log-setup 'done org-state this 'findpos 'note)))
11430 (when (and org-state dolog)
11431 ;; This is a non-nil state, and we need to log it
11432 (org-add-log-setup 'state org-state this 'findpos dolog)))
11433 ;; Fixup tag positioning
11434 (org-todo-trigger-tag-changes org-state)
11435 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11436 (when org-provide-todo-statistics
11437 (org-update-parent-todo-statistics))
11438 (run-hooks 'org-after-todo-state-change-hook)
11439 (if (and arg (not (member org-state org-done-keywords)))
11440 (setq head (org-get-todo-sequence-head org-state)))
11441 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11442 ;; Do we need to trigger a repeat?
11443 (when now-done-p
11444 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11445 ;; This is for the agenda, take a snapshot of the headline.
11446 (save-match-data
11447 (setq org-agenda-headline-snapshot-before-repeat
11448 (org-get-heading))))
11449 (org-auto-repeat-maybe org-state))
11450 ;; Fixup cursor location if close to the keyword
11451 (if (and (outline-on-heading-p)
11452 (not (bolp))
11453 (save-excursion (beginning-of-line 1)
11454 (looking-at org-todo-line-regexp))
11455 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11456 (progn
11457 (goto-char (or (match-end 2) (match-end 1)))
11458 (and (looking-at " ") (just-one-space))))
11459 (when org-trigger-hook
11460 (save-excursion
11461 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11463 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11464 "Block turning an entry into a TODO, using the hierarchy.
11465 This checks whether the current task should be blocked from state
11466 changes. Such blocking occurs when:
11468 1. The task has children which are not all in a completed state.
11470 2. A task has a parent with the property :ORDERED:, and there
11471 are siblings prior to the current task with incomplete
11472 status.
11474 3. The parent of the task is blocked because it has siblings that should
11475 be done first, or is child of a block grandparent TODO entry."
11477 (if (not org-enforce-todo-dependencies)
11478 t ; if locally turned off don't block
11479 (catch 'dont-block
11480 ;; If this is not a todo state change, or if this entry is already DONE,
11481 ;; do not block
11482 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11483 (member (plist-get change-plist :from)
11484 (cons 'done org-done-keywords))
11485 (member (plist-get change-plist :to)
11486 (cons 'todo org-not-done-keywords))
11487 (not (plist-get change-plist :to)))
11488 (throw 'dont-block t))
11489 ;; If this task has children, and any are undone, it's blocked
11490 (save-excursion
11491 (org-back-to-heading t)
11492 (let ((this-level (funcall outline-level)))
11493 (outline-next-heading)
11494 (let ((child-level (funcall outline-level)))
11495 (while (and (not (eobp))
11496 (> child-level this-level))
11497 ;; this todo has children, check whether they are all
11498 ;; completed
11499 (if (and (not (org-entry-is-done-p))
11500 (org-entry-is-todo-p))
11501 (throw 'dont-block nil))
11502 (outline-next-heading)
11503 (setq child-level (funcall outline-level))))))
11504 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11505 ;; any previous siblings are undone, it's blocked
11506 (save-excursion
11507 (org-back-to-heading t)
11508 (let* ((pos (point))
11509 (parent-pos (and (org-up-heading-safe) (point))))
11510 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11511 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11512 (forward-line 1)
11513 (re-search-forward org-not-done-heading-regexp pos t))
11514 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11515 ;; Search further up the hierarchy, to see if an ancestor is blocked
11516 (while t
11517 (goto-char parent-pos)
11518 (if (not (looking-at org-not-done-heading-regexp))
11519 (throw 'dont-block t)) ; do not block, parent is not a TODO
11520 (setq pos (point))
11521 (setq parent-pos (and (org-up-heading-safe) (point)))
11522 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11523 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11524 (forward-line 1)
11525 (re-search-forward org-not-done-heading-regexp pos t))
11526 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11528 (defcustom org-track-ordered-property-with-tag nil
11529 "Should the ORDERED property also be shown as a tag?
11530 The ORDERED property decides if an entry should require subtasks to be
11531 completed in sequence. Since a property is not very visible, setting
11532 this option means that toggling the ORDERED property with the command
11533 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11534 not relevant for the behavior, but it makes things more visible.
11536 Note that toggling the tag with tags commands will not change the property
11537 and therefore not influence behavior!
11539 This can be t, meaning the tag ORDERED should be used, It can also be a
11540 string to select a different tag for this task."
11541 :group 'org-todo
11542 :type '(choice
11543 (const :tag "No tracking" nil)
11544 (const :tag "Track with ORDERED tag" t)
11545 (string :tag "Use other tag")))
11547 (defun org-toggle-ordered-property ()
11548 "Toggle the ORDERED property of the current entry.
11549 For better visibility, you can track the value of this property with a tag.
11550 See variable `org-track-ordered-property-with-tag'."
11551 (interactive)
11552 (let* ((t1 org-track-ordered-property-with-tag)
11553 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11554 (save-excursion
11555 (org-back-to-heading)
11556 (if (org-entry-get nil "ORDERED")
11557 (progn
11558 (org-delete-property "ORDERED")
11559 (and tag (org-toggle-tag tag 'off))
11560 (message "Subtasks can be completed in arbitrary order"))
11561 (org-entry-put nil "ORDERED" "t")
11562 (and tag (org-toggle-tag tag 'on))
11563 (message "Subtasks must be completed in sequence")))))
11565 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11566 (defun org-block-todo-from-checkboxes (change-plist)
11567 "Block turning an entry into a TODO, using checkboxes.
11568 This checks whether the current task should be blocked from state
11569 changes because there are unchecked boxes in this entry."
11570 (if (not org-enforce-todo-checkbox-dependencies)
11571 t ; if locally turned off don't block
11572 (catch 'dont-block
11573 ;; If this is not a todo state change, or if this entry is already DONE,
11574 ;; do not block
11575 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11576 (member (plist-get change-plist :from)
11577 (cons 'done org-done-keywords))
11578 (member (plist-get change-plist :to)
11579 (cons 'todo org-not-done-keywords))
11580 (not (plist-get change-plist :to)))
11581 (throw 'dont-block t))
11582 ;; If this task has checkboxes that are not checked, it's blocked
11583 (save-excursion
11584 (org-back-to-heading t)
11585 (let ((beg (point)) end)
11586 (outline-next-heading)
11587 (setq end (point))
11588 (goto-char beg)
11589 (if (org-list-search-forward
11590 (concat (org-item-beginning-re)
11591 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11592 "\\[[- ]\\]")
11593 end t)
11594 (progn
11595 (if (boundp 'org-blocked-by-checkboxes)
11596 (setq org-blocked-by-checkboxes t))
11597 (throw 'dont-block nil)))))
11598 t))) ; do not block
11600 (defun org-entry-blocked-p ()
11601 "Is the current entry blocked?"
11602 (if (org-entry-get nil "NOBLOCKING")
11603 nil ;; Never block this entry
11604 (not
11605 (run-hook-with-args-until-failure
11606 'org-blocker-hook
11607 (list :type 'todo-state-change
11608 :position (point)
11609 :from 'todo
11610 :to 'done)))))
11612 (defun org-update-statistics-cookies (all)
11613 "Update the statistics cookie, either from TODO or from checkboxes.
11614 This should be called with the cursor in a line with a statistics cookie."
11615 (interactive "P")
11616 (if all
11617 (progn
11618 (org-update-checkbox-count 'all)
11619 (org-map-entries 'org-update-parent-todo-statistics))
11620 (if (not (org-at-heading-p))
11621 (org-update-checkbox-count)
11622 (let ((pos (move-marker (make-marker) (point)))
11623 end l1 l2)
11624 (ignore-errors (org-back-to-heading t))
11625 (if (not (org-at-heading-p))
11626 (org-update-checkbox-count)
11627 (setq l1 (org-outline-level))
11628 (setq end (save-excursion
11629 (outline-next-heading)
11630 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11631 (point)))
11632 (if (and (save-excursion
11633 (re-search-forward
11634 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11635 (not (save-excursion (re-search-forward
11636 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11637 (org-update-checkbox-count)
11638 (if (and l2 (> l2 l1))
11639 (progn
11640 (goto-char end)
11641 (org-update-parent-todo-statistics))
11642 (goto-char pos)
11643 (beginning-of-line 1)
11644 (while (re-search-forward
11645 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11646 (point-at-eol) t)
11647 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11648 (goto-char pos)
11649 (move-marker pos nil)))))
11651 (defvar org-entry-property-inherited-from) ;; defined below
11652 (defun org-update-parent-todo-statistics ()
11653 "Update any statistics cookie in the parent of the current headline.
11654 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11655 the entire subtree and this will travel up the hierarchy and update
11656 statistics everywhere."
11657 (let* ((prop (save-excursion (org-up-heading-safe)
11658 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11659 (recursive (or (not org-hierarchical-todo-statistics)
11660 (and prop (string-match "\\<recursive\\>" prop))))
11661 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11663 (first t)
11664 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11665 level ltoggle l1 new ndel
11666 (cnt-all 0) (cnt-done 0) is-percent kwd
11667 checkbox-beg ov ovs ove cookie-present)
11668 (catch 'exit
11669 (save-excursion
11670 (beginning-of-line 1)
11671 (setq ltoggle (funcall outline-level))
11672 ;; Three situations are to consider:
11674 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11675 ;; to the top-level ancestor on the headline;
11677 ;; 2. If parent has "recursive" property, repeat up to the
11678 ;; headline setting that property, taking inheritance into
11679 ;; account;
11681 ;; 3. Else, move up to direct parent and proceed only once.
11682 (while (and (setq level (org-up-heading-safe))
11683 (or recursive first)
11684 (>= (point) lim))
11685 (setq first nil cookie-present nil)
11686 (unless (and level
11687 (not (string-match
11688 "\\<checkbox\\>"
11689 (downcase (or (org-entry-get nil "COOKIE_DATA")
11690 "")))))
11691 (throw 'exit nil))
11692 (while (re-search-forward box-re (point-at-eol) t)
11693 (setq cnt-all 0 cnt-done 0 cookie-present t)
11694 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11695 (save-match-data
11696 (unless (outline-next-heading) (throw 'exit nil))
11697 (while (and (looking-at org-complex-heading-regexp)
11698 (> (setq l1 (length (match-string 1))) level))
11699 (setq kwd (and (or recursive (= l1 ltoggle))
11700 (match-string 2)))
11701 (if (or (eq org-provide-todo-statistics 'all-headlines)
11702 (and (listp org-provide-todo-statistics)
11703 (or (member kwd org-provide-todo-statistics)
11704 (member kwd org-done-keywords))))
11705 (setq cnt-all (1+ cnt-all))
11706 (if (eq org-provide-todo-statistics t)
11707 (and kwd (setq cnt-all (1+ cnt-all)))))
11708 (and (member kwd org-done-keywords)
11709 (setq cnt-done (1+ cnt-done)))
11710 (outline-next-heading)))
11711 (setq new
11712 (if is-percent
11713 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11714 (format "[%d/%d]" cnt-done cnt-all))
11715 ndel (- (match-end 0) checkbox-beg))
11716 ;; handle overlays when updating cookie from column view
11717 (when (setq ov (car (overlays-at checkbox-beg)))
11718 (setq ovs (overlay-start ov) ove (overlay-end ov))
11719 (delete-overlay ov))
11720 (goto-char checkbox-beg)
11721 (insert new)
11722 (delete-region (point) (+ (point) ndel))
11723 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11724 (when ov (move-overlay ov ovs ove)))
11725 (when cookie-present
11726 (run-hook-with-args 'org-after-todo-statistics-hook
11727 cnt-done (- cnt-all cnt-done))))))
11728 (run-hooks 'org-todo-statistics-hook)))
11730 (defvar org-after-todo-statistics-hook nil
11731 "Hook that is called after a TODO statistics cookie has been updated.
11732 Each function is called with two arguments: the number of not-done entries
11733 and the number of done entries.
11735 For example, the following function, when added to this hook, will switch
11736 an entry to DONE when all children are done, and back to TODO when new
11737 entries are set to a TODO status. Note that this hook is only called
11738 when there is a statistics cookie in the headline!
11740 (defun org-summary-todo (n-done n-not-done)
11741 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11742 (let (org-log-done org-log-states) ; turn off logging
11743 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11746 (defvar org-todo-statistics-hook nil
11747 "Hook that is run whenever Org thinks TODO statistics should be updated.
11748 This hook runs even if there is no statistics cookie present, in which case
11749 `org-after-todo-statistics-hook' would not run.")
11751 (defun org-todo-trigger-tag-changes (state)
11752 "Apply the changes defined in `org-todo-state-tags-triggers'."
11753 (let ((l org-todo-state-tags-triggers)
11754 changes)
11755 (when (or (not state) (equal state ""))
11756 (setq changes (append changes (cdr (assoc "" l)))))
11757 (when (and (stringp state) (> (length state) 0))
11758 (setq changes (append changes (cdr (assoc state l)))))
11759 (when (member state org-not-done-keywords)
11760 (setq changes (append changes (cdr (assoc 'todo l)))))
11761 (when (member state org-done-keywords)
11762 (setq changes (append changes (cdr (assoc 'done l)))))
11763 (dolist (c changes)
11764 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11766 (defun org-local-logging (value)
11767 "Get logging settings from a property VALUE."
11768 (let* (words w a)
11769 ;; directly set the variables, they are already local.
11770 (setq org-log-done nil
11771 org-log-repeat nil
11772 org-todo-log-states nil)
11773 (setq words (org-split-string value))
11774 (while (setq w (pop words))
11775 (cond
11776 ((setq a (assoc w org-startup-options))
11777 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11778 (set (nth 1 a) (nth 2 a))))
11779 ((setq a (org-extract-log-state-settings w))
11780 (and (member (car a) org-todo-keywords-1)
11781 (push a org-todo-log-states)))))))
11783 (defun org-get-todo-sequence-head (kwd)
11784 "Return the head of the TODO sequence to which KWD belongs.
11785 If KWD is not set, check if there is a text property remembering the
11786 right sequence."
11787 (let (p)
11788 (cond
11789 ((not kwd)
11790 (or (get-text-property (point-at-bol) 'org-todo-head)
11791 (progn
11792 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11793 nil (point-at-eol)))
11794 (get-text-property p 'org-todo-head))))
11795 ((not (member kwd org-todo-keywords-1))
11796 (car org-todo-keywords-1))
11797 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11799 (defun org-fast-todo-selection ()
11800 "Fast TODO keyword selection with single keys.
11801 Returns the new TODO keyword, or nil if no state change should occur."
11802 (let* ((fulltable org-todo-key-alist)
11803 (done-keywords org-done-keywords) ;; needed for the faces.
11804 (maxlen (apply 'max (mapcar
11805 (lambda (x)
11806 (if (stringp (car x)) (string-width (car x)) 0))
11807 fulltable)))
11808 (expert nil)
11809 (fwidth (+ maxlen 3 1 3))
11810 (ncol (/ (- (window-width) 4) fwidth))
11811 tg cnt e c tbl
11812 groups ingroup)
11813 (save-excursion
11814 (save-window-excursion
11815 (if expert
11816 (set-buffer (get-buffer-create " *Org todo*"))
11817 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11818 (erase-buffer)
11819 (org-set-local 'org-done-keywords done-keywords)
11820 (setq tbl fulltable cnt 0)
11821 (while (setq e (pop tbl))
11822 (cond
11823 ((equal e '(:startgroup))
11824 (push '() groups) (setq ingroup t)
11825 (when (not (= cnt 0))
11826 (setq cnt 0)
11827 (insert "\n"))
11828 (insert "{ "))
11829 ((equal e '(:endgroup))
11830 (setq ingroup nil cnt 0)
11831 (insert "}\n"))
11832 ((equal e '(:newline))
11833 (when (not (= cnt 0))
11834 (setq cnt 0)
11835 (insert "\n")
11836 (setq e (car tbl))
11837 (while (equal (car tbl) '(:newline))
11838 (insert "\n")
11839 (setq tbl (cdr tbl)))))
11841 (setq tg (car e) c (cdr e))
11842 (if ingroup (push tg (car groups)))
11843 (setq tg (org-add-props tg nil 'face
11844 (org-get-todo-face tg)))
11845 (if (and (= cnt 0) (not ingroup)) (insert " "))
11846 (insert "[" c "] " tg (make-string
11847 (- fwidth 4 (length tg)) ?\ ))
11848 (when (= (setq cnt (1+ cnt)) ncol)
11849 (insert "\n")
11850 (if ingroup (insert " "))
11851 (setq cnt 0)))))
11852 (insert "\n")
11853 (goto-char (point-min))
11854 (if (not expert) (org-fit-window-to-buffer))
11855 (message "[a-z..]:Set [SPC]:clear")
11856 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11857 (cond
11858 ((or (= c ?\C-g)
11859 (and (= c ?q) (not (rassoc c fulltable))))
11860 (setq quit-flag t))
11861 ((= c ?\ ) nil)
11862 ((setq e (rassoc c fulltable) tg (car e))
11864 (t (setq quit-flag t)))))))
11866 (defun org-entry-is-todo-p ()
11867 (member (org-get-todo-state) org-not-done-keywords))
11869 (defun org-entry-is-done-p ()
11870 (member (org-get-todo-state) org-done-keywords))
11872 (defun org-get-todo-state ()
11873 (save-excursion
11874 (org-back-to-heading t)
11875 (and (looking-at org-todo-line-regexp)
11876 (match-end 2)
11877 (match-string 2))))
11879 (defun org-at-date-range-p (&optional inactive-ok)
11880 "Is the cursor inside a date range?"
11881 (interactive)
11882 (save-excursion
11883 (catch 'exit
11884 (let ((pos (point)))
11885 (skip-chars-backward "^[<\r\n")
11886 (skip-chars-backward "<[")
11887 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11888 (>= (match-end 0) pos)
11889 (throw 'exit t))
11890 (skip-chars-backward "^<[\r\n")
11891 (skip-chars-backward "<[")
11892 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11893 (>= (match-end 0) pos)
11894 (throw 'exit t)))
11895 nil)))
11897 (defun org-get-repeat (&optional tagline)
11898 "Check if there is a deadline/schedule with repeater in this entry."
11899 (save-match-data
11900 (save-excursion
11901 (org-back-to-heading t)
11902 (and (re-search-forward (if tagline
11903 (concat tagline "\\s-*" org-repeat-re)
11904 org-repeat-re)
11905 (org-entry-end-position) t)
11906 (match-string-no-properties 1)))))
11908 (defvar org-last-changed-timestamp)
11909 (defvar org-last-inserted-timestamp)
11910 (defvar org-log-post-message)
11911 (defvar org-log-note-purpose)
11912 (defvar org-log-note-how)
11913 (defvar org-log-note-extra)
11914 (defun org-auto-repeat-maybe (done-word)
11915 "Check if the current headline contains a repeated deadline/schedule.
11916 If yes, set TODO state back to what it was and change the base date
11917 of repeating deadline/scheduled time stamps to new date.
11918 This function is run automatically after each state change to a DONE state."
11919 ;; last-state is dynamically scoped into this function
11920 (let* ((repeat (org-get-repeat))
11921 (aa (assoc org-last-state org-todo-kwd-alist))
11922 (interpret (nth 1 aa))
11923 (head (nth 2 aa))
11924 (whata '(("d" . day) ("m" . month) ("y" . year)))
11925 (msg "Entry repeats: ")
11926 (org-log-done nil)
11927 (org-todo-log-states nil)
11928 re type n what ts time to-state)
11929 (when repeat
11930 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11931 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11932 org-todo-repeat-to-state))
11933 (unless (and to-state (member to-state org-todo-keywords-1))
11934 (setq to-state (if (eq interpret 'type) org-last-state head)))
11935 (org-todo to-state)
11936 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11937 (org-entry-put nil "LAST_REPEAT" (format-time-string
11938 (org-time-stamp-format t t))))
11939 (when org-log-repeat
11940 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11941 (memq 'org-add-log-note post-command-hook))
11942 ;; OK, we are already setup for some record
11943 (if (eq org-log-repeat 'note)
11944 ;; make sure we take a note, not only a time stamp
11945 (setq org-log-note-how 'note))
11946 ;; Set up for taking a record
11947 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11948 org-last-state
11949 'findpos org-log-repeat)))
11950 (org-back-to-heading t)
11951 (org-add-planning-info nil nil 'closed)
11952 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11953 org-deadline-time-regexp "\\)\\|\\("
11954 org-ts-regexp "\\)"))
11955 (while (re-search-forward
11956 re (save-excursion (outline-next-heading) (point)) t)
11957 (setq type (if (match-end 1) org-scheduled-string
11958 (if (match-end 3) org-deadline-string "Plain:"))
11959 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11960 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11961 (setq n (string-to-number (match-string 2 ts))
11962 what (match-string 3 ts))
11963 (if (equal what "w") (setq n (* n 7) what "d"))
11964 ;; Preparation, see if we need to modify the start date for the change
11965 (when (match-end 1)
11966 (setq time (save-match-data (org-time-string-to-time ts)))
11967 (cond
11968 ((equal (match-string 1 ts) ".")
11969 ;; Shift starting date to today
11970 (org-timestamp-change
11971 (- (org-today) (time-to-days time))
11972 'day))
11973 ((equal (match-string 1 ts) "+")
11974 (let ((nshiftmax 10) (nshift 0))
11975 (while (or (= nshift 0)
11976 (<= (time-to-days time)
11977 (time-to-days (current-time))))
11978 (when (= (incf nshift) nshiftmax)
11979 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11980 (error "Abort")))
11981 (org-timestamp-change n (cdr (assoc what whata)))
11982 (org-at-timestamp-p t)
11983 (setq ts (match-string 1))
11984 (setq time (save-match-data (org-time-string-to-time ts)))))
11985 (org-timestamp-change (- n) (cdr (assoc what whata)))
11986 ;; rematch, so that we have everything in place for the real shift
11987 (org-at-timestamp-p t)
11988 (setq ts (match-string 1))
11989 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11990 (org-timestamp-change n (cdr (assoc what whata)))
11991 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11992 (setq org-log-post-message msg)
11993 (message "%s" msg))))
11995 (defun org-show-todo-tree (arg)
11996 "Make a compact tree which shows all headlines marked with TODO.
11997 The tree will show the lines where the regexp matches, and all higher
11998 headlines above the match.
11999 With a \\[universal-argument] prefix, prompt for a regexp to match.
12000 With a numeric prefix N, construct a sparse tree for the Nth element
12001 of `org-todo-keywords-1'."
12002 (interactive "P")
12003 (let ((case-fold-search nil)
12004 (kwd-re
12005 (cond ((null arg) org-not-done-regexp)
12006 ((equal arg '(4))
12007 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12008 (mapcar 'list org-todo-keywords-1))))
12009 (concat "\\("
12010 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12011 "\\)\\>")))
12012 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12013 (regexp-quote (nth (1- (prefix-numeric-value arg))
12014 org-todo-keywords-1)))
12015 (t (error "Invalid prefix argument: %s" arg)))))
12016 (message "%d TODO entries found"
12017 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12019 (defun org-deadline (&optional remove time)
12020 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12021 With argument REMOVE, remove any deadline from the item.
12022 With argument TIME, set the deadline at the corresponding date. TIME
12023 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12024 (interactive "P")
12025 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12026 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12027 'region-start-level 'region))
12028 org-loop-over-headlines-in-active-region)
12029 (org-map-entries
12030 `(org-deadline ',remove ,time)
12031 org-loop-over-headlines-in-active-region
12032 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12033 (let* ((old-date (org-entry-get nil "DEADLINE"))
12034 (repeater (and old-date
12035 (string-match
12036 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12037 old-date)
12038 (match-string 1 old-date))))
12039 (if remove
12040 (progn
12041 (when (and old-date org-log-redeadline)
12042 (org-add-log-setup 'deldeadline nil old-date 'findpos
12043 org-log-redeadline))
12044 (org-remove-timestamp-with-keyword org-deadline-string)
12045 (message "Item no longer has a deadline."))
12046 (org-add-planning-info 'deadline time 'closed)
12047 (when (and old-date org-log-redeadline
12048 (not (equal old-date
12049 (substring org-last-inserted-timestamp 1 -1))))
12050 (org-add-log-setup 'redeadline nil old-date 'findpos
12051 org-log-redeadline))
12052 (when repeater
12053 (save-excursion
12054 (org-back-to-heading t)
12055 (when (re-search-forward (concat org-deadline-string " "
12056 org-last-inserted-timestamp)
12057 (save-excursion
12058 (outline-next-heading) (point)) t)
12059 (goto-char (1- (match-end 0)))
12060 (insert " " repeater)
12061 (setq org-last-inserted-timestamp
12062 (concat (substring org-last-inserted-timestamp 0 -1)
12063 " " repeater
12064 (substring org-last-inserted-timestamp -1))))))
12065 (message "Deadline on %s" org-last-inserted-timestamp)))))
12067 (defun org-schedule (&optional remove time)
12068 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12069 With argument REMOVE, remove any scheduling date from the item.
12070 With argument TIME, scheduled at the corresponding date. TIME can
12071 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12072 (interactive "P")
12073 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12074 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12075 'region-start-level 'region))
12076 org-loop-over-headlines-in-active-region)
12077 (org-map-entries
12078 `(org-schedule ',remove ,time)
12079 org-loop-over-headlines-in-active-region
12080 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12081 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12082 (repeater (and old-date
12083 (string-match
12084 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12085 old-date)
12086 (match-string 1 old-date))))
12087 (if remove
12088 (progn
12089 (when (and old-date org-log-reschedule)
12090 (org-add-log-setup 'delschedule nil old-date 'findpos
12091 org-log-reschedule))
12092 (org-remove-timestamp-with-keyword org-scheduled-string)
12093 (message "Item is no longer scheduled."))
12094 (org-add-planning-info 'scheduled time 'closed)
12095 (when (and old-date org-log-reschedule
12096 (not (equal old-date
12097 (substring org-last-inserted-timestamp 1 -1))))
12098 (org-add-log-setup 'reschedule nil old-date 'findpos
12099 org-log-reschedule))
12100 (when repeater
12101 (save-excursion
12102 (org-back-to-heading t)
12103 (when (re-search-forward (concat org-scheduled-string " "
12104 org-last-inserted-timestamp)
12105 (save-excursion
12106 (outline-next-heading) (point)) t)
12107 (goto-char (1- (match-end 0)))
12108 (insert " " repeater)
12109 (setq org-last-inserted-timestamp
12110 (concat (substring org-last-inserted-timestamp 0 -1)
12111 " " repeater
12112 (substring org-last-inserted-timestamp -1))))))
12113 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12115 (defun org-get-scheduled-time (pom &optional inherit)
12116 "Get the scheduled time as a time tuple, of a format suitable
12117 for calling org-schedule with, or if there is no scheduling,
12118 returns nil."
12119 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12120 (when time
12121 (apply 'encode-time (org-parse-time-string time)))))
12123 (defun org-get-deadline-time (pom &optional inherit)
12124 "Get the deadline as a time tuple, of a format suitable for
12125 calling org-deadline with, or if there is no scheduling, returns
12126 nil."
12127 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12128 (when time
12129 (apply 'encode-time (org-parse-time-string time)))))
12131 (defun org-remove-timestamp-with-keyword (keyword)
12132 "Remove all time stamps with KEYWORD in the current entry."
12133 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12134 beg)
12135 (save-excursion
12136 (org-back-to-heading t)
12137 (setq beg (point))
12138 (outline-next-heading)
12139 (while (re-search-backward re beg t)
12140 (replace-match "")
12141 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12142 (equal (char-before) ?\ ))
12143 (backward-delete-char 1)
12144 (if (string-match "^[ \t]*$" (buffer-substring
12145 (point-at-bol) (point-at-eol)))
12146 (delete-region (point-at-bol)
12147 (min (point-max) (1+ (point-at-eol))))))))))
12149 (defun org-add-planning-info (what &optional time &rest remove)
12150 "Insert new timestamp with keyword in the line directly after the headline.
12151 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12152 If non is given, the user is prompted for a date.
12153 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12154 be removed."
12155 (interactive)
12156 (let (org-time-was-given org-end-time-was-given ts
12157 end default-time default-input)
12159 (catch 'exit
12160 (when (and (memq what '(scheduled deadline))
12161 (or (not time)
12162 (and (stringp time)
12163 (string-match "^[-+]+[0-9]" time))))
12164 ;; Try to get a default date/time from existing timestamp
12165 (save-excursion
12166 (org-back-to-heading t)
12167 (setq end (save-excursion (outline-next-heading) (point)))
12168 (when (re-search-forward (if (eq what 'scheduled)
12169 org-scheduled-time-regexp
12170 org-deadline-time-regexp)
12171 end t)
12172 (setq ts (match-string 1)
12173 default-time
12174 (apply 'encode-time (org-parse-time-string ts))
12175 default-input (and ts (org-get-compact-tod ts))))))
12176 (when what
12177 (setq time
12178 (if (stringp time)
12179 ;; This is a string (relative or absolute), set proper date
12180 (apply 'encode-time
12181 (org-read-date-analyze
12182 time default-time (decode-time default-time)))
12183 ;; If necessary, get the time from the user
12184 (or time (org-read-date nil 'to-time nil nil
12185 default-time default-input)))))
12187 (when (and org-insert-labeled-timestamps-at-point
12188 (member what '(scheduled deadline)))
12189 (insert
12190 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12191 (org-insert-time-stamp time org-time-was-given
12192 nil nil nil (list org-end-time-was-given))
12193 (setq what nil))
12194 (save-excursion
12195 (save-restriction
12196 (let (col list elt ts buffer-invisibility-spec)
12197 (org-back-to-heading t)
12198 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12199 (goto-char (match-end 1))
12200 (setq col (current-column))
12201 (goto-char (match-end 0))
12202 (if (eobp) (insert "\n") (forward-char 1))
12203 (when (and (not what)
12204 (not (looking-at
12205 (concat "[ \t]*"
12206 org-keyword-time-not-clock-regexp))))
12207 ;; Nothing to add, nothing to remove...... :-)
12208 (throw 'exit nil))
12209 (if (and (not (looking-at org-outline-regexp))
12210 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12211 "[^\r\n]*"))
12212 (not (equal (match-string 1) org-clock-string)))
12213 (narrow-to-region (match-beginning 0) (match-end 0))
12214 (insert-before-markers "\n")
12215 (backward-char 1)
12216 (narrow-to-region (point) (point))
12217 (and org-adapt-indentation (org-indent-to-column col)))
12218 ;; Check if we have to remove something.
12219 (setq list (cons what remove))
12220 (while list
12221 (setq elt (pop list))
12222 (when (or (and (eq elt 'scheduled)
12223 (re-search-forward org-scheduled-time-regexp nil t))
12224 (and (eq elt 'deadline)
12225 (re-search-forward org-deadline-time-regexp nil t))
12226 (and (eq elt 'closed)
12227 (re-search-forward org-closed-time-regexp nil t)))
12228 (replace-match "")
12229 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12230 (and (looking-at "[ \t]+") (replace-match ""))
12231 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12232 (when what
12233 (insert
12234 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12235 (cond ((eq what 'scheduled) org-scheduled-string)
12236 ((eq what 'deadline) org-deadline-string)
12237 ((eq what 'closed) org-closed-string))
12238 " ")
12239 (setq ts (org-insert-time-stamp
12240 time
12241 (or org-time-was-given
12242 (and (eq what 'closed) org-log-done-with-time))
12243 (eq what 'closed)
12244 nil nil (list org-end-time-was-given)))
12245 (insert
12246 (if (not (or (bolp) (eq (char-before) ?\ )
12247 (memq (char-after) '(32 10))
12248 (eobp))) " " ""))
12249 (end-of-line 1))
12250 (goto-char (point-min))
12251 (widen)
12252 (if (and (looking-at "[ \t]*\n")
12253 (equal (char-before) ?\n))
12254 (delete-region (1- (point)) (point-at-eol)))
12255 ts))))))
12257 (defvar org-log-note-marker (make-marker))
12258 (defvar org-log-note-purpose nil)
12259 (defvar org-log-note-state nil)
12260 (defvar org-log-note-previous-state nil)
12261 (defvar org-log-note-how nil)
12262 (defvar org-log-note-extra nil)
12263 (defvar org-log-note-window-configuration nil)
12264 (defvar org-log-note-return-to (make-marker))
12265 (defvar org-log-note-effective-time nil
12266 "Remembered current time so that dynamically scoped
12267 `org-extend-today-until' affects tha timestamps in state change
12268 log")
12270 (defvar org-log-post-message nil
12271 "Message to be displayed after a log note has been stored.
12272 The auto-repeater uses this.")
12274 (defun org-add-note ()
12275 "Add a note to the current entry.
12276 This is done in the same way as adding a state change note."
12277 (interactive)
12278 (org-add-log-setup 'note nil nil 'findpos nil))
12280 (defvar org-property-end-re)
12281 (defun org-add-log-setup (&optional purpose state prev-state
12282 findpos how extra)
12283 "Set up the post command hook to take a note.
12284 If this is about to TODO state change, the new state is expected in STATE.
12285 When FINDPOS is non-nil, find the correct position for the note in
12286 the current entry. If not, assume that it can be inserted at point.
12287 HOW is an indicator what kind of note should be created.
12288 EXTRA is additional text that will be inserted into the notes buffer."
12289 (let* ((org-log-into-drawer (org-log-into-drawer))
12290 (drawer (cond ((stringp org-log-into-drawer)
12291 org-log-into-drawer)
12292 (org-log-into-drawer "LOGBOOK")
12293 (t nil))))
12294 (save-restriction
12295 (save-excursion
12296 (when findpos
12297 (org-back-to-heading t)
12298 (narrow-to-region (point) (save-excursion
12299 (outline-next-heading) (point)))
12300 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12301 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12302 "[^\r\n]*\\)?"))
12303 (goto-char (match-end 0))
12304 (cond
12305 (drawer
12306 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12307 nil t)
12308 (progn
12309 (goto-char (match-end 0))
12310 (or org-log-states-order-reversed
12311 (and (re-search-forward org-property-end-re nil t)
12312 (goto-char (1- (match-beginning 0))))))
12313 (insert "\n:" drawer ":\n:END:")
12314 (beginning-of-line 0)
12315 (org-indent-line-function)
12316 (beginning-of-line 2)
12317 (org-indent-line-function)
12318 (end-of-line 0)))
12319 ((and org-log-state-notes-insert-after-drawers
12320 (save-excursion
12321 (forward-line) (looking-at org-drawer-regexp)))
12322 (forward-line)
12323 (while (looking-at org-drawer-regexp)
12324 (goto-char (match-end 0))
12325 (re-search-forward org-property-end-re (point-max) t)
12326 (forward-line))
12327 (forward-line -1)))
12328 (unless org-log-states-order-reversed
12329 (and (= (char-after) ?\n) (forward-char 1))
12330 (org-skip-over-state-notes)
12331 (skip-chars-backward " \t\n\r")))
12332 (move-marker org-log-note-marker (point))
12333 (setq org-log-note-purpose purpose
12334 org-log-note-state state
12335 org-log-note-previous-state prev-state
12336 org-log-note-how how
12337 org-log-note-extra extra
12338 org-log-note-effective-time (org-current-effective-time))
12339 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12341 (defun org-skip-over-state-notes ()
12342 "Skip past the list of State notes in an entry."
12343 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12344 (when (ignore-errors (goto-char (org-in-item-p)))
12345 (let* ((struct (org-list-struct))
12346 (prevs (org-list-prevs-alist struct)))
12347 (while (looking-at "[ \t]*- State")
12348 (goto-char (or (org-list-get-next-item (point) struct prevs)
12349 (org-list-get-item-end (point) struct)))))))
12351 (defun org-add-log-note (&optional purpose)
12352 "Pop up a window for taking a note, and add this note later at point."
12353 (remove-hook 'post-command-hook 'org-add-log-note)
12354 (setq org-log-note-window-configuration (current-window-configuration))
12355 (delete-other-windows)
12356 (move-marker org-log-note-return-to (point))
12357 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12358 (goto-char org-log-note-marker)
12359 (org-switch-to-buffer-other-window "*Org Note*")
12360 (erase-buffer)
12361 (if (memq org-log-note-how '(time state))
12362 (let (current-prefix-arg) (org-store-log-note))
12363 (let ((org-inhibit-startup t)) (org-mode))
12364 (insert (format "# Insert note for %s.
12365 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12366 (cond
12367 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12368 ((eq org-log-note-purpose 'done) "closed todo item")
12369 ((eq org-log-note-purpose 'state)
12370 (format "state change from \"%s\" to \"%s\""
12371 (or org-log-note-previous-state "")
12372 (or org-log-note-state "")))
12373 ((eq org-log-note-purpose 'reschedule)
12374 "rescheduling")
12375 ((eq org-log-note-purpose 'delschedule)
12376 "no longer scheduled")
12377 ((eq org-log-note-purpose 'redeadline)
12378 "changing deadline")
12379 ((eq org-log-note-purpose 'deldeadline)
12380 "removing deadline")
12381 ((eq org-log-note-purpose 'refile)
12382 "refiling")
12383 ((eq org-log-note-purpose 'note)
12384 "this entry")
12385 (t (error "This should not happen")))))
12386 (if org-log-note-extra (insert org-log-note-extra))
12387 (org-set-local 'org-finish-function 'org-store-log-note)
12388 (run-hooks 'org-log-buffer-setup-hook)))
12390 (defvar org-note-abort nil) ; dynamically scoped
12391 (defun org-store-log-note ()
12392 "Finish taking a log note, and insert it to where it belongs."
12393 (let ((txt (buffer-string))
12394 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12395 lines ind bul)
12396 (kill-buffer (current-buffer))
12397 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12398 (setq txt (replace-match "" t t txt)))
12399 (if (string-match "\\s-+\\'" txt)
12400 (setq txt (replace-match "" t t txt)))
12401 (setq lines (org-split-string txt "\n"))
12402 (when (and note (string-match "\\S-" note))
12403 (setq note
12404 (org-replace-escapes
12405 note
12406 (list (cons "%u" (user-login-name))
12407 (cons "%U" user-full-name)
12408 (cons "%t" (format-time-string
12409 (org-time-stamp-format 'long 'inactive)
12410 org-log-note-effective-time))
12411 (cons "%T" (format-time-string
12412 (org-time-stamp-format 'long nil)
12413 org-log-note-effective-time))
12414 (cons "%d" (format-time-string
12415 (org-time-stamp-format nil 'inactive)
12416 org-log-note-effective-time))
12417 (cons "%D" (format-time-string
12418 (org-time-stamp-format nil nil)
12419 org-log-note-effective-time))
12420 (cons "%s" (if org-log-note-state
12421 (concat "\"" org-log-note-state "\"")
12422 ""))
12423 (cons "%S" (if org-log-note-previous-state
12424 (concat "\"" org-log-note-previous-state "\"")
12425 "\"\"")))))
12426 (if lines (setq note (concat note " \\\\")))
12427 (push note lines))
12428 (when (or current-prefix-arg org-note-abort)
12429 (when org-log-into-drawer
12430 (org-remove-empty-drawer-at
12431 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12432 org-log-note-marker))
12433 (setq lines nil))
12434 (when lines
12435 (with-current-buffer (marker-buffer org-log-note-marker)
12436 (save-excursion
12437 (goto-char org-log-note-marker)
12438 (move-marker org-log-note-marker nil)
12439 (end-of-line 1)
12440 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12441 (setq ind (save-excursion
12442 (if (ignore-errors (goto-char (org-in-item-p)))
12443 (let ((struct (org-list-struct)))
12444 (org-list-get-ind
12445 (org-list-get-top-point struct) struct))
12446 (skip-chars-backward " \r\t\n")
12447 (cond
12448 ((and (org-at-heading-p)
12449 org-adapt-indentation)
12450 (1+ (org-current-level)))
12451 ((org-at-heading-p) 0)
12452 (t (org-get-indentation))))))
12453 (setq bul (org-list-bullet-string "-"))
12454 (org-indent-line-to ind)
12455 (insert bul (pop lines))
12456 (let ((ind-body (+ (length bul) ind)))
12457 (while lines
12458 (insert "\n")
12459 (org-indent-line-to ind-body)
12460 (insert (pop lines))))
12461 (message "Note stored")
12462 (org-back-to-heading t)
12463 (org-cycle-hide-drawers 'children)))))
12464 (set-window-configuration org-log-note-window-configuration)
12465 (with-current-buffer (marker-buffer org-log-note-return-to)
12466 (goto-char org-log-note-return-to))
12467 (move-marker org-log-note-return-to nil)
12468 (and org-log-post-message (message "%s" org-log-post-message)))
12470 (defun org-remove-empty-drawer-at (drawer pos)
12471 "Remove an empty drawer DRAWER at position POS.
12472 POS may also be a marker."
12473 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12474 (save-excursion
12475 (save-restriction
12476 (widen)
12477 (goto-char pos)
12478 (if (org-in-regexp
12479 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12480 (replace-match ""))))))
12482 (defun org-sparse-tree (&optional arg)
12483 "Create a sparse tree, prompt for the details.
12484 This command can create sparse trees. You first need to select the type
12485 of match used to create the tree:
12487 t Show all TODO entries.
12488 T Show entries with a specific TODO keyword.
12489 m Show entries selected by a tags/property match.
12490 p Enter a property name and its value (both with completion on existing
12491 names/values) and show entries with that property.
12492 r Show entries matching a regular expression (`/' can be used as well)
12493 d Show deadlines due within `org-deadline-warning-days'.
12494 b Show deadlines and scheduled items before a date.
12495 a Show deadlines and scheduled items after a date."
12496 (interactive "P")
12497 (let (ans kwd value)
12498 (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")
12499 (setq ans (read-char-exclusive))
12500 (cond
12501 ((equal ans ?d)
12502 (call-interactively 'org-check-deadlines))
12503 ((equal ans ?b)
12504 (call-interactively 'org-check-before-date))
12505 ((equal ans ?a)
12506 (call-interactively 'org-check-after-date))
12507 ((equal ans ?D)
12508 (call-interactively 'org-check-dates-range))
12509 ((equal ans ?t)
12510 (org-show-todo-tree nil))
12511 ((equal ans ?T)
12512 (org-show-todo-tree '(4)))
12513 ((member ans '(?T ?m))
12514 (call-interactively 'org-match-sparse-tree))
12515 ((member ans '(?p ?P))
12516 (setq kwd (org-icompleting-read "Property: "
12517 (mapcar 'list (org-buffer-property-keys))))
12518 (setq value (org-icompleting-read "Value: "
12519 (mapcar 'list (org-property-values kwd))))
12520 (unless (string-match "\\`{.*}\\'" value)
12521 (setq value (concat "\"" value "\"")))
12522 (org-match-sparse-tree arg (concat kwd "=" value)))
12523 ((member ans '(?r ?R ?/))
12524 (call-interactively 'org-occur))
12525 (t (error "No such sparse tree command \"%c\"" ans)))))
12527 (defvar org-occur-highlights nil
12528 "List of overlays used for occur matches.")
12529 (make-variable-buffer-local 'org-occur-highlights)
12530 (defvar org-occur-parameters nil
12531 "Parameters of the active org-occur calls.
12532 This is a list, each call to org-occur pushes as cons cell,
12533 containing the regular expression and the callback, onto the list.
12534 The list can contain several entries if `org-occur' has been called
12535 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12536 will only contain one set of parameters. When the highlights are
12537 removed (for example with `C-c C-c', or with the next edit (depending
12538 on `org-remove-highlights-with-change'), this variable is emptied
12539 as well.")
12540 (make-variable-buffer-local 'org-occur-parameters)
12542 (defun org-occur (regexp &optional keep-previous callback)
12543 "Make a compact tree which shows all matches of REGEXP.
12544 The tree will show the lines where the regexp matches, and all higher
12545 headlines above the match. It will also show the heading after the match,
12546 to make sure editing the matching entry is easy.
12547 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12548 call to `org-occur' will be kept, to allow stacking of calls to this
12549 command.
12550 If CALLBACK is non-nil, it is a function which is called to confirm
12551 that the match should indeed be shown."
12552 (interactive "sRegexp: \nP")
12553 (when (equal regexp "")
12554 (error "Regexp cannot be empty"))
12555 (unless keep-previous
12556 (org-remove-occur-highlights nil nil t))
12557 (push (cons regexp callback) org-occur-parameters)
12558 (let ((cnt 0))
12559 (save-excursion
12560 (goto-char (point-min))
12561 (if (or (not keep-previous) ; do not want to keep
12562 (not org-occur-highlights)) ; no previous matches
12563 ;; hide everything
12564 (org-overview))
12565 (while (re-search-forward regexp nil t)
12566 (when (or (not callback)
12567 (save-match-data (funcall callback)))
12568 (setq cnt (1+ cnt))
12569 (when org-highlight-sparse-tree-matches
12570 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12571 (org-show-context 'occur-tree))))
12572 (when org-remove-highlights-with-change
12573 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12574 nil 'local))
12575 (unless org-sparse-tree-open-archived-trees
12576 (org-hide-archived-subtrees (point-min) (point-max)))
12577 (run-hooks 'org-occur-hook)
12578 (if (org-called-interactively-p 'interactive)
12579 (message "%d match(es) for regexp %s" cnt regexp))
12580 cnt))
12582 (defun org-occur-next-match (&optional n reset)
12583 "Function for `next-error-function' to find sparse tree matches.
12584 N is the number of matches to move, when negative move backwards.
12585 RESET is entirely ignored - this function always goes back to the
12586 starting point when no match is found."
12587 (let* ((limit (if (< n 0) (point-min) (point-max)))
12588 (search-func (if (< n 0)
12589 'previous-single-char-property-change
12590 'next-single-char-property-change))
12591 (n (abs n))
12592 (pos (point))
12594 (catch 'exit
12595 (while (setq p1 (funcall search-func (point) 'org-type))
12596 (when (equal p1 limit)
12597 (goto-char pos)
12598 (error "No more matches"))
12599 (when (equal (get-char-property p1 'org-type) 'org-occur)
12600 (setq n (1- n))
12601 (when (= n 0)
12602 (goto-char p1)
12603 (throw 'exit (point))))
12604 (goto-char p1))
12605 (goto-char p1)
12606 (error "No more matches"))))
12608 (defun org-show-context (&optional key)
12609 "Make sure point and context are visible.
12610 How much context is shown depends upon the variables
12611 `org-show-hierarchy-above', `org-show-following-heading',
12612 `org-show-entry-below' and `org-show-siblings'."
12613 (let ((heading-p (org-at-heading-p t))
12614 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12615 (following-p (org-get-alist-option org-show-following-heading key))
12616 (entry-p (org-get-alist-option org-show-entry-below key))
12617 (siblings-p (org-get-alist-option org-show-siblings key)))
12618 (catch 'exit
12619 ;; Show heading or entry text
12620 (if (and heading-p (not entry-p))
12621 (org-flag-heading nil) ; only show the heading
12622 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12623 (org-show-hidden-entry))) ; show entire entry
12624 (when following-p
12625 ;; Show next sibling, or heading below text
12626 (save-excursion
12627 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12628 (org-flag-heading nil))))
12629 (when siblings-p (org-show-siblings))
12630 (when hierarchy-p
12631 ;; show all higher headings, possibly with siblings
12632 (save-excursion
12633 (while (and (condition-case nil
12634 (progn (org-up-heading-all 1) t)
12635 (error nil))
12636 (not (bobp)))
12637 (org-flag-heading nil)
12638 (when siblings-p (org-show-siblings))))))))
12640 (defvar org-reveal-start-hook nil
12641 "Hook run before revealing a location.")
12643 (defun org-reveal (&optional siblings)
12644 "Show current entry, hierarchy above it, and the following headline.
12645 This can be used to show a consistent set of context around locations
12646 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12647 not t for the search context.
12649 With optional argument SIBLINGS, on each level of the hierarchy all
12650 siblings are shown. This repairs the tree structure to what it would
12651 look like when opened with hierarchical calls to `org-cycle'.
12652 With double optional argument \\[universal-argument] \\[universal-argument], \
12653 go to the parent and show the
12654 entire tree."
12655 (interactive "P")
12656 (run-hooks 'org-reveal-start-hook)
12657 (let ((org-show-hierarchy-above t)
12658 (org-show-following-heading t)
12659 (org-show-siblings (if siblings t org-show-siblings)))
12660 (org-show-context nil))
12661 (when (equal siblings '(16))
12662 (save-excursion
12663 (when (org-up-heading-safe)
12664 (org-show-subtree)
12665 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12667 (defun org-highlight-new-match (beg end)
12668 "Highlight from BEG to END and mark the highlight is an occur headline."
12669 (let ((ov (make-overlay beg end)))
12670 (overlay-put ov 'face 'secondary-selection)
12671 (overlay-put ov 'org-type 'org-occur)
12672 (push ov org-occur-highlights)))
12674 (defun org-remove-occur-highlights (&optional beg end noremove)
12675 "Remove the occur highlights from the buffer.
12676 BEG and END are ignored. If NOREMOVE is nil, remove this function
12677 from the `before-change-functions' in the current buffer."
12678 (interactive)
12679 (unless org-inhibit-highlight-removal
12680 (mapc 'delete-overlay org-occur-highlights)
12681 (setq org-occur-highlights nil)
12682 (setq org-occur-parameters nil)
12683 (unless noremove
12684 (remove-hook 'before-change-functions
12685 'org-remove-occur-highlights 'local))))
12687 ;;;; Priorities
12689 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12690 "Regular expression matching the priority indicator.")
12692 (defvar org-remove-priority-next-time nil)
12694 (defun org-priority-up ()
12695 "Increase the priority of the current item."
12696 (interactive)
12697 (org-priority 'up))
12699 (defun org-priority-down ()
12700 "Decrease the priority of the current item."
12701 (interactive)
12702 (org-priority 'down))
12704 (defun org-priority (&optional action)
12705 "Change the priority of an item by ARG.
12706 ACTION can be `set', `up', `down', or a character."
12707 (interactive)
12708 (unless org-enable-priority-commands
12709 (error "Priority commands are disabled"))
12710 (setq action (or action 'set))
12711 (let (current new news have remove)
12712 (save-excursion
12713 (org-back-to-heading t)
12714 (if (looking-at org-priority-regexp)
12715 (setq current (string-to-char (match-string 2))
12716 have t))
12717 (cond
12718 ((eq action 'remove)
12719 (setq remove t new ?\ ))
12720 ((or (eq action 'set)
12721 (if (featurep 'xemacs) (characterp action) (integerp action)))
12722 (if (not (eq action 'set))
12723 (setq new action)
12724 (message "Priority %c-%c, SPC to remove: "
12725 org-highest-priority org-lowest-priority)
12726 (save-match-data
12727 (setq new (read-char-exclusive))))
12728 (if (and (= (upcase org-highest-priority) org-highest-priority)
12729 (= (upcase org-lowest-priority) org-lowest-priority))
12730 (setq new (upcase new)))
12731 (cond ((equal new ?\ ) (setq remove t))
12732 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12733 (error "Priority must be between `%c' and `%c'"
12734 org-highest-priority org-lowest-priority))))
12735 ((eq action 'up)
12736 (setq new (if have
12737 (1- current) ; normal cycling
12738 ;; last priority was empty
12739 (if (eq last-command this-command)
12740 org-lowest-priority ; wrap around empty to lowest
12741 ;; default
12742 (if org-priority-start-cycle-with-default
12743 org-default-priority
12744 (1- org-default-priority))))))
12745 ((eq action 'down)
12746 (setq new (if have
12747 (1+ current) ; normal cycling
12748 ;; last priority was empty
12749 (if (eq last-command this-command)
12750 org-highest-priority ; wrap around empty to highest
12751 ;; default
12752 (if org-priority-start-cycle-with-default
12753 org-default-priority
12754 (1+ org-default-priority))))))
12755 (t (error "Invalid action")))
12756 (if (or (< (upcase new) org-highest-priority)
12757 (> (upcase new) org-lowest-priority))
12758 (if (and (memq action '(up down))
12759 (not have) (not (eq last-command this-command)))
12760 ;; `new' is from default priority
12761 (error
12762 "The default can not be set, see `org-default-priority' why")
12763 ;; normal cycling: `new' is beyond highest/lowest priority
12764 ;; and is wrapped around to the empty priority
12765 (setq remove t)))
12766 (setq news (format "%c" new))
12767 (if have
12768 (if remove
12769 (replace-match "" t t nil 1)
12770 (replace-match news t t nil 2))
12771 (if remove
12772 (error "No priority cookie found in line")
12773 (let ((case-fold-search nil))
12774 (looking-at org-todo-line-regexp))
12775 (if (match-end 2)
12776 (progn
12777 (goto-char (match-end 2))
12778 (insert " [#" news "]"))
12779 (goto-char (match-beginning 3))
12780 (insert "[#" news "] "))))
12781 (org-preserve-lc (org-set-tags nil 'align)))
12782 (if remove
12783 (message "Priority removed")
12784 (message "Priority of current item set to %s" news))))
12786 (defun org-get-priority (s)
12787 "Find priority cookie and return priority."
12788 (if (functionp org-get-priority-function)
12789 (funcall org-get-priority-function)
12790 (save-match-data
12791 (if (not (string-match org-priority-regexp s))
12792 (* 1000 (- org-lowest-priority org-default-priority))
12793 (* 1000 (- org-lowest-priority
12794 (string-to-char (match-string 2 s))))))))
12796 ;;;; Tags
12798 (defvar org-agenda-archives-mode)
12799 (defvar org-map-continue-from nil
12800 "Position from where mapping should continue.
12801 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12803 (defvar org-scanner-tags nil
12804 "The current tag list while the tags scanner is running.")
12805 (defvar org-trust-scanner-tags nil
12806 "Should `org-get-tags-at' use the tags for the scanner.
12807 This is for internal dynamical scoping only.
12808 When this is non-nil, the function `org-get-tags-at' will return the value
12809 of `org-scanner-tags' instead of building the list by itself. This
12810 can lead to large speed-ups when the tags scanner is used in a file with
12811 many entries, and when the list of tags is retrieved, for example to
12812 obtain a list of properties. Building the tags list for each entry in such
12813 a file becomes an N^2 operation - but with this variable set, it scales
12814 as N.")
12816 (defun org-scan-tags (action matcher todo-only &optional start-level)
12817 "Scan headline tags with inheritance and produce output ACTION.
12819 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12820 or `agenda' to produce an entry list for an agenda view. It can also be
12821 a Lisp form or a function that should be called at each matched headline, in
12822 this case the return value is a list of all return values from these calls.
12824 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12825 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12826 only lines with a not-done TODO keyword are included in the output.
12827 This should be the same variable that was scoped into
12828 and set by `org-make-tags-matcher' when it constructed MATCHER.
12830 START-LEVEL can be a string with asterisks, reducing the scope to
12831 headlines matching this string."
12832 (require 'org-agenda)
12833 (let* ((re (concat "^"
12834 (if start-level
12835 ;; Get the correct level to match
12836 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12837 org-outline-regexp)
12838 " *\\(\\<\\("
12839 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12840 (org-re
12841 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12842 (props (list 'face 'default
12843 'done-face 'org-agenda-done
12844 'undone-face 'default
12845 'mouse-face 'highlight
12846 'org-not-done-regexp org-not-done-regexp
12847 'org-todo-regexp org-todo-regexp
12848 'org-complex-heading-regexp org-complex-heading-regexp
12849 'help-echo
12850 (format "mouse-2 or RET jump to org file %s"
12851 (abbreviate-file-name
12852 (or (buffer-file-name (buffer-base-buffer))
12853 (buffer-name (buffer-base-buffer)))))))
12854 (case-fold-search nil)
12855 (org-map-continue-from nil)
12856 lspos tags tags-list
12857 (tags-alist (list (cons 0 org-file-tags)))
12858 (llast 0) rtn rtn1 level category i txt
12859 todo marker entry priority)
12860 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12861 (setq action (list 'lambda nil action)))
12862 (save-excursion
12863 (goto-char (point-min))
12864 (when (eq action 'sparse-tree)
12865 (org-overview)
12866 (org-remove-occur-highlights))
12867 (while (re-search-forward re nil t)
12868 (setq org-map-continue-from nil)
12869 (catch :skip
12870 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12871 tags (if (match-end 4) (org-match-string-no-properties 4)))
12872 (goto-char (setq lspos (match-beginning 0)))
12873 (setq level (org-reduced-level (funcall outline-level))
12874 category (org-get-category))
12875 (setq i llast llast level)
12876 ;; remove tag lists from same and sublevels
12877 (while (>= i level)
12878 (when (setq entry (assoc i tags-alist))
12879 (setq tags-alist (delete entry tags-alist)))
12880 (setq i (1- i)))
12881 ;; add the next tags
12882 (when tags
12883 (setq tags (org-split-string tags ":")
12884 tags-alist
12885 (cons (cons level tags) tags-alist)))
12886 ;; compile tags for current headline
12887 (setq tags-list
12888 (if org-use-tag-inheritance
12889 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12890 tags)
12891 org-scanner-tags tags-list)
12892 (when org-use-tag-inheritance
12893 (setcdr (car tags-alist)
12894 (mapcar (lambda (x)
12895 (setq x (copy-sequence x))
12896 (org-add-prop-inherited x))
12897 (cdar tags-alist))))
12898 (when (and tags org-use-tag-inheritance
12899 (or (not (eq t org-use-tag-inheritance))
12900 org-tags-exclude-from-inheritance))
12901 ;; selective inheritance, remove uninherited ones
12902 (setcdr (car tags-alist)
12903 (org-remove-uninherited-tags (cdar tags-alist))))
12904 (when (and
12906 ;; eval matcher only when the todo condition is OK
12907 (and (or (not todo-only) (member todo org-not-done-keywords))
12908 (let ((case-fold-search t) (org-trust-scanner-tags t))
12909 (eval matcher)))
12911 ;; Call the skipper, but return t if it does not skip,
12912 ;; so that the `and' form continues evaluating
12913 (progn
12914 (unless (eq action 'sparse-tree) (org-agenda-skip))
12917 ;; Check if timestamps are deselecting this entry
12918 (or (not todo-only)
12919 (and (member todo org-not-done-keywords)
12920 (or (not org-agenda-tags-todo-honor-ignore-options)
12921 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12923 ;; Extra check for the archive tag
12924 ;; FIXME: Does the skipper already do this????
12926 (not (member org-archive-tag tags-list))
12927 ;; we have an archive tag, should we use this anyway?
12928 (or (not org-agenda-skip-archived-trees)
12929 (and (eq action 'agenda) org-agenda-archives-mode))))
12931 ;; select this headline
12933 (cond
12934 ((eq action 'sparse-tree)
12935 (and org-highlight-sparse-tree-matches
12936 (org-get-heading) (match-end 0)
12937 (org-highlight-new-match
12938 (match-beginning 1) (match-end 1)))
12939 (org-show-context 'tags-tree))
12940 ((eq action 'agenda)
12941 (setq txt (org-agenda-format-item
12943 (concat
12944 (if (eq org-tags-match-list-sublevels 'indented)
12945 (make-string (1- level) ?.) "")
12946 (org-get-heading))
12947 category
12948 tags-list)
12949 priority (org-get-priority txt))
12950 (goto-char lspos)
12951 (setq marker (org-agenda-new-marker))
12952 (org-add-props txt props
12953 'org-marker marker 'org-hd-marker marker 'org-category category
12954 'todo-state todo
12955 'priority priority 'type "tagsmatch")
12956 (push txt rtn))
12957 ((functionp action)
12958 (setq org-map-continue-from nil)
12959 (save-excursion
12960 (setq rtn1 (funcall action))
12961 (push rtn1 rtn)))
12962 (t (error "Invalid action")))
12964 ;; if we are to skip sublevels, jump to end of subtree
12965 (unless org-tags-match-list-sublevels
12966 (org-end-of-subtree t)
12967 (backward-char 1))))
12968 ;; Get the correct position from where to continue
12969 (if org-map-continue-from
12970 (goto-char org-map-continue-from)
12971 (and (= (point) lspos) (end-of-line 1)))))
12972 (when (and (eq action 'sparse-tree)
12973 (not org-sparse-tree-open-archived-trees))
12974 (org-hide-archived-subtrees (point-min) (point-max)))
12975 (nreverse rtn)))
12977 (defun org-remove-uninherited-tags (tags)
12978 "Remove all tags that are not inherited from the list TAGS."
12979 (cond
12980 ((eq org-use-tag-inheritance t)
12981 (if org-tags-exclude-from-inheritance
12982 (org-delete-all org-tags-exclude-from-inheritance tags)
12983 tags))
12984 ((not org-use-tag-inheritance) nil)
12985 ((stringp org-use-tag-inheritance)
12986 (delq nil (mapcar
12987 (lambda (x)
12988 (if (and (string-match org-use-tag-inheritance x)
12989 (not (member x org-tags-exclude-from-inheritance)))
12990 x nil))
12991 tags)))
12992 ((listp org-use-tag-inheritance)
12993 (delq nil (mapcar
12994 (lambda (x)
12995 (if (member x org-use-tag-inheritance) x nil))
12996 tags)))))
12998 (defun org-match-sparse-tree (&optional todo-only match)
12999 "Create a sparse tree according to tags string MATCH.
13000 MATCH can contain positive and negative selection of tags, like
13001 \"+WORK+URGENT-WITHBOSS\".
13002 If optional argument TODO-ONLY is non-nil, only select lines that are
13003 also TODO lines."
13004 (interactive "P")
13005 (org-prepare-agenda-buffers (list (current-buffer)))
13006 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13008 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13010 (defvar org-cached-props nil)
13011 (defun org-cached-entry-get (pom property)
13012 (if (or (eq t org-use-property-inheritance)
13013 (and (stringp org-use-property-inheritance)
13014 (string-match org-use-property-inheritance property))
13015 (and (listp org-use-property-inheritance)
13016 (member property org-use-property-inheritance)))
13017 ;; Caching is not possible, check it directly
13018 (org-entry-get pom property 'inherit)
13019 ;; Get all properties, so that we can do complicated checks easily
13020 (cdr (assoc property (or org-cached-props
13021 (setq org-cached-props
13022 (org-entry-properties pom)))))))
13024 (defun org-global-tags-completion-table (&optional files)
13025 "Return the list of all tags in all agenda buffer/files.
13026 Optional FILES argument is a list of files to which can be used
13027 instead of the agenda files."
13028 (save-excursion
13029 (org-uniquify
13030 (delq nil
13031 (apply 'append
13032 (mapcar
13033 (lambda (file)
13034 (set-buffer (find-file-noselect file))
13035 (append (org-get-buffer-tags)
13036 (mapcar (lambda (x) (if (stringp (car-safe x))
13037 (list (car-safe x)) nil))
13038 org-tag-alist)))
13039 (if (and files (car files))
13040 files
13041 (org-agenda-files))))))))
13043 (defun org-make-tags-matcher (match)
13044 "Create the TAGS/TODO matcher form for the selection string MATCH.
13046 The variable `todo-only' is scoped dynamically into this function; it will be
13047 set to t if the matcher restricts matching to TODO entries,
13048 otherwise will not be touched.
13050 Returns a cons of the selection string MATCH and the constructed
13051 lisp form implementing the matcher. The matcher is to be
13052 evaluated at an Org entry, with point on the headline,
13053 and returns t if the entry matches the
13054 selection string MATCH. The returned lisp form references
13055 two variables with information about the entry, which must be
13056 bound around the form's evaluation: todo, the TODO keyword at the
13057 entry (or nil of none); and tags-list, the list of all tags at the
13058 entry including inherited ones. Additionally, the category
13059 of the entry (if any) must be specified as the text property
13060 'org-category on the headline.
13062 See also `org-scan-tags'.
13064 (declare (special todo-only))
13065 (unless (boundp 'todo-only)
13066 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13067 (unless match
13068 ;; Get a new match request, with completion
13069 (let ((org-last-tags-completion-table
13070 (org-global-tags-completion-table)))
13071 (setq match (org-completing-read-no-i
13072 "Match: " 'org-tags-completion-function nil nil nil
13073 'org-tags-history))))
13075 ;; Parse the string and create a lisp form
13076 (let ((match0 match)
13077 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13078 minus tag mm
13079 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13080 orterms term orlist re-p str-p level-p level-op time-p
13081 prop-p pn pv po gv rest)
13082 (if (string-match "/+" match)
13083 ;; match contains also a todo-matching request
13084 (progn
13085 (setq tagsmatch (substring match 0 (match-beginning 0))
13086 todomatch (substring match (match-end 0)))
13087 (if (string-match "^!" todomatch)
13088 (setq todo-only t todomatch (substring todomatch 1)))
13089 (if (string-match "^\\s-*$" todomatch)
13090 (setq todomatch nil)))
13091 ;; only matching tags
13092 (setq tagsmatch match todomatch nil))
13094 ;; Make the tags matcher
13095 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13096 (setq tagsmatcher t)
13097 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13098 (while (setq term (pop orterms))
13099 (while (and (equal (substring term -1) "\\") orterms)
13100 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13101 (while (string-match re term)
13102 (setq rest (substring term (match-end 0))
13103 minus (and (match-end 1)
13104 (equal (match-string 1 term) "-"))
13105 tag (save-match-data (replace-regexp-in-string
13106 "\\\\-" "-"
13107 (match-string 2 term)))
13108 re-p (equal (string-to-char tag) ?{)
13109 level-p (match-end 4)
13110 prop-p (match-end 5)
13111 mm (cond
13112 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13113 (level-p
13114 (setq level-op (org-op-to-function (match-string 3 term)))
13115 `(,level-op level ,(string-to-number
13116 (match-string 4 term))))
13117 (prop-p
13118 (setq pn (match-string 5 term)
13119 po (match-string 6 term)
13120 pv (match-string 7 term)
13121 re-p (equal (string-to-char pv) ?{)
13122 str-p (equal (string-to-char pv) ?\")
13123 time-p (save-match-data
13124 (string-match "^\"[[<].*[]>]\"$" pv))
13125 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13126 (if time-p (setq pv (org-matcher-time pv)))
13127 (setq po (org-op-to-function po (if time-p 'time str-p)))
13128 (cond
13129 ((equal pn "CATEGORY")
13130 (setq gv '(get-text-property (point) 'org-category)))
13131 ((equal pn "TODO")
13132 (setq gv 'todo))
13134 (setq gv `(org-cached-entry-get nil ,pn))))
13135 (if re-p
13136 (if (eq po 'org<>)
13137 `(not (string-match ,pv (or ,gv "")))
13138 `(string-match ,pv (or ,gv "")))
13139 (if str-p
13140 `(,po (or ,gv "") ,pv)
13141 `(,po (string-to-number (or ,gv ""))
13142 ,(string-to-number pv) ))))
13143 (t `(member ,tag tags-list)))
13144 mm (if minus (list 'not mm) mm)
13145 term rest)
13146 (push mm tagsmatcher))
13147 (push (if (> (length tagsmatcher) 1)
13148 (cons 'and tagsmatcher)
13149 (car tagsmatcher))
13150 orlist)
13151 (setq tagsmatcher nil))
13152 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13153 (setq tagsmatcher
13154 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13155 ;; Make the todo matcher
13156 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13157 (setq todomatcher t)
13158 (setq orterms (org-split-string todomatch "|") orlist nil)
13159 (while (setq term (pop orterms))
13160 (while (string-match re term)
13161 (setq minus (and (match-end 1)
13162 (equal (match-string 1 term) "-"))
13163 kwd (match-string 2 term)
13164 re-p (equal (string-to-char kwd) ?{)
13165 term (substring term (match-end 0))
13166 mm (if re-p
13167 `(string-match ,(substring kwd 1 -1) todo)
13168 (list 'equal 'todo kwd))
13169 mm (if minus (list 'not mm) mm))
13170 (push mm todomatcher))
13171 (push (if (> (length todomatcher) 1)
13172 (cons 'and todomatcher)
13173 (car todomatcher))
13174 orlist)
13175 (setq todomatcher nil))
13176 (setq todomatcher (if (> (length orlist) 1)
13177 (cons 'or orlist) (car orlist))))
13179 ;; Return the string and lisp forms of the matcher
13180 (setq matcher (if todomatcher
13181 (list 'and tagsmatcher todomatcher)
13182 tagsmatcher))
13183 (when todo-only
13184 (setq matcher (list 'and '(member todo org-not-done-keywords)
13185 matcher)))
13186 (cons match0 matcher)))
13188 (defun org-op-to-function (op &optional stringp)
13189 "Turn an operator into the appropriate function."
13190 (setq op
13191 (cond
13192 ((equal op "<" ) '(< string< org-time<))
13193 ((equal op ">" ) '(> org-string> org-time>))
13194 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13195 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13196 ((member op '("=" "==")) '(= string= org-time=))
13197 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13198 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13200 (defun org<> (a b) (not (= a b)))
13201 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13202 (defun org-string>= (a b) (not (string< a b)))
13203 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13204 (defun org-string<> (a b) (not (string= a b)))
13205 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13206 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13207 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13208 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13209 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13210 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13211 (defun org-2ft (s)
13212 "Convert S to a floating point time.
13213 If S is already a number, just return it. If it is a string, parse
13214 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13215 (cond
13216 ((numberp s) s)
13217 ((stringp s)
13218 (condition-case nil
13219 (float-time (apply 'encode-time (org-parse-time-string s)))
13220 (error 0.)))
13221 (t 0.)))
13223 (defun org-time-today ()
13224 "Time in seconds today at 0:00.
13225 Returns the float number of seconds since the beginning of the
13226 epoch to the beginning of today (00:00)."
13227 (float-time (apply 'encode-time
13228 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13230 (defun org-matcher-time (s)
13231 "Interpret a time comparison value."
13232 (save-match-data
13233 (cond
13234 ((string= s "<now>") (float-time))
13235 ((string= s "<today>") (org-time-today))
13236 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13237 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13238 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13239 (+ (org-time-today)
13240 (* (string-to-number (match-string 1 s))
13241 (cdr (assoc (match-string 2 s)
13242 '(("d" . 86400.0) ("w" . 604800.0)
13243 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13244 (t (org-2ft s)))))
13246 (defun org-match-any-p (re list)
13247 "Does re match any element of list?"
13248 (setq list (mapcar (lambda (x) (string-match re x)) list))
13249 (delq nil list))
13251 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13252 (defvar org-tags-overlay (make-overlay 1 1))
13253 (org-detach-overlay org-tags-overlay)
13255 (defun org-get-local-tags-at (&optional pos)
13256 "Get a list of tags defined in the current headline."
13257 (org-get-tags-at pos 'local))
13259 (defun org-get-local-tags ()
13260 "Get a list of tags defined in the current headline."
13261 (org-get-tags-at nil 'local))
13263 (defun org-get-tags-at (&optional pos local)
13264 "Get a list of all headline tags applicable at POS.
13265 POS defaults to point. If tags are inherited, the list contains
13266 the targets in the same sequence as the headlines appear, i.e.
13267 the tags of the current headline come last.
13268 When LOCAL is non-nil, only return tags from the current headline,
13269 ignore inherited ones."
13270 (interactive)
13271 (if (and org-trust-scanner-tags
13272 (or (not pos) (equal pos (point)))
13273 (not local))
13274 org-scanner-tags
13275 (let (tags ltags lastpos parent)
13276 (save-excursion
13277 (save-restriction
13278 (widen)
13279 (goto-char (or pos (point)))
13280 (save-match-data
13281 (catch 'done
13282 (condition-case nil
13283 (progn
13284 (org-back-to-heading t)
13285 (while (not (equal lastpos (point)))
13286 (setq lastpos (point))
13287 (when (looking-at
13288 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13289 (setq ltags (org-split-string
13290 (org-match-string-no-properties 1) ":"))
13291 (when parent
13292 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13293 (setq tags (append
13294 (if parent
13295 (org-remove-uninherited-tags ltags)
13296 ltags)
13297 tags)))
13298 (or org-use-tag-inheritance (throw 'done t))
13299 (if local (throw 'done t))
13300 (or (org-up-heading-safe) (error nil))
13301 (setq parent t)))
13302 (error nil)))))
13303 (if local
13304 tags
13305 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13307 (defun org-add-prop-inherited (s)
13308 (add-text-properties 0 (length s) '(inherited t) s)
13311 (defun org-toggle-tag (tag &optional onoff)
13312 "Toggle the tag TAG for the current line.
13313 If ONOFF is `on' or `off', don't toggle but set to this state."
13314 (let (res current)
13315 (save-excursion
13316 (org-back-to-heading t)
13317 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13318 (point-at-eol) t)
13319 (progn
13320 (setq current (match-string 1))
13321 (replace-match ""))
13322 (setq current ""))
13323 (setq current (nreverse (org-split-string current ":")))
13324 (cond
13325 ((eq onoff 'on)
13326 (setq res t)
13327 (or (member tag current) (push tag current)))
13328 ((eq onoff 'off)
13329 (or (not (member tag current)) (setq current (delete tag current))))
13330 (t (if (member tag current)
13331 (setq current (delete tag current))
13332 (setq res t)
13333 (push tag current))))
13334 (end-of-line 1)
13335 (if current
13336 (progn
13337 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13338 (org-set-tags nil t))
13339 (delete-horizontal-space))
13340 (run-hooks 'org-after-tags-change-hook))
13341 res))
13343 (defun org-align-tags-here (to-col)
13344 ;; Assumes that this is a headline
13345 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13346 (beginning-of-line 1)
13347 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13348 (< pos (match-beginning 2)))
13349 (progn
13350 (setq tags-l (- (match-end 2) (match-beginning 2)))
13351 (goto-char (match-beginning 1))
13352 (insert " ")
13353 (delete-region (point) (1+ (match-beginning 2)))
13354 (setq ncol (max (current-column)
13355 (1+ col)
13356 (if (> to-col 0)
13357 to-col
13358 (- (abs to-col) tags-l))))
13359 (setq p (point))
13360 (insert (make-string (- ncol (current-column)) ?\ ))
13361 (setq ncol (current-column))
13362 (when indent-tabs-mode (tabify p (point-at-eol)))
13363 (org-move-to-column (min ncol col) t))
13364 (goto-char pos))))
13366 (defun org-set-tags-command (&optional arg just-align)
13367 "Call the set-tags command for the current entry."
13368 (interactive "P")
13369 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13370 (org-set-tags arg just-align)
13371 (save-excursion
13372 (org-back-to-heading t)
13373 (org-set-tags arg just-align))))
13375 (defun org-set-tags-to (data)
13376 "Set the tags of the current entry to DATA, replacing the current tags.
13377 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13378 If DATA is nil or the empty string, any tags will be removed."
13379 (interactive "sTags: ")
13380 (setq data
13381 (cond
13382 ((eq data nil) "")
13383 ((equal data "") "")
13384 ((stringp data)
13385 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13386 ":"))
13387 ((listp data)
13388 (concat ":" (mapconcat 'identity data ":") ":"))
13389 (t nil)))
13390 (when data
13391 (save-excursion
13392 (org-back-to-heading t)
13393 (when (looking-at org-complex-heading-regexp)
13394 (if (match-end 5)
13395 (progn
13396 (goto-char (match-beginning 5))
13397 (insert data)
13398 (delete-region (point) (point-at-eol))
13399 (org-set-tags nil 'align))
13400 (goto-char (point-at-eol))
13401 (insert " " data)
13402 (org-set-tags nil 'align)))
13403 (beginning-of-line 1)
13404 (if (looking-at ".*?\\([ \t]+\\)$")
13405 (delete-region (match-beginning 1) (match-end 1))))))
13407 (defun org-align-all-tags ()
13408 "Align the tags i all headings."
13409 (interactive)
13410 (save-excursion
13411 (or (ignore-errors (org-back-to-heading t))
13412 (outline-next-heading))
13413 (if (org-at-heading-p)
13414 (org-set-tags t)
13415 (message "No headings"))))
13417 (defvar org-indent-indentation-per-level)
13418 (defun org-set-tags (&optional arg just-align)
13419 "Set the tags for the current headline.
13420 With prefix ARG, realign all tags in headings in the current buffer."
13421 (interactive "P")
13422 (let* ((re org-outline-regexp-bol)
13423 (current (unless arg (org-get-tags-string)))
13424 (col (current-column))
13425 (org-setting-tags t)
13426 table current-tags inherited-tags ; computed below when needed
13427 tags p0 c0 c1 rpl di tc level)
13428 (if arg
13429 (save-excursion
13430 (goto-char (point-min))
13431 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13432 (while (re-search-forward re nil t)
13433 (org-set-tags nil t)
13434 (end-of-line 1)))
13435 (message "All tags realigned to column %d" org-tags-column))
13436 (if just-align
13437 (setq tags current)
13438 ;; Get a new set of tags from the user
13439 (save-excursion
13440 (setq table (append org-tag-persistent-alist
13441 (or org-tag-alist (org-get-buffer-tags))
13442 (and
13443 org-complete-tags-always-offer-all-agenda-tags
13444 (org-global-tags-completion-table
13445 (org-agenda-files))))
13446 org-last-tags-completion-table table
13447 current-tags (org-split-string current ":")
13448 inherited-tags (nreverse
13449 (nthcdr (length current-tags)
13450 (nreverse (org-get-tags-at))))
13451 tags
13452 (if (or (eq t org-use-fast-tag-selection)
13453 (and org-use-fast-tag-selection
13454 (delq nil (mapcar 'cdr table))))
13455 (org-fast-tag-selection
13456 current-tags inherited-tags table
13457 (if org-fast-tag-selection-include-todo
13458 org-todo-key-alist))
13459 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13460 (org-trim
13461 (org-icompleting-read "Tags: "
13462 'org-tags-completion-function
13463 nil nil current 'org-tags-history))))))
13464 (while (string-match "[-+&]+" tags)
13465 ;; No boolean logic, just a list
13466 (setq tags (replace-match ":" t t tags))))
13468 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13470 (if org-tags-sort-function
13471 (setq tags (mapconcat 'identity
13472 (sort (org-split-string
13473 tags (org-re "[^[:alnum:]_@#%]+"))
13474 org-tags-sort-function) ":")))
13476 (if (string-match "\\`[\t ]*\\'" tags)
13477 (setq tags "")
13478 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13479 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13481 ;; Insert new tags at the correct column
13482 (beginning-of-line 1)
13483 (setq level (or (and (looking-at org-outline-regexp)
13484 (- (match-end 0) (point) 1))
13486 (cond
13487 ((and (equal current "") (equal tags "")))
13488 ((re-search-forward
13489 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13490 (point-at-eol) t)
13491 (if (equal tags "")
13492 (setq rpl "")
13493 (goto-char (match-beginning 0))
13494 (setq c0 (current-column)
13495 ;; compute offset for the case of org-indent-mode active
13496 di (if org-indent-mode
13497 (* (1- org-indent-indentation-per-level) (1- level))
13499 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13500 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13501 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13502 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13503 (replace-match rpl t t)
13504 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13505 tags)
13506 (t (error "Tags alignment failed")))
13507 (org-move-to-column col)
13508 (unless just-align
13509 (run-hooks 'org-after-tags-change-hook)))))
13511 (defun org-change-tag-in-region (beg end tag off)
13512 "Add or remove TAG for each entry in the region.
13513 This works in the agenda, and also in an org-mode buffer."
13514 (interactive
13515 (list (region-beginning) (region-end)
13516 (let ((org-last-tags-completion-table
13517 (if (eq major-mode 'org-mode)
13518 (org-get-buffer-tags)
13519 (org-global-tags-completion-table))))
13520 (org-icompleting-read
13521 "Tag: " 'org-tags-completion-function nil nil nil
13522 'org-tags-history))
13523 (progn
13524 (message "[s]et or [r]emove? ")
13525 (equal (read-char-exclusive) ?r))))
13526 (if (fboundp 'deactivate-mark) (deactivate-mark))
13527 (let ((agendap (equal major-mode 'org-agenda-mode))
13528 l1 l2 m buf pos newhead (cnt 0))
13529 (goto-char end)
13530 (setq l2 (1- (org-current-line)))
13531 (goto-char beg)
13532 (setq l1 (org-current-line))
13533 (loop for l from l1 to l2 do
13534 (org-goto-line l)
13535 (setq m (get-text-property (point) 'org-hd-marker))
13536 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13537 (and agendap m))
13538 (setq buf (if agendap (marker-buffer m) (current-buffer))
13539 pos (if agendap m (point)))
13540 (with-current-buffer buf
13541 (save-excursion
13542 (save-restriction
13543 (goto-char pos)
13544 (setq cnt (1+ cnt))
13545 (org-toggle-tag tag (if off 'off 'on))
13546 (setq newhead (org-get-heading)))))
13547 (and agendap (org-agenda-change-all-lines newhead m))))
13548 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13550 (defun org-tags-completion-function (string predicate &optional flag)
13551 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13552 (confirm (lambda (x) (stringp (car x)))))
13553 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13554 (setq s1 (match-string 1 string)
13555 s2 (match-string 2 string))
13556 (setq s1 "" s2 string))
13557 (cond
13558 ((eq flag nil)
13559 ;; try completion
13560 (setq rtn (try-completion s2 ctable confirm))
13561 (if (stringp rtn)
13562 (setq rtn
13563 (concat s1 s2 (substring rtn (length s2))
13564 (if (and org-add-colon-after-tag-completion
13565 (assoc rtn ctable))
13566 ":" ""))))
13567 rtn)
13568 ((eq flag t)
13569 ;; all-completions
13570 (all-completions s2 ctable confirm)
13572 ((eq flag 'lambda)
13573 ;; exact match?
13574 (assoc s2 ctable)))
13577 (defun org-fast-tag-insert (kwd tags face &optional end)
13578 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13579 (insert (format "%-12s" (concat kwd ":"))
13580 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13581 (or end "")))
13583 (defun org-fast-tag-show-exit (flag)
13584 (save-excursion
13585 (org-goto-line 3)
13586 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13587 (replace-match ""))
13588 (when flag
13589 (end-of-line 1)
13590 (org-move-to-column (- (window-width) 19) t)
13591 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13593 (defun org-set-current-tags-overlay (current prefix)
13594 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13595 (if (featurep 'xemacs)
13596 (org-overlay-display org-tags-overlay (concat prefix s)
13597 'secondary-selection)
13598 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13599 (org-overlay-display org-tags-overlay (concat prefix s)))))
13601 (defvar org-last-tag-selection-key nil)
13602 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13603 "Fast tag selection with single keys.
13604 CURRENT is the current list of tags in the headline, INHERITED is the
13605 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13606 possibly with grouping information. TODO-TABLE is a similar table with
13607 TODO keywords, should these have keys assigned to them.
13608 If the keys are nil, a-z are automatically assigned.
13609 Returns the new tags string, or nil to not change the current settings."
13610 (let* ((fulltable (append table todo-table))
13611 (maxlen (apply 'max (mapcar
13612 (lambda (x)
13613 (if (stringp (car x)) (string-width (car x)) 0))
13614 fulltable)))
13615 (buf (current-buffer))
13616 (expert (eq org-fast-tag-selection-single-key 'expert))
13617 (buffer-tags nil)
13618 (fwidth (+ maxlen 3 1 3))
13619 (ncol (/ (- (window-width) 4) fwidth))
13620 (i-face 'org-done)
13621 (c-face 'org-todo)
13622 tg cnt e c char c1 c2 ntable tbl rtn
13623 ov-start ov-end ov-prefix
13624 (exit-after-next org-fast-tag-selection-single-key)
13625 (done-keywords org-done-keywords)
13626 groups ingroup)
13627 (save-excursion
13628 (beginning-of-line 1)
13629 (if (looking-at
13630 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13631 (setq ov-start (match-beginning 1)
13632 ov-end (match-end 1)
13633 ov-prefix "")
13634 (setq ov-start (1- (point-at-eol))
13635 ov-end (1+ ov-start))
13636 (skip-chars-forward "^\n\r")
13637 (setq ov-prefix
13638 (concat
13639 (buffer-substring (1- (point)) (point))
13640 (if (> (current-column) org-tags-column)
13642 (make-string (- org-tags-column (current-column)) ?\ ))))))
13643 (move-overlay org-tags-overlay ov-start ov-end)
13644 (save-window-excursion
13645 (if expert
13646 (set-buffer (get-buffer-create " *Org tags*"))
13647 (delete-other-windows)
13648 (split-window-vertically)
13649 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13650 (erase-buffer)
13651 (org-set-local 'org-done-keywords done-keywords)
13652 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13653 (org-fast-tag-insert "Current" current c-face "\n\n")
13654 (org-fast-tag-show-exit exit-after-next)
13655 (org-set-current-tags-overlay current ov-prefix)
13656 (setq tbl fulltable char ?a cnt 0)
13657 (while (setq e (pop tbl))
13658 (cond
13659 ((equal (car e) :startgroup)
13660 (push '() groups) (setq ingroup t)
13661 (when (not (= cnt 0))
13662 (setq cnt 0)
13663 (insert "\n"))
13664 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13665 ((equal (car e) :endgroup)
13666 (setq ingroup nil cnt 0)
13667 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13668 ((equal e '(:newline))
13669 (when (not (= cnt 0))
13670 (setq cnt 0)
13671 (insert "\n")
13672 (setq e (car tbl))
13673 (while (equal (car tbl) '(:newline))
13674 (insert "\n")
13675 (setq tbl (cdr tbl)))))
13677 (setq tg (copy-sequence (car e)) c2 nil)
13678 (if (cdr e)
13679 (setq c (cdr e))
13680 ;; automatically assign a character.
13681 (setq c1 (string-to-char
13682 (downcase (substring
13683 tg (if (= (string-to-char tg) ?@) 1 0)))))
13684 (if (or (rassoc c1 ntable) (rassoc c1 table))
13685 (while (or (rassoc char ntable) (rassoc char table))
13686 (setq char (1+ char)))
13687 (setq c2 c1))
13688 (setq c (or c2 char)))
13689 (if ingroup (push tg (car groups)))
13690 (setq tg (org-add-props tg nil 'face
13691 (cond
13692 ((not (assoc tg table))
13693 (org-get-todo-face tg))
13694 ((member tg current) c-face)
13695 ((member tg inherited) i-face)
13696 (t nil))))
13697 (if (and (= cnt 0) (not ingroup)) (insert " "))
13698 (insert "[" c "] " tg (make-string
13699 (- fwidth 4 (length tg)) ?\ ))
13700 (push (cons tg c) ntable)
13701 (when (= (setq cnt (1+ cnt)) ncol)
13702 (insert "\n")
13703 (if ingroup (insert " "))
13704 (setq cnt 0)))))
13705 (setq ntable (nreverse ntable))
13706 (insert "\n")
13707 (goto-char (point-min))
13708 (if (not expert) (org-fit-window-to-buffer))
13709 (setq rtn
13710 (catch 'exit
13711 (while t
13712 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13713 (if (not groups) "no " "")
13714 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13715 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13716 (setq org-last-tag-selection-key c)
13717 (cond
13718 ((= c ?\r) (throw 'exit t))
13719 ((= c ?!)
13720 (setq groups (not groups))
13721 (goto-char (point-min))
13722 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13723 ((= c ?\C-c)
13724 (if (not expert)
13725 (org-fast-tag-show-exit
13726 (setq exit-after-next (not exit-after-next)))
13727 (setq expert nil)
13728 (delete-other-windows)
13729 (set-window-buffer (split-window-vertically) " *Org tags*")
13730 (org-switch-to-buffer-other-window " *Org tags*")
13731 (org-fit-window-to-buffer)))
13732 ((or (= c ?\C-g)
13733 (and (= c ?q) (not (rassoc c ntable))))
13734 (org-detach-overlay org-tags-overlay)
13735 (setq quit-flag t))
13736 ((= c ?\ )
13737 (setq current nil)
13738 (if exit-after-next (setq exit-after-next 'now)))
13739 ((= c ?\t)
13740 (condition-case nil
13741 (setq tg (org-icompleting-read
13742 "Tag: "
13743 (or buffer-tags
13744 (with-current-buffer buf
13745 (org-get-buffer-tags)))))
13746 (quit (setq tg "")))
13747 (when (string-match "\\S-" tg)
13748 (add-to-list 'buffer-tags (list tg))
13749 (if (member tg current)
13750 (setq current (delete tg current))
13751 (push tg current)))
13752 (if exit-after-next (setq exit-after-next 'now)))
13753 ((setq e (rassoc c todo-table) tg (car e))
13754 (with-current-buffer buf
13755 (save-excursion (org-todo tg)))
13756 (if exit-after-next (setq exit-after-next 'now)))
13757 ((setq e (rassoc c ntable) tg (car e))
13758 (if (member tg current)
13759 (setq current (delete tg current))
13760 (loop for g in groups do
13761 (if (member tg g)
13762 (mapc (lambda (x)
13763 (setq current (delete x current)))
13764 g)))
13765 (push tg current))
13766 (if exit-after-next (setq exit-after-next 'now))))
13768 ;; Create a sorted list
13769 (setq current
13770 (sort current
13771 (lambda (a b)
13772 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13773 (if (eq exit-after-next 'now) (throw 'exit t))
13774 (goto-char (point-min))
13775 (beginning-of-line 2)
13776 (delete-region (point) (point-at-eol))
13777 (org-fast-tag-insert "Current" current c-face)
13778 (org-set-current-tags-overlay current ov-prefix)
13779 (while (re-search-forward
13780 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13781 (setq tg (match-string 1))
13782 (add-text-properties
13783 (match-beginning 1) (match-end 1)
13784 (list 'face
13785 (cond
13786 ((member tg current) c-face)
13787 ((member tg inherited) i-face)
13788 (t (get-text-property (match-beginning 1) 'face))))))
13789 (goto-char (point-min)))))
13790 (org-detach-overlay org-tags-overlay)
13791 (if rtn
13792 (mapconcat 'identity current ":")
13793 nil))))
13795 (defun org-get-tags-string ()
13796 "Get the TAGS string in the current headline."
13797 (unless (org-at-heading-p t)
13798 (error "Not on a heading"))
13799 (save-excursion
13800 (beginning-of-line 1)
13801 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13802 (org-match-string-no-properties 1)
13803 "")))
13805 (defun org-get-tags ()
13806 "Get the list of tags specified in the current headline."
13807 (org-split-string (org-get-tags-string) ":"))
13809 (defun org-get-buffer-tags ()
13810 "Get a table of all tags used in the buffer, for completion."
13811 (let (tags)
13812 (save-excursion
13813 (goto-char (point-min))
13814 (while (re-search-forward
13815 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13816 (when (equal (char-after (point-at-bol 0)) ?*)
13817 (mapc (lambda (x) (add-to-list 'tags x))
13818 (org-split-string (org-match-string-no-properties 1) ":")))))
13819 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13820 (mapcar 'list tags)))
13822 ;;;; The mapping API
13824 ;;;###autoload
13825 (defun org-map-entries (func &optional match scope &rest skip)
13826 "Call FUNC at each headline selected by MATCH in SCOPE.
13828 FUNC is a function or a lisp form. The function will be called without
13829 arguments, with the cursor positioned at the beginning of the headline.
13830 The return values of all calls to the function will be collected and
13831 returned as a list.
13833 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13834 does not need to preserve point. After evaluation, the cursor will be
13835 moved to the end of the line (presumably of the headline of the
13836 processed entry) and search continues from there. Under some
13837 circumstances, this may not produce the wanted results. For example,
13838 if you have removed (e.g. archived) the current (sub)tree it could
13839 mean that the next entry will be skipped entirely. In such cases, you
13840 can specify the position from where search should continue by making
13841 FUNC set the variable `org-map-continue-from' to the desired buffer
13842 position.
13844 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13845 Only headlines that are matched by this query will be considered during
13846 the iteration. When MATCH is nil or t, all headlines will be
13847 visited by the iteration.
13849 SCOPE determines the scope of this command. It can be any of:
13851 nil The current buffer, respecting the restriction if any
13852 tree The subtree started with the entry at point
13853 region The entries within the active region, if any
13854 region-start-level
13855 The entries within the active region, but only those at
13856 the same level than the first one.
13857 file The current buffer, without restriction
13858 file-with-archives
13859 The current buffer, and any archives associated with it
13860 agenda All agenda files
13861 agenda-with-archives
13862 All agenda files with any archive files associated with them
13863 \(file1 file2 ...)
13864 If this is a list, all files in the list will be scanned
13866 The remaining args are treated as settings for the skipping facilities of
13867 the scanner. The following items can be given here:
13869 archive skip trees with the archive tag.
13870 comment skip trees with the COMMENT keyword
13871 function or Emacs Lisp form:
13872 will be used as value for `org-agenda-skip-function', so whenever
13873 the function returns t, FUNC will not be called for that
13874 entry and search will continue from the point where the
13875 function leaves it.
13877 If your function needs to retrieve the tags including inherited tags
13878 at the *current* entry, you can use the value of the variable
13879 `org-scanner-tags' which will be much faster than getting the value
13880 with `org-get-tags-at'. If your function gets properties with
13881 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13882 to t around the call to `org-entry-properties' to get the same speedup.
13883 Note that if your function moves around to retrieve tags and properties at
13884 a *different* entry, you cannot use these techniques."
13885 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13886 (not (org-region-active-p)))
13887 (let* ((org-agenda-archives-mode nil) ; just to make sure
13888 (org-agenda-skip-archived-trees (memq 'archive skip))
13889 (org-agenda-skip-comment-trees (memq 'comment skip))
13890 (org-agenda-skip-function
13891 (car (org-delete-all '(comment archive) skip)))
13892 (org-tags-match-list-sublevels t)
13893 (start-level (eq scope 'region-start-level))
13894 matcher file res
13895 org-todo-keywords-for-agenda
13896 org-done-keywords-for-agenda
13897 org-todo-keyword-alist-for-agenda
13898 org-drawers-for-agenda
13899 org-tag-alist-for-agenda
13900 todo-only)
13902 (cond
13903 ((eq match t) (setq matcher t))
13904 ((eq match nil) (setq matcher t))
13905 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13907 (save-excursion
13908 (save-restriction
13909 (cond ((eq scope 'tree)
13910 (org-back-to-heading t)
13911 (org-narrow-to-subtree)
13912 (setq scope nil))
13913 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13914 (org-region-active-p))
13915 ;; If needed, set start-level to a string like "2"
13916 (when start-level
13917 (save-excursion
13918 (goto-char (region-beginning))
13919 (unless (org-at-heading-p) (outline-next-heading))
13920 (setq start-level (org-current-level))))
13921 (narrow-to-region (region-beginning)
13922 (save-excursion
13923 (goto-char (region-end))
13924 (unless (and (bolp) (org-at-heading-p))
13925 (outline-next-heading))
13926 (point)))
13927 (setq scope nil)))
13929 (if (not scope)
13930 (progn
13931 (org-prepare-agenda-buffers
13932 (list (buffer-file-name (current-buffer))))
13933 (setq res (org-scan-tags func matcher todo-only start-level)))
13934 ;; Get the right scope
13935 (cond
13936 ((and scope (listp scope) (symbolp (car scope)))
13937 (setq scope (eval scope)))
13938 ((eq scope 'agenda)
13939 (setq scope (org-agenda-files t)))
13940 ((eq scope 'agenda-with-archives)
13941 (setq scope (org-agenda-files t))
13942 (setq scope (org-add-archive-files scope)))
13943 ((eq scope 'file)
13944 (setq scope (list (buffer-file-name))))
13945 ((eq scope 'file-with-archives)
13946 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13947 (org-prepare-agenda-buffers scope)
13948 (while (setq file (pop scope))
13949 (with-current-buffer (org-find-base-buffer-visiting file)
13950 (save-excursion
13951 (save-restriction
13952 (widen)
13953 (goto-char (point-min))
13954 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13955 res)))
13957 ;;;; Properties
13959 ;;; Setting and retrieving properties
13961 (defconst org-special-properties
13962 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13963 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13964 "The special properties valid in Org-mode.
13966 These are properties that are not defined in the property drawer,
13967 but in some other way.")
13969 (defconst org-default-properties
13970 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13971 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13972 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13973 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13974 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13975 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13976 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13977 "Some properties that are used by Org-mode for various purposes.
13978 Being in this list makes sure that they are offered for completion.")
13980 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13981 "Regular expression matching the first line of a property drawer.")
13983 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13984 "Regular expression matching the last line of a property drawer.")
13986 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13987 "Regular expression matching the first line of a property drawer.")
13989 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13990 "Regular expression matching the first line of a property drawer.")
13992 (defconst org-property-drawer-re
13993 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13994 org-property-end-re "\\)\n?")
13995 "Matches an entire property drawer.")
13997 (defconst org-clock-drawer-re
13998 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13999 org-property-end-re "\\)\n?")
14000 "Matches an entire clock drawer.")
14002 (defsubst org-re-property (property)
14003 "Return a regexp matching PROPERTY.
14004 Match group 1 will be set to the value "
14005 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14007 (defun org-property-action ()
14008 "Do an action on properties."
14009 (interactive)
14010 (let (c)
14011 (org-at-property-p)
14012 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14013 (setq c (read-char-exclusive))
14014 (cond
14015 ((equal c ?s)
14016 (call-interactively 'org-set-property))
14017 ((equal c ?d)
14018 (call-interactively 'org-delete-property))
14019 ((equal c ?D)
14020 (call-interactively 'org-delete-property-globally))
14021 ((equal c ?c)
14022 (call-interactively 'org-compute-property-at-point))
14023 (t (error "No such property action %c" c)))))
14025 (defun org-set-effort (&optional value)
14026 "Set the effort property of the current entry.
14027 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14028 allowed value."
14029 (interactive "P")
14030 (if (equal value 0) (setq value 10))
14031 (let* ((completion-ignore-case t)
14032 (prop org-effort-property)
14033 (cur (org-entry-get nil prop))
14034 (allowed (org-property-get-allowed-values nil prop 'table))
14035 (existing (mapcar 'list (org-property-values prop)))
14037 (val (cond
14038 ((stringp value) value)
14039 ((and allowed (integerp value))
14040 (or (car (nth (1- value) allowed))
14041 (car (org-last allowed))))
14042 (allowed
14043 (message "Select 1-9,0, [RET%s]: %s"
14044 (if cur (concat "=" cur) "")
14045 (mapconcat 'car allowed " "))
14046 (setq rpl (read-char-exclusive))
14047 (if (equal rpl ?\r)
14049 (setq rpl (- rpl ?0))
14050 (if (equal rpl 0) (setq rpl 10))
14051 (if (and (> rpl 0) (<= rpl (length allowed)))
14052 (car (nth (1- rpl) allowed))
14053 (org-completing-read "Effort: " allowed nil))))
14055 (let (org-completion-use-ido org-completion-use-iswitchb)
14056 (org-completing-read
14057 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14058 (concat "[" cur "]") "")
14059 ": ")
14060 existing nil nil "" nil cur))))))
14061 (unless (equal (org-entry-get nil prop) val)
14062 (org-entry-put nil prop val))
14063 (message "%s is now %s" prop val)))
14065 (defun org-at-property-p ()
14066 "Is cursor inside a property drawer?"
14067 (save-excursion
14068 (beginning-of-line 1)
14069 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14070 (save-match-data ;; Used by calling procedures
14071 (let ((p (point))
14072 (range (unless (org-before-first-heading-p)
14073 (org-get-property-block))))
14074 (and range (<= (car range) p) (< p (cdr range))))))))
14076 (defun org-get-property-block (&optional beg end force)
14077 "Return the (beg . end) range of the body of the property drawer.
14078 BEG and END can be beginning and end of subtree, if not given
14079 they will be found.
14080 If the drawer does not exist and FORCE is non-nil, create the drawer."
14081 (catch 'exit
14082 (save-excursion
14083 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14084 (end (or end (progn (outline-next-heading) (point)))))
14085 (goto-char beg)
14086 (if (re-search-forward org-property-start-re end t)
14087 (setq beg (1+ (match-end 0)))
14088 (if force
14089 (save-excursion
14090 (org-insert-property-drawer)
14091 (setq end (progn (outline-next-heading) (point))))
14092 (throw 'exit nil))
14093 (goto-char beg)
14094 (if (re-search-forward org-property-start-re end t)
14095 (setq beg (1+ (match-end 0)))))
14096 (if (re-search-forward org-property-end-re end t)
14097 (setq end (match-beginning 0))
14098 (or force (throw 'exit nil))
14099 (goto-char beg)
14100 (setq end beg)
14101 (org-indent-line-function)
14102 (insert ":END:\n"))
14103 (cons beg end)))))
14105 (defun org-entry-properties (&optional pom which specific)
14106 "Get all properties of the entry at point-or-marker POM.
14107 This includes the TODO keyword, the tags, time strings for deadline,
14108 scheduled, and clocking, and any additional properties defined in the
14109 entry. The return value is an alist, keys may occur multiple times
14110 if the property key was used several times.
14111 POM may also be nil, in which case the current entry is used.
14112 If WHICH is nil or `all', get all properties. If WHICH is
14113 `special' or `standard', only get that subclass. If WHICH
14114 is a string only get exactly this property. SPECIFIC can be a string, the
14115 specific property we are interested in. Specifying it can speed
14116 things up because then unnecessary parsing is avoided."
14117 (setq which (or which 'all))
14118 (org-with-point-at pom
14119 (let ((clockstr (substring org-clock-string 0 -1))
14120 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14121 (case-fold-search nil)
14122 beg end range props sum-props key key1 value string clocksum)
14123 (save-excursion
14124 (when (condition-case nil
14125 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14126 (error nil))
14127 (setq beg (point))
14128 (setq sum-props (get-text-property (point) 'org-summaries))
14129 (setq clocksum (get-text-property (point) :org-clock-minutes))
14130 (outline-next-heading)
14131 (setq end (point))
14132 (when (memq which '(all special))
14133 ;; Get the special properties, like TODO and tags
14134 (goto-char beg)
14135 (when (and (or (not specific) (string= specific "TODO"))
14136 (looking-at org-todo-line-regexp) (match-end 2))
14137 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14138 (when (and (or (not specific) (string= specific "PRIORITY"))
14139 (looking-at org-priority-regexp))
14140 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14141 (when (or (not specific) (string= specific "FILE"))
14142 (push (cons "FILE" buffer-file-name) props))
14143 (when (and (or (not specific) (string= specific "TAGS"))
14144 (setq value (org-get-tags-string))
14145 (string-match "\\S-" value))
14146 (push (cons "TAGS" value) props))
14147 (when (and (or (not specific) (string= specific "ALLTAGS"))
14148 (setq value (org-get-tags-at)))
14149 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14150 ":"))
14151 props))
14152 (when (or (not specific) (string= specific "BLOCKED"))
14153 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14154 (when (or (not specific)
14155 (member specific
14156 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14157 "TIMESTAMP" "TIMESTAMP_IA")))
14158 (catch 'match
14159 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14160 (setq key (if (match-end 1)
14161 (substring (org-match-string-no-properties 1)
14162 0 -1))
14163 string (if (equal key clockstr)
14164 (org-no-properties
14165 (org-trim
14166 (buffer-substring
14167 (match-beginning 3) (goto-char
14168 (point-at-eol)))))
14169 (substring (org-match-string-no-properties 3)
14170 1 -1)))
14171 ;; Get the correct property name from the key. This is
14172 ;; necessary if the user has configured time keywords.
14173 (setq key1 (concat key ":"))
14174 (cond
14175 ((not key)
14176 (setq key
14177 (if (= (char-after (match-beginning 3)) ?\[)
14178 "TIMESTAMP_IA" "TIMESTAMP")))
14179 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14180 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14181 ((equal key1 org-closed-string) (setq key "CLOSED"))
14182 ((equal key1 org-clock-string) (setq key "CLOCK")))
14183 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14184 (progn
14185 (push (cons key string) props)
14186 ;; no need to search further if match is found
14187 (throw 'match t))
14188 (when (or (equal key "CLOCK") (not (assoc key props)))
14189 (push (cons key string) props))))))
14192 (when (memq which '(all standard))
14193 ;; Get the standard properties, like :PROP: ...
14194 (setq range (org-get-property-block beg end))
14195 (when range
14196 (goto-char (car range))
14197 (while (re-search-forward
14198 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14199 (cdr range) t)
14200 (setq key (org-match-string-no-properties 1)
14201 value (org-trim (or (org-match-string-no-properties 2) "")))
14202 (unless (member key excluded)
14203 (push (cons key (or value "")) props)))))
14204 (if clocksum
14205 (push (cons "CLOCKSUM"
14206 (org-columns-number-to-string (/ (float clocksum) 60.)
14207 'add_times))
14208 props))
14209 (unless (assoc "CATEGORY" props)
14210 (push (cons "CATEGORY" (org-get-category)) props))
14211 (append sum-props (nreverse props)))))))
14213 (defun org-entry-get (pom property &optional inherit literal-nil)
14214 "Get value of PROPERTY for entry at point-or-marker POM.
14215 If INHERIT is non-nil and the entry does not have the property,
14216 then also check higher levels of the hierarchy.
14217 If INHERIT is the symbol `selective', use inheritance only if the setting
14218 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14219 If the property is present but empty, the return value is the empty string.
14220 If the property is not present at all, nil is returned.
14222 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14223 do not interpret it as the list atom nil. This is used for inheritance
14224 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14225 (org-with-point-at pom
14226 (if (and inherit (if (eq inherit 'selective)
14227 (org-property-inherit-p property)
14229 (org-entry-get-with-inheritance property literal-nil)
14230 (if (member property org-special-properties)
14231 ;; We need a special property. Use `org-entry-properties' to
14232 ;; retrieve it, but specify the wanted property
14233 (cdr (assoc property (org-entry-properties nil 'special property)))
14234 (let ((range (unless (org-before-first-heading-p)
14235 (org-get-property-block)))
14236 (props (list (or (assoc property org-file-properties)
14237 (assoc property org-global-properties)
14238 (assoc property org-global-properties-fixed))))
14239 val)
14240 (flet ((ap (key)
14241 (when (re-search-forward
14242 (org-re-property key) (cdr range) t)
14243 (setq props
14244 (org-update-property-plist
14246 (if (match-end 1)
14247 (org-match-string-no-properties 1) "")
14248 props)))))
14249 (when (and range (goto-char (car range)))
14250 (ap property)
14251 (goto-char (car range))
14252 (while (ap (concat property "+")))
14253 (setq val (cdr (assoc property props)))
14254 (when val (if literal-nil val (org-not-nil val))))))))))
14256 (defun org-property-or-variable-value (var &optional inherit)
14257 "Check if there is a property fixing the value of VAR.
14258 If yes, return this value. If not, return the current value of the variable."
14259 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14260 (if (and prop (stringp prop) (string-match "\\S-" prop))
14261 (read prop)
14262 (symbol-value var))))
14264 (defun org-entry-delete (pom property)
14265 "Delete the property PROPERTY from entry at point-or-marker POM."
14266 (org-with-point-at pom
14267 (if (member property org-special-properties)
14268 nil ; cannot delete these properties.
14269 (let ((range (org-get-property-block)))
14270 (if (and range
14271 (goto-char (car range))
14272 (re-search-forward
14273 (org-re-property property)
14274 (cdr range) t))
14275 (progn
14276 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14278 nil)))))
14280 ;; Multi-values properties are properties that contain multiple values
14281 ;; These values are assumed to be single words, separated by whitespace.
14282 (defun org-entry-add-to-multivalued-property (pom property value)
14283 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14284 (let* ((old (org-entry-get pom property))
14285 (values (and old (org-split-string old "[ \t]"))))
14286 (setq value (org-entry-protect-space value))
14287 (unless (member value values)
14288 (setq values (cons value values))
14289 (org-entry-put pom property
14290 (mapconcat 'identity values " ")))))
14292 (defun org-entry-remove-from-multivalued-property (pom property value)
14293 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14294 (let* ((old (org-entry-get pom property))
14295 (values (and old (org-split-string old "[ \t]"))))
14296 (setq value (org-entry-protect-space value))
14297 (when (member value values)
14298 (setq values (delete value values))
14299 (org-entry-put pom property
14300 (mapconcat 'identity values " ")))))
14302 (defun org-entry-member-in-multivalued-property (pom property value)
14303 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14304 (let* ((old (org-entry-get pom property))
14305 (values (and old (org-split-string old "[ \t]"))))
14306 (setq value (org-entry-protect-space value))
14307 (member value values)))
14309 (defun org-entry-get-multivalued-property (pom property)
14310 "Return a list of values in a multivalued property."
14311 (let* ((value (org-entry-get pom property))
14312 (values (and value (org-split-string value "[ \t]"))))
14313 (mapcar 'org-entry-restore-space values)))
14315 (defun org-entry-put-multivalued-property (pom property &rest values)
14316 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14317 VALUES should be a list of strings. Spaces will be protected."
14318 (org-entry-put pom property
14319 (mapconcat 'org-entry-protect-space values " "))
14320 (let* ((value (org-entry-get pom property))
14321 (values (and value (org-split-string value "[ \t]"))))
14322 (mapcar 'org-entry-restore-space values)))
14324 (defun org-entry-protect-space (s)
14325 "Protect spaces and newline in string S."
14326 (while (string-match " " s)
14327 (setq s (replace-match "%20" t t s)))
14328 (while (string-match "\n" s)
14329 (setq s (replace-match "%0A" t t s)))
14332 (defun org-entry-restore-space (s)
14333 "Restore spaces and newline in string S."
14334 (while (string-match "%20" s)
14335 (setq s (replace-match " " t t s)))
14336 (while (string-match "%0A" s)
14337 (setq s (replace-match "\n" t t s)))
14340 (defvar org-entry-property-inherited-from (make-marker)
14341 "Marker pointing to the entry from where a property was inherited.
14342 Each call to `org-entry-get-with-inheritance' will set this marker to the
14343 location of the entry where the inheritance search matched. If there was
14344 no match, the marker will point nowhere.
14345 Note that also `org-entry-get' calls this function, if the INHERIT flag
14346 is set.")
14348 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14349 "Get entry property, and search higher levels if not present.
14350 The search will stop at the first ancestor which has the property defined.
14351 If the value found is \"nil\", return nil to show that the property
14352 should be considered as undefined (this is the meaning of nil here).
14353 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14354 (move-marker org-entry-property-inherited-from nil)
14355 (let (tmp)
14356 (unless (org-before-first-heading-p)
14357 (save-excursion
14358 (save-restriction
14359 (widen)
14360 (catch 'ex
14361 (while t
14362 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14363 (org-back-to-heading t)
14364 (move-marker org-entry-property-inherited-from (point))
14365 (throw 'ex tmp))
14366 (or (org-up-heading-safe) (throw 'ex nil)))))))
14367 (setq tmp (or tmp
14368 (cdr (assoc property org-file-properties))
14369 (cdr (assoc property org-global-properties))
14370 (cdr (assoc property org-global-properties-fixed))))
14371 (if literal-nil tmp (org-not-nil tmp))))
14373 (defvar org-property-changed-functions nil
14374 "Hook called when the value of a property has changed.
14375 Each hook function should accept two arguments, the name of the property
14376 and the new value.")
14378 (defun org-entry-put (pom property value)
14379 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14380 (org-with-point-at pom
14381 (org-back-to-heading t)
14382 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14383 range)
14384 (cond
14385 ((equal property "TODO")
14386 (when (and (stringp value) (string-match "\\S-" value)
14387 (not (member value org-todo-keywords-1)))
14388 (error "\"%s\" is not a valid TODO state" value))
14389 (if (or (not value)
14390 (not (string-match "\\S-" value)))
14391 (setq value 'none))
14392 (org-todo value)
14393 (org-set-tags nil 'align))
14394 ((equal property "PRIORITY")
14395 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14396 (string-to-char value) ?\ ))
14397 (org-set-tags nil 'align))
14398 ((equal property "SCHEDULED")
14399 (if (re-search-forward org-scheduled-time-regexp end t)
14400 (cond
14401 ((eq value 'earlier) (org-timestamp-change -1 'day))
14402 ((eq value 'later) (org-timestamp-change 1 'day))
14403 (t (call-interactively 'org-schedule)))
14404 (call-interactively 'org-schedule)))
14405 ((equal property "DEADLINE")
14406 (if (re-search-forward org-deadline-time-regexp end t)
14407 (cond
14408 ((eq value 'earlier) (org-timestamp-change -1 'day))
14409 ((eq value 'later) (org-timestamp-change 1 'day))
14410 (t (call-interactively 'org-deadline)))
14411 (call-interactively 'org-deadline)))
14412 ((member property org-special-properties)
14413 (error "The %s property can not yet be set with `org-entry-put'"
14414 property))
14415 (t ; a non-special property
14416 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14417 (setq range (org-get-property-block beg end 'force))
14418 (goto-char (car range))
14419 (if (re-search-forward
14420 (org-re-property property) (cdr range) t)
14421 (progn
14422 (delete-region (match-beginning 0) (match-end 0))
14423 (goto-char (match-beginning 0)))
14424 (goto-char (cdr range))
14425 (insert "\n")
14426 (backward-char 1)
14427 (org-indent-line-function))
14428 (insert ":" property ":")
14429 (and value (insert " " value))
14430 (org-indent-line-function)))))
14431 (run-hook-with-args 'org-property-changed-functions property value)))
14433 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14434 "Get all property keys in the current buffer.
14435 With INCLUDE-SPECIALS, also list the special properties that reflect things
14436 like tags and TODO state.
14437 With INCLUDE-DEFAULTS, also include properties that has special meaning
14438 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14439 and others.
14440 With INCLUDE-COLUMNS, also include property names given in COLUMN
14441 formats in the current buffer."
14442 (let (rtn range cfmt s p)
14443 (save-excursion
14444 (save-restriction
14445 (widen)
14446 (goto-char (point-min))
14447 (while (re-search-forward org-property-start-re nil t)
14448 (setq range (org-get-property-block))
14449 (goto-char (car range))
14450 (while (re-search-forward
14451 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14452 (cdr range) t)
14453 (add-to-list 'rtn (org-match-string-no-properties 1)))
14454 (outline-next-heading))))
14456 (when include-specials
14457 (setq rtn (append org-special-properties rtn)))
14459 (when include-defaults
14460 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14461 (add-to-list 'rtn org-effort-property))
14463 (when include-columns
14464 (save-excursion
14465 (save-restriction
14466 (widen)
14467 (goto-char (point-min))
14468 (while (re-search-forward
14469 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14470 nil t)
14471 (setq cfmt (match-string 2) s 0)
14472 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14473 cfmt s)
14474 (setq s (match-end 0)
14475 p (match-string 1 cfmt))
14476 (unless (or (equal p "ITEM")
14477 (member p org-special-properties))
14478 (add-to-list 'rtn (match-string 1 cfmt))))))))
14480 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14482 (defun org-property-values (key)
14483 "Return a list of all values of property KEY in the current buffer."
14484 (save-excursion
14485 (save-restriction
14486 (widen)
14487 (goto-char (point-min))
14488 (let ((re (org-re-property key))
14489 values)
14490 (while (re-search-forward re nil t)
14491 (add-to-list 'values (org-trim (match-string 1))))
14492 (delete "" values)))))
14494 (defun org-insert-property-drawer ()
14495 "Insert a property drawer into the current entry."
14496 (org-back-to-heading t)
14497 (looking-at org-outline-regexp)
14498 (let ((indent (if org-adapt-indentation
14499 (- (match-end 0) (match-beginning 0))
14501 (beg (point))
14502 (re (concat "^[ \t]*" org-keyword-time-regexp))
14503 end hiddenp)
14504 (outline-next-heading)
14505 (setq end (point))
14506 (goto-char beg)
14507 (while (re-search-forward re end t))
14508 (setq hiddenp (outline-invisible-p))
14509 (end-of-line 1)
14510 (and (equal (char-after) ?\n) (forward-char 1))
14511 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14512 (if (member (match-string 1) '("CLOCK:" ":END:"))
14513 ;; just skip this line
14514 (beginning-of-line 2)
14515 ;; Drawer start, find the end
14516 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14517 (beginning-of-line 1)))
14518 (org-skip-over-state-notes)
14519 (skip-chars-backward " \t\n\r")
14520 (if (eq (char-before) ?*) (forward-char 1))
14521 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14522 (beginning-of-line 0)
14523 (org-indent-to-column indent)
14524 (beginning-of-line 2)
14525 (org-indent-to-column indent)
14526 (beginning-of-line 0)
14527 (if hiddenp
14528 (save-excursion
14529 (org-back-to-heading t)
14530 (hide-entry))
14531 (org-flag-drawer t))))
14533 (defun org-insert-drawer (&optional arg drawer)
14534 "Insert a drawer at point.
14536 Optional argument DRAWER, when non-nil, is a string representing
14537 drawer's name. Otherwise, the user is prompted for a name.
14539 If a region is active, insert the drawer around that region
14540 instead.
14542 Point is left between drawer's boundaries."
14543 (interactive "P")
14544 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14545 "LOGBOOK"))
14546 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14547 ;; internally by Org. They are meant to be inserted
14548 ;; automatically.
14549 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14550 ;; Remove system drawers from list. Note: For some reason,
14551 ;; `org-completing-read' ignores the predicate while
14552 ;; `completing-read' handles it fine.
14553 (drawer (if arg "PROPERTIES"
14554 (or drawer
14555 (completing-read
14556 "Drawer: " org-drawers
14557 (lambda (d) (not (member d system-drawers))))))))
14558 (cond
14559 ;; With C-u, fall back on `org-insert-property-drawer'
14560 (arg (org-insert-property-drawer))
14561 ;; With an active region, insert a drawer at point.
14562 ((not (org-region-active-p))
14563 (progn
14564 (unless (bolp) (insert "\n"))
14565 (insert (format ":%s:\n\n:END:\n" drawer))
14566 (forward-line -2)))
14567 ;; Otherwise, insert the drawer at point
14569 (let ((rbeg (region-beginning))
14570 (rend (copy-marker (region-end))))
14571 (unwind-protect
14572 (progn
14573 (goto-char rbeg)
14574 (beginning-of-line)
14575 (when (save-excursion
14576 (re-search-forward org-outline-regexp-bol rend t))
14577 (error "Drawers cannot contain headlines"))
14578 ;; Position point at the beginning of the first
14579 ;; non-blank line in region. Insert drawer's opening
14580 ;; there, then indent it.
14581 (org-skip-whitespace)
14582 (beginning-of-line)
14583 (insert ":" drawer ":\n")
14584 (forward-line -1)
14585 (indent-for-tab-command)
14586 ;; Move point to the beginning of the first blank line
14587 ;; after the last non-blank line in region. Insert
14588 ;; drawer's closing, then indent it.
14589 (goto-char rend)
14590 (skip-chars-backward " \r\t\n")
14591 (insert "\n:END:")
14592 (indent-for-tab-command)
14593 (unless (eolp) (insert "\n")))
14594 ;; Clear marker, whatever the outcome of insertion is.
14595 (set-marker rend nil)))))))
14597 (defvar org-property-set-functions-alist nil
14598 "Property set function alist.
14599 Each entry should have the following format:
14601 (PROPERTY . READ-FUNCTION)
14603 The read function will be called with the same argument as
14604 `org-completing-read'.")
14606 (defun org-set-property-function (property)
14607 "Get the function that should be used to set PROPERTY.
14608 This is computed according to `org-property-set-functions-alist'."
14609 (or (cdr (assoc property org-property-set-functions-alist))
14610 'org-completing-read))
14612 (defun org-read-property-value (property)
14613 "Read PROPERTY value from user."
14614 (let* ((completion-ignore-case t)
14615 (allowed (org-property-get-allowed-values nil property 'table))
14616 (cur (org-entry-get nil property))
14617 (prompt (concat property " value"
14618 (if (and cur (string-match "\\S-" cur))
14619 (concat " [" cur "]") "") ": "))
14620 (set-function (org-set-property-function property))
14621 (val (if allowed
14622 (funcall set-function prompt allowed nil
14623 (not (get-text-property 0 'org-unrestricted
14624 (caar allowed))))
14625 (let (org-completion-use-ido org-completion-use-iswitchb)
14626 (funcall set-function prompt
14627 (mapcar 'list (org-property-values property))
14628 nil nil "" nil cur)))))
14629 (if (equal val "")
14631 val)))
14633 (defvar org-last-set-property nil)
14634 (defun org-read-property-name ()
14635 "Read a property name."
14636 (let* ((completion-ignore-case t)
14637 (keys (org-buffer-property-keys nil t t))
14638 (default-prop (or (save-excursion
14639 (save-match-data
14640 (beginning-of-line)
14641 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14642 (null (string= (match-string 1) "END"))
14643 (match-string 1))))
14644 org-last-set-property))
14645 (property (org-icompleting-read
14646 (concat "Property"
14647 (if default-prop (concat " [" default-prop "]") "")
14648 ": ")
14649 (mapcar 'list keys)
14650 nil nil nil nil
14651 default-prop
14653 (if (member property keys)
14654 property
14655 (or (cdr (assoc (downcase property)
14656 (mapcar (lambda (x) (cons (downcase x) x))
14657 keys)))
14658 property))))
14660 (defun org-set-property (property value)
14661 "In the current entry, set PROPERTY to VALUE.
14662 When called interactively, this will prompt for a property name, offering
14663 completion on existing and default properties. And then it will prompt
14664 for a value, offering completion either on allowed values (via an inherited
14665 xxx_ALL property) or on existing values in other instances of this property
14666 in the current file."
14667 (interactive (list nil nil))
14668 (let* ((property (or property (org-read-property-name)))
14669 (value (or value (org-read-property-value property)))
14670 (fn (assoc property org-properties-postprocess-alist)))
14671 (setq org-last-set-property property)
14672 ;; Possibly postprocess the inserted value:
14673 (when fn (setq value (funcall (cadr fn) value)))
14674 (unless (equal (org-entry-get nil property) value)
14675 (org-entry-put nil property value))))
14677 (defun org-delete-property (property)
14678 "In the current entry, delete PROPERTY."
14679 (interactive
14680 (let* ((completion-ignore-case t)
14681 (prop (org-icompleting-read "Property: "
14682 (org-entry-properties nil 'standard))))
14683 (list prop)))
14684 (message "Property %s %s" property
14685 (if (org-entry-delete nil property)
14686 "deleted"
14687 "was not present in the entry")))
14689 (defun org-delete-property-globally (property)
14690 "Remove PROPERTY globally, from all entries."
14691 (interactive
14692 (let* ((completion-ignore-case t)
14693 (prop (org-icompleting-read
14694 "Globally remove property: "
14695 (mapcar 'list (org-buffer-property-keys)))))
14696 (list prop)))
14697 (save-excursion
14698 (save-restriction
14699 (widen)
14700 (goto-char (point-min))
14701 (let ((cnt 0))
14702 (while (re-search-forward
14703 (org-re-property property)
14704 nil t)
14705 (setq cnt (1+ cnt))
14706 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14707 (message "Property \"%s\" removed from %d entries" property cnt)))))
14709 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14711 (defun org-compute-property-at-point ()
14712 "Compute the property at point.
14713 This looks for an enclosing column format, extracts the operator and
14714 then applies it to the property in the column format's scope."
14715 (interactive)
14716 (unless (org-at-property-p)
14717 (error "Not at a property"))
14718 (let ((prop (org-match-string-no-properties 2)))
14719 (org-columns-get-format-and-top-level)
14720 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14721 (error "No operator defined for property %s" prop))
14722 (org-columns-compute prop)))
14724 (defvar org-property-allowed-value-functions nil
14725 "Hook for functions supplying allowed values for a specific property.
14726 The functions must take a single argument, the name of the property, and
14727 return a flat list of allowed values. If \":ETC\" is one of
14728 the values, this means that these values are intended as defaults for
14729 completion, but that other values should be allowed too.
14730 The functions must return nil if they are not responsible for this
14731 property.")
14733 (defun org-property-get-allowed-values (pom property &optional table)
14734 "Get allowed values for the property PROPERTY.
14735 When TABLE is non-nil, return an alist that can directly be used for
14736 completion."
14737 (let (vals)
14738 (cond
14739 ((equal property "TODO")
14740 (setq vals (org-with-point-at pom
14741 (append org-todo-keywords-1 '("")))))
14742 ((equal property "PRIORITY")
14743 (let ((n org-lowest-priority))
14744 (while (>= n org-highest-priority)
14745 (push (char-to-string n) vals)
14746 (setq n (1- n)))))
14747 ((member property org-special-properties))
14748 ((setq vals (run-hook-with-args-until-success
14749 'org-property-allowed-value-functions property)))
14751 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14752 (when (and vals (string-match "\\S-" vals))
14753 (setq vals (car (read-from-string (concat "(" vals ")"))))
14754 (setq vals (mapcar (lambda (x)
14755 (cond ((stringp x) x)
14756 ((numberp x) (number-to-string x))
14757 ((symbolp x) (symbol-name x))
14758 (t "???")))
14759 vals)))))
14760 (when (member ":ETC" vals)
14761 (setq vals (remove ":ETC" vals))
14762 (org-add-props (car vals) '(org-unrestricted t)))
14763 (if table (mapcar 'list vals) vals)))
14765 (defun org-property-previous-allowed-value (&optional previous)
14766 "Switch to the next allowed value for this property."
14767 (interactive)
14768 (org-property-next-allowed-value t))
14770 (defun org-property-next-allowed-value (&optional previous)
14771 "Switch to the next allowed value for this property."
14772 (interactive)
14773 (unless (org-at-property-p)
14774 (error "Not at a property"))
14775 (let* ((key (match-string 2))
14776 (value (match-string 3))
14777 (allowed (or (org-property-get-allowed-values (point) key)
14778 (and (member value '("[ ]" "[-]" "[X]"))
14779 '("[ ]" "[X]"))))
14780 nval)
14781 (unless allowed
14782 (error "Allowed values for this property have not been defined"))
14783 (if previous (setq allowed (reverse allowed)))
14784 (if (member value allowed)
14785 (setq nval (car (cdr (member value allowed)))))
14786 (setq nval (or nval (car allowed)))
14787 (if (equal nval value)
14788 (error "Only one allowed value for this property"))
14789 (org-at-property-p)
14790 (replace-match (concat " :" key ": " nval) t t)
14791 (org-indent-line-function)
14792 (beginning-of-line 1)
14793 (skip-chars-forward " \t")
14794 (run-hook-with-args 'org-property-changed-functions key nval)))
14796 (defun org-find-olp (path &optional this-buffer)
14797 "Return a marker pointing to the entry at outline path OLP.
14798 If anything goes wrong, throw an error.
14799 You can wrap this call to catch the error like this:
14801 (condition-case msg
14802 (org-mobile-locate-entry (match-string 4))
14803 (error (nth 1 msg)))
14805 The return value will then be either a string with the error message,
14806 or a marker if everything is OK.
14808 If THIS-BUFFER is set, the outline path does not contain a file,
14809 only headings."
14810 (let* ((file (if this-buffer buffer-file-name (pop path)))
14811 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14812 (level 1)
14813 (lmin 1)
14814 (lmax 1)
14815 limit re end found pos heading cnt flevel)
14816 (unless buffer (error "File not found :%s" file))
14817 (with-current-buffer buffer
14818 (save-excursion
14819 (save-restriction
14820 (widen)
14821 (setq limit (point-max))
14822 (goto-char (point-min))
14823 (while (setq heading (pop path))
14824 (setq re (format org-complex-heading-regexp-format
14825 (regexp-quote heading)))
14826 (setq cnt 0 pos (point))
14827 (while (re-search-forward re end t)
14828 (setq level (- (match-end 1) (match-beginning 1)))
14829 (if (and (>= level lmin) (<= level lmax))
14830 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14831 (when (= cnt 0) (error "Heading not found on level %d: %s"
14832 lmax heading))
14833 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14834 lmax heading))
14835 (goto-char found)
14836 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14837 (setq end (save-excursion (org-end-of-subtree t t))))
14838 (when (org-at-heading-p)
14839 (move-marker (make-marker) (point))))))))
14841 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14842 "Find node HEADING in BUFFER.
14843 Return a marker to the heading if it was found, or nil if not.
14844 If POS-ONLY is set, return just the position instead of a marker.
14846 The heading text must match exact, but it may have a TODO keyword,
14847 a priority cookie and tags in the standard locations."
14848 (with-current-buffer (or buffer (current-buffer))
14849 (save-excursion
14850 (save-restriction
14851 (widen)
14852 (goto-char (point-min))
14853 (let (case-fold-search)
14854 (if (re-search-forward
14855 (format org-complex-heading-regexp-format
14856 (regexp-quote heading)) nil t)
14857 (if pos-only
14858 (match-beginning 0)
14859 (move-marker (make-marker) (match-beginning 0)))))))))
14861 (defun org-find-exact-heading-in-directory (heading &optional dir)
14862 "Find Org node headline HEADING in all .org files in directory DIR.
14863 When the target headline is found, return a marker to this location."
14864 (let ((files (directory-files (or dir default-directory)
14865 nil "\\`[^.#].*\\.org\\'"))
14866 file visiting m buffer)
14867 (catch 'found
14868 (while (setq file (pop files))
14869 (message "trying %s" file)
14870 (setq visiting (org-find-base-buffer-visiting file))
14871 (setq buffer (or visiting (find-file-noselect file)))
14872 (setq m (org-find-exact-headline-in-buffer
14873 heading buffer))
14874 (when (and (not m) (not visiting)) (kill-buffer buffer))
14875 (and m (throw 'found m))))))
14877 (defun org-find-entry-with-id (ident)
14878 "Locate the entry that contains the ID property with exact value IDENT.
14879 IDENT can be a string, a symbol or a number, this function will search for
14880 the string representation of it.
14881 Return the position where this entry starts, or nil if there is no such entry."
14882 (interactive "sID: ")
14883 (let ((id (cond
14884 ((stringp ident) ident)
14885 ((symbol-name ident) (symbol-name ident))
14886 ((numberp ident) (number-to-string ident))
14887 (t (error "IDENT %s must be a string, symbol or number" ident))))
14888 (case-fold-search nil))
14889 (save-excursion
14890 (save-restriction
14891 (widen)
14892 (goto-char (point-min))
14893 (when (re-search-forward
14894 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14895 nil t)
14896 (org-back-to-heading t)
14897 (point))))))
14899 ;;;; Timestamps
14901 (defvar org-last-changed-timestamp nil)
14902 (defvar org-last-inserted-timestamp nil
14903 "The last time stamp inserted with `org-insert-time-stamp'.")
14904 (defvar org-time-was-given) ; dynamically scoped parameter
14905 (defvar org-end-time-was-given) ; dynamically scoped parameter
14906 (defvar org-ts-what) ; dynamically scoped parameter
14908 (defun org-time-stamp (arg &optional inactive)
14909 "Prompt for a date/time and insert a time stamp.
14910 If the user specifies a time like HH:MM, or if this command is called
14911 with a prefix argument, the time stamp will contain date and time.
14912 Otherwise, only the date will be included. All parts of a date not
14913 specified by the user will be filled in from the current date/time.
14914 So if you press just return without typing anything, the time stamp
14915 will represent the current date/time. If there is already a timestamp
14916 at the cursor, it will be modified."
14917 (interactive "P")
14918 (let* ((ts nil)
14919 (default-time
14920 ;; Default time is either today, or, when entering a range,
14921 ;; the range start.
14922 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14923 (save-excursion
14924 (re-search-backward
14925 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14926 (- (point) 20) t)))
14927 (apply 'encode-time (org-parse-time-string (match-string 1)))
14928 (current-time)))
14929 (default-input (and ts (org-get-compact-tod ts)))
14930 (repeater (save-excursion
14931 (save-match-data
14932 (beginning-of-line)
14933 (when (re-search-forward
14934 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14935 (save-excursion (progn (end-of-line) (point))) t)
14936 (match-string 0)))))
14937 org-time-was-given org-end-time-was-given time)
14938 (cond
14939 ((and (org-at-timestamp-p t)
14940 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14941 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14942 (insert "--")
14943 (setq time (let ((this-command this-command))
14944 (org-read-date arg 'totime nil nil
14945 default-time default-input inactive)))
14946 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14947 ((org-at-timestamp-p t)
14948 (setq time (let ((this-command this-command))
14949 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14950 (when (org-at-timestamp-p t) ; just to get the match data
14951 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14952 (replace-match "")
14953 (setq org-last-changed-timestamp
14954 (org-insert-time-stamp
14955 time (or org-time-was-given arg)
14956 inactive nil nil (list org-end-time-was-given)))
14957 (when repeater (goto-char (1- (point))) (insert " " repeater)
14958 (setq org-last-changed-timestamp
14959 (concat (substring org-last-inserted-timestamp 0 -1)
14960 " " repeater ">"))))
14961 (message "Timestamp updated"))
14963 (setq time (let ((this-command this-command))
14964 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14965 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14966 nil nil (list org-end-time-was-given))))))
14968 ;; FIXME: can we use this for something else, like computing time differences?
14969 (defun org-get-compact-tod (s)
14970 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14971 (let* ((t1 (match-string 1 s))
14972 (h1 (string-to-number (match-string 2 s)))
14973 (m1 (string-to-number (match-string 3 s)))
14974 (t2 (and (match-end 4) (match-string 5 s)))
14975 (h2 (and t2 (string-to-number (match-string 6 s))))
14976 (m2 (and t2 (string-to-number (match-string 7 s))))
14977 dh dm)
14978 (if (not t2)
14980 (setq dh (- h2 h1) dm (- m2 m1))
14981 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14982 (concat t1 "+" (number-to-string dh)
14983 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14985 (defun org-time-stamp-inactive (&optional arg)
14986 "Insert an inactive time stamp.
14987 An inactive time stamp is enclosed in square brackets instead of angle
14988 brackets. It is inactive in the sense that it does not trigger agenda entries,
14989 does not link to the calendar and cannot be changed with the S-cursor keys.
14990 So these are more for recording a certain time/date."
14991 (interactive "P")
14992 (org-time-stamp arg 'inactive))
14994 (defvar org-date-ovl (make-overlay 1 1))
14995 (overlay-put org-date-ovl 'face 'org-date-selected)
14996 (org-detach-overlay org-date-ovl)
14998 (defvar org-ans1) ; dynamically scoped parameter
14999 (defvar org-ans2) ; dynamically scoped parameter
15001 (defvar org-plain-time-of-day-regexp) ; defined below
15003 (defvar org-overriding-default-time nil) ; dynamically scoped
15004 (defvar org-read-date-overlay nil)
15005 (defvar org-dcst nil) ; dynamically scoped
15006 (defvar org-read-date-history nil)
15007 (defvar org-read-date-final-answer nil)
15008 (defvar org-read-date-analyze-futurep nil)
15009 (defvar org-read-date-analyze-forced-year nil)
15010 (defvar org-read-date-inactive)
15012 (defun org-read-date (&optional org-with-time to-time from-string prompt
15013 default-time default-input inactive)
15014 "Read a date, possibly a time, and make things smooth for the user.
15015 The prompt will suggest to enter an ISO date, but you can also enter anything
15016 which will at least partially be understood by `parse-time-string'.
15017 Unrecognized parts of the date will default to the current day, month, year,
15018 hour and minute. If this command is called to replace a timestamp at point,
15019 or to enter the second timestamp of a range, the default time is taken
15020 from the existing stamp. Furthermore, the command prefers the future,
15021 so if you are giving a date where the year is not given, and the day-month
15022 combination is already past in the current year, it will assume you
15023 mean next year. For details, see the manual. A few examples:
15025 3-2-5 --> 2003-02-05
15026 feb 15 --> currentyear-02-15
15027 2/15 --> currentyear-02-15
15028 sep 12 9 --> 2009-09-12
15029 12:45 --> today 12:45
15030 22 sept 0:34 --> currentyear-09-22 0:34
15031 12 --> currentyear-currentmonth-12
15032 Fri --> nearest Friday (today or later)
15033 etc.
15035 Furthermore you can specify a relative date by giving, as the *first* thing
15036 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15037 change in days weeks, months, years.
15038 With a single plus or minus, the date is relative to today. With a double
15039 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15040 +4d --> four days from today
15041 +4 --> same as above
15042 +2w --> two weeks from today
15043 ++5 --> five days from default date
15045 The function understands only English month and weekday abbreviations.
15047 While prompting, a calendar is popped up - you can also select the
15048 date with the mouse (button 1). The calendar shows a period of three
15049 months. To scroll it to other months, use the keys `>' and `<'.
15050 If you don't like the calendar, turn it off with
15051 \(setq org-read-date-popup-calendar nil)
15053 With optional argument TO-TIME, the date will immediately be converted
15054 to an internal time.
15055 With an optional argument WITH-TIME, the prompt will suggest to also
15056 insert a time. Note that when WITH-TIME is not set, you can still
15057 enter a time, and this function will inform the calling routine about
15058 this change. The calling routine may then choose to change the format
15059 used to insert the time stamp into the buffer to include the time.
15060 With optional argument FROM-STRING, read from this string instead from
15061 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15062 the time/date that is used for everything that is not specified by the
15063 user."
15064 (require 'parse-time)
15065 (let* ((org-time-stamp-rounding-minutes
15066 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15067 (org-dcst org-display-custom-times)
15068 (ct (org-current-time))
15069 (org-def (or org-overriding-default-time default-time ct))
15070 (org-defdecode (decode-time org-def))
15071 (dummy (progn
15072 (when (< (nth 2 org-defdecode) org-extend-today-until)
15073 (setcar (nthcdr 2 org-defdecode) -1)
15074 (setcar (nthcdr 1 org-defdecode) 59)
15075 (setq org-def (apply 'encode-time org-defdecode)
15076 org-defdecode (decode-time org-def)))))
15077 (calendar-frame-setup nil)
15078 (calendar-setup nil)
15079 (calendar-move-hook nil)
15080 (calendar-view-diary-initially-flag nil)
15081 (calendar-view-holidays-initially-flag nil)
15082 (timestr (format-time-string
15083 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15084 (prompt (concat (if prompt (concat prompt " ") "")
15085 (format "Date+time [%s]: " timestr)))
15086 ans (org-ans0 "") org-ans1 org-ans2 final)
15088 (cond
15089 (from-string (setq ans from-string))
15090 (org-read-date-popup-calendar
15091 (save-excursion
15092 (save-window-excursion
15093 (calendar)
15094 (unwind-protect
15095 (progn
15096 (calendar-forward-day (- (time-to-days org-def)
15097 (calendar-absolute-from-gregorian
15098 (calendar-current-date))))
15099 (org-eval-in-calendar nil t)
15100 (let* ((old-map (current-local-map))
15101 (map (copy-keymap calendar-mode-map))
15102 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15103 (org-defkey map (kbd "RET") 'org-calendar-select)
15104 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15105 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15106 (org-defkey minibuffer-local-map [(meta shift left)]
15107 (lambda () (interactive)
15108 (org-eval-in-calendar '(calendar-backward-month 1))))
15109 (org-defkey minibuffer-local-map [(meta shift right)]
15110 (lambda () (interactive)
15111 (org-eval-in-calendar '(calendar-forward-month 1))))
15112 (org-defkey minibuffer-local-map [(meta shift up)]
15113 (lambda () (interactive)
15114 (org-eval-in-calendar '(calendar-backward-year 1))))
15115 (org-defkey minibuffer-local-map [(meta shift down)]
15116 (lambda () (interactive)
15117 (org-eval-in-calendar '(calendar-forward-year 1))))
15118 (org-defkey minibuffer-local-map [?\e (shift left)]
15119 (lambda () (interactive)
15120 (org-eval-in-calendar '(calendar-backward-month 1))))
15121 (org-defkey minibuffer-local-map [?\e (shift right)]
15122 (lambda () (interactive)
15123 (org-eval-in-calendar '(calendar-forward-month 1))))
15124 (org-defkey minibuffer-local-map [?\e (shift up)]
15125 (lambda () (interactive)
15126 (org-eval-in-calendar '(calendar-backward-year 1))))
15127 (org-defkey minibuffer-local-map [?\e (shift down)]
15128 (lambda () (interactive)
15129 (org-eval-in-calendar '(calendar-forward-year 1))))
15130 (org-defkey minibuffer-local-map [(shift up)]
15131 (lambda () (interactive)
15132 (org-eval-in-calendar '(calendar-backward-week 1))))
15133 (org-defkey minibuffer-local-map [(shift down)]
15134 (lambda () (interactive)
15135 (org-eval-in-calendar '(calendar-forward-week 1))))
15136 (org-defkey minibuffer-local-map [(shift left)]
15137 (lambda () (interactive)
15138 (org-eval-in-calendar '(calendar-backward-day 1))))
15139 (org-defkey minibuffer-local-map [(shift right)]
15140 (lambda () (interactive)
15141 (org-eval-in-calendar '(calendar-forward-day 1))))
15142 (org-defkey minibuffer-local-map ">"
15143 (lambda () (interactive)
15144 (org-eval-in-calendar '(scroll-calendar-left 1))))
15145 (org-defkey minibuffer-local-map "<"
15146 (lambda () (interactive)
15147 (org-eval-in-calendar '(scroll-calendar-right 1))))
15148 (org-defkey minibuffer-local-map "\C-v"
15149 (lambda () (interactive)
15150 (org-eval-in-calendar
15151 '(calendar-scroll-left-three-months 1))))
15152 (org-defkey minibuffer-local-map "\M-v"
15153 (lambda () (interactive)
15154 (org-eval-in-calendar
15155 '(calendar-scroll-right-three-months 1))))
15156 (run-hooks 'org-read-date-minibuffer-setup-hook)
15157 (unwind-protect
15158 (progn
15159 (use-local-map map)
15160 (setq org-read-date-inactive inactive)
15161 (add-hook 'post-command-hook 'org-read-date-display)
15162 (setq org-ans0 (read-string prompt default-input
15163 'org-read-date-history nil))
15164 ;; org-ans0: from prompt
15165 ;; org-ans1: from mouse click
15166 ;; org-ans2: from calendar motion
15167 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15168 (remove-hook 'post-command-hook 'org-read-date-display)
15169 (use-local-map old-map)
15170 (when org-read-date-overlay
15171 (delete-overlay org-read-date-overlay)
15172 (setq org-read-date-overlay nil)))))
15173 (bury-buffer "*Calendar*")))))
15175 (t ; Naked prompt only
15176 (unwind-protect
15177 (setq ans (read-string prompt default-input
15178 'org-read-date-history timestr))
15179 (when org-read-date-overlay
15180 (delete-overlay org-read-date-overlay)
15181 (setq org-read-date-overlay nil)))))
15183 (setq final (org-read-date-analyze ans org-def org-defdecode))
15185 (when org-read-date-analyze-forced-year
15186 (message "Year was forced into %s"
15187 (if org-read-date-force-compatible-dates
15188 "compatible range (1970-2037)"
15189 "range representable on this machine"))
15190 (ding))
15192 ;; One round trip to get rid of 34th of August and stuff like that....
15193 (setq final (decode-time (apply 'encode-time final)))
15195 (setq org-read-date-final-answer ans)
15197 (if to-time
15198 (apply 'encode-time final)
15199 (if (and (boundp 'org-time-was-given) org-time-was-given)
15200 (format "%04d-%02d-%02d %02d:%02d"
15201 (nth 5 final) (nth 4 final) (nth 3 final)
15202 (nth 2 final) (nth 1 final))
15203 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15205 (defvar org-def)
15206 (defvar org-defdecode)
15207 (defvar org-with-time)
15208 (defun org-read-date-display ()
15209 "Display the current date prompt interpretation in the minibuffer."
15210 (when org-read-date-display-live
15211 (when org-read-date-overlay
15212 (delete-overlay org-read-date-overlay))
15213 (when (minibufferp (current-buffer))
15214 (save-excursion
15215 (end-of-line 1)
15216 (while (not (equal (buffer-substring
15217 (max (point-min) (- (point) 4)) (point))
15218 " "))
15219 (insert " ")))
15220 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15221 " " (or org-ans1 org-ans2)))
15222 (org-end-time-was-given nil)
15223 (f (org-read-date-analyze ans org-def org-defdecode))
15224 (fmts (if org-dcst
15225 org-time-stamp-custom-formats
15226 org-time-stamp-formats))
15227 (fmt (if (or org-with-time
15228 (and (boundp 'org-time-was-given) org-time-was-given))
15229 (cdr fmts)
15230 (car fmts)))
15231 (txt (format-time-string fmt (apply 'encode-time f)))
15232 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15233 (txt (concat "=> " txt)))
15234 (when (and org-end-time-was-given
15235 (string-match org-plain-time-of-day-regexp txt))
15236 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15237 org-end-time-was-given
15238 (substring txt (match-end 0)))))
15239 (when org-read-date-analyze-futurep
15240 (setq txt (concat txt " (=>F)")))
15241 (setq org-read-date-overlay
15242 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15243 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15245 (defun org-read-date-analyze (ans org-def org-defdecode)
15246 "Analyze the combined answer of the date prompt."
15247 ;; FIXME: cleanup and comment
15248 (let ((nowdecode (decode-time (current-time)))
15249 delta deltan deltaw deltadef year month day
15250 hour minute second wday pm h2 m2 tl wday1
15251 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15252 (setq org-read-date-analyze-futurep nil
15253 org-read-date-analyze-forced-year nil)
15254 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15255 (setq ans "+0"))
15257 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15258 (setq ans (replace-match "" t t ans)
15259 deltan (car delta)
15260 deltaw (nth 1 delta)
15261 deltadef (nth 2 delta)))
15263 ;; Check if there is an iso week date in there
15264 ;; If yes, store the info and postpone interpreting it until the rest
15265 ;; of the parsing is done
15266 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15267 (setq iso-year (if (match-end 1)
15268 (org-small-year-to-year
15269 (string-to-number (match-string 1 ans))))
15270 iso-weekday (if (match-end 3)
15271 (string-to-number (match-string 3 ans)))
15272 iso-week (string-to-number (match-string 2 ans)))
15273 (setq ans (replace-match "" t t ans)))
15275 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15276 (when (string-match
15277 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15278 (setq year (if (match-end 2)
15279 (string-to-number (match-string 2 ans))
15280 (progn (setq kill-year t)
15281 (string-to-number (format-time-string "%Y"))))
15282 month (string-to-number (match-string 3 ans))
15283 day (string-to-number (match-string 4 ans)))
15284 (if (< year 100) (setq year (+ 2000 year)))
15285 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15286 t nil ans)))
15288 ;; Help matching dotted european dates
15289 (when (string-match
15290 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15291 (setq year (if (match-end 3)
15292 (string-to-number (match-string 3 ans))
15293 (progn (setq kill-year t)
15294 (string-to-number (format-time-string "%Y"))))
15295 day (string-to-number (match-string 1 ans))
15296 month (string-to-number (match-string 2 ans))
15297 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15298 t nil ans)))
15300 ;; Help matching american dates, like 5/30 or 5/30/7
15301 (when (string-match
15302 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15303 (setq year (if (match-end 4)
15304 (string-to-number (match-string 4 ans))
15305 (progn (setq kill-year t)
15306 (string-to-number (format-time-string "%Y"))))
15307 month (string-to-number (match-string 1 ans))
15308 day (string-to-number (match-string 2 ans)))
15309 (if (< year 100) (setq year (+ 2000 year)))
15310 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15311 t nil ans)))
15312 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15313 ;; If there is a time with am/pm, and *no* time without it, we convert
15314 ;; so that matching will be successful.
15315 (loop for i from 1 to 2 do ; twice, for end time as well
15316 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15317 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15318 (setq hour (string-to-number (match-string 1 ans))
15319 minute (if (match-end 3)
15320 (string-to-number (match-string 3 ans))
15322 pm (equal ?p
15323 (string-to-char (downcase (match-string 4 ans)))))
15324 (if (and (= hour 12) (not pm))
15325 (setq hour 0)
15326 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15327 (setq ans (replace-match (format "%02d:%02d" hour minute)
15328 t t ans))))
15330 ;; Check if a time range is given as a duration
15331 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15332 (setq hour (string-to-number (match-string 1 ans))
15333 h2 (+ hour (string-to-number (match-string 3 ans)))
15334 minute (string-to-number (match-string 2 ans))
15335 m2 (+ minute (if (match-end 5) (string-to-number
15336 (match-string 5 ans))0)))
15337 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15338 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15339 t t ans)))
15341 ;; Check if there is a time range
15342 (when (boundp 'org-end-time-was-given)
15343 (setq org-time-was-given nil)
15344 (when (and (string-match org-plain-time-of-day-regexp ans)
15345 (match-end 8))
15346 (setq org-end-time-was-given (match-string 8 ans))
15347 (setq ans (concat (substring ans 0 (match-beginning 7))
15348 (substring ans (match-end 7))))))
15350 (setq tl (parse-time-string ans)
15351 day (or (nth 3 tl) (nth 3 org-defdecode))
15352 month (or (nth 4 tl)
15353 (if (and org-read-date-prefer-future
15354 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15355 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15356 (nth 4 org-defdecode)))
15357 year (or (and (not kill-year) (nth 5 tl))
15358 (if (and org-read-date-prefer-future
15359 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15360 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15361 (nth 5 org-defdecode)))
15362 hour (or (nth 2 tl) (nth 2 org-defdecode))
15363 minute (or (nth 1 tl) (nth 1 org-defdecode))
15364 second (or (nth 0 tl) 0)
15365 wday (nth 6 tl))
15367 (when (and (eq org-read-date-prefer-future 'time)
15368 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15369 (equal day (nth 3 nowdecode))
15370 (equal month (nth 4 nowdecode))
15371 (equal year (nth 5 nowdecode))
15372 (nth 2 tl)
15373 (or (< (nth 2 tl) (nth 2 nowdecode))
15374 (and (= (nth 2 tl) (nth 2 nowdecode))
15375 (nth 1 tl)
15376 (< (nth 1 tl) (nth 1 nowdecode)))))
15377 (setq day (1+ day)
15378 futurep t))
15380 ;; Special date definitions below
15381 (cond
15382 (iso-week
15383 ;; There was an iso week
15384 (require 'cal-iso)
15385 (setq futurep nil)
15386 (setq year (or iso-year year)
15387 day (or iso-weekday wday 1)
15388 wday nil ; to make sure that the trigger below does not match
15389 iso-date (calendar-gregorian-from-absolute
15390 (calendar-absolute-from-iso
15391 (list iso-week day year))))
15392 ; FIXME: Should we also push ISO weeks into the future?
15393 ; (when (and org-read-date-prefer-future
15394 ; (not iso-year)
15395 ; (< (calendar-absolute-from-gregorian iso-date)
15396 ; (time-to-days (current-time))))
15397 ; (setq year (1+ year)
15398 ; iso-date (calendar-gregorian-from-absolute
15399 ; (calendar-absolute-from-iso
15400 ; (list iso-week day year)))))
15401 (setq month (car iso-date)
15402 year (nth 2 iso-date)
15403 day (nth 1 iso-date)))
15404 (deltan
15405 (setq futurep nil)
15406 (unless deltadef
15407 (let ((now (decode-time (current-time))))
15408 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15409 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15410 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15411 ((equal deltaw "m") (setq month (+ month deltan)))
15412 ((equal deltaw "y") (setq year (+ year deltan)))))
15413 ((and wday (not (nth 3 tl)))
15414 (setq futurep nil)
15415 ;; Weekday was given, but no day, so pick that day in the week
15416 ;; on or after the derived date.
15417 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15418 (unless (equal wday wday1)
15419 (setq day (+ day (% (- wday wday1 -7) 7))))))
15420 (if (and (boundp 'org-time-was-given)
15421 (nth 2 tl))
15422 (setq org-time-was-given t))
15423 (if (< year 100) (setq year (+ 2000 year)))
15424 ;; Check of the date is representable
15425 (if org-read-date-force-compatible-dates
15426 (progn
15427 (if (< year 1970)
15428 (setq year 1970 org-read-date-analyze-forced-year t))
15429 (if (> year 2037)
15430 (setq year 2037 org-read-date-analyze-forced-year t)))
15431 (condition-case nil
15432 (ignore (encode-time second minute hour day month year))
15433 (error
15434 (setq year (nth 5 org-defdecode))
15435 (setq org-read-date-analyze-forced-year t))))
15436 (setq org-read-date-analyze-futurep futurep)
15437 (list second minute hour day month year)))
15439 (defvar parse-time-weekdays)
15440 (defun org-read-date-get-relative (s today default)
15441 "Check string S for special relative date string.
15442 TODAY and DEFAULT are internal times, for today and for a default.
15443 Return shift list (N what def-flag)
15444 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15445 N is the number of WHATs to shift.
15446 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15447 the DEFAULT date rather than TODAY."
15448 (require 'parse-time)
15449 (when (and
15450 (string-match
15451 (concat
15452 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15453 "\\([0-9]+\\)?"
15454 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15455 "\\([ \t]\\|$\\)") s)
15456 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15457 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15458 (string-to-char (substring (match-string 1 s) -1))
15459 ?+))
15460 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15461 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15462 (what (if (match-end 3) (match-string 3 s) "d"))
15463 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15464 (date (if rel default today))
15465 (wday (nth 6 (decode-time date)))
15466 delta)
15467 (if wday1
15468 (progn
15469 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15470 (if (= dir ?-) (setq delta (- delta 7)))
15471 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15472 (list delta "d" rel))
15473 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15475 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15476 "Turn a user-specified date into the internal representation.
15477 The internal representation needed by the calendar is (month day year).
15478 This is a wrapper to handle the brain-dead convention in calendar that
15479 user function argument order change dependent on argument order."
15480 (if (boundp 'calendar-date-style)
15481 (cond
15482 ((eq calendar-date-style 'american)
15483 (list arg1 arg2 arg3))
15484 ((eq calendar-date-style 'european)
15485 (list arg2 arg1 arg3))
15486 ((eq calendar-date-style 'iso)
15487 (list arg2 arg3 arg1)))
15488 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15489 (if (org-bound-and-true-p european-calendar-style)
15490 (list arg2 arg1 arg3)
15491 (list arg1 arg2 arg3)))))
15493 (defun org-eval-in-calendar (form &optional keepdate)
15494 "Eval FORM in the calendar window and return to current window.
15495 Also, store the cursor date in variable org-ans2."
15496 (let ((sf (selected-frame))
15497 (sw (selected-window)))
15498 (select-window (get-buffer-window "*Calendar*" t))
15499 (eval form)
15500 (when (and (not keepdate) (calendar-cursor-to-date))
15501 (let* ((date (calendar-cursor-to-date))
15502 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15503 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15504 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15505 (select-window sw)
15506 (org-select-frame-set-input-focus sf)))
15508 (defun org-calendar-select ()
15509 "Return to `org-read-date' with the date currently selected.
15510 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15511 (interactive)
15512 (when (calendar-cursor-to-date)
15513 (let* ((date (calendar-cursor-to-date))
15514 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15515 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15516 (if (active-minibuffer-window) (exit-minibuffer))))
15518 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15519 "Insert a date stamp for the date given by the internal TIME.
15520 WITH-HM means use the stamp format that includes the time of the day.
15521 INACTIVE means use square brackets instead of angular ones, so that the
15522 stamp will not contribute to the agenda.
15523 PRE and POST are optional strings to be inserted before and after the
15524 stamp.
15525 The command returns the inserted time stamp."
15526 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15527 stamp)
15528 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15529 (insert-before-markers (or pre ""))
15530 (when (listp extra)
15531 (setq extra (car extra))
15532 (if (and (stringp extra)
15533 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15534 (setq extra (format "-%02d:%02d"
15535 (string-to-number (match-string 1 extra))
15536 (string-to-number (match-string 2 extra))))
15537 (setq extra nil)))
15538 (when extra
15539 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15540 (insert-before-markers (setq stamp (format-time-string fmt time)))
15541 (insert-before-markers (or post ""))
15542 (setq org-last-inserted-timestamp stamp)))
15544 (defun org-toggle-time-stamp-overlays ()
15545 "Toggle the use of custom time stamp formats."
15546 (interactive)
15547 (setq org-display-custom-times (not org-display-custom-times))
15548 (unless org-display-custom-times
15549 (let ((p (point-min)) (bmp (buffer-modified-p)))
15550 (while (setq p (next-single-property-change p 'display))
15551 (if (and (get-text-property p 'display)
15552 (eq (get-text-property p 'face) 'org-date))
15553 (remove-text-properties
15554 p (setq p (next-single-property-change p 'display))
15555 '(display t))))
15556 (set-buffer-modified-p bmp)))
15557 (if (featurep 'xemacs)
15558 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15559 (org-restart-font-lock)
15560 (setq org-table-may-need-update t)
15561 (if org-display-custom-times
15562 (message "Time stamps are overlaid with custom format")
15563 (message "Time stamp overlays removed")))
15565 (defun org-display-custom-time (beg end)
15566 "Overlay modified time stamp format over timestamp between BEG and END."
15567 (let* ((ts (buffer-substring beg end))
15568 t1 w1 with-hm tf time str w2 (off 0))
15569 (save-match-data
15570 (setq t1 (org-parse-time-string ts t))
15571 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15572 (setq off (- (match-end 0) (match-beginning 0)))))
15573 (setq end (- end off))
15574 (setq w1 (- end beg)
15575 with-hm (and (nth 1 t1) (nth 2 t1))
15576 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15577 time (org-fix-decoded-time t1)
15578 str (org-add-props
15579 (format-time-string
15580 (substring tf 1 -1) (apply 'encode-time time))
15581 nil 'mouse-face 'highlight)
15582 w2 (length str))
15583 (if (not (= w2 w1))
15584 (add-text-properties (1+ beg) (+ 2 beg)
15585 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15586 (if (featurep 'xemacs)
15587 (progn
15588 (put-text-property beg end 'invisible t)
15589 (put-text-property beg end 'end-glyph (make-glyph str)))
15590 (put-text-property beg end 'display str))))
15592 (defun org-translate-time (string)
15593 "Translate all timestamps in STRING to custom format.
15594 But do this only if the variable `org-display-custom-times' is set."
15595 (when org-display-custom-times
15596 (save-match-data
15597 (let* ((start 0)
15598 (re org-ts-regexp-both)
15599 t1 with-hm inactive tf time str beg end)
15600 (while (setq start (string-match re string start))
15601 (setq beg (match-beginning 0)
15602 end (match-end 0)
15603 t1 (save-match-data
15604 (org-parse-time-string (substring string beg end) t))
15605 with-hm (and (nth 1 t1) (nth 2 t1))
15606 inactive (equal (substring string beg (1+ beg)) "[")
15607 tf (funcall (if with-hm 'cdr 'car)
15608 org-time-stamp-custom-formats)
15609 time (org-fix-decoded-time t1)
15610 str (format-time-string
15611 (concat
15612 (if inactive "[" "<") (substring tf 1 -1)
15613 (if inactive "]" ">"))
15614 (apply 'encode-time time))
15615 string (replace-match str t t string)
15616 start (+ start (length str)))))))
15617 string)
15619 (defun org-fix-decoded-time (time)
15620 "Set 0 instead of nil for the first 6 elements of time.
15621 Don't touch the rest."
15622 (let ((n 0))
15623 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15625 (defun org-days-to-time (timestamp-string)
15626 "Difference between TIMESTAMP-STRING and now in days."
15627 (- (time-to-days (org-time-string-to-time timestamp-string))
15628 (time-to-days (current-time))))
15630 (defun org-deadline-close (timestamp-string &optional ndays)
15631 "Is the time in TIMESTAMP-STRING close to the current date?"
15632 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15633 (and (< (org-days-to-time timestamp-string) ndays)
15634 (not (org-entry-is-done-p))))
15636 (defun org-get-wdays (ts)
15637 "Get the deadline lead time appropriate for timestring TS."
15638 (cond
15639 ((<= org-deadline-warning-days 0)
15640 ;; 0 or negative, enforce this value no matter what
15641 (- org-deadline-warning-days))
15642 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15643 ;; lead time is specified.
15644 (floor (* (string-to-number (match-string 1 ts))
15645 (cdr (assoc (match-string 2 ts)
15646 '(("d" . 1) ("w" . 7)
15647 ("m" . 30.4) ("y" . 365.25)))))))
15648 ;; go for the default.
15649 (t org-deadline-warning-days)))
15651 (defun org-calendar-select-mouse (ev)
15652 "Return to `org-read-date' with the date currently selected.
15653 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15654 (interactive "e")
15655 (mouse-set-point ev)
15656 (when (calendar-cursor-to-date)
15657 (let* ((date (calendar-cursor-to-date))
15658 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15659 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15660 (if (active-minibuffer-window) (exit-minibuffer))))
15662 (defun org-check-deadlines (ndays)
15663 "Check if there are any deadlines due or past due.
15664 A deadline is considered due if it happens within `org-deadline-warning-days'
15665 days from today's date. If the deadline appears in an entry marked DONE,
15666 it is not shown. The prefix arg NDAYS can be used to test that many
15667 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15668 (interactive "P")
15669 (let* ((org-warn-days
15670 (cond
15671 ((equal ndays '(4)) 100000)
15672 (ndays (prefix-numeric-value ndays))
15673 (t (abs org-deadline-warning-days))))
15674 (case-fold-search nil)
15675 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15676 (callback
15677 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15679 (message "%d deadlines past-due or due within %d days"
15680 (org-occur regexp nil callback)
15681 org-warn-days)))
15683 (defun org-check-before-date (date)
15684 "Check if there are deadlines or scheduled entries before DATE."
15685 (interactive (list (org-read-date)))
15686 (let ((case-fold-search nil)
15687 (regexp (concat "\\<\\(" org-deadline-string
15688 "\\|" org-scheduled-string
15689 "\\) *<\\([^>]+\\)>"))
15690 (callback
15691 (lambda () (time-less-p
15692 (org-time-string-to-time (match-string 2))
15693 (org-time-string-to-time date)))))
15694 (message "%d entries before %s"
15695 (org-occur regexp nil callback) date)))
15697 (defun org-check-after-date (date)
15698 "Check if there are deadlines or scheduled entries after DATE."
15699 (interactive (list (org-read-date)))
15700 (let ((case-fold-search nil)
15701 (regexp (concat "\\<\\(" org-deadline-string
15702 "\\|" org-scheduled-string
15703 "\\) *<\\([^>]+\\)>"))
15704 (callback
15705 (lambda () (not
15706 (time-less-p
15707 (org-time-string-to-time (match-string 2))
15708 (org-time-string-to-time date))))))
15709 (message "%d entries after %s"
15710 (org-occur regexp nil callback) date)))
15712 (defun org-check-dates-range (start-date end-date)
15713 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15714 (interactive (list (org-read-date nil nil nil "Range starts")
15715 (org-read-date nil nil nil "Range end")))
15716 (let ((case-fold-search nil)
15717 (regexp (concat "\\<\\(" org-deadline-string
15718 "\\|" org-scheduled-string
15719 "\\) *<\\([^>]+\\)>"))
15720 (callback
15721 (lambda ()
15722 (let ((match (match-string 2)))
15723 (and
15724 (not (time-less-p
15725 (org-time-string-to-time match)
15726 (org-time-string-to-time start-date)))
15727 (time-less-p
15728 (org-time-string-to-time match)
15729 (org-time-string-to-time end-date)))))))
15730 (message "%d entries between %s and %s"
15731 (org-occur regexp nil callback) start-date end-date)))
15733 (defun org-evaluate-time-range (&optional to-buffer)
15734 "Evaluate a time range by computing the difference between start and end.
15735 Normally the result is just printed in the echo area, but with prefix arg
15736 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15737 If the time range is actually in a table, the result is inserted into the
15738 next column.
15739 For time difference computation, a year is assumed to be exactly 365
15740 days in order to avoid rounding problems."
15741 (interactive "P")
15743 (org-clock-update-time-maybe)
15744 (save-excursion
15745 (unless (org-at-date-range-p t)
15746 (goto-char (point-at-bol))
15747 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15748 (if (not (org-at-date-range-p t))
15749 (error "Not at a time-stamp range, and none found in current line")))
15750 (let* ((ts1 (match-string 1))
15751 (ts2 (match-string 2))
15752 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15753 (match-end (match-end 0))
15754 (time1 (org-time-string-to-time ts1))
15755 (time2 (org-time-string-to-time ts2))
15756 (t1 (org-float-time time1))
15757 (t2 (org-float-time time2))
15758 (diff (abs (- t2 t1)))
15759 (negative (< (- t2 t1) 0))
15760 ;; (ys (floor (* 365 24 60 60)))
15761 (ds (* 24 60 60))
15762 (hs (* 60 60))
15763 (fy "%dy %dd %02d:%02d")
15764 (fy1 "%dy %dd")
15765 (fd "%dd %02d:%02d")
15766 (fd1 "%dd")
15767 (fh "%02d:%02d")
15768 y d h m align)
15769 (if havetime
15770 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15772 d (floor (/ diff ds)) diff (mod diff ds)
15773 h (floor (/ diff hs)) diff (mod diff hs)
15774 m (floor (/ diff 60)))
15775 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15777 d (floor (+ (/ diff ds) 0.5))
15778 h 0 m 0))
15779 (if (not to-buffer)
15780 (message "%s" (org-make-tdiff-string y d h m))
15781 (if (org-at-table-p)
15782 (progn
15783 (goto-char match-end)
15784 (setq align t)
15785 (and (looking-at " *|") (goto-char (match-end 0))))
15786 (goto-char match-end))
15787 (if (looking-at
15788 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15789 (replace-match ""))
15790 (if negative (insert " -"))
15791 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15792 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15793 (insert " " (format fh h m))))
15794 (if align (org-table-align))
15795 (message "Time difference inserted")))))
15797 (defun org-make-tdiff-string (y d h m)
15798 (let ((fmt "")
15799 (l nil))
15800 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15801 l (push y l)))
15802 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15803 l (push d l)))
15804 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15805 l (push h l)))
15806 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15807 l (push m l)))
15808 (apply 'format fmt (nreverse l))))
15810 (defun org-time-string-to-time (s &optional buffer pos)
15811 (condition-case errdata
15812 (apply 'encode-time (org-parse-time-string s))
15813 (error (error "Bad timestamp `%s'%s\nError was: %s"
15814 s (if (not (and buffer pos))
15816 (format " at %d in buffer `%s'" pos buffer))
15817 (cdr errdata)))))
15819 (defun org-time-string-to-seconds (s)
15820 (org-float-time (org-time-string-to-time s)))
15822 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15823 "Convert a time stamp to an absolute day number.
15824 If there is a specifier for a cyclic time stamp, get the closest date to
15825 DAYNR.
15826 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15827 The variable date is bound by the calendar when this is called."
15828 (cond
15829 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15830 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15831 daynr
15832 (+ daynr 1000)))
15833 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15834 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15835 (time-to-days (current-time))) (match-string 0 s)
15836 prefer show-all))
15837 (t (time-to-days
15838 (condition-case errdata
15839 (apply 'encode-time (org-parse-time-string s))
15840 (error (error "Bad timestamp `%s'%s\nError was: %s"
15841 s (if (not (and buffer pos))
15843 (format " at %d in buffer `%s'" pos buffer))
15844 (cdr errdata))))))))
15846 (defun org-days-to-iso-week (days)
15847 "Return the iso week number."
15848 (require 'cal-iso)
15849 (car (calendar-iso-from-absolute days)))
15851 (defun org-small-year-to-year (year)
15852 "Convert 2-digit years into 4-digit years.
15853 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15854 The year 2000 cannot be abbreviated. Any year larger than 99
15855 is returned unchanged."
15856 (if (< year 38)
15857 (setq year (+ 2000 year))
15858 (if (< year 100)
15859 (setq year (+ 1900 year))))
15860 year)
15862 (defun org-time-from-absolute (d)
15863 "Return the time corresponding to date D.
15864 D may be an absolute day number, or a calendar-type list (month day year)."
15865 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15866 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15868 (defun org-calendar-holiday ()
15869 "List of holidays, for Diary display in Org-mode."
15870 (require 'holidays)
15871 (let ((hl (funcall
15872 (if (fboundp 'calendar-check-holidays)
15873 'calendar-check-holidays 'check-calendar-holidays) date)))
15874 (if hl (mapconcat 'identity hl "; "))))
15876 (defun org-diary-sexp-entry (sexp entry date)
15877 "Process a SEXP diary ENTRY for DATE."
15878 (require 'diary-lib)
15879 (let ((result (if calendar-debug-sexp
15880 (let ((stack-trace-on-error t))
15881 (eval (car (read-from-string sexp))))
15882 (condition-case nil
15883 (eval (car (read-from-string sexp)))
15884 (error
15885 (beep)
15886 (message "Bad sexp at line %d in %s: %s"
15887 (org-current-line)
15888 (buffer-file-name) sexp)
15889 (sleep-for 2))))))
15890 (cond ((stringp result) (split-string result "; "))
15891 ((and (consp result)
15892 (not (consp (cdr result)))
15893 (stringp (cdr result))) (cdr result))
15894 ((and (consp result)
15895 (stringp (car result))) result)
15896 (result entry)
15897 (t nil))))
15899 (defun org-diary-to-ical-string (frombuf)
15900 "Get iCalendar entries from diary entries in buffer FROMBUF.
15901 This uses the icalendar.el library."
15902 (let* ((tmpdir (if (featurep 'xemacs)
15903 (temp-directory)
15904 temporary-file-directory))
15905 (tmpfile (make-temp-name
15906 (expand-file-name "orgics" tmpdir)))
15907 buf rtn b e)
15908 (with-current-buffer frombuf
15909 (icalendar-export-region (point-min) (point-max) tmpfile)
15910 (setq buf (find-buffer-visiting tmpfile))
15911 (set-buffer buf)
15912 (goto-char (point-min))
15913 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15914 (setq b (match-beginning 0)))
15915 (goto-char (point-max))
15916 (if (re-search-backward "^END:VEVENT" nil t)
15917 (setq e (match-end 0)))
15918 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15919 (kill-buffer buf)
15920 (delete-file tmpfile)
15921 rtn))
15923 (defun org-closest-date (start current change prefer show-all)
15924 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15925 When PREFER is `past', return a date that is either CURRENT or past.
15926 When PREFER is `future', return a date that is either CURRENT or future.
15927 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15928 ;; Make the proper lists from the dates
15929 (catch 'exit
15930 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15931 dn dw sday cday n1 n2 n0
15932 d m y y1 y2 date1 date2 nmonths nm ny m2)
15934 (setq start (org-date-to-gregorian start)
15935 current (org-date-to-gregorian
15936 (if show-all
15937 current
15938 (time-to-days (current-time))))
15939 sday (calendar-absolute-from-gregorian start)
15940 cday (calendar-absolute-from-gregorian current))
15942 (if (<= cday sday) (throw 'exit sday))
15944 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15945 (setq dn (string-to-number (match-string 1 change))
15946 dw (cdr (assoc (match-string 2 change) a1)))
15947 (error "Invalid change specifier: %s" change))
15948 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15949 (cond
15950 ((eq dw 'day)
15951 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15952 n2 (+ n1 dn)))
15953 ((eq dw 'year)
15954 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15955 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15956 (setq date1 (list m d y1)
15957 n1 (calendar-absolute-from-gregorian date1)
15958 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15959 n2 (calendar-absolute-from-gregorian date2)))
15960 ((eq dw 'month)
15961 ;; approx number of month between the two dates
15962 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15963 ;; How often does dn fit in there?
15964 (setq d (nth 1 start) m (car start) y (nth 2 start)
15965 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15966 m (+ m nm)
15967 ny (floor (/ m 12))
15968 y (+ y ny)
15969 m (- m (* ny 12)))
15970 (while (> m 12) (setq m (- m 12) y (1+ y)))
15971 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15972 (setq m2 (+ m dn) y2 y)
15973 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15974 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15975 (while (<= n2 cday)
15976 (setq n1 n2 m m2 y y2)
15977 (setq m2 (+ m dn) y2 y)
15978 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15979 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15980 ;; Make sure n1 is the earlier date
15981 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15982 (if show-all
15983 (cond
15984 ((eq prefer 'past) (if (= cday n2) n2 n1))
15985 ((eq prefer 'future) (if (= cday n1) n1 n2))
15986 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15987 (cond
15988 ((eq prefer 'past) (if (= cday n2) n2 n1))
15989 ((eq prefer 'future) (if (= cday n1) n1 n2))
15990 (t (if (= cday n1) n1 n2)))))))
15992 (defun org-date-to-gregorian (date)
15993 "Turn any specification of DATE into a Gregorian date for the calendar."
15994 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15995 ((and (listp date) (= (length date) 3)) date)
15996 ((stringp date)
15997 (setq date (org-parse-time-string date))
15998 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15999 ((listp date)
16000 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16002 (defun org-parse-time-string (s &optional nodefault)
16003 "Parse the standard Org-mode time string.
16004 This should be a lot faster than the normal `parse-time-string'.
16005 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16006 hour and minute fields will be nil if not given."
16007 (if (string-match org-ts-regexp0 s)
16008 (list 0
16009 (if (or (match-beginning 8) (not nodefault))
16010 (string-to-number (or (match-string 8 s) "0")))
16011 (if (or (match-beginning 7) (not nodefault))
16012 (string-to-number (or (match-string 7 s) "0")))
16013 (string-to-number (match-string 4 s))
16014 (string-to-number (match-string 3 s))
16015 (string-to-number (match-string 2 s))
16016 nil nil nil)
16017 (error "Not a standard Org-mode time string: %s" s)))
16019 (defun org-timestamp-up (&optional arg)
16020 "Increase the date item at the cursor by one.
16021 If the cursor is on the year, change the year. If it is on the month,
16022 the day or the time, change that.
16023 With prefix ARG, change by that many units."
16024 (interactive "p")
16025 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16027 (defun org-timestamp-down (&optional arg)
16028 "Decrease the date item at the cursor by one.
16029 If the cursor is on the year, change the year. If it is on the month,
16030 the day or the time, change that.
16031 With prefix ARG, change by that many units."
16032 (interactive "p")
16033 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16035 (defun org-timestamp-up-day (&optional arg)
16036 "Increase the date in the time stamp by one day.
16037 With prefix ARG, change that many days."
16038 (interactive "p")
16039 (if (and (not (org-at-timestamp-p t))
16040 (org-at-heading-p))
16041 (org-todo 'up)
16042 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16044 (defun org-timestamp-down-day (&optional arg)
16045 "Decrease the date in the time stamp by one day.
16046 With prefix ARG, change that many days."
16047 (interactive "p")
16048 (if (and (not (org-at-timestamp-p t))
16049 (org-at-heading-p))
16050 (org-todo 'down)
16051 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16053 (defun org-at-timestamp-p (&optional inactive-ok)
16054 "Determine if the cursor is in or at a timestamp."
16055 (interactive)
16056 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16057 (pos (point))
16058 (ans (or (looking-at tsr)
16059 (save-excursion
16060 (skip-chars-backward "^[<\n\r\t")
16061 (if (> (point) (point-min)) (backward-char 1))
16062 (and (looking-at tsr)
16063 (> (- (match-end 0) pos) -1))))))
16064 (and ans
16065 (boundp 'org-ts-what)
16066 (setq org-ts-what
16067 (cond
16068 ((= pos (match-beginning 0)) 'bracket)
16069 ;; Point is considered to be "on the bracket" whether
16070 ;; it's really on it or right after it.
16071 ((or (= pos (1- (match-end 0)))
16072 (= pos (match-end 0))) 'bracket)
16073 ((org-pos-in-match-range pos 2) 'year)
16074 ((org-pos-in-match-range pos 3) 'month)
16075 ((org-pos-in-match-range pos 7) 'hour)
16076 ((org-pos-in-match-range pos 8) 'minute)
16077 ((or (org-pos-in-match-range pos 4)
16078 (org-pos-in-match-range pos 5)) 'day)
16079 ((and (> pos (or (match-end 8) (match-end 5)))
16080 (< pos (match-end 0)))
16081 (- pos (or (match-end 8) (match-end 5))))
16082 (t 'day))))
16083 ans))
16085 (defun org-toggle-timestamp-type ()
16086 "Toggle the type (<active> or [inactive]) of a time stamp."
16087 (interactive)
16088 (when (org-at-timestamp-p t)
16089 (let ((beg (match-beginning 0)) (end (match-end 0))
16090 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16091 (save-excursion
16092 (goto-char beg)
16093 (while (re-search-forward "[][<>]" end t)
16094 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16095 t t)))
16096 (message "Timestamp is now %sactive"
16097 (if (equal (char-after beg) ?<) "" "in")))))
16099 (defun org-timestamp-change (n &optional what updown)
16100 "Change the date in the time stamp at point.
16101 The date will be changed by N times WHAT. WHAT can be `day', `month',
16102 `year', `minute', `second'. If WHAT is not given, the cursor position
16103 in the timestamp determines what will be changed."
16104 (let ((origin (point)) origin-cat
16105 with-hm inactive
16106 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16107 org-ts-what
16108 extra rem
16109 ts time time0)
16110 (if (not (org-at-timestamp-p t))
16111 (error "Not at a timestamp"))
16112 (if (and (not what) (eq org-ts-what 'bracket))
16113 (org-toggle-timestamp-type)
16114 ;; Point isn't on brackets. Remember the part of the time-stamp
16115 ;; the point was in. Indeed, size of time-stamps may change,
16116 ;; but point must be kept in the same category nonetheless.
16117 (setq origin-cat org-ts-what)
16118 (if (and (not what) (not (eq org-ts-what 'day))
16119 org-display-custom-times
16120 (get-text-property (point) 'display)
16121 (not (get-text-property (1- (point)) 'display)))
16122 (setq org-ts-what 'day))
16123 (setq org-ts-what (or what org-ts-what)
16124 inactive (= (char-after (match-beginning 0)) ?\[)
16125 ts (match-string 0))
16126 (replace-match "")
16127 (if (string-match
16128 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16130 (setq extra (match-string 1 ts)))
16131 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16132 (setq with-hm t))
16133 (setq time0 (org-parse-time-string ts))
16134 (when (and updown
16135 (eq org-ts-what 'minute)
16136 (not current-prefix-arg))
16137 ;; This looks like s-up and s-down. Change by one rounding step.
16138 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16139 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16140 (setcar (cdr time0) (+ (nth 1 time0)
16141 (if (> n 0) (- rem) (- dm rem))))))
16142 (setq time
16143 (encode-time (or (car time0) 0)
16144 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16145 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16146 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16147 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16148 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16149 (nthcdr 6 time0)))
16150 (when (and (member org-ts-what '(hour minute))
16151 extra
16152 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16153 (setq extra (org-modify-ts-extra
16154 extra
16155 (if (eq org-ts-what 'hour) 2 5)
16156 n dm)))
16157 (when (integerp org-ts-what)
16158 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16159 (if (eq what 'calendar)
16160 (let ((cal-date (org-get-date-from-calendar)))
16161 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16162 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16163 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16164 (setcar time0 (or (car time0) 0))
16165 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16166 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16167 (setq time (apply 'encode-time time0))))
16168 ;; Insert the new time-stamp, and ensure point stays in the same
16169 ;; category as before (i.e. not after the last position in that
16170 ;; category).
16171 (let ((pos (point)))
16172 ;; Stay before inserted string. `save-excursion' is of no use.
16173 (setq org-last-changed-timestamp
16174 (org-insert-time-stamp time with-hm inactive nil nil extra))
16175 (goto-char pos))
16176 (save-match-data
16177 (looking-at org-ts-regexp3)
16178 (goto-char (cond
16179 ;; `day' category ends before `hour' if any, or at
16180 ;; the end of the day name.
16181 ((eq origin-cat 'day)
16182 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16183 ((eq origin-cat 'hour) (min (match-end 7) origin))
16184 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16185 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16186 ;; `year' and `month' have both fixed size: point
16187 ;; couldn't have moved into another part.
16188 (t origin))))
16189 ;; Update clock if on a CLOCK line.
16190 (org-clock-update-time-maybe)
16191 ;; Try to recenter the calendar window, if any.
16192 (if (and org-calendar-follow-timestamp-change
16193 (get-buffer-window "*Calendar*" t)
16194 (memq org-ts-what '(day month year)))
16195 (org-recenter-calendar (time-to-days time))))))
16197 (defun org-modify-ts-extra (s pos n dm)
16198 "Change the different parts of the lead-time and repeat fields in timestamp."
16199 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16200 ng h m new rem)
16201 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16202 (cond
16203 ((or (org-pos-in-match-range pos 2)
16204 (org-pos-in-match-range pos 3))
16205 (setq m (string-to-number (match-string 3 s))
16206 h (string-to-number (match-string 2 s)))
16207 (if (org-pos-in-match-range pos 2)
16208 (setq h (+ h n))
16209 (setq n (* dm (org-no-warnings (signum n))))
16210 (when (not (= 0 (setq rem (% m dm))))
16211 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16212 (setq m (+ m n)))
16213 (if (< m 0) (setq m (+ m 60) h (1- h)))
16214 (if (> m 59) (setq m (- m 60) h (1+ h)))
16215 (setq h (min 24 (max 0 h)))
16216 (setq ng 1 new (format "-%02d:%02d" h m)))
16217 ((org-pos-in-match-range pos 6)
16218 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16219 ((org-pos-in-match-range pos 5)
16220 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16222 ((org-pos-in-match-range pos 9)
16223 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16224 ((org-pos-in-match-range pos 8)
16225 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16227 (when ng
16228 (setq s (concat
16229 (substring s 0 (match-beginning ng))
16231 (substring s (match-end ng))))))
16234 (defun org-recenter-calendar (date)
16235 "If the calendar is visible, recenter it to DATE."
16236 (let ((cwin (get-buffer-window "*Calendar*" t)))
16237 (when cwin
16238 (let ((calendar-move-hook nil))
16239 (with-selected-window cwin
16240 (calendar-goto-date (if (listp date) date
16241 (calendar-gregorian-from-absolute date))))))))
16243 (defun org-goto-calendar (&optional arg)
16244 "Go to the Emacs calendar at the current date.
16245 If there is a time stamp in the current line, go to that date.
16246 A prefix ARG can be used to force the current date."
16247 (interactive "P")
16248 (let ((tsr org-ts-regexp) diff
16249 (calendar-move-hook nil)
16250 (calendar-view-holidays-initially-flag nil)
16251 (calendar-view-diary-initially-flag nil))
16252 (if (or (org-at-timestamp-p)
16253 (save-excursion
16254 (beginning-of-line 1)
16255 (looking-at (concat ".*" tsr))))
16256 (let ((d1 (time-to-days (current-time)))
16257 (d2 (time-to-days
16258 (org-time-string-to-time (match-string 1)))))
16259 (setq diff (- d2 d1))))
16260 (calendar)
16261 (calendar-goto-today)
16262 (if (and diff (not arg)) (calendar-forward-day diff))))
16264 (defun org-get-date-from-calendar ()
16265 "Return a list (month day year) of date at point in calendar."
16266 (with-current-buffer "*Calendar*"
16267 (save-match-data
16268 (calendar-cursor-to-date))))
16270 (defun org-date-from-calendar ()
16271 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16272 If there is already a time stamp at the cursor position, update it."
16273 (interactive)
16274 (if (org-at-timestamp-p t)
16275 (org-timestamp-change 0 'calendar)
16276 (let ((cal-date (org-get-date-from-calendar)))
16277 (org-insert-time-stamp
16278 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16280 (defun org-minutes-to-hh:mm-string (m)
16281 "Compute H:MM from a number of minutes."
16282 (let ((h (/ m 60)))
16283 (setq m (- m (* 60 h)))
16284 (format org-time-clocksum-format h m)))
16286 (defun org-hh:mm-string-to-minutes (s)
16287 "Convert a string H:MM to a number of minutes.
16288 If the string is just a number, interpret it as minutes.
16289 In fact, the first hh:mm or number in the string will be taken,
16290 there can be extra stuff in the string.
16291 If no number is found, the return value is 0."
16292 (cond
16293 ((integerp s) s)
16294 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16295 (+ (* (string-to-number (match-string 1 s)) 60)
16296 (string-to-number (match-string 2 s))))
16297 ((string-match "\\([0-9]+\\)" s)
16298 (string-to-number (match-string 1 s)))
16299 (t 0)))
16301 (defcustom org-effort-durations
16302 `(("h" . 60)
16303 ("d" . ,(* 60 8))
16304 ("w" . ,(* 60 8 5))
16305 ("m" . ,(* 60 8 5 4))
16306 ("y" . ,(* 60 8 5 40)))
16307 "Conversion factor to minutes for an effort modifier.
16309 Each entry has the form (MODIFIER . MINUTES).
16311 In an effort string, a number followed by MODIFIER is multiplied
16312 by the specified number of MINUTES to obtain an effort in
16313 minutes.
16315 For example, if the value of this variable is ((\"hours\" . 60)), then an
16316 effort string \"2hours\" is equivalent to 120 minutes."
16317 :group 'org-agenda
16318 :version "24.1"
16319 :type '(alist :key-type (string :tag "Modifier")
16320 :value-type (number :tag "Minutes")))
16322 (defun org-duration-string-to-minutes (s)
16323 "Convert a duration string S to minutes.
16325 A bare number is interpreted as minutes, modifiers can be set by
16326 customizing `org-effort-durations' (which see).
16328 Entries containing a colon are interpreted as H:MM by
16329 `org-hh:mm-string-to-minutes'."
16330 (let ((result 0)
16331 (re (concat "\\([0-9]+\\) *\\("
16332 (regexp-opt (mapcar 'car org-effort-durations))
16333 "\\)")))
16334 (while (string-match re s)
16335 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16336 (string-to-number (match-string 1 s))))
16337 (setq s (replace-match "" nil t s)))
16338 (incf result (org-hh:mm-string-to-minutes s))
16339 result))
16341 ;;;; Files
16343 (defun org-save-all-org-buffers ()
16344 "Save all Org-mode buffers without user confirmation."
16345 (interactive)
16346 (message "Saving all Org-mode buffers...")
16347 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16348 (when (featurep 'org-id) (org-id-locations-save))
16349 (message "Saving all Org-mode buffers... done"))
16351 (defun org-revert-all-org-buffers ()
16352 "Revert all Org-mode buffers.
16353 Prompt for confirmation when there are unsaved changes.
16354 Be sure you know what you are doing before letting this function
16355 overwrite your changes.
16357 This function is useful in a setup where one tracks org files
16358 with a version control system, to revert on one machine after pulling
16359 changes from another. I believe the procedure must be like this:
16361 1. M-x org-save-all-org-buffers
16362 2. Pull changes from the other machine, resolve conflicts
16363 3. M-x org-revert-all-org-buffers"
16364 (interactive)
16365 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16366 (error "Abort"))
16367 (save-excursion
16368 (save-window-excursion
16369 (mapc
16370 (lambda (b)
16371 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16372 (with-current-buffer b buffer-file-name))
16373 (org-pop-to-buffer-same-window b)
16374 (revert-buffer t 'no-confirm)))
16375 (buffer-list))
16376 (when (and (featurep 'org-id) org-id-track-globally)
16377 (org-id-locations-load)))))
16379 ;;;; Agenda files
16381 ;;;###autoload
16382 (defun org-switchb (&optional arg)
16383 "Switch between Org buffers.
16384 With one prefix argument, restrict available buffers to files.
16385 With two prefix arguments, restrict available buffers to agenda files.
16387 Defaults to `iswitchb' for buffer name completion.
16388 Set `org-completion-use-ido' to make it use ido instead."
16389 (interactive "P")
16390 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16391 ((equal arg '(16)) (org-buffer-list 'agenda))
16392 (t (org-buffer-list))))
16393 (org-completion-use-iswitchb org-completion-use-iswitchb)
16394 (org-completion-use-ido org-completion-use-ido))
16395 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16396 (setq org-completion-use-iswitchb t))
16397 (org-pop-to-buffer-same-window
16398 (org-icompleting-read "Org buffer: "
16399 (mapcar 'list (mapcar 'buffer-name blist))
16400 nil t))))
16402 ;;; Define some older names previously used for this functionality
16403 ;;;###autoload
16404 (defalias 'org-ido-switchb 'org-switchb)
16405 ;;;###autoload
16406 (defalias 'org-iswitchb 'org-switchb)
16408 (defun org-buffer-list (&optional predicate exclude-tmp)
16409 "Return a list of Org buffers.
16410 PREDICATE can be `export', `files' or `agenda'.
16412 export restrict the list to Export buffers.
16413 files restrict the list to buffers visiting Org files.
16414 agenda restrict the list to buffers visiting agenda files.
16416 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16417 (let* ((bfn nil)
16418 (agenda-files (and (eq predicate 'agenda)
16419 (mapcar 'file-truename (org-agenda-files t))))
16420 (filter
16421 (cond
16422 ((eq predicate 'files)
16423 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16424 ((eq predicate 'export)
16425 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16426 ((eq predicate 'agenda)
16427 (lambda (b)
16428 (with-current-buffer b
16429 (and (eq major-mode 'org-mode)
16430 (setq bfn (buffer-file-name b))
16431 (member (file-truename bfn) agenda-files)))))
16432 (t (lambda (b) (with-current-buffer b
16433 (or (eq major-mode 'org-mode)
16434 (string-match "\*Org .*Export"
16435 (buffer-name b)))))))))
16436 (delq nil
16437 (mapcar
16438 (lambda(b)
16439 (if (and (funcall filter b)
16440 (or (not exclude-tmp)
16441 (not (string-match "tmp" (buffer-name b)))))
16443 nil))
16444 (buffer-list)))))
16446 (defun org-agenda-files (&optional unrestricted archives)
16447 "Get the list of agenda files.
16448 Optional UNRESTRICTED means return the full list even if a restriction
16449 is currently in place.
16450 When ARCHIVES is t, include all archive files that are really being
16451 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16452 `org-agenda-archives-mode' is t."
16453 (let ((files
16454 (cond
16455 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16456 ((stringp org-agenda-files) (org-read-agenda-file-list))
16457 ((listp org-agenda-files) org-agenda-files)
16458 (t (error "Invalid value of `org-agenda-files'")))))
16459 (setq files (apply 'append
16460 (mapcar (lambda (f)
16461 (if (file-directory-p f)
16462 (directory-files
16463 f t org-agenda-file-regexp)
16464 (list f)))
16465 files)))
16466 (when org-agenda-skip-unavailable-files
16467 (setq files (delq nil
16468 (mapcar (function
16469 (lambda (file)
16470 (and (file-readable-p file) file)))
16471 files))))
16472 (when (or (eq archives t)
16473 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16474 (setq files (org-add-archive-files files)))
16475 files))
16477 (defun org-agenda-file-p (&optional file)
16478 "Return non-nil, if FILE is an agenda file.
16479 If FILE is omitted, use the file associated with the current
16480 buffer."
16481 (member (or file (buffer-file-name))
16482 (org-agenda-files t)))
16484 (defun org-edit-agenda-file-list ()
16485 "Edit the list of agenda files.
16486 Depending on setup, this either uses customize to edit the variable
16487 `org-agenda-files', or it visits the file that is holding the list. In the
16488 latter case, the buffer is set up in a way that saving it automatically kills
16489 the buffer and restores the previous window configuration."
16490 (interactive)
16491 (if (stringp org-agenda-files)
16492 (let ((cw (current-window-configuration)))
16493 (find-file org-agenda-files)
16494 (org-set-local 'org-window-configuration cw)
16495 (org-add-hook 'after-save-hook
16496 (lambda ()
16497 (set-window-configuration
16498 (prog1 org-window-configuration
16499 (kill-buffer (current-buffer))))
16500 (org-install-agenda-files-menu)
16501 (message "New agenda file list installed"))
16502 nil 'local)
16503 (message "%s" (substitute-command-keys
16504 "Edit list and finish with \\[save-buffer]")))
16505 (customize-variable 'org-agenda-files)))
16507 (defun org-store-new-agenda-file-list (list)
16508 "Set new value for the agenda file list and save it correctly."
16509 (if (stringp org-agenda-files)
16510 (let ((fe (org-read-agenda-file-list t)) b u)
16511 (while (setq b (find-buffer-visiting org-agenda-files))
16512 (kill-buffer b))
16513 (with-temp-file org-agenda-files
16514 (insert
16515 (mapconcat
16516 (lambda (f) ;; Keep un-expanded entries.
16517 (if (setq u (assoc f fe))
16518 (cdr u)
16520 list "\n")
16521 "\n")))
16522 (let ((org-mode-hook nil) (org-inhibit-startup t)
16523 (org-insert-mode-line-in-empty-file nil))
16524 (setq org-agenda-files list)
16525 (customize-save-variable 'org-agenda-files org-agenda-files))))
16527 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16528 "Read the list of agenda files from a file.
16529 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16530 filenames, used by `org-store-new-agenda-file-list' to write back
16531 un-expanded file names."
16532 (when (file-directory-p org-agenda-files)
16533 (error "`org-agenda-files' cannot be a single directory"))
16534 (when (stringp org-agenda-files)
16535 (with-temp-buffer
16536 (insert-file-contents org-agenda-files)
16537 (mapcar
16538 (lambda (f)
16539 (let ((e (expand-file-name (substitute-in-file-name f)
16540 org-directory)))
16541 (if pair-with-expansion
16542 (cons e f)
16543 e)))
16544 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16546 ;;;###autoload
16547 (defun org-cycle-agenda-files ()
16548 "Cycle through the files in `org-agenda-files'.
16549 If the current buffer visits an agenda file, find the next one in the list.
16550 If the current buffer does not, find the first agenda file."
16551 (interactive)
16552 (let* ((fs (org-agenda-files t))
16553 (files (append fs (list (car fs))))
16554 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16555 file)
16556 (unless files (error "No agenda files"))
16557 (catch 'exit
16558 (while (setq file (pop files))
16559 (if (equal (file-truename file) tcf)
16560 (when (car files)
16561 (find-file (car files))
16562 (throw 'exit t))))
16563 (find-file (car fs)))
16564 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16566 (defun org-agenda-file-to-front (&optional to-end)
16567 "Move/add the current file to the top of the agenda file list.
16568 If the file is not present in the list, it is added to the front. If it is
16569 present, it is moved there. With optional argument TO-END, add/move to the
16570 end of the list."
16571 (interactive "P")
16572 (let ((org-agenda-skip-unavailable-files nil)
16573 (file-alist (mapcar (lambda (x)
16574 (cons (file-truename x) x))
16575 (org-agenda-files t)))
16576 (ctf (file-truename buffer-file-name))
16577 x had)
16578 (setq x (assoc ctf file-alist) had x)
16580 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16581 (if to-end
16582 (setq file-alist (append (delq x file-alist) (list x)))
16583 (setq file-alist (cons x (delq x file-alist))))
16584 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16585 (org-install-agenda-files-menu)
16586 (message "File %s to %s of agenda file list"
16587 (if had "moved" "added") (if to-end "end" "front"))))
16589 (defun org-remove-file (&optional file)
16590 "Remove current file from the list of files in variable `org-agenda-files'.
16591 These are the files which are being checked for agenda entries.
16592 Optional argument FILE means use this file instead of the current."
16593 (interactive)
16594 (let* ((org-agenda-skip-unavailable-files nil)
16595 (file (or file buffer-file-name))
16596 (true-file (file-truename file))
16597 (afile (abbreviate-file-name file))
16598 (files (delq nil (mapcar
16599 (lambda (x)
16600 (if (equal true-file
16601 (file-truename x))
16602 nil x))
16603 (org-agenda-files t)))))
16604 (if (not (= (length files) (length (org-agenda-files t))))
16605 (progn
16606 (org-store-new-agenda-file-list files)
16607 (org-install-agenda-files-menu)
16608 (message "Removed file: %s" afile))
16609 (message "File was not in list: %s (not removed)" afile))))
16611 (defun org-file-menu-entry (file)
16612 (vector file (list 'find-file file) t))
16614 (defun org-check-agenda-file (file)
16615 "Make sure FILE exists. If not, ask user what to do."
16616 (when (not (file-exists-p file))
16617 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16618 (abbreviate-file-name file))
16619 (let ((r (downcase (read-char-exclusive))))
16620 (cond
16621 ((equal r ?r)
16622 (org-remove-file file)
16623 (throw 'nextfile t))
16624 (t (error "Abort"))))))
16626 (defun org-get-agenda-file-buffer (file)
16627 "Get a buffer visiting FILE. If the buffer needs to be created, add
16628 it to the list of buffers which might be released later."
16629 (let ((buf (org-find-base-buffer-visiting file)))
16630 (if buf
16631 buf ; just return it
16632 ;; Make a new buffer and remember it
16633 (setq buf (find-file-noselect file))
16634 (if buf (push buf org-agenda-new-buffers))
16635 buf)))
16637 (defun org-release-buffers (blist)
16638 "Release all buffers in list, asking the user for confirmation when needed.
16639 When a buffer is unmodified, it is just killed. When modified, it is saved
16640 \(if the user agrees) and then killed."
16641 (let (buf file)
16642 (while (setq buf (pop blist))
16643 (setq file (buffer-file-name buf))
16644 (when (and (buffer-modified-p buf)
16645 file
16646 (y-or-n-p (format "Save file %s? " file)))
16647 (with-current-buffer buf (save-buffer)))
16648 (kill-buffer buf))))
16650 (defun org-prepare-agenda-buffers (files)
16651 "Create buffers for all agenda files, protect archived trees and comments."
16652 (interactive)
16653 (let ((pa '(:org-archived t))
16654 (pc '(:org-comment t))
16655 (pall '(:org-archived t :org-comment t))
16656 (inhibit-read-only t)
16657 (rea (concat ":" org-archive-tag ":"))
16658 bmp file re)
16659 (save-excursion
16660 (save-restriction
16661 (while (setq file (pop files))
16662 (catch 'nextfile
16663 (if (bufferp file)
16664 (set-buffer file)
16665 (org-check-agenda-file file)
16666 (set-buffer (org-get-agenda-file-buffer file)))
16667 (widen)
16668 (setq bmp (buffer-modified-p))
16669 (org-refresh-category-properties)
16670 (setq org-todo-keywords-for-agenda
16671 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16672 (setq org-done-keywords-for-agenda
16673 (append org-done-keywords-for-agenda org-done-keywords))
16674 (setq org-todo-keyword-alist-for-agenda
16675 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16676 (setq org-drawers-for-agenda
16677 (append org-drawers-for-agenda org-drawers))
16678 (setq org-tag-alist-for-agenda
16679 (append org-tag-alist-for-agenda org-tag-alist))
16681 (save-excursion
16682 (remove-text-properties (point-min) (point-max) pall)
16683 (when org-agenda-skip-archived-trees
16684 (goto-char (point-min))
16685 (while (re-search-forward rea nil t)
16686 (if (org-at-heading-p t)
16687 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16688 (goto-char (point-min))
16689 (setq re (format org-heading-keyword-regexp-format
16690 org-comment-string))
16691 (while (re-search-forward re nil t)
16692 (add-text-properties
16693 (match-beginning 0) (org-end-of-subtree t) pc)))
16694 (set-buffer-modified-p bmp)))))
16695 (setq org-todo-keywords-for-agenda
16696 (org-uniquify org-todo-keywords-for-agenda))
16697 (setq org-todo-keyword-alist-for-agenda
16698 (org-uniquify org-todo-keyword-alist-for-agenda)
16699 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16701 ;;;; Embedded LaTeX
16703 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16704 "Keymap for the minor `org-cdlatex-mode'.")
16706 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16707 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16708 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16709 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16710 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16712 (defvar org-cdlatex-texmathp-advice-is-done nil
16713 "Flag remembering if we have applied the advice to texmathp already.")
16715 (define-minor-mode org-cdlatex-mode
16716 "Toggle the minor `org-cdlatex-mode'.
16717 This mode supports entering LaTeX environment and math in LaTeX fragments
16718 in Org-mode.
16719 \\{org-cdlatex-mode-map}"
16720 nil " OCDL" nil
16721 (when org-cdlatex-mode
16722 (require 'cdlatex)
16723 (run-hooks 'cdlatex-mode-hook)
16724 (cdlatex-compute-tables))
16725 (unless org-cdlatex-texmathp-advice-is-done
16726 (setq org-cdlatex-texmathp-advice-is-done t)
16727 (defadvice texmathp (around org-math-always-on activate)
16728 "Always return t in org-mode buffers.
16729 This is because we want to insert math symbols without dollars even outside
16730 the LaTeX math segments. If Orgmode thinks that point is actually inside
16731 an embedded LaTeX fragment, let texmathp do its job.
16732 \\[org-cdlatex-mode-map]"
16733 (interactive)
16734 (let (p)
16735 (cond
16736 ((not (eq major-mode 'org-mode)) ad-do-it)
16737 ((eq this-command 'cdlatex-math-symbol)
16738 (setq ad-return-value t
16739 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16741 (let ((p (org-inside-LaTeX-fragment-p)))
16742 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16743 (setq ad-return-value t
16744 texmathp-why '("Org-mode embedded math" . 0))
16745 (if p ad-do-it)))))))))
16747 (defun turn-on-org-cdlatex ()
16748 "Unconditionally turn on `org-cdlatex-mode'."
16749 (org-cdlatex-mode 1))
16751 (defun org-inside-LaTeX-fragment-p ()
16752 "Test if point is inside a LaTeX fragment.
16753 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16754 sequence appearing also before point.
16755 Even though the matchers for math are configurable, this function assumes
16756 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16757 delimiters are skipped when they have been removed by customization.
16758 The return value is nil, or a cons cell with the delimiter and the
16759 position of this delimiter.
16761 This function does a reasonably good job, but can locally be fooled by
16762 for example currency specifications. For example it will assume being in
16763 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16764 fragments that are properly closed, but during editing, we have to live
16765 with the uncertainty caused by missing closing delimiters. This function
16766 looks only before point, not after."
16767 (catch 'exit
16768 (let ((pos (point))
16769 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16770 (lim (progn
16771 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16772 (point)))
16773 dd-on str (start 0) m re)
16774 (goto-char pos)
16775 (when dodollar
16776 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16777 re (nth 1 (assoc "$" org-latex-regexps)))
16778 (while (string-match re str start)
16779 (cond
16780 ((= (match-end 0) (length str))
16781 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16782 ((= (match-end 0) (- (length str) 5))
16783 (throw 'exit nil))
16784 (t (setq start (match-end 0))))))
16785 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16786 (goto-char pos)
16787 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16788 (and (match-beginning 2) (throw 'exit nil))
16789 ;; count $$
16790 (while (re-search-backward "\\$\\$" lim t)
16791 (setq dd-on (not dd-on)))
16792 (goto-char pos)
16793 (if dd-on (cons "$$" m))))))
16795 (defun org-inside-latex-macro-p ()
16796 "Is point inside a LaTeX macro or its arguments?"
16797 (save-match-data
16798 (org-in-regexp
16799 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16801 (defun org-try-cdlatex-tab ()
16802 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16803 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16804 - inside a LaTeX fragment, or
16805 - after the first word in a line, where an abbreviation expansion could
16806 insert a LaTeX environment."
16807 (when org-cdlatex-mode
16808 (cond
16809 ;; Before any word on the line: No expansion possible.
16810 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16811 ;; Just after first word on the line: Expand it. Make sure it
16812 ;; cannot happen on headlines, though.
16813 ((save-excursion
16814 (skip-chars-backward "a-zA-Z0-9*")
16815 (skip-chars-backward " \t")
16816 (and (bolp) (not (org-at-heading-p))))
16817 (cdlatex-tab) t)
16818 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16820 (defun org-cdlatex-underscore-caret (&optional arg)
16821 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16822 Revert to the normal definition outside of these fragments."
16823 (interactive "P")
16824 (if (org-inside-LaTeX-fragment-p)
16825 (call-interactively 'cdlatex-sub-superscript)
16826 (let (org-cdlatex-mode)
16827 (call-interactively (key-binding (vector last-input-event))))))
16829 (defun org-cdlatex-math-modify (&optional arg)
16830 "Execute `cdlatex-math-modify' in LaTeX fragments.
16831 Revert to the normal definition outside of these fragments."
16832 (interactive "P")
16833 (if (org-inside-LaTeX-fragment-p)
16834 (call-interactively 'cdlatex-math-modify)
16835 (let (org-cdlatex-mode)
16836 (call-interactively (key-binding (vector last-input-event))))))
16838 (defvar org-latex-fragment-image-overlays nil
16839 "List of overlays carrying the images of latex fragments.")
16840 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16842 (defun org-remove-latex-fragment-image-overlays ()
16843 "Remove all overlays with LaTeX fragment images in current buffer."
16844 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16845 (setq org-latex-fragment-image-overlays nil))
16847 (defun org-preview-latex-fragment (&optional subtree)
16848 "Preview the LaTeX fragment at point, or all locally or globally.
16849 If the cursor is in a LaTeX fragment, create the image and overlay
16850 it over the source code. If there is no fragment at point, display
16851 all fragments in the current text, from one headline to the next. With
16852 prefix SUBTREE, display all fragments in the current subtree. With a
16853 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16854 the cursor is before the first headline,
16855 display all fragments in the buffer.
16856 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16857 (interactive "P")
16858 (unless buffer-file-name
16859 (error "Can't preview LaTeX fragment in a non-file buffer"))
16860 (org-remove-latex-fragment-image-overlays)
16861 (save-excursion
16862 (save-restriction
16863 (let (beg end at msg)
16864 (cond
16865 ((or (equal subtree '(16))
16866 (not (save-excursion
16867 (re-search-backward org-outline-regexp-bol nil t))))
16868 (setq beg (point-min) end (point-max)
16869 msg "Creating images for buffer...%s"))
16870 ((equal subtree '(4))
16871 (org-back-to-heading)
16872 (setq beg (point) end (org-end-of-subtree t)
16873 msg "Creating images for subtree...%s"))
16875 (if (setq at (org-inside-LaTeX-fragment-p))
16876 (goto-char (max (point-min) (- (cdr at) 2)))
16877 (org-back-to-heading))
16878 (setq beg (point) end (progn (outline-next-heading) (point))
16879 msg (if at "Creating image...%s"
16880 "Creating images for entry...%s"))))
16881 (message msg "")
16882 (narrow-to-region beg end)
16883 (goto-char beg)
16884 (org-format-latex
16885 (concat "ltxpng/" (file-name-sans-extension
16886 (file-name-nondirectory
16887 buffer-file-name)))
16888 default-directory 'overlays msg at 'forbuffer 'dvipng)
16889 (message msg "done. Use `C-c C-c' to remove images.")))))
16891 (defvar org-latex-regexps
16892 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16893 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16894 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16895 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16896 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16897 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16898 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16899 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16900 "Regular expressions for matching embedded LaTeX.")
16902 (defvar org-export-have-math nil) ;; dynamic scoping
16903 (defun org-format-latex (prefix &optional dir overlays msg at
16904 forbuffer processing-type)
16905 "Replace LaTeX fragments with links to an image, and produce images.
16906 Some of the options can be changed using the variable
16907 `org-format-latex-options'."
16908 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16909 (let* ((prefixnodir (file-name-nondirectory prefix))
16910 (absprefix (expand-file-name prefix dir))
16911 (todir (file-name-directory absprefix))
16912 (opt org-format-latex-options)
16913 (matchers (plist-get opt :matchers))
16914 (re-list org-latex-regexps)
16915 (org-format-latex-header-extra
16916 (plist-get (org-infile-export-plist) :latex-header-extra))
16917 (cnt 0) txt hash link beg end re e checkdir
16918 executables-checked string
16919 m n block-type block linkfile movefile ov)
16920 ;; Check the different regular expressions
16921 (while (setq e (pop re-list))
16922 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16923 block (if block-type "\n\n" ""))
16924 (when (member m matchers)
16925 (goto-char (point-min))
16926 (while (re-search-forward re nil t)
16927 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16928 (not (get-text-property (match-beginning n)
16929 'org-protected))
16930 (or (not overlays)
16931 (not (eq (get-char-property (match-beginning n)
16932 'org-overlay-type)
16933 'org-latex-overlay))))
16934 (setq org-export-have-math t)
16935 (cond
16936 ((eq processing-type 'verbatim)
16937 ;; Leave the text verbatim, just protect it
16938 (add-text-properties (match-beginning n) (match-end n)
16939 '(org-protected t)))
16940 ((eq processing-type 'mathjax)
16941 ;; Prepare for MathJax processing
16942 (setq string (match-string n))
16943 (if (member m '("$" "$1"))
16944 (save-excursion
16945 (delete-region (match-beginning n) (match-end n))
16946 (goto-char (match-beginning n))
16947 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16948 "\\)")
16949 '(org-protected t))))
16950 (add-text-properties (match-beginning n) (match-end n)
16951 '(org-protected t))))
16952 ((eq processing-type 'dvipng)
16953 ;; Process to an image
16954 (setq txt (match-string n)
16955 beg (match-beginning n) end (match-end n)
16956 cnt (1+ cnt))
16957 (let (print-length print-level) ; make sure full list is printed
16958 (setq hash (sha1 (prin1-to-string
16959 (list org-format-latex-header
16960 org-format-latex-header-extra
16961 org-export-latex-default-packages-alist
16962 org-export-latex-packages-alist
16963 org-format-latex-options
16964 forbuffer txt)))
16965 linkfile (format "%s_%s.png" prefix hash)
16966 movefile (format "%s_%s.png" absprefix hash)))
16967 (setq link (concat block "[[file:" linkfile "]]" block))
16968 (if msg (message msg cnt))
16969 (goto-char beg)
16970 (unless checkdir ; make sure the directory exists
16971 (setq checkdir t)
16972 (or (file-directory-p todir) (make-directory todir t)))
16974 (unless executables-checked
16975 (org-check-external-command
16976 "latex" "needed to convert LaTeX fragments to images")
16977 (org-check-external-command
16978 "dvipng" "needed to convert LaTeX fragments to images")
16979 (setq executables-checked t))
16981 (unless (file-exists-p movefile)
16982 (org-create-formula-image
16983 txt movefile opt forbuffer))
16984 (if overlays
16985 (progn
16986 (mapc (lambda (o)
16987 (if (eq (overlay-get o 'org-overlay-type)
16988 'org-latex-overlay)
16989 (delete-overlay o)))
16990 (overlays-in beg end))
16991 (setq ov (make-overlay beg end))
16992 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16993 (if (featurep 'xemacs)
16994 (progn
16995 (overlay-put ov 'invisible t)
16996 (overlay-put
16997 ov 'end-glyph
16998 (make-glyph (vector 'png :file movefile))))
16999 (overlay-put
17000 ov 'display
17001 (list 'image :type 'png :file movefile :ascent 'center)))
17002 (push ov org-latex-fragment-image-overlays)
17003 (goto-char end))
17004 (delete-region beg end)
17005 (insert (org-add-props link
17006 (list 'org-latex-src
17007 (replace-regexp-in-string
17008 "\"" "" txt)
17009 'org-latex-src-embed-type
17010 (if block-type 'paragraph 'character))))))
17011 ((eq processing-type 'mathml)
17012 ;; Process to MathML
17013 (unless executables-checked
17014 (unless (save-match-data (org-format-latex-mathml-available-p))
17015 (error "LaTeX to MathML converter not configured"))
17016 (setq executables-checked t))
17017 (setq txt (match-string n)
17018 beg (match-beginning n) end (match-end n)
17019 cnt (1+ cnt))
17020 (if msg (message msg cnt))
17021 (goto-char beg)
17022 (delete-region beg end)
17023 (insert (org-format-latex-as-mathml
17024 txt block-type prefix dir)))
17026 (error "Unknown conversion type %s for latex fragments"
17027 processing-type)))))))))
17029 (defun org-create-math-formula (latex-frag &optional mathml-file)
17030 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17031 Use `org-latex-to-mathml-convert-command'. If the conversion is
17032 sucessful, return the portion between \"<math...> </math>\"
17033 elements otherwise return nil. When MATHML-FILE is specified,
17034 write the results in to that file. When invoked as an
17035 interactive command, prompt for LATEX-FRAG, with initial value
17036 set to the current active region and echo the results for user
17037 inspection."
17038 (interactive (list (let ((frag (when (region-active-p)
17039 (buffer-substring-no-properties
17040 (region-beginning) (region-end)))))
17041 (read-string "LaTeX Fragment: " frag nil frag))))
17042 (unless latex-frag (error "Invalid latex-frag"))
17043 (let* ((tmp-in-file (file-relative-name
17044 (make-temp-name (expand-file-name "ltxmathml-in"))))
17045 (ignore (write-region latex-frag nil tmp-in-file))
17046 (tmp-out-file (file-relative-name
17047 (make-temp-name (expand-file-name "ltxmathml-out"))))
17048 (cmd (format-spec
17049 org-latex-to-mathml-convert-command
17050 `((?j . ,(shell-quote-argument
17051 (expand-file-name org-latex-to-mathml-jar-file)))
17052 (?I . ,(shell-quote-argument tmp-in-file))
17053 (?o . ,(shell-quote-argument tmp-out-file)))))
17054 mathml shell-command-output)
17055 (when (org-called-interactively-p 'any)
17056 (unless (org-format-latex-mathml-available-p)
17057 (error "LaTeX to MathML converter not configured")))
17058 (message "Running %s" cmd)
17059 (setq shell-command-output (shell-command-to-string cmd))
17060 (setq mathml
17061 (when (file-readable-p tmp-out-file)
17062 (with-current-buffer (find-file-noselect tmp-out-file t)
17063 (goto-char (point-min))
17064 (when (re-search-forward
17065 (concat
17066 (regexp-quote
17067 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17068 "\\(.\\|\n\\)*"
17069 (regexp-quote "</math>")) nil t)
17070 (prog1 (match-string 0) (kill-buffer))))))
17071 (cond
17072 (mathml
17073 (setq mathml
17074 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17075 (when mathml-file
17076 (write-region mathml nil mathml-file))
17077 (when (org-called-interactively-p 'any)
17078 (message mathml)))
17079 ((message "LaTeX to MathML conversion failed")
17080 (message shell-command-output)))
17081 (delete-file tmp-in-file)
17082 (when (file-exists-p tmp-out-file)
17083 (delete-file tmp-out-file))
17084 mathml))
17086 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17087 prefix &optional dir)
17088 "Use `org-create-math-formula' but check local cache first."
17089 (let* ((absprefix (expand-file-name prefix dir))
17090 (print-length nil) (print-level nil)
17091 (formula-id (concat
17092 "formula-"
17093 (sha1
17094 (prin1-to-string
17095 (list latex-frag
17096 org-latex-to-mathml-convert-command)))))
17097 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17098 (formula-cache-dir (file-name-directory formula-cache)))
17100 (unless (file-directory-p formula-cache-dir)
17101 (make-directory formula-cache-dir t))
17103 (unless (file-exists-p formula-cache)
17104 (org-create-math-formula latex-frag formula-cache))
17106 (if (file-exists-p formula-cache)
17107 ;; Successful conversion. Return the link to MathML file.
17108 (org-add-props
17109 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17110 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17111 'org-latex-src-embed-type (if latex-frag-type
17112 'paragraph 'character)))
17113 ;; Failed conversion. Return the LaTeX fragment verbatim
17114 (add-text-properties
17115 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17116 latex-frag)))
17118 ;; This function borrows from Ganesh Swami's latex2png.el
17119 (defun org-create-formula-image (string tofile options buffer)
17120 "This calls dvipng."
17121 (require 'org-latex)
17122 (let* ((tmpdir (if (featurep 'xemacs)
17123 (temp-directory)
17124 temporary-file-directory))
17125 (texfilebase (make-temp-name
17126 (expand-file-name "orgtex" tmpdir)))
17127 (texfile (concat texfilebase ".tex"))
17128 (dvifile (concat texfilebase ".dvi"))
17129 (pngfile (concat texfilebase ".png"))
17130 (fnh (if (featurep 'xemacs)
17131 (font-height (face-font 'default))
17132 (face-attribute 'default :height nil)))
17133 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17134 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17135 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17136 "Black"))
17137 (bg (or (plist-get options (if buffer :background :html-background))
17138 "Transparent")))
17139 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17140 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17141 (with-temp-file texfile
17142 (insert (org-splice-latex-header
17143 org-format-latex-header
17144 org-export-latex-default-packages-alist
17145 org-export-latex-packages-alist t
17146 org-format-latex-header-extra))
17147 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17148 (require 'org-latex)
17149 (org-export-latex-fix-inputenc))
17150 (let ((dir default-directory))
17151 (condition-case nil
17152 (progn
17153 (cd tmpdir)
17154 (call-process "latex" nil nil nil texfile))
17155 (error nil))
17156 (cd dir))
17157 (if (not (file-exists-p dvifile))
17158 (progn (message "Failed to create dvi file from %s" texfile) nil)
17159 (condition-case nil
17160 (if (featurep 'xemacs)
17161 (call-process "dvipng" nil nil nil
17162 "-fg" fg "-bg" bg
17163 "-T" "tight"
17164 "-o" pngfile
17165 dvifile)
17166 (call-process "dvipng" nil nil nil
17167 "-fg" fg "-bg" bg
17168 "-D" dpi
17169 ;;"-x" scale "-y" scale
17170 "-T" "tight"
17171 "-o" pngfile
17172 dvifile))
17173 (error nil))
17174 (if (not (file-exists-p pngfile))
17175 (if org-format-latex-signal-error
17176 (error "Failed to create png file from %s" texfile)
17177 (message "Failed to create png file from %s" texfile)
17178 nil)
17179 ;; Use the requested file name and clean up
17180 (copy-file pngfile tofile 'replace)
17181 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17182 (delete-file (concat texfilebase e)))
17183 pngfile))))
17185 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17186 "Fill a LaTeX header template TPL.
17187 In the template, the following place holders will be recognized:
17189 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17190 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17191 [PACKAGES] \\usepackage statements for PKG
17192 [NO-PACKAGES] do not include PKG
17193 [EXTRA] the string EXTRA
17194 [NO-EXTRA] do not include EXTRA
17196 For backward compatibility, if both the positive and the negative place
17197 holder is missing, the positive one (without the \"NO-\") will be
17198 assumed to be present at the end of the template.
17199 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17200 EXTRA is a string.
17201 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17202 (let (rpl (end ""))
17203 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17204 (setq rpl (if (or (match-end 1) (not def-pkg))
17205 "" (org-latex-packages-to-string def-pkg snippets-p t))
17206 tpl (replace-match rpl t t tpl))
17207 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17209 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17210 (setq rpl (if (or (match-end 1) (not pkg))
17211 "" (org-latex-packages-to-string pkg snippets-p t))
17212 tpl (replace-match rpl t t tpl))
17213 (if pkg (setq end
17214 (concat end "\n"
17215 (org-latex-packages-to-string pkg snippets-p)))))
17217 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17218 (setq rpl (if (or (match-end 1) (not extra))
17219 "" (concat extra "\n"))
17220 tpl (replace-match rpl t t tpl))
17221 (if (and extra (string-match "\\S-" extra))
17222 (setq end (concat end "\n" extra))))
17224 (if (string-match "\\S-" end)
17225 (concat tpl "\n" end)
17226 tpl)))
17228 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17229 "Turn an alist of packages into a string with the \\usepackage macros."
17230 (setq pkg (mapconcat (lambda(p)
17231 (cond
17232 ((stringp p) p)
17233 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17234 (format "%% Package %s omitted" (cadr p)))
17235 ((equal "" (car p))
17236 (format "\\usepackage{%s}" (cadr p)))
17238 (format "\\usepackage[%s]{%s}"
17239 (car p) (cadr p)))))
17241 "\n"))
17242 (if newline (concat pkg "\n") pkg))
17244 (defun org-dvipng-color (attr)
17245 "Return an rgb color specification for dvipng."
17246 (apply 'format "rgb %s %s %s"
17247 (mapcar 'org-normalize-color
17248 (if (featurep 'xemacs)
17249 (color-rgb-components
17250 (face-property 'default
17251 (cond ((eq attr :foreground) 'foreground)
17252 ((eq attr :background) 'background))))
17253 (color-values (face-attribute 'default attr nil))))))
17255 (defun org-normalize-color (value)
17256 "Return string to be used as color value for an RGB component."
17257 (format "%g" (/ value 65535.0)))
17259 ;; Image display
17262 (defvar org-inline-image-overlays nil)
17263 (make-variable-buffer-local 'org-inline-image-overlays)
17265 (defun org-toggle-inline-images (&optional include-linked)
17266 "Toggle the display of inline images.
17267 INCLUDE-LINKED is passed to `org-display-inline-images'."
17268 (interactive "P")
17269 (if org-inline-image-overlays
17270 (progn
17271 (org-remove-inline-images)
17272 (message "Inline image display turned off"))
17273 (org-display-inline-images include-linked)
17274 (if org-inline-image-overlays
17275 (message "%d images displayed inline"
17276 (length org-inline-image-overlays))
17277 (message "No images to display inline"))))
17279 (defun org-display-inline-images (&optional include-linked refresh beg end)
17280 "Display inline images.
17281 Normally only links without a description part are inlined, because this
17282 is how it will work for export. When INCLUDE-LINKED is set, also links
17283 with a description part will be inlined. This can be nice for a quick
17284 look at those images, but it does not reflect what exported files will look
17285 like.
17286 When REFRESH is set, refresh existing images between BEG and END.
17287 This will create new image displays only if necessary.
17288 BEG and END default to the buffer boundaries."
17289 (interactive "P")
17290 (unless refresh
17291 (org-remove-inline-images)
17292 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17293 (save-excursion
17294 (save-restriction
17295 (widen)
17296 (setq beg (or beg (point-min)) end (or end (point-max)))
17297 (goto-char beg)
17298 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17299 (substring (org-image-file-name-regexp) 0 -2)
17300 "\\)\\]" (if include-linked "" "\\]")))
17301 old file ov img)
17302 (while (re-search-forward re end t)
17303 (setq old (get-char-property-and-overlay (match-beginning 1)
17304 'org-image-overlay))
17305 (setq file (expand-file-name
17306 (concat (or (match-string 3) "") (match-string 4))))
17307 (when (file-exists-p file)
17308 (if (and (car-safe old) refresh)
17309 (image-refresh (overlay-get (cdr old) 'display))
17310 (setq img (save-match-data (create-image file)))
17311 (when img
17312 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17313 (overlay-put ov 'display img)
17314 (overlay-put ov 'face 'default)
17315 (overlay-put ov 'org-image-overlay t)
17316 (overlay-put ov 'modification-hooks
17317 (list 'org-display-inline-modification-hook))
17318 (push ov org-inline-image-overlays)))))))))
17320 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17321 "Remove inline-display overlay if a corresponding region is modified."
17322 (let ((inhibit-modification-hooks t))
17323 (when (and ov after)
17324 (delete ov org-inline-image-overlays)
17325 (delete-overlay ov))))
17327 (defun org-remove-inline-images ()
17328 "Remove inline display of images."
17329 (interactive)
17330 (mapc 'delete-overlay org-inline-image-overlays)
17331 (setq org-inline-image-overlays nil))
17333 ;;;; Key bindings
17335 ;; Outline functions from `outline-mode-prefix-map'
17336 ;; that can be remapped in Org:
17337 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17338 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17339 (define-key org-mode-map [remap outline-forward-same-level]
17340 'org-forward-same-level)
17341 (define-key org-mode-map [remap outline-backward-same-level]
17342 'org-backward-same-level)
17343 (define-key org-mode-map [remap show-branches]
17344 'org-kill-note-or-show-branches)
17345 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17346 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17347 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17349 ;; Outline functions from `outline-mode-prefix-map'
17350 ;; that can not be remapped in Org:
17351 ;; - the column "key binding" shows whether the Outline function is still
17352 ;; available in Org mode on the same key that it has been bound to in
17353 ;; Outline mode:
17354 ;; - "overridden": key used for a different functionality in Org mode
17355 ;; - else: key still bound to the same Outline function in Org mode
17356 ;; | Outline function | key binding | Org replacement |
17357 ;; |------------------------------------+-------------+-----------------------|
17358 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17359 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17360 ;; | `show-children' | `C-c C-i' | visibility cycling |
17361 ;; | `hide-subtree' | overridden | visibility cycling |
17362 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17363 ;; | `hide-body' | overridden | no replacement |
17364 ;; | `show-all' | overridden | no replacement |
17365 ;; | `hide-entry' | overridden | visibility cycling |
17366 ;; | `show-entry' | overridden | no replacement |
17367 ;; | `hide-leaves' | overridden | no replacement |
17368 ;; | `hide-sublevels' | overridden | no replacement |
17369 ;; | `hide-other' | overridden | no replacement |
17370 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17371 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17373 ;; Make `C-c C-x' a prefix key
17374 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17376 ;; TAB key with modifiers
17377 (org-defkey org-mode-map "\C-i" 'org-cycle)
17378 (org-defkey org-mode-map [(tab)] 'org-cycle)
17379 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17380 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17381 ;; The following line is necessary under Suse GNU/Linux
17382 (unless (featurep 'xemacs)
17383 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17384 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17385 (define-key org-mode-map [backtab] 'org-shifttab)
17387 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17388 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17389 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17391 ;; Cursor keys with modifiers
17392 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17393 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17394 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17395 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17397 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17398 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17399 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17400 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17402 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17403 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17404 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17405 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17407 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17408 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17409 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17410 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17412 ;; Babel keys
17413 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17414 (mapc (lambda (pair)
17415 (define-key org-babel-map (car pair) (cdr pair)))
17416 org-babel-key-bindings)
17418 ;;; Extra keys for tty access.
17419 ;; We only set them when really needed because otherwise the
17420 ;; menus don't show the simple keys
17422 (when (or org-use-extra-keys
17423 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17424 (not window-system))
17425 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17426 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17427 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17428 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17429 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17430 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17431 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17432 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17433 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17434 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17435 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17436 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17437 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17438 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17439 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17440 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17441 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17442 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17443 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17444 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17445 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17446 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17447 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17448 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17449 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17450 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17451 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17452 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17454 ;; All the other keys
17456 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17457 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17458 (if (boundp 'narrow-map)
17459 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17460 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17461 (if (boundp 'narrow-map)
17462 (org-defkey narrow-map "b" 'org-narrow-to-block)
17463 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17464 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17465 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17466 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17467 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17468 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17469 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17470 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17471 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17472 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17473 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17474 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17475 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17476 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17477 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17478 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17479 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17480 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17481 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17482 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17483 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17484 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17485 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17486 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17487 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17488 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17489 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17490 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17491 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17492 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17493 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17494 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17495 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17496 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17497 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17498 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17499 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17500 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17501 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17502 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17503 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17504 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17505 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17506 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17507 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17508 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17509 (org-defkey org-mode-map "\C-c^" 'org-sort)
17510 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17511 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17512 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17513 (org-defkey org-mode-map "\C-m" 'org-return)
17514 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17515 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17516 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17517 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17518 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17519 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17520 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17521 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17522 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17523 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17524 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17525 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17526 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17527 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17528 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17529 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17530 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17531 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17532 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17533 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17534 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17535 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17536 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17538 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17539 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17540 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17541 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17543 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17544 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17545 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17546 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17547 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17548 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17549 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17550 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17551 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17552 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17553 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17554 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17555 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17556 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17557 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17558 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17559 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17560 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17562 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17563 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17564 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17565 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17566 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17568 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17570 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17572 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17573 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17575 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17578 (when (featurep 'xemacs)
17579 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17582 (defconst org-speed-commands-default
17584 ("Outline Navigation")
17585 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17586 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17587 ("f" . (org-speed-move-safe 'org-forward-same-level))
17588 ("b" . (org-speed-move-safe 'org-backward-same-level))
17589 ("u" . (org-speed-move-safe 'outline-up-heading))
17590 ("j" . org-goto)
17591 ("g" . (org-refile t))
17592 ("Outline Visibility")
17593 ("c" . org-cycle)
17594 ("C" . org-shifttab)
17595 (" " . org-display-outline-path)
17596 ("Outline Structure Editing")
17597 ("U" . org-shiftmetaup)
17598 ("D" . org-shiftmetadown)
17599 ("r" . org-metaright)
17600 ("l" . org-metaleft)
17601 ("R" . org-shiftmetaright)
17602 ("L" . org-shiftmetaleft)
17603 ("i" . (progn (forward-char 1) (call-interactively
17604 'org-insert-heading-respect-content)))
17605 ("^" . org-sort)
17606 ("w" . org-refile)
17607 ("a" . org-archive-subtree-default-with-confirmation)
17608 ("." . org-mark-subtree)
17609 ("Clock Commands")
17610 ("I" . org-clock-in)
17611 ("O" . org-clock-out)
17612 ("Meta Data Editing")
17613 ("t" . org-todo)
17614 ("0" . (org-priority ?\ ))
17615 ("1" . (org-priority ?A))
17616 ("2" . (org-priority ?B))
17617 ("3" . (org-priority ?C))
17618 (";" . org-set-tags-command)
17619 ("e" . org-set-effort)
17620 ("Agenda Views etc")
17621 ("v" . org-agenda)
17622 ("/" . org-sparse-tree)
17623 ("Misc")
17624 ("o" . org-open-at-point)
17625 ("?" . org-speed-command-help)
17626 ("<" . (org-agenda-set-restriction-lock 'subtree))
17627 (">" . (org-agenda-remove-restriction-lock))
17629 "The default speed commands.")
17631 (defun org-print-speed-command (e)
17632 (if (> (length (car e)) 1)
17633 (progn
17634 (princ "\n")
17635 (princ (car e))
17636 (princ "\n")
17637 (princ (make-string (length (car e)) ?-))
17638 (princ "\n"))
17639 (princ (car e))
17640 (princ " ")
17641 (if (symbolp (cdr e))
17642 (princ (symbol-name (cdr e)))
17643 (prin1 (cdr e)))
17644 (princ "\n")))
17646 (defun org-speed-command-help ()
17647 "Show the available speed commands."
17648 (interactive)
17649 (if (not org-use-speed-commands)
17650 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17651 (with-output-to-temp-buffer "*Help*"
17652 (princ "User-defined Speed commands\n===========================\n")
17653 (mapc 'org-print-speed-command org-speed-commands-user)
17654 (princ "\n")
17655 (princ "Built-in Speed commands\n=======================\n")
17656 (mapc 'org-print-speed-command org-speed-commands-default))
17657 (with-current-buffer "*Help*"
17658 (setq truncate-lines t))))
17660 (defun org-speed-move-safe (cmd)
17661 "Execute CMD, but make sure that the cursor always ends up in a headline.
17662 If not, return to the original position and throw an error."
17663 (interactive)
17664 (let ((pos (point)))
17665 (call-interactively cmd)
17666 (unless (and (bolp) (org-at-heading-p))
17667 (goto-char pos)
17668 (error "Boundary reached while executing %s" cmd))))
17670 (defvar org-self-insert-command-undo-counter 0)
17672 (defvar org-table-auto-blank-field) ; defined in org-table.el
17673 (defvar org-speed-command nil)
17675 (defun org-speed-command-default-hook (keys)
17676 "Hook for activating single-letter speed commands.
17677 `org-speed-commands-default' specifies a minimal command set.
17678 Use `org-speed-commands-user' for further customization."
17679 (when (or (and (bolp) (looking-at org-outline-regexp))
17680 (and (functionp org-use-speed-commands)
17681 (funcall org-use-speed-commands)))
17682 (cdr (assoc keys (append org-speed-commands-user
17683 org-speed-commands-default)))))
17685 (defun org-babel-speed-command-hook (keys)
17686 "Hook for activating single-letter code block commands."
17687 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17688 (cdr (assoc keys org-babel-key-bindings))))
17690 (defcustom org-speed-command-hook
17691 '(org-speed-command-default-hook org-babel-speed-command-hook)
17692 "Hook for activating speed commands at strategic locations.
17693 Hook functions are called in sequence until a valid handler is
17694 found.
17696 Each hook takes a single argument, a user-pressed command key
17697 which is also a `self-insert-command' from the global map.
17699 Within the hook, examine the cursor position and the command key
17700 and return nil or a valid handler as appropriate. Handler could
17701 be one of an interactive command, a function, or a form.
17703 Set `org-use-speed-commands' to non-nil value to enable this
17704 hook. The default setting is `org-speed-command-default-hook'."
17705 :group 'org-structure
17706 :version "24.1"
17707 :type 'hook)
17709 (defun org-self-insert-command (N)
17710 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17711 If the cursor is in a table looking at whitespace, the whitespace is
17712 overwritten, and the table is not marked as requiring realignment."
17713 (interactive "p")
17714 (org-check-before-invisible-edit 'insert)
17715 (cond
17716 ((and org-use-speed-commands
17717 (setq org-speed-command
17718 (run-hook-with-args-until-success
17719 'org-speed-command-hook (this-command-keys))))
17720 (cond
17721 ((commandp org-speed-command)
17722 (setq this-command org-speed-command)
17723 (call-interactively org-speed-command))
17724 ((functionp org-speed-command)
17725 (funcall org-speed-command))
17726 ((and org-speed-command (listp org-speed-command))
17727 (eval org-speed-command))
17728 (t (let (org-use-speed-commands)
17729 (call-interactively 'org-self-insert-command)))))
17730 ((and
17731 (org-table-p)
17732 (progn
17733 ;; check if we blank the field, and if that triggers align
17734 (and (featurep 'org-table) org-table-auto-blank-field
17735 (member last-command
17736 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17737 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17738 ;; got extra space, this field does not determine column width
17739 (let (org-table-may-need-update) (org-table-blank-field))
17740 ;; no extra space, this field may determine column width
17741 (org-table-blank-field)))
17743 (eq N 1)
17744 (looking-at "[^|\n]* |"))
17745 (let (org-table-may-need-update)
17746 (goto-char (1- (match-end 0)))
17747 (backward-delete-char 1)
17748 (goto-char (match-beginning 0))
17749 (self-insert-command N)))
17751 (setq org-table-may-need-update t)
17752 (self-insert-command N)
17753 (org-fix-tags-on-the-fly)
17754 (if org-self-insert-cluster-for-undo
17755 (if (not (eq last-command 'org-self-insert-command))
17756 (setq org-self-insert-command-undo-counter 1)
17757 (if (>= org-self-insert-command-undo-counter 20)
17758 (setq org-self-insert-command-undo-counter 1)
17759 (and (> org-self-insert-command-undo-counter 0)
17760 buffer-undo-list (listp buffer-undo-list)
17761 (not (cadr buffer-undo-list)) ; remove nil entry
17762 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17763 (setq org-self-insert-command-undo-counter
17764 (1+ org-self-insert-command-undo-counter))))))))
17766 (defun org-check-before-invisible-edit (kind)
17767 "Check is editing if kind KIND would be dangerous with invisible text around.
17768 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17769 ;; First, try to get out of here as quickly as possible, to reduce overhead
17770 (if (and org-catch-invisible-edits
17771 (or (not (boundp 'visible-mode)) (not visible-mode))
17772 (or (get-char-property (point) 'invisible)
17773 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17774 ;; OK, we need to take a closer look
17775 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17776 (invisible-before-point (if (bobp) nil (get-char-property
17777 (1- (point)) 'invisible)))
17778 (border-and-ok-direction
17780 ;; Check if we are acting predictably before invisible text
17781 (and invisible-at-point (not invisible-before-point)
17782 (memq kind '(insert delete-backward)))
17783 ;; Check if we are acting predictably after invisible text
17784 ;; This works not well, and I have turned it off. It seems
17785 ;; better to always show and stop after invisible text.
17786 ;; (and (not invisible-at-point) invisible-before-point
17787 ;; (memq kind '(insert delete)))
17790 (when (or (memq invisible-at-point '(outline org-hide-block))
17791 (memq invisible-before-point '(outline org-hide-block)))
17792 (if (eq org-catch-invisible-edits 'error)
17793 (error "Editing in invisible areas is prohibited - make visible first"))
17794 ;; Make the area visible
17795 (save-excursion
17796 (if invisible-before-point
17797 (goto-char (previous-single-char-property-change
17798 (point) 'invisible)))
17799 (org-cycle))
17800 (cond
17801 ((eq org-catch-invisible-edits 'show)
17802 ;; That's it, we do the edit after showing
17803 (message
17804 "Unfolding invisible region around point before editing")
17805 (sit-for 1))
17806 ((and (eq org-catch-invisible-edits 'smart)
17807 border-and-ok-direction)
17808 (message "Unfolding invisible region around point before editing"))
17810 ;; Don't do the edit, make the user repeat it in full visibility
17811 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17813 (defun org-fix-tags-on-the-fly ()
17814 (when (and (equal (char-after (point-at-bol)) ?*)
17815 (org-at-heading-p))
17816 (org-align-tags-here org-tags-column)))
17818 (defun org-delete-backward-char (N)
17819 "Like `delete-backward-char', insert whitespace at field end in tables.
17820 When deleting backwards, in tables this function will insert whitespace in
17821 front of the next \"|\" separator, to keep the table aligned. The table will
17822 still be marked for re-alignment if the field did fill the entire column,
17823 because, in this case the deletion might narrow the column."
17824 (interactive "p")
17825 (org-check-before-invisible-edit 'delete-backward)
17826 (if (and (org-table-p)
17827 (eq N 1)
17828 (string-match "|" (buffer-substring (point-at-bol) (point)))
17829 (looking-at ".*?|"))
17830 (let ((pos (point))
17831 (noalign (looking-at "[^|\n\r]* |"))
17832 (c org-table-may-need-update))
17833 (backward-delete-char N)
17834 (if (not overwrite-mode)
17835 (progn
17836 (skip-chars-forward "^|")
17837 (insert " ")
17838 (goto-char (1- pos))))
17839 ;; noalign: if there were two spaces at the end, this field
17840 ;; does not determine the width of the column.
17841 (if noalign (setq org-table-may-need-update c)))
17842 (backward-delete-char N)
17843 (org-fix-tags-on-the-fly)))
17845 (defun org-delete-char (N)
17846 "Like `delete-char', but insert whitespace at field end in tables.
17847 When deleting characters, in tables this function will insert whitespace in
17848 front of the next \"|\" separator, to keep the table aligned. The table will
17849 still be marked for re-alignment if the field did fill the entire column,
17850 because, in this case the deletion might narrow the column."
17851 (interactive "p")
17852 (org-check-before-invisible-edit 'delete)
17853 (if (and (org-table-p)
17854 (not (bolp))
17855 (not (= (char-after) ?|))
17856 (eq N 1))
17857 (if (looking-at ".*?|")
17858 (let ((pos (point))
17859 (noalign (looking-at "[^|\n\r]* |"))
17860 (c org-table-may-need-update))
17861 (replace-match (concat
17862 (substring (match-string 0) 1 -1)
17863 " |"))
17864 (goto-char pos)
17865 ;; noalign: if there were two spaces at the end, this field
17866 ;; does not determine the width of the column.
17867 (if noalign (setq org-table-may-need-update c)))
17868 (delete-char N))
17869 (delete-char N)
17870 (org-fix-tags-on-the-fly)))
17872 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17873 (put 'org-self-insert-command 'delete-selection t)
17874 (put 'orgtbl-self-insert-command 'delete-selection t)
17875 (put 'org-delete-char 'delete-selection 'supersede)
17876 (put 'org-delete-backward-char 'delete-selection 'supersede)
17877 (put 'org-yank 'delete-selection 'yank)
17879 ;; Make `flyspell-mode' delay after some commands
17880 (put 'org-self-insert-command 'flyspell-delayed t)
17881 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17882 (put 'org-delete-char 'flyspell-delayed t)
17883 (put 'org-delete-backward-char 'flyspell-delayed t)
17885 ;; Make pabbrev-mode expand after org-mode commands
17886 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17887 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17889 ;; How to do this: Measure non-white length of current string
17890 ;; If equal to column width, we should realign.
17892 (defun org-remap (map &rest commands)
17893 "In MAP, remap the functions given in COMMANDS.
17894 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17895 (let (new old)
17896 (while commands
17897 (setq old (pop commands) new (pop commands))
17898 (if (fboundp 'command-remapping)
17899 (org-defkey map (vector 'remap old) new)
17900 (substitute-key-definition old new map global-map)))))
17902 (when (eq org-enable-table-editor 'optimized)
17903 ;; If the user wants maximum table support, we need to hijack
17904 ;; some standard editing functions
17905 (org-remap org-mode-map
17906 'self-insert-command 'org-self-insert-command
17907 'delete-char 'org-delete-char
17908 'delete-backward-char 'org-delete-backward-char)
17909 (org-defkey org-mode-map "|" 'org-force-self-insert))
17911 (defvar org-ctrl-c-ctrl-c-hook nil
17912 "Hook for functions attaching themselves to `C-c C-c'.
17914 This can be used to add additional functionality to the C-c C-c
17915 key which executes context-dependent commands. This hook is run
17916 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17917 run after the last test.
17919 Each function will be called with no arguments. The function
17920 must check if the context is appropriate for it to act. If yes,
17921 it should do its thing and then return a non-nil value. If the
17922 context is wrong, just do nothing and return nil.")
17924 (defvar org-ctrl-c-ctrl-c-final-hook nil
17925 "Hook for functions attaching themselves to `C-c C-c'.
17927 This can be used to add additional functionality to the C-c C-c
17928 key which executes context-dependent commands. This hook is run
17929 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17930 before the first test.
17932 Each function will be called with no arguments. The function
17933 must check if the context is appropriate for it to act. If yes,
17934 it should do its thing and then return a non-nil value. If the
17935 context is wrong, just do nothing and return nil.")
17937 (defvar org-tab-first-hook nil
17938 "Hook for functions to attach themselves to TAB.
17939 See `org-ctrl-c-ctrl-c-hook' for more information.
17940 This hook runs as the first action when TAB is pressed, even before
17941 `org-cycle' messes around with the `outline-regexp' to cater for
17942 inline tasks and plain list item folding.
17943 If any function in this hook returns t, any other actions that
17944 would have been caused by TAB (such as table field motion or visibility
17945 cycling) will not occur.")
17947 (defvar org-tab-after-check-for-table-hook nil
17948 "Hook for functions to attach themselves to TAB.
17949 See `org-ctrl-c-ctrl-c-hook' for more information.
17950 This hook runs after it has been established that the cursor is not in a
17951 table, but before checking if the cursor is in a headline or if global cycling
17952 should be done.
17953 If any function in this hook returns t, not other actions like visibility
17954 cycling will be done.")
17956 (defvar org-tab-after-check-for-cycling-hook nil
17957 "Hook for functions to attach themselves to TAB.
17958 See `org-ctrl-c-ctrl-c-hook' for more information.
17959 This hook runs after it has been established that not table field motion and
17960 not visibility should be done because of current context. This is probably
17961 the place where a package like yasnippets can hook in.")
17963 (defvar org-tab-before-tab-emulation-hook nil
17964 "Hook for functions to attach themselves to TAB.
17965 See `org-ctrl-c-ctrl-c-hook' for more information.
17966 This hook runs after every other options for TAB have been exhausted, but
17967 before indentation and \t insertion takes place.")
17969 (defvar org-metaleft-hook nil
17970 "Hook for functions attaching themselves to `M-left'.
17971 See `org-ctrl-c-ctrl-c-hook' for more information.")
17972 (defvar org-metaright-hook nil
17973 "Hook for functions attaching themselves to `M-right'.
17974 See `org-ctrl-c-ctrl-c-hook' for more information.")
17975 (defvar org-metaup-hook nil
17976 "Hook for functions attaching themselves to `M-up'.
17977 See `org-ctrl-c-ctrl-c-hook' for more information.")
17978 (defvar org-metadown-hook nil
17979 "Hook for functions attaching themselves to `M-down'.
17980 See `org-ctrl-c-ctrl-c-hook' for more information.")
17981 (defvar org-shiftmetaleft-hook nil
17982 "Hook for functions attaching themselves to `M-S-left'.
17983 See `org-ctrl-c-ctrl-c-hook' for more information.")
17984 (defvar org-shiftmetaright-hook nil
17985 "Hook for functions attaching themselves to `M-S-right'.
17986 See `org-ctrl-c-ctrl-c-hook' for more information.")
17987 (defvar org-shiftmetaup-hook nil
17988 "Hook for functions attaching themselves to `M-S-up'.
17989 See `org-ctrl-c-ctrl-c-hook' for more information.")
17990 (defvar org-shiftmetadown-hook nil
17991 "Hook for functions attaching themselves to `M-S-down'.
17992 See `org-ctrl-c-ctrl-c-hook' for more information.")
17993 (defvar org-metareturn-hook nil
17994 "Hook for functions attaching themselves to `M-RET'.
17995 See `org-ctrl-c-ctrl-c-hook' for more information.")
17996 (defvar org-shiftup-hook nil
17997 "Hook for functions attaching themselves to `S-up'.
17998 See `org-ctrl-c-ctrl-c-hook' for more information.")
17999 (defvar org-shiftup-final-hook nil
18000 "Hook for functions attaching themselves to `S-up'.
18001 This one runs after all other options except shift-select have been excluded.
18002 See `org-ctrl-c-ctrl-c-hook' for more information.")
18003 (defvar org-shiftdown-hook nil
18004 "Hook for functions attaching themselves to `S-down'.
18005 See `org-ctrl-c-ctrl-c-hook' for more information.")
18006 (defvar org-shiftdown-final-hook nil
18007 "Hook for functions attaching themselves to `S-down'.
18008 This one runs after all other options except shift-select have been excluded.
18009 See `org-ctrl-c-ctrl-c-hook' for more information.")
18010 (defvar org-shiftleft-hook nil
18011 "Hook for functions attaching themselves to `S-left'.
18012 See `org-ctrl-c-ctrl-c-hook' for more information.")
18013 (defvar org-shiftleft-final-hook nil
18014 "Hook for functions attaching themselves to `S-left'.
18015 This one runs after all other options except shift-select have been excluded.
18016 See `org-ctrl-c-ctrl-c-hook' for more information.")
18017 (defvar org-shiftright-hook nil
18018 "Hook for functions attaching themselves to `S-right'.
18019 See `org-ctrl-c-ctrl-c-hook' for more information.")
18020 (defvar org-shiftright-final-hook nil
18021 "Hook for functions attaching themselves to `S-right'.
18022 This one runs after all other options except shift-select have been excluded.
18023 See `org-ctrl-c-ctrl-c-hook' for more information.")
18025 (defun org-modifier-cursor-error ()
18026 "Throw an error, a modified cursor command was applied in wrong context."
18027 (error "This command is active in special context like tables, headlines or items"))
18029 (defun org-shiftselect-error ()
18030 "Throw an error because Shift-Cursor command was applied in wrong context."
18031 (if (and (boundp 'shift-select-mode) shift-select-mode)
18032 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18033 (error "This command works only in special context like headlines or timestamps")))
18035 (defun org-call-for-shift-select (cmd)
18036 (let ((this-command-keys-shift-translated t))
18037 (call-interactively cmd)))
18039 (defun org-shifttab (&optional arg)
18040 "Global visibility cycling or move to previous table field.
18041 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18042 on context.
18043 See the individual commands for more information."
18044 (interactive "P")
18045 (cond
18046 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18047 ((integerp arg)
18048 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18049 (message "Content view to level: %d" arg)
18050 (org-content (prefix-numeric-value arg2))
18051 (setq org-cycle-global-status 'overview)))
18052 (t (call-interactively 'org-global-cycle))))
18054 (defun org-shiftmetaleft ()
18055 "Promote subtree or delete table column.
18056 Calls `org-promote-subtree', `org-outdent-item-tree', or
18057 `org-table-delete-column', depending on context. See the
18058 individual commands for more information."
18059 (interactive)
18060 (cond
18061 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18062 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18063 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18064 ((if (not (org-region-active-p)) (org-at-item-p)
18065 (save-excursion (goto-char (region-beginning))
18066 (org-at-item-p)))
18067 (call-interactively 'org-outdent-item-tree))
18068 (t (org-modifier-cursor-error))))
18070 (defun org-shiftmetaright ()
18071 "Demote subtree or insert table column.
18072 Calls `org-demote-subtree', `org-indent-item-tree', or
18073 `org-table-insert-column', depending on context. See the
18074 individual commands for more information."
18075 (interactive)
18076 (cond
18077 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18078 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18079 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18080 ((if (not (org-region-active-p)) (org-at-item-p)
18081 (save-excursion (goto-char (region-beginning))
18082 (org-at-item-p)))
18083 (call-interactively 'org-indent-item-tree))
18084 (t (org-modifier-cursor-error))))
18086 (defun org-shiftmetaup (&optional arg)
18087 "Move subtree up or kill table row.
18088 Calls `org-move-subtree-up' or `org-table-kill-row' or
18089 `org-move-item-up' depending on context. See the individual commands
18090 for more information."
18091 (interactive "P")
18092 (cond
18093 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18094 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18095 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18096 ((org-at-item-p) (call-interactively 'org-move-item-up))
18097 (t (org-modifier-cursor-error))))
18099 (defun org-shiftmetadown (&optional arg)
18100 "Move subtree down or insert table row.
18101 Calls `org-move-subtree-down' or `org-table-insert-row' or
18102 `org-move-item-down', depending on context. See the individual
18103 commands for more information."
18104 (interactive "P")
18105 (cond
18106 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18107 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18108 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18109 ((org-at-item-p) (call-interactively 'org-move-item-down))
18110 (t (org-modifier-cursor-error))))
18112 (defsubst org-hidden-tree-error ()
18113 (error
18114 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18116 (defun org-metaleft (&optional arg)
18117 "Promote heading or move table column to left.
18118 Calls `org-do-promote' or `org-table-move-column', depending on context.
18119 With no specific context, calls the Emacs default `backward-word'.
18120 See the individual commands for more information."
18121 (interactive "P")
18122 (cond
18123 ((run-hook-with-args-until-success 'org-metaleft-hook))
18124 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18125 ((org-with-limited-levels
18126 (or (org-at-heading-p)
18127 (and (org-region-active-p)
18128 (save-excursion
18129 (goto-char (region-beginning))
18130 (org-at-heading-p)))))
18131 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18132 (call-interactively 'org-do-promote))
18133 ;; At an inline task.
18134 ((org-at-heading-p)
18135 (call-interactively 'org-inlinetask-promote))
18136 ((or (org-at-item-p)
18137 (and (org-region-active-p)
18138 (save-excursion
18139 (goto-char (region-beginning))
18140 (org-at-item-p))))
18141 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18142 (call-interactively 'org-outdent-item))
18143 (t (call-interactively 'backward-word))))
18145 (defun org-metaright (&optional arg)
18146 "Demote a subtree, a list item or move table column to right.
18147 In front of a drawer or a block keyword, indent it correctly.
18148 With no specific context, calls the Emacs default `forward-word'.
18149 See the individual commands for more information."
18150 (interactive "P")
18151 (cond
18152 ((run-hook-with-args-until-success 'org-metaright-hook))
18153 ((org-at-table-p) (call-interactively 'org-table-move-column))
18154 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18155 ((org-at-block-p) (call-interactively 'org-indent-block))
18156 ((org-with-limited-levels
18157 (or (org-at-heading-p)
18158 (and (org-region-active-p)
18159 (save-excursion
18160 (goto-char (region-beginning))
18161 (org-at-heading-p)))))
18162 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18163 (call-interactively 'org-do-demote))
18164 ;; At an inline task.
18165 ((org-at-heading-p)
18166 (call-interactively 'org-inlinetask-demote))
18167 ((or (org-at-item-p)
18168 (and (org-region-active-p)
18169 (save-excursion
18170 (goto-char (region-beginning))
18171 (org-at-item-p))))
18172 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18173 (call-interactively 'org-indent-item))
18174 (t (call-interactively 'forward-word))))
18176 (defun org-check-for-hidden (what)
18177 "Check if there are hidden headlines/items in the current visual line.
18178 WHAT can be either `headlines' or `items'. If the current line is
18179 an outline or item heading and it has a folded subtree below it,
18180 this function returns t, nil otherwise."
18181 (let ((re (cond
18182 ((eq what 'headlines) org-outline-regexp-bol)
18183 ((eq what 'items) (org-item-beginning-re))
18184 (t (error "This should not happen"))))
18185 beg end)
18186 (save-excursion
18187 (catch 'exit
18188 (unless (org-region-active-p)
18189 (setq beg (point-at-bol))
18190 (beginning-of-line 2)
18191 (while (and (not (eobp)) ;; this is like `next-line'
18192 (get-char-property (1- (point)) 'invisible))
18193 (beginning-of-line 2))
18194 (setq end (point))
18195 (goto-char beg)
18196 (goto-char (point-at-eol))
18197 (setq end (max end (point)))
18198 (while (re-search-forward re end t)
18199 (if (get-char-property (match-beginning 0) 'invisible)
18200 (throw 'exit t))))
18201 nil))))
18203 (defun org-metaup (&optional arg)
18204 "Move subtree up or move table row up.
18205 Calls `org-move-subtree-up' or `org-table-move-row' or
18206 `org-move-item-up', depending on context. See the individual commands
18207 for more information."
18208 (interactive "P")
18209 (cond
18210 ((run-hook-with-args-until-success 'org-metaup-hook))
18211 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18212 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18213 ((org-at-item-p) (call-interactively 'org-move-item-up))
18214 (t (transpose-lines 1) (beginning-of-line -1))))
18216 (defun org-metadown (&optional arg)
18217 "Move subtree down or move table row down.
18218 Calls `org-move-subtree-down' or `org-table-move-row' or
18219 `org-move-item-down', depending on context. See the individual
18220 commands for more information."
18221 (interactive "P")
18222 (cond
18223 ((run-hook-with-args-until-success 'org-metadown-hook))
18224 ((org-at-table-p) (call-interactively 'org-table-move-row))
18225 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18226 ((org-at-item-p) (call-interactively 'org-move-item-down))
18227 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18229 (defun org-shiftup (&optional arg)
18230 "Increase item in timestamp or increase priority of current headline.
18231 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18232 depending on context. See the individual commands for more information."
18233 (interactive "P")
18234 (cond
18235 ((run-hook-with-args-until-success 'org-shiftup-hook))
18236 ((and org-support-shift-select (org-region-active-p))
18237 (org-call-for-shift-select 'previous-line))
18238 ((org-at-timestamp-p t)
18239 (call-interactively (if org-edit-timestamp-down-means-later
18240 'org-timestamp-down 'org-timestamp-up)))
18241 ((and (not (eq org-support-shift-select 'always))
18242 org-enable-priority-commands
18243 (org-at-heading-p))
18244 (call-interactively 'org-priority-up))
18245 ((and (not org-support-shift-select) (org-at-item-p))
18246 (call-interactively 'org-previous-item))
18247 ((org-clocktable-try-shift 'up arg))
18248 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18249 (org-support-shift-select
18250 (org-call-for-shift-select 'previous-line))
18251 (t (org-shiftselect-error))))
18253 (defun org-shiftdown (&optional arg)
18254 "Decrease item in timestamp or decrease priority of current headline.
18255 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18256 depending on context. See the individual commands for more information."
18257 (interactive "P")
18258 (cond
18259 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18260 ((and org-support-shift-select (org-region-active-p))
18261 (org-call-for-shift-select 'next-line))
18262 ((org-at-timestamp-p t)
18263 (call-interactively (if org-edit-timestamp-down-means-later
18264 'org-timestamp-up 'org-timestamp-down)))
18265 ((and (not (eq org-support-shift-select 'always))
18266 org-enable-priority-commands
18267 (org-at-heading-p))
18268 (call-interactively 'org-priority-down))
18269 ((and (not org-support-shift-select) (org-at-item-p))
18270 (call-interactively 'org-next-item))
18271 ((org-clocktable-try-shift 'down arg))
18272 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18273 (org-support-shift-select
18274 (org-call-for-shift-select 'next-line))
18275 (t (org-shiftselect-error))))
18277 (defun org-shiftright (&optional arg)
18278 "Cycle the thing at point or in the current line, depending on context.
18279 Depending on context, this does one of the following:
18281 - switch a timestamp at point one day into the future
18282 - on a headline, switch to the next TODO keyword.
18283 - on an item, switch entire list to the next bullet type
18284 - on a property line, switch to the next allowed value
18285 - on a clocktable definition line, move time block into the future"
18286 (interactive "P")
18287 (cond
18288 ((run-hook-with-args-until-success 'org-shiftright-hook))
18289 ((and org-support-shift-select (org-region-active-p))
18290 (org-call-for-shift-select 'forward-char))
18291 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18292 ((and (not (eq org-support-shift-select 'always))
18293 (org-at-heading-p))
18294 (let ((org-inhibit-logging
18295 (not org-treat-S-cursor-todo-selection-as-state-change))
18296 (org-inhibit-blocking
18297 (not org-treat-S-cursor-todo-selection-as-state-change)))
18298 (org-call-with-arg 'org-todo 'right)))
18299 ((or (and org-support-shift-select
18300 (not (eq org-support-shift-select 'always))
18301 (org-at-item-bullet-p))
18302 (and (not org-support-shift-select) (org-at-item-p)))
18303 (org-call-with-arg 'org-cycle-list-bullet nil))
18304 ((and (not (eq org-support-shift-select 'always))
18305 (org-at-property-p))
18306 (call-interactively 'org-property-next-allowed-value))
18307 ((org-clocktable-try-shift 'right arg))
18308 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18309 (org-support-shift-select
18310 (org-call-for-shift-select 'forward-char))
18311 (t (org-shiftselect-error))))
18313 (defun org-shiftleft (&optional arg)
18314 "Cycle the thing at point or in the current line, depending on context.
18315 Depending on context, this does one of the following:
18317 - switch a timestamp at point one day into the past
18318 - on a headline, switch to the previous TODO keyword.
18319 - on an item, switch entire list to the previous bullet type
18320 - on a property line, switch to the previous allowed value
18321 - on a clocktable definition line, move time block into the past"
18322 (interactive "P")
18323 (cond
18324 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18325 ((and org-support-shift-select (org-region-active-p))
18326 (org-call-for-shift-select 'backward-char))
18327 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18328 ((and (not (eq org-support-shift-select 'always))
18329 (org-at-heading-p))
18330 (let ((org-inhibit-logging
18331 (not org-treat-S-cursor-todo-selection-as-state-change))
18332 (org-inhibit-blocking
18333 (not org-treat-S-cursor-todo-selection-as-state-change)))
18334 (org-call-with-arg 'org-todo 'left)))
18335 ((or (and org-support-shift-select
18336 (not (eq org-support-shift-select 'always))
18337 (org-at-item-bullet-p))
18338 (and (not org-support-shift-select) (org-at-item-p)))
18339 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18340 ((and (not (eq org-support-shift-select 'always))
18341 (org-at-property-p))
18342 (call-interactively 'org-property-previous-allowed-value))
18343 ((org-clocktable-try-shift 'left arg))
18344 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18345 (org-support-shift-select
18346 (org-call-for-shift-select 'backward-char))
18347 (t (org-shiftselect-error))))
18349 (defun org-shiftcontrolright ()
18350 "Switch to next TODO set."
18351 (interactive)
18352 (cond
18353 ((and org-support-shift-select (org-region-active-p))
18354 (org-call-for-shift-select 'forward-word))
18355 ((and (not (eq org-support-shift-select 'always))
18356 (org-at-heading-p))
18357 (org-call-with-arg 'org-todo 'nextset))
18358 (org-support-shift-select
18359 (org-call-for-shift-select 'forward-word))
18360 (t (org-shiftselect-error))))
18362 (defun org-shiftcontrolleft ()
18363 "Switch to previous TODO set."
18364 (interactive)
18365 (cond
18366 ((and org-support-shift-select (org-region-active-p))
18367 (org-call-for-shift-select 'backward-word))
18368 ((and (not (eq org-support-shift-select 'always))
18369 (org-at-heading-p))
18370 (org-call-with-arg 'org-todo 'previousset))
18371 (org-support-shift-select
18372 (org-call-for-shift-select 'backward-word))
18373 (t (org-shiftselect-error))))
18375 (defun org-shiftcontrolup ()
18376 "Change timestamps synchronously up in CLOCK log lines."
18377 (interactive)
18378 (cond ((and (not org-support-shift-select)
18379 (org-at-clock-log-p)
18380 (org-at-timestamp-p t))
18381 (org-clock-timestamps-up))
18382 (t (org-shiftselect-error))))
18384 (defun org-shiftcontroldown ()
18385 "Change timestamps synchronously down in CLOCK log lines."
18386 (interactive)
18387 (cond ((and (not org-support-shift-select)
18388 (org-at-clock-log-p)
18389 (org-at-timestamp-p t))
18390 (org-clock-timestamps-down))
18391 (t (org-shiftselect-error))))
18393 (defun org-ctrl-c-ret ()
18394 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18395 (interactive)
18396 (cond
18397 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18398 (t (call-interactively 'org-insert-heading))))
18400 (defun org-find-visible ()
18401 (let ((s (point)))
18402 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18403 (get-char-property s 'invisible)))
18405 (defun org-find-invisible ()
18406 (let ((s (point)))
18407 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18408 (not (get-char-property s 'invisible))))
18411 (defun org-copy-visible (beg end)
18412 "Copy the visible parts of the region."
18413 (interactive "r")
18414 (let (snippets s)
18415 (save-excursion
18416 (save-restriction
18417 (narrow-to-region beg end)
18418 (setq s (goto-char (point-min)))
18419 (while (not (= (point) (point-max)))
18420 (goto-char (org-find-invisible))
18421 (push (buffer-substring s (point)) snippets)
18422 (setq s (goto-char (org-find-visible))))))
18423 (kill-new (apply 'concat (nreverse snippets)))))
18425 (defun org-copy-special ()
18426 "Copy region in table or copy current subtree.
18427 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18428 See the individual commands for more information."
18429 (interactive)
18430 (call-interactively
18431 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18433 (defun org-cut-special ()
18434 "Cut region in table or cut current subtree.
18435 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18436 See the individual commands for more information."
18437 (interactive)
18438 (call-interactively
18439 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18441 (defun org-paste-special (arg)
18442 "Paste rectangular region into table, or past subtree relative to level.
18443 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18444 See the individual commands for more information."
18445 (interactive "P")
18446 (if (org-at-table-p)
18447 (org-table-paste-rectangle)
18448 (org-paste-subtree arg)))
18450 (defun org-edit-special (&optional arg)
18451 "Call a special editor for the stuff at point.
18452 When at a table, call the formula editor with `org-table-edit-formulas'.
18453 When at the first line of an src example, call `org-edit-src-code'.
18454 When in an #+include line, visit the include file. Otherwise call
18455 `ffap' to visit the file at point."
18456 (interactive)
18457 ;; possibly prep session before editing source
18458 (when arg
18459 (let* ((info (org-babel-get-src-block-info))
18460 (lang (nth 0 info))
18461 (params (nth 2 info))
18462 (session (cdr (assoc :session params))))
18463 (when (and info session) ;; we are in a source-code block with a session
18464 (funcall
18465 (intern (concat "org-babel-prep-session:" lang)) session params))))
18466 (cond ;; proceed with `org-edit-special'
18467 ((save-excursion
18468 (beginning-of-line 1)
18469 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18470 (find-file (org-trim (match-string 1))))
18471 ((org-edit-src-code))
18472 ((org-edit-fixed-width-region))
18473 ((org-at-table.el-p)
18474 (org-edit-src-code))
18475 ((or (org-at-table-p)
18476 (save-excursion
18477 (beginning-of-line 1)
18478 (looking-at "[ \t]*#\\+TBLFM:")))
18479 (call-interactively 'org-table-edit-formulas))
18480 (t (call-interactively 'ffap))))
18482 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18483 (defun org-ctrl-c-ctrl-c (&optional arg)
18484 "Set tags in headline, or update according to changed information at point.
18486 This command does many different things, depending on context:
18488 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18489 this is what we do.
18491 - If the cursor is on a statistics cookie, update it.
18493 - If the cursor is in a headline, prompt for tags and insert them
18494 into the current line, aligned to `org-tags-column'. When called
18495 with prefix arg, realign all tags in the current buffer.
18497 - If the cursor is in one of the special #+KEYWORD lines, this
18498 triggers scanning the buffer for these lines and updating the
18499 information.
18501 - If the cursor is inside a table, realign the table. This command
18502 works even if the automatic table editor has been turned off.
18504 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18505 the entire table.
18507 - If the cursor is at a footnote reference or definition, jump to
18508 the corresponding definition or references, respectively.
18510 - If the cursor is a the beginning of a dynamic block, update it.
18512 - If the current buffer is a capture buffer, close note and file it.
18514 - If the cursor is on a <<<target>>>, update radio targets and
18515 corresponding links in this buffer.
18517 - If the cursor is on a numbered item in a plain list, renumber the
18518 ordered list.
18520 - If the cursor is on a checkbox, toggle it.
18522 - If the cursor is on a code block, evaluate it. The variable
18523 `org-confirm-babel-evaluate' can be used to control prompting
18524 before code block evaluation, by default every code block
18525 evaluation requires confirmation. Code block evaluation can be
18526 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18527 (interactive "P")
18528 (let ((org-enable-table-editor t))
18529 (cond
18530 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18531 org-occur-highlights
18532 org-latex-fragment-image-overlays)
18533 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18534 (org-remove-occur-highlights)
18535 (org-remove-latex-fragment-image-overlays)
18536 (message "Temporary highlights/overlays removed from current buffer"))
18537 ((and (local-variable-p 'org-finish-function (current-buffer))
18538 (fboundp org-finish-function))
18539 (funcall org-finish-function))
18540 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18541 ((org-in-regexp org-ts-regexp-both)
18542 (org-timestamp-change 0 'day))
18543 ((or (looking-at org-property-start-re)
18544 (org-at-property-p))
18545 (call-interactively 'org-property-action))
18546 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18547 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18548 (or (org-at-heading-p) (org-at-item-p)))
18549 (call-interactively 'org-update-statistics-cookies))
18550 ((org-at-heading-p) (call-interactively 'org-set-tags))
18551 ((org-at-table.el-p)
18552 (message "Use C-c ' to edit table.el tables"))
18553 ((org-at-table-p)
18554 (org-table-maybe-eval-formula)
18555 (if arg
18556 (call-interactively 'org-table-recalculate)
18557 (org-table-maybe-recalculate-line))
18558 (call-interactively 'org-table-align)
18559 (orgtbl-send-table 'maybe))
18560 ((or (org-footnote-at-reference-p)
18561 (org-footnote-at-definition-p))
18562 (call-interactively 'org-footnote-action))
18563 ((org-at-item-checkbox-p)
18564 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18565 ;; list only if at top item.
18566 (let* ((cbox (match-string 1))
18567 (struct (org-list-struct))
18568 (old-struct (copy-tree struct))
18569 (parents (org-list-parents-alist struct))
18570 (orderedp (org-entry-get nil "ORDERED"))
18571 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18572 block-item)
18573 ;; Use a light version of `org-toggle-checkbox' to avoid
18574 ;; computing list structure twice.
18575 (let ((new-box (cond
18576 ((equal arg '(16)) "[-]")
18577 ((equal arg '(4)) nil)
18578 ((equal "[X]" cbox) "[ ]")
18579 (t "[X]"))))
18580 (if (and firstp arg)
18581 ;; If at first item of sub-list, remove check-box from
18582 ;; every item at the same level.
18583 (mapc
18584 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18585 (org-list-get-all-items
18586 (point-at-bol) struct (org-list-prevs-alist struct)))
18587 (org-list-set-checkbox (point-at-bol) struct new-box)))
18588 ;; Replicate `org-list-write-struct', while grabbing a return
18589 ;; value from `org-list-struct-fix-box'.
18590 (org-list-struct-fix-ind struct parents 2)
18591 (org-list-struct-fix-item-end struct)
18592 (let ((prevs (org-list-prevs-alist struct)))
18593 (org-list-struct-fix-bul struct prevs)
18594 (org-list-struct-fix-ind struct parents)
18595 (setq block-item
18596 (org-list-struct-fix-box struct parents prevs orderedp)))
18597 (org-list-struct-apply-struct struct old-struct)
18598 (org-update-checkbox-count-maybe)
18599 (when block-item
18600 (message
18601 "Checkboxes were removed due to unchecked box at line %d"
18602 (org-current-line block-item)))
18603 (when firstp (org-list-send-list 'maybe))))
18604 ((org-at-item-p)
18605 ;; Cursor at an item: repair list. Do checkbox related actions
18606 ;; only if function was called with an argument. Send list only
18607 ;; if at top item.
18608 (let* ((struct (org-list-struct))
18609 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18610 old-struct)
18611 (when arg
18612 (setq old-struct (copy-tree struct))
18613 (if firstp
18614 ;; If at first item of sub-list, add check-box to every
18615 ;; item at the same level.
18616 (mapc
18617 (lambda (pos)
18618 (unless (org-list-get-checkbox pos struct)
18619 (org-list-set-checkbox pos struct "[ ]")))
18620 (org-list-get-all-items
18621 (point-at-bol) struct (org-list-prevs-alist struct)))
18622 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18623 (org-list-write-struct
18624 struct (org-list-parents-alist struct) old-struct)
18625 (when arg (org-update-checkbox-count-maybe))
18626 (when firstp (org-list-send-list 'maybe))))
18627 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18628 ;; Dynamic block
18629 (beginning-of-line 1)
18630 (save-excursion (org-update-dblock)))
18631 ((save-excursion
18632 (beginning-of-line 1)
18633 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18634 (cond
18635 ((equal (match-string 1) "TBLFM")
18636 ;; Recalculate the table before this line
18637 (save-excursion
18638 (beginning-of-line 1)
18639 (skip-chars-backward " \r\n\t")
18640 (if (org-at-table-p)
18641 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18643 (let ((org-inhibit-startup-visibility-stuff t)
18644 (org-startup-align-all-tables nil))
18645 (when (boundp 'org-table-coordinate-overlays)
18646 (mapc 'delete-overlay org-table-coordinate-overlays)
18647 (setq org-table-coordinate-overlays nil))
18648 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18649 (message "Local setup has been refreshed"))))
18650 ((org-clock-update-time-maybe))
18652 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18653 (error "C-c C-c can do nothing useful at this location"))))))
18655 (defun org-mode-restart ()
18656 "Restart Org-mode, to scan again for special lines.
18657 Also updates the keyword regular expressions."
18658 (interactive)
18659 (org-mode)
18660 (message "Org-mode restarted"))
18662 (defun org-kill-note-or-show-branches ()
18663 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18664 (interactive)
18665 (if (not org-finish-function)
18666 (progn
18667 (hide-subtree)
18668 (call-interactively 'show-branches))
18669 (let ((org-note-abort t))
18670 (funcall org-finish-function))))
18672 (defun org-return (&optional indent)
18673 "Goto next table row or insert a newline.
18674 Calls `org-table-next-row' or `newline', depending on context.
18675 See the individual commands for more information."
18676 (interactive)
18677 (cond
18678 ((or (bobp) (org-in-src-block-p))
18679 (if indent (newline-and-indent) (newline)))
18680 ((org-at-table-p)
18681 (org-table-justify-field-maybe)
18682 (call-interactively 'org-table-next-row))
18683 ;; when `newline-and-indent' is called within a list, make sure
18684 ;; text moved stays inside the item.
18685 ((and (org-in-item-p) indent)
18686 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18687 (progn
18688 (save-match-data (newline))
18689 (org-indent-line-to (length (match-string 0))))
18690 (let ((ind (org-get-indentation)))
18691 (newline)
18692 (if (org-looking-back org-list-end-re)
18693 (org-indent-line-function)
18694 (org-indent-line-to ind)))))
18695 ((and org-return-follows-link
18696 (let ((tprop (get-text-property (point) 'face)))
18697 (or (eq tprop 'org-link)
18698 (and (listp tprop) (memq 'org-link tprop)))))
18699 (call-interactively 'org-open-at-point))
18700 ((and (org-at-heading-p)
18701 (looking-at
18702 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18703 (org-show-entry)
18704 (end-of-line 1)
18705 (newline))
18706 (t (if indent (newline-and-indent) (newline)))))
18708 (defun org-return-indent ()
18709 "Goto next table row or insert a newline and indent.
18710 Calls `org-table-next-row' or `newline-and-indent', depending on
18711 context. See the individual commands for more information."
18712 (interactive)
18713 (org-return t))
18715 (defun org-ctrl-c-star ()
18716 "Compute table, or change heading status of lines.
18717 Calls `org-table-recalculate' or `org-toggle-heading',
18718 depending on context."
18719 (interactive)
18720 (cond
18721 ((org-at-table-p)
18722 (call-interactively 'org-table-recalculate))
18724 ;; Convert all lines in region to list items
18725 (call-interactively 'org-toggle-heading))))
18727 (defun org-ctrl-c-minus ()
18728 "Insert separator line in table or modify bullet status of line.
18729 Also turns a plain line or a region of lines into list items.
18730 Calls `org-table-insert-hline', `org-toggle-item', or
18731 `org-cycle-list-bullet', depending on context."
18732 (interactive)
18733 (cond
18734 ((org-at-table-p)
18735 (call-interactively 'org-table-insert-hline))
18736 ((org-region-active-p)
18737 (call-interactively 'org-toggle-item))
18738 ((org-in-item-p)
18739 (call-interactively 'org-cycle-list-bullet))
18741 (call-interactively 'org-toggle-item))))
18743 (defun org-toggle-item (arg)
18744 "Convert headings or normal lines to items, items to normal lines.
18745 If there is no active region, only the current line is considered.
18747 If the first non blank line in the region is an headline, convert
18748 all headlines to items, shifting text accordingly.
18750 If it is an item, convert all items to normal lines.
18752 If it is normal text, change region into an item. With a prefix
18753 argument ARG, change each line in region into an item."
18754 (interactive "P")
18755 (let ((shift-text
18756 (function
18757 ;; Shift text in current section to IND, from point to END.
18758 ;; The function leaves point to END line.
18759 (lambda (ind end)
18760 (let ((min-i 1000) (end (copy-marker end)))
18761 ;; First determine the minimum indentation (MIN-I) of
18762 ;; the text.
18763 (save-excursion
18764 (catch 'exit
18765 (while (< (point) end)
18766 (let ((i (org-get-indentation)))
18767 (cond
18768 ;; Skip blank lines and inline tasks.
18769 ((looking-at "^[ \t]*$"))
18770 ((looking-at org-outline-regexp-bol))
18771 ;; We can't find less than 0 indentation.
18772 ((zerop i) (throw 'exit (setq min-i 0)))
18773 ((< i min-i) (setq min-i i))))
18774 (forward-line))))
18775 ;; Then indent each line so that a line indented to
18776 ;; MIN-I becomes indented to IND. Ignore blank lines
18777 ;; and inline tasks in the process.
18778 (let ((delta (- ind min-i)))
18779 (while (< (point) end)
18780 (unless (or (looking-at "^[ \t]*$")
18781 (looking-at org-outline-regexp-bol))
18782 (org-indent-line-to (+ (org-get-indentation) delta)))
18783 (forward-line)))))))
18784 (skip-blanks
18785 (function
18786 ;; Return beginning of first non-blank line, starting from
18787 ;; line at POS.
18788 (lambda (pos)
18789 (save-excursion
18790 (goto-char pos)
18791 (skip-chars-forward " \r\t\n")
18792 (point-at-bol)))))
18793 beg end)
18794 ;; Determine boundaries of changes.
18795 (if (org-region-active-p)
18796 (setq beg (funcall skip-blanks (region-beginning))
18797 end (copy-marker (region-end)))
18798 (setq beg (funcall skip-blanks (point-at-bol))
18799 end (copy-marker (point-at-eol))))
18800 ;; Depending on the starting line, choose an action on the text
18801 ;; between BEG and END.
18802 (org-with-limited-levels
18803 (save-excursion
18804 (goto-char beg)
18805 (cond
18806 ;; Case 1. Start at an item: de-itemize. Note that it only
18807 ;; happens when a region is active: `org-ctrl-c-minus'
18808 ;; would call `org-cycle-list-bullet' otherwise.
18809 ((org-at-item-p)
18810 (while (< (point) end)
18811 (when (org-at-item-p)
18812 (skip-chars-forward " \t")
18813 (delete-region (point) (match-end 0)))
18814 (forward-line)))
18815 ;; Case 2. Start at an heading: convert to items.
18816 ((org-at-heading-p)
18817 (let* ((bul (org-list-bullet-string "-"))
18818 (bul-len (length bul))
18819 ;; Indentation of the first heading. It should be
18820 ;; relative to the indentation of its parent, if any.
18821 (start-ind (save-excursion
18822 (cond
18823 ((not org-adapt-indentation) 0)
18824 ((not (outline-previous-heading)) 0)
18825 (t (length (match-string 0))))))
18826 ;; Level of first heading. Further headings will be
18827 ;; compared to it to determine hierarchy in the list.
18828 (ref-level (org-reduced-level (org-outline-level))))
18829 (while (< (point) end)
18830 (let* ((level (org-reduced-level (org-outline-level)))
18831 (delta (max 0 (- level ref-level))))
18832 ;; If current headline is less indented than the first
18833 ;; one, set it as reference, in order to preserve
18834 ;; subtrees.
18835 (when (< level ref-level) (setq ref-level level))
18836 (replace-match bul t t)
18837 (org-indent-line-to (+ start-ind (* delta bul-len)))
18838 ;; Ensure all text down to END (or SECTION-END) belongs
18839 ;; to the newly created item.
18840 (let ((section-end (save-excursion
18841 (or (outline-next-heading) (point)))))
18842 (forward-line)
18843 (funcall shift-text
18844 (+ start-ind (* (1+ delta) bul-len))
18845 (min end section-end)))))))
18846 ;; Case 3. Normal line with ARG: turn each non-item line into
18847 ;; an item.
18848 (arg
18849 (while (< (point) end)
18850 (unless (or (org-at-heading-p) (org-at-item-p))
18851 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18852 (replace-match
18853 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18854 (forward-line)))
18855 ;; Case 4. Normal line without ARG: make the first line of
18856 ;; region an item, and shift indentation of others
18857 ;; lines to set them as item's body.
18858 (t (let* ((bul (org-list-bullet-string "-"))
18859 (bul-len (length bul))
18860 (ref-ind (org-get-indentation)))
18861 (skip-chars-forward " \t")
18862 (insert bul)
18863 (forward-line)
18864 (while (< (point) end)
18865 ;; Ensure that lines less indented than first one
18866 ;; still get included in item body.
18867 (funcall shift-text
18868 (+ ref-ind bul-len)
18869 (min end (save-excursion (or (outline-next-heading)
18870 (point)))))
18871 (forward-line)))))))))
18873 (defun org-toggle-heading (&optional nstars)
18874 "Convert headings to normal text, or items or text to headings.
18875 If there is no active region, only the current line is considered.
18877 If the first non blank line is an headline, remove the stars from
18878 all headlines in the region.
18880 If it is a plain list item, turn all plain list items into headings.
18882 If it is a normal line, turn each and every normal line (i.e. not
18883 an heading or an item) in the region into a heading.
18885 When converting a line into a heading, the number of stars is chosen
18886 such that the lines become children of the current entry. However,
18887 when a prefix argument is given, its value determines the number of
18888 stars to add."
18889 (interactive "P")
18890 (let ((skip-blanks
18891 (function
18892 ;; Return beginning of first non-blank line, starting from
18893 ;; line at POS.
18894 (lambda (pos)
18895 (save-excursion
18896 (goto-char pos)
18897 (skip-chars-forward " \r\t\n")
18898 (point-at-bol)))))
18899 beg end)
18900 ;; Determine boundaries of changes. If region ends at a bol, do
18901 ;; not consider the last line to be in the region.
18902 (if (org-region-active-p)
18903 (setq beg (funcall skip-blanks (region-beginning))
18904 end (copy-marker (save-excursion
18905 (goto-char (region-end))
18906 (if (bolp) (point) (point-at-eol)))))
18907 (setq beg (funcall skip-blanks (point-at-bol))
18908 end (copy-marker (point-at-eol))))
18909 ;; Ensure inline tasks don't count as headings.
18910 (org-with-limited-levels
18911 (save-excursion
18912 (goto-char beg)
18913 (cond
18914 ;; Case 1. Started at an heading: de-star headings.
18915 ((org-at-heading-p)
18916 (while (< (point) end)
18917 (when (org-at-heading-p t)
18918 (looking-at org-outline-regexp) (replace-match ""))
18919 (forward-line)))
18920 ;; Case 2. Started at an item: change items into headlines.
18921 ;; One star will be added by `org-list-to-subtree'.
18922 ((org-at-item-p)
18923 (let* ((stars (make-string
18924 (if nstars
18925 ;; subtract the star that will be added again by
18926 ;; `org-list-to-subtree'
18927 (1- (prefix-numeric-value current-prefix-arg))
18928 (or (org-current-level) 0))
18929 ?*))
18930 (add-stars
18931 (cond (nstars "") ; stars from prefix only
18932 ((equal stars "") "") ; before first heading
18933 (org-odd-levels-only "*") ; inside heading, odd
18934 (t "")))) ; inside heading, oddeven
18935 (while (< (point) end)
18936 (when (org-at-item-p)
18937 ;; Pay attention to cases when region ends before list.
18938 (let* ((struct (org-list-struct))
18939 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18940 (save-restriction
18941 (narrow-to-region (point) list-end)
18942 (insert
18943 (org-list-to-subtree
18944 (org-list-parse-list t)
18945 '(:istart (concat stars add-stars (funcall get-stars depth))
18946 :icount (concat stars add-stars (funcall get-stars depth))))))))
18947 (forward-line))))
18948 ;; Case 3. Started at normal text: make every line an heading,
18949 ;; skipping headlines and items.
18950 (t (let* ((stars (make-string
18951 (if nstars
18952 (prefix-numeric-value current-prefix-arg)
18953 (or (org-current-level) 0))
18954 ?*))
18955 (add-stars
18956 (cond (nstars "") ; stars from prefix only
18957 ((equal stars "") "*") ; before first heading
18958 (org-odd-levels-only "**") ; inside heading, odd
18959 (t "*"))) ; inside heading, oddeven
18960 (rpl (concat stars add-stars " ")))
18961 (while (< (point) end)
18962 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18963 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18964 (replace-match (concat rpl (match-string 2))))
18965 (forward-line)))))))))
18967 (defun org-meta-return (&optional arg)
18968 "Insert a new heading or wrap a region in a table.
18969 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18970 See the individual commands for more information."
18971 (interactive "P")
18972 (cond
18973 ((run-hook-with-args-until-success 'org-metareturn-hook))
18974 ((or (org-at-drawer-p) (org-at-property-p))
18975 (newline-and-indent))
18976 ((org-at-table-p)
18977 (call-interactively 'org-table-wrap-region))
18978 (t (call-interactively 'org-insert-heading))))
18980 ;;; Menu entries
18982 ;; Define the Org-mode menus
18983 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18984 '("Tbl"
18985 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18986 ["Next Field" org-cycle (org-at-table-p)]
18987 ["Previous Field" org-shifttab (org-at-table-p)]
18988 ["Next Row" org-return (org-at-table-p)]
18989 "--"
18990 ["Blank Field" org-table-blank-field (org-at-table-p)]
18991 ["Edit Field" org-table-edit-field (org-at-table-p)]
18992 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18993 "--"
18994 ("Column"
18995 ["Move Column Left" org-metaleft (org-at-table-p)]
18996 ["Move Column Right" org-metaright (org-at-table-p)]
18997 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18998 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18999 ("Row"
19000 ["Move Row Up" org-metaup (org-at-table-p)]
19001 ["Move Row Down" org-metadown (org-at-table-p)]
19002 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19003 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19004 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19005 "--"
19006 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19007 ("Rectangle"
19008 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19009 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19010 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19011 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19012 "--"
19013 ("Calculate"
19014 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19015 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19016 ["Edit Formulas" org-edit-special (org-at-table-p)]
19017 "--"
19018 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19019 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19020 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19021 "--"
19022 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19023 "--"
19024 ["Sum Column/Rectangle" org-table-sum
19025 (or (org-at-table-p) (org-region-active-p))]
19026 ["Which Column?" org-table-current-column (org-at-table-p)])
19027 ["Debug Formulas"
19028 org-table-toggle-formula-debugger
19029 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19030 ["Show Col/Row Numbers"
19031 org-table-toggle-coordinate-overlays
19032 :style toggle
19033 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19034 "--"
19035 ["Create" org-table-create (and (not (org-at-table-p))
19036 org-enable-table-editor)]
19037 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19038 ["Import from File" org-table-import (not (org-at-table-p))]
19039 ["Export to File" org-table-export (org-at-table-p)]
19040 "--"
19041 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19043 (easy-menu-define org-org-menu org-mode-map "Org menu"
19044 '("Org"
19045 ("Show/Hide"
19046 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19047 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19048 ["Sparse Tree..." org-sparse-tree t]
19049 ["Reveal Context" org-reveal t]
19050 ["Show All" show-all t]
19051 "--"
19052 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19053 "--"
19054 ["New Heading" org-insert-heading t]
19055 ("Navigate Headings"
19056 ["Up" outline-up-heading t]
19057 ["Next" outline-next-visible-heading t]
19058 ["Previous" outline-previous-visible-heading t]
19059 ["Next Same Level" outline-forward-same-level t]
19060 ["Previous Same Level" outline-backward-same-level t]
19061 "--"
19062 ["Jump" org-goto t])
19063 ("Edit Structure"
19064 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19065 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19066 "--"
19067 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19068 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19069 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19070 "--"
19071 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19072 "--"
19073 ["Copy visible text" org-copy-visible t]
19074 "--"
19075 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19076 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19077 ["Demote Heading" org-metaright (not (org-at-table-p))]
19078 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19079 "--"
19080 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19081 "--"
19082 ["Convert to odd levels" org-convert-to-odd-levels t]
19083 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19084 ("Editing"
19085 ["Emphasis..." org-emphasize t]
19086 ["Edit Source Example" org-edit-special t]
19087 "--"
19088 ["Footnote new/jump" org-footnote-action t]
19089 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19090 ("Archive"
19091 ["Archive (default method)" org-archive-subtree-default t]
19092 "--"
19093 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19094 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19095 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19097 "--"
19098 ("Hyperlinks"
19099 ["Store Link (Global)" org-store-link t]
19100 ["Find existing link to here" org-occur-link-in-agenda-files t]
19101 ["Insert Link" org-insert-link t]
19102 ["Follow Link" org-open-at-point t]
19103 "--"
19104 ["Next link" org-next-link t]
19105 ["Previous link" org-previous-link t]
19106 "--"
19107 ["Descriptive Links"
19108 org-toggle-link-display
19109 :style radio
19110 :selected org-descriptive-links
19112 ["Literal Links"
19113 org-toggle-link-display
19114 :style radio
19115 :selected (not org-descriptive-links)])
19116 "--"
19117 ("TODO Lists"
19118 ["TODO/DONE/-" org-todo t]
19119 ("Select keyword"
19120 ["Next keyword" org-shiftright (org-at-heading-p)]
19121 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19122 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19123 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19124 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19125 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19126 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19127 "--"
19128 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19129 :selected org-enforce-todo-dependencies :style toggle :active t]
19130 "Settings for tree at point"
19131 ["Do Children sequentially" org-toggle-ordered-property :style radio
19132 :selected (org-entry-get nil "ORDERED")
19133 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19134 ["Do Children parallel" org-toggle-ordered-property :style radio
19135 :selected (not (org-entry-get nil "ORDERED"))
19136 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19137 "--"
19138 ["Set Priority" org-priority t]
19139 ["Priority Up" org-shiftup t]
19140 ["Priority Down" org-shiftdown t]
19141 "--"
19142 ["Get news from all feeds" org-feed-update-all t]
19143 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19144 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19145 ("TAGS and Properties"
19146 ["Set Tags" org-set-tags-command t]
19147 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19148 "--"
19149 ["Set property" org-set-property t]
19150 ["Column view of properties" org-columns t]
19151 ["Insert Column View DBlock" org-insert-columns-dblock t])
19152 ("Dates and Scheduling"
19153 ["Timestamp" org-time-stamp t]
19154 ["Timestamp (inactive)" org-time-stamp-inactive t]
19155 ("Change Date"
19156 ["1 Day Later" org-shiftright t]
19157 ["1 Day Earlier" org-shiftleft t]
19158 ["1 ... Later" org-shiftup t]
19159 ["1 ... Earlier" org-shiftdown t])
19160 ["Compute Time Range" org-evaluate-time-range t]
19161 ["Schedule Item" org-schedule t]
19162 ["Deadline" org-deadline t]
19163 "--"
19164 ["Custom time format" org-toggle-time-stamp-overlays
19165 :style radio :selected org-display-custom-times]
19166 "--"
19167 ["Goto Calendar" org-goto-calendar t]
19168 ["Date from Calendar" org-date-from-calendar t]
19169 "--"
19170 ["Start/Restart Timer" org-timer-start t]
19171 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19172 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19173 ["Insert Timer String" org-timer t]
19174 ["Insert Timer Item" org-timer-item t])
19175 ("Logging work"
19176 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19177 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19178 ["Clock out" org-clock-out t]
19179 ["Clock cancel" org-clock-cancel t]
19180 "--"
19181 ["Mark as default task" org-clock-mark-default-task t]
19182 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19183 ["Goto running clock" org-clock-goto t]
19184 "--"
19185 ["Display times" org-clock-display t]
19186 ["Create clock table" org-clock-report t]
19187 "--"
19188 ["Record DONE time"
19189 (progn (setq org-log-done (not org-log-done))
19190 (message "Switching to %s will %s record a timestamp"
19191 (car org-done-keywords)
19192 (if org-log-done "automatically" "not")))
19193 :style toggle :selected org-log-done])
19194 "--"
19195 ["Agenda Command..." org-agenda t]
19196 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19197 ("File List for Agenda")
19198 ("Special views current file"
19199 ["TODO Tree" org-show-todo-tree t]
19200 ["Check Deadlines" org-check-deadlines t]
19201 ["Timeline" org-timeline t]
19202 ["Tags/Property tree" org-match-sparse-tree t])
19203 "--"
19204 ["Export/Publish..." org-export t]
19205 ("LaTeX"
19206 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19207 :selected org-cdlatex-mode]
19208 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19209 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19210 ["Modify math symbol" org-cdlatex-math-modify
19211 (org-inside-LaTeX-fragment-p)]
19212 ["Insert citation" org-reftex-citation t]
19213 "--"
19214 ["Template for BEAMER" (progn (require 'org-beamer)
19215 (org-insert-beamer-options-template)) t])
19216 "--"
19217 ("MobileOrg"
19218 ["Push Files and Views" org-mobile-push t]
19219 ["Get Captured and Flagged" org-mobile-pull t]
19220 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19221 "--"
19222 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19223 "--"
19224 ("Documentation"
19225 ["Show Version" org-version t]
19226 ["Info Documentation" org-info t])
19227 ("Customize"
19228 ["Browse Org Group" org-customize t]
19229 "--"
19230 ["Expand This Menu" org-create-customize-menu
19231 (fboundp 'customize-menu-create)])
19232 ["Send bug report" org-submit-bug-report t]
19233 "--"
19234 ("Refresh/Reload"
19235 ["Refresh setup current buffer" org-mode-restart t]
19236 ["Reload Org (after update)" org-reload t]
19237 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19240 (defun org-info (&optional node)
19241 "Read documentation for Org-mode in the info system.
19242 With optional NODE, go directly to that node."
19243 (interactive)
19244 (info (format "(org)%s" (or node ""))))
19246 ;;;###autoload
19247 (defun org-submit-bug-report ()
19248 "Submit a bug report on Org-mode via mail.
19250 Don't hesitate to report any problems or inaccurate documentation.
19252 If you don't have setup sending mail from (X)Emacs, please copy the
19253 output buffer into your mail program, as it gives us important
19254 information about your Org-mode version and configuration."
19255 (interactive)
19256 (require 'reporter)
19257 (org-load-modules-maybe)
19258 (org-require-autoloaded-modules)
19259 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19260 (reporter-submit-bug-report
19261 "emacs-orgmode@gnu.org"
19262 (org-version)
19263 (let (list)
19264 (save-window-excursion
19265 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19266 (delete-other-windows)
19267 (erase-buffer)
19268 (insert "You are about to submit a bug report to the Org-mode mailing list.
19270 We would like to add your full Org-mode and Outline configuration to the
19271 bug report. This greatly simplifies the work of the maintainer and
19272 other experts on the mailing list.
19274 HOWEVER, some variables you have customized may contain private
19275 information. The names of customers, colleagues, or friends, might
19276 appear in the form of file names, tags, todo states, or search strings.
19277 If you answer yes to the prompt, you might want to check and remove
19278 such private information before sending the email.")
19279 (add-text-properties (point-min) (point-max) '(face org-warning))
19280 (when (yes-or-no-p "Include your Org-mode configuration ")
19281 (mapatoms
19282 (lambda (v)
19283 (and (boundp v)
19284 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19285 (or (and (symbol-value v)
19286 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19287 (and
19288 (get v 'custom-type) (get v 'standard-value)
19289 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19290 (push v list)))))
19291 (kill-buffer (get-buffer "*Warn about privacy*"))
19292 list))
19293 nil nil
19294 "Remember to cover the basics, that is, what you expected to happen and
19295 what in fact did happen. You don't know how to make a good report? See
19297 http://orgmode.org/manual/Feedback.html#Feedback
19299 Your bug report will be posted to the Org-mode mailing list.
19300 ------------------------------------------------------------------------")
19301 (save-excursion
19302 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19303 (replace-match "\\1Bug: \\3 [\\2]")))))
19306 (defun org-install-agenda-files-menu ()
19307 (let ((bl (buffer-list)))
19308 (save-excursion
19309 (while bl
19310 (set-buffer (pop bl))
19311 (if (eq major-mode 'org-mode) (setq bl nil)))
19312 (when (eq major-mode 'org-mode)
19313 (easy-menu-change
19314 '("Org") "File List for Agenda"
19315 (append
19316 (list
19317 ["Edit File List" (org-edit-agenda-file-list) t]
19318 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19319 ["Remove Current File from List" org-remove-file t]
19320 ["Cycle through agenda files" org-cycle-agenda-files t]
19321 ["Occur in all agenda files" org-occur-in-agenda-files t]
19322 "--")
19323 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19325 ;;;; Documentation
19327 ;;;###autoload
19328 (defun org-require-autoloaded-modules ()
19329 (interactive)
19330 (mapc 'require
19331 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19332 org-docbook org-exp org-html org-icalendar
19333 org-id org-latex
19334 org-publish org-remember org-table
19335 org-timer org-xoxo)))
19337 ;;;###autoload
19338 (defun org-reload (&optional uncompiled)
19339 "Reload all org lisp files.
19340 With prefix arg UNCOMPILED, load the uncompiled versions."
19341 (interactive "P")
19342 (require 'find-func)
19343 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19344 (dir-org (file-name-directory (org-find-library-name "org")))
19345 (dir-org-contrib (ignore-errors
19346 (file-name-directory
19347 (org-find-library-name "org-contribdir"))))
19348 (babel-files
19349 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19350 (append (list nil "comint" "eval" "exp" "keys"
19351 "lob" "ref" "table" "tangle")
19352 (delq nil
19353 (mapcar
19354 (lambda (lang)
19355 (when (cdr lang) (symbol-name (car lang))))
19356 org-babel-load-languages)))))
19357 (files
19358 (append (directory-files dir-org t file-re)
19359 babel-files
19360 (and dir-org-contrib
19361 (directory-files dir-org-contrib t file-re))))
19362 (remove-re (concat (if (featurep 'xemacs)
19363 "org-colview" "org-colview-xemacs")
19364 "\\'")))
19365 (setq files (mapcar 'file-name-sans-extension files))
19366 (setq files (mapcar
19367 (lambda (x) (if (string-match remove-re x) nil x))
19368 files))
19369 (setq files (delq nil files))
19370 (mapc
19371 (lambda (f)
19372 (when (featurep (intern (file-name-nondirectory f)))
19373 (if (and (not uncompiled)
19374 (file-exists-p (concat f ".elc")))
19375 (load (concat f ".elc") nil nil t)
19376 (load (concat f ".el") nil nil t))))
19377 files))
19378 (org-version))
19380 ;;;###autoload
19381 (defun org-customize ()
19382 "Call the customize function with org as argument."
19383 (interactive)
19384 (org-load-modules-maybe)
19385 (org-require-autoloaded-modules)
19386 (customize-browse 'org))
19388 (defun org-create-customize-menu ()
19389 "Create a full customization menu for Org-mode, insert it into the menu."
19390 (interactive)
19391 (org-load-modules-maybe)
19392 (org-require-autoloaded-modules)
19393 (if (fboundp 'customize-menu-create)
19394 (progn
19395 (easy-menu-change
19396 '("Org") "Customize"
19397 `(["Browse Org group" org-customize t]
19398 "--"
19399 ,(customize-menu-create 'org)
19400 ["Set" Custom-set t]
19401 ["Save" Custom-save t]
19402 ["Reset to Current" Custom-reset-current t]
19403 ["Reset to Saved" Custom-reset-saved t]
19404 ["Reset to Standard Settings" Custom-reset-standard t]))
19405 (message "\"Org\"-menu now contains full customization menu"))
19406 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19408 ;;;; Miscellaneous stuff
19410 ;;; Generally useful functions
19412 (defun org-get-at-bol (property)
19413 "Get text property PROPERTY at beginning of line."
19414 (get-text-property (point-at-bol) property))
19416 (defun org-find-text-property-in-string (prop s)
19417 "Return the first non-nil value of property PROP in string S."
19418 (or (get-text-property 0 prop s)
19419 (get-text-property (or (next-single-property-change 0 prop s) 0)
19420 prop s)))
19422 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19423 "Display the given MESSAGE as a warning."
19424 (if (fboundp 'display-warning)
19425 (display-warning 'org message
19426 (if (featurep 'xemacs) 'warning :warning))
19427 (let ((buf (get-buffer-create "*Org warnings*")))
19428 (with-current-buffer buf
19429 (goto-char (point-max))
19430 (insert "Warning (Org): " message)
19431 (unless (bolp)
19432 (newline)))
19433 (display-buffer buf)
19434 (sit-for 0))))
19436 (defun org-eval (form)
19437 "Eval FORM and return result."
19438 (condition-case error
19439 (eval form)
19440 (error (format "%%![Error: %s]" error))))
19442 (defun org-in-clocktable-p ()
19443 "Check if the cursor is in a clocktable."
19444 (let ((pos (point)) start)
19445 (save-excursion
19446 (end-of-line 1)
19447 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19448 (setq start (match-beginning 0))
19449 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19450 (>= (match-end 0) pos)
19451 start))))
19453 (defun org-in-commented-line ()
19454 "Is point in a line starting with `#'?"
19455 (equal (char-after (point-at-bol)) ?#))
19457 (defun org-in-indented-comment-line ()
19458 "Is point in a line starting with `#' after some white space?"
19459 (save-excursion
19460 (save-match-data
19461 (goto-char (point-at-bol))
19462 (looking-at "[ \t]*#"))))
19464 (defun org-in-verbatim-emphasis ()
19465 (save-match-data
19466 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19468 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19469 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19470 (if (and marker (marker-buffer marker)
19471 (buffer-live-p (marker-buffer marker)))
19472 (progn
19473 (org-pop-to-buffer-same-window (marker-buffer marker))
19474 (if (or (> marker (point-max)) (< marker (point-min)))
19475 (widen))
19476 (goto-char marker)
19477 (org-show-context 'org-goto))
19478 (if bookmark
19479 (bookmark-jump bookmark)
19480 (error "Cannot find location"))))
19482 (defun org-quote-csv-field (s)
19483 "Quote field for inclusion in CSV material."
19484 (if (string-match "[\",]" s)
19485 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19488 (defun org-force-self-insert (N)
19489 "Needed to enforce self-insert under remapping."
19490 (interactive "p")
19491 (self-insert-command N))
19493 (defun org-string-width (s)
19494 "Compute width of string, ignoring invisible characters.
19495 This ignores character with invisibility property `org-link', and also
19496 characters with property `org-cwidth', because these will become invisible
19497 upon the next fontification round."
19498 (let (b l)
19499 (when (or (eq t buffer-invisibility-spec)
19500 (assq 'org-link buffer-invisibility-spec))
19501 (while (setq b (text-property-any 0 (length s)
19502 'invisible 'org-link s))
19503 (setq s (concat (substring s 0 b)
19504 (substring s (or (next-single-property-change
19505 b 'invisible s) (length s)))))))
19506 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19507 (setq s (concat (substring s 0 b)
19508 (substring s (or (next-single-property-change
19509 b 'org-cwidth s) (length s))))))
19510 (setq l (string-width s) b -1)
19511 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19512 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19515 (defun org-shorten-string (s maxlength)
19516 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19517 If the string is shorter or has length MAXLENGTH, just return the
19518 original string. If it is longer, the functions finds a space in the
19519 string, breaks this string off at that locations and adds three dots
19520 as ellipsis. Including the ellipsis, the string will not be longer
19521 than MAXLENGTH. If finding a good breaking point in the string does
19522 not work, the string is just chopped off in the middle of a word
19523 if necessary."
19524 (if (<= (length s) maxlength)
19526 (let* ((n (max (- maxlength 4) 1))
19527 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19528 (if (string-match re s)
19529 (concat (match-string 1 s) "...")
19530 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19532 (defun org-get-indentation (&optional line)
19533 "Get the indentation of the current line, interpreting tabs.
19534 When LINE is given, assume it represents a line and compute its indentation."
19535 (if line
19536 (if (string-match "^ *" (org-remove-tabs line))
19537 (match-end 0))
19538 (save-excursion
19539 (beginning-of-line 1)
19540 (skip-chars-forward " \t")
19541 (current-column))))
19543 (defun org-get-string-indentation (s)
19544 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19545 (let ((n -1) (i 0) (w tab-width) c)
19546 (catch 'exit
19547 (while (< (setq n (1+ n)) (length s))
19548 (setq c (aref s n))
19549 (cond ((= c ?\ ) (setq i (1+ i)))
19550 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19551 (t (throw 'exit t)))))
19554 (defun org-remove-tabs (s &optional width)
19555 "Replace tabulators in S with spaces.
19556 Assumes that s is a single line, starting in column 0."
19557 (setq width (or width tab-width))
19558 (while (string-match "\t" s)
19559 (setq s (replace-match
19560 (make-string
19561 (- (* width (/ (+ (match-beginning 0) width) width))
19562 (match-beginning 0)) ?\ )
19563 t t s)))
19566 (defun org-fix-indentation (line ind)
19567 "Fix indentation in LINE.
19568 IND is a cons cell with target and minimum indentation.
19569 If the current indentation in LINE is smaller than the minimum,
19570 leave it alone. If it is larger than ind, set it to the target."
19571 (let* ((l (org-remove-tabs line))
19572 (i (org-get-indentation l))
19573 (i1 (car ind)) (i2 (cdr ind)))
19574 (if (>= i i2) (setq l (substring line i2)))
19575 (if (> i1 0)
19576 (concat (make-string i1 ?\ ) l)
19577 l)))
19579 (defun org-remove-indentation (code &optional n)
19580 "Remove the maximum common indentation from the lines in CODE.
19581 N may optionally be the number of spaces to remove."
19582 (with-temp-buffer
19583 (insert code)
19584 (org-do-remove-indentation n)
19585 (buffer-string)))
19587 (defun org-do-remove-indentation (&optional n)
19588 "Remove the maximum common indentation from the buffer."
19589 (untabify (point-min) (point-max))
19590 (let ((min 10000) re)
19591 (if n
19592 (setq min n)
19593 (goto-char (point-min))
19594 (while (re-search-forward "^ *[^ \n]" nil t)
19595 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19596 (unless (or (= min 0) (= min 10000))
19597 (setq re (format "^ \\{%d\\}" min))
19598 (goto-char (point-min))
19599 (while (re-search-forward re nil t)
19600 (replace-match "")
19601 (end-of-line 1))
19602 min)))
19604 (defun org-fill-template (template alist)
19605 "Find each %key of ALIST in TEMPLATE and replace it."
19606 (let ((case-fold-search nil)
19607 entry key value)
19608 (setq alist (sort (copy-sequence alist)
19609 (lambda (a b) (< (length (car a)) (length (car b))))))
19610 (while (setq entry (pop alist))
19611 (setq template
19612 (replace-regexp-in-string
19613 (concat "%" (regexp-quote (car entry)))
19614 (cdr entry) template t t)))
19615 template))
19617 (defun org-base-buffer (buffer)
19618 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19619 (if (not buffer)
19620 buffer
19621 (or (buffer-base-buffer buffer)
19622 buffer)))
19624 (defun org-trim (s)
19625 "Remove whitespace at beginning and end of string."
19626 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19627 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19630 (defun org-wrap (string &optional width lines)
19631 "Wrap string to either a number of lines, or a width in characters.
19632 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19633 that costs. If there is a word longer than WIDTH, the text is actually
19634 wrapped to the length of that word.
19635 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19636 many lines, whatever width that takes.
19637 The return value is a list of lines, without newlines at the end."
19638 (let* ((words (org-split-string string "[ \t\n]+"))
19639 (maxword (apply 'max (mapcar 'org-string-width words)))
19640 w ll)
19641 (cond (width
19642 (org-do-wrap words (max maxword width)))
19643 (lines
19644 (setq w maxword)
19645 (setq ll (org-do-wrap words maxword))
19646 (if (<= (length ll) lines)
19648 (setq ll words)
19649 (while (> (length ll) lines)
19650 (setq w (1+ w))
19651 (setq ll (org-do-wrap words w)))
19652 ll))
19653 (t (error "Cannot wrap this")))))
19655 (defun org-do-wrap (words width)
19656 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19657 (let (lines line)
19658 (while words
19659 (setq line (pop words))
19660 (while (and words (< (+ (length line) (length (car words))) width))
19661 (setq line (concat line " " (pop words))))
19662 (setq lines (push line lines)))
19663 (nreverse lines)))
19665 (defun org-split-string (string &optional separators)
19666 "Splits STRING into substrings at SEPARATORS.
19667 No empty strings are returned if there are matches at the beginning
19668 and end of string."
19669 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19670 (start 0)
19671 notfirst
19672 (list nil))
19673 (while (and (string-match rexp string
19674 (if (and notfirst
19675 (= start (match-beginning 0))
19676 (< start (length string)))
19677 (1+ start) start))
19678 (< (match-beginning 0) (length string)))
19679 (setq notfirst t)
19680 (or (eq (match-beginning 0) 0)
19681 (and (eq (match-beginning 0) (match-end 0))
19682 (eq (match-beginning 0) start))
19683 (setq list
19684 (cons (substring string start (match-beginning 0))
19685 list)))
19686 (setq start (match-end 0)))
19687 (or (eq start (length string))
19688 (setq list
19689 (cons (substring string start)
19690 list)))
19691 (nreverse list)))
19693 (defun org-quote-vert (s)
19694 "Replace \"|\" with \"\\vert\"."
19695 (while (string-match "|" s)
19696 (setq s (replace-match "\\vert" t t s)))
19699 (defun org-uuidgen-p (s)
19700 "Is S an ID created by UUIDGEN?"
19701 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19703 (defun org-in-src-block-p nil
19704 "Whether point is in a code source block."
19705 (let (ov)
19706 (when (setq ov (overlays-at (point)))
19707 (memq 'org-block-background
19708 (overlay-properties
19709 (car ov))))))
19711 (defun org-context ()
19712 "Return a list of contexts of the current cursor position.
19713 If several contexts apply, all are returned.
19714 Each context entry is a list with a symbol naming the context, and
19715 two positions indicating start and end of the context. Possible
19716 contexts are:
19718 :headline anywhere in a headline
19719 :headline-stars on the leading stars in a headline
19720 :todo-keyword on a TODO keyword (including DONE) in a headline
19721 :tags on the TAGS in a headline
19722 :priority on the priority cookie in a headline
19723 :item on the first line of a plain list item
19724 :item-bullet on the bullet/number of a plain list item
19725 :checkbox on the checkbox in a plain list item
19726 :table in an org-mode table
19727 :table-special on a special filed in a table
19728 :table-table in a table.el table
19729 :clocktable in a clocktable
19730 :src-block in a source block
19731 :link on a hyperlink
19732 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19733 :target on a <<target>>
19734 :radio-target on a <<<radio-target>>>
19735 :latex-fragment on a LaTeX fragment
19736 :latex-preview on a LaTeX fragment with overlaid preview image
19738 This function expects the position to be visible because it uses font-lock
19739 faces as a help to recognize the following contexts: :table-special, :link,
19740 and :keyword."
19741 (let* ((f (get-text-property (point) 'face))
19742 (faces (if (listp f) f (list f)))
19743 (case-fold-search t)
19744 (p (point)) clist o)
19745 ;; First the large context
19746 (cond
19747 ((org-at-heading-p t)
19748 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19749 (when (progn
19750 (beginning-of-line 1)
19751 (looking-at org-todo-line-tags-regexp))
19752 (push (org-point-in-group p 1 :headline-stars) clist)
19753 (push (org-point-in-group p 2 :todo-keyword) clist)
19754 (push (org-point-in-group p 4 :tags) clist))
19755 (goto-char p)
19756 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19757 (if (looking-at "\\[#[A-Z0-9]\\]")
19758 (push (org-point-in-group p 0 :priority) clist)))
19760 ((org-at-item-p)
19761 (push (org-point-in-group p 2 :item-bullet) clist)
19762 (push (list :item (point-at-bol)
19763 (save-excursion (org-end-of-item) (point)))
19764 clist)
19765 (and (org-at-item-checkbox-p)
19766 (push (org-point-in-group p 0 :checkbox) clist)))
19768 ((org-at-table-p)
19769 (push (list :table (org-table-begin) (org-table-end)) clist)
19770 (if (memq 'org-formula faces)
19771 (push (list :table-special
19772 (previous-single-property-change p 'face)
19773 (next-single-property-change p 'face)) clist)))
19774 ((org-at-table-p 'any)
19775 (push (list :table-table) clist)))
19776 (goto-char p)
19778 ;; New the "medium" contexts: clocktables, source blocks
19779 (cond ((org-in-clocktable-p)
19780 (push (list :clocktable
19781 (and (or (looking-at "#\\+BEGIN: clocktable")
19782 (search-backward "#+BEGIN: clocktable" nil t))
19783 (match-beginning 0))
19784 (and (re-search-forward "#\\+END:?" nil t)
19785 (match-end 0))) clist))
19786 ((org-in-src-block-p)
19787 (push (list :src-block
19788 (and (or (looking-at "#\\+BEGIN_SRC")
19789 (search-backward "#+BEGIN_SRC" nil t))
19790 (match-beginning 0))
19791 (and (search-forward "#+END_SRC" nil t)
19792 (match-beginning 0))) clist)))
19793 (goto-char p)
19795 ;; Now the small context
19796 (cond
19797 ((org-at-timestamp-p)
19798 (push (org-point-in-group p 0 :timestamp) clist))
19799 ((memq 'org-link faces)
19800 (push (list :link
19801 (previous-single-property-change p 'face)
19802 (next-single-property-change p 'face)) clist))
19803 ((memq 'org-special-keyword faces)
19804 (push (list :keyword
19805 (previous-single-property-change p 'face)
19806 (next-single-property-change p 'face)) clist))
19807 ((org-at-target-p)
19808 (push (org-point-in-group p 0 :target) clist)
19809 (goto-char (1- (match-beginning 0)))
19810 (if (looking-at org-radio-target-regexp)
19811 (push (org-point-in-group p 0 :radio-target) clist))
19812 (goto-char p))
19813 ((setq o (car (delq nil
19814 (mapcar
19815 (lambda (x)
19816 (if (memq x org-latex-fragment-image-overlays) x))
19817 (overlays-at (point))))))
19818 (push (list :latex-fragment
19819 (overlay-start o) (overlay-end o)) clist)
19820 (push (list :latex-preview
19821 (overlay-start o) (overlay-end o)) clist))
19822 ((org-inside-LaTeX-fragment-p)
19823 ;; FIXME: positions wrong.
19824 (push (list :latex-fragment (point) (point)) clist)))
19826 (setq clist (nreverse (delq nil clist)))
19827 clist))
19829 ;; FIXME: Compare with at-regexp-p Do we need both?
19830 (defun org-in-regexp (re &optional nlines visually)
19831 "Check if point is inside a match of regexp.
19832 Normally only the current line is checked, but you can include NLINES extra
19833 lines both before and after point into the search.
19834 If VISUALLY is set, require that the cursor is not after the match but
19835 really on, so that the block visually is on the match."
19836 (catch 'exit
19837 (let ((pos (point))
19838 (eol (point-at-eol (+ 1 (or nlines 0))))
19839 (inc (if visually 1 0)))
19840 (save-excursion
19841 (beginning-of-line (- 1 (or nlines 0)))
19842 (while (re-search-forward re eol t)
19843 (if (and (<= (match-beginning 0) pos)
19844 (>= (+ inc (match-end 0)) pos))
19845 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19847 (defun org-at-regexp-p (regexp)
19848 "Is point inside a match of REGEXP in the current line?"
19849 (catch 'exit
19850 (save-excursion
19851 (let ((pos (point)) (end (point-at-eol)))
19852 (beginning-of-line 1)
19853 (while (re-search-forward regexp end t)
19854 (if (and (<= (match-beginning 0) pos)
19855 (>= (match-end 0) pos))
19856 (throw 'exit t)))
19857 nil))))
19859 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19860 "Non-nil when point is between matches of START-RE and END-RE.
19862 Also return a non-nil value when point is on one of the matches.
19864 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19865 buffer positions. Default values are the positions of headlines
19866 surrounding the point.
19868 The functions returns a cons cell whose car (resp. cdr) is the
19869 position before START-RE (resp. after END-RE)."
19870 (save-match-data
19871 (let ((pos (point))
19872 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19873 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19874 beg end)
19875 (save-excursion
19876 ;; Point is on a block when on START-RE or if START-RE can be
19877 ;; found before it...
19878 (and (or (org-at-regexp-p start-re)
19879 (re-search-backward start-re limit-up t))
19880 (setq beg (match-beginning 0))
19881 ;; ... and END-RE after it...
19882 (goto-char (match-end 0))
19883 (re-search-forward end-re limit-down t)
19884 (> (setq end (match-end 0)) pos)
19885 ;; ... without another START-RE in-between.
19886 (goto-char (match-beginning 0))
19887 (not (re-search-backward start-re (1+ beg) t))
19888 ;; Return value.
19889 (cons beg end))))))
19891 (defun org-in-block-p (names)
19892 "Non-nil when point belongs to a block whose name belongs to NAMES.
19894 NAMES is a list of strings containing names of blocks.
19896 Return first block name matched, or nil. Beware that in case of
19897 nested blocks, the returned name may not belong to the closest
19898 block from point."
19899 (save-match-data
19900 (catch 'exit
19901 (let ((case-fold-search t)
19902 (lim-up (save-excursion (outline-previous-heading)))
19903 (lim-down (save-excursion (outline-next-heading))))
19904 (mapc (lambda (name)
19905 (let ((n (regexp-quote name)))
19906 (when (org-between-regexps-p
19907 (concat "^[ \t]*#\\+begin_" n)
19908 (concat "^[ \t]*#\\+end_" n)
19909 lim-up lim-down)
19910 (throw 'exit n))))
19911 names))
19912 nil)))
19914 (defun org-occur-in-agenda-files (regexp &optional nlines)
19915 "Call `multi-occur' with buffers for all agenda files."
19916 (interactive "sOrg-files matching: \np")
19917 (let* ((files (org-agenda-files))
19918 (tnames (mapcar 'file-truename files))
19919 (extra org-agenda-text-search-extra-files)
19921 (when (eq (car extra) 'agenda-archives)
19922 (setq extra (cdr extra))
19923 (setq files (org-add-archive-files files)))
19924 (while (setq f (pop extra))
19925 (unless (member (file-truename f) tnames)
19926 (add-to-list 'files f 'append)
19927 (add-to-list 'tnames (file-truename f) 'append)))
19928 (multi-occur
19929 (mapcar (lambda (x)
19930 (with-current-buffer
19931 (or (get-file-buffer x) (find-file-noselect x))
19932 (widen)
19933 (current-buffer)))
19934 files)
19935 regexp)))
19937 (if (boundp 'occur-mode-find-occurrence-hook)
19938 ;; Emacs 23
19939 (add-hook 'occur-mode-find-occurrence-hook
19940 (lambda ()
19941 (when (eq major-mode 'org-mode)
19942 (org-reveal))))
19943 ;; Emacs 22
19944 (defadvice occur-mode-goto-occurrence
19945 (after org-occur-reveal activate)
19946 (and (eq major-mode 'org-mode) (org-reveal)))
19947 (defadvice occur-mode-goto-occurrence-other-window
19948 (after org-occur-reveal activate)
19949 (and (eq major-mode 'org-mode) (org-reveal)))
19950 (defadvice occur-mode-display-occurrence
19951 (after org-occur-reveal activate)
19952 (when (eq major-mode 'org-mode)
19953 (let ((pos (occur-mode-find-occurrence)))
19954 (with-current-buffer (marker-buffer pos)
19955 (save-excursion
19956 (goto-char pos)
19957 (org-reveal)))))))
19959 (defun org-occur-link-in-agenda-files ()
19960 "Create a link and search for it in the agendas.
19961 The link is not stored in `org-stored-links', it is just created
19962 for the search purpose."
19963 (interactive)
19964 (let ((link (condition-case nil
19965 (org-store-link nil)
19966 (error "Unable to create a link to here"))))
19967 (org-occur-in-agenda-files (regexp-quote link))))
19969 (defun org-uniquify (list)
19970 "Remove duplicate elements from LIST."
19971 (let (res)
19972 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19973 res))
19975 (defun org-delete-all (elts list)
19976 "Remove all elements in ELTS from LIST."
19977 (while elts
19978 (setq list (delete (pop elts) list)))
19979 list)
19981 (defun org-count (cl-item cl-seq)
19982 "Count the number of occurrences of ITEM in SEQ.
19983 Taken from `count' in cl-seq.el with all keyword arguments removed."
19984 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19985 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19986 (while (< cl-start cl-end)
19987 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19988 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19989 (setq cl-start (1+ cl-start)))
19990 cl-count))
19992 (defun org-remove-if (predicate seq)
19993 "Remove everything from SEQ that fulfills PREDICATE."
19994 (let (res e)
19995 (while seq
19996 (setq e (pop seq))
19997 (if (not (funcall predicate e)) (push e res)))
19998 (nreverse res)))
20000 (defun org-remove-if-not (predicate seq)
20001 "Remove everything from SEQ that does not fulfill PREDICATE."
20002 (let (res e)
20003 (while seq
20004 (setq e (pop seq))
20005 (if (funcall predicate e) (push e res)))
20006 (nreverse res)))
20008 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20009 "Reduce two-argument FUNCTION across SEQ.
20010 Taken from `reduce' in cl-seq.el with all keyword arguments but
20011 \":initial-value\" removed."
20012 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20013 (cadr (memq :initial-value cl-keys)))
20014 (cl-seq (pop cl-seq))
20015 (t (funcall cl-func)))))
20016 (while cl-seq
20017 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20018 cl-accum))
20020 (defun org-back-over-empty-lines ()
20021 "Move backwards over whitespace, to the beginning of the first empty line.
20022 Returns the number of empty lines passed."
20023 (let ((pos (point)))
20024 (if (cdr (assoc 'heading org-blank-before-new-entry))
20025 (skip-chars-backward " \t\n\r")
20026 (unless (eobp)
20027 (forward-line -1)))
20028 (beginning-of-line 2)
20029 (goto-char (min (point) pos))
20030 (count-lines (point) pos)))
20032 (defun org-skip-whitespace ()
20033 (skip-chars-forward " \t\n\r"))
20035 (defun org-point-in-group (point group &optional context)
20036 "Check if POINT is in match-group GROUP.
20037 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20038 match. If the match group does not exist or point is not inside it,
20039 return nil."
20040 (and (match-beginning group)
20041 (>= point (match-beginning group))
20042 (<= point (match-end group))
20043 (if context
20044 (list context (match-beginning group) (match-end group))
20045 t)))
20047 (defun org-switch-to-buffer-other-window (&rest args)
20048 "Switch to buffer in a second window on the current frame.
20049 In particular, do not allow pop-up frames.
20050 Returns the newly created buffer."
20051 (let (pop-up-frames special-display-buffer-names special-display-regexps
20052 special-display-function)
20053 (apply 'switch-to-buffer-other-window args)))
20055 (defun org-combine-plists (&rest plists)
20056 "Create a single property list from all plists in PLISTS.
20057 The process starts by copying the first list, and then setting properties
20058 from the other lists. Settings in the last list are the most significant
20059 ones and overrule settings in the other lists."
20060 (let ((rtn (copy-sequence (pop plists)))
20061 p v ls)
20062 (while plists
20063 (setq ls (pop plists))
20064 (while ls
20065 (setq p (pop ls) v (pop ls))
20066 (setq rtn (plist-put rtn p v))))
20067 rtn))
20069 (defun org-move-line-down (arg)
20070 "Move the current line down. With prefix argument, move it past ARG lines."
20071 (interactive "p")
20072 (let ((col (current-column))
20073 beg end pos)
20074 (beginning-of-line 1) (setq beg (point))
20075 (beginning-of-line 2) (setq end (point))
20076 (beginning-of-line (+ 1 arg))
20077 (setq pos (move-marker (make-marker) (point)))
20078 (insert (delete-and-extract-region beg end))
20079 (goto-char pos)
20080 (org-move-to-column col)))
20082 (defun org-move-line-up (arg)
20083 "Move the current line up. With prefix argument, move it past ARG lines."
20084 (interactive "p")
20085 (let ((col (current-column))
20086 beg end pos)
20087 (beginning-of-line 1) (setq beg (point))
20088 (beginning-of-line 2) (setq end (point))
20089 (beginning-of-line (- arg))
20090 (setq pos (move-marker (make-marker) (point)))
20091 (insert (delete-and-extract-region beg end))
20092 (goto-char pos)
20093 (org-move-to-column col)))
20095 (defun org-replace-escapes (string table)
20096 "Replace %-escapes in STRING with values in TABLE.
20097 TABLE is an association list with keys like \"%a\" and string values.
20098 The sequences in STRING may contain normal field width and padding information,
20099 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20100 so values can contain further %-escapes if they are define later in TABLE."
20101 (let ((tbl (copy-alist table))
20102 (case-fold-search nil)
20103 (pchg 0)
20104 e re rpl)
20105 (while (setq e (pop tbl))
20106 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20107 (when (and (cdr e) (string-match re (cdr e)))
20108 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20109 (safe "SREF"))
20110 (add-text-properties 0 3 (list 'sref sref) safe)
20111 (setcdr e (replace-match safe t t (cdr e)))))
20112 (while (string-match re string)
20113 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20114 (cdr e)))
20115 (setq string (replace-match rpl t t string))))
20116 (while (setq pchg (next-property-change pchg string))
20117 (let ((sref (get-text-property pchg 'sref string)))
20118 (when (and sref (string-match "SREF" string pchg))
20119 (setq string (replace-match sref t t string)))))
20120 string))
20122 (defun org-sublist (list start end)
20123 "Return a section of LIST, from START to END.
20124 Counting starts at 1."
20125 (let (rtn (c start))
20126 (setq list (nthcdr (1- start) list))
20127 (while (and list (<= c end))
20128 (push (pop list) rtn)
20129 (setq c (1+ c)))
20130 (nreverse rtn)))
20132 (defun org-find-base-buffer-visiting (file)
20133 "Like `find-buffer-visiting' but always return the base buffer and
20134 not an indirect buffer."
20135 (let ((buf (or (get-file-buffer file)
20136 (find-buffer-visiting file))))
20137 (if buf
20138 (or (buffer-base-buffer buf) buf)
20139 nil)))
20141 (defun org-image-file-name-regexp (&optional extensions)
20142 "Return regexp matching the file names of images.
20143 If EXTENSIONS is given, only match these."
20144 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20145 (image-file-name-regexp)
20146 (let ((image-file-name-extensions
20147 (or extensions
20148 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20149 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20150 (concat "\\."
20151 (regexp-opt (nconc (mapcar 'upcase
20152 image-file-name-extensions)
20153 image-file-name-extensions)
20155 "\\'"))))
20157 (defun org-file-image-p (file &optional extensions)
20158 "Return non-nil if FILE is an image."
20159 (save-match-data
20160 (string-match (org-image-file-name-regexp extensions) file)))
20162 (defun org-get-cursor-date ()
20163 "Return the date at cursor in as a time.
20164 This works in the calendar and in the agenda, anywhere else it just
20165 returns the current time."
20166 (let (date day defd)
20167 (cond
20168 ((eq major-mode 'calendar-mode)
20169 (setq date (calendar-cursor-to-date)
20170 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20171 ((eq major-mode 'org-agenda-mode)
20172 (setq day (get-text-property (point) 'day))
20173 (if day
20174 (setq date (calendar-gregorian-from-absolute day)
20175 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20176 (nth 2 date))))))
20177 (or defd (current-time))))
20179 (defvar org-agenda-action-marker (make-marker)
20180 "Marker pointing to the entry for the next agenda action.")
20182 (defun org-mark-entry-for-agenda-action ()
20183 "Mark the current entry as target of an agenda action.
20184 Agenda actions are actions executed from the agenda with the key `k',
20185 which make use of the date at the cursor."
20186 (interactive)
20187 (move-marker org-agenda-action-marker
20188 (save-excursion (org-back-to-heading t) (point))
20189 (current-buffer))
20190 (message
20191 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20193 (defun org-mark-subtree ()
20194 "Mark the current subtree.
20195 This puts point at the start of the current subtree, and mark at the end.
20197 If point is in an inline task, mark that task instead."
20198 (interactive)
20199 (let ((inline-task-p
20200 (and (featurep 'org-inlinetask)
20201 (org-inlinetask-in-task-p)))
20202 (beg))
20203 ;; Get beginning of subtree
20204 (cond
20205 (inline-task-p (org-inlinetask-goto-beginning))
20206 ((org-at-heading-p) (beginning-of-line))
20207 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20208 (setq beg (point))
20209 ;; Get end of it
20210 (if inline-task-p
20211 (org-inlinetask-goto-end)
20212 (org-end-of-subtree))
20213 ;; Mark zone
20214 (push-mark (point) nil t)
20215 (goto-char beg)))
20217 ;;; Paragraph filling stuff.
20218 ;; We want this to be just right, so use the full arsenal.
20220 (defun org-indent-line-function ()
20221 "Indent line depending on context."
20222 (interactive)
20223 (let* ((pos (point))
20224 (itemp (org-at-item-p))
20225 (case-fold-search t)
20226 (org-drawer-regexp (or org-drawer-regexp "\000"))
20227 (inline-task-p (and (featurep 'org-inlinetask)
20228 (org-inlinetask-in-task-p)))
20229 (inline-re (and inline-task-p
20230 (org-inlinetask-outline-regexp)))
20231 column)
20232 (beginning-of-line 1)
20233 (cond
20234 ;; Comments
20235 ((looking-at "# ") (setq column 0))
20236 ;; Headings
20237 ((looking-at org-outline-regexp) (setq column 0))
20238 ;; Included files
20239 ((looking-at "#\\+include:") (setq column 0))
20240 ;; Footnote definition
20241 ((looking-at org-footnote-definition-re) (setq column 0))
20242 ;; Literal examples
20243 ((looking-at "[ \t]*:\\( \\|$\\)")
20244 (setq column (org-get-indentation))) ; do nothing
20245 ;; Lists
20246 ((ignore-errors (goto-char (org-in-item-p)))
20247 (setq column (if itemp
20248 (org-get-indentation)
20249 (org-list-item-body-column (point))))
20250 (goto-char pos))
20251 ;; Drawers
20252 ((and (looking-at "[ \t]*:END:")
20253 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20254 (save-excursion
20255 (goto-char (1- (match-beginning 1)))
20256 (setq column (current-column))))
20257 ;; Special blocks
20258 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20259 (save-excursion
20260 (re-search-backward
20261 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20262 (setq column (org-get-indentation (match-string 0))))
20263 ((and (not (looking-at "[ \t]*#\\+begin_"))
20264 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20265 (save-excursion
20266 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20267 (setq column
20268 (cond ((equal (downcase (match-string 1)) "src")
20269 ;; src blocks: let `org-edit-src-exit' handle them
20270 (org-get-indentation))
20271 ((equal (downcase (match-string 1)) "example")
20272 (max (org-get-indentation)
20273 (org-get-indentation (match-string 0))))
20275 (org-get-indentation (match-string 0))))))
20276 ;; This line has nothing special, look at the previous relevant
20277 ;; line to compute indentation
20279 (beginning-of-line 0)
20280 (while (and (not (bobp))
20281 (not (looking-at org-drawer-regexp))
20282 ;; When point started in an inline task, do not move
20283 ;; above task starting line.
20284 (not (and inline-task-p (looking-at inline-re)))
20285 ;; Skip drawers, blocks, empty lines, verbatim,
20286 ;; comments, tables, footnotes definitions, lists,
20287 ;; inline tasks.
20288 (or (and (looking-at "[ \t]*:END:")
20289 (re-search-backward org-drawer-regexp nil t))
20290 (and (looking-at "[ \t]*#\\+end_")
20291 (re-search-backward "[ \t]*#\\+begin_"nil t))
20292 (looking-at "[ \t]*[\n:#|]")
20293 (looking-at org-footnote-definition-re)
20294 (and (ignore-errors (goto-char (org-in-item-p)))
20295 (goto-char
20296 (org-list-get-top-point (org-list-struct))))
20297 (and (not inline-task-p)
20298 (featurep 'org-inlinetask)
20299 (org-inlinetask-in-task-p)
20300 (or (org-inlinetask-goto-beginning) t))))
20301 (beginning-of-line 0))
20302 (cond
20303 ;; There was an heading above.
20304 ((looking-at "\\*+[ \t]+")
20305 (if (not org-adapt-indentation)
20306 (setq column 0)
20307 (goto-char (match-end 0))
20308 (setq column (current-column))))
20309 ;; A drawer had started and is unfinished
20310 ((looking-at org-drawer-regexp)
20311 (goto-char (1- (match-beginning 1)))
20312 (setq column (current-column)))
20313 ;; Else, nothing noticeable found: get indentation and go on.
20314 (t (setq column (org-get-indentation))))))
20315 ;; Now apply indentation and move cursor accordingly
20316 (goto-char pos)
20317 (if (<= (current-column) (current-indentation))
20318 (org-indent-line-to column)
20319 (save-excursion (org-indent-line-to column)))
20320 ;; Special polishing for properties, see `org-property-format'
20321 (setq column (current-column))
20322 (beginning-of-line 1)
20323 (if (looking-at
20324 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20325 (replace-match (concat (match-string 1)
20326 (format org-property-format
20327 (match-string 2) (match-string 3)))
20328 t t))
20329 (org-move-to-column column)))
20331 (defun org-indent-drawer ()
20332 "Indent the drawer at point."
20333 (interactive)
20334 (let ((p (point))
20335 (e (and (save-excursion (re-search-forward ":END:" nil t))
20336 (match-end 0)))
20337 (folded
20338 (save-excursion
20339 (end-of-line)
20340 (when (overlays-at (point))
20341 (member 'invisible (overlay-properties
20342 (car (overlays-at (point)))))))))
20343 (when folded (org-cycle))
20344 (indent-for-tab-command)
20345 (while (and (move-beginning-of-line 2) (< (point) e))
20346 (indent-for-tab-command))
20347 (goto-char p)
20348 (when folded (org-cycle)))
20349 (message "Drawer at point indented"))
20351 (defun org-indent-block ()
20352 "Indent the block at point."
20353 (interactive)
20354 (let ((p (point))
20355 (case-fold-search t)
20356 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20357 (match-end 0)))
20358 (folded
20359 (save-excursion
20360 (end-of-line)
20361 (when (overlays-at (point))
20362 (member 'invisible (overlay-properties
20363 (car (overlays-at (point)))))))))
20364 (when folded (org-cycle))
20365 (indent-for-tab-command)
20366 (while (and (move-beginning-of-line 2) (< (point) e))
20367 (indent-for-tab-command))
20368 (goto-char p)
20369 (when folded (org-cycle)))
20370 (message "Block at point indented"))
20372 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20373 "Variable to store copy of `adaptive-fill-regexp'.
20374 Since `adaptive-fill-regexp' is set to never match, we need to
20375 store a backup of its value before entering `org-mode' so that
20376 the functionality can be provided as a fall-back.")
20378 (defun org-set-autofill-regexps ()
20379 (interactive)
20380 ;; In the paragraph separator we include headlines, because filling
20381 ;; text in a line directly attached to a headline would otherwise
20382 ;; fill the headline as well.
20383 (org-set-local 'comment-start-skip "^#+[ \t]*")
20384 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20385 ;; The paragraph starter includes hand-formatted lists.
20386 (org-set-local
20387 'paragraph-start
20388 (concat
20389 "\f" "\\|"
20390 "[ ]*$" "\\|"
20391 org-outline-regexp "\\|"
20392 "[ \t]*#" "\\|"
20393 (org-item-re) "\\|"
20394 "[ \t]*[:|]" "\\|"
20395 "\\$\\$" "\\|"
20396 "\\\\\\(begin\\|end\\|[][]\\)"))
20397 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20398 ;; But only if the user has not turned off tables or fixed-width regions
20399 (org-set-local
20400 'auto-fill-inhibit-regexp
20401 (concat org-outline-regexp
20402 "\\|#\\+"
20403 "\\|[ \t]*" org-keyword-time-regexp
20404 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20405 (concat
20406 "\\|[ \t]*["
20407 (if org-enable-table-editor "|" "")
20408 (if org-enable-fixed-width-editor ":" "")
20409 "]"))))
20410 ;; We use our own fill-paragraph function, to make sure that tables
20411 ;; and fixed-width regions are not wrapped. That function will pass
20412 ;; through to `fill-paragraph' when appropriate.
20413 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20414 ;; Prevent auto-fill from inserting unwanted new items.
20415 (if (boundp 'fill-nobreak-predicate)
20416 (org-set-local
20417 'fill-nobreak-predicate
20418 (org-uniquify
20419 (append fill-nobreak-predicate
20420 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20421 ;; Adaptive filling: To get full control, first make sure that
20422 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20423 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20424 (org-set-local 'org-adaptive-fill-regexp-backup
20425 adaptive-fill-regexp))
20426 (org-set-local 'adaptive-fill-regexp "\000")
20427 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20428 (org-set-local 'adaptive-fill-function
20429 'org-adaptive-fill-function)
20430 (org-set-local
20431 'align-mode-rules-list
20432 '((org-in-buffer-settings
20433 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20434 (modes . '(org-mode))))))
20436 (defun org-fill-item-nobreak-p ()
20437 "Non-nil when a line break at point would insert a new item."
20438 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20440 (defun org-fill-line-break-nobreak-p ()
20441 "Non-nil when a line break at point would create an Org line break."
20442 (save-excursion
20443 (skip-chars-backward "[ \t]")
20444 (skip-chars-backward "\\\\")
20445 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20447 (defun org-fill-paragraph (&optional justify)
20448 "Re-align a table, pass through to fill-paragraph if no table."
20449 (let ((table-p (org-at-table-p))
20450 (table.el-p (org-at-table.el-p))
20451 (itemp (org-in-item-p)))
20452 (cond ((and (equal (char-after (point-at-bol)) ?*)
20453 (save-excursion (goto-char (point-at-bol))
20454 (looking-at org-outline-regexp)))
20455 t) ; skip headlines
20456 (table.el-p t) ; skip table.el tables
20457 (table-p (org-table-align) t) ; align Org tables
20458 (itemp ; align text in items
20459 (let* ((struct (save-excursion (goto-char itemp)
20460 (org-list-struct)))
20461 (parents (org-list-parents-alist struct))
20462 (children (org-list-get-children itemp struct parents))
20463 beg end prev next prefix)
20464 ;; Determine in which part of item point is: before
20465 ;; first child, after last child, between two
20466 ;; sub-lists, or simply in item if there's no child.
20467 (cond
20468 ((not children)
20469 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20470 beg itemp
20471 end (org-list-get-item-end itemp struct)))
20472 ((< (point) (setq next (car children)))
20473 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20474 beg itemp
20475 end next))
20476 ((> (point) (setq prev (car (last children))))
20477 (setq beg (org-list-get-item-end prev struct)
20478 end (org-list-get-item-end itemp struct)
20479 prefix (save-excursion
20480 (goto-char beg)
20481 (skip-chars-forward " \t")
20482 (make-string (current-column) ?\ ))))
20483 (t (catch 'exit
20484 (while (setq next (pop children))
20485 (if (> (point) next)
20486 (setq prev next)
20487 (setq beg (org-list-get-item-end prev struct)
20488 end next
20489 prefix (save-excursion
20490 (goto-char beg)
20491 (skip-chars-forward " \t")
20492 (make-string (current-column) ?\ )))
20493 (throw 'exit nil))))))
20494 ;; Use `fill-paragraph' with buffer narrowed to item
20495 ;; without any child, and with our computed PREFIX.
20496 (flet ((fill-context-prefix (from to &optional flr) prefix))
20497 (save-restriction
20498 (narrow-to-region beg end)
20499 (save-excursion (fill-paragraph justify)))) t))
20500 ;; Special case where point is not in a list but is on
20501 ;; a paragraph adjacent to a list: make sure this paragraph
20502 ;; doesn't get merged with the end of the list by narrowing
20503 ;; buffer first.
20504 ((save-excursion (forward-paragraph -1)
20505 (setq itemp (org-in-item-p)))
20506 (let ((struct (save-excursion (goto-char itemp)
20507 (org-list-struct))))
20508 (save-restriction
20509 (narrow-to-region (org-list-get-bottom-point struct)
20510 (save-excursion (forward-paragraph 1)
20511 (point)))
20512 (fill-paragraph justify) t)))
20513 ;; Don't fill schedule/deadline line before a paragraph
20514 ((save-excursion (forward-paragraph -1)
20515 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20516 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$"))))
20517 (save-restriction
20518 (narrow-to-region (1+ (match-end 0))
20519 (save-excursion (forward-paragraph 1) (point)))
20520 (fill-paragraph justify) t))
20521 ;; Else simply call `fill-paragraph'.
20522 (t nil))))
20524 ;; For reference, this is the default value of adaptive-fill-regexp
20525 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20527 (defun org-adaptive-fill-function ()
20528 "Return a fill prefix for org-mode files."
20529 (let (itemp)
20530 (save-excursion
20531 (cond
20532 ;; Comment line
20533 ((looking-at "#[ \t]+")
20534 (match-string-no-properties 0))
20535 ;; Plain list item
20536 ((org-at-item-p)
20537 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20538 ;; Point is in a list after `backward-paragraph': original
20539 ;; point wasn't in the list, or filling would have been taken
20540 ;; care of by `org-auto-fill-function', but the list and the
20541 ;; real paragraph are not separated by a blank line. Thus, move
20542 ;; point after the list to go back to real paragraph and
20543 ;; determine fill-prefix.
20544 ((setq itemp (org-in-item-p))
20545 (goto-char itemp)
20546 (let* ((struct (org-list-struct))
20547 (bottom (org-list-get-bottom-point struct)))
20548 (goto-char bottom)
20549 (make-string (org-get-indentation) ?\ )))
20550 ;; Other text
20551 ((looking-at org-adaptive-fill-regexp-backup)
20552 (match-string-no-properties 0))))))
20554 (defun org-auto-fill-function ()
20555 "Auto-fill function."
20556 (let (itemp prefix)
20557 ;; When in a list, compute an appropriate fill-prefix and make
20558 ;; sure it will be used by `do-auto-fill'.
20559 (if (setq itemp (org-in-item-p))
20560 (progn
20561 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20562 (flet ((fill-context-prefix (from to &optional flr) prefix))
20563 (do-auto-fill)))
20564 ;; Else just use `do-auto-fill'.
20565 (do-auto-fill))))
20567 ;;; Other stuff.
20569 (defun org-toggle-fixed-width-section (arg)
20570 "Toggle the fixed-width export.
20571 If there is no active region, the QUOTE keyword at the current headline is
20572 inserted or removed. When present, it causes the text between this headline
20573 and the next to be exported as fixed-width text, and unmodified.
20574 If there is an active region, this command adds or removes a colon as the
20575 first character of this line. If the first character of a line is a colon,
20576 this line is also exported in fixed-width font."
20577 (interactive "P")
20578 (let* ((cc 0)
20579 (regionp (org-region-active-p))
20580 (beg (if regionp (region-beginning) (point)))
20581 (end (if regionp (region-end)))
20582 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20583 (case-fold-search nil)
20584 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20585 off)
20586 (if regionp
20587 (save-excursion
20588 (goto-char beg)
20589 (setq cc (current-column))
20590 (beginning-of-line 1)
20591 (setq off (looking-at re))
20592 (while (> nlines 0)
20593 (setq nlines (1- nlines))
20594 (beginning-of-line 1)
20595 (cond
20596 (arg
20597 (org-move-to-column cc t)
20598 (insert ": \n")
20599 (forward-line -1))
20600 ((and off (looking-at re))
20601 (replace-match "" t t nil 1))
20602 ((not off) (org-move-to-column cc t) (insert ": ")))
20603 (forward-line 1)))
20604 (save-excursion
20605 (org-back-to-heading)
20606 (cond
20607 ((looking-at (format org-heading-keyword-regexp-format
20608 org-quote-string))
20609 (goto-char (match-end 1))
20610 (looking-at (concat " +" org-quote-string))
20611 (replace-match "" t t)
20612 (when (eolp) (insert " ")))
20613 ((looking-at org-outline-regexp)
20614 (goto-char (match-end 0))
20615 (insert org-quote-string " ")))))))
20617 (defun org-reftex-citation ()
20618 "Use reftex-citation to insert a citation into the buffer.
20619 This looks for a line like
20621 #+BIBLIOGRAPHY: foo plain option:-d
20623 and derives from it that foo.bib is the bibliography file relevant
20624 for this document. It then installs the necessary environment for RefTeX
20625 to work in this buffer and calls `reftex-citation' to insert a citation
20626 into the buffer.
20628 Export of such citations to both LaTeX and HTML is handled by the contributed
20629 package org-exp-bibtex by Taru Karttunen."
20630 (interactive)
20631 (let ((reftex-docstruct-symbol 'rds)
20632 (reftex-cite-format "\\cite{%l}")
20633 rds bib)
20634 (save-excursion
20635 (save-restriction
20636 (widen)
20637 (let ((case-fold-search t)
20638 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20639 (if (not (save-excursion
20640 (or (re-search-forward re nil t)
20641 (re-search-backward re nil t))))
20642 (error "No bibliography defined in file")
20643 (setq bib (concat (match-string 1) ".bib")
20644 rds (list (list 'bib bib)))))))
20645 (call-interactively 'reftex-citation)))
20647 ;;;; Functions extending outline functionality
20649 (defun org-beginning-of-line (&optional arg)
20650 "Go to the beginning of the current line. If that is invisible, continue
20651 to a visible line beginning. This makes the function of C-a more intuitive.
20652 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20653 first attempt, and only move to after the tags when the cursor is already
20654 beyond the end of the headline."
20655 (interactive "P")
20656 (let ((pos (point))
20657 (special (if (consp org-special-ctrl-a/e)
20658 (car org-special-ctrl-a/e)
20659 org-special-ctrl-a/e))
20660 refpos)
20661 (if (org-bound-and-true-p line-move-visual)
20662 (beginning-of-visual-line 1)
20663 (beginning-of-line 1))
20664 (if (and arg (fboundp 'move-beginning-of-line))
20665 (call-interactively 'move-beginning-of-line)
20666 (if (bobp)
20668 (backward-char 1)
20669 (if (org-truely-invisible-p)
20670 (while (and (not (bobp)) (org-truely-invisible-p))
20671 (backward-char 1)
20672 (beginning-of-line 1))
20673 (forward-char 1))))
20674 (when special
20675 (cond
20676 ((and (looking-at org-complex-heading-regexp)
20677 (= (char-after (match-end 1)) ?\ ))
20678 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20679 (point-at-eol)))
20680 (goto-char
20681 (if (eq special t)
20682 (cond ((> pos refpos) refpos)
20683 ((= pos (point)) refpos)
20684 (t (point)))
20685 (cond ((> pos (point)) (point))
20686 ((not (eq last-command this-command)) (point))
20687 (t refpos)))))
20688 ((org-at-item-p)
20689 ;; Being at an item and not looking at an the item means point
20690 ;; was previously moved to beginning of a visual line, which
20691 ;; doesn't contain the item. Therefore, do nothing special,
20692 ;; just stay here.
20693 (when (looking-at org-list-full-item-re)
20694 ;; Set special position at first white space character after
20695 ;; bullet, and check-box, if any.
20696 (let ((after-bullet
20697 (let ((box (match-end 3)))
20698 (if (not box) (match-end 1)
20699 (let ((after (char-after box)))
20700 (if (and after (= after ? )) (1+ box) box))))))
20701 ;; Special case: Move point to special position when
20702 ;; currently after it or at beginning of line.
20703 (if (eq special t)
20704 (when (or (> pos after-bullet) (= (point) pos))
20705 (goto-char after-bullet))
20706 ;; Reversed case: Move point to special position when
20707 ;; point was already at beginning of line and command is
20708 ;; repeated.
20709 (when (and (= (point) pos) (eq last-command this-command))
20710 (goto-char after-bullet))))))))
20711 (org-no-warnings
20712 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20714 (defun org-end-of-line (&optional arg)
20715 "Go to the end of the line.
20716 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20717 first attempt, and only move to after the tags when the cursor is already
20718 beyond the end of the headline."
20719 (interactive "P")
20720 (let ((special (if (consp org-special-ctrl-a/e)
20721 (cdr org-special-ctrl-a/e)
20722 org-special-ctrl-a/e)))
20723 (cond
20724 ((or (not special) arg
20725 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20726 (call-interactively
20727 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20728 ((fboundp 'move-end-of-line) 'move-end-of-line)
20729 (t 'end-of-line))))
20730 ((org-at-heading-p)
20731 (let ((pos (point)))
20732 (beginning-of-line 1)
20733 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20734 (if (eq special t)
20735 (if (or (< pos (match-beginning 1))
20736 (= pos (match-end 0)))
20737 (goto-char (match-beginning 1))
20738 (goto-char (match-end 0)))
20739 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20740 (goto-char (match-end 0))
20741 (goto-char (match-beginning 1))))
20742 (call-interactively (if (fboundp 'move-end-of-line)
20743 'move-end-of-line
20744 'end-of-line)))))
20745 ((org-at-drawer-p)
20746 (move-end-of-line 1)
20747 (when (overlays-at (1- (point))) (backward-char 1)))
20748 ;; At an item: Move before any hidden text.
20749 (t (call-interactively
20750 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20751 ((fboundp 'move-end-of-line) 'move-end-of-line)
20752 (t 'end-of-line)))))
20753 (org-no-warnings
20754 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20756 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20757 (define-key org-mode-map "\C-e" 'org-end-of-line)
20759 (defun org-backward-sentence (&optional arg)
20760 "Go to beginning of sentence, or beginning of table field.
20761 This will call `backward-sentence' or `org-table-beginning-of-field',
20762 depending on context."
20763 (interactive "P")
20764 (cond
20765 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20766 (t (call-interactively 'backward-sentence))))
20768 (defun org-forward-sentence (&optional arg)
20769 "Go to end of sentence, or end of table field.
20770 This will call `forward-sentence' or `org-table-end-of-field',
20771 depending on context."
20772 (interactive "P")
20773 (cond
20774 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20775 (t (call-interactively 'forward-sentence))))
20777 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20778 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20780 (defun org-kill-line (&optional arg)
20781 "Kill line, to tags or end of line."
20782 (interactive "P")
20783 (cond
20784 ((or (not org-special-ctrl-k)
20785 (bolp)
20786 (not (org-at-heading-p)))
20787 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20788 org-ctrl-k-protect-subtree)
20789 (if (or (eq org-ctrl-k-protect-subtree 'error)
20790 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20791 (error "C-k aborted - would kill hidden subtree")))
20792 (call-interactively
20793 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
20794 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20795 (kill-region (point) (match-beginning 1))
20796 (org-set-tags nil t))
20797 (t (kill-region (point) (point-at-eol)))))
20799 (define-key org-mode-map "\C-k" 'org-kill-line)
20801 (defun org-yank (&optional arg)
20802 "Yank. If the kill is a subtree, treat it specially.
20803 This command will look at the current kill and check if is a single
20804 subtree, or a series of subtrees[1]. If it passes the test, and if the
20805 cursor is at the beginning of a line or after the stars of a currently
20806 empty headline, then the yank is handled specially. How exactly depends
20807 on the value of the following variables, both set by default.
20809 org-yank-folded-subtrees
20810 When set, the subtree(s) will be folded after insertion, but only
20811 if doing so would now swallow text after the yanked text.
20813 org-yank-adjusted-subtrees
20814 When set, the subtree will be promoted or demoted in order to
20815 fit into the local outline tree structure, which means that the level
20816 will be adjusted so that it becomes the smaller one of the two
20817 *visible* surrounding headings.
20819 Any prefix to this command will cause `yank' to be called directly with
20820 no special treatment. In particular, a simple \\[universal-argument] prefix \
20821 will just
20822 plainly yank the text as it is.
20824 \[1] The test checks if the first non-white line is a heading
20825 and if there are no other headings with fewer stars."
20826 (interactive "P")
20827 (org-yank-generic 'yank arg))
20829 (defun org-yank-generic (command arg)
20830 "Perform some yank-like command.
20832 This function implements the behavior described in the `org-yank'
20833 documentation. However, it has been generalized to work for any
20834 interactive command with similar behavior."
20836 ;; pretend to be command COMMAND
20837 (setq this-command command)
20839 (if arg
20840 (call-interactively command)
20842 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20843 (and (org-kill-is-subtree-p)
20844 (or (bolp)
20845 (and (looking-at "[ \t]*$")
20846 (string-match
20847 "\\`\\*+\\'"
20848 (buffer-substring (point-at-bol) (point)))))))
20849 swallowp)
20850 (cond
20851 ((and subtreep org-yank-folded-subtrees)
20852 (let ((beg (point))
20853 end)
20854 (if (and subtreep org-yank-adjusted-subtrees)
20855 (org-paste-subtree nil nil 'for-yank)
20856 (call-interactively command))
20858 (setq end (point))
20859 (goto-char beg)
20860 (when (and (bolp) subtreep
20861 (not (setq swallowp
20862 (org-yank-folding-would-swallow-text beg end))))
20863 (org-with-limited-levels
20864 (or (looking-at org-outline-regexp)
20865 (re-search-forward org-outline-regexp-bol end t))
20866 (while (and (< (point) end) (looking-at org-outline-regexp))
20867 (hide-subtree)
20868 (org-cycle-show-empty-lines 'folded)
20869 (condition-case nil
20870 (outline-forward-same-level 1)
20871 (error (goto-char end))))))
20872 (when swallowp
20873 (message
20874 "Inserted text not folded because that would swallow text"))
20876 (goto-char end)
20877 (skip-chars-forward " \t\n\r")
20878 (beginning-of-line 1)
20879 (push-mark beg 'nomsg)))
20880 ((and subtreep org-yank-adjusted-subtrees)
20881 (let ((beg (point-at-bol)))
20882 (org-paste-subtree nil nil 'for-yank)
20883 (push-mark beg 'nomsg)))
20885 (call-interactively command))))))
20887 (defun org-yank-folding-would-swallow-text (beg end)
20888 "Would hide-subtree at BEG swallow any text after END?"
20889 (let (level)
20890 (org-with-limited-levels
20891 (save-excursion
20892 (goto-char beg)
20893 (when (or (looking-at org-outline-regexp)
20894 (re-search-forward org-outline-regexp-bol end t))
20895 (setq level (org-outline-level)))
20896 (goto-char end)
20897 (skip-chars-forward " \t\r\n\v\f")
20898 (if (or (eobp)
20899 (and (bolp) (looking-at org-outline-regexp)
20900 (<= (org-outline-level) level)))
20901 nil ; Nothing would be swallowed
20902 t))))) ; something would swallow
20904 (define-key org-mode-map "\C-y" 'org-yank)
20906 (defun org-truely-invisible-p ()
20907 "Check if point is at a character currently not visible.
20908 This version does not only check the character property, but also
20909 `visible-mode'."
20910 ;; Early versions of noutline don't have `outline-invisible-p'.
20911 (if (org-bound-and-true-p visible-mode)
20913 (outline-invisible-p)))
20915 (defun org-invisible-p2 ()
20916 "Check if point is at a character currently not visible."
20917 (save-excursion
20918 (if (and (eolp) (not (bobp))) (backward-char 1))
20919 ;; Early versions of noutline don't have `outline-invisible-p'.
20920 (outline-invisible-p)))
20922 (defun org-back-to-heading (&optional invisible-ok)
20923 "Call `outline-back-to-heading', but provide a better error message."
20924 (condition-case nil
20925 (outline-back-to-heading invisible-ok)
20926 (error (error "Before first headline at position %d in buffer %s"
20927 (point) (current-buffer)))))
20929 (defun org-beginning-of-defun ()
20930 "Go to the beginning of the subtree, i.e. back to the heading."
20931 (org-back-to-heading))
20932 (defun org-end-of-defun ()
20933 "Go to the end of the subtree."
20934 (org-end-of-subtree nil t))
20936 (defun org-before-first-heading-p ()
20937 "Before first heading?"
20938 (save-excursion
20939 (end-of-line)
20940 (null (re-search-backward org-outline-regexp-bol nil t))))
20942 (defun org-at-heading-p (&optional ignored)
20943 (outline-on-heading-p t))
20944 ;; Compatibility alias with Org versions < 7.8.03
20945 (defalias 'org-on-heading-p 'org-at-heading-p)
20947 (defun org-at-drawer-p nil
20948 "Is cursor at a drawer keyword?"
20949 (save-excursion
20950 (move-beginning-of-line 1)
20951 (looking-at org-drawer-regexp)))
20953 (defun org-at-block-p nil
20954 "Is cursor at a block keyword?"
20955 (save-excursion
20956 (move-beginning-of-line 1)
20957 (looking-at org-block-regexp)))
20959 (defun org-point-at-end-of-empty-headline ()
20960 "If point is at the end of an empty headline, return t, else nil.
20961 If the heading only contains a TODO keyword, it is still still considered
20962 empty."
20963 (and (looking-at "[ \t]*$")
20964 (when org-todo-line-regexp
20965 (save-excursion
20966 (beginning-of-line 1)
20967 (let ((case-fold-search nil))
20968 (looking-at org-todo-line-regexp)
20969 (string= (match-string 3) ""))))))
20971 (defun org-at-heading-or-item-p ()
20972 (or (org-at-heading-p) (org-at-item-p)))
20974 (defun org-at-target-p ()
20975 (or (org-in-regexp org-radio-target-regexp)
20976 (org-in-regexp org-target-regexp)))
20977 ;; Compatibility alias with Org versions < 7.8.03
20978 (defalias 'org-on-target-p 'org-at-target-p)
20980 (defun org-up-heading-all (arg)
20981 "Move to the heading line of which the present line is a subheading.
20982 This function considers both visible and invisible heading lines.
20983 With argument, move up ARG levels."
20984 (if (fboundp 'outline-up-heading-all)
20985 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20986 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20988 (defun org-up-heading-safe ()
20989 "Move to the heading line of which the present line is a subheading.
20990 This version will not throw an error. It will return the level of the
20991 headline found, or nil if no higher level is found.
20993 Also, this function will be a lot faster than `outline-up-heading',
20994 because it relies on stars being the outline starters. This can really
20995 make a significant difference in outlines with very many siblings."
20996 (let (start-level re)
20997 (org-back-to-heading t)
20998 (setq start-level (funcall outline-level))
20999 (if (equal start-level 1)
21001 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21002 (if (re-search-backward re nil t)
21003 (funcall outline-level)))))
21005 (defun org-first-sibling-p ()
21006 "Is this heading the first child of its parents?"
21007 (interactive)
21008 (let ((re org-outline-regexp-bol)
21009 level l)
21010 (unless (org-at-heading-p t)
21011 (error "Not at a heading"))
21012 (setq level (funcall outline-level))
21013 (save-excursion
21014 (if (not (re-search-backward re nil t))
21016 (setq l (funcall outline-level))
21017 (< l level)))))
21019 (defun org-goto-sibling (&optional previous)
21020 "Goto the next sibling, even if it is invisible.
21021 When PREVIOUS is set, go to the previous sibling instead. Returns t
21022 when a sibling was found. When none is found, return nil and don't
21023 move point."
21024 (let ((fun (if previous 're-search-backward 're-search-forward))
21025 (pos (point))
21026 (re org-outline-regexp-bol)
21027 level l)
21028 (when (condition-case nil (org-back-to-heading t) (error nil))
21029 (setq level (funcall outline-level))
21030 (catch 'exit
21031 (or previous (forward-char 1))
21032 (while (funcall fun re nil t)
21033 (setq l (funcall outline-level))
21034 (when (< l level) (goto-char pos) (throw 'exit nil))
21035 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21036 (goto-char pos)
21037 nil))))
21039 (defun org-show-siblings ()
21040 "Show all siblings of the current headline."
21041 (save-excursion
21042 (while (org-goto-sibling) (org-flag-heading nil)))
21043 (save-excursion
21044 (while (org-goto-sibling 'previous)
21045 (org-flag-heading nil))))
21047 (defun org-goto-first-child ()
21048 "Goto the first child, even if it is invisible.
21049 Return t when a child was found. Otherwise don't move point and
21050 return nil."
21051 (let (level (pos (point)) (re org-outline-regexp-bol))
21052 (when (condition-case nil (org-back-to-heading t) (error nil))
21053 (setq level (outline-level))
21054 (forward-char 1)
21055 (if (and (re-search-forward re nil t) (> (outline-level) level))
21056 (progn (goto-char (match-beginning 0)) t)
21057 (goto-char pos) nil))))
21059 (defun org-show-hidden-entry ()
21060 "Show an entry where even the heading is hidden."
21061 (save-excursion
21062 (org-show-entry)))
21064 (defun org-flag-heading (flag &optional entry)
21065 "Flag the current heading. FLAG non-nil means make invisible.
21066 When ENTRY is non-nil, show the entire entry."
21067 (save-excursion
21068 (org-back-to-heading t)
21069 ;; Check if we should show the entire entry
21070 (if entry
21071 (progn
21072 (org-show-entry)
21073 (save-excursion
21074 (and (outline-next-heading)
21075 (org-flag-heading nil))))
21076 (outline-flag-region (max (point-min) (1- (point)))
21077 (save-excursion (outline-end-of-heading) (point))
21078 flag))))
21080 (defun org-get-next-sibling ()
21081 "Move to next heading of the same level, and return point.
21082 If there is no such heading, return nil.
21083 This is like outline-next-sibling, but invisible headings are ok."
21084 (let ((level (funcall outline-level)))
21085 (outline-next-heading)
21086 (while (and (not (eobp)) (> (funcall outline-level) level))
21087 (outline-next-heading))
21088 (if (or (eobp) (< (funcall outline-level) level))
21090 (point))))
21092 (defun org-get-last-sibling ()
21093 "Move to previous heading of the same level, and return point.
21094 If there is no such heading, return nil."
21095 (let ((opoint (point))
21096 (level (funcall outline-level)))
21097 (outline-previous-heading)
21098 (when (and (/= (point) opoint) (outline-on-heading-p t))
21099 (while (and (> (funcall outline-level) level)
21100 (not (bobp)))
21101 (outline-previous-heading))
21102 (if (< (funcall outline-level) level)
21104 (point)))))
21106 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21107 ;; This contains an exact copy of the original function, but it uses
21108 ;; `org-back-to-heading', to make it work also in invisible
21109 ;; trees. And is uses an invisible-OK argument.
21110 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21111 ;; Furthermore, when used inside Org, finding the end of a large subtree
21112 ;; with many children and grandchildren etc, this can be much faster
21113 ;; than the outline version.
21114 (org-back-to-heading invisible-OK)
21115 (let ((first t)
21116 (level (funcall outline-level)))
21117 (if (and (eq major-mode 'org-mode) (< level 1000))
21118 ;; A true heading (not a plain list item), in Org-mode
21119 ;; This means we can easily find the end by looking
21120 ;; only for the right number of stars. Using a regexp to do
21121 ;; this is so much faster than using a Lisp loop.
21122 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21123 (forward-char 1)
21124 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21125 ;; something else, do it the slow way
21126 (while (and (not (eobp))
21127 (or first (> (funcall outline-level) level)))
21128 (setq first nil)
21129 (outline-next-heading)))
21130 (unless to-heading
21131 (if (memq (preceding-char) '(?\n ?\^M))
21132 (progn
21133 ;; Go to end of line before heading
21134 (forward-char -1)
21135 (if (memq (preceding-char) '(?\n ?\^M))
21136 ;; leave blank line before heading
21137 (forward-char -1))))))
21138 (point))
21140 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21141 "Use Org version in org-mode, for dramatic speed-up."
21142 (if (eq major-mode 'org-mode)
21143 (progn
21144 (org-end-of-subtree nil t)
21145 (unless (eobp) (backward-char 1)))
21146 ad-do-it))
21148 (defun org-end-of-meta-data-and-drawers ()
21149 "Jump to the first text after meta data and drawers in the current entry.
21150 This will move over empty lines, lines with planning time stamps,
21151 clocking lines, and drawers."
21152 (org-back-to-heading t)
21153 (let ((end (save-excursion (outline-next-heading) (point)))
21154 (re (concat "\\(" org-drawer-regexp "\\)"
21155 "\\|" "[ \t]*" org-keyword-time-regexp)))
21156 (forward-line 1)
21157 (while (re-search-forward re end t)
21158 (if (not (match-end 1))
21159 ;; empty or planning line
21160 (forward-line 1)
21161 ;; a drawer, find the end
21162 (re-search-forward "^[ \t]*:END:" end 'move)
21163 (forward-line 1)))
21164 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21165 (point)))
21167 (defun org-forward-same-level (arg &optional invisible-ok)
21168 "Move forward to the arg'th subheading at same level as this one.
21169 Stop at the first and last subheadings of a superior heading.
21170 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21171 it wil also look at invisible ones."
21172 (interactive "p")
21173 (org-back-to-heading invisible-ok)
21174 (org-at-heading-p)
21175 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21176 (re (format "^\\*\\{1,%d\\} " level))
21178 (forward-char 1)
21179 (while (> arg 0)
21180 (while (and (re-search-forward re nil 'move)
21181 (setq l (- (match-end 0) (match-beginning 0) 1))
21182 (= l level)
21183 (not invisible-ok)
21184 (progn (backward-char 1) (outline-invisible-p)))
21185 (if (< l level) (setq arg 1)))
21186 (setq arg (1- arg)))
21187 (beginning-of-line 1)))
21189 (defun org-backward-same-level (arg &optional invisible-ok)
21190 "Move backward to the arg'th subheading at same level as this one.
21191 Stop at the first and last subheadings of a superior heading."
21192 (interactive "p")
21193 (org-back-to-heading)
21194 (org-at-heading-p)
21195 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21196 (re (format "^\\*\\{1,%d\\} " level))
21198 (while (> arg 0)
21199 (while (and (re-search-backward re nil 'move)
21200 (setq l (- (match-end 0) (match-beginning 0) 1))
21201 (= l level)
21202 (not invisible-ok)
21203 (outline-invisible-p))
21204 (if (< l level) (setq arg 1)))
21205 (setq arg (1- arg)))))
21207 (defun org-show-subtree ()
21208 "Show everything after this heading at deeper levels."
21209 (interactive)
21210 (outline-flag-region
21211 (point)
21212 (save-excursion
21213 (org-end-of-subtree t t))
21214 nil))
21216 (defun org-show-entry ()
21217 "Show the body directly following this heading.
21218 Show the heading too, if it is currently invisible."
21219 (interactive)
21220 (save-excursion
21221 (condition-case nil
21222 (progn
21223 (org-back-to-heading t)
21224 (outline-flag-region
21225 (max (point-min) (1- (point)))
21226 (save-excursion
21227 (if (re-search-forward
21228 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21229 (match-beginning 1)
21230 (point-max)))
21231 nil)
21232 (org-cycle-hide-drawers 'children))
21233 (error nil))))
21235 (defun org-make-options-regexp (kwds &optional extra)
21236 "Make a regular expression for keyword lines."
21237 (concat
21239 "#?[ \t]*\\+\\("
21240 (mapconcat 'regexp-quote kwds "\\|")
21241 (if extra (concat "\\|" extra))
21242 "\\):[ \t]*"
21243 "\\(.*\\)"))
21245 ;; Make isearch reveal the necessary context
21246 (defun org-isearch-end ()
21247 "Reveal context after isearch exits."
21248 (when isearch-success ; only if search was successful
21249 (if (featurep 'xemacs)
21250 ;; Under XEmacs, the hook is run in the correct place,
21251 ;; we directly show the context.
21252 (org-show-context 'isearch)
21253 ;; In Emacs the hook runs *before* restoring the overlays.
21254 ;; So we have to use a one-time post-command-hook to do this.
21255 ;; (Emacs 22 has a special variable, see function `org-mode')
21256 (unless (and (boundp 'isearch-mode-end-hook-quit)
21257 isearch-mode-end-hook-quit)
21258 ;; Only when the isearch was not quitted.
21259 (org-add-hook 'post-command-hook 'org-isearch-post-command
21260 'append 'local)))))
21262 (defun org-isearch-post-command ()
21263 "Remove self from hook, and show context."
21264 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21265 (org-show-context 'isearch))
21268 ;;;; Integration with and fixes for other packages
21270 ;;; Imenu support
21272 (defvar org-imenu-markers nil
21273 "All markers currently used by Imenu.")
21274 (make-variable-buffer-local 'org-imenu-markers)
21276 (defun org-imenu-new-marker (&optional pos)
21277 "Return a new marker for use by Imenu, and remember the marker."
21278 (let ((m (make-marker)))
21279 (move-marker m (or pos (point)))
21280 (push m org-imenu-markers)
21283 (defun org-imenu-get-tree ()
21284 "Produce the index for Imenu."
21285 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21286 (setq org-imenu-markers nil)
21287 (let* ((n org-imenu-depth)
21288 (re (concat "^" (org-get-limited-outline-regexp)))
21289 (subs (make-vector (1+ n) nil))
21290 (last-level 0)
21291 m level head)
21292 (save-excursion
21293 (save-restriction
21294 (widen)
21295 (goto-char (point-max))
21296 (while (re-search-backward re nil t)
21297 (setq level (org-reduced-level (funcall outline-level)))
21298 (when (and (<= level n)
21299 (looking-at org-complex-heading-regexp))
21300 (setq head (org-link-display-format
21301 (org-match-string-no-properties 4))
21302 m (org-imenu-new-marker))
21303 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21304 (if (>= level last-level)
21305 (push (cons head m) (aref subs level))
21306 (push (cons head (aref subs (1+ level))) (aref subs level))
21307 (loop for i from (1+ level) to n do (aset subs i nil)))
21308 (setq last-level level)))))
21309 (aref subs 1)))
21311 (eval-after-load "imenu"
21312 '(progn
21313 (add-hook 'imenu-after-jump-hook
21314 (lambda ()
21315 (if (eq major-mode 'org-mode)
21316 (org-show-context 'org-goto))))))
21318 (defun org-link-display-format (link)
21319 "Replace a link with either the description, or the link target
21320 if no description is present"
21321 (save-match-data
21322 (if (string-match org-bracket-link-analytic-regexp link)
21323 (replace-match (if (match-end 5)
21324 (match-string 5 link)
21325 (concat (match-string 1 link)
21326 (match-string 3 link)))
21327 nil t link)
21328 link)))
21330 (defun org-toggle-link-display ()
21331 "Toggle the literal or descriptive display of links."
21332 (interactive)
21333 (if org-descriptive-links
21334 (progn (org-remove-from-invisibility-spec '(org-link))
21335 (org-restart-font-lock)
21336 (setq org-descriptive-links nil))
21337 (progn (add-to-invisibility-spec '(org-link))
21338 (org-restart-font-lock)
21339 (setq org-descriptive-links t))))
21341 ;; Speedbar support
21343 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21344 "Overlay marking the agenda restriction line in speedbar.")
21345 (overlay-put org-speedbar-restriction-lock-overlay
21346 'face 'org-agenda-restriction-lock)
21347 (overlay-put org-speedbar-restriction-lock-overlay
21348 'help-echo "Agendas are currently limited to this item.")
21349 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21351 (defun org-speedbar-set-agenda-restriction ()
21352 "Restrict future agenda commands to the location at point in speedbar.
21353 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21354 (interactive)
21355 (require 'org-agenda)
21356 (let (p m tp np dir txt)
21357 (cond
21358 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21359 'org-imenu t))
21360 (setq m (get-text-property p 'org-imenu-marker))
21361 (with-current-buffer (marker-buffer m)
21362 (goto-char m)
21363 (org-agenda-set-restriction-lock 'subtree)))
21364 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21365 'speedbar-function 'speedbar-find-file))
21366 (setq tp (previous-single-property-change
21367 (1+ p) 'speedbar-function)
21368 np (next-single-property-change
21369 tp 'speedbar-function)
21370 dir (speedbar-line-directory)
21371 txt (buffer-substring-no-properties (or tp (point-min))
21372 (or np (point-max))))
21373 (with-current-buffer (find-file-noselect
21374 (let ((default-directory dir))
21375 (expand-file-name txt)))
21376 (unless (eq major-mode 'org-mode)
21377 (error "Cannot restrict to non-Org-mode file"))
21378 (org-agenda-set-restriction-lock 'file)))
21379 (t (error "Don't know how to restrict Org-mode's agenda")))
21380 (move-overlay org-speedbar-restriction-lock-overlay
21381 (point-at-bol) (point-at-eol))
21382 (setq current-prefix-arg nil)
21383 (org-agenda-maybe-redo)))
21385 (eval-after-load "speedbar"
21386 '(progn
21387 (speedbar-add-supported-extension ".org")
21388 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21389 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21390 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21391 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21392 (add-hook 'speedbar-visiting-tag-hook
21393 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21395 ;;; Fixes and Hacks for problems with other packages
21397 ;; Make flyspell not check words in links, to not mess up our keymap
21398 (defun org-mode-flyspell-verify ()
21399 "Don't let flyspell put overlays at active buttons, or on
21400 {todo,all-time,additional-option-like}-keywords."
21401 (let ((pos (max (1- (point)) (point-min)))
21402 (word (thing-at-point 'word)))
21403 (and (not (get-text-property pos 'keymap))
21404 (not (get-text-property pos 'org-no-flyspell))
21405 (not (member word org-todo-keywords-1))
21406 (not (member word org-all-time-keywords))
21407 (not (member word org-additional-option-like-keywords)))))
21409 (defun org-remove-flyspell-overlays-in (beg end)
21410 "Remove flyspell overlays in region."
21411 (and (org-bound-and-true-p flyspell-mode)
21412 (fboundp 'flyspell-delete-region-overlays)
21413 (flyspell-delete-region-overlays beg end))
21414 (add-text-properties beg end '(org-no-flyspell t)))
21416 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21417 (eval-after-load "bookmark"
21418 '(if (boundp 'bookmark-after-jump-hook)
21419 ;; We can use the hook
21420 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21421 ;; Hook not available, use advice
21422 (defadvice bookmark-jump (after org-make-visible activate)
21423 "Make the position visible."
21424 (org-bookmark-jump-unhide))))
21426 ;; Make sure saveplace shows the location if it was hidden
21427 (eval-after-load "saveplace"
21428 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21429 "Make the position visible."
21430 (org-bookmark-jump-unhide)))
21432 ;; Make sure ecb shows the location if it was hidden
21433 (eval-after-load "ecb"
21434 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21435 "Make hierarchy visible when jumping into location from ECB tree buffer."
21436 (if (eq major-mode 'org-mode)
21437 (org-show-context))))
21439 (defun org-bookmark-jump-unhide ()
21440 "Unhide the current position, to show the bookmark location."
21441 (and (eq major-mode 'org-mode)
21442 (or (outline-invisible-p)
21443 (save-excursion (goto-char (max (point-min) (1- (point))))
21444 (outline-invisible-p)))
21445 (org-show-context 'bookmark-jump)))
21447 ;; Make session.el ignore our circular variable
21448 (eval-after-load "session"
21449 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21451 ;;;; Experimental code
21453 (defun org-closed-in-range ()
21454 "Sparse tree of items closed in a certain time range.
21455 Still experimental, may disappear in the future."
21456 (interactive)
21457 ;; Get the time interval from the user.
21458 (let* ((time1 (org-float-time
21459 (org-read-date nil 'to-time nil "Starting date: ")))
21460 (time2 (org-float-time
21461 (org-read-date nil 'to-time nil "End date:")))
21462 ;; callback function
21463 (callback (lambda ()
21464 (let ((time
21465 (org-float-time
21466 (apply 'encode-time
21467 (org-parse-time-string
21468 (match-string 1))))))
21469 ;; check if time in interval
21470 (and (>= time time1) (<= time time2))))))
21471 ;; make tree, check each match with the callback
21472 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21474 ;;;; Finish up
21476 (provide 'org)
21478 (run-hooks 'org-load-hook)
21480 ;;; org.el ends here