]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
Merge from emacs-24; up to 2012-04-30T11:57:47Z!sdl.web@gmail.com
[gnu-emacs] / lisp / org / org.el
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.8.11
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
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.
17
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.
22
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28 ;;
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.
31 ;;
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.
46 ;;
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
50 ;;
51 ;; http://orgmode.org/org.html#Installation
52 ;;
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.
60 ;;
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
63 ;;
64 ;;; Code:
65
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)
70
71 ;;;; Require other packages
72
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
76
77 (require 'calendar)
78 (require 'format-spec)
79
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)))
90
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)
97
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)
106
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
115 ;; babel
116 (require 'ob)
117 (require 'ob-table)
118 (require 'ob-lob)
119 (require 'ob-ref)
120 (require 'ob-tangle)
121 (require 'ob-comint)
122 (require 'ob-keys)
123
124 ;; load languages based on value of `org-babel-load-languages'
125 (defvar org-babel-load-languages)
126 ;;;###autoload
127 (defun org-babel-do-load-languages (sym value)
128 "Load the languages defined in `org-babel-load-languages'."
129 (set-default sym value)
130 (mapc (lambda (pair)
131 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
132 (if active
133 (progn
134 (require (intern (concat "ob-" lang))))
135 (progn
136 (funcall 'fmakunbound
137 (intern (concat "org-babel-execute:" lang)))
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-expand-body:" lang)))))))
140 org-babel-load-languages))
141
142 (defcustom org-babel-load-languages '((emacs-lisp . t))
143 "Languages which can be evaluated in Org-mode buffers.
144 This list can be used to load support for any of the languages
145 below, note that each language will depend on a different set of
146 system executables and/or Emacs modes. When a language is
147 \"loaded\", then code blocks in that language can be evaluated
148 with `org-babel-execute-src-block' bound by default to C-c
149 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
150 be set to remove code block evaluation from the C-c C-c
151 keybinding. By default only Emacs Lisp (which has no
152 requirements) is loaded."
153 :group 'org-babel
154 :set 'org-babel-do-load-languages
155 :version "24.1"
156 :type '(alist :tag "Babel Languages"
157 :key-type
158 (choice
159 (const :tag "Awk" awk)
160 (const :tag "C" C)
161 (const :tag "R" R)
162 (const :tag "Asymptote" asymptote)
163 (const :tag "Calc" calc)
164 (const :tag "Clojure" clojure)
165 (const :tag "CSS" css)
166 (const :tag "Ditaa" ditaa)
167 (const :tag "Dot" dot)
168 (const :tag "Emacs Lisp" emacs-lisp)
169 (const :tag "Fortran" fortran)
170 (const :tag "Gnuplot" gnuplot)
171 (const :tag "Haskell" haskell)
172 (const :tag "Java" java)
173 (const :tag "Javascript" js)
174 (const :tag "Latex" latex)
175 (const :tag "Ledger" ledger)
176 (const :tag "Lilypond" lilypond)
177 (const :tag "Maxima" maxima)
178 (const :tag "Matlab" matlab)
179 (const :tag "Mscgen" mscgen)
180 (const :tag "Ocaml" ocaml)
181 (const :tag "Octave" octave)
182 (const :tag "Org" org)
183 (const :tag "Perl" perl)
184 (const :tag "Pico Lisp" picolisp)
185 (const :tag "PlantUML" plantuml)
186 (const :tag "Python" python)
187 (const :tag "Ruby" ruby)
188 (const :tag "Sass" sass)
189 (const :tag "Scheme" scheme)
190 (const :tag "Screen" screen)
191 (const :tag "Shell Script" sh)
192 (const :tag "Shen" shen)
193 (const :tag "Sql" sql)
194 (const :tag "Sqlite" sqlite))
195 :value-type (boolean :tag "Activate" :value t)))
196
197 ;;;; Customization variables
198 (defcustom org-clone-delete-id nil
199 "Remove ID property of clones of a subtree.
200 When non-nil, clones of a subtree don't inherit the ID property.
201 Otherwise they inherit the ID property with a new unique
202 identifier."
203 :type 'boolean
204 :version "24.1"
205 :group 'org-id)
206
207 ;;; Version
208
209 (defconst org-version "7.8.11"
210 "The version number of the file org.el.")
211
212 ;;;###autoload
213 (defun org-version (&optional here)
214 "Show the org-mode version in the echo area.
215 With prefix arg HERE, insert it at point."
216 (interactive "P")
217 (let* ((origin default-directory)
218 (version org-version)
219 (git-version)
220 (dir (concat (file-name-directory (locate-library "org")) "../" )))
221 (when (and (file-exists-p (expand-file-name ".git" dir))
222 (executable-find "git"))
223 (unwind-protect
224 (progn
225 (cd dir)
226 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
227 (with-current-buffer "*Shell Command Output*"
228 (goto-char (point-min))
229 (setq git-version (buffer-substring (point) (point-at-eol))))
230 (subst-char-in-string ?- ?. git-version t)
231 (when (string-match "\\S-"
232 (shell-command-to-string
233 "git diff-index --name-only HEAD --"))
234 (setq git-version (concat git-version ".dirty")))
235 (setq version (concat version " (" git-version ")"))))
236 (cd origin)))
237 (setq version (format "Org-mode version %s" version))
238 (if here (insert version))
239 (message version)))
240
241 ;;; Compatibility constants
242
243 ;;; The custom variables
244
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
250
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
255
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
260
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
266
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
270
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
279
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
285
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
289
290 (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)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
295
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
300
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
329
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
345
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
347
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
367
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
370
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
377
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
386
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
392
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
400
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
403
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
411
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
414
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
417
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
421
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
425
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
437
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
442
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
447
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
458
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
465
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
470
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
477
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
485
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
491
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
497
498 Not all export backends support this, but HTML does.
499
500 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
508
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
511
512
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
517
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
522
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
533
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
543
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
553
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
563
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
569
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
575
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
582
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
585
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
596
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
602
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
616
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
623
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
627
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
639
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
642
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
647
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
656
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
665
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
670
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
675
676 (defcustom org-comment-string "COMMENT"
677 "Entries starting with this keyword will never be exported.
678 An entry can be toggled between COMMENT and normal with
679 \\[org-toggle-comment].
680 Changes become only effective after restarting Emacs."
681 :group 'org-keywords
682 :type 'string)
683
684 (defcustom org-quote-string "QUOTE"
685 "Entries starting with this keyword will be exported in fixed-width font.
686 Quoting applies only to the text in the entry following the headline, and does
687 not extend beyond the next headline, even if that is lower level.
688 An entry can be toggled between QUOTE and normal with
689 \\[org-toggle-fixed-width-section]."
690 :group 'org-keywords
691 :type 'string)
692
693 (defconst org-repeat-re
694 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
695 "Regular expression for specifying repeated events.
696 After a match, group 1 contains the repeat expression.")
697
698 (defgroup org-structure nil
699 "Options concerning the general structure of Org-mode files."
700 :tag "Org Structure"
701 :group 'org)
702
703 (defgroup org-reveal-location nil
704 "Options about how to make context of a location visible."
705 :tag "Org Reveal Location"
706 :group 'org-structure)
707
708 (defconst org-context-choice
709 '(choice
710 (const :tag "Always" t)
711 (const :tag "Never" nil)
712 (repeat :greedy t :tag "Individual contexts"
713 (cons
714 (choice :tag "Context"
715 (const agenda)
716 (const org-goto)
717 (const occur-tree)
718 (const tags-tree)
719 (const link-search)
720 (const mark-goto)
721 (const bookmark-jump)
722 (const isearch)
723 (const default))
724 (boolean))))
725 "Contexts for the reveal options.")
726
727 (defcustom org-show-hierarchy-above '((default . t))
728 "Non-nil means show full hierarchy when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the hierarchy of headings
731 above the exposed location is shown.
732 Turning this off for example for sparse trees makes them very compact.
733 Instead of t, this can also be an alist specifying this option for different
734 contexts. Valid contexts are
735 agenda when exposing an entry from the agenda
736 org-goto when using the command `org-goto' on key C-c C-j
737 occur-tree when using the command `org-occur' on key C-c /
738 tags-tree when constructing a sparse tree based on tags matches
739 link-search when exposing search matches associated with a link
740 mark-goto when exposing the jump goal of a mark
741 bookmark-jump when exposing a bookmark location
742 isearch when exiting from an incremental search
743 default default for all contexts not set explicitly"
744 :group 'org-reveal-location
745 :type org-context-choice)
746
747 (defcustom org-show-following-heading '((default . nil))
748 "Non-nil means show following heading when revealing a location.
749 Org-mode often shows locations in an org-mode file which might have
750 been invisible before. When this is set, the heading following the
751 match is shown.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
759
760 (defcustom org-show-siblings '((default . nil) (isearch t))
761 "Non-nil means show all sibling heading when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the sibling of the current entry
764 heading are all made visible. If `org-show-hierarchy-above' is t,
765 the same happens on each level of the hierarchy above the current entry.
766
767 By default this is on for the isearch context, off for all other contexts.
768 Turning this off for example for sparse trees makes them very compact,
769 but makes it harder to edit the location of the match. In such a case,
770 use the command \\[org-reveal] to show more context.
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)
775
776 (defcustom org-show-entry-below '((default . nil))
777 "Non-nil means show the entry below a headline when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the text below the headline that is
780 exposed is also shown.
781
782 By default this is off for all contexts.
783 Instead of t, this can also be an alist specifying this option for different
784 contexts. See `org-show-hierarchy-above' for valid contexts."
785 :group 'org-reveal-location
786 :type org-context-choice)
787
788 (defcustom org-indirect-buffer-display 'other-window
789 "How should indirect tree buffers be displayed?
790 This applies to indirect buffers created with the commands
791 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
792 Valid values are:
793 current-window Display in the current window
794 other-window Just display in another window.
795 dedicated-frame Create one new frame, and re-use it each time.
796 new-frame Make a new frame each time. Note that in this case
797 previously-made indirect buffers are kept, and you need to
798 kill these buffers yourself."
799 :group 'org-structure
800 :group 'org-agenda-windows
801 :type '(choice
802 (const :tag "In current window" current-window)
803 (const :tag "In current frame, other window" other-window)
804 (const :tag "Each time a new frame" new-frame)
805 (const :tag "One dedicated frame" dedicated-frame)))
806
807 (defcustom org-use-speed-commands nil
808 "Non-nil means activate single letter commands at beginning of a headline.
809 This may also be a function to test for appropriate locations where speed
810 commands should be active."
811 :group 'org-structure
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "At beginning of headline stars" t)
815 (function)))
816
817 (defcustom org-speed-commands-user nil
818 "Alist of additional speed commands.
819 This list will be checked before `org-speed-commands-default'
820 when the variable `org-use-speed-commands' is non-nil
821 and when the cursor is at the beginning of a headline.
822 The car if each entry is a string with a single letter, which must
823 be assigned to `self-insert-command' in the global map.
824 The cdr is either a command to be called interactively, a function
825 to be called, or a form to be evaluated.
826 An entry that is just a list with a single string will be interpreted
827 as a descriptive headline that will be added when listing the speed
828 commands in the Help buffer using the `?' speed command."
829 :group 'org-structure
830 :type '(repeat :value ("k" . ignore)
831 (choice :value ("k" . ignore)
832 (list :tag "Descriptive Headline" (string :tag "Headline"))
833 (cons :tag "Letter and Command"
834 (string :tag "Command letter")
835 (choice
836 (function)
837 (sexp))))))
838
839 (defgroup org-cycle nil
840 "Options concerning visibility cycling in Org-mode."
841 :tag "Org Cycle"
842 :group 'org-structure)
843
844 (defcustom org-cycle-skip-children-state-if-no-children t
845 "Non-nil means skip CHILDREN state in entries that don't have any."
846 :group 'org-cycle
847 :type 'boolean)
848
849 (defcustom org-cycle-max-level nil
850 "Maximum level which should still be subject to visibility cycling.
851 Levels higher than this will, for cycling, be treated as text, not a headline.
852 When `org-odd-levels-only' is set, a value of N in this variable actually
853 means 2N-1 stars as the limiting headline.
854 When nil, cycle all levels.
855 Note that the limiting level of cycling is also influenced by
856 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
857 `org-inlinetask-min-level' is, cycling will be limited to levels one less
858 than its value."
859 :group 'org-cycle
860 :type '(choice
861 (const :tag "No limit" nil)
862 (integer :tag "Maximum level")))
863
864 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
865 "Names of drawers. Drawers are not opened by cycling on the headline above.
866 Drawers only open with a TAB on the drawer line itself. A drawer looks like
867 this:
868 :DRAWERNAME:
869 .....
870 :END:
871 The drawer \"PROPERTIES\" is special for capturing properties through
872 the property API.
873
874 Drawers can be defined on the per-file basis with a line like:
875
876 #+DRAWERS: HIDDEN STATE PROPERTIES"
877 :group 'org-structure
878 :group 'org-cycle
879 :type '(repeat (string :tag "Drawer Name")))
880
881 (defcustom org-hide-block-startup nil
882 "Non-nil means entering Org-mode will fold all blocks.
883 This can also be set in on a per-file basis with
884
885 #+STARTUP: hideblocks
886 #+STARTUP: showblocks"
887 :group 'org-startup
888 :group 'org-cycle
889 :type 'boolean)
890
891 (defcustom org-cycle-global-at-bob nil
892 "Cycle globally if cursor is at beginning of buffer and not at a headline.
893 This makes it possible to do global cycling without having to use S-TAB or
894 \\[universal-argument] TAB. For this special case to work, the first line \
895 of the buffer
896 must not be a headline - it may be empty or some other text. When used in
897 this way, `org-cycle-hook' is disables temporarily, to make sure the
898 cursor stays at the beginning of the buffer.
899 When this option is nil, don't do anything special at the beginning
900 of the buffer."
901 :group 'org-cycle
902 :type 'boolean)
903
904 (defcustom org-cycle-level-after-item/entry-creation t
905 "Non-nil means cycle entry level or item indentation in new empty entries.
906
907 When the cursor is at the end of an empty headline, i.e with only stars
908 and maybe a TODO keyword, TAB will then switch the entry to become a child,
909 and then all possible ancestor states, before returning to the original state.
910 This makes data entry extremely fast: M-RET to create a new headline,
911 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
912
913 When the cursor is at the end of an empty plain list item, one TAB will
914 make it a subitem, two or more tabs will back up to make this an item
915 higher up in the item hierarchy."
916 :group 'org-cycle
917 :type 'boolean)
918
919 (defcustom org-cycle-emulate-tab t
920 "Where should `org-cycle' emulate TAB.
921 nil Never
922 white Only in completely white lines
923 whitestart Only at the beginning of lines, before the first non-white char
924 t Everywhere except in headlines
925 exc-hl-bol Everywhere except at the start of a headline
926 If TAB is used in a place where it does not emulate TAB, the current subtree
927 visibility is cycled."
928 :group 'org-cycle
929 :type '(choice (const :tag "Never" nil)
930 (const :tag "Only in completely white lines" white)
931 (const :tag "Before first char in a line" whitestart)
932 (const :tag "Everywhere except in headlines" t)
933 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
934 ))
935
936 (defcustom org-cycle-separator-lines 2
937 "Number of empty lines needed to keep an empty line between collapsed trees.
938 If you leave an empty line between the end of a subtree and the following
939 headline, this empty line is hidden when the subtree is folded.
940 Org-mode will leave (exactly) one empty line visible if the number of
941 empty lines is equal or larger to the number given in this variable.
942 So the default 2 means at least 2 empty lines after the end of a subtree
943 are needed to produce free space between a collapsed subtree and the
944 following headline.
945
946 If the number is negative, and the number of empty lines is at least -N,
947 all empty lines are shown.
948
949 Special case: when 0, never leave empty lines in collapsed view."
950 :group 'org-cycle
951 :type 'integer)
952 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
953
954 (defcustom org-pre-cycle-hook nil
955 "Hook that is run before visibility cycling is happening.
956 The function(s) in this hook must accept a single argument which indicates
957 the new state that will be set right after running this hook. The
958 argument is a symbol. Before a global state change, it can have the values
959 `overview', `content', or `all'. Before a local state change, it can have
960 the values `folded', `children', or `subtree'."
961 :group 'org-cycle
962 :type 'hook)
963
964 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
965 org-cycle-hide-drawers
966 org-cycle-show-empty-lines
967 org-optimize-window-after-visibility-change)
968 "Hook that is run after `org-cycle' has changed the buffer visibility.
969 The function(s) in this hook must accept a single argument which indicates
970 the new state that was set by the most recent `org-cycle' command. The
971 argument is a symbol. After a global state change, it can have the values
972 `overview', `content', or `all'. After a local state change, it can have
973 the values `folded', `children', or `subtree'."
974 :group 'org-cycle
975 :type 'hook)
976
977 (defgroup org-edit-structure nil
978 "Options concerning structure editing in Org-mode."
979 :tag "Org Edit Structure"
980 :group 'org-structure)
981
982 (defcustom org-odd-levels-only nil
983 "Non-nil means skip even levels and only use odd levels for the outline.
984 This has the effect that two stars are being added/taken away in
985 promotion/demotion commands. It also influences how levels are
986 handled by the exporters.
987 Changing it requires restart of `font-lock-mode' to become effective
988 for fontification also in regions already fontified.
989 You may also set this on a per-file basis by adding one of the following
990 lines to the buffer:
991
992 #+STARTUP: odd
993 #+STARTUP: oddeven"
994 :group 'org-edit-structure
995 :group 'org-appearance
996 :type 'boolean)
997
998 (defcustom org-adapt-indentation t
999 "Non-nil means adapt indentation to outline node level.
1000
1001 When this variable is set, Org assumes that you write outlines by
1002 indenting text in each node to align with the headline (after the stars).
1003 The following issues are influenced by this variable:
1004
1005 - When this is set and the *entire* text in an entry is indented, the
1006 indentation is increased by one space in a demotion command, and
1007 decreased by one in a promotion command. If any line in the entry
1008 body starts with text at column 0, indentation is not changed at all.
1009
1010 - Property drawers and planning information is inserted indented when
1011 this variable s set. When nil, they will not be indented.
1012
1013 - TAB indents a line relative to context. The lines below a headline
1014 will be indented when this variable is set.
1015
1016 Note that this is all about true indentation, by adding and removing
1017 space characters. See also `org-indent.el' which does level-dependent
1018 indentation in a virtual way, i.e. at display time in Emacs."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1021
1022 (defcustom org-special-ctrl-a/e nil
1023 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1024
1025 When t, `C-a' will bring back the cursor to the beginning of the
1026 headline text, i.e. after the stars and after a possible TODO keyword.
1027 In an item, this will be the position after the bullet.
1028 When the cursor is already at that position, another `C-a' will bring
1029 it to the beginning of the line.
1030
1031 `C-e' will jump to the end of the headline, ignoring the presence of tags
1032 in the headline. A second `C-e' will then jump to the true end of the
1033 line, after any tags. This also means that, when this variable is
1034 non-nil, `C-e' also will never jump beyond the end of the heading of a
1035 folded section, i.e. not after the ellipses.
1036
1037 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1038 going to the true line boundary first. Only a directly following, identical
1039 keypress will bring the cursor to the special positions.
1040
1041 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1042 set separately."
1043 :group 'org-edit-structure
1044 :type '(choice
1045 (const :tag "off" nil)
1046 (const :tag "on: after stars/bullet and before tags first" t)
1047 (const :tag "reversed: true line boundary first" reversed)
1048 (cons :tag "Set C-a and C-e separately"
1049 (choice :tag "Special C-a"
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet first" t)
1052 (const :tag "reversed: before stars/bullet first" reversed))
1053 (choice :tag "Special C-e"
1054 (const :tag "off" nil)
1055 (const :tag "on: before tags first" t)
1056 (const :tag "reversed: after tags first" reversed)))))
1057 (if (fboundp 'defvaralias)
1058 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1059
1060 (defcustom org-special-ctrl-k nil
1061 "Non-nil means `C-k' will behave specially in headlines.
1062 When nil, `C-k' will call the default `kill-line' command.
1063 When t, the following will happen while the cursor is in the headline:
1064
1065 - When the cursor is at the beginning of a headline, kill the entire
1066 line and possible the folded subtree below the line.
1067 - When in the middle of the headline text, kill the headline up to the tags.
1068 - When after the headline text, kill the tags."
1069 :group 'org-edit-structure
1070 :type 'boolean)
1071
1072 (defcustom org-ctrl-k-protect-subtree nil
1073 "Non-nil means, do not delete a hidden subtree with C-k.
1074 When set to the symbol `error', simply throw an error when C-k is
1075 used to kill (part-of) a headline that has hidden text behind it.
1076 Any other non-nil value will result in a query to the user, if it is
1077 OK to kill that hidden subtree. When nil, kill without remorse."
1078 :group 'org-edit-structure
1079 :version "24.1"
1080 :type '(choice
1081 (const :tag "Do not protect hidden subtrees" nil)
1082 (const :tag "Protect hidden subtrees with a security query" t)
1083 (const :tag "Never kill a hidden subtree with C-k" error)))
1084
1085 (defcustom org-catch-invisible-edits nil
1086 "Check if in invisible region before inserting or deleting a character.
1087 Valid values are:
1088
1089 nil Do not check, so just do invisible edits.
1090 error Throw an error and do nothing.
1091 show Make point visible, and do the requested edit.
1092 show-and-error Make point visible, then throw an error and abort the edit.
1093 smart Make point visible, and do insertion/deletion if it is
1094 adjacent to visible text and the change feels predictable.
1095 Never delete a previously invisible character or add in the
1096 middle or right after an invisible region. Basically, this
1097 allows insertion and backward-delete right before ellipses.
1098 FIXME: maybe in this case we should not even show?"
1099 :group 'org-edit-structure
1100 :version "24.1"
1101 :type '(choice
1102 (const :tag "Do not check" nil)
1103 (const :tag "Throw error when trying to edit" error)
1104 (const :tag "Unhide, but do not do the edit" show-and-error)
1105 (const :tag "Show invisible part and do the edit" show)
1106 (const :tag "Be smart and do the right thing" smart)))
1107
1108 (defcustom org-yank-folded-subtrees t
1109 "Non-nil means when yanking subtrees, fold them.
1110 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1111 it starts with a heading and all other headings in it are either children
1112 or siblings, then fold all the subtrees. However, do this only if no
1113 text after the yank would be swallowed into a folded tree by this action."
1114 :group 'org-edit-structure
1115 :type 'boolean)
1116
1117 (defcustom org-yank-adjusted-subtrees nil
1118 "Non-nil means when yanking subtrees, adjust the level.
1119 With this setting, `org-paste-subtree' is used to insert the subtree, see
1120 this function for details."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1123
1124 (defcustom org-M-RET-may-split-line '((default . t))
1125 "Non-nil means M-RET will split the line at the cursor position.
1126 When nil, it will go to the end of the line before making a
1127 new line.
1128 You may also set this option in a different way for different
1129 contexts. Valid contexts are:
1130
1131 headline when creating a new headline
1132 item when creating a new item
1133 table in a table field
1134 default the value to be used for all contexts not explicitly
1135 customized"
1136 :group 'org-structure
1137 :group 'org-table
1138 :type '(choice
1139 (const :tag "Always" t)
1140 (const :tag "Never" nil)
1141 (repeat :greedy t :tag "Individual contexts"
1142 (cons
1143 (choice :tag "Context"
1144 (const headline)
1145 (const item)
1146 (const table)
1147 (const default))
1148 (boolean)))))
1149
1150
1151 (defcustom org-insert-heading-respect-content nil
1152 "Non-nil means insert new headings after the current subtree.
1153 When nil, the new heading is created directly after the current line.
1154 The commands \\[org-insert-heading-respect-content] and
1155 \\[org-insert-todo-heading-respect-content] turn this variable on
1156 for the duration of the command."
1157 :group 'org-structure
1158 :type 'boolean)
1159
1160 (defcustom org-blank-before-new-entry '((heading . auto)
1161 (plain-list-item . auto))
1162 "Should `org-insert-heading' leave a blank line before new heading/item?
1163 The value is an alist, with `heading' and `plain-list-item' as CAR,
1164 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1165 which case Org will look at the surrounding headings/items and try to
1166 make an intelligent decision whether to insert a blank line or not.
1167
1168 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1169 set, the setting here is ignored and no empty line is inserted, to avoid
1170 breaking the list structure."
1171 :group 'org-edit-structure
1172 :type '(list
1173 (cons (const heading)
1174 (choice (const :tag "Never" nil)
1175 (const :tag "Always" t)
1176 (const :tag "Auto" auto)))
1177 (cons (const plain-list-item)
1178 (choice (const :tag "Never" nil)
1179 (const :tag "Always" t)
1180 (const :tag "Auto" auto)))))
1181
1182 (defcustom org-insert-heading-hook nil
1183 "Hook being run after inserting a new heading."
1184 :group 'org-edit-structure
1185 :type 'hook)
1186
1187 (defcustom org-enable-fixed-width-editor t
1188 "Non-nil means lines starting with \":\" are treated as fixed-width.
1189 This currently only means they are never auto-wrapped.
1190 When nil, such lines will be treated like ordinary lines.
1191 See also the QUOTE keyword."
1192 :group 'org-edit-structure
1193 :type 'boolean)
1194
1195 (defcustom org-goto-auto-isearch t
1196 "Non-nil means typing characters in `org-goto' starts incremental search."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1199
1200 (defgroup org-sparse-trees nil
1201 "Options concerning sparse trees in Org-mode."
1202 :tag "Org Sparse Trees"
1203 :group 'org-structure)
1204
1205 (defcustom org-highlight-sparse-tree-matches t
1206 "Non-nil means highlight all matches that define a sparse tree.
1207 The highlights will automatically disappear the next time the buffer is
1208 changed by an edit command."
1209 :group 'org-sparse-trees
1210 :type 'boolean)
1211
1212 (defcustom org-remove-highlights-with-change t
1213 "Non-nil means any change to the buffer will remove temporary highlights.
1214 Such highlights are created by `org-occur' and `org-clock-display'.
1215 When nil, `C-c C-c needs to be used to get rid of the highlights.
1216 The highlights created by `org-preview-latex-fragment' always need
1217 `C-c C-c' to be removed."
1218 :group 'org-sparse-trees
1219 :group 'org-time
1220 :type 'boolean)
1221
1222
1223 (defcustom org-occur-hook '(org-first-headline-recenter)
1224 "Hook that is run after `org-occur' has constructed a sparse tree.
1225 This can be used to recenter the window to show as much of the structure
1226 as possible."
1227 :group 'org-sparse-trees
1228 :type 'hook)
1229
1230 (defgroup org-imenu-and-speedbar nil
1231 "Options concerning imenu and speedbar in Org-mode."
1232 :tag "Org Imenu and Speedbar"
1233 :group 'org-structure)
1234
1235 (defcustom org-imenu-depth 2
1236 "The maximum level for Imenu access to Org-mode headlines.
1237 This also applied for speedbar access."
1238 :group 'org-imenu-and-speedbar
1239 :type 'integer)
1240
1241 (defgroup org-table nil
1242 "Options concerning tables in Org-mode."
1243 :tag "Org Table"
1244 :group 'org)
1245
1246 (defcustom org-enable-table-editor 'optimized
1247 "Non-nil means lines starting with \"|\" are handled by the table editor.
1248 When nil, such lines will be treated like ordinary lines.
1249
1250 When equal to the symbol `optimized', the table editor will be optimized to
1251 do the following:
1252 - Automatic overwrite mode in front of whitespace in table fields.
1253 This makes the structure of the table stay in tact as long as the edited
1254 field does not exceed the column width.
1255 - Minimize the number of realigns. Normally, the table is aligned each time
1256 TAB or RET are pressed to move to another field. With optimization this
1257 happens only if changes to a field might have changed the column width.
1258 Optimization requires replacing the functions `self-insert-command',
1259 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1260 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1261 very good at guessing when a re-align will be necessary, but you can always
1262 force one with \\[org-ctrl-c-ctrl-c].
1263
1264 If you would like to use the optimized version in Org-mode, but the
1265 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1266
1267 This variable can be used to turn on and off the table editor during a session,
1268 but in order to toggle optimization, a restart is required.
1269
1270 See also the variable `org-table-auto-blank-field'."
1271 :group 'org-table
1272 :type '(choice
1273 (const :tag "off" nil)
1274 (const :tag "on" t)
1275 (const :tag "on, optimized" optimized)))
1276
1277 (defcustom org-self-insert-cluster-for-undo t
1278 "Non-nil means cluster self-insert commands for undo when possible.
1279 If this is set, then, like in the Emacs command loop, 20 consecutive
1280 characters will be undone together.
1281 This is configurable, because there is some impact on typing performance."
1282 :group 'org-table
1283 :type 'boolean)
1284
1285 (defcustom org-table-tab-recognizes-table.el t
1286 "Non-nil means TAB will automatically notice a table.el table.
1287 When it sees such a table, it moves point into it and - if necessary -
1288 calls `table-recognize-table'."
1289 :group 'org-table-editing
1290 :type 'boolean)
1291
1292 (defgroup org-link nil
1293 "Options concerning links in Org-mode."
1294 :tag "Org Link"
1295 :group 'org)
1296
1297 (defvar org-link-abbrev-alist-local nil
1298 "Buffer-local version of `org-link-abbrev-alist', which see.
1299 The value of this is taken from the #+LINK lines.")
1300 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1301
1302 (defcustom org-link-abbrev-alist nil
1303 "Alist of link abbreviations.
1304 The car of each element is a string, to be replaced at the start of a link.
1305 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1306 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1307
1308 [[linkkey:tag][description]]
1309
1310 The 'linkkey' must be a word word, starting with a letter, followed
1311 by letters, numbers, '-' or '_'.
1312
1313 If REPLACE is a string, the tag will simply be appended to create the link.
1314 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1315 the placeholder \"%h\" will cause a url-encoded version of the tag to
1316 be inserted at that point (see the function `url-hexify-string').
1317
1318 REPLACE may also be a function that will be called with the tag as the
1319 only argument to create the link, which should be returned as a string.
1320
1321 See the manual for examples."
1322 :group 'org-link
1323 :type '(repeat
1324 (cons
1325 (string :tag "Protocol")
1326 (choice
1327 (string :tag "Format")
1328 (function)))))
1329
1330 (defcustom org-descriptive-links t
1331 "Non-nil means Org will display descriptive links.
1332 E.g. [[http://orgmode.org][Org website]] will be displayed as
1333 \"Org Website\", hiding the link itself and just displaying its
1334 description. When set to `nil', Org will display the full links
1335 literally.
1336
1337 You can interactively set the value of this variable by calling
1338 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1339 :group 'org-link
1340 :type 'boolean)
1341
1342 (defcustom org-link-file-path-type 'adaptive
1343 "How the path name in file links should be stored.
1344 Valid values are:
1345
1346 relative Relative to the current directory, i.e. the directory of the file
1347 into which the link is being inserted.
1348 absolute Absolute path, if possible with ~ for home directory.
1349 noabbrev Absolute path, no abbreviation of home directory.
1350 adaptive Use relative path for files in the current directory and sub-
1351 directories of it. For other files, use an absolute path."
1352 :group 'org-link
1353 :type '(choice
1354 (const relative)
1355 (const absolute)
1356 (const noabbrev)
1357 (const adaptive)))
1358
1359 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1360 "Types of links that should be activated in Org-mode files.
1361 This is a list of symbols, each leading to the activation of a certain link
1362 type. In principle, it does not hurt to turn on most link types - there may
1363 be a small gain when turning off unused link types. The types are:
1364
1365 bracket The recommended [[link][description]] or [[link]] links with hiding.
1366 angle Links in angular brackets that may contain whitespace like
1367 <bbdb:Carsten Dominik>.
1368 plain Plain links in normal text, no whitespace, like http://google.com.
1369 radio Text that is matched by a radio target, see manual for details.
1370 tag Tag settings in a headline (link to tag search).
1371 date Time stamps (link to calendar).
1372 footnote Footnote labels.
1373
1374 Changing this variable requires a restart of Emacs to become effective."
1375 :group 'org-link
1376 :type '(set :greedy t
1377 (const :tag "Double bracket links" bracket)
1378 (const :tag "Angular bracket links" angle)
1379 (const :tag "Plain text links" plain)
1380 (const :tag "Radio target matches" radio)
1381 (const :tag "Tags" tag)
1382 (const :tag "Timestamps" date)
1383 (const :tag "Footnotes" footnote)))
1384
1385 (defcustom org-make-link-description-function nil
1386 "Function to use to generate link descriptions from links.
1387 If nil the link location will be used. This function must take
1388 two parameters; the first is the link and the second the
1389 description `org-insert-link' has generated, and should return the
1390 description to use."
1391 :group 'org-link
1392 :type 'function)
1393
1394 (defgroup org-link-store nil
1395 "Options concerning storing links in Org-mode."
1396 :tag "Org Store Link"
1397 :group 'org-link)
1398
1399 (defcustom org-email-link-description-format "Email %c: %.30s"
1400 "Format of the description part of a link to an email or usenet message.
1401 The following %-escapes will be replaced by corresponding information:
1402
1403 %F full \"From\" field
1404 %f name, taken from \"From\" field, address if no name
1405 %T full \"To\" field
1406 %t first name in \"To\" field, address if no name
1407 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1408 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1409 %s subject
1410 %d date
1411 %m message-id.
1412
1413 You may use normal field width specification between the % and the letter.
1414 This is for example useful to limit the length of the subject.
1415
1416 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1417 :group 'org-link-store
1418 :type 'string)
1419
1420 (defcustom org-from-is-user-regexp
1421 (let (r1 r2)
1422 (when (and user-mail-address (not (string= user-mail-address "")))
1423 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1424 (when (and user-full-name (not (string= user-full-name "")))
1425 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1426 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1427 "Regexp matched against the \"From:\" header of an email or usenet message.
1428 It should match if the message is from the user him/herself."
1429 :group 'org-link-store
1430 :type 'regexp)
1431
1432 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1433 "Non-nil means storing a link to an Org file will use entry IDs.
1434
1435 Note that before this variable is even considered, org-id must be loaded,
1436 so please customize `org-modules' and turn it on.
1437
1438 The variable can have the following values:
1439
1440 t Create an ID if needed to make a link to the current entry.
1441
1442 create-if-interactive
1443 If `org-store-link' is called directly (interactively, as a user
1444 command), do create an ID to support the link. But when doing the
1445 job for remember, only use the ID if it already exists. The
1446 purpose of this setting is to avoid proliferation of unwanted
1447 IDs, just because you happen to be in an Org file when you
1448 call `org-remember' that automatically and preemptively
1449 creates a link. If you do want to get an ID link in a remember
1450 template to an entry not having an ID, create it first by
1451 explicitly creating a link to it, using `C-c C-l' first.
1452
1453 create-if-interactive-and-no-custom-id
1454 Like create-if-interactive, but do not create an ID if there is
1455 a CUSTOM_ID property defined in the entry. This is the default.
1456
1457 use-existing
1458 Use existing ID, do not create one.
1459
1460 nil Never use an ID to make a link, instead link using a text search for
1461 the headline text."
1462 :group 'org-link-store
1463 :type '(choice
1464 (const :tag "Create ID to make link" t)
1465 (const :tag "Create if storing link interactively"
1466 create-if-interactive)
1467 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1468 create-if-interactive-and-no-custom-id)
1469 (const :tag "Only use existing" use-existing)
1470 (const :tag "Do not use ID to create link" nil)))
1471
1472 (defcustom org-context-in-file-links t
1473 "Non-nil means file links from `org-store-link' contain context.
1474 A search string will be added to the file name with :: as separator and
1475 used to find the context when the link is activated by the command
1476 `org-open-at-point'. When this option is t, the entire active region
1477 will be placed in the search string of the file link. If set to a
1478 positive integer, only the first n lines of context will be stored.
1479
1480 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1481 negates this setting for the duration of the command."
1482 :group 'org-link-store
1483 :type '(choice boolean integer))
1484
1485 (defcustom org-keep-stored-link-after-insertion nil
1486 "Non-nil means keep link in list for entire session.
1487
1488 The command `org-store-link' adds a link pointing to the current
1489 location to an internal list. These links accumulate during a session.
1490 The command `org-insert-link' can be used to insert links into any
1491 Org-mode file (offering completion for all stored links). When this
1492 option is nil, every link which has been inserted once using \\[org-insert-link]
1493 will be removed from the list, to make completing the unused links
1494 more efficient."
1495 :group 'org-link-store
1496 :type 'boolean)
1497
1498 (defgroup org-link-follow nil
1499 "Options concerning following links in Org-mode."
1500 :tag "Org Follow Link"
1501 :group 'org-link)
1502
1503 (defcustom org-link-translation-function nil
1504 "Function to translate links with different syntax to Org syntax.
1505 This can be used to translate links created for example by the Planner
1506 or emacs-wiki packages to Org syntax.
1507 The function must accept two parameters, a TYPE containing the link
1508 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1509 which is everything after the link protocol. It should return a cons
1510 with possibly modified values of type and path.
1511 Org contains a function for this, so if you set this variable to
1512 `org-translate-link-from-planner', you should be able follow many
1513 links created by planner."
1514 :group 'org-link-follow
1515 :type 'function)
1516
1517 (defcustom org-follow-link-hook nil
1518 "Hook that is run after a link has been followed."
1519 :group 'org-link-follow
1520 :type 'hook)
1521
1522 (defcustom org-tab-follows-link nil
1523 "Non-nil means on links TAB will follow the link.
1524 Needs to be set before org.el is loaded.
1525 This really should not be used, it does not make sense, and the
1526 implementation is bad."
1527 :group 'org-link-follow
1528 :type 'boolean)
1529
1530 (defcustom org-return-follows-link nil
1531 "Non-nil means on links RET will follow the link."
1532 :group 'org-link-follow
1533 :type 'boolean)
1534
1535 (defcustom org-mouse-1-follows-link
1536 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1537 "Non-nil means mouse-1 on a link will follow the link.
1538 A longer mouse click will still set point. Does not work on XEmacs.
1539 Needs to be set before org.el is loaded."
1540 :group 'org-link-follow
1541 :type 'boolean)
1542
1543 (defcustom org-mark-ring-length 4
1544 "Number of different positions to be recorded in the ring.
1545 Changing this requires a restart of Emacs to work correctly."
1546 :group 'org-link-follow
1547 :type 'integer)
1548
1549 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1550 "Non-nil means internal links in Org files must exactly match a headline.
1551 When nil, the link search tries to match a phrase with all words
1552 in the search text."
1553 :group 'org-link-follow
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Use fuzzy text search" nil)
1557 (const :tag "Match only exact headline" t)
1558 (const :tag "Match exact headline or query to create it"
1559 query-to-create)))
1560
1561 (defcustom org-link-frame-setup
1562 '((vm . vm-visit-folder-other-frame)
1563 (gnus . org-gnus-no-new-news)
1564 (file . find-file-other-window)
1565 (wl . wl-other-frame))
1566 "Setup the frame configuration for following links.
1567 When following a link with Emacs, it may often be useful to display
1568 this link in another window or frame. This variable can be used to
1569 set this up for the different types of links.
1570 For VM, use any of
1571 `vm-visit-folder'
1572 `vm-visit-folder-other-window'
1573 `vm-visit-folder-other-frame'
1574 For Gnus, use any of
1575 `gnus'
1576 `gnus-other-frame'
1577 `org-gnus-no-new-news'
1578 For FILE, use any of
1579 `find-file'
1580 `find-file-other-window'
1581 `find-file-other-frame'
1582 For Wanderlust use any of
1583 `wl'
1584 `wl-other-frame'
1585 For the calendar, use the variable `calendar-setup'.
1586 For BBDB, it is currently only possible to display the matches in
1587 another window."
1588 :group 'org-link-follow
1589 :type '(list
1590 (cons (const vm)
1591 (choice
1592 (const vm-visit-folder)
1593 (const vm-visit-folder-other-window)
1594 (const vm-visit-folder-other-frame)))
1595 (cons (const gnus)
1596 (choice
1597 (const gnus)
1598 (const gnus-other-frame)
1599 (const org-gnus-no-new-news)))
1600 (cons (const file)
1601 (choice
1602 (const find-file)
1603 (const find-file-other-window)
1604 (const find-file-other-frame)))
1605 (cons (const wl)
1606 (choice
1607 (const wl)
1608 (const wl-other-frame)))))
1609
1610 (defcustom org-display-internal-link-with-indirect-buffer nil
1611 "Non-nil means use indirect buffer to display infile links.
1612 Activating internal links (from one location in a file to another location
1613 in the same file) normally just jumps to the location. When the link is
1614 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1615 is displayed in
1616 another window. When this option is set, the other window actually displays
1617 an indirect buffer clone of the current buffer, to avoid any visibility
1618 changes to the current buffer."
1619 :group 'org-link-follow
1620 :type 'boolean)
1621
1622 (defcustom org-open-non-existing-files nil
1623 "Non-nil means `org-open-file' will open non-existing files.
1624 When nil, an error will be generated.
1625 This variable applies only to external applications because they
1626 might choke on non-existing files. If the link is to a file that
1627 will be opened in Emacs, the variable is ignored."
1628 :group 'org-link-follow
1629 :type 'boolean)
1630
1631 (defcustom org-open-directory-means-index-dot-org nil
1632 "Non-nil means a link to a directory really means to index.org.
1633 When nil, following a directory link will run dired or open a finder/explorer
1634 window on that directory."
1635 :group 'org-link-follow
1636 :type 'boolean)
1637
1638 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1639 "Function and arguments to call for following mailto links.
1640 This is a list with the first element being a Lisp function, and the
1641 remaining elements being arguments to the function. In string arguments,
1642 %a will be replaced by the address, and %s will be replaced by the subject
1643 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1644 :group 'org-link-follow
1645 :type '(choice
1646 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1647 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1648 (const :tag "message-mail" (message-mail "%a" "%s"))
1649 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1650
1651 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1652 "Non-nil means ask for confirmation before executing shell links.
1653 Shell links can be dangerous: just think about a link
1654
1655 [[shell:rm -rf ~/*][Google Search]]
1656
1657 This link would show up in your Org-mode document as \"Google Search\",
1658 but really it would remove your entire home directory.
1659 Therefore we advise against setting this variable to nil.
1660 Just change it to `y-or-n-p' if you want to confirm with a
1661 single keystroke rather than having to type \"yes\"."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1665 (const :tag "with y-or-n (faster)" y-or-n-p)
1666 (const :tag "no confirmation (dangerous)" nil)))
1667 (put 'org-confirm-shell-link-function
1668 'safe-local-variable
1669 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1670
1671 (defcustom org-confirm-shell-link-not-regexp ""
1672 "A regexp to skip confirmation for shell links."
1673 :group 'org-link-follow
1674 :version "24.1"
1675 :type 'regexp)
1676
1677 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1678 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1679 Elisp links can be dangerous: just think about a link
1680
1681 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1682
1683 This link would show up in your Org-mode document as \"Google Search\",
1684 but really it would remove your entire home directory.
1685 Therefore we advise against setting this variable to nil.
1686 Just change it to `y-or-n-p' if you want to confirm with a
1687 single keystroke rather than having to type \"yes\"."
1688 :group 'org-link-follow
1689 :type '(choice
1690 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1691 (const :tag "with y-or-n (faster)" y-or-n-p)
1692 (const :tag "no confirmation (dangerous)" nil)))
1693 (put 'org-confirm-shell-link-function
1694 'safe-local-variable
1695 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1696
1697 (defcustom org-confirm-elisp-link-not-regexp ""
1698 "A regexp to skip confirmation for Elisp links."
1699 :group 'org-link-follow
1700 :version "24.1"
1701 :type 'regexp)
1702
1703 (defconst org-file-apps-defaults-gnu
1704 '((remote . emacs)
1705 (system . mailcap)
1706 (t . mailcap))
1707 "Default file applications on a UNIX or GNU/Linux system.
1708 See `org-file-apps'.")
1709
1710 (defconst org-file-apps-defaults-macosx
1711 '((remote . emacs)
1712 (t . "open %s")
1713 (system . "open %s")
1714 ("ps.gz" . "gv %s")
1715 ("eps.gz" . "gv %s")
1716 ("dvi" . "xdvi %s")
1717 ("fig" . "xfig %s"))
1718 "Default file applications on a MacOS X system.
1719 The system \"open\" is known as a default, but we use X11 applications
1720 for some files for which the OS does not have a good default.
1721 See `org-file-apps'.")
1722
1723 (defconst org-file-apps-defaults-windowsnt
1724 (list
1725 '(remote . emacs)
1726 (cons t
1727 (list (if (featurep 'xemacs)
1728 'mswindows-shell-execute
1729 'w32-shell-execute)
1730 "open" 'file))
1731 (cons 'system
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file)))
1736 "Default file applications on a Windows NT system.
1737 The system \"open\" is used for most files.
1738 See `org-file-apps'.")
1739
1740 (defcustom org-file-apps
1741 '(
1742 (auto-mode . emacs)
1743 ("\\.mm\\'" . default)
1744 ("\\.x?html?\\'" . default)
1745 ("\\.pdf\\'" . default)
1746 )
1747 "External applications for opening `file:path' items in a document.
1748 Org-mode uses system defaults for different file types, but
1749 you can use this variable to set the application for a given file
1750 extension. The entries in this list are cons cells where the car identifies
1751 files and the cdr the corresponding command. Possible values for the
1752 file identifier are
1753 \"string\" A string as a file identifier can be interpreted in different
1754 ways, depending on its contents:
1755
1756 - Alphanumeric characters only:
1757 Match links with this file extension.
1758 Example: (\"pdf\" . \"evince %s\")
1759 to open PDFs with evince.
1760
1761 - Regular expression: Match links where the
1762 filename matches the regexp. If you want to
1763 use groups here, use shy groups.
1764
1765 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1766 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1767 to open *.html and *.xhtml with firefox.
1768
1769 - Regular expression which contains (non-shy) groups:
1770 Match links where the whole link, including \"::\", and
1771 anything after that, matches the regexp.
1772 In a custom command string, %1, %2, etc. are replaced with
1773 the parts of the link that were matched by the groups.
1774 For backwards compatibility, if a command string is given
1775 that does not use any of the group matches, this case is
1776 handled identically to the second one (i.e. match against
1777 file name only).
1778 In a custom lisp form, you can access the group matches with
1779 (match-string n link).
1780
1781 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1782 to open [[file:document.pdf::5]] with evince at page 5.
1783
1784 `directory' Matches a directory
1785 `remote' Matches a remote file, accessible through tramp or efs.
1786 Remote files most likely should be visited through Emacs
1787 because external applications cannot handle such paths.
1788 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1789 so all files Emacs knows how to handle. Using this with
1790 command `emacs' will open most files in Emacs. Beware that this
1791 will also open html files inside Emacs, unless you add
1792 (\"html\" . default) to the list as well.
1793 t Default for files not matched by any of the other options.
1794 `system' The system command to open files, like `open' on Windows
1795 and Mac OS X, and mailcap under GNU/Linux. This is the command
1796 that will be selected if you call `C-c C-o' with a double
1797 \\[universal-argument] \\[universal-argument] prefix.
1798
1799 Possible values for the command are:
1800 `emacs' The file will be visited by the current Emacs process.
1801 `default' Use the default application for this file type, which is the
1802 association for t in the list, most likely in the system-specific
1803 part.
1804 This can be used to overrule an unwanted setting in the
1805 system-specific variable.
1806 `system' Use the system command for opening files, like \"open\".
1807 This command is specified by the entry whose car is `system'.
1808 Most likely, the system-specific version of this variable
1809 does define this command, but you can overrule/replace it
1810 here.
1811 string A command to be executed by a shell; %s will be replaced
1812 by the path to the file.
1813 sexp A Lisp form which will be evaluated. The file path will
1814 be available in the Lisp variable `file'.
1815 For more examples, see the system specific constants
1816 `org-file-apps-defaults-macosx'
1817 `org-file-apps-defaults-windowsnt'
1818 `org-file-apps-defaults-gnu'."
1819 :group 'org-link-follow
1820 :type '(repeat
1821 (cons (choice :value ""
1822 (string :tag "Extension")
1823 (const :tag "System command to open files" system)
1824 (const :tag "Default for unrecognized files" t)
1825 (const :tag "Remote file" remote)
1826 (const :tag "Links to a directory" directory)
1827 (const :tag "Any files that have Emacs modes"
1828 auto-mode))
1829 (choice :value ""
1830 (const :tag "Visit with Emacs" emacs)
1831 (const :tag "Use default" default)
1832 (const :tag "Use the system command" system)
1833 (string :tag "Command")
1834 (sexp :tag "Lisp form")))))
1835
1836
1837
1838 (defgroup org-refile nil
1839 "Options concerning refiling entries in Org-mode."
1840 :tag "Org Refile"
1841 :group 'org)
1842
1843 (defcustom org-directory "~/org"
1844 "Directory with org files.
1845 This is just a default location to look for Org files. There is no need
1846 at all to put your files into this directory. It is only used in the
1847 following situations:
1848
1849 1. When a remember template specifies a target file that is not an
1850 absolute path. The path will then be interpreted relative to
1851 `org-directory'
1852 2. When a remember note is filed away in an interactive way (when exiting the
1853 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1854 with `org-directory' as the default path."
1855 :group 'org-refile
1856 :group 'org-remember
1857 :type 'directory)
1858
1859 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1860 "Default target for storing notes.
1861 Used as a fall back file for org-remember.el and org-capture.el, for
1862 templates that do not specify a target file."
1863 :group 'org-refile
1864 :group 'org-remember
1865 :type '(choice
1866 (const :tag "Default from remember-data-file" nil)
1867 file))
1868
1869 (defcustom org-goto-interface 'outline
1870 "The default interface to be used for `org-goto'.
1871 Allowed values are:
1872 outline The interface shows an outline of the relevant file
1873 and the correct heading is found by moving through
1874 the outline or by searching with incremental search.
1875 outline-path-completion Headlines in the current buffer are offered via
1876 completion. This is the interface also used by
1877 the refile command."
1878 :group 'org-refile
1879 :type '(choice
1880 (const :tag "Outline" outline)
1881 (const :tag "Outline-path-completion" outline-path-completion)))
1882
1883 (defcustom org-goto-max-level 5
1884 "Maximum target level when running `org-goto' with refile interface."
1885 :group 'org-refile
1886 :type 'integer)
1887
1888 (defcustom org-reverse-note-order nil
1889 "Non-nil means store new notes at the beginning of a file or entry.
1890 When nil, new notes will be filed to the end of a file or entry.
1891 This can also be a list with cons cells of regular expressions that
1892 are matched against file names, and values."
1893 :group 'org-remember
1894 :group 'org-refile
1895 :type '(choice
1896 (const :tag "Reverse always" t)
1897 (const :tag "Reverse never" nil)
1898 (repeat :tag "By file name regexp"
1899 (cons regexp boolean))))
1900
1901 (defcustom org-log-refile nil
1902 "Information to record when a task is refiled.
1903
1904 Possible values are:
1905
1906 nil Don't add anything
1907 time Add a time stamp to the task
1908 note Prompt for a note and add it with template `org-log-note-headings'
1909
1910 This option can also be set with on a per-file-basis with
1911
1912 #+STARTUP: nologrefile
1913 #+STARTUP: logrefile
1914 #+STARTUP: lognoterefile
1915
1916 You can have local logging settings for a subtree by setting the LOGGING
1917 property to one or more of these keywords.
1918
1919 When bulk-refiling from the agenda, the value `note' is forbidden and
1920 will temporarily be changed to `time'."
1921 :group 'org-refile
1922 :group 'org-progress
1923 :version "24.1"
1924 :type '(choice
1925 (const :tag "No logging" nil)
1926 (const :tag "Record timestamp" time)
1927 (const :tag "Record timestamp with note." note)))
1928
1929 (defcustom org-refile-targets nil
1930 "Targets for refiling entries with \\[org-refile].
1931 This is a list of cons cells. Each cell contains:
1932 - a specification of the files to be considered, either a list of files,
1933 or a symbol whose function or variable value will be used to retrieve
1934 a file name or a list of file names. If you use `org-agenda-files' for
1935 that, all agenda files will be scanned for targets. Nil means consider
1936 headings in the current buffer.
1937 - A specification of how to find candidate refile targets. This may be
1938 any of:
1939 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1940 This tag has to be present in all target headlines, inheritance will
1941 not be considered.
1942 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1943 todo keyword.
1944 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1945 headlines that are refiling targets.
1946 - a cons cell (:level . N). Any headline of level N is considered a target.
1947 Note that, when `org-odd-levels-only' is set, level corresponds to
1948 order in hierarchy, not to the number of stars.
1949 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1950 Note that, when `org-odd-levels-only' is set, level corresponds to
1951 order in hierarchy, not to the number of stars.
1952
1953 Each element of this list generates a set of possible targets.
1954 The union of these sets is presented (with completion) to
1955 the user by `org-refile'.
1956
1957 You can set the variable `org-refile-target-verify-function' to a function
1958 to verify each headline found by the simple criteria above.
1959
1960 When this variable is nil, all top-level headlines in the current buffer
1961 are used, equivalent to the value `((nil . (:level . 1))'."
1962 :group 'org-refile
1963 :type '(repeat
1964 (cons
1965 (choice :value org-agenda-files
1966 (const :tag "All agenda files" org-agenda-files)
1967 (const :tag "Current buffer" nil)
1968 (function) (variable) (file))
1969 (choice :tag "Identify target headline by"
1970 (cons :tag "Specific tag" (const :value :tag) (string))
1971 (cons :tag "TODO keyword" (const :value :todo) (string))
1972 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1973 (cons :tag "Level number" (const :value :level) (integer))
1974 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1975
1976 (defcustom org-refile-target-verify-function nil
1977 "Function to verify if the headline at point should be a refile target.
1978 The function will be called without arguments, with point at the
1979 beginning of the headline. It should return t and leave point
1980 where it is if the headline is a valid target for refiling.
1981
1982 If the target should not be selected, the function must return nil.
1983 In addition to this, it may move point to a place from where the search
1984 should be continued. For example, the function may decide that the entire
1985 subtree of the current entry should be excluded and move point to the end
1986 of the subtree."
1987 :group 'org-refile
1988 :type 'function)
1989
1990 (defcustom org-refile-use-cache nil
1991 "Non-nil means cache refile targets to speed up the process.
1992 The cache for a particular file will be updated automatically when
1993 the buffer has been killed, or when any of the marker used for flagging
1994 refile targets no longer points at a live buffer.
1995 If you have added new entries to a buffer that might themselves be targets,
1996 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1997 find that easier, `C-u C-u C-u C-c C-w'."
1998 :group 'org-refile
1999 :version "24.1"
2000 :type 'boolean)
2001
2002 (defcustom org-refile-use-outline-path nil
2003 "Non-nil means provide refile targets as paths.
2004 So a level 3 headline will be available as level1/level2/level3.
2005
2006 When the value is `file', also include the file name (without directory)
2007 into the path. In this case, you can also stop the completion after
2008 the file name, to get entries inserted as top level in the file.
2009
2010 When `full-file-path', include the full file path."
2011 :group 'org-refile
2012 :type '(choice
2013 (const :tag "Not" nil)
2014 (const :tag "Yes" t)
2015 (const :tag "Start with file name" file)
2016 (const :tag "Start with full file path" full-file-path)))
2017
2018 (defcustom org-outline-path-complete-in-steps t
2019 "Non-nil means complete the outline path in hierarchical steps.
2020 When Org-mode uses the refile interface to select an outline path
2021 \(see variable `org-refile-use-outline-path'), the completion of
2022 the path can be done is a single go, or if can be done in steps down
2023 the headline hierarchy. Going in steps is probably the best if you
2024 do not use a special completion package like `ido' or `icicles'.
2025 However, when using these packages, going in one step can be very
2026 fast, while still showing the whole path to the entry."
2027 :group 'org-refile
2028 :type 'boolean)
2029
2030 (defcustom org-refile-allow-creating-parent-nodes nil
2031 "Non-nil means allow to create new nodes as refile targets.
2032 New nodes are then created by adding \"/new node name\" to the completion
2033 of an existing node. When the value of this variable is `confirm',
2034 new node creation must be confirmed by the user (recommended)
2035 When nil, the completion must match an existing entry.
2036
2037 Note that, if the new heading is not seen by the criteria
2038 listed in `org-refile-targets', multiple instances of the same
2039 heading would be created by trying again to file under the new
2040 heading."
2041 :group 'org-refile
2042 :type '(choice
2043 (const :tag "Never" nil)
2044 (const :tag "Always" t)
2045 (const :tag "Prompt for confirmation" confirm)))
2046
2047 (defcustom org-refile-active-region-within-subtree nil
2048 "Non-nil means also refile active region within a subtree.
2049
2050 By default `org-refile' doesn't allow refiling regions if they
2051 don't contain a set of subtrees, but it might be convenient to
2052 do so sometimes: in that case, the first line of the region is
2053 converted to a headline before refiling."
2054 :group 'org-refile
2055 :version "24.1"
2056 :type 'boolean)
2057
2058 (defgroup org-todo nil
2059 "Options concerning TODO items in Org-mode."
2060 :tag "Org TODO"
2061 :group 'org)
2062
2063 (defgroup org-progress nil
2064 "Options concerning Progress logging in Org-mode."
2065 :tag "Org Progress"
2066 :group 'org-time)
2067
2068 (defvar org-todo-interpretation-widgets
2069 '((:tag "Sequence (cycling hits every state)" sequence)
2070 (:tag "Type (cycling directly to DONE)" type))
2071 "The available interpretation symbols for customizing `org-todo-keywords'.
2072 Interested libraries should add to this list.")
2073
2074 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2075 "List of TODO entry keyword sequences and their interpretation.
2076 \\<org-mode-map>This is a list of sequences.
2077
2078 Each sequence starts with a symbol, either `sequence' or `type',
2079 indicating if the keywords should be interpreted as a sequence of
2080 action steps, or as different types of TODO items. The first
2081 keywords are states requiring action - these states will select a headline
2082 for inclusion into the global TODO list Org-mode produces. If one of
2083 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2084 signify that no further action is necessary. If \"|\" is not found,
2085 the last keyword is treated as the only DONE state of the sequence.
2086
2087 The command \\[org-todo] cycles an entry through these states, and one
2088 additional state where no keyword is present. For details about this
2089 cycling, see the manual.
2090
2091 TODO keywords and interpretation can also be set on a per-file basis with
2092 the special #+SEQ_TODO and #+TYP_TODO lines.
2093
2094 Each keyword can optionally specify a character for fast state selection
2095 \(in combination with the variable `org-use-fast-todo-selection')
2096 and specifiers for state change logging, using the same syntax
2097 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2098 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2099 indicates to record a time stamp each time this state is selected.
2100
2101 Each keyword may also specify if a timestamp or a note should be
2102 recorded when entering or leaving the state, by adding additional
2103 characters in the parenthesis after the keyword. This looks like this:
2104 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2105 record only the time of the state change. With X and Y being either
2106 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2107 Y when leaving the state if and only if the *target* state does not
2108 define X. You may omit any of the fast-selection key or X or /Y,
2109 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2110
2111 For backward compatibility, this variable may also be just a list
2112 of keywords - in this case the interpretation (sequence or type) will be
2113 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2114 :group 'org-todo
2115 :group 'org-keywords
2116 :type '(choice
2117 (repeat :tag "Old syntax, just keywords"
2118 (string :tag "Keyword"))
2119 (repeat :tag "New syntax"
2120 (cons
2121 (choice
2122 :tag "Interpretation"
2123 ;;Quick and dirty way to see
2124 ;;`org-todo-interpretations'. This takes the
2125 ;;place of item arguments
2126 :convert-widget
2127 (lambda (widget)
2128 (widget-put widget
2129 :args (mapcar
2130 #'(lambda (x)
2131 (widget-convert
2132 (cons 'const x)))
2133 org-todo-interpretation-widgets))
2134 widget))
2135 (repeat
2136 (string :tag "Keyword"))))))
2137
2138 (defvar org-todo-keywords-1 nil
2139 "All TODO and DONE keywords active in a buffer.")
2140 (make-variable-buffer-local 'org-todo-keywords-1)
2141 (defvar org-todo-keywords-for-agenda nil)
2142 (defvar org-done-keywords-for-agenda nil)
2143 (defvar org-drawers-for-agenda nil)
2144 (defvar org-todo-keyword-alist-for-agenda nil)
2145 (defvar org-tag-alist-for-agenda nil)
2146 (defvar org-agenda-contributing-files nil)
2147 (defvar org-not-done-keywords nil)
2148 (make-variable-buffer-local 'org-not-done-keywords)
2149 (defvar org-done-keywords nil)
2150 (make-variable-buffer-local 'org-done-keywords)
2151 (defvar org-todo-heads nil)
2152 (make-variable-buffer-local 'org-todo-heads)
2153 (defvar org-todo-sets nil)
2154 (make-variable-buffer-local 'org-todo-sets)
2155 (defvar org-todo-log-states nil)
2156 (make-variable-buffer-local 'org-todo-log-states)
2157 (defvar org-todo-kwd-alist nil)
2158 (make-variable-buffer-local 'org-todo-kwd-alist)
2159 (defvar org-todo-key-alist nil)
2160 (make-variable-buffer-local 'org-todo-key-alist)
2161 (defvar org-todo-key-trigger nil)
2162 (make-variable-buffer-local 'org-todo-key-trigger)
2163
2164 (defcustom org-todo-interpretation 'sequence
2165 "Controls how TODO keywords are interpreted.
2166 This variable is in principle obsolete and is only used for
2167 backward compatibility, if the interpretation of todo keywords is
2168 not given already in `org-todo-keywords'. See that variable for
2169 more information."
2170 :group 'org-todo
2171 :group 'org-keywords
2172 :type '(choice (const sequence)
2173 (const type)))
2174
2175 (defcustom org-use-fast-todo-selection t
2176 "Non-nil means use the fast todo selection scheme with C-c C-t.
2177 This variable describes if and under what circumstances the cycling
2178 mechanism for TODO keywords will be replaced by a single-key, direct
2179 selection scheme.
2180
2181 When nil, fast selection is never used.
2182
2183 When the symbol `prefix', it will be used when `org-todo' is called with
2184 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2185 in an agenda buffer.
2186
2187 When t, fast selection is used by default. In this case, the prefix
2188 argument forces cycling instead.
2189
2190 In all cases, the special interface is only used if access keys have actually
2191 been assigned by the user, i.e. if keywords in the configuration are followed
2192 by a letter in parenthesis, like TODO(t)."
2193 :group 'org-todo
2194 :type '(choice
2195 (const :tag "Never" nil)
2196 (const :tag "By default" t)
2197 (const :tag "Only with C-u C-c C-t" prefix)))
2198
2199 (defcustom org-provide-todo-statistics t
2200 "Non-nil means update todo statistics after insert and toggle.
2201 ALL-HEADLINES means update todo statistics by including headlines
2202 with no TODO keyword as well, counting them as not done.
2203 A list of TODO keywords means the same, but skip keywords that are
2204 not in this list.
2205
2206 When this is set, todo statistics is updated in the parent of the
2207 current entry each time a todo state is changed."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Yes, only for TODO entries" t)
2211 (const :tag "Yes, including all entries" 'all-headlines)
2212 (repeat :tag "Yes, for TODOs in this list"
2213 (string :tag "TODO keyword"))
2214 (other :tag "No TODO statistics" nil)))
2215
2216 (defcustom org-hierarchical-todo-statistics t
2217 "Non-nil means TODO statistics covers just direct children.
2218 When nil, all entries in the subtree are considered.
2219 This has only an effect if `org-provide-todo-statistics' is set.
2220 To set this to nil for only a single subtree, use a COOKIE_DATA
2221 property and include the word \"recursive\" into the value."
2222 :group 'org-todo
2223 :type 'boolean)
2224
2225 (defcustom org-after-todo-state-change-hook nil
2226 "Hook which is run after the state of a TODO item was changed.
2227 The new state (a string with a TODO keyword, or nil) is available in the
2228 Lisp variable `org-state'."
2229 :group 'org-todo
2230 :type 'hook)
2231
2232 (defvar org-blocker-hook nil
2233 "Hook for functions that are allowed to block a state change.
2234
2235 Each function gets as its single argument a property list, see
2236 `org-trigger-hook' for more information about this list.
2237
2238 If any of the functions in this hook returns nil, the state change
2239 is blocked.")
2240
2241 (defvar org-trigger-hook nil
2242 "Hook for functions that are triggered by a state change.
2243
2244 Each function gets as its single argument a property list with at least
2245 the following elements:
2246
2247 (:type type-of-change :position pos-at-entry-start
2248 :from old-state :to new-state)
2249
2250 Depending on the type, more properties may be present.
2251
2252 This mechanism is currently implemented for:
2253
2254 TODO state changes
2255 ------------------
2256 :type todo-state-change
2257 :from previous state (keyword as a string), or nil, or a symbol
2258 'todo' or 'done', to indicate the general type of state.
2259 :to new state, like in :from")
2260
2261 (defcustom org-enforce-todo-dependencies nil
2262 "Non-nil means undone TODO entries will block switching the parent to DONE.
2263 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2264 be blocked if any prior sibling is not yet done.
2265 Finally, if the parent is blocked because of ordered siblings of its own,
2266 the child will also be blocked."
2267 :set (lambda (var val)
2268 (set var val)
2269 (if val
2270 (add-hook 'org-blocker-hook
2271 'org-block-todo-from-children-or-siblings-or-parent)
2272 (remove-hook 'org-blocker-hook
2273 'org-block-todo-from-children-or-siblings-or-parent)))
2274 :group 'org-todo
2275 :type 'boolean)
2276
2277 (defcustom org-enforce-todo-checkbox-dependencies nil
2278 "Non-nil means unchecked boxes will block switching the parent to DONE.
2279 When this is nil, checkboxes have no influence on switching TODO states.
2280 When non-nil, you first need to check off all check boxes before the TODO
2281 entry can be switched to DONE.
2282 This variable needs to be set before org.el is loaded, and you need to
2283 restart Emacs after a change to make the change effective. The only way
2284 to change is while Emacs is running is through the customize interface."
2285 :set (lambda (var val)
2286 (set var val)
2287 (if val
2288 (add-hook 'org-blocker-hook
2289 'org-block-todo-from-checkboxes)
2290 (remove-hook 'org-blocker-hook
2291 'org-block-todo-from-checkboxes)))
2292 :group 'org-todo
2293 :type 'boolean)
2294
2295 (defcustom org-treat-insert-todo-heading-as-state-change nil
2296 "Non-nil means inserting a TODO heading is treated as state change.
2297 So when the command \\[org-insert-todo-heading] is used, state change
2298 logging will apply if appropriate. When nil, the new TODO item will
2299 be inserted directly, and no logging will take place."
2300 :group 'org-todo
2301 :type 'boolean)
2302
2303 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2304 "Non-nil means switching TODO states with S-cursor counts as state change.
2305 This is the default behavior. However, setting this to nil allows a
2306 convenient way to select a TODO state and bypass any logging associated
2307 with that."
2308 :group 'org-todo
2309 :type 'boolean)
2310
2311 (defcustom org-todo-state-tags-triggers nil
2312 "Tag changes that should be triggered by TODO state changes.
2313 This is a list. Each entry is
2314
2315 (state-change (tag . flag) .......)
2316
2317 State-change can be a string with a state, and empty string to indicate the
2318 state that has no TODO keyword, or it can be one of the symbols `todo'
2319 or `done', meaning any not-done or done state, respectively."
2320 :group 'org-todo
2321 :group 'org-tags
2322 :type '(repeat
2323 (cons (choice :tag "When changing to"
2324 (const :tag "Not-done state" todo)
2325 (const :tag "Done state" done)
2326 (string :tag "State"))
2327 (repeat
2328 (cons :tag "Tag action"
2329 (string :tag "Tag")
2330 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2331
2332 (defcustom org-log-done nil
2333 "Information to record when a task moves to the DONE state.
2334
2335 Possible values are:
2336
2337 nil Don't add anything, just change the keyword
2338 time Add a time stamp to the task
2339 note Prompt for a note and add it with template `org-log-note-headings'
2340
2341 This option can also be set with on a per-file-basis with
2342
2343 #+STARTUP: nologdone
2344 #+STARTUP: logdone
2345 #+STARTUP: lognotedone
2346
2347 You can have local logging settings for a subtree by setting the LOGGING
2348 property to one or more of these keywords."
2349 :group 'org-todo
2350 :group 'org-progress
2351 :type '(choice
2352 (const :tag "No logging" nil)
2353 (const :tag "Record CLOSED timestamp" time)
2354 (const :tag "Record CLOSED timestamp with note." note)))
2355
2356 ;; Normalize old uses of org-log-done.
2357 (cond
2358 ((eq org-log-done t) (setq org-log-done 'time))
2359 ((and (listp org-log-done) (memq 'done org-log-done))
2360 (setq org-log-done 'note)))
2361
2362 (defcustom org-log-reschedule nil
2363 "Information to record when the scheduling date of a tasks is modified.
2364
2365 Possible values are:
2366
2367 nil Don't add anything, just change the date
2368 time Add a time stamp to the task
2369 note Prompt for a note and add it with template `org-log-note-headings'
2370
2371 This option can also be set with on a per-file-basis with
2372
2373 #+STARTUP: nologreschedule
2374 #+STARTUP: logreschedule
2375 #+STARTUP: lognotereschedule"
2376 :group 'org-todo
2377 :group 'org-progress
2378 :type '(choice
2379 (const :tag "No logging" nil)
2380 (const :tag "Record timestamp" time)
2381 (const :tag "Record timestamp with note." note)))
2382
2383 (defcustom org-log-redeadline nil
2384 "Information to record when the deadline date of a tasks is modified.
2385
2386 Possible values are:
2387
2388 nil Don't add anything, just change the date
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2391
2392 This option can also be set with on a per-file-basis with
2393
2394 #+STARTUP: nologredeadline
2395 #+STARTUP: logredeadline
2396 #+STARTUP: lognoteredeadline
2397
2398 You can have local logging settings for a subtree by setting the LOGGING
2399 property to one or more of these keywords."
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2406
2407 (defcustom org-log-note-clock-out nil
2408 "Non-nil means record a note when clocking out of an item.
2409 This can also be configured on a per-file basis by adding one of
2410 the following lines anywhere in the buffer:
2411
2412 #+STARTUP: lognoteclock-out
2413 #+STARTUP: nolognoteclock-out"
2414 :group 'org-todo
2415 :group 'org-progress
2416 :type 'boolean)
2417
2418 (defcustom org-log-done-with-time t
2419 "Non-nil means the CLOSED time stamp will contain date and time.
2420 When nil, only the date will be recorded."
2421 :group 'org-progress
2422 :type 'boolean)
2423
2424 (defcustom org-log-note-headings
2425 '((done . "CLOSING NOTE %t")
2426 (state . "State %-12s from %-12S %t")
2427 (note . "Note taken on %t")
2428 (reschedule . "Rescheduled from %S on %t")
2429 (delschedule . "Not scheduled, was %S on %t")
2430 (redeadline . "New deadline from %S on %t")
2431 (deldeadline . "Removed deadline, was %S on %t")
2432 (refile . "Refiled on %t")
2433 (clock-out . ""))
2434 "Headings for notes added to entries.
2435 The value is an alist, with the car being a symbol indicating the note
2436 context, and the cdr is the heading to be used. The heading may also be the
2437 empty string.
2438 %t in the heading will be replaced by a time stamp.
2439 %T will be an active time stamp instead the default inactive one
2440 %d will be replaced by a short-format time stamp.
2441 %D will be replaced by an active short-format time stamp.
2442 %s will be replaced by the new TODO state, in double quotes.
2443 %S will be replaced by the old TODO state, in double quotes.
2444 %u will be replaced by the user name.
2445 %U will be replaced by the full user name.
2446
2447 In fact, it is not a good idea to change the `state' entry, because
2448 agenda log mode depends on the format of these entries."
2449 :group 'org-todo
2450 :group 'org-progress
2451 :type '(list :greedy t
2452 (cons (const :tag "Heading when closing an item" done) string)
2453 (cons (const :tag
2454 "Heading when changing todo state (todo sequence only)"
2455 state) string)
2456 (cons (const :tag "Heading when just taking a note" note) string)
2457 (cons (const :tag "Heading when clocking out" clock-out) string)
2458 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2459 (cons (const :tag "Heading when rescheduling" reschedule) string)
2460 (cons (const :tag "Heading when changing deadline" redeadline) string)
2461 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2462 (cons (const :tag "Heading when refiling" refile) string)))
2463
2464 (unless (assq 'note org-log-note-headings)
2465 (push '(note . "%t") org-log-note-headings))
2466
2467 (defcustom org-log-into-drawer nil
2468 "Non-nil means insert state change notes and time stamps into a drawer.
2469 When nil, state changes notes will be inserted after the headline and
2470 any scheduling and clock lines, but not inside a drawer.
2471
2472 The value of this variable should be the name of the drawer to use.
2473 LOGBOOK is proposed as the default drawer for this purpose, you can
2474 also set this to a string to define the drawer of your choice.
2475
2476 A value of t is also allowed, representing \"LOGBOOK\".
2477
2478 If this variable is set, `org-log-state-notes-insert-after-drawers'
2479 will be ignored.
2480
2481 You can set the property LOG_INTO_DRAWER to overrule this setting for
2482 a subtree."
2483 :group 'org-todo
2484 :group 'org-progress
2485 :type '(choice
2486 (const :tag "Not into a drawer" nil)
2487 (const :tag "LOGBOOK" t)
2488 (string :tag "Other")))
2489
2490 (if (fboundp 'defvaralias)
2491 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2492
2493 (defun org-log-into-drawer ()
2494 "Return the value of `org-log-into-drawer', but let properties overrule.
2495 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2496 used instead of the default value."
2497 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2498 (cond
2499 ((or (not p) (equal p "nil")) org-log-into-drawer)
2500 ((equal p "t") "LOGBOOK")
2501 (t p))))
2502
2503 (defcustom org-log-state-notes-insert-after-drawers nil
2504 "Non-nil means insert state change notes after any drawers in entry.
2505 Only the drawers that *immediately* follow the headline and the
2506 deadline/scheduled line are skipped.
2507 When nil, insert notes right after the heading and perhaps the line
2508 with deadline/scheduling if present.
2509
2510 This variable will have no effect if `org-log-into-drawer' is
2511 set."
2512 :group 'org-todo
2513 :group 'org-progress
2514 :type 'boolean)
2515
2516 (defcustom org-log-states-order-reversed t
2517 "Non-nil means the latest state note will be directly after heading.
2518 When nil, the state change notes will be ordered according to time."
2519 :group 'org-todo
2520 :group 'org-progress
2521 :type 'boolean)
2522
2523 (defcustom org-todo-repeat-to-state nil
2524 "The TODO state to which a repeater should return the repeating task.
2525 By default this is the first task in a TODO sequence, or the previous state
2526 in a TODO_TYP set. But you can specify another task here.
2527 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2528 :group 'org-todo
2529 :version "24.1"
2530 :type '(choice (const :tag "Head of sequence" nil)
2531 (string :tag "Specific state")))
2532
2533 (defcustom org-log-repeat 'time
2534 "Non-nil means record moving through the DONE state when triggering repeat.
2535 An auto-repeating task is immediately switched back to TODO when
2536 marked DONE. If you are not logging state changes (by adding \"@\"
2537 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2538 record a closing note, there will be no record of the task moving
2539 through DONE. This variable forces taking a note anyway.
2540
2541 nil Don't force a record
2542 time Record a time stamp
2543 note Record a note
2544
2545 This option can also be set with on a per-file-basis with
2546
2547 #+STARTUP: logrepeat
2548 #+STARTUP: lognoterepeat
2549 #+STARTUP: nologrepeat
2550
2551 You can have local logging settings for a subtree by setting the LOGGING
2552 property to one or more of these keywords."
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type '(choice
2556 (const :tag "Don't force a record" nil)
2557 (const :tag "Force recording the DONE state" time)
2558 (const :tag "Force recording a note with the DONE state" note)))
2559
2560
2561 (defgroup org-priorities nil
2562 "Priorities in Org-mode."
2563 :tag "Org Priorities"
2564 :group 'org-todo)
2565
2566 (defcustom org-enable-priority-commands t
2567 "Non-nil means priority commands are active.
2568 When nil, these commands will be disabled, so that you never accidentally
2569 set a priority."
2570 :group 'org-priorities
2571 :type 'boolean)
2572
2573 (defcustom org-highest-priority ?A
2574 "The highest priority of TODO items. A character like ?A, ?B etc.
2575 Must have a smaller ASCII number than `org-lowest-priority'."
2576 :group 'org-priorities
2577 :type 'character)
2578
2579 (defcustom org-lowest-priority ?C
2580 "The lowest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a larger ASCII number than `org-highest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2584
2585 (defcustom org-default-priority ?B
2586 "The default priority of TODO items.
2587 This is the priority an item gets if no explicit priority is given.
2588 When starting to cycle on an empty priority the first step in the cycle
2589 depends on `org-priority-start-cycle-with-default'. The resulting first
2590 step priority must not exceed the range from `org-highest-priority' to
2591 `org-lowest-priority' which means that `org-default-priority' has to be
2592 in this range exclusive or inclusive the range boundaries. Else the
2593 first step refuses to set the default and the second will fall back
2594 to (depending on the command used) the highest or lowest priority."
2595 :group 'org-priorities
2596 :type 'character)
2597
2598 (defcustom org-priority-start-cycle-with-default t
2599 "Non-nil means start with default priority when starting to cycle.
2600 When this is nil, the first step in the cycle will be (depending on the
2601 command used) one higher or lower than the default priority.
2602 See also `org-default-priority'."
2603 :group 'org-priorities
2604 :type 'boolean)
2605
2606 (defcustom org-get-priority-function nil
2607 "Function to extract the priority from a string.
2608 The string is normally the headline. If this is nil Org computes the
2609 priority from the priority cookie like [#A] in the headline. It returns
2610 an integer, increasing by 1000 for each priority level.
2611 The user can set a different function here, which should take a string
2612 as an argument and return the numeric priority."
2613 :group 'org-priorities
2614 :version "24.1"
2615 :type 'function)
2616
2617 (defgroup org-time nil
2618 "Options concerning time stamps and deadlines in Org-mode."
2619 :tag "Org Time"
2620 :group 'org)
2621
2622 (defcustom org-insert-labeled-timestamps-at-point nil
2623 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2624 When nil, these labeled time stamps are forces into the second line of an
2625 entry, just after the headline. When scheduling from the global TODO list,
2626 the time stamp will always be forced into the second line."
2627 :group 'org-time
2628 :type 'boolean)
2629
2630 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2631 "Formats for `format-time-string' which are used for time stamps.
2632 It is not recommended to change this constant.")
2633
2634 (defcustom org-time-stamp-rounding-minutes '(0 5)
2635 "Number of minutes to round time stamps to.
2636 These are two values, the first applies when first creating a time stamp.
2637 The second applies when changing it with the commands `S-up' and `S-down'.
2638 When changing the time stamp, this means that it will change in steps
2639 of N minutes, as given by the second value.
2640
2641 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2642 numbers should be factors of 60, so for example 5, 10, 15.
2643
2644 When this is larger than 1, you can still force an exact time stamp by using
2645 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2646 and by using a prefix arg to `S-up/down' to specify the exact number
2647 of minutes to shift."
2648 :group 'org-time
2649 :get #'(lambda (var) ; Make sure both elements are there
2650 (if (integerp (default-value var))
2651 (list (default-value var) 5)
2652 (default-value var)))
2653 :type '(list
2654 (integer :tag "when inserting times")
2655 (integer :tag "when modifying times")))
2656
2657 ;; Normalize old customizations of this variable.
2658 (when (integerp org-time-stamp-rounding-minutes)
2659 (setq org-time-stamp-rounding-minutes
2660 (list org-time-stamp-rounding-minutes
2661 org-time-stamp-rounding-minutes)))
2662
2663 (defcustom org-display-custom-times nil
2664 "Non-nil means overlay custom formats over all time stamps.
2665 The formats are defined through the variable `org-time-stamp-custom-formats'.
2666 To turn this on on a per-file basis, insert anywhere in the file:
2667 #+STARTUP: customtime"
2668 :group 'org-time
2669 :set 'set-default
2670 :type 'sexp)
2671 (make-variable-buffer-local 'org-display-custom-times)
2672
2673 (defcustom org-time-stamp-custom-formats
2674 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2675 "Custom formats for time stamps. See `format-time-string' for the syntax.
2676 These are overlaid over the default ISO format if the variable
2677 `org-display-custom-times' is set. Time like %H:%M should be at the
2678 end of the second format. The custom formats are also honored by export
2679 commands, if custom time display is turned on at the time of export."
2680 :group 'org-time
2681 :type 'sexp)
2682
2683 (defun org-time-stamp-format (&optional long inactive)
2684 "Get the right format for a time string."
2685 (let ((f (if long (cdr org-time-stamp-formats)
2686 (car org-time-stamp-formats))))
2687 (if inactive
2688 (concat "[" (substring f 1 -1) "]")
2689 f)))
2690
2691 (defcustom org-time-clocksum-format "%d:%02d"
2692 "The format string used when creating CLOCKSUM lines.
2693 This is also used when org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2696
2697 (defcustom org-time-clocksum-use-fractional nil
2698 "If non-nil, \\[org-clock-display] uses fractional times.
2699 org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'boolean)
2702
2703 (defcustom org-time-clocksum-fractional-format "%.2f"
2704 "The format string used when creating CLOCKSUM lines, or when
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'string)
2708
2709 (defcustom org-deadline-warning-days 14
2710 "No. of days before expiration during which a deadline becomes active.
2711 This variable governs the display in sparse trees and in the agenda.
2712 When 0 or negative, it means use this number (the absolute value of it)
2713 even if a deadline has a different individual lead time specified.
2714
2715 Custom commands can set this variable in the options section."
2716 :group 'org-time
2717 :group 'org-agenda-daily/weekly
2718 :type 'integer)
2719
2720 (defcustom org-read-date-prefer-future t
2721 "Non-nil means assume future for incomplete date input from user.
2722 This affects the following situations:
2723 1. The user gives a month but not a year.
2724 For example, if it is April and you enter \"feb 2\", this will be read
2725 as Feb 2, *next* year. \"May 5\", however, will be this year.
2726 2. The user gives a day, but no month.
2727 For example, if today is the 15th, and you enter \"3\", Org-mode will
2728 read this as the third of *next* month. However, if you enter \"17\",
2729 it will be considered as *this* month.
2730
2731 If you set this variable to the symbol `time', then also the following
2732 will work:
2733
2734 3. If the user gives a time, but no day. If the time is before now,
2735 to will be interpreted as tomorrow.
2736
2737 Currently none of this works for ISO week specifications.
2738
2739 When this option is nil, the current day, month and year will always be
2740 used as defaults.
2741
2742 See also `org-agenda-jump-prefer-future'."
2743 :group 'org-time
2744 :type '(choice
2745 (const :tag "Never" nil)
2746 (const :tag "Check month and day" t)
2747 (const :tag "Check month, day, and time" time)))
2748
2749 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2750 "Should the agenda jump command prefer the future for incomplete dates?
2751 The default is to do the same as configured in `org-read-date-prefer-future'.
2752 But you can also set a deviating value here.
2753 This may t or nil, or the symbol `org-read-date-prefer-future'."
2754 :group 'org-agenda
2755 :group 'org-time
2756 :version "24.1"
2757 :type '(choice
2758 (const :tag "Use org-read-date-prefer-future"
2759 org-read-date-prefer-future)
2760 (const :tag "Never" nil)
2761 (const :tag "Always" t)))
2762
2763 (defcustom org-read-date-force-compatible-dates t
2764 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2765
2766 Depending on the system Emacs is running on, certain dates cannot
2767 be represented with the type used internally to represent time.
2768 Dates between 1970-1-1 and 2038-1-1 can always be represented
2769 correctly. Some systems allow for earlier dates, some for later,
2770 some for both. One way to find out it to insert any date into an
2771 Org buffer, putting the cursor on the year and hitting S-up and
2772 S-down to test the range.
2773
2774 When this variable is set to t, the date/time prompt will not let
2775 you specify dates outside the 1970-2037 range, so it is certain that
2776 these dates will work in whatever version of Emacs you are
2777 running, and also that you can move a file from one Emacs implementation
2778 to another. WHenever Org is forcing the year for you, it will display
2779 a message and beep.
2780
2781 When this variable is nil, Org will check if the date is
2782 representable in the specific Emacs implementation you are using.
2783 If not, it will force a year, usually the current year, and beep
2784 to remind you. Currently this setting is not recommended because
2785 the likelihood that you will open your Org files in an Emacs that
2786 has limited date range is not negligible.
2787
2788 A workaround for this problem is to use diary sexp dates for time
2789 stamps outside of this range."
2790 :group 'org-time
2791 :version "24.1"
2792 :type 'boolean)
2793
2794 (defcustom org-read-date-display-live t
2795 "Non-nil means display current interpretation of date prompt live.
2796 This display will be in an overlay, in the minibuffer."
2797 :group 'org-time
2798 :type 'boolean)
2799
2800 (defcustom org-read-date-popup-calendar t
2801 "Non-nil means pop up a calendar when prompting for a date.
2802 In the calendar, the date can be selected with mouse-1. However, the
2803 minibuffer will also be active, and you can simply enter the date as well.
2804 When nil, only the minibuffer will be available."
2805 :group 'org-time
2806 :type 'boolean)
2807 (if (fboundp 'defvaralias)
2808 (defvaralias 'org-popup-calendar-for-date-prompt
2809 'org-read-date-popup-calendar))
2810
2811 (defcustom org-read-date-minibuffer-setup-hook nil
2812 "Hook to be used to set up keys for the date/time interface.
2813 Add key definitions to `minibuffer-local-map', which will be a temporary
2814 copy."
2815 :group 'org-time
2816 :type 'hook)
2817
2818 (defcustom org-extend-today-until 0
2819 "The hour when your day really ends. Must be an integer.
2820 This has influence for the following applications:
2821 - When switching the agenda to \"today\". It it is still earlier than
2822 the time given here, the day recognized as TODAY is actually yesterday.
2823 - When a date is read from the user and it is still before the time given
2824 here, the current date and time will be assumed to be yesterday, 23:59.
2825 Also, timestamps inserted in remember templates follow this rule.
2826
2827 IMPORTANT: This is a feature whose implementation is and likely will
2828 remain incomplete. Really, it is only here because past midnight seems to
2829 be the favorite working time of John Wiegley :-)"
2830 :group 'org-time
2831 :type 'integer)
2832
2833 (defcustom org-use-effective-time nil
2834 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2835 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2836 \"effective time\" of any timestamps between midnight and 8am will be
2837 23:59 of the previous day."
2838 :group 'org-time
2839 :version "24.1"
2840 :type 'boolean)
2841
2842 (defcustom org-edit-timestamp-down-means-later nil
2843 "Non-nil means S-down will increase the time in a time stamp.
2844 When nil, S-up will increase."
2845 :group 'org-time
2846 :type 'boolean)
2847
2848 (defcustom org-calendar-follow-timestamp-change t
2849 "Non-nil means make the calendar window follow timestamp changes.
2850 When a timestamp is modified and the calendar window is visible, it will be
2851 moved to the new date."
2852 :group 'org-time
2853 :type 'boolean)
2854
2855 (defgroup org-tags nil
2856 "Options concerning tags in Org-mode."
2857 :tag "Org Tags"
2858 :group 'org)
2859
2860 (defcustom org-tag-alist nil
2861 "List of tags allowed in Org-mode files.
2862 When this list is nil, Org-mode will base TAG input on what is already in the
2863 buffer.
2864 The value of this variable is an alist, the car of each entry must be a
2865 keyword as a string, the cdr may be a character that is used to select
2866 that tag through the fast-tag-selection interface.
2867 See the manual for details."
2868 :group 'org-tags
2869 :type '(repeat
2870 (choice
2871 (cons (string :tag "Tag name")
2872 (character :tag "Access char"))
2873 (list :tag "Start radio group"
2874 (const :startgroup)
2875 (option (string :tag "Group description")))
2876 (list :tag "End radio group"
2877 (const :endgroup)
2878 (option (string :tag "Group description")))
2879 (const :tag "New line" (:newline)))))
2880
2881 (defcustom org-tag-persistent-alist nil
2882 "List of tags that will always appear in all Org-mode files.
2883 This is in addition to any in buffer settings or customizations
2884 of `org-tag-alist'.
2885 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2886 The value of this variable is an alist, the car of each entry must be a
2887 keyword as a string, the cdr may be a character that is used to select
2888 that tag through the fast-tag-selection interface.
2889 See the manual for details.
2890 To disable these tags on a per-file basis, insert anywhere in the file:
2891 #+STARTUP: noptag"
2892 :group 'org-tags
2893 :type '(repeat
2894 (choice
2895 (cons (string :tag "Tag name")
2896 (character :tag "Access char"))
2897 (const :tag "Start radio group" (:startgroup))
2898 (const :tag "End radio group" (:endgroup))
2899 (const :tag "New line" (:newline)))))
2900
2901 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2902 "If non-nil, always offer completion for all tags of all agenda files.
2903 Instead of customizing this variable directly, you might want to
2904 set it locally for capture buffers, because there no list of
2905 tags in that file can be created dynamically (there are none).
2906
2907 (add-hook 'org-capture-mode-hook
2908 (lambda ()
2909 (set (make-local-variable
2910 'org-complete-tags-always-offer-all-agenda-tags)
2911 t)))"
2912 :group 'org-tags
2913 :version "24.1"
2914 :type 'boolean)
2915
2916 (defvar org-file-tags nil
2917 "List of tags that can be inherited by all entries in the file.
2918 The tags will be inherited if the variable `org-use-tag-inheritance'
2919 says they should be.
2920 This variable is populated from #+FILETAGS lines.")
2921
2922 (defcustom org-use-fast-tag-selection 'auto
2923 "Non-nil means use fast tag selection scheme.
2924 This is a special interface to select and deselect tags with single keys.
2925 When nil, fast selection is never used.
2926 When the symbol `auto', fast selection is used if and only if selection
2927 characters for tags have been configured, either through the variable
2928 `org-tag-alist' or through a #+TAGS line in the buffer.
2929 When t, fast selection is always used and selection keys are assigned
2930 automatically if necessary."
2931 :group 'org-tags
2932 :type '(choice
2933 (const :tag "Always" t)
2934 (const :tag "Never" nil)
2935 (const :tag "When selection characters are configured" 'auto)))
2936
2937 (defcustom org-fast-tag-selection-single-key nil
2938 "Non-nil means fast tag selection exits after first change.
2939 When nil, you have to press RET to exit it.
2940 During fast tag selection, you can toggle this flag with `C-c'.
2941 This variable can also have the value `expert'. In this case, the window
2942 displaying the tags menu is not even shown, until you press C-c again."
2943 :group 'org-tags
2944 :type '(choice
2945 (const :tag "No" nil)
2946 (const :tag "Yes" t)
2947 (const :tag "Expert" expert)))
2948
2949 (defvar org-fast-tag-selection-include-todo nil
2950 "Non-nil means fast tags selection interface will also offer TODO states.
2951 This is an undocumented feature, you should not rely on it.")
2952
2953 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2954 "The column to which tags should be indented in a headline.
2955 If this number is positive, it specifies the column. If it is negative,
2956 it means that the tags should be flushright to that column. For example,
2957 -80 works well for a normal 80 character screen.
2958 When 0, place tags directly after headline text, with only one space in
2959 between."
2960 :group 'org-tags
2961 :type 'integer)
2962
2963 (defcustom org-auto-align-tags t
2964 "Non-nil keeps tags aligned when modifying headlines.
2965 Some operations (i.e. demoting) change the length of a headline and
2966 therefore shift the tags around. With this option turned on, after
2967 each such operation the tags are again aligned to `org-tags-column'."
2968 :group 'org-tags
2969 :type 'boolean)
2970
2971 (defcustom org-use-tag-inheritance t
2972 "Non-nil means tags in levels apply also for sublevels.
2973 When nil, only the tags directly given in a specific line apply there.
2974 This may also be a list of tags that should be inherited, or a regexp that
2975 matches tags that should be inherited. Additional control is possible
2976 with the variable `org-tags-exclude-from-inheritance' which gives an
2977 explicit list of tags to be excluded from inheritance., even if the value of
2978 `org-use-tag-inheritance' would select it for inheritance.
2979
2980 If this option is t, a match early-on in a tree can lead to a large
2981 number of matches in the subtree when constructing the agenda or creating
2982 a sparse tree. If you only want to see the first match in a tree during
2983 a search, check out the variable `org-tags-match-list-sublevels'."
2984 :group 'org-tags
2985 :type '(choice
2986 (const :tag "Not" nil)
2987 (const :tag "Always" t)
2988 (repeat :tag "Specific tags" (string :tag "Tag"))
2989 (regexp :tag "Tags matched by regexp")))
2990
2991 (defcustom org-tags-exclude-from-inheritance nil
2992 "List of tags that should never be inherited.
2993 This is a way to exclude a few tags from inheritance. For way to do
2994 the opposite, to actively allow inheritance for selected tags,
2995 see the variable `org-use-tag-inheritance'."
2996 :group 'org-tags
2997 :type '(repeat (string :tag "Tag")))
2998
2999 (defun org-tag-inherit-p (tag)
3000 "Check if TAG is one that should be inherited."
3001 (cond
3002 ((member tag org-tags-exclude-from-inheritance) nil)
3003 ((eq org-use-tag-inheritance t) t)
3004 ((not org-use-tag-inheritance) nil)
3005 ((stringp org-use-tag-inheritance)
3006 (string-match org-use-tag-inheritance tag))
3007 ((listp org-use-tag-inheritance)
3008 (member tag org-use-tag-inheritance))
3009 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3010
3011 (defcustom org-tags-match-list-sublevels t
3012 "Non-nil means list also sublevels of headlines matching a search.
3013 This variable applies to tags/property searches, and also to stuck
3014 projects because this search is based on a tags match as well.
3015
3016 When set to the symbol `indented', sublevels are indented with
3017 leading dots.
3018
3019 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3020 the sublevels of a headline matching a tag search often also match
3021 the same search. Listing all of them can create very long lists.
3022 Setting this variable to nil causes subtrees of a match to be skipped.
3023
3024 This variable is semi-obsolete and probably should always be true. It
3025 is better to limit inheritance to certain tags using the variables
3026 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3027 :group 'org-tags
3028 :type '(choice
3029 (const :tag "No, don't list them" nil)
3030 (const :tag "Yes, do list them" t)
3031 (const :tag "List them, indented with leading dots" indented)))
3032
3033 (defcustom org-tags-sort-function nil
3034 "When set, tags are sorted using this comparison function."
3035 :group 'org-tags
3036 :type '(choice
3037 (const :tag "No sorting" nil)
3038 (const :tag "Alphabetical" string<)
3039 (const :tag "Reverse alphabetical" string>)
3040 (function :tag "Custom function" nil)))
3041
3042 (defvar org-tags-history nil
3043 "History of minibuffer reads for tags.")
3044 (defvar org-last-tags-completion-table nil
3045 "The last used completion table for tags.")
3046 (defvar org-after-tags-change-hook nil
3047 "Hook that is run after the tags in a line have changed.")
3048
3049 (defgroup org-properties nil
3050 "Options concerning properties in Org-mode."
3051 :tag "Org Properties"
3052 :group 'org)
3053
3054 (defcustom org-property-format "%-10s %s"
3055 "How property key/value pairs should be formatted by `indent-line'.
3056 When `indent-line' hits a property definition, it will format the line
3057 according to this format, mainly to make sure that the values are
3058 lined-up with respect to each other."
3059 :group 'org-properties
3060 :type 'string)
3061
3062 (defcustom org-properties-postprocess-alist nil
3063 "Alist of properties and functions to adjust inserted values.
3064 Elements of this alist must be of the form
3065
3066 ([string] [function])
3067
3068 where [string] must be a property name and [function] must be a
3069 lambda expression: this lambda expression must take one argument,
3070 the value to adjust, and return the new value as a string.
3071
3072 For example, this element will allow the property \"Remaining\"
3073 to be updated wrt the relation between the \"Effort\" property
3074 and the clock summary:
3075
3076 ((\"Remaining\" (lambda(value)
3077 (let ((clocksum (org-clock-sum-current-item))
3078 (effort (org-duration-string-to-minutes
3079 (org-entry-get (point) \"Effort\"))))
3080 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3081 :group 'org-properties
3082 :version "24.1"
3083 :type 'alist)
3084
3085 (defcustom org-use-property-inheritance nil
3086 "Non-nil means properties apply also for sublevels.
3087
3088 This setting is chiefly used during property searches. Turning it on can
3089 cause significant overhead when doing a search, which is why it is not
3090 on by default.
3091
3092 When nil, only the properties directly given in the current entry count.
3093 When t, every property is inherited. The value may also be a list of
3094 properties that should have inheritance, or a regular expression matching
3095 properties that should be inherited.
3096
3097 However, note that some special properties use inheritance under special
3098 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3099 and the properties ending in \"_ALL\" when they are used as descriptor
3100 for valid values of a property.
3101
3102 Note for programmers:
3103 When querying an entry with `org-entry-get', you can control if inheritance
3104 should be used. By default, `org-entry-get' looks only at the local
3105 properties. You can request inheritance by setting the inherit argument
3106 to t (to force inheritance) or to `selective' (to respect the setting
3107 in this variable)."
3108 :group 'org-properties
3109 :type '(choice
3110 (const :tag "Not" nil)
3111 (const :tag "Always" t)
3112 (repeat :tag "Specific properties" (string :tag "Property"))
3113 (regexp :tag "Properties matched by regexp")))
3114
3115 (defun org-property-inherit-p (property)
3116 "Check if PROPERTY is one that should be inherited."
3117 (cond
3118 ((eq org-use-property-inheritance t) t)
3119 ((not org-use-property-inheritance) nil)
3120 ((stringp org-use-property-inheritance)
3121 (string-match org-use-property-inheritance property))
3122 ((listp org-use-property-inheritance)
3123 (member property org-use-property-inheritance))
3124 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3125
3126 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3127 "The default column format, if no other format has been defined.
3128 This variable can be set on the per-file basis by inserting a line
3129
3130 #+COLUMNS: %25ITEM ....."
3131 :group 'org-properties
3132 :type 'string)
3133
3134 (defcustom org-columns-ellipses ".."
3135 "The ellipses to be used when a field in column view is truncated.
3136 When this is the empty string, as many characters as possible are shown,
3137 but then there will be no visual indication that the field has been truncated.
3138 When this is a string of length N, the last N characters of a truncated
3139 field are replaced by this string. If the column is narrower than the
3140 ellipses string, only part of the ellipses string will be shown."
3141 :group 'org-properties
3142 :type 'string)
3143
3144 (defcustom org-columns-modify-value-for-display-function nil
3145 "Function that modifies values for display in column view.
3146 For example, it can be used to cut out a certain part from a time stamp.
3147 The function must take 2 arguments:
3148
3149 column-title The title of the column (*not* the property name)
3150 value The value that should be modified.
3151
3152 The function should return the value that should be displayed,
3153 or nil if the normal value should be used."
3154 :group 'org-properties
3155 :type 'function)
3156
3157 (defcustom org-effort-property "Effort"
3158 "The property that is being used to keep track of effort estimates.
3159 Effort estimates given in this property need to have the format H:MM."
3160 :group 'org-properties
3161 :group 'org-progress
3162 :type '(string :tag "Property"))
3163
3164 (defconst org-global-properties-fixed
3165 '(("VISIBILITY_ALL" . "folded children content all")
3166 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3167 "List of property/value pairs that can be inherited by any entry.
3168
3169 These are fixed values, for the preset properties. The user variable
3170 that can be used to add to this list is `org-global-properties'.
3171
3172 The entries in this list are cons cells where the car is a property
3173 name and cdr is a string with the value. If the value represents
3174 multiple items like an \"_ALL\" property, separate the items by
3175 spaces.")
3176
3177 (defcustom org-global-properties nil
3178 "List of property/value pairs that can be inherited by any entry.
3179
3180 This list will be combined with the constant `org-global-properties-fixed'.
3181
3182 The entries in this list are cons cells where the car is a property
3183 name and cdr is a string with the value.
3184
3185 You can set buffer-local values for the same purpose in the variable
3186 `org-file-properties' this by adding lines like
3187
3188 #+PROPERTY: NAME VALUE"
3189 :group 'org-properties
3190 :type '(repeat
3191 (cons (string :tag "Property")
3192 (string :tag "Value"))))
3193
3194 (defvar org-file-properties nil
3195 "List of property/value pairs that can be inherited by any entry.
3196 Valid for the current buffer.
3197 This variable is populated from #+PROPERTY lines.")
3198 (make-variable-buffer-local 'org-file-properties)
3199
3200 (defgroup org-agenda nil
3201 "Options concerning agenda views in Org-mode."
3202 :tag "Org Agenda"
3203 :group 'org)
3204
3205 (defvar org-category nil
3206 "Variable used by org files to set a category for agenda display.
3207 Such files should use a file variable to set it, for example
3208
3209 # -*- mode: org; org-category: \"ELisp\"
3210
3211 or contain a special line
3212
3213 #+CATEGORY: ELisp
3214
3215 If the file does not specify a category, then file's base name
3216 is used instead.")
3217 (make-variable-buffer-local 'org-category)
3218 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3219
3220 (defcustom org-agenda-files nil
3221 "The files to be used for agenda display.
3222 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3223 \\[org-remove-file]. You can also use customize to edit the list.
3224
3225 If an entry is a directory, all files in that directory that are matched by
3226 `org-agenda-file-regexp' will be part of the file list.
3227
3228 If the value of the variable is not a list but a single file name, then
3229 the list of agenda files is actually stored and maintained in that file, one
3230 agenda file per line. In this file paths can be given relative to
3231 `org-directory'. Tilde expansion and environment variable substitution
3232 are also made."
3233 :group 'org-agenda
3234 :type '(choice
3235 (repeat :tag "List of files and directories" file)
3236 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3237
3238 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3239 "Regular expression to match files for `org-agenda-files'.
3240 If any element in the list in that variable contains a directory instead
3241 of a normal file, all files in that directory that are matched by this
3242 regular expression will be included."
3243 :group 'org-agenda
3244 :type 'regexp)
3245
3246 (defcustom org-agenda-text-search-extra-files nil
3247 "List of extra files to be searched by text search commands.
3248 These files will be search in addition to the agenda files by the
3249 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3250 Note that these files will only be searched for text search commands,
3251 not for the other agenda views like todo lists, tag searches or the weekly
3252 agenda. This variable is intended to list notes and possibly archive files
3253 that should also be searched by these two commands.
3254 In fact, if the first element in the list is the symbol `agenda-archives',
3255 than all archive files of all agenda files will be added to the search
3256 scope."
3257 :group 'org-agenda
3258 :type '(set :greedy t
3259 (const :tag "Agenda Archives" agenda-archives)
3260 (repeat :inline t (file))))
3261
3262 (if (fboundp 'defvaralias)
3263 (defvaralias 'org-agenda-multi-occur-extra-files
3264 'org-agenda-text-search-extra-files))
3265
3266 (defcustom org-agenda-skip-unavailable-files nil
3267 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3268 A nil value means to remove them, after a query, from the list."
3269 :group 'org-agenda
3270 :type 'boolean)
3271
3272 (defcustom org-calendar-to-agenda-key [?c]
3273 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3274 The command `org-calendar-goto-agenda' will be bound to this key. The
3275 default is the character `c' because then `c' can be used to switch back and
3276 forth between agenda and calendar."
3277 :group 'org-agenda
3278 :type 'sexp)
3279
3280 (defcustom org-calendar-agenda-action-key [?k]
3281 "The key to be installed in `calendar-mode-map' for agenda-action.
3282 The command `org-agenda-action' will be bound to this key. The
3283 default is the character `k' because we use the same key in the agenda."
3284 :group 'org-agenda
3285 :type 'sexp)
3286
3287 (defcustom org-calendar-insert-diary-entry-key [?i]
3288 "The key to be installed in `calendar-mode-map' for adding diary entries.
3289 This option is irrelevant until `org-agenda-diary-file' has been configured
3290 to point to an Org-mode file. When that is the case, the command
3291 `org-agenda-diary-entry' will be bound to the key given here, by default
3292 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3293 if you want to continue doing this, you need to change this to a different
3294 key."
3295 :group 'org-agenda
3296 :type 'sexp)
3297
3298 (defcustom org-agenda-diary-file 'diary-file
3299 "File to which to add new entries with the `i' key in agenda and calendar.
3300 When this is the symbol `diary-file', the functionality in the Emacs
3301 calendar will be used to add entries to the `diary-file'. But when this
3302 points to a file, `org-agenda-diary-entry' will be used instead."
3303 :group 'org-agenda
3304 :type '(choice
3305 (const :tag "The standard Emacs diary file" diary-file)
3306 (file :tag "Special Org file diary entries")))
3307
3308 (eval-after-load "calendar"
3309 '(progn
3310 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3311 'org-calendar-goto-agenda)
3312 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3313 'org-agenda-action)
3314 (add-hook 'calendar-mode-hook
3315 (lambda ()
3316 (unless (eq org-agenda-diary-file 'diary-file)
3317 (define-key calendar-mode-map
3318 org-calendar-insert-diary-entry-key
3319 'org-agenda-diary-entry))))))
3320
3321 (defgroup org-latex nil
3322 "Options for embedding LaTeX code into Org-mode."
3323 :tag "Org LaTeX"
3324 :group 'org)
3325
3326 (defcustom org-format-latex-options
3327 '(:foreground default :background default :scale 1.0
3328 :html-foreground "Black" :html-background "Transparent"
3329 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3330 "Options for creating images from LaTeX fragments.
3331 This is a property list with the following properties:
3332 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3333 `default' means use the foreground of the default face.
3334 :background the background color, or \"Transparent\".
3335 `default' means use the background of the default face.
3336 :scale a scaling factor for the size of the images, to get more pixels
3337 :html-foreground, :html-background, :html-scale
3338 the same numbers for HTML export.
3339 :matchers a list indicating which matchers should be used to
3340 find LaTeX fragments. Valid members of this list are:
3341 \"begin\" find environments
3342 \"$1\" find single characters surrounded by $.$
3343 \"$\" find math expressions surrounded by $...$
3344 \"$$\" find math expressions surrounded by $$....$$
3345 \"\\(\" find math expressions surrounded by \\(...\\)
3346 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3347 :group 'org-latex
3348 :type 'plist)
3349
3350 (defcustom org-format-latex-signal-error t
3351 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3352 When nil, just push out a message."
3353 :group 'org-latex
3354 :version "24.1"
3355 :type 'boolean)
3356 (defcustom org-latex-to-mathml-jar-file nil
3357 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3358 Use this to specify additional executable file say a jar file.
3359
3360 When using MathToWeb as the converter, specify the full-path to
3361 your mathtoweb.jar file."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type '(choice
3365 (const :tag "None" nil)
3366 (file :tag "JAR file" :must-match t)))
3367
3368 (defcustom org-latex-to-mathml-convert-command nil
3369 "Command to convert LaTeX fragments to MathML.
3370 Replace format-specifiers in the command as noted below and use
3371 `shell-command' to convert LaTeX to MathML.
3372 %j: Executable file in fully expanded form as specified by
3373 `org-latex-to-mathml-jar-file'.
3374 %I: Input LaTeX file in fully expanded form
3375 %o: Output MathML file
3376 This command is used by `org-create-math-formula'.
3377
3378 When using MathToWeb as the converter, set this to
3379 \"java -jar %j -unicode -force -df %o %I\"."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type '(choice
3383 (const :tag "None" nil)
3384 (string :tag "\nShell command")))
3385
3386 (defun org-format-latex-mathml-available-p ()
3387 "Return t if `org-latex-to-mathml-convert-command' is usable."
3388 (save-match-data
3389 (when (and (boundp 'org-latex-to-mathml-convert-command)
3390 org-latex-to-mathml-convert-command)
3391 (let ((executable (car (split-string
3392 org-latex-to-mathml-convert-command))))
3393 (when (executable-find executable)
3394 (if (string-match
3395 "%j" org-latex-to-mathml-convert-command)
3396 (file-readable-p org-latex-to-mathml-jar-file)
3397 t))))))
3398
3399 (defcustom org-format-latex-header "\\documentclass{article}
3400 \\usepackage[usenames]{color}
3401 \\usepackage{amsmath}
3402 \\usepackage[mathscr]{eucal}
3403 \\pagestyle{empty} % do not remove
3404 \[PACKAGES]
3405 \[DEFAULT-PACKAGES]
3406 % The settings below are copied from fullpage.sty
3407 \\setlength{\\textwidth}{\\paperwidth}
3408 \\addtolength{\\textwidth}{-3cm}
3409 \\setlength{\\oddsidemargin}{1.5cm}
3410 \\addtolength{\\oddsidemargin}{-2.54cm}
3411 \\setlength{\\evensidemargin}{\\oddsidemargin}
3412 \\setlength{\\textheight}{\\paperheight}
3413 \\addtolength{\\textheight}{-\\headheight}
3414 \\addtolength{\\textheight}{-\\headsep}
3415 \\addtolength{\\textheight}{-\\footskip}
3416 \\addtolength{\\textheight}{-3cm}
3417 \\setlength{\\topmargin}{1.5cm}
3418 \\addtolength{\\topmargin}{-2.54cm}"
3419 "The document header used for processing LaTeX fragments.
3420 It is imperative that this header make sure that no page number
3421 appears on the page. The package defined in the variables
3422 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3423 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3424 will be appended."
3425 :group 'org-latex
3426 :type 'string)
3427
3428 (defvar org-format-latex-header-extra nil)
3429
3430 (defun org-set-packages-alist (var val)
3431 "Set the packages alist and make sure it has 3 elements per entry."
3432 (set var (mapcar (lambda (x)
3433 (if (and (consp x) (= (length x) 2))
3434 (list (car x) (nth 1 x) t)
3435 x))
3436 val)))
3437
3438 (defun org-get-packages-alist (var)
3439
3440 "Get the packages alist and make sure it has 3 elements per entry."
3441 (mapcar (lambda (x)
3442 (if (and (consp x) (= (length x) 2))
3443 (list (car x) (nth 1 x) t)
3444 x))
3445 (default-value var)))
3446
3447 ;; The following variables are defined here because is it also used
3448 ;; when formatting latex fragments. Originally it was part of the
3449 ;; LaTeX exporter, which is why the name includes "export".
3450 (defcustom org-export-latex-default-packages-alist
3451 '(("AUTO" "inputenc" t)
3452 ("T1" "fontenc" t)
3453 ("" "fixltx2e" nil)
3454 ("" "graphicx" t)
3455 ("" "longtable" nil)
3456 ("" "float" nil)
3457 ("" "wrapfig" nil)
3458 ("" "soul" t)
3459 ("" "textcomp" t)
3460 ("" "marvosym" t)
3461 ("" "wasysym" t)
3462 ("" "latexsym" t)
3463 ("" "amssymb" t)
3464 ("" "hyperref" nil)
3465 "\\tolerance=1000"
3466 )
3467 "Alist of default packages to be inserted in the header.
3468 Change this only if one of the packages here causes an incompatibility
3469 with another package you are using.
3470 The packages in this list are needed by one part or another of Org-mode
3471 to function properly.
3472
3473 - inputenc, fontenc: for basic font and character selection
3474 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3475 for interpreting the entities in `org-entities'. You can skip some of these
3476 packages if you don't use any of the symbols in it.
3477 - graphicx: for including images
3478 - float, wrapfig: for figure placement
3479 - longtable: for long tables
3480 - hyperref: for cross references
3481
3482 Therefore you should not modify this variable unless you know what you
3483 are doing. The one reason to change it anyway is that you might be loading
3484 some other package that conflicts with one of the default packages.
3485 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3486 If SNIPPET-FLAG is t, the package also needs to be included when
3487 compiling LaTeX snippets into images for inclusion into HTML."
3488 :group 'org-export-latex
3489 :set 'org-set-packages-alist
3490 :get 'org-get-packages-alist
3491 :version "24.1"
3492 :type '(repeat
3493 (choice
3494 (list :tag "options/package pair"
3495 (string :tag "options")
3496 (string :tag "package")
3497 (boolean :tag "Snippet"))
3498 (string :tag "A line of LaTeX"))))
3499
3500 (defcustom org-export-latex-packages-alist nil
3501 "Alist of packages to be inserted in every LaTeX header.
3502 These will be inserted after `org-export-latex-default-packages-alist'.
3503 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3504 SNIPPET-FLAG, when t, indicates that this package is also needed when
3505 turning LaTeX snippets into images for inclusion into HTML.
3506 Make sure that you only list packages here which:
3507 - you want in every file
3508 - do not conflict with the default packages in
3509 `org-export-latex-default-packages-alist'
3510 - do not conflict with the setup in `org-format-latex-header'."
3511 :group 'org-export-latex
3512 :set 'org-set-packages-alist
3513 :get 'org-get-packages-alist
3514 :type '(repeat
3515 (choice
3516 (list :tag "options/package pair"
3517 (string :tag "options")
3518 (string :tag "package")
3519 (boolean :tag "Snippet"))
3520 (string :tag "A line of LaTeX"))))
3521
3522
3523 (defgroup org-appearance nil
3524 "Settings for Org-mode appearance."
3525 :tag "Org Appearance"
3526 :group 'org)
3527
3528 (defcustom org-level-color-stars-only nil
3529 "Non-nil means fontify only the stars in each headline.
3530 When nil, the entire headline is fontified.
3531 Changing it requires restart of `font-lock-mode' to become effective
3532 also in regions already fontified."
3533 :group 'org-appearance
3534 :type 'boolean)
3535
3536 (defcustom org-hide-leading-stars nil
3537 "Non-nil means hide the first N-1 stars in a headline.
3538 This works by using the face `org-hide' for these stars. This
3539 face is white for a light background, and black for a dark
3540 background. You may have to customize the face `org-hide' to
3541 make this work.
3542 Changing it requires restart of `font-lock-mode' to become effective
3543 also in regions already fontified.
3544 You may also set this on a per-file basis by adding one of the following
3545 lines to the buffer:
3546
3547 #+STARTUP: hidestars
3548 #+STARTUP: showstars"
3549 :group 'org-appearance
3550 :type 'boolean)
3551
3552 (defcustom org-hidden-keywords nil
3553 "List of symbols corresponding to keywords to be hidden the org buffer.
3554 For example, a value '(title) for this list will make the document's title
3555 appear in the buffer without the initial #+TITLE: keyword."
3556 :group 'org-appearance
3557 :version "24.1"
3558 :type '(set (const :tag "#+AUTHOR" author)
3559 (const :tag "#+DATE" date)
3560 (const :tag "#+EMAIL" email)
3561 (const :tag "#+TITLE" title)))
3562
3563 (defcustom org-fontify-done-headline nil
3564 "Non-nil means change the face of a headline if it is marked DONE.
3565 Normally, only the TODO/DONE keyword indicates the state of a headline.
3566 When this is non-nil, the headline after the keyword is set to the
3567 `org-headline-done' as an additional indication."
3568 :group 'org-appearance
3569 :type 'boolean)
3570
3571 (defcustom org-fontify-emphasized-text t
3572 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3573 Changing this variable requires a restart of Emacs to take effect."
3574 :group 'org-appearance
3575 :type 'boolean)
3576
3577 (defcustom org-fontify-whole-heading-line nil
3578 "Non-nil means fontify the whole line for headings.
3579 This is useful when setting a background color for the
3580 org-level-* faces."
3581 :group 'org-appearance
3582 :type 'boolean)
3583
3584 (defcustom org-highlight-latex-fragments-and-specials nil
3585 "Non-nil means fontify what is treated specially by the exporters."
3586 :group 'org-appearance
3587 :type 'boolean)
3588
3589 (defcustom org-hide-emphasis-markers nil
3590 "Non-nil mean font-lock should hide the emphasis marker characters."
3591 :group 'org-appearance
3592 :type 'boolean)
3593
3594 (defcustom org-pretty-entities nil
3595 "Non-nil means show entities as UTF8 characters.
3596 When nil, the \\name form remains in the buffer."
3597 :group 'org-appearance
3598 :version "24.1"
3599 :type 'boolean)
3600
3601 (defcustom org-pretty-entities-include-sub-superscripts t
3602 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3603 :group 'org-appearance
3604 :version "24.1"
3605 :type 'boolean)
3606
3607 (defvar org-emph-re nil
3608 "Regular expression for matching emphasis.
3609 After a match, the match groups contain these elements:
3610 0 The match of the full regular expression, including the characters
3611 before and after the proper match
3612 1 The character before the proper match, or empty at beginning of line
3613 2 The proper match, including the leading and trailing markers
3614 3 The leading marker like * or /, indicating the type of highlighting
3615 4 The text between the emphasis markers, not including the markers
3616 5 The character after the match, empty at the end of a line")
3617 (defvar org-verbatim-re nil
3618 "Regular expression for matching verbatim text.")
3619 (defvar org-emphasis-regexp-components) ; defined just below
3620 (defvar org-emphasis-alist) ; defined just below
3621 (defun org-set-emph-re (var val)
3622 "Set variable and compute the emphasis regular expression."
3623 (set var val)
3624 (when (and (boundp 'org-emphasis-alist)
3625 (boundp 'org-emphasis-regexp-components)
3626 org-emphasis-alist org-emphasis-regexp-components)
3627 (let* ((e org-emphasis-regexp-components)
3628 (pre (car e))
3629 (post (nth 1 e))
3630 (border (nth 2 e))
3631 (body (nth 3 e))
3632 (nl (nth 4 e))
3633 (body1 (concat body "*?"))
3634 (markers (mapconcat 'car org-emphasis-alist ""))
3635 (vmarkers (mapconcat
3636 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3637 org-emphasis-alist "")))
3638 ;; make sure special characters appear at the right position in the class
3639 (if (string-match "\\^" markers)
3640 (setq markers (concat (replace-match "" t t markers) "^")))
3641 (if (string-match "-" markers)
3642 (setq markers (concat (replace-match "" t t markers) "-")))
3643 (if (string-match "\\^" vmarkers)
3644 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3645 (if (string-match "-" vmarkers)
3646 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3647 (if (> nl 0)
3648 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3649 (int-to-string nl) "\\}")))
3650 ;; Make the regexp
3651 (setq org-emph-re
3652 (concat "\\([" pre "]\\|^\\)"
3653 "\\("
3654 "\\([" markers "]\\)"
3655 "\\("
3656 "[^" border "]\\|"
3657 "[^" border "]"
3658 body1
3659 "[^" border "]"
3660 "\\)"
3661 "\\3\\)"
3662 "\\([" post "]\\|$\\)"))
3663 (setq org-verbatim-re
3664 (concat "\\([" pre "]\\|^\\)"
3665 "\\("
3666 "\\([" vmarkers "]\\)"
3667 "\\("
3668 "[^" border "]\\|"
3669 "[^" border "]"
3670 body1
3671 "[^" border "]"
3672 "\\)"
3673 "\\3\\)"
3674 "\\([" post "]\\|$\\)")))))
3675
3676 (defcustom org-emphasis-regexp-components
3677 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3678 "Components used to build the regular expression for emphasis.
3679 This is a list with five entries. Terminology: In an emphasis string
3680 like \" *strong word* \", we call the initial space PREMATCH, the final
3681 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3682 and \"trong wor\" is the body. The different components in this variable
3683 specify what is allowed/forbidden in each part:
3684
3685 pre Chars allowed as prematch. Beginning of line will be allowed too.
3686 post Chars allowed as postmatch. End of line will be allowed too.
3687 border The chars *forbidden* as border characters.
3688 body-regexp A regexp like \".\" to match a body character. Don't use
3689 non-shy groups here, and don't allow newline here.
3690 newline The maximum number of newlines allowed in an emphasis exp.
3691
3692 Use customize to modify this, or restart Emacs after changing it."
3693 :group 'org-appearance
3694 :set 'org-set-emph-re
3695 :type '(list
3696 (sexp :tag "Allowed chars in pre ")
3697 (sexp :tag "Allowed chars in post ")
3698 (sexp :tag "Forbidden chars in border ")
3699 (sexp :tag "Regexp for body ")
3700 (integer :tag "number of newlines allowed")
3701 (option (boolean :tag "Please ignore this button"))))
3702
3703 (defcustom org-emphasis-alist
3704 `(("*" bold "<b>" "</b>")
3705 ("/" italic "<i>" "</i>")
3706 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3707 ("=" org-code "<code>" "</code>" verbatim)
3708 ("~" org-verbatim "<code>" "</code>" verbatim)
3709 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3710 "<del>" "</del>")
3711 )
3712 "Special syntax for emphasized text.
3713 Text starting and ending with a special character will be emphasized, for
3714 example *bold*, _underlined_ and /italic/. This variable sets the marker
3715 characters, the face to be used by font-lock for highlighting in Org-mode
3716 Emacs buffers, and the HTML tags to be used for this.
3717 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3718 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3719 Use customize to modify this, or restart Emacs after changing it."
3720 :group 'org-appearance
3721 :set 'org-set-emph-re
3722 :type '(repeat
3723 (list
3724 (string :tag "Marker character")
3725 (choice
3726 (face :tag "Font-lock-face")
3727 (plist :tag "Face property list"))
3728 (string :tag "HTML start tag")
3729 (string :tag "HTML end tag")
3730 (option (const verbatim)))))
3731
3732 (defvar org-protecting-blocks
3733 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3734 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3735 This is needed for font-lock setup.")
3736
3737 ;;; Miscellaneous options
3738
3739 (defgroup org-completion nil
3740 "Completion in Org-mode."
3741 :tag "Org Completion"
3742 :group 'org)
3743
3744 (defcustom org-completion-use-ido nil
3745 "Non-nil means use ido completion wherever possible.
3746 Note that `ido-mode' must be active for this variable to be relevant.
3747 If you decide to turn this variable on, you might well want to turn off
3748 `org-outline-path-complete-in-steps'.
3749 See also `org-completion-use-iswitchb'."
3750 :group 'org-completion
3751 :type 'boolean)
3752
3753 (defcustom org-completion-use-iswitchb nil
3754 "Non-nil means use iswitchb completion wherever possible.
3755 Note that `iswitchb-mode' must be active for this variable to be relevant.
3756 If you decide to turn this variable on, you might well want to turn off
3757 `org-outline-path-complete-in-steps'.
3758 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3759 :group 'org-completion
3760 :type 'boolean)
3761
3762 (defcustom org-completion-fallback-command 'hippie-expand
3763 "The expansion command called by \\[pcomplete] in normal context.
3764 Normal means, no org-mode-specific context."
3765 :group 'org-completion
3766 :type 'function)
3767
3768 ;;; Functions and variables from their packages
3769 ;; Declared here to avoid compiler warnings
3770
3771 ;; XEmacs only
3772 (defvar outline-mode-menu-heading)
3773 (defvar outline-mode-menu-show)
3774 (defvar outline-mode-menu-hide)
3775 (defvar zmacs-regions) ; XEmacs regions
3776
3777 ;; Emacs only
3778 (defvar mark-active)
3779
3780 ;; Various packages
3781 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3782 (declare-function calendar-forward-day "cal-move" (arg))
3783 (declare-function calendar-goto-date "cal-move" (date))
3784 (declare-function calendar-goto-today "cal-move" ())
3785 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3786 (defvar calc-embedded-close-formula)
3787 (defvar calc-embedded-open-formula)
3788 (declare-function cdlatex-tab "ext:cdlatex" ())
3789 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3790 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3791 (defvar font-lock-unfontify-region-function)
3792 (declare-function iswitchb-read-buffer "iswitchb"
3793 (prompt &optional default require-match start matches-set))
3794 (defvar iswitchb-temp-buflist)
3795 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3796 (defvar org-agenda-tags-todo-honor-ignore-options)
3797 (declare-function org-agenda-skip "org-agenda" ())
3798 (declare-function
3799 org-agenda-format-item "org-agenda"
3800 (extra txt &optional category tags dotime noprefix remove-re habitp))
3801 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3802 (declare-function org-agenda-change-all-lines "org-agenda"
3803 (newhead hdmarker &optional fixface just-this))
3804 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3805 (declare-function org-agenda-maybe-redo "org-agenda" ())
3806 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3807 (beg end))
3808 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3809 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3810 "org-agenda" (&optional end))
3811 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3812 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3813 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3814 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3815 (declare-function org-indent-mode "org-indent" (&optional arg))
3816 (declare-function parse-time-string "parse-time" (string))
3817 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3818 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3819 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3820 (defvar remember-data-file)
3821 (defvar texmathp-why)
3822 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3823 (declare-function table--at-cell-p "table" (position &optional object at-column))
3824
3825 (defvar w3m-current-url)
3826 (defvar w3m-current-title)
3827
3828 (defvar org-latex-regexps)
3829
3830 ;;; Autoload and prepare some org modules
3831
3832 ;; Some table stuff that needs to be defined here, because it is used
3833 ;; by the functions setting up org-mode or checking for table context.
3834
3835 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3836 "Detect an org-type or table-type table.")
3837 (defconst org-table-line-regexp "^[ \t]*|"
3838 "Detect an org-type table line.")
3839 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3840 "Detect an org-type table line.")
3841 (defconst org-table-hline-regexp "^[ \t]*|-"
3842 "Detect an org-type table hline.")
3843 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3844 "Detect a table-type table hline.")
3845 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3846 "Detect the first line outside a table when searching from within it.
3847 This works for both table types.")
3848
3849 ;; Autoload the functions in org-table.el that are needed by functions here.
3850
3851 (eval-and-compile
3852 (org-autoload "org-table"
3853 '(org-table-align org-table-begin org-table-blank-field
3854 org-table-convert org-table-convert-region org-table-copy-down
3855 org-table-copy-region org-table-create
3856 org-table-create-or-convert-from-region
3857 org-table-create-with-table.el org-table-current-dline
3858 org-table-cut-region org-table-delete-column org-table-edit-field
3859 org-table-edit-formulas org-table-end org-table-eval-formula
3860 org-table-export org-table-field-info
3861 org-table-get-stored-formulas org-table-goto-column
3862 org-table-hline-and-move org-table-import org-table-insert-column
3863 org-table-insert-hline org-table-insert-row org-table-iterate
3864 org-table-justify-field-maybe org-table-kill-row
3865 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3866 org-table-move-column org-table-move-column-left
3867 org-table-move-column-right org-table-move-row
3868 org-table-move-row-down org-table-move-row-up
3869 org-table-next-field org-table-next-row org-table-paste-rectangle
3870 org-table-previous-field org-table-recalculate
3871 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3872 org-table-toggle-coordinate-overlays
3873 org-table-toggle-formula-debugger org-table-wrap-region
3874 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3875 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3876 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3877
3878 (defun org-at-table-p (&optional table-type)
3879 "Return t if the cursor is inside an org-type table.
3880 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3881 (if org-enable-table-editor
3882 (save-excursion
3883 (beginning-of-line 1)
3884 (looking-at (if table-type org-table-any-line-regexp
3885 org-table-line-regexp)))
3886 nil))
3887 (defsubst org-table-p () (org-at-table-p))
3888
3889 (defun org-at-table.el-p ()
3890 "Return t if and only if we are at a table.el table."
3891 (and (org-at-table-p 'any)
3892 (save-excursion
3893 (goto-char (org-table-begin 'any))
3894 (looking-at org-table1-hline-regexp))))
3895 (defun org-table-recognize-table.el ()
3896 "If there is a table.el table nearby, recognize it and move into it."
3897 (if org-table-tab-recognizes-table.el
3898 (if (org-at-table.el-p)
3899 (progn
3900 (beginning-of-line 1)
3901 (if (looking-at org-table-dataline-regexp)
3902 nil
3903 (if (looking-at org-table1-hline-regexp)
3904 (progn
3905 (beginning-of-line 2)
3906 (if (looking-at org-table-any-border-regexp)
3907 (beginning-of-line -1)))))
3908 (if (re-search-forward "|" (org-table-end t) t)
3909 (progn
3910 (require 'table)
3911 (if (table--at-cell-p (point))
3912 t
3913 (message "recognizing table.el table...")
3914 (table-recognize-table)
3915 (message "recognizing table.el table...done")))
3916 (error "This should not happen"))
3917 t)
3918 nil)
3919 nil))
3920
3921 (defun org-at-table-hline-p ()
3922 "Return t if the cursor is inside a hline in a table."
3923 (if org-enable-table-editor
3924 (save-excursion
3925 (beginning-of-line 1)
3926 (looking-at org-table-hline-regexp))
3927 nil))
3928
3929 (defvar org-table-clean-did-remove-column nil)
3930
3931 (defun org-table-map-tables (function &optional quietly)
3932 "Apply FUNCTION to the start of all tables in the buffer."
3933 (save-excursion
3934 (save-restriction
3935 (widen)
3936 (goto-char (point-min))
3937 (while (re-search-forward org-table-any-line-regexp nil t)
3938 (unless quietly
3939 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3940 (beginning-of-line 1)
3941 (when (looking-at org-table-line-regexp)
3942 (save-excursion (funcall function))
3943 (or (looking-at org-table-line-regexp)
3944 (forward-char 1)))
3945 (re-search-forward org-table-any-border-regexp nil 1))))
3946 (unless quietly (message "Mapping tables: done")))
3947
3948 ;; Declare and autoload functions from org-exp.el & Co
3949
3950 (declare-function org-default-export-plist "org-exp")
3951 (declare-function org-infile-export-plist "org-exp")
3952 (declare-function org-get-current-options "org-exp")
3953 (eval-and-compile
3954 (org-autoload "org-exp"
3955 '(org-export org-export-visible
3956 org-insert-export-options-template
3957 org-table-clean-before-export))
3958 (org-autoload "org-ascii"
3959 '(org-export-as-ascii org-export-ascii-preprocess
3960 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3961 org-export-region-as-ascii))
3962 (org-autoload "org-latex"
3963 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3964 org-replace-region-by-latex org-export-region-as-latex
3965 org-export-as-latex org-export-as-pdf
3966 org-export-as-pdf-and-open))
3967 (org-autoload "org-html"
3968 '(org-export-as-html-and-open
3969 org-export-as-html-batch org-export-as-html-to-buffer
3970 org-replace-region-by-html org-export-region-as-html
3971 org-export-as-html))
3972 (org-autoload "org-docbook"
3973 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3974 org-replace-region-by-docbook org-export-region-as-docbook
3975 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3976 org-export-as-docbook))
3977 (org-autoload "org-icalendar"
3978 '(org-export-icalendar-this-file
3979 org-export-icalendar-all-agenda-files
3980 org-export-icalendar-combine-agenda-files))
3981 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3982 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3983
3984 ;; Declare and autoload functions from org-agenda.el
3985
3986 (eval-and-compile
3987 (org-autoload "org-agenda"
3988 '(org-agenda org-agenda-list org-search-view
3989 org-todo-list org-tags-view org-agenda-list-stuck-projects
3990 org-diary org-agenda-to-appt
3991 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3992
3993 ;; Autoload org-remember
3994
3995 (eval-and-compile
3996 (org-autoload "org-remember"
3997 '(org-remember-insinuate org-remember-annotation
3998 org-remember-apply-template org-remember org-remember-handler)))
3999
4000 (eval-and-compile
4001 (org-autoload "org-capture"
4002 '(org-capture org-capture-insert-template-here
4003 org-capture-import-remember-templates)))
4004
4005 ;; Autoload org-clock.el
4006
4007 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4008 (beg end))
4009 (declare-function org-clock-update-mode-line "org-clock" ())
4010 (declare-function org-resolve-clocks "org-clock"
4011 (&optional also-non-dangling-p prompt last-valid))
4012 (defvar org-clock-start-time)
4013 (defvar org-clock-marker (make-marker)
4014 "Marker recording the last clock-in.")
4015 (defvar org-clock-hd-marker (make-marker)
4016 "Marker recording the last clock-in, but the headline position.")
4017 (defvar org-clock-heading ""
4018 "The heading of the current clock entry.")
4019 (defun org-clock-is-active ()
4020 "Return non-nil if clock is currently running.
4021 The return value is actually the clock marker."
4022 (marker-buffer org-clock-marker))
4023
4024 (eval-and-compile
4025 (org-autoload
4026 "org-clock"
4027 '(org-clock-in org-clock-out org-clock-cancel
4028 org-clock-goto org-clock-sum org-clock-display
4029 org-clock-remove-overlays org-clock-report
4030 org-clocktable-shift org-dblock-write:clocktable
4031 org-get-clocktable org-resolve-clocks)))
4032
4033 (defun org-clock-update-time-maybe ()
4034 "If this is a CLOCK line, update it and return t.
4035 Otherwise, return nil."
4036 (interactive)
4037 (save-excursion
4038 (beginning-of-line 1)
4039 (skip-chars-forward " \t")
4040 (when (looking-at org-clock-string)
4041 (let ((re (concat "[ \t]*" org-clock-string
4042 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4043 "\\([ \t]*=>.*\\)?\\)?"))
4044 ts te h m s neg)
4045 (cond
4046 ((not (looking-at re))
4047 nil)
4048 ((not (match-end 2))
4049 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4050 (> org-clock-marker (point))
4051 (<= org-clock-marker (point-at-eol)))
4052 ;; The clock is running here
4053 (setq org-clock-start-time
4054 (apply 'encode-time
4055 (org-parse-time-string (match-string 1))))
4056 (org-clock-update-mode-line)))
4057 (t
4058 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4059 (end-of-line 1)
4060 (setq ts (match-string 1)
4061 te (match-string 3))
4062 (setq s (- (org-float-time
4063 (apply 'encode-time (org-parse-time-string te)))
4064 (org-float-time
4065 (apply 'encode-time (org-parse-time-string ts))))
4066 neg (< s 0)
4067 s (abs s)
4068 h (floor (/ s 3600))
4069 s (- s (* 3600 h))
4070 m (floor (/ s 60))
4071 s (- s (* 60 s)))
4072 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4073 t))))))
4074
4075 (defun org-check-running-clock ()
4076 "Check if the current buffer contains the running clock.
4077 If yes, offer to stop it and to save the buffer with the changes."
4078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4079 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4080 (buffer-name))))
4081 (org-clock-out)
4082 (when (y-or-n-p "Save changed buffer?")
4083 (save-buffer))))
4084
4085 (defun org-clocktable-try-shift (dir n)
4086 "Check if this line starts a clock table, if yes, shift the time block."
4087 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4088 (org-clocktable-shift dir n)))
4089
4090 ;; Autoload org-timer.el
4091
4092 (eval-and-compile
4093 (org-autoload
4094 "org-timer"
4095 '(org-timer-start org-timer org-timer-item
4096 org-timer-change-times-in-region
4097 org-timer-set-timer
4098 org-timer-reset-timers
4099 org-timer-show-remaining-time)))
4100
4101 ;; Autoload org-feed.el
4102
4103 (eval-and-compile
4104 (org-autoload
4105 "org-feed"
4106 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4107
4108
4109 ;; Autoload org-indent.el
4110
4111 ;; Define the variable already here, to make sure we have it.
4112 (defvar org-indent-mode nil
4113 "Non-nil if Org-Indent mode is enabled.
4114 Use the command `org-indent-mode' to change this variable.")
4115
4116 (eval-and-compile
4117 (org-autoload
4118 "org-indent"
4119 '(org-indent-mode)))
4120
4121 ;; Autoload org-mobile.el
4122
4123 (eval-and-compile
4124 (org-autoload
4125 "org-mobile"
4126 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4127
4128 ;; Autoload archiving code
4129 ;; The stuff that is needed for cycling and tags has to be defined here.
4130
4131 (defgroup org-archive nil
4132 "Options concerning archiving in Org-mode."
4133 :tag "Org Archive"
4134 :group 'org-structure)
4135
4136 (defcustom org-archive-location "%s_archive::"
4137 "The location where subtrees should be archived.
4138
4139 The value of this variable is a string, consisting of two parts,
4140 separated by a double-colon. The first part is a filename and
4141 the second part is a headline.
4142
4143 When the filename is omitted, archiving happens in the same file.
4144 %s in the filename will be replaced by the current file
4145 name (without the directory part). Archiving to a different file
4146 is useful to keep archived entries from contributing to the
4147 Org-mode Agenda.
4148
4149 The archived entries will be filed as subtrees of the specified
4150 headline. When the headline is omitted, the subtrees are simply
4151 filed away at the end of the file, as top-level entries. Also in
4152 the heading you can use %s to represent the file name, this can be
4153 useful when using the same archive for a number of different files.
4154
4155 Here are a few examples:
4156 \"%s_archive::\"
4157 If the current file is Projects.org, archive in file
4158 Projects.org_archive, as top-level trees. This is the default.
4159
4160 \"::* Archived Tasks\"
4161 Archive in the current file, under the top-level headline
4162 \"* Archived Tasks\".
4163
4164 \"~/org/archive.org::\"
4165 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4166
4167 \"~/org/archive.org::* From %s\"
4168 Archive in file ~/org/archive.org (absolute path), under headlines
4169 \"From FILENAME\" where file name is the current file name.
4170
4171 \"basement::** Finished Tasks\"
4172 Archive in file ./basement (relative path), as level 3 trees
4173 below the level 2 heading \"** Finished Tasks\".
4174
4175 You may set this option on a per-file basis by adding to the buffer a
4176 line like
4177
4178 #+ARCHIVE: basement::** Finished Tasks
4179
4180 You may also define it locally for a subtree by setting an ARCHIVE property
4181 in the entry. If such a property is found in an entry, or anywhere up
4182 the hierarchy, it will be used."
4183 :group 'org-archive
4184 :type 'string)
4185
4186 (defcustom org-archive-tag "ARCHIVE"
4187 "The tag that marks a subtree as archived.
4188 An archived subtree does not open during visibility cycling, and does
4189 not contribute to the agenda listings.
4190 After changing this, font-lock must be restarted in the relevant buffers to
4191 get the proper fontification."
4192 :group 'org-archive
4193 :group 'org-keywords
4194 :type 'string)
4195
4196 (defcustom org-agenda-skip-archived-trees t
4197 "Non-nil means the agenda will skip any items located in archived trees.
4198 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4199 variable is no longer recommended, you should leave it at the value t.
4200 Instead, use the key `v' to cycle the archives-mode in the agenda."
4201 :group 'org-archive
4202 :group 'org-agenda-skip
4203 :type 'boolean)
4204
4205 (defcustom org-columns-skip-archived-trees t
4206 "Non-nil means ignore archived trees when creating column view."
4207 :group 'org-archive
4208 :group 'org-properties
4209 :type 'boolean)
4210
4211 (defcustom org-cycle-open-archived-trees nil
4212 "Non-nil means `org-cycle' will open archived trees.
4213 An archived tree is a tree marked with the tag ARCHIVE.
4214 When nil, archived trees will stay folded. You can still open them with
4215 normal outline commands like `show-all', but not with the cycling commands."
4216 :group 'org-archive
4217 :group 'org-cycle
4218 :type 'boolean)
4219
4220 (defcustom org-sparse-tree-open-archived-trees nil
4221 "Non-nil means sparse tree construction shows matches in archived trees.
4222 When nil, matches in these trees are highlighted, but the trees are kept in
4223 collapsed state."
4224 :group 'org-archive
4225 :group 'org-sparse-trees
4226 :type 'boolean)
4227
4228 (defun org-cycle-hide-archived-subtrees (state)
4229 "Re-hide all archived subtrees after a visibility state change."
4230 (when (and (not org-cycle-open-archived-trees)
4231 (not (memq state '(overview folded))))
4232 (save-excursion
4233 (let* ((globalp (memq state '(contents all)))
4234 (beg (if globalp (point-min) (point)))
4235 (end (if globalp (point-max) (org-end-of-subtree t))))
4236 (org-hide-archived-subtrees beg end)
4237 (goto-char beg)
4238 (if (looking-at (concat ".*:" org-archive-tag ":"))
4239 (message "%s" (substitute-command-keys
4240 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4241
4242 (defun org-force-cycle-archived ()
4243 "Cycle subtree even if it is archived."
4244 (interactive)
4245 (setq this-command 'org-cycle)
4246 (let ((org-cycle-open-archived-trees t))
4247 (call-interactively 'org-cycle)))
4248
4249 (defun org-hide-archived-subtrees (beg end)
4250 "Re-hide all archived subtrees after a visibility state change."
4251 (save-excursion
4252 (let* ((re (concat ":" org-archive-tag ":")))
4253 (goto-char beg)
4254 (while (re-search-forward re end t)
4255 (when (org-at-heading-p)
4256 (org-flag-subtree t)
4257 (org-end-of-subtree t))))))
4258
4259 (defun org-flag-subtree (flag)
4260 (save-excursion
4261 (org-back-to-heading t)
4262 (outline-end-of-heading)
4263 (outline-flag-region (point)
4264 (progn (org-end-of-subtree t) (point))
4265 flag)))
4266
4267 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4268
4269 (eval-and-compile
4270 (org-autoload "org-archive"
4271 '(org-add-archive-files org-archive-subtree
4272 org-archive-to-archive-sibling org-toggle-archive-tag
4273 org-archive-subtree-default
4274 org-archive-subtree-default-with-confirmation)))
4275
4276 ;; Autoload Column View Code
4277
4278 (declare-function org-columns-number-to-string "org-colview")
4279 (declare-function org-columns-get-format-and-top-level "org-colview")
4280 (declare-function org-columns-compute "org-colview")
4281
4282 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4283 '(org-columns-number-to-string org-columns-get-format-and-top-level
4284 org-columns-compute org-agenda-columns org-columns-remove-overlays
4285 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4286
4287 ;; Autoload ID code
4288
4289 (declare-function org-id-store-link "org-id")
4290 (declare-function org-id-locations-load "org-id")
4291 (declare-function org-id-locations-save "org-id")
4292 (defvar org-id-track-globally)
4293 (org-autoload "org-id"
4294 '(org-id-get-create org-id-new org-id-copy org-id-get
4295 org-id-get-with-outline-path-completion
4296 org-id-get-with-outline-drilling org-id-store-link
4297 org-id-goto org-id-find org-id-store-link))
4298
4299 ;; Autoload Plotting Code
4300
4301 (org-autoload "org-plot"
4302 '(org-plot/gnuplot))
4303
4304 ;;; Variables for pre-computed regular expressions, all buffer local
4305
4306 (defvar org-drawer-regexp nil
4307 "Matches first line of a hidden block.")
4308 (make-variable-buffer-local 'org-drawer-regexp)
4309 (defvar org-todo-regexp nil
4310 "Matches any of the TODO state keywords.")
4311 (make-variable-buffer-local 'org-todo-regexp)
4312 (defvar org-not-done-regexp nil
4313 "Matches any of the TODO state keywords except the last one.")
4314 (make-variable-buffer-local 'org-not-done-regexp)
4315 (defvar org-not-done-heading-regexp nil
4316 "Matches a TODO headline that is not done.")
4317 (make-variable-buffer-local 'org-not-done-regexp)
4318 (defvar org-todo-line-regexp nil
4319 "Matches a headline and puts TODO state into group 2 if present.")
4320 (make-variable-buffer-local 'org-todo-line-regexp)
4321 (defvar org-complex-heading-regexp nil
4322 "Matches a headline and puts everything into groups:
4323 group 1: the stars
4324 group 2: The todo keyword, maybe
4325 group 3: Priority cookie
4326 group 4: True headline
4327 group 5: Tags")
4328 (make-variable-buffer-local 'org-complex-heading-regexp)
4329 (defvar org-complex-heading-regexp-format nil
4330 "Printf format to make regexp to match an exact headline.
4331 This regexp will match the headline of any node which has the
4332 exact headline text that is put into the format, but may have any
4333 TODO state, priority and tags.")
4334 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4335 (defvar org-todo-line-tags-regexp nil
4336 "Matches a headline and puts TODO state into group 2 if present.
4337 Also put tags into group 4 if tags are present.")
4338 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4339 (defvar org-ds-keyword-length 12
4340 "Maximum length of the Deadline and SCHEDULED keywords.")
4341 (make-variable-buffer-local 'org-ds-keyword-length)
4342 (defvar org-deadline-regexp nil
4343 "Matches the DEADLINE keyword.")
4344 (make-variable-buffer-local 'org-deadline-regexp)
4345 (defvar org-deadline-time-regexp nil
4346 "Matches the DEADLINE keyword together with a time stamp.")
4347 (make-variable-buffer-local 'org-deadline-time-regexp)
4348 (defvar org-deadline-line-regexp nil
4349 "Matches the DEADLINE keyword and the rest of the line.")
4350 (make-variable-buffer-local 'org-deadline-line-regexp)
4351 (defvar org-scheduled-regexp nil
4352 "Matches the SCHEDULED keyword.")
4353 (make-variable-buffer-local 'org-scheduled-regexp)
4354 (defvar org-scheduled-time-regexp nil
4355 "Matches the SCHEDULED keyword together with a time stamp.")
4356 (make-variable-buffer-local 'org-scheduled-time-regexp)
4357 (defvar org-closed-time-regexp nil
4358 "Matches the CLOSED keyword together with a time stamp.")
4359 (make-variable-buffer-local 'org-closed-time-regexp)
4360
4361 (defvar org-keyword-time-regexp nil
4362 "Matches any of the 4 keywords, together with the time stamp.")
4363 (make-variable-buffer-local 'org-keyword-time-regexp)
4364 (defvar org-keyword-time-not-clock-regexp nil
4365 "Matches any of the 3 keywords, together with the time stamp.")
4366 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4367 (defvar org-maybe-keyword-time-regexp nil
4368 "Matches a timestamp, possibly preceded by a keyword.")
4369 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4370 (defvar org-planning-or-clock-line-re nil
4371 "Matches a line with planning or clock info.")
4372 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4373 (defvar org-all-time-keywords nil
4374 "List of time keywords.")
4375 (make-variable-buffer-local 'org-all-time-keywords)
4376
4377 (defconst org-plain-time-of-day-regexp
4378 (concat
4379 "\\(\\<[012]?[0-9]"
4380 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4381 "\\(--?"
4382 "\\(\\<[012]?[0-9]"
4383 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4384 "\\)?")
4385 "Regular expression to match a plain time or time range.
4386 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4387 groups carry important information:
4388 0 the full match
4389 1 the first time, range or not
4390 8 the second time, if it is a range.")
4391
4392 (defconst org-plain-time-extension-regexp
4393 (concat
4394 "\\(\\<[012]?[0-9]"
4395 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4396 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4397 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4398 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4399 groups carry important information:
4400 0 the full match
4401 7 hours of duration
4402 9 minutes of duration")
4403
4404 (defconst org-stamp-time-of-day-regexp
4405 (concat
4406 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4407 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4408 "\\(--?"
4409 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4410 "Regular expression to match a timestamp time or time range.
4411 After a match, the following groups carry important information:
4412 0 the full match
4413 1 date plus weekday, for back referencing to make sure both times are on the same day
4414 2 the first time, range or not
4415 4 the second time, if it is a range.")
4416
4417 (defconst org-startup-options
4418 '(("fold" org-startup-folded t)
4419 ("overview" org-startup-folded t)
4420 ("nofold" org-startup-folded nil)
4421 ("showall" org-startup-folded nil)
4422 ("showeverything" org-startup-folded showeverything)
4423 ("content" org-startup-folded content)
4424 ("indent" org-startup-indented t)
4425 ("noindent" org-startup-indented nil)
4426 ("hidestars" org-hide-leading-stars t)
4427 ("showstars" org-hide-leading-stars nil)
4428 ("odd" org-odd-levels-only t)
4429 ("oddeven" org-odd-levels-only nil)
4430 ("align" org-startup-align-all-tables t)
4431 ("noalign" org-startup-align-all-tables nil)
4432 ("inlineimages" org-startup-with-inline-images t)
4433 ("noinlineimages" org-startup-with-inline-images nil)
4434 ("customtime" org-display-custom-times t)
4435 ("logdone" org-log-done time)
4436 ("lognotedone" org-log-done note)
4437 ("nologdone" org-log-done nil)
4438 ("lognoteclock-out" org-log-note-clock-out t)
4439 ("nolognoteclock-out" org-log-note-clock-out nil)
4440 ("logrepeat" org-log-repeat state)
4441 ("lognoterepeat" org-log-repeat note)
4442 ("nologrepeat" org-log-repeat nil)
4443 ("logreschedule" org-log-reschedule time)
4444 ("lognotereschedule" org-log-reschedule note)
4445 ("nologreschedule" org-log-reschedule nil)
4446 ("logredeadline" org-log-redeadline time)
4447 ("lognoteredeadline" org-log-redeadline note)
4448 ("nologredeadline" org-log-redeadline nil)
4449 ("logrefile" org-log-refile time)
4450 ("lognoterefile" org-log-refile note)
4451 ("nologrefile" org-log-refile nil)
4452 ("fninline" org-footnote-define-inline t)
4453 ("nofninline" org-footnote-define-inline nil)
4454 ("fnlocal" org-footnote-section nil)
4455 ("fnauto" org-footnote-auto-label t)
4456 ("fnprompt" org-footnote-auto-label nil)
4457 ("fnconfirm" org-footnote-auto-label confirm)
4458 ("fnplain" org-footnote-auto-label plain)
4459 ("fnadjust" org-footnote-auto-adjust t)
4460 ("nofnadjust" org-footnote-auto-adjust nil)
4461 ("constcgs" constants-unit-system cgs)
4462 ("constSI" constants-unit-system SI)
4463 ("noptag" org-tag-persistent-alist nil)
4464 ("hideblocks" org-hide-block-startup t)
4465 ("nohideblocks" org-hide-block-startup nil)
4466 ("beamer" org-startup-with-beamer-mode t)
4467 ("entitiespretty" org-pretty-entities t)
4468 ("entitiesplain" org-pretty-entities nil))
4469 "Variable associated with STARTUP options for org-mode.
4470 Each element is a list of three items: The startup options as written
4471 in the #+STARTUP line, the corresponding variable, and the value to
4472 set this variable to if the option is found. An optional forth element PUSH
4473 means to push this value onto the list in the variable.")
4474
4475 (defun org-update-property-plist (key val props)
4476 "Update PROPS with KEY and VAL."
4477 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4478 (key (if appending (substring key 0 (- (length key) 1)) key))
4479 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4480 (previous (cdr (assoc key props))))
4481 (if appending
4482 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4483 (cons (cons key val) remainder))))
4484
4485 (defconst org-block-regexp
4486 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4487 "Regular expression for hiding blocks.")
4488 (defconst org-heading-keyword-regexp-format
4489 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4490 "Printf format for a regexp matching an headline with some keyword.
4491 This regexp will match the headline of any node which has the
4492 exact keyword that is put into the format. The keyword isn't in
4493 any group by default, but the stars and the body are.")
4494 (defconst org-heading-keyword-maybe-regexp-format
4495 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4496 "Printf format for a regexp matching an headline, possibly with some keyword.
4497 This regexp can match any headline with the specified keyword, or
4498 without a keyword. The keyword isn't in any group by default,
4499 but the stars and the body are.")
4500
4501 (defun org-set-regexps-and-options ()
4502 "Precompute regular expressions for current buffer."
4503 (when (eq major-mode 'org-mode)
4504 (org-set-local 'org-todo-kwd-alist nil)
4505 (org-set-local 'org-todo-key-alist nil)
4506 (org-set-local 'org-todo-key-trigger nil)
4507 (org-set-local 'org-todo-keywords-1 nil)
4508 (org-set-local 'org-done-keywords nil)
4509 (org-set-local 'org-todo-heads nil)
4510 (org-set-local 'org-todo-sets nil)
4511 (org-set-local 'org-todo-log-states nil)
4512 (org-set-local 'org-file-properties nil)
4513 (org-set-local 'org-file-tags nil)
4514 (let ((re (org-make-options-regexp
4515 '("CATEGORY" "TODO" "COLUMNS"
4516 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4517 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4518 "OPTIONS")
4519 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4520 (splitre "[ \t]+")
4521 (scripts org-use-sub-superscripts)
4522 kwds kws0 kwsa key log value cat arch tags const links hw dws
4523 tail sep kws1 prio props ftags drawers beamer-p
4524 ext-setup-or-nil setup-contents (start 0))
4525 (save-excursion
4526 (save-restriction
4527 (widen)
4528 (goto-char (point-min))
4529 (while (or (and ext-setup-or-nil
4530 (string-match re ext-setup-or-nil start)
4531 (setq start (match-end 0)))
4532 (and (setq ext-setup-or-nil nil start 0)
4533 (re-search-forward re nil t)))
4534 (setq key (upcase (match-string 1 ext-setup-or-nil))
4535 value (org-match-string-no-properties 2 ext-setup-or-nil))
4536 (if (stringp value) (setq value (org-trim value)))
4537 (cond
4538 ((equal key "CATEGORY")
4539 (setq cat value))
4540 ((member key '("SEQ_TODO" "TODO"))
4541 (push (cons 'sequence (org-split-string value splitre)) kwds))
4542 ((equal key "TYP_TODO")
4543 (push (cons 'type (org-split-string value splitre)) kwds))
4544 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4545 ;; general TODO-like setup
4546 (push (cons (intern (downcase (match-string 1 key)))
4547 (org-split-string value splitre)) kwds))
4548 ((equal key "TAGS")
4549 (setq tags (append tags (if tags '("\\n") nil)
4550 (org-split-string value splitre))))
4551 ((equal key "COLUMNS")
4552 (org-set-local 'org-columns-default-format value))
4553 ((equal key "LINK")
4554 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4555 (push (cons (match-string 1 value)
4556 (org-trim (match-string 2 value)))
4557 links)))
4558 ((equal key "PRIORITIES")
4559 (setq prio (org-split-string value " +")))
4560 ((equal key "PROPERTY")
4561 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4562 (setq props (org-update-property-plist (match-string 1 value)
4563 (match-string 2 value)
4564 props))))
4565 ((equal key "FILETAGS")
4566 (when (string-match "\\S-" value)
4567 (setq ftags
4568 (append
4569 ftags
4570 (apply 'append
4571 (mapcar (lambda (x) (org-split-string x ":"))
4572 (org-split-string value)))))))
4573 ((equal key "DRAWERS")
4574 (setq drawers (org-split-string value splitre)))
4575 ((equal key "CONSTANTS")
4576 (setq const (append const (org-split-string value splitre))))
4577 ((equal key "STARTUP")
4578 (let ((opts (org-split-string value splitre))
4579 l var val)
4580 (while (setq l (pop opts))
4581 (when (setq l (assoc l org-startup-options))
4582 (setq var (nth 1 l) val (nth 2 l))
4583 (if (not (nth 3 l))
4584 (set (make-local-variable var) val)
4585 (if (not (listp (symbol-value var)))
4586 (set (make-local-variable var) nil))
4587 (set (make-local-variable var) (symbol-value var))
4588 (add-to-list var val))))))
4589 ((equal key "ARCHIVE")
4590 (setq arch value)
4591 (remove-text-properties 0 (length arch)
4592 '(face t fontified t) arch))
4593 ((equal key "LATEX_CLASS")
4594 (setq beamer-p (equal value "beamer")))
4595 ((equal key "OPTIONS")
4596 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4597 (setq scripts (read (match-string 2 value)))))
4598 ((equal key "SETUPFILE")
4599 (setq setup-contents (org-file-contents
4600 (expand-file-name
4601 (org-remove-double-quotes value))
4602 'noerror))
4603 (if (not ext-setup-or-nil)
4604 (setq ext-setup-or-nil setup-contents start 0)
4605 (setq ext-setup-or-nil
4606 (concat (substring ext-setup-or-nil 0 start)
4607 "\n" setup-contents "\n"
4608 (substring ext-setup-or-nil start)))))))
4609 ;; search for property blocks
4610 (goto-char (point-min))
4611 (while (re-search-forward org-block-regexp nil t)
4612 (when (equal "PROPERTY" (upcase (match-string 1)))
4613 (setq value (replace-regexp-in-string
4614 "[\n\r]" " " (match-string 4)))
4615 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4616 (setq props (org-update-property-plist (match-string 1 value)
4617 (match-string 2 value)
4618 props)))))))
4619 (org-set-local 'org-use-sub-superscripts scripts)
4620 (when cat
4621 (org-set-local 'org-category (intern cat))
4622 (push (cons "CATEGORY" cat) props))
4623 (when prio
4624 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4625 (setq prio (mapcar 'string-to-char prio))
4626 (org-set-local 'org-highest-priority (nth 0 prio))
4627 (org-set-local 'org-lowest-priority (nth 1 prio))
4628 (org-set-local 'org-default-priority (nth 2 prio)))
4629 (and props (org-set-local 'org-file-properties (nreverse props)))
4630 (and ftags (org-set-local 'org-file-tags
4631 (mapcar 'org-add-prop-inherited ftags)))
4632 (and drawers (org-set-local 'org-drawers drawers))
4633 (and arch (org-set-local 'org-archive-location arch))
4634 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4635 ;; Process the TODO keywords
4636 (unless kwds
4637 ;; Use the global values as if they had been given locally.
4638 (setq kwds (default-value 'org-todo-keywords))
4639 (if (stringp (car kwds))
4640 (setq kwds (list (cons org-todo-interpretation
4641 (default-value 'org-todo-keywords)))))
4642 (setq kwds (reverse kwds)))
4643 (setq kwds (nreverse kwds))
4644 (let (inter kws kw)
4645 (while (setq kws (pop kwds))
4646 (let ((kws (or
4647 (run-hook-with-args-until-success
4648 'org-todo-setup-filter-hook kws)
4649 kws)))
4650 (setq inter (pop kws) sep (member "|" kws)
4651 kws0 (delete "|" (copy-sequence kws))
4652 kwsa nil
4653 kws1 (mapcar
4654 (lambda (x)
4655 ;; 1 2
4656 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4657 (progn
4658 (setq kw (match-string 1 x)
4659 key (and (match-end 2) (match-string 2 x))
4660 log (org-extract-log-state-settings x))
4661 (push (cons kw (and key (string-to-char key))) kwsa)
4662 (and log (push log org-todo-log-states))
4663 kw)
4664 (error "Invalid TODO keyword %s" x)))
4665 kws0)
4666 kwsa (if kwsa (append '((:startgroup))
4667 (nreverse kwsa)
4668 '((:endgroup))))
4669 hw (car kws1)
4670 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4671 tail (list inter hw (car dws) (org-last dws))))
4672 (add-to-list 'org-todo-heads hw 'append)
4673 (push kws1 org-todo-sets)
4674 (setq org-done-keywords (append org-done-keywords dws nil))
4675 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4676 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4677 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4678 (setq org-todo-sets (nreverse org-todo-sets)
4679 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4680 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4681 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4682 ;; Process the constants
4683 (when const
4684 (let (e cst)
4685 (while (setq e (pop const))
4686 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4687 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4688 (setq org-table-formula-constants-local cst)))
4689
4690 ;; Process the tags.
4691 (when tags
4692 (let (e tgs)
4693 (while (setq e (pop tags))
4694 (cond
4695 ((equal e "{") (push '(:startgroup) tgs))
4696 ((equal e "}") (push '(:endgroup) tgs))
4697 ((equal e "\\n") (push '(:newline) tgs))
4698 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4699 (push (cons (match-string 1 e)
4700 (string-to-char (match-string 2 e)))
4701 tgs))
4702 (t (push (list e) tgs))))
4703 (org-set-local 'org-tag-alist nil)
4704 (while (setq e (pop tgs))
4705 (or (and (stringp (car e))
4706 (assoc (car e) org-tag-alist))
4707 (push e org-tag-alist)))))
4708
4709 ;; Compute the regular expressions and other local variables.
4710 ;; Using `org-outline-regexp-bol' would complicate them much,
4711 ;; because of the fixed white space at the end of that string.
4712 (if (not org-done-keywords)
4713 (setq org-done-keywords (and org-todo-keywords-1
4714 (list (org-last org-todo-keywords-1)))))
4715 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4716 (length org-scheduled-string)
4717 (length org-clock-string)
4718 (length org-closed-string)))
4719 org-drawer-regexp
4720 (concat "^[ \t]*:\\("
4721 (mapconcat 'regexp-quote org-drawers "\\|")
4722 "\\):[ \t]*$")
4723 org-not-done-keywords
4724 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4725 org-todo-regexp
4726 (concat "\\("
4727 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4728 "\\)")
4729 org-not-done-regexp
4730 (concat "\\("
4731 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4732 "\\)")
4733 org-not-done-heading-regexp
4734 (format org-heading-keyword-regexp-format org-not-done-regexp)
4735 org-todo-line-regexp
4736 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4737 org-complex-heading-regexp
4738 (concat "^\\(\\*+\\)"
4739 "\\(?: +" org-todo-regexp "\\)?"
4740 "\\(?: +\\(\\[#.\\]\\)\\)?"
4741 "\\(?: +\\(.*?\\)\\)?"
4742 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4743 "[ \t]*$")
4744 org-complex-heading-regexp-format
4745 (concat "^\\(\\*+\\)"
4746 "\\(?: +" org-todo-regexp "\\)?"
4747 "\\(?: +\\(\\[#.\\]\\)\\)?"
4748 "\\(?: +"
4749 ;; Stats cookies can be stuck to body.
4750 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4751 "\\(%s\\)"
4752 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4753 "\\)"
4754 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4755 "[ \t]*$")
4756 org-todo-line-tags-regexp
4757 (concat "^\\(\\*+\\)"
4758 "\\(?: +" org-todo-regexp "\\)?"
4759 "\\(?: +\\(.*?\\)\\)?"
4760 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4761 "[ \t]*$")
4762 org-deadline-regexp (concat "\\<" org-deadline-string)
4763 org-deadline-time-regexp
4764 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4765 org-deadline-line-regexp
4766 (concat "\\<\\(" org-deadline-string "\\).*")
4767 org-scheduled-regexp
4768 (concat "\\<" org-scheduled-string)
4769 org-scheduled-time-regexp
4770 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4771 org-closed-time-regexp
4772 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4773 org-keyword-time-regexp
4774 (concat "\\<\\(" org-scheduled-string
4775 "\\|" org-deadline-string
4776 "\\|" org-closed-string
4777 "\\|" org-clock-string "\\)"
4778 " *[[<]\\([^]>]+\\)[]>]")
4779 org-keyword-time-not-clock-regexp
4780 (concat "\\<\\(" org-scheduled-string
4781 "\\|" org-deadline-string
4782 "\\|" org-closed-string
4783 "\\)"
4784 " *[[<]\\([^]>]+\\)[]>]")
4785 org-maybe-keyword-time-regexp
4786 (concat "\\(\\<\\(" org-scheduled-string
4787 "\\|" org-deadline-string
4788 "\\|" org-closed-string
4789 "\\|" org-clock-string "\\)\\)?"
4790 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4791 org-planning-or-clock-line-re
4792 (concat "^[ \t]*\\("
4793 org-scheduled-string "\\|"
4794 org-deadline-string "\\|"
4795 org-closed-string "\\|"
4796 org-clock-string "\\)")
4797 org-all-time-keywords
4798 (mapcar (lambda (w) (substring w 0 -1))
4799 (list org-scheduled-string org-deadline-string
4800 org-clock-string org-closed-string))
4801 )
4802 (org-compute-latex-and-specials-regexp)
4803 (org-set-font-lock-defaults))))
4804
4805 (defun org-file-contents (file &optional noerror)
4806 "Return the contents of FILE, as a string."
4807 (if (or (not file)
4808 (not (file-readable-p file)))
4809 (if noerror
4810 (progn
4811 (message "Cannot read file \"%s\"" file)
4812 (ding) (sit-for 2)
4813 "")
4814 (error "Cannot read file \"%s\"" file))
4815 (with-temp-buffer
4816 (insert-file-contents file)
4817 (buffer-string))))
4818
4819 (defun org-extract-log-state-settings (x)
4820 "Extract the log state setting from a TODO keyword string.
4821 This will extract info from a string like \"WAIT(w@/!)\"."
4822 (let (kw key log1 log2)
4823 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4824 (setq kw (match-string 1 x)
4825 key (and (match-end 2) (match-string 2 x))
4826 log1 (and (match-end 3) (match-string 3 x))
4827 log2 (and (match-end 4) (match-string 4 x)))
4828 (and (or log1 log2)
4829 (list kw
4830 (and log1 (if (equal log1 "!") 'time 'note))
4831 (and log2 (if (equal log2 "!") 'time 'note)))))))
4832
4833 (defun org-remove-keyword-keys (list)
4834 "Remove a pair of parenthesis at the end of each string in LIST."
4835 (mapcar (lambda (x)
4836 (if (string-match "(.*)$" x)
4837 (substring x 0 (match-beginning 0))
4838 x))
4839 list))
4840
4841 (defun org-assign-fast-keys (alist)
4842 "Assign fast keys to a keyword-key alist.
4843 Respect keys that are already there."
4844 (let (new e (alt ?0))
4845 (while (setq e (pop alist))
4846 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4847 (cdr e)) ;; Key already assigned.
4848 (push e new)
4849 (let ((clist (string-to-list (downcase (car e))))
4850 (used (append new alist)))
4851 (when (= (car clist) ?@)
4852 (pop clist))
4853 (while (and clist (rassoc (car clist) used))
4854 (pop clist))
4855 (unless clist
4856 (while (rassoc alt used)
4857 (incf alt)))
4858 (push (cons (car e) (or (car clist) alt)) new))))
4859 (nreverse new)))
4860
4861 ;;; Some variables used in various places
4862
4863 (defvar org-window-configuration nil
4864 "Used in various places to store a window configuration.")
4865 (defvar org-selected-window nil
4866 "Used in various places to store a window configuration.")
4867 (defvar org-finish-function nil
4868 "Function to be called when `C-c C-c' is used.
4869 This is for getting out of special buffers like remember.")
4870
4871
4872 ;; FIXME: Occasionally check by commenting these, to make sure
4873 ;; no other functions uses these, forgetting to let-bind them.
4874 (defvar entry)
4875 (defvar org-last-state)
4876 (defvar date)
4877
4878 ;; Defined somewhere in this file, but used before definition.
4879 (defvar org-entities) ;; defined in org-entities.el
4880 (defvar org-struct-menu)
4881 (defvar org-org-menu)
4882 (defvar org-tbl-menu)
4883
4884 ;;;; Define the Org-mode
4885
4886 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4887 (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"))
4888
4889
4890 ;; We use a before-change function to check if a table might need
4891 ;; an update.
4892 (defvar org-table-may-need-update t
4893 "Indicates that a table might need an update.
4894 This variable is set by `org-before-change-function'.
4895 `org-table-align' sets it back to nil.")
4896 (defun org-before-change-function (beg end)
4897 "Every change indicates that a table might need an update."
4898 (setq org-table-may-need-update t))
4899 (defvar org-mode-map)
4900 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4901 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4902 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4903 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4904 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4905 (defvar org-table-buffer-is-an nil)
4906
4907 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4908 ;; some places -- e.g. see the macro org-with-limited-levels.
4909 ;;
4910 ;; In Org buffers, the value of `outline-regexp' is that of
4911 ;; `org-outline-regexp'. The only function still directly relying on
4912 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4913 ;; job when `orgstruct-mode' is active.
4914 (defvar org-outline-regexp "\\*+ "
4915 "Regexp to match Org headlines.")
4916 (defconst org-outline-regexp-bol "^\\*+ "
4917 "Regexp to match Org headlines.
4918 This is similar to `org-outline-regexp' but additionally makes
4919 sure that we are at the beginning of the line.")
4920
4921 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4922 "Matches an headline, putting stars and text into groups.
4923 Stars are put in group 1 and the trimmed body in group 2.")
4924
4925 (defvar buffer-face-mode-face)
4926
4927 ;;;###autoload
4928 (define-derived-mode org-mode outline-mode "Org"
4929 "Outline-based notes management and organizer, alias
4930 \"Carsten's outline-mode for keeping track of everything.\"
4931
4932 Org-mode develops organizational tasks around a NOTES file which
4933 contains information about projects as plain text. Org-mode is
4934 implemented on top of outline-mode, which is ideal to keep the content
4935 of large files well structured. It supports ToDo items, deadlines and
4936 time stamps, which magically appear in the diary listing of the Emacs
4937 calendar. Tables are easily created with a built-in table editor.
4938 Plain text URL-like links connect to websites, emails (VM), Usenet
4939 messages (Gnus), BBDB entries, and any files related to the project.
4940 For printing and sharing of notes, an Org-mode file (or a part of it)
4941 can be exported as a structured ASCII or HTML file.
4942
4943 The following commands are available:
4944
4945 \\{org-mode-map}"
4946
4947 ;; Get rid of Outline menus, they are not needed
4948 ;; Need to do this here because define-derived-mode sets up
4949 ;; the keymap so late. Still, it is a waste to call this each time
4950 ;; we switch another buffer into org-mode.
4951 (if (featurep 'xemacs)
4952 (when (boundp 'outline-mode-menu-heading)
4953 ;; Assume this is Greg's port, it uses easymenu
4954 (easy-menu-remove outline-mode-menu-heading)
4955 (easy-menu-remove outline-mode-menu-show)
4956 (easy-menu-remove outline-mode-menu-hide))
4957 (define-key org-mode-map [menu-bar headings] 'undefined)
4958 (define-key org-mode-map [menu-bar hide] 'undefined)
4959 (define-key org-mode-map [menu-bar show] 'undefined))
4960
4961 (org-load-modules-maybe)
4962 (easy-menu-add org-org-menu)
4963 (easy-menu-add org-tbl-menu)
4964 (org-install-agenda-files-menu)
4965 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4966 (add-to-invisibility-spec '(org-cwidth))
4967 (add-to-invisibility-spec '(org-hide-block . t))
4968 (when (featurep 'xemacs)
4969 (org-set-local 'line-move-ignore-invisible t))
4970 (org-set-local 'outline-regexp org-outline-regexp)
4971 (org-set-local 'outline-level 'org-outline-level)
4972 (setq bidi-paragraph-direction 'left-to-right)
4973 (when (and org-ellipsis
4974 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4975 (fboundp 'make-glyph-code))
4976 (unless org-display-table
4977 (setq org-display-table (make-display-table)))
4978 (set-display-table-slot
4979 org-display-table 4
4980 (vconcat (mapcar
4981 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4982 org-ellipsis)))
4983 (if (stringp org-ellipsis) org-ellipsis "..."))))
4984 (setq buffer-display-table org-display-table))
4985 (org-set-regexps-and-options)
4986 (when (and org-tag-faces (not org-tags-special-faces-re))
4987 ;; tag faces set outside customize.... force initialization.
4988 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4989 ;; Calc embedded
4990 (org-set-local 'calc-embedded-open-mode "# ")
4991 (modify-syntax-entry ?@ "w")
4992 (if org-startup-truncated (setq truncate-lines t))
4993 (org-set-local 'font-lock-unfontify-region-function
4994 'org-unfontify-region)
4995 ;; Activate before-change-function
4996 (org-set-local 'org-table-may-need-update t)
4997 (org-add-hook 'before-change-functions 'org-before-change-function nil
4998 'local)
4999 ;; Check for running clock before killing a buffer
5000 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5001 ;; Paragraphs and auto-filling
5002 (org-set-autofill-regexps)
5003 (setq indent-line-function 'org-indent-line-function)
5004 (org-update-radio-target-regexp)
5005 ;; Beginning/end of defun
5006 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5007 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5008 ;; Next error for sparse trees
5009 (org-set-local 'next-error-function 'org-occur-next-match)
5010 ;; Make sure dependence stuff works reliably, even for users who set it
5011 ;; too late :-(
5012 (if org-enforce-todo-dependencies
5013 (add-hook 'org-blocker-hook
5014 'org-block-todo-from-children-or-siblings-or-parent)
5015 (remove-hook 'org-blocker-hook
5016 'org-block-todo-from-children-or-siblings-or-parent))
5017 (if org-enforce-todo-checkbox-dependencies
5018 (add-hook 'org-blocker-hook
5019 'org-block-todo-from-checkboxes)
5020 (remove-hook 'org-blocker-hook
5021 'org-block-todo-from-checkboxes))
5022
5023 ;; Comment characters
5024 (org-set-local 'comment-start "#")
5025 (org-set-local 'comment-padding " ")
5026
5027 ;; Align options lines
5028 (org-set-local
5029 'align-mode-rules-list
5030 '((org-in-buffer-settings
5031 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5032 (modes . '(org-mode)))))
5033
5034 ;; Imenu
5035 (org-set-local 'imenu-create-index-function
5036 'org-imenu-get-tree)
5037
5038 ;; Make isearch reveal context
5039 (if (or (featurep 'xemacs)
5040 (not (boundp 'outline-isearch-open-invisible-function)))
5041 ;; Emacs 21 and XEmacs make use of the hook
5042 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5043 ;; Emacs 22 deals with this through a special variable
5044 (org-set-local 'outline-isearch-open-invisible-function
5045 (lambda (&rest ignore) (org-show-context 'isearch))))
5046
5047 ;; Turn on org-beamer-mode?
5048 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5049
5050 ;; Setup the pcomplete hooks
5051 (set (make-local-variable 'pcomplete-command-completion-function)
5052 'org-pcomplete-initial)
5053 (set (make-local-variable 'pcomplete-command-name-function)
5054 'org-command-at-point)
5055 (set (make-local-variable 'pcomplete-default-completion-function)
5056 'ignore)
5057 (set (make-local-variable 'pcomplete-parse-arguments-function)
5058 'org-parse-arguments)
5059 (set (make-local-variable 'pcomplete-termination-string) "")
5060 (when (>= emacs-major-version 23)
5061 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5062
5063 ;; If empty file that did not turn on org-mode automatically, make it to.
5064 (if (and org-insert-mode-line-in-empty-file
5065 (org-called-interactively-p 'any)
5066 (= (point-min) (point-max)))
5067 (insert "# -*- mode: org -*-\n\n"))
5068 (unless org-inhibit-startup
5069 (when org-startup-align-all-tables
5070 (let ((bmp (buffer-modified-p)))
5071 (org-table-map-tables 'org-table-align 'quietly)
5072 (set-buffer-modified-p bmp)))
5073 (when org-startup-with-inline-images
5074 (org-display-inline-images))
5075 (when org-startup-indented
5076 (require 'org-indent)
5077 (org-indent-mode 1))
5078 (unless org-inhibit-startup-visibility-stuff
5079 (org-set-startup-visibility))))
5080
5081 (when (fboundp 'abbrev-table-put)
5082 (abbrev-table-put org-mode-abbrev-table
5083 :parents (list text-mode-abbrev-table)))
5084
5085 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5086
5087 (defun org-current-time ()
5088 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5089 (if (> (car org-time-stamp-rounding-minutes) 1)
5090 (let ((r (car org-time-stamp-rounding-minutes))
5091 (time (decode-time)))
5092 (apply 'encode-time
5093 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5094 (nthcdr 2 time))))
5095 (current-time)))
5096
5097 (defun org-today ()
5098 "Return today date, considering `org-extend-today-until'."
5099 (time-to-days
5100 (time-subtract (current-time)
5101 (list 0 (* 3600 org-extend-today-until) 0))))
5102
5103 ;;;; Font-Lock stuff, including the activators
5104
5105 (defvar org-mouse-map (make-sparse-keymap))
5106 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5107 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5108 (when org-mouse-1-follows-link
5109 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5110 (when org-tab-follows-link
5111 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5112 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5113
5114 (require 'font-lock)
5115
5116 (defconst org-non-link-chars "]\t\n\r<>")
5117 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5118 "shell" "elisp" "doi" "message"))
5119 (defvar org-link-types-re nil
5120 "Matches a link that has a url-like prefix like \"http:\"")
5121 (defvar org-link-re-with-space nil
5122 "Matches a link with spaces, optional angular brackets around it.")
5123 (defvar org-link-re-with-space2 nil
5124 "Matches a link with spaces, optional angular brackets around it.")
5125 (defvar org-link-re-with-space3 nil
5126 "Matches a link with spaces, only for internal part in bracket links.")
5127 (defvar org-angle-link-re nil
5128 "Matches link with angular brackets, spaces are allowed.")
5129 (defvar org-plain-link-re nil
5130 "Matches plain link, without spaces.")
5131 (defvar org-bracket-link-regexp nil
5132 "Matches a link in double brackets.")
5133 (defvar org-bracket-link-analytic-regexp nil
5134 "Regular expression used to analyze links.
5135 Here is what the match groups contain after a match:
5136 1: http:
5137 2: http
5138 3: path
5139 4: [desc]
5140 5: desc")
5141 (defvar org-bracket-link-analytic-regexp++ nil
5142 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5143 (defvar org-any-link-re nil
5144 "Regular expression matching any link.")
5145
5146 (defcustom org-match-sexp-depth 3
5147 "Number of stacked braces for sub/superscript matching.
5148 This has to be set before loading org.el to be effective."
5149 :group 'org-export-translation ; ??????????????????????????/
5150 :type 'integer)
5151
5152 (defun org-create-multibrace-regexp (left right n)
5153 "Create a regular expression which will match a balanced sexp.
5154 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5155 as single character strings.
5156 The regexp returned will match the entire expression including the
5157 delimiters. It will also define a single group which contains the
5158 match except for the outermost delimiters. The maximum depth of
5159 stacked delimiters is N. Escaping delimiters is not possible."
5160 (let* ((nothing (concat "[^" left right "]*?"))
5161 (or "\\|")
5162 (re nothing)
5163 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5164 (while (> n 1)
5165 (setq n (1- n)
5166 re (concat re or next)
5167 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5168 (concat left "\\(" re "\\)" right)))
5169
5170 (defvar org-match-substring-regexp
5171 (concat
5172 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5173 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5174 "\\|"
5175 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5176 "\\|"
5177 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5178 "The regular expression matching a sub- or superscript.")
5179
5180 (defvar org-match-substring-with-braces-regexp
5181 (concat
5182 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5183 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5184 "\\)")
5185 "The regular expression matching a sub- or superscript, forcing braces.")
5186
5187 (defun org-make-link-regexps ()
5188 "Update the link regular expressions.
5189 This should be called after the variable `org-link-types' has changed."
5190 (setq org-link-types-re
5191 (concat
5192 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5193 org-link-re-with-space
5194 (concat
5195 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5196 "\\([^" org-non-link-chars " ]"
5197 "[^" org-non-link-chars "]*"
5198 "[^" org-non-link-chars " ]\\)>?")
5199 org-link-re-with-space2
5200 (concat
5201 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5202 "\\([^" org-non-link-chars " ]"
5203 "[^\t\n\r]*"
5204 "[^" org-non-link-chars " ]\\)>?")
5205 org-link-re-with-space3
5206 (concat
5207 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5208 "\\([^" org-non-link-chars " ]"
5209 "[^\t\n\r]*\\)")
5210 org-angle-link-re
5211 (concat
5212 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^" org-non-link-chars "]*"
5215 "\\)>")
5216 org-plain-link-re
5217 (concat
5218 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5220 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5221 org-bracket-link-regexp
5222 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5223 org-bracket-link-analytic-regexp
5224 (concat
5225 "\\[\\["
5226 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5227 "\\([^]]+\\)"
5228 "\\]"
5229 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5230 "\\]")
5231 org-bracket-link-analytic-regexp++
5232 (concat
5233 "\\[\\["
5234 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5235 "\\([^]]+\\)"
5236 "\\]"
5237 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5238 "\\]")
5239 org-any-link-re
5240 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5241 org-angle-link-re "\\)\\|\\("
5242 org-plain-link-re "\\)")))
5243
5244 (org-make-link-regexps)
5245
5246 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5247 "Regular expression for fast time stamp matching.")
5248 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5249 "Regular expression for fast time stamp matching.")
5250 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5251 "Regular expression matching time strings for analysis.
5252 This one does not require the space after the date, so it can be used
5253 on a string that terminates immediately after the date.")
5254 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5255 "Regular expression matching time strings for analysis.")
5256 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5257 "Regular expression matching time stamps, with groups.")
5258 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5259 "Regular expression matching time stamps (also [..]), with groups.")
5260 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5261 "Regular expression matching a time stamp range.")
5262 (defconst org-tr-regexp-both
5263 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5264 "Regular expression matching a time stamp range.")
5265 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5266 org-ts-regexp "\\)?")
5267 "Regular expression matching a time stamp or time stamp range.")
5268 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5269 org-ts-regexp-both "\\)?")
5270 "Regular expression matching a time stamp or time stamp range.
5271 The time stamps may be either active or inactive.")
5272
5273 (defvar org-emph-face nil)
5274
5275 (defun org-do-emphasis-faces (limit)
5276 "Run through the buffer and add overlays to emphasized strings."
5277 (let (rtn a)
5278 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5279 (if (not (= (char-after (match-beginning 3))
5280 (char-after (match-beginning 4))))
5281 (progn
5282 (setq rtn t)
5283 (setq a (assoc (match-string 3) org-emphasis-alist))
5284 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5285 'face
5286 (nth 1 a))
5287 (and (nth 4 a)
5288 (org-remove-flyspell-overlays-in
5289 (match-beginning 0) (match-end 0)))
5290 (add-text-properties (match-beginning 2) (match-end 2)
5291 '(font-lock-multiline t org-emphasis t))
5292 (when org-hide-emphasis-markers
5293 (add-text-properties (match-end 4) (match-beginning 5)
5294 '(invisible org-link))
5295 (add-text-properties (match-beginning 3) (match-end 3)
5296 '(invisible org-link)))))
5297 (backward-char 1))
5298 rtn))
5299
5300 (defun org-emphasize (&optional char)
5301 "Insert or change an emphasis, i.e. a font like bold or italic.
5302 If there is an active region, change that region to a new emphasis.
5303 If there is no region, just insert the marker characters and position
5304 the cursor between them.
5305 CHAR should be either the marker character, or the first character of the
5306 HTML tag associated with that emphasis. If CHAR is a space, the means
5307 to remove the emphasis of the selected region.
5308 If char is not given (for example in an interactive call) it
5309 will be prompted for."
5310 (interactive)
5311 (let ((eal org-emphasis-alist) e det
5312 (erc org-emphasis-regexp-components)
5313 (prompt "")
5314 (string "") beg end move tag c s)
5315 (if (org-region-active-p)
5316 (setq beg (region-beginning) end (region-end)
5317 string (buffer-substring beg end))
5318 (setq move t))
5319
5320 (while (setq e (pop eal))
5321 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5322 c (aref tag 0))
5323 (push (cons c (string-to-char (car e))) det)
5324 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5325 (substring tag 1)))))
5326 (setq det (nreverse det))
5327 (unless char
5328 (message "%s" (concat "Emphasis marker or tag:" prompt))
5329 (setq char (read-char-exclusive)))
5330 (setq char (or (cdr (assoc char det)) char))
5331 (if (equal char ?\ )
5332 (setq s "" move nil)
5333 (unless (assoc (char-to-string char) org-emphasis-alist)
5334 (error "No such emphasis marker: \"%c\"" char))
5335 (setq s (char-to-string char)))
5336 (while (and (> (length string) 1)
5337 (equal (substring string 0 1) (substring string -1))
5338 (assoc (substring string 0 1) org-emphasis-alist))
5339 (setq string (substring string 1 -1)))
5340 (setq string (concat s string s))
5341 (if beg (delete-region beg end))
5342 (unless (or (bolp)
5343 (string-match (concat "[" (nth 0 erc) "\n]")
5344 (char-to-string (char-before (point)))))
5345 (insert " "))
5346 (unless (or (eobp)
5347 (string-match (concat "[" (nth 1 erc) "\n]")
5348 (char-to-string (char-after (point)))))
5349 (insert " ") (backward-char 1))
5350 (insert string)
5351 (and move (backward-char 1))))
5352
5353 (defconst org-nonsticky-props
5354 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5355
5356 (defsubst org-rear-nonsticky-at (pos)
5357 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5358
5359 (defun org-activate-plain-links (limit)
5360 "Run through the buffer and add overlays to links."
5361 (catch 'exit
5362 (let (f)
5363 (if (re-search-forward org-plain-link-re limit t)
5364 (progn
5365 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5366 (setq f (get-text-property (match-beginning 0) 'face))
5367 (if (or (eq f 'org-tag)
5368 (and (listp f) (memq 'org-tag f)))
5369 nil
5370 (add-text-properties (match-beginning 0) (match-end 0)
5371 (list 'mouse-face 'highlight
5372 'face 'org-link
5373 'keymap org-mouse-map))
5374 (org-rear-nonsticky-at (match-end 0)))
5375 t)))))
5376
5377 (defun org-activate-code (limit)
5378 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5379 (progn
5380 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5381 (remove-text-properties (match-beginning 0) (match-end 0)
5382 '(display t invisible t intangible t))
5383 t)))
5384
5385 (defcustom org-src-fontify-natively nil
5386 "When non-nil, fontify code in code blocks."
5387 :type 'boolean
5388 :version "24.1"
5389 :group 'org-appearance
5390 :group 'org-babel)
5391
5392 (defun org-fontify-meta-lines-and-blocks (limit)
5393 (condition-case nil
5394 (org-fontify-meta-lines-and-blocks-1 limit)
5395 (error (message "org-mode fontification error"))))
5396
5397 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5398 "Fontify #+ lines and blocks, in the correct ways."
5399 (let ((case-fold-search t))
5400 (if (re-search-forward
5401 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5402 limit t)
5403 (let ((beg (match-beginning 0))
5404 (block-start (match-end 0))
5405 (block-end nil)
5406 (lang (match-string 7))
5407 (beg1 (line-beginning-position 2))
5408 (dc1 (downcase (match-string 2)))
5409 (dc3 (downcase (match-string 3)))
5410 end end1 quoting block-type ovl)
5411 (cond
5412 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5413 ;; a single line of backend-specific content
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 (add-text-properties (match-beginning 1) (match-end 3)
5418 '(font-lock-fontified t face org-meta-line))
5419 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5420 '(font-lock-fontified t face org-block))
5421 ; for backend-specific code
5422 t)
5423 ((and (match-end 4) (equal dc3 "begin"))
5424 ;; Truly a block
5425 (setq block-type (downcase (match-string 5))
5426 quoting (member block-type org-protecting-blocks))
5427 (when (re-search-forward
5428 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5429 nil t) ;; on purpose, we look further than LIMIT
5430 (setq end (min (point-max) (match-end 0))
5431 end1 (min (point-max) (1- (match-beginning 0))))
5432 (setq block-end (match-beginning 0))
5433 (when quoting
5434 (remove-text-properties beg end
5435 '(display t invisible t intangible t)))
5436 (add-text-properties
5437 beg end
5438 '(font-lock-fontified t font-lock-multiline t))
5439 (add-text-properties beg beg1 '(face org-meta-line))
5440 (add-text-properties end1 (min (point-max) (1+ end))
5441 '(face org-meta-line)) ; for end_src
5442 (cond
5443 ((and lang (not (string= lang "")) org-src-fontify-natively)
5444 (org-src-font-lock-fontify-block lang block-start block-end)
5445 ;; remove old background overlays
5446 (mapc (lambda (ov)
5447 (if (eq (overlay-get ov 'face) 'org-block-background)
5448 (delete-overlay ov)))
5449 (overlays-at (/ (+ beg1 block-end) 2)))
5450 ;; add a background overlay
5451 (setq ovl (make-overlay beg1 block-end))
5452 (overlay-put ovl 'face 'org-block-background)
5453 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5454 (quoting
5455 (add-text-properties beg1 (min (point-max) (1+ end1))
5456 '(face org-block))) ; end of source block
5457 ((not org-fontify-quote-and-verse-blocks))
5458 ((string= block-type "quote")
5459 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5460 ((string= block-type "verse")
5461 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5462 (add-text-properties beg beg1 '(face org-block-begin-line))
5463 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5464 '(face org-block-end-line))
5465 t))
5466 ((member dc1 '("title:" "author:" "email:" "date:"))
5467 (add-text-properties
5468 beg (match-end 3)
5469 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5470 '(font-lock-fontified t invisible t)
5471 '(font-lock-fontified t face org-document-info-keyword)))
5472 (add-text-properties
5473 (match-beginning 6) (match-end 6)
5474 (if (string-equal dc1 "title:")
5475 '(font-lock-fontified t face org-document-title)
5476 '(font-lock-fontified t face org-document-info))))
5477 ((not (member (char-after beg) '(?\ ?\t)))
5478 ;; just any other in-buffer setting, but not indented
5479 (add-text-properties
5480 beg (match-end 0)
5481 '(font-lock-fontified t face org-meta-line))
5482 t)
5483 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5484 "orgtbl:" "tblfm:" "tblname:" "results:"
5485 "call:" "header:" "headers:" "name:"))
5486 (and (match-end 4) (equal dc3 "attr")))
5487 (add-text-properties
5488 beg (match-end 0)
5489 '(font-lock-fontified t face org-meta-line))
5490 t)
5491 ((member dc3 '(" " ""))
5492 (add-text-properties
5493 beg (match-end 0)
5494 '(font-lock-fontified t face font-lock-comment-face)))
5495 (t nil))))))
5496
5497 (defun org-strip-protective-commas (beg end)
5498 "Strip protective commas between BEG and END in the current buffer."
5499 (interactive "r")
5500 (save-excursion
5501 (save-match-data
5502 (goto-char beg)
5503 (let ((front-line (save-excursion
5504 (re-search-forward
5505 "[^[:space:]]" end t)
5506 (goto-char (match-beginning 0))
5507 (current-column))))
5508 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5509 (goto-char (match-beginning 1))
5510 (when (= (current-column) front-line)
5511 (replace-match "" nil nil nil 1)))))))
5512
5513 (defun org-activate-angle-links (limit)
5514 "Run through the buffer and add overlays to links."
5515 (if (re-search-forward org-angle-link-re limit t)
5516 (progn
5517 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5518 (add-text-properties (match-beginning 0) (match-end 0)
5519 (list 'mouse-face 'highlight
5520 'keymap org-mouse-map))
5521 (org-rear-nonsticky-at (match-end 0))
5522 t)))
5523
5524 (defun org-activate-footnote-links (limit)
5525 "Run through the buffer and add overlays to footnotes."
5526 (let ((fn (org-footnote-next-reference-or-definition limit)))
5527 (when fn
5528 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5529 (org-remove-flyspell-overlays-in beg end)
5530 (add-text-properties beg end
5531 (list 'mouse-face 'highlight
5532 'keymap org-mouse-map
5533 'help-echo
5534 (if (= (point-at-bol) beg)
5535 "Footnote definition"
5536 "Footnote reference")
5537 'font-lock-fontified t
5538 'font-lock-multiline t
5539 'face 'org-footnote))))))
5540
5541 (defun org-activate-bracket-links (limit)
5542 "Run through the buffer and add overlays to bracketed links."
5543 (if (re-search-forward org-bracket-link-regexp limit t)
5544 (let* ((help (concat "LINK: "
5545 (org-match-string-no-properties 1)))
5546 ;; FIXME: above we should remove the escapes.
5547 ;; but that requires another match, protecting match data,
5548 ;; a lot of overhead for font-lock.
5549 (ip (org-maybe-intangible
5550 (list 'invisible 'org-link
5551 'keymap org-mouse-map 'mouse-face 'highlight
5552 'font-lock-multiline t 'help-echo help)))
5553 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5554 'font-lock-multiline t 'help-echo help)))
5555 ;; We need to remove the invisible property here. Table narrowing
5556 ;; may have made some of this invisible.
5557 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5558 (remove-text-properties (match-beginning 0) (match-end 0)
5559 '(invisible nil))
5560 (if (match-end 3)
5561 (progn
5562 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5563 (org-rear-nonsticky-at (match-beginning 3))
5564 (add-text-properties (match-beginning 3) (match-end 3) vp)
5565 (org-rear-nonsticky-at (match-end 3))
5566 (add-text-properties (match-end 3) (match-end 0) ip)
5567 (org-rear-nonsticky-at (match-end 0)))
5568 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5569 (org-rear-nonsticky-at (match-beginning 1))
5570 (add-text-properties (match-beginning 1) (match-end 1) vp)
5571 (org-rear-nonsticky-at (match-end 1))
5572 (add-text-properties (match-end 1) (match-end 0) ip)
5573 (org-rear-nonsticky-at (match-end 0)))
5574 t)))
5575
5576 (defun org-activate-dates (limit)
5577 "Run through the buffer and add overlays to dates."
5578 (if (re-search-forward org-tsr-regexp-both limit t)
5579 (progn
5580 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5581 (add-text-properties (match-beginning 0) (match-end 0)
5582 (list 'mouse-face 'highlight
5583 'keymap org-mouse-map))
5584 (org-rear-nonsticky-at (match-end 0))
5585 (when org-display-custom-times
5586 (if (match-end 3)
5587 (org-display-custom-time (match-beginning 3) (match-end 3)))
5588 (org-display-custom-time (match-beginning 1) (match-end 1)))
5589 t)))
5590
5591 (defvar org-target-link-regexp nil
5592 "Regular expression matching radio targets in plain text.")
5593 (make-variable-buffer-local 'org-target-link-regexp)
5594 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5595 "Regular expression matching a link target.")
5596 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5597 "Regular expression matching a radio target.")
5598 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5599 "Regular expression matching any target.")
5600
5601 (defun org-activate-target-links (limit)
5602 "Run through the buffer and add overlays to target matches."
5603 (when org-target-link-regexp
5604 (let ((case-fold-search t))
5605 (if (re-search-forward org-target-link-regexp limit t)
5606 (progn
5607 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5608 (add-text-properties (match-beginning 0) (match-end 0)
5609 (list 'mouse-face 'highlight
5610 'keymap org-mouse-map
5611 'help-echo "Radio target link"
5612 'org-linked-text t))
5613 (org-rear-nonsticky-at (match-end 0))
5614 t)))))
5615
5616 (defun org-update-radio-target-regexp ()
5617 "Find all radio targets in this file and update the regular expression."
5618 (interactive)
5619 (when (memq 'radio org-activate-links)
5620 (setq org-target-link-regexp
5621 (org-make-target-link-regexp (org-all-targets 'radio)))
5622 (org-restart-font-lock)))
5623
5624 (defun org-hide-wide-columns (limit)
5625 (let (s e)
5626 (setq s (text-property-any (point) (or limit (point-max))
5627 'org-cwidth t))
5628 (when s
5629 (setq e (next-single-property-change s 'org-cwidth))
5630 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5631 (goto-char e)
5632 t)))
5633
5634 (defvar org-latex-and-specials-regexp nil
5635 "Regular expression for highlighting export special stuff.")
5636 (defvar org-match-substring-regexp)
5637 (defvar org-match-substring-with-braces-regexp)
5638
5639 ;; This should be with the exporter code, but we also use if for font-locking
5640 (defconst org-export-html-special-string-regexps
5641 '(("\\\\-" . "&shy;")
5642 ("---\\([^-]\\)" . "&mdash;\\1")
5643 ("--\\([^-]\\)" . "&ndash;\\1")
5644 ("\\.\\.\\." . "&hellip;"))
5645 "Regular expressions for special string conversion.")
5646
5647
5648 (defun org-compute-latex-and-specials-regexp ()
5649 "Compute regular expression for stuff treated specially by exporters."
5650 (if (not org-highlight-latex-fragments-and-specials)
5651 (org-set-local 'org-latex-and-specials-regexp nil)
5652 (require 'org-exp)
5653 (let*
5654 ((matchers (plist-get org-format-latex-options :matchers))
5655 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5656 org-latex-regexps)))
5657 (org-export-allow-BIND nil)
5658 (options (org-combine-plists (org-default-export-plist)
5659 (org-infile-export-plist)))
5660 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5661 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5662 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5663 (org-export-html-expand (plist-get options :expand-quoted-html))
5664 (org-export-with-special-strings (plist-get options :special-strings))
5665 (re-sub
5666 (cond
5667 ((equal org-export-with-sub-superscripts '{})
5668 (list org-match-substring-with-braces-regexp))
5669 (org-export-with-sub-superscripts
5670 (list org-match-substring-regexp))
5671 (t nil)))
5672 (re-latex
5673 (if org-export-with-LaTeX-fragments
5674 (mapcar (lambda (x) (nth 1 x)) latexs)))
5675 (re-macros
5676 (if org-export-with-TeX-macros
5677 (list (concat "\\\\"
5678 (regexp-opt
5679 (append
5680
5681 (delq nil
5682 (mapcar 'car-safe
5683 (append org-entities-user
5684 org-entities)))
5685 (if (boundp 'org-latex-entities)
5686 (mapcar (lambda (x)
5687 (or (car-safe x) x))
5688 org-latex-entities)
5689 nil))
5690 'words))) ; FIXME
5691 ))
5692 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5693 (re-special (if org-export-with-special-strings
5694 (mapcar (lambda (x) (car x))
5695 org-export-html-special-string-regexps)))
5696 (re-rest
5697 (delq nil
5698 (list
5699 (if org-export-html-expand "@<[^>\n]+>")
5700 ))))
5701 (org-set-local
5702 'org-latex-and-specials-regexp
5703 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5704 re-rest) "\\|")))))
5705
5706 (defun org-do-latex-and-special-faces (limit)
5707 "Run through the buffer and add overlays to links."
5708 (when org-latex-and-specials-regexp
5709 (let (rtn d)
5710 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5711 limit t))
5712 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5713 'face))
5714 '(org-code org-verbatim underline)))
5715 (progn
5716 (setq rtn t
5717 d (cond ((member (char-after (1+ (match-beginning 0)))
5718 '(?_ ?^)) 1)
5719 (t 0)))
5720 (font-lock-prepend-text-property
5721 (+ d (match-beginning 0)) (match-end 0)
5722 'face 'org-latex-and-export-specials)
5723 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5724 '(font-lock-multiline t)))))
5725 rtn)))
5726
5727 (defun org-restart-font-lock ()
5728 "Restart `font-lock-mode', to force refontification."
5729 (when (and (boundp 'font-lock-mode) font-lock-mode)
5730 (font-lock-mode -1)
5731 (font-lock-mode 1)))
5732
5733 (defun org-all-targets (&optional radio)
5734 "Return a list of all targets in this file.
5735 With optional argument RADIO, only find radio targets."
5736 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5737 rtn)
5738 (save-excursion
5739 (goto-char (point-min))
5740 (while (re-search-forward re nil t)
5741 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5742 rtn)))
5743
5744 (defun org-make-target-link-regexp (targets)
5745 "Make regular expression matching all strings in TARGETS.
5746 The regular expression finds the targets also if there is a line break
5747 between words."
5748 (and targets
5749 (concat
5750 "\\<\\("
5751 (mapconcat
5752 (lambda (x)
5753 (setq x (regexp-quote x))
5754 (while (string-match " +" x)
5755 (setq x (replace-match "\\s-+" t t x)))
5756 x)
5757 targets
5758 "\\|")
5759 "\\)\\>")))
5760
5761 (defun org-activate-tags (limit)
5762 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5765 (add-text-properties (match-beginning 1) (match-end 1)
5766 (list 'mouse-face 'highlight
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 1))
5769 t)))
5770
5771 (defun org-outline-level ()
5772 "Compute the outline level of the heading at point.
5773 This function assumes that the cursor is at the beginning of a line matched
5774 by `outline-regexp'. Otherwise it returns garbage.
5775 If this is called at a normal headline, the level is the number of stars.
5776 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5777 (save-excursion
5778 (looking-at org-outline-regexp)
5779 (1- (- (match-end 0) (match-beginning 0)))))
5780
5781 (defvar org-font-lock-keywords nil)
5782
5783 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5784 "Regular expression matching a property line.")
5785
5786 (defvar org-font-lock-hook nil
5787 "Functions to be called for special font lock stuff.")
5788
5789 (defvar org-font-lock-set-keywords-hook nil
5790 "Functions that can manipulate `org-font-lock-extra-keywords'.
5791 This is called after `org-font-lock-extra-keywords' is defined, but before
5792 it is installed to be used by font lock. This can be useful if something
5793 needs to be inserted at a specific position in the font-lock sequence.")
5794
5795 (defun org-font-lock-hook (limit)
5796 (run-hook-with-args 'org-font-lock-hook limit))
5797
5798 (defun org-set-font-lock-defaults ()
5799 (let* ((em org-fontify-emphasized-text)
5800 (lk org-activate-links)
5801 (org-font-lock-extra-keywords
5802 (list
5803 ;; Call the hook
5804 '(org-font-lock-hook)
5805 ;; Headlines
5806 `(,(if org-fontify-whole-heading-line
5807 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5808 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5809 (1 (org-get-level-face 1))
5810 (2 (org-get-level-face 2))
5811 (3 (org-get-level-face 3)))
5812 ;; Table lines
5813 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5814 (1 'org-table t))
5815 ;; Table internals
5816 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5817 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5818 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5819 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5820 ;; Drawers
5821 (list org-drawer-regexp '(0 'org-special-keyword t))
5822 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5823 ;; Properties
5824 (list org-property-re
5825 '(1 'org-special-keyword t)
5826 '(3 'org-property-value t))
5827 ;; Links
5828 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5829 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5830 (if (memq 'plain lk) '(org-activate-plain-links))
5831 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5832 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5833 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5834 (if (memq 'footnote lk) '(org-activate-footnote-links))
5835 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5836 '(org-hide-wide-columns (0 nil append))
5837 ;; TODO keyword
5838 (list (format org-heading-keyword-regexp-format
5839 org-todo-regexp)
5840 '(2 (org-get-todo-face 2) t))
5841 ;; DONE
5842 (if org-fontify-done-headline
5843 (list (format org-heading-keyword-regexp-format
5844 (concat
5845 "\\(?:"
5846 (mapconcat 'regexp-quote org-done-keywords "\\|")
5847 "\\)"))
5848 '(2 'org-headline-done t))
5849 nil)
5850 ;; Priorities
5851 '(org-font-lock-add-priority-faces)
5852 ;; Tags
5853 '(org-font-lock-add-tag-faces)
5854 ;; Special keywords
5855 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5856 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5857 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5858 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5859 ;; Emphasis
5860 (if em
5861 (if (featurep 'xemacs)
5862 '(org-do-emphasis-faces (0 nil append))
5863 '(org-do-emphasis-faces)))
5864 ;; Checkboxes
5865 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5866 1 'org-checkbox prepend)
5867 (if (cdr (assq 'checkbox org-list-automatic-rules))
5868 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5869 (0 (org-get-checkbox-statistics-face) t)))
5870 ;; Description list items
5871 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5872 1 'bold prepend)
5873 ;; ARCHIVEd headings
5874 (list (concat
5875 org-outline-regexp-bol
5876 "\\(.*:" org-archive-tag ":.*\\)")
5877 '(1 'org-archived prepend))
5878 ;; Specials
5879 '(org-do-latex-and-special-faces)
5880 '(org-fontify-entities)
5881 '(org-raise-scripts)
5882 ;; Code
5883 '(org-activate-code (1 'org-code t))
5884 ;; COMMENT
5885 (list (format org-heading-keyword-regexp-format
5886 (concat "\\("
5887 org-comment-string "\\|" org-quote-string
5888 "\\)"))
5889 '(2 'org-special-keyword t))
5890 '("^#.*" (0 'font-lock-comment-face t))
5891 ;; Blocks and meta lines
5892 '(org-fontify-meta-lines-and-blocks)
5893 )))
5894 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5895 (run-hooks 'org-font-lock-set-keywords-hook)
5896 ;; Now set the full font-lock-keywords
5897 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5898 (org-set-local 'font-lock-defaults
5899 '(org-font-lock-keywords t nil nil backward-paragraph))
5900 (kill-local-variable 'font-lock-keywords) nil))
5901
5902 (defun org-toggle-pretty-entities ()
5903 "Toggle the composition display of entities as UTF8 characters."
5904 (interactive)
5905 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5906 (org-restart-font-lock)
5907 (if org-pretty-entities
5908 (message "Entities are displayed as UTF8 characters")
5909 (save-restriction
5910 (widen)
5911 (org-decompose-region (point-min) (point-max))
5912 (message "Entities are displayed plain"))))
5913
5914 (defun org-fontify-entities (limit)
5915 "Find an entity to fontify."
5916 (let (ee)
5917 (when org-pretty-entities
5918 (catch 'match
5919 (while (re-search-forward
5920 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5921 limit t)
5922 (if (and (not (org-in-indented-comment-line))
5923 (setq ee (org-entity-get (match-string 1)))
5924 (= (length (nth 6 ee)) 1))
5925 (let*
5926 ((end (if (equal (match-string 2) "{}")
5927 (match-end 2)
5928 (match-end 1))))
5929 (add-text-properties
5930 (match-beginning 0) end
5931 (list 'font-lock-fontified t))
5932 (compose-region (match-beginning 0) end
5933 (nth 6 ee) nil)
5934 (backward-char 1)
5935 (throw 'match t))))
5936 nil))))
5937
5938 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5939 "Fontify string S like in Org-mode."
5940 (with-temp-buffer
5941 (insert s)
5942 (let ((org-odd-levels-only odd-levels))
5943 (org-mode)
5944 (font-lock-fontify-buffer)
5945 (buffer-string))))
5946
5947 (defvar org-m nil)
5948 (defvar org-l nil)
5949 (defvar org-f nil)
5950 (defun org-get-level-face (n)
5951 "Get the right face for match N in font-lock matching of headlines."
5952 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5953 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5954 (if org-cycle-level-faces
5955 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5956 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5957 (cond
5958 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5959 ((eq n 2) org-f)
5960 (t (if org-level-color-stars-only nil org-f))))
5961
5962
5963 (defun org-get-todo-face (kwd)
5964 "Get the right face for a TODO keyword KWD.
5965 If KWD is a number, get the corresponding match group."
5966 (if (numberp kwd) (setq kwd (match-string kwd)))
5967 (or (org-face-from-face-or-color
5968 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5969 (and (member kwd org-done-keywords) 'org-done)
5970 'org-todo))
5971
5972 (defun org-face-from-face-or-color (context inherit face-or-color)
5973 "Create a face list that inherits INHERIT, but sets the foreground color.
5974 When FACE-OR-COLOR is not a string, just return it."
5975 (if (stringp face-or-color)
5976 (list :inherit inherit
5977 (cdr (assoc context org-faces-easy-properties))
5978 face-or-color)
5979 face-or-color))
5980
5981 (defun org-font-lock-add-tag-faces (limit)
5982 "Add the special tag faces."
5983 (when (and org-tag-faces org-tags-special-faces-re)
5984 (while (re-search-forward org-tags-special-faces-re limit t)
5985 (add-text-properties (match-beginning 1) (match-end 1)
5986 (list 'face (org-get-tag-face 1)
5987 'font-lock-fontified t))
5988 (backward-char 1))))
5989
5990 (defun org-font-lock-add-priority-faces (limit)
5991 "Add the special priority faces."
5992 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5993 (when (save-match-data (org-at-heading-p))
5994 (add-text-properties
5995 (match-beginning 0) (match-end 0)
5996 (list 'face (or (org-face-from-face-or-color
5997 'priority 'org-special-keyword
5998 (cdr (assoc (char-after (match-beginning 1))
5999 org-priority-faces)))
6000 'org-special-keyword)
6001 'font-lock-fontified t)))))
6002
6003 (defun org-get-tag-face (kwd)
6004 "Get the right face for a TODO keyword KWD.
6005 If KWD is a number, get the corresponding match group."
6006 (if (numberp kwd) (setq kwd (match-string kwd)))
6007 (or (org-face-from-face-or-color
6008 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6009 'org-tag))
6010
6011 (defun org-unfontify-region (beg end &optional maybe_loudly)
6012 "Remove fontification and activation overlays from links."
6013 (font-lock-default-unfontify-region beg end)
6014 (let* ((buffer-undo-list t)
6015 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6016 (inhibit-modification-hooks t)
6017 deactivate-mark buffer-file-name buffer-file-truename)
6018 (org-decompose-region beg end)
6019 (remove-text-properties beg end
6020 '(mouse-face t keymap t org-linked-text t
6021 invisible t intangible t
6022 org-no-flyspell t org-emphasis t))
6023 (org-remove-font-lock-display-properties beg end)))
6024
6025 (defconst org-script-display '(((raise -0.3) (height 0.7))
6026 ((raise 0.3) (height 0.7))
6027 ((raise -0.5))
6028 ((raise 0.5)))
6029 "Display properties for showing superscripts and subscripts.")
6030
6031 (defun org-remove-font-lock-display-properties (beg end)
6032 "Remove specific display properties that have been added by font lock.
6033 The will remove the raise properties that are used to show superscripts
6034 and subscripts."
6035 (let (next prop)
6036 (while (< beg end)
6037 (setq next (next-single-property-change beg 'display nil end)
6038 prop (get-text-property beg 'display))
6039 (if (member prop org-script-display)
6040 (put-text-property beg next 'display nil))
6041 (setq beg next))))
6042
6043 (defun org-raise-scripts (limit)
6044 "Add raise properties to sub/superscripts."
6045 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6046 (if (re-search-forward
6047 (if (eq org-use-sub-superscripts t)
6048 org-match-substring-regexp
6049 org-match-substring-with-braces-regexp)
6050 limit t)
6051 (let* ((pos (point)) table-p comment-p
6052 (mpos (match-beginning 3))
6053 (emph-p (get-text-property mpos 'org-emphasis))
6054 (link-p (get-text-property mpos 'mouse-face))
6055 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6056 (goto-char (point-at-bol))
6057 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6058 comment-p (org-looking-at-p "[ \t]*#"))
6059 (goto-char pos)
6060 ;; FIXME: Should we go back one character here, for a_b^c
6061 ;; (goto-char (1- pos)) ;????????????????????
6062 (if (or comment-p emph-p link-p keyw-p)
6063 t
6064 (put-text-property (match-beginning 3) (match-end 0)
6065 'display
6066 (if (equal (char-after (match-beginning 2)) ?^)
6067 (nth (if table-p 3 1) org-script-display)
6068 (nth (if table-p 2 0) org-script-display)))
6069 (add-text-properties (match-beginning 2) (match-end 2)
6070 (list 'invisible t
6071 'org-dwidth t 'org-dwidth-n 1))
6072 (if (and (eq (char-after (match-beginning 3)) ?{)
6073 (eq (char-before (match-end 3)) ?}))
6074 (progn
6075 (add-text-properties
6076 (match-beginning 3) (1+ (match-beginning 3))
6077 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6078 (add-text-properties
6079 (1- (match-end 3)) (match-end 3)
6080 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6081 t)))))
6082
6083 ;;;; Visibility cycling, including org-goto and indirect buffer
6084
6085 ;;; Cycling
6086
6087 (defvar org-cycle-global-status nil)
6088 (make-variable-buffer-local 'org-cycle-global-status)
6089 (defvar org-cycle-subtree-status nil)
6090 (make-variable-buffer-local 'org-cycle-subtree-status)
6091
6092 ;;;###autoload
6093
6094 (defvar org-inlinetask-min-level)
6095
6096 (defun org-cycle (&optional arg)
6097 "TAB-action and visibility cycling for Org-mode.
6098
6099 This is the command invoked in Org-mode by the TAB key. Its main purpose
6100 is outline visibility cycling, but it also invokes other actions
6101 in special contexts.
6102
6103 - When this function is called with a prefix argument, rotate the entire
6104 buffer through 3 states (global cycling)
6105 1. OVERVIEW: Show only top-level headlines.
6106 2. CONTENTS: Show all headlines of all levels, but no body text.
6107 3. SHOW ALL: Show everything.
6108 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6109 determined by the variable `org-startup-folded', and by any VISIBILITY
6110 properties in the buffer.
6111 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6112 including any drawers.
6113
6114 - When inside a table, re-align the table and move to the next field.
6115
6116 - When point is at the beginning of a headline, rotate the subtree started
6117 by this line through 3 different states (local cycling)
6118 1. FOLDED: Only the main headline is shown.
6119 2. CHILDREN: The main headline and the direct children are shown.
6120 From this state, you can move to one of the children
6121 and zoom in further.
6122 3. SUBTREE: Show the entire subtree, including body text.
6123 If there is no subtree, switch directly from CHILDREN to FOLDED.
6124
6125 - When point is at the beginning of an empty headline and the variable
6126 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6127 of the headline by demoting and promoting it to likely levels. This
6128 speeds up creation document structure by pressing TAB once or several
6129 times right after creating a new headline.
6130
6131 - When there is a numeric prefix, go up to a heading with level ARG, do
6132 a `show-subtree' and return to the previous cursor position. If ARG
6133 is negative, go up that many levels.
6134
6135 - When point is not at the beginning of a headline, execute the global
6136 binding for TAB, which is re-indenting the line. See the option
6137 `org-cycle-emulate-tab' for details.
6138
6139 - Special case: if point is at the beginning of the buffer and there is
6140 no headline in line 1, this function will act as if called with prefix arg
6141 (C-u TAB, same as S-TAB) also when called without prefix arg.
6142 But only if also the variable `org-cycle-global-at-bob' is t."
6143 (interactive "P")
6144 (org-load-modules-maybe)
6145 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6146 (and org-cycle-level-after-item/entry-creation
6147 (or (org-cycle-level)
6148 (org-cycle-item-indentation))))
6149 (let* ((limit-level
6150 (or org-cycle-max-level
6151 (and (boundp 'org-inlinetask-min-level)
6152 org-inlinetask-min-level
6153 (1- org-inlinetask-min-level))))
6154 (nstars (and limit-level
6155 (if org-odd-levels-only
6156 (and limit-level (1- (* limit-level 2)))
6157 limit-level)))
6158 (org-outline-regexp
6159 (if (not (eq major-mode 'org-mode))
6160 outline-regexp
6161 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6162 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6163 (not (looking-at org-outline-regexp))))
6164 (org-cycle-hook
6165 (if bob-special
6166 (delq 'org-optimize-window-after-visibility-change
6167 (copy-sequence org-cycle-hook))
6168 org-cycle-hook))
6169 (pos (point)))
6170
6171 (if (or bob-special (equal arg '(4)))
6172 ;; special case: use global cycling
6173 (setq arg t))
6174
6175 (cond
6176
6177 ((equal arg '(16))
6178 (setq last-command 'dummy)
6179 (org-set-startup-visibility)
6180 (message "Startup visibility, plus VISIBILITY properties"))
6181
6182 ((equal arg '(64))
6183 (show-all)
6184 (message "Entire buffer visible, including drawers"))
6185
6186 ;; Table: enter it or move to the next field.
6187 ((org-at-table-p 'any)
6188 (if (org-at-table.el-p)
6189 (message "Use C-c ' to edit table.el tables")
6190 (if arg (org-table-edit-field t)
6191 (org-table-justify-field-maybe)
6192 (call-interactively 'org-table-next-field))))
6193
6194 ((run-hook-with-args-until-success
6195 'org-tab-after-check-for-table-hook))
6196
6197 ;; Global cycling: delegate to `org-cycle-internal-global'.
6198 ((eq arg t) (org-cycle-internal-global))
6199
6200 ;; Drawers: delegate to `org-flag-drawer'.
6201 ((and org-drawers org-drawer-regexp
6202 (save-excursion
6203 (beginning-of-line 1)
6204 (looking-at org-drawer-regexp)))
6205 (org-flag-drawer ; toggle block visibility
6206 (not (get-char-property (match-end 0) 'invisible))))
6207
6208 ;; Show-subtree, ARG levels up from here.
6209 ((integerp arg)
6210 (save-excursion
6211 (org-back-to-heading)
6212 (outline-up-heading (if (< arg 0) (- arg)
6213 (- (funcall outline-level) arg)))
6214 (org-show-subtree)))
6215
6216 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6217 ((and (featurep 'org-inlinetask)
6218 (org-inlinetask-at-task-p)
6219 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6220 (org-inlinetask-toggle-visibility))
6221
6222 ((org-try-cdlatex-tab))
6223
6224 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6225 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6226 (save-excursion (beginning-of-line 1)
6227 (looking-at org-outline-regexp)))
6228 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6229 (org-cycle-internal-local))
6230
6231 ;; From there: TAB emulation and template completion.
6232 (buffer-read-only (org-back-to-heading))
6233
6234 ((run-hook-with-args-until-success
6235 'org-tab-after-check-for-cycling-hook))
6236
6237 ((org-try-structure-completion))
6238
6239 ((run-hook-with-args-until-success
6240 'org-tab-before-tab-emulation-hook))
6241
6242 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6243 (or (not (bolp))
6244 (not (looking-at org-outline-regexp))))
6245 (call-interactively (global-key-binding "\t")))
6246
6247 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6248 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6249 (or (and (eq org-cycle-emulate-tab 'white)
6250 (= (match-end 0) (point-at-eol)))
6251 (and (eq org-cycle-emulate-tab 'whitestart)
6252 (>= (match-end 0) pos))))
6253 t
6254 (eq org-cycle-emulate-tab t))
6255 (call-interactively (global-key-binding "\t")))
6256
6257 (t (save-excursion
6258 (org-back-to-heading)
6259 (org-cycle)))))))
6260
6261 (defun org-cycle-internal-global ()
6262 "Do the global cycling action."
6263 ;; Hack to avoid display of messages for .org attachments in Gnus
6264 (let ((ga (string-match "\\*fontification" (buffer-name))))
6265 (cond
6266 ((and (eq last-command this-command)
6267 (eq org-cycle-global-status 'overview))
6268 ;; We just created the overview - now do table of contents
6269 ;; This can be slow in very large buffers, so indicate action
6270 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6271 (unless ga (message "CONTENTS..."))
6272 (org-content)
6273 (unless ga (message "CONTENTS...done"))
6274 (setq org-cycle-global-status 'contents)
6275 (run-hook-with-args 'org-cycle-hook 'contents))
6276
6277 ((and (eq last-command this-command)
6278 (eq org-cycle-global-status 'contents))
6279 ;; We just showed the table of contents - now show everything
6280 (run-hook-with-args 'org-pre-cycle-hook 'all)
6281 (show-all)
6282 (unless ga (message "SHOW ALL"))
6283 (setq org-cycle-global-status 'all)
6284 (run-hook-with-args 'org-cycle-hook 'all))
6285
6286 (t
6287 ;; Default action: go to overview
6288 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6289 (org-overview)
6290 (unless ga (message "OVERVIEW"))
6291 (setq org-cycle-global-status 'overview)
6292 (run-hook-with-args 'org-cycle-hook 'overview)))))
6293
6294 (defun org-cycle-internal-local ()
6295 "Do the local cycling action."
6296 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6297 ;; First, determine end of headline (EOH), end of subtree or item
6298 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6299 (save-excursion
6300 (if (org-at-item-p)
6301 (progn
6302 (beginning-of-line)
6303 (setq struct (org-list-struct))
6304 (setq eoh (point-at-eol))
6305 (setq eos (org-list-get-item-end-before-blank (point) struct))
6306 (setq has-children (org-list-has-child-p (point) struct)))
6307 (org-back-to-heading)
6308 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6309 (setq eos (save-excursion
6310 (org-end-of-subtree t)
6311 (unless (eobp)
6312 (skip-chars-forward " \t\n"))
6313 (if (eobp) (point) (1- (point)))))
6314 (setq has-children
6315 (or (save-excursion
6316 (let ((level (funcall outline-level)))
6317 (outline-next-heading)
6318 (and (org-at-heading-p t)
6319 (> (funcall outline-level) level))))
6320 (save-excursion
6321 (org-list-search-forward (org-item-beginning-re) eos t)))))
6322 ;; Determine end invisible part of buffer (EOL)
6323 (beginning-of-line 2)
6324 ;; XEmacs doesn't have `next-single-char-property-change'
6325 (if (featurep 'xemacs)
6326 (while (and (not (eobp)) ;; this is like `next-line'
6327 (get-char-property (1- (point)) 'invisible))
6328 (beginning-of-line 2))
6329 (while (and (not (eobp)) ;; this is like `next-line'
6330 (get-char-property (1- (point)) 'invisible))
6331 (goto-char (next-single-char-property-change (point) 'invisible))
6332 (and (eolp) (beginning-of-line 2))))
6333 (setq eol (point)))
6334 ;; Find out what to do next and set `this-command'
6335 (cond
6336 ((= eos eoh)
6337 ;; Nothing is hidden behind this heading
6338 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6339 (message "EMPTY ENTRY")
6340 (setq org-cycle-subtree-status nil)
6341 (save-excursion
6342 (goto-char eos)
6343 (outline-next-heading)
6344 (if (outline-invisible-p) (org-flag-heading nil))))
6345 ((and (or (>= eol eos)
6346 (not (string-match "\\S-" (buffer-substring eol eos))))
6347 (or has-children
6348 (not (setq children-skipped
6349 org-cycle-skip-children-state-if-no-children))))
6350 ;; Entire subtree is hidden in one line: children view
6351 (run-hook-with-args 'org-pre-cycle-hook 'children)
6352 (if (org-at-item-p)
6353 (org-list-set-item-visibility (point-at-bol) struct 'children)
6354 (org-show-entry)
6355 (org-with-limited-levels (show-children))
6356 ;; FIXME: This slows down the func way too much.
6357 ;; How keep drawers hidden in subtree anyway?
6358 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6359 ;; (org-cycle-hide-drawers 'subtree))
6360
6361 ;; Fold every list in subtree to top-level items.
6362 (when (eq org-cycle-include-plain-lists 'integrate)
6363 (save-excursion
6364 (org-back-to-heading)
6365 (while (org-list-search-forward (org-item-beginning-re) eos t)
6366 (beginning-of-line 1)
6367 (let* ((struct (org-list-struct))
6368 (prevs (org-list-prevs-alist struct))
6369 (end (org-list-get-bottom-point struct)))
6370 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6371 (org-list-get-all-items (point) struct prevs))
6372 (goto-char end))))))
6373 (message "CHILDREN")
6374 (save-excursion
6375 (goto-char eos)
6376 (outline-next-heading)
6377 (if (outline-invisible-p) (org-flag-heading nil)))
6378 (setq org-cycle-subtree-status 'children)
6379 (run-hook-with-args 'org-cycle-hook 'children))
6380 ((or children-skipped
6381 (and (eq last-command this-command)
6382 (eq org-cycle-subtree-status 'children)))
6383 ;; We just showed the children, or no children are there,
6384 ;; now show everything.
6385 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6386 (outline-flag-region eoh eos nil)
6387 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6388 (setq org-cycle-subtree-status 'subtree)
6389 (run-hook-with-args 'org-cycle-hook 'subtree))
6390 (t
6391 ;; Default action: hide the subtree.
6392 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6393 (outline-flag-region eoh eos t)
6394 (message "FOLDED")
6395 (setq org-cycle-subtree-status 'folded)
6396 (run-hook-with-args 'org-cycle-hook 'folded)))))
6397
6398 ;;;###autoload
6399 (defun org-global-cycle (&optional arg)
6400 "Cycle the global visibility. For details see `org-cycle'.
6401 With \\[universal-argument] prefix arg, switch to startup visibility.
6402 With a numeric prefix, show all headlines up to that level."
6403 (interactive "P")
6404 (let ((org-cycle-include-plain-lists
6405 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6406 (cond
6407 ((integerp arg)
6408 (show-all)
6409 (hide-sublevels arg)
6410 (setq org-cycle-global-status 'contents))
6411 ((equal arg '(4))
6412 (org-set-startup-visibility)
6413 (message "Startup visibility, plus VISIBILITY properties."))
6414 (t
6415 (org-cycle '(4))))))
6416
6417 (defun org-set-startup-visibility ()
6418 "Set the visibility required by startup options and properties."
6419 (cond
6420 ((eq org-startup-folded t)
6421 (org-cycle '(4)))
6422 ((eq org-startup-folded 'content)
6423 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6424 (org-cycle '(4)) (org-cycle '(4)))))
6425 (unless (eq org-startup-folded 'showeverything)
6426 (if org-hide-block-startup (org-hide-block-all))
6427 (org-set-visibility-according-to-property 'no-cleanup)
6428 (org-cycle-hide-archived-subtrees 'all)
6429 (org-cycle-hide-drawers 'all)
6430 (org-cycle-show-empty-lines t)))
6431
6432 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6433 "Switch subtree visibilities according to :VISIBILITY: property."
6434 (interactive)
6435 (let (org-show-entry-below state)
6436 (save-excursion
6437 (goto-char (point-min))
6438 (while (re-search-forward
6439 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6440 nil t)
6441 (setq state (match-string 1))
6442 (save-excursion
6443 (org-back-to-heading t)
6444 (hide-subtree)
6445 (org-reveal)
6446 (cond
6447 ((equal state '("fold" "folded"))
6448 (hide-subtree))
6449 ((equal state "children")
6450 (org-show-hidden-entry)
6451 (show-children))
6452 ((equal state "content")
6453 (save-excursion
6454 (save-restriction
6455 (org-narrow-to-subtree)
6456 (org-content))))
6457 ((member state '("all" "showall"))
6458 (show-subtree)))))
6459 (unless no-cleanup
6460 (org-cycle-hide-archived-subtrees 'all)
6461 (org-cycle-hide-drawers 'all)
6462 (org-cycle-show-empty-lines 'all)))))
6463
6464 ;; This function uses outline-regexp instead of the more fundamental
6465 ;; org-outline-regexp so that org-cycle-global works outside of Org
6466 ;; buffers, where outline-regexp is needed.
6467 (defun org-overview ()
6468 "Switch to overview mode, showing only top-level headlines.
6469 Really, this shows all headlines with level equal or greater than the level
6470 of the first headline in the buffer. This is important, because if the
6471 first headline is not level one, then (hide-sublevels 1) gives confusing
6472 results."
6473 (interactive)
6474 (let ((level (save-excursion
6475 (goto-char (point-min))
6476 (if (re-search-forward (concat "^" outline-regexp) nil t)
6477 (progn
6478 (goto-char (match-beginning 0))
6479 (funcall outline-level))))))
6480 (and level (hide-sublevels level))))
6481
6482 (defun org-content (&optional arg)
6483 "Show all headlines in the buffer, like a table of contents.
6484 With numerical argument N, show content up to level N."
6485 (interactive "P")
6486 (save-excursion
6487 ;; Visit all headings and show their offspring
6488 (and (integerp arg) (org-overview))
6489 (goto-char (point-max))
6490 (catch 'exit
6491 (while (and (progn (condition-case nil
6492 (outline-previous-visible-heading 1)
6493 (error (goto-char (point-min))))
6494 t)
6495 (looking-at org-outline-regexp))
6496 (if (integerp arg)
6497 (show-children (1- arg))
6498 (show-branches))
6499 (if (bobp) (throw 'exit nil))))))
6500
6501
6502 (defun org-optimize-window-after-visibility-change (state)
6503 "Adjust the window after a change in outline visibility.
6504 This function is the default value of the hook `org-cycle-hook'."
6505 (when (get-buffer-window (current-buffer))
6506 (cond
6507 ((eq state 'content) nil)
6508 ((eq state 'all) nil)
6509 ((eq state 'folded) nil)
6510 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6511 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6512
6513 (defun org-remove-empty-overlays-at (pos)
6514 "Remove outline overlays that do not contain non-white stuff."
6515 (mapc
6516 (lambda (o)
6517 (and (eq 'outline (overlay-get o 'invisible))
6518 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6519 (overlay-end o))))
6520 (delete-overlay o)))
6521 (overlays-at pos)))
6522
6523 (defun org-clean-visibility-after-subtree-move ()
6524 "Fix visibility issues after moving a subtree."
6525 ;; First, find a reasonable region to look at:
6526 ;; Start two siblings above, end three below
6527 (let* ((beg (save-excursion
6528 (and (org-get-last-sibling)
6529 (org-get-last-sibling))
6530 (point)))
6531 (end (save-excursion
6532 (and (org-get-next-sibling)
6533 (org-get-next-sibling)
6534 (org-get-next-sibling))
6535 (if (org-at-heading-p)
6536 (point-at-eol)
6537 (point))))
6538 (level (looking-at "\\*+"))
6539 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6540 (save-excursion
6541 (save-restriction
6542 (narrow-to-region beg end)
6543 (when re
6544 ;; Properly fold already folded siblings
6545 (goto-char (point-min))
6546 (while (re-search-forward re nil t)
6547 (if (and (not (outline-invisible-p))
6548 (save-excursion
6549 (goto-char (point-at-eol)) (outline-invisible-p)))
6550 (hide-entry))))
6551 (org-cycle-show-empty-lines 'overview)
6552 (org-cycle-hide-drawers 'overview)))))
6553
6554 (defun org-cycle-show-empty-lines (state)
6555 "Show empty lines above all visible headlines.
6556 The region to be covered depends on STATE when called through
6557 `org-cycle-hook'. Lisp program can use t for STATE to get the
6558 entire buffer covered. Note that an empty line is only shown if there
6559 are at least `org-cycle-separator-lines' empty lines before the headline."
6560 (when (not (= org-cycle-separator-lines 0))
6561 (save-excursion
6562 (let* ((n (abs org-cycle-separator-lines))
6563 (re (cond
6564 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6565 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6566 (t (let ((ns (number-to-string (- n 2))))
6567 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6568 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6569 beg end b e)
6570 (cond
6571 ((memq state '(overview contents t))
6572 (setq beg (point-min) end (point-max)))
6573 ((memq state '(children folded))
6574 (setq beg (point) end (progn (org-end-of-subtree t t)
6575 (beginning-of-line 2)
6576 (point)))))
6577 (when beg
6578 (goto-char beg)
6579 (while (re-search-forward re end t)
6580 (unless (get-char-property (match-end 1) 'invisible)
6581 (setq e (match-end 1))
6582 (if (< org-cycle-separator-lines 0)
6583 (setq b (save-excursion
6584 (goto-char (match-beginning 0))
6585 (org-back-over-empty-lines)
6586 (if (save-excursion
6587 (goto-char (max (point-min) (1- (point))))
6588 (org-at-heading-p))
6589 (1- (point))
6590 (point))))
6591 (setq b (match-beginning 1)))
6592 (outline-flag-region b e nil)))))))
6593 ;; Never hide empty lines at the end of the file.
6594 (save-excursion
6595 (goto-char (point-max))
6596 (outline-previous-heading)
6597 (outline-end-of-heading)
6598 (if (and (looking-at "[ \t\n]+")
6599 (= (match-end 0) (point-max)))
6600 (outline-flag-region (point) (match-end 0) nil))))
6601
6602 (defun org-show-empty-lines-in-parent ()
6603 "Move to the parent and re-show empty lines before visible headlines."
6604 (save-excursion
6605 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6606 (org-cycle-show-empty-lines context))))
6607
6608 (defun org-files-list ()
6609 "Return `org-agenda-files' list, plus all open org-mode files.
6610 This is useful for operations that need to scan all of a user's
6611 open and agenda-wise Org files."
6612 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6613 (dolist (buf (buffer-list))
6614 (with-current-buffer buf
6615 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6616 (let ((file (expand-file-name (buffer-file-name))))
6617 (unless (member file files)
6618 (push file files))))))
6619 files))
6620
6621 (defsubst org-entry-beginning-position ()
6622 "Return the beginning position of the current entry."
6623 (save-excursion (outline-back-to-heading t) (point)))
6624
6625 (defsubst org-entry-end-position ()
6626 "Return the end position of the current entry."
6627 (save-excursion (outline-next-heading) (point)))
6628
6629 (defun org-cycle-hide-drawers (state)
6630 "Re-hide all drawers after a visibility state change."
6631 (when (and (eq major-mode 'org-mode)
6632 (not (memq state '(overview folded contents))))
6633 (save-excursion
6634 (let* ((globalp (memq state '(contents all)))
6635 (beg (if globalp (point-min) (point)))
6636 (end (if globalp (point-max)
6637 (if (eq state 'children)
6638 (save-excursion (outline-next-heading) (point))
6639 (org-end-of-subtree t)))))
6640 (goto-char beg)
6641 (while (re-search-forward org-drawer-regexp end t)
6642 (org-flag-drawer t))))))
6643
6644 (defun org-flag-drawer (flag)
6645 (save-excursion
6646 (beginning-of-line 1)
6647 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6648 (let ((b (match-end 0)))
6649 (if (re-search-forward
6650 "^[ \t]*:END:"
6651 (save-excursion (outline-next-heading) (point)) t)
6652 (outline-flag-region b (point-at-eol) flag)
6653 (error ":END: line missing at position %s" b))))))
6654
6655 (defun org-subtree-end-visible-p ()
6656 "Is the end of the current subtree visible?"
6657 (pos-visible-in-window-p
6658 (save-excursion (org-end-of-subtree t) (point))))
6659
6660 (defun org-first-headline-recenter (&optional N)
6661 "Move cursor to the first headline and recenter the headline.
6662 Optional argument N means put the headline into the Nth line of the window."
6663 (goto-char (point-min))
6664 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6665 (beginning-of-line)
6666 (recenter (prefix-numeric-value N))))
6667
6668 ;;; Saving and restoring visibility
6669
6670 (defun org-outline-overlay-data (&optional use-markers)
6671 "Return a list of the locations of all outline overlays.
6672 These are overlays with the `invisible' property value `outline'.
6673 The return value is a list of cons cells, with start and stop
6674 positions for each overlay.
6675 If USE-MARKERS is set, return the positions as markers."
6676 (let (beg end)
6677 (save-excursion
6678 (save-restriction
6679 (widen)
6680 (delq nil
6681 (mapcar (lambda (o)
6682 (when (eq (overlay-get o 'invisible) 'outline)
6683 (setq beg (overlay-start o)
6684 end (overlay-end o))
6685 (and beg end (> end beg)
6686 (if use-markers
6687 (cons (move-marker (make-marker) beg)
6688 (move-marker (make-marker) end))
6689 (cons beg end)))))
6690 (overlays-in (point-min) (point-max))))))))
6691
6692 (defun org-set-outline-overlay-data (data)
6693 "Create visibility overlays for all positions in DATA.
6694 DATA should have been made by `org-outline-overlay-data'."
6695 (let (o)
6696 (save-excursion
6697 (save-restriction
6698 (widen)
6699 (show-all)
6700 (mapc (lambda (c)
6701 (outline-flag-region (car c) (cdr c) t))
6702 data)))))
6703
6704 ;;; Folding of blocks
6705
6706 (defvar org-hide-block-overlays nil
6707 "Overlays hiding blocks.")
6708 (make-variable-buffer-local 'org-hide-block-overlays)
6709
6710 (defun org-block-map (function &optional start end)
6711 "Call FUNCTION at the head of all source blocks in the current buffer.
6712 Optional arguments START and END can be used to limit the range."
6713 (let ((start (or start (point-min)))
6714 (end (or end (point-max))))
6715 (save-excursion
6716 (goto-char start)
6717 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6718 (save-excursion
6719 (save-match-data
6720 (goto-char (match-beginning 0))
6721 (funcall function)))))))
6722
6723 (defun org-hide-block-toggle-all ()
6724 "Toggle the visibility of all blocks in the current buffer."
6725 (org-block-map #'org-hide-block-toggle))
6726
6727 (defun org-hide-block-all ()
6728 "Fold all blocks in the current buffer."
6729 (interactive)
6730 (org-show-block-all)
6731 (org-block-map #'org-hide-block-toggle-maybe))
6732
6733 (defun org-show-block-all ()
6734 "Unfold all blocks in the current buffer."
6735 (interactive)
6736 (mapc 'delete-overlay org-hide-block-overlays)
6737 (setq org-hide-block-overlays nil))
6738
6739 (defun org-hide-block-toggle-maybe ()
6740 "Toggle visibility of block at point."
6741 (interactive)
6742 (let ((case-fold-search t))
6743 (if (save-excursion
6744 (beginning-of-line 1)
6745 (looking-at org-block-regexp))
6746 (progn (org-hide-block-toggle)
6747 t) ;; to signal that we took action
6748 nil))) ;; to signal that we did not
6749
6750 (defun org-hide-block-toggle (&optional force)
6751 "Toggle the visibility of the current block."
6752 (interactive)
6753 (save-excursion
6754 (beginning-of-line)
6755 (if (re-search-forward org-block-regexp nil t)
6756 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6757 (end (match-end 0)) ;; end of entire body
6758 ov)
6759 (if (memq t (mapcar (lambda (overlay)
6760 (eq (overlay-get overlay 'invisible)
6761 'org-hide-block))
6762 (overlays-at start)))
6763 (if (or (not force) (eq force 'off))
6764 (mapc (lambda (ov)
6765 (when (member ov org-hide-block-overlays)
6766 (setq org-hide-block-overlays
6767 (delq ov org-hide-block-overlays)))
6768 (when (eq (overlay-get ov 'invisible)
6769 'org-hide-block)
6770 (delete-overlay ov)))
6771 (overlays-at start)))
6772 (setq ov (make-overlay start end))
6773 (overlay-put ov 'invisible 'org-hide-block)
6774 ;; make the block accessible to isearch
6775 (overlay-put
6776 ov 'isearch-open-invisible
6777 (lambda (ov)
6778 (when (member ov org-hide-block-overlays)
6779 (setq org-hide-block-overlays
6780 (delq ov org-hide-block-overlays)))
6781 (when (eq (overlay-get ov 'invisible)
6782 'org-hide-block)
6783 (delete-overlay ov))))
6784 (push ov org-hide-block-overlays)))
6785 (error "Not looking at a source block"))))
6786
6787 ;; org-tab-after-check-for-cycling-hook
6788 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6789 ;; Remove overlays when changing major mode
6790 (add-hook 'org-mode-hook
6791 (lambda () (org-add-hook 'change-major-mode-hook
6792 'org-show-block-all 'append 'local)))
6793
6794 ;;; Org-goto
6795
6796 (defvar org-goto-window-configuration nil)
6797 (defvar org-goto-marker nil)
6798 (defvar org-goto-map
6799 (let ((map (make-sparse-keymap)))
6800 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6801 (while (setq cmd (pop cmds))
6802 (substitute-key-definition cmd cmd map global-map)))
6803 (suppress-keymap map)
6804 (org-defkey map "\C-m" 'org-goto-ret)
6805 (org-defkey map [(return)] 'org-goto-ret)
6806 (org-defkey map [(left)] 'org-goto-left)
6807 (org-defkey map [(right)] 'org-goto-right)
6808 (org-defkey map [(control ?g)] 'org-goto-quit)
6809 (org-defkey map "\C-i" 'org-cycle)
6810 (org-defkey map [(tab)] 'org-cycle)
6811 (org-defkey map [(down)] 'outline-next-visible-heading)
6812 (org-defkey map [(up)] 'outline-previous-visible-heading)
6813 (if org-goto-auto-isearch
6814 (if (fboundp 'define-key-after)
6815 (define-key-after map [t] 'org-goto-local-auto-isearch)
6816 nil)
6817 (org-defkey map "q" 'org-goto-quit)
6818 (org-defkey map "n" 'outline-next-visible-heading)
6819 (org-defkey map "p" 'outline-previous-visible-heading)
6820 (org-defkey map "f" 'outline-forward-same-level)
6821 (org-defkey map "b" 'outline-backward-same-level)
6822 (org-defkey map "u" 'outline-up-heading))
6823 (org-defkey map "/" 'org-occur)
6824 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6825 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6826 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6827 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6828 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6829 map))
6830
6831 (defconst org-goto-help
6832 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6833 RET=jump to location [Q]uit and return to previous location
6834 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6835
6836 (defvar org-goto-start-pos) ; dynamically scoped parameter
6837
6838 ;; FIXME: Docstring does not mention both interfaces
6839 (defun org-goto (&optional alternative-interface)
6840 "Look up a different location in the current file, keeping current visibility.
6841
6842 When you want look-up or go to a different location in a document, the
6843 fastest way is often to fold the entire buffer and then dive into the tree.
6844 This method has the disadvantage, that the previous location will be folded,
6845 which may not be what you want.
6846
6847 This command works around this by showing a copy of the current buffer
6848 in an indirect buffer, in overview mode. You can dive into the tree in
6849 that copy, use org-occur and incremental search to find a location.
6850 When pressing RET or `Q', the command returns to the original buffer in
6851 which the visibility is still unchanged. After RET it will also jump to
6852 the location selected in the indirect buffer and expose the headline
6853 hierarchy above."
6854 (interactive "P")
6855 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6856 (org-refile-use-outline-path t)
6857 (org-refile-target-verify-function nil)
6858 (interface
6859 (if (not alternative-interface)
6860 org-goto-interface
6861 (if (eq org-goto-interface 'outline)
6862 'outline-path-completion
6863 'outline)))
6864 (org-goto-start-pos (point))
6865 (selected-point
6866 (if (eq interface 'outline)
6867 (car (org-get-location (current-buffer) org-goto-help))
6868 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6869 (org-refile-check-position pa)
6870 (nth 3 pa)))))
6871 (if selected-point
6872 (progn
6873 (org-mark-ring-push org-goto-start-pos)
6874 (goto-char selected-point)
6875 (if (or (outline-invisible-p) (org-invisible-p2))
6876 (org-show-context 'org-goto)))
6877 (message "Quit"))))
6878
6879 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6880 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6881 (defvar org-goto-local-auto-isearch-map) ; defined below
6882
6883 (defun org-get-location (buf help)
6884 "Let the user select a location in the Org-mode buffer BUF.
6885 This function uses a recursive edit. It returns the selected position
6886 or nil."
6887 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6888 (isearch-hide-immediately nil)
6889 (isearch-search-fun-function
6890 (lambda () 'org-goto-local-search-headings))
6891 (org-goto-selected-point org-goto-exit-command)
6892 (pop-up-frames nil)
6893 (special-display-buffer-names nil)
6894 (special-display-regexps nil)
6895 (special-display-function nil))
6896 (save-excursion
6897 (save-window-excursion
6898 (delete-other-windows)
6899 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6900 (org-pop-to-buffer-same-window
6901 (condition-case nil
6902 (make-indirect-buffer (current-buffer) "*org-goto*")
6903 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6904 (with-output-to-temp-buffer "*Help*"
6905 (princ help))
6906 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6907 (setq buffer-read-only nil)
6908 (let ((org-startup-truncated t)
6909 (org-startup-folded nil)
6910 (org-startup-align-all-tables nil))
6911 (org-mode)
6912 (org-overview))
6913 (setq buffer-read-only t)
6914 (if (and (boundp 'org-goto-start-pos)
6915 (integer-or-marker-p org-goto-start-pos))
6916 (let ((org-show-hierarchy-above t)
6917 (org-show-siblings t)
6918 (org-show-following-heading t))
6919 (goto-char org-goto-start-pos)
6920 (and (outline-invisible-p) (org-show-context)))
6921 (goto-char (point-min)))
6922 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6923 (message "Select location and press RET")
6924 (use-local-map org-goto-map)
6925 (recursive-edit)
6926 ))
6927 (kill-buffer "*org-goto*")
6928 (cons org-goto-selected-point org-goto-exit-command)))
6929
6930 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6931 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6932 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6933 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6934
6935 (defun org-goto-local-search-headings (string bound noerror)
6936 "Search and make sure that any matches are in headlines."
6937 (catch 'return
6938 (while (if isearch-forward
6939 (search-forward string bound noerror)
6940 (search-backward string bound noerror))
6941 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6942 (and (member :headline context)
6943 (not (member :tags context))))
6944 (throw 'return (point))))))
6945
6946 (defun org-goto-local-auto-isearch ()
6947 "Start isearch."
6948 (interactive)
6949 (goto-char (point-min))
6950 (let ((keys (this-command-keys)))
6951 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6952 (isearch-mode t)
6953 (isearch-process-search-char (string-to-char keys)))))
6954
6955 (defun org-goto-ret (&optional arg)
6956 "Finish `org-goto' by going to the new location."
6957 (interactive "P")
6958 (setq org-goto-selected-point (point)
6959 org-goto-exit-command 'return)
6960 (throw 'exit nil))
6961
6962 (defun org-goto-left ()
6963 "Finish `org-goto' by going to the new location."
6964 (interactive)
6965 (if (org-at-heading-p)
6966 (progn
6967 (beginning-of-line 1)
6968 (setq org-goto-selected-point (point)
6969 org-goto-exit-command 'left)
6970 (throw 'exit nil))
6971 (error "Not on a heading")))
6972
6973 (defun org-goto-right ()
6974 "Finish `org-goto' by going to the new location."
6975 (interactive)
6976 (if (org-at-heading-p)
6977 (progn
6978 (setq org-goto-selected-point (point)
6979 org-goto-exit-command 'right)
6980 (throw 'exit nil))
6981 (error "Not on a heading")))
6982
6983 (defun org-goto-quit ()
6984 "Finish `org-goto' without cursor motion."
6985 (interactive)
6986 (setq org-goto-selected-point nil)
6987 (setq org-goto-exit-command 'quit)
6988 (throw 'exit nil))
6989
6990 ;;; Indirect buffer display of subtrees
6991
6992 (defvar org-indirect-dedicated-frame nil
6993 "This is the frame being used for indirect tree display.")
6994 (defvar org-last-indirect-buffer nil)
6995
6996 (defun org-tree-to-indirect-buffer (&optional arg)
6997 "Create indirect buffer and narrow it to current subtree.
6998 With numerical prefix ARG, go up to this level and then take that tree.
6999 If ARG is negative, go up that many levels.
7000 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7001 indirect buffer previously made with this command, to avoid proliferation of
7002 indirect buffers. However, when you call the command with a \
7003 \\[universal-argument] prefix, or
7004 when `org-indirect-buffer-display' is `new-frame', the last buffer
7005 is kept so that you can work with several indirect buffers at the same time.
7006 If `org-indirect-buffer-display' is `dedicated-frame', the \
7007 \\[universal-argument] prefix also
7008 requests that a new frame be made for the new buffer, so that the dedicated
7009 frame is not changed."
7010 (interactive "P")
7011 (let ((cbuf (current-buffer))
7012 (cwin (selected-window))
7013 (pos (point))
7014 beg end level heading ibuf)
7015 (save-excursion
7016 (org-back-to-heading t)
7017 (when (numberp arg)
7018 (setq level (org-outline-level))
7019 (if (< arg 0) (setq arg (+ level arg)))
7020 (while (> (setq level (org-outline-level)) arg)
7021 (outline-up-heading 1 t)))
7022 (setq beg (point)
7023 heading (org-get-heading))
7024 (org-end-of-subtree t t)
7025 (if (org-at-heading-p) (backward-char 1))
7026 (setq end (point)))
7027 (if (and (buffer-live-p org-last-indirect-buffer)
7028 (not (eq org-indirect-buffer-display 'new-frame))
7029 (not arg))
7030 (kill-buffer org-last-indirect-buffer))
7031 (setq ibuf (org-get-indirect-buffer cbuf)
7032 org-last-indirect-buffer ibuf)
7033 (cond
7034 ((or (eq org-indirect-buffer-display 'new-frame)
7035 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7036 (select-frame (make-frame))
7037 (delete-other-windows)
7038 (org-pop-to-buffer-same-window ibuf)
7039 (org-set-frame-title heading))
7040 ((eq org-indirect-buffer-display 'dedicated-frame)
7041 (raise-frame
7042 (select-frame (or (and org-indirect-dedicated-frame
7043 (frame-live-p org-indirect-dedicated-frame)
7044 org-indirect-dedicated-frame)
7045 (setq org-indirect-dedicated-frame (make-frame)))))
7046 (delete-other-windows)
7047 (org-pop-to-buffer-same-window ibuf)
7048 (org-set-frame-title (concat "Indirect: " heading)))
7049 ((eq org-indirect-buffer-display 'current-window)
7050 (org-pop-to-buffer-same-window ibuf))
7051 ((eq org-indirect-buffer-display 'other-window)
7052 (pop-to-buffer ibuf))
7053 (t (error "Invalid value")))
7054 (if (featurep 'xemacs)
7055 (save-excursion (org-mode) (turn-on-font-lock)))
7056 (narrow-to-region beg end)
7057 (show-all)
7058 (goto-char pos)
7059 (run-hook-with-args 'org-cycle-hook 'all)
7060 (and (window-live-p cwin) (select-window cwin))))
7061
7062 (defun org-get-indirect-buffer (&optional buffer)
7063 (setq buffer (or buffer (current-buffer)))
7064 (let ((n 1) (base (buffer-name buffer)) bname)
7065 (while (buffer-live-p
7066 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7067 (setq n (1+ n)))
7068 (condition-case nil
7069 (make-indirect-buffer buffer bname 'clone)
7070 (error (make-indirect-buffer buffer bname)))))
7071
7072 (defun org-set-frame-title (title)
7073 "Set the title of the current frame to the string TITLE."
7074 ;; FIXME: how to name a single frame in XEmacs???
7075 (unless (featurep 'xemacs)
7076 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7077
7078 ;;;; Structure editing
7079
7080 ;;; Inserting headlines
7081
7082 (defun org-previous-line-empty-p ()
7083 (save-excursion
7084 (and (not (bobp))
7085 (or (beginning-of-line 0) t)
7086 (save-match-data
7087 (looking-at "[ \t]*$")))))
7088
7089 (defun org-insert-heading (&optional force-heading invisible-ok)
7090 "Insert a new heading or item with same depth at point.
7091 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7092 If point is at the beginning of a headline, insert a sibling before the
7093 current headline. If point is not at the beginning, split the line,
7094 create the new headline with the text in the current line after point
7095 \(but see also the variable `org-M-RET-may-split-line').
7096
7097 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7098 This is important for non-interactive uses of the command."
7099 (interactive "P")
7100 (if (or (= (buffer-size) 0)
7101 (and (not (save-excursion
7102 (and (ignore-errors (org-back-to-heading invisible-ok))
7103 (org-at-heading-p))))
7104 (or force-heading (not (org-in-item-p)))))
7105 (progn
7106 (insert "\n* ")
7107 (run-hooks 'org-insert-heading-hook))
7108 (when (or force-heading (not (org-insert-item)))
7109 (let* ((empty-line-p nil)
7110 (level nil)
7111 (on-heading (org-at-heading-p))
7112 (head (save-excursion
7113 (condition-case nil
7114 (progn
7115 (org-back-to-heading invisible-ok)
7116 (when (and (not on-heading)
7117 (featurep 'org-inlinetask)
7118 (integerp org-inlinetask-min-level)
7119 (>= (length (match-string 0))
7120 org-inlinetask-min-level))
7121 ;; Find a heading level before the inline task
7122 (while (and (setq level (org-up-heading-safe))
7123 (>= level org-inlinetask-min-level)))
7124 (if (org-at-heading-p)
7125 (org-back-to-heading invisible-ok)
7126 (error "This should not happen")))
7127 (setq empty-line-p (org-previous-line-empty-p))
7128 (match-string 0))
7129 (error "*"))))
7130 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7131 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7132 pos hide-previous previous-pos)
7133 (cond
7134 ((and (org-at-heading-p) (bolp)
7135 (or (bobp)
7136 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7137 ;; insert before the current line
7138 (open-line (if blank 2 1)))
7139 ((and (bolp)
7140 (not org-insert-heading-respect-content)
7141 (or (bobp)
7142 (save-excursion
7143 (backward-char 1) (not (outline-invisible-p)))))
7144 ;; insert right here
7145 nil)
7146 (t
7147 ;; somewhere in the line
7148 (save-excursion
7149 (setq previous-pos (point-at-bol))
7150 (end-of-line)
7151 (setq hide-previous (outline-invisible-p)))
7152 (and org-insert-heading-respect-content (org-show-subtree))
7153 (let ((split
7154 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7155 (save-excursion
7156 (let ((p (point)))
7157 (goto-char (point-at-bol))
7158 (and (looking-at org-complex-heading-regexp)
7159 (match-beginning 4)
7160 (> p (match-beginning 4)))))))
7161 tags pos)
7162 (cond
7163 (org-insert-heading-respect-content
7164 (org-end-of-subtree nil t)
7165 (when (featurep 'org-inlinetask)
7166 (while (and (not (eobp))
7167 (looking-at "\\(\\*+\\)[ \t]+")
7168 (>= (length (match-string 1))
7169 org-inlinetask-min-level))
7170 (org-end-of-subtree nil t)))
7171 (or (bolp) (newline))
7172 (or (org-previous-line-empty-p)
7173 (and blank (newline)))
7174 (open-line 1))
7175 ((org-at-heading-p)
7176 (when hide-previous
7177 (show-children)
7178 (org-show-entry))
7179 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7180 (setq tags (and (match-end 2) (match-string 2)))
7181 (and (match-end 1)
7182 (delete-region (match-beginning 1) (match-end 1)))
7183 (setq pos (point-at-bol))
7184 (or split (end-of-line 1))
7185 (delete-horizontal-space)
7186 (if (string-match "\\`\\*+\\'"
7187 (buffer-substring (point-at-bol) (point)))
7188 (insert " "))
7189 (newline (if blank 2 1))
7190 (when tags
7191 (save-excursion
7192 (goto-char pos)
7193 (end-of-line 1)
7194 (insert " " tags)
7195 (org-set-tags nil 'align))))
7196 (t
7197 (or split (end-of-line 1))
7198 (newline (if blank 2 1)))))))
7199 (insert head) (just-one-space)
7200 (setq pos (point))
7201 (end-of-line 1)
7202 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7203 (when (and org-insert-heading-respect-content hide-previous)
7204 (save-excursion
7205 (goto-char previous-pos)
7206 (hide-subtree)))
7207 (run-hooks 'org-insert-heading-hook)))))
7208
7209 (defun org-get-heading (&optional no-tags no-todo)
7210 "Return the heading of the current entry, without the stars.
7211 When NO-TAGS is non-nil, don't include tags.
7212 When NO-TODO is non-nil, don't include TODO keywords."
7213 (save-excursion
7214 (org-back-to-heading t)
7215 (cond
7216 ((and no-tags no-todo)
7217 (looking-at org-complex-heading-regexp)
7218 (match-string 4))
7219 (no-tags
7220 (looking-at (concat org-outline-regexp
7221 "\\(.*?\\)"
7222 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7223 (match-string 1))
7224 (no-todo
7225 (looking-at org-todo-line-regexp)
7226 (match-string 3))
7227 (t (looking-at org-heading-regexp)
7228 (match-string 2)))))
7229
7230 (defun org-heading-components ()
7231 "Return the components of the current heading.
7232 This is a list with the following elements:
7233 - the level as an integer
7234 - the reduced level, different if `org-odd-levels-only' is set.
7235 - the TODO keyword, or nil
7236 - the priority character, like ?A, or nil if no priority is given
7237 - the headline text itself, or the tags string if no headline text
7238 - the tags string, or nil."
7239 (save-excursion
7240 (org-back-to-heading t)
7241 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7242 (list (length (match-string 1))
7243 (org-reduced-level (length (match-string 1)))
7244 (org-match-string-no-properties 2)
7245 (and (match-end 3) (aref (match-string 3) 2))
7246 (org-match-string-no-properties 4)
7247 (org-match-string-no-properties 5)))))
7248
7249 (defun org-get-entry ()
7250 "Get the entry text, after heading, entire subtree."
7251 (save-excursion
7252 (org-back-to-heading t)
7253 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7254
7255 (defun org-insert-heading-after-current ()
7256 "Insert a new heading with same level as current, after current subtree."
7257 (interactive)
7258 (org-back-to-heading)
7259 (org-insert-heading)
7260 (org-move-subtree-down)
7261 (end-of-line 1))
7262
7263 (defun org-insert-heading-respect-content ()
7264 (interactive)
7265 (let ((org-insert-heading-respect-content t))
7266 (org-insert-heading t)))
7267
7268 (defun org-insert-todo-heading-respect-content (&optional force-state)
7269 (interactive "P")
7270 (let ((org-insert-heading-respect-content t))
7271 (org-insert-todo-heading force-state t)))
7272
7273 (defun org-insert-todo-heading (arg &optional force-heading)
7274 "Insert a new heading with the same level and TODO state as current heading.
7275 If the heading has no TODO state, or if the state is DONE, use the first
7276 state (TODO by default). Also with prefix arg, force first state."
7277 (interactive "P")
7278 (when (or force-heading (not (org-insert-item 'checkbox)))
7279 (org-insert-heading force-heading)
7280 (save-excursion
7281 (org-back-to-heading)
7282 (outline-previous-heading)
7283 (looking-at org-todo-line-regexp))
7284 (let*
7285 ((new-mark-x
7286 (if (or arg
7287 (not (match-beginning 2))
7288 (member (match-string 2) org-done-keywords))
7289 (car org-todo-keywords-1)
7290 (match-string 2)))
7291 (new-mark
7292 (or
7293 (run-hook-with-args-until-success
7294 'org-todo-get-default-hook new-mark-x nil)
7295 new-mark-x)))
7296 (beginning-of-line 1)
7297 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7298 (if org-treat-insert-todo-heading-as-state-change
7299 (org-todo new-mark)
7300 (insert new-mark " "))))
7301 (when org-provide-todo-statistics
7302 (org-update-parent-todo-statistics))))
7303
7304 (defun org-insert-subheading (arg)
7305 "Insert a new subheading and demote it.
7306 Works for outline headings and for plain lists alike."
7307 (interactive "P")
7308 (org-insert-heading arg)
7309 (cond
7310 ((org-at-heading-p) (org-do-demote))
7311 ((org-at-item-p) (org-indent-item))))
7312
7313 (defun org-insert-todo-subheading (arg)
7314 "Insert a new subheading with TODO keyword or checkbox and demote it.
7315 Works for outline headings and for plain lists alike."
7316 (interactive "P")
7317 (org-insert-todo-heading arg)
7318 (cond
7319 ((org-at-heading-p) (org-do-demote))
7320 ((org-at-item-p) (org-indent-item))))
7321
7322 ;;; Promotion and Demotion
7323
7324 (defvar org-after-demote-entry-hook nil
7325 "Hook run after an entry has been demoted.
7326 The cursor will be at the beginning of the entry.
7327 When a subtree is being demoted, the hook will be called for each node.")
7328
7329 (defvar org-after-promote-entry-hook nil
7330 "Hook run after an entry has been promoted.
7331 The cursor will be at the beginning of the entry.
7332 When a subtree is being promoted, the hook will be called for each node.")
7333
7334 (defun org-promote-subtree ()
7335 "Promote the entire subtree.
7336 See also `org-promote'."
7337 (interactive)
7338 (save-excursion
7339 (org-with-limited-levels (org-map-tree 'org-promote)))
7340 (org-fix-position-after-promote))
7341
7342 (defun org-demote-subtree ()
7343 "Demote the entire subtree. See `org-demote'.
7344 See also `org-promote'."
7345 (interactive)
7346 (save-excursion
7347 (org-with-limited-levels (org-map-tree 'org-demote)))
7348 (org-fix-position-after-promote))
7349
7350
7351 (defun org-do-promote ()
7352 "Promote the current heading higher up the tree.
7353 If the region is active in `transient-mark-mode', promote all headings
7354 in the region."
7355 (interactive)
7356 (save-excursion
7357 (if (org-region-active-p)
7358 (org-map-region 'org-promote (region-beginning) (region-end))
7359 (org-promote)))
7360 (org-fix-position-after-promote))
7361
7362 (defun org-do-demote ()
7363 "Demote the current heading lower down the tree.
7364 If the region is active in `transient-mark-mode', demote all headings
7365 in the region."
7366 (interactive)
7367 (save-excursion
7368 (if (org-region-active-p)
7369 (org-map-region 'org-demote (region-beginning) (region-end))
7370 (org-demote)))
7371 (org-fix-position-after-promote))
7372
7373 (defun org-fix-position-after-promote ()
7374 "Make sure that after pro/demotion cursor position is right."
7375 (let ((pos (point)))
7376 (when (save-excursion
7377 (beginning-of-line 1)
7378 (looking-at org-todo-line-regexp)
7379 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7380 (cond ((eobp) (insert " "))
7381 ((eolp) (insert " "))
7382 ((equal (char-after) ?\ ) (forward-char 1))))))
7383
7384 (defun org-current-level ()
7385 "Return the level of the current entry, or nil if before the first headline.
7386 The level is the number of stars at the beginning of the headline."
7387 (save-excursion
7388 (org-with-limited-levels
7389 (if (ignore-errors (org-back-to-heading t))
7390 (funcall outline-level)))))
7391
7392 (defun org-get-previous-line-level ()
7393 "Return the outline depth of the last headline before the current line.
7394 Returns 0 for the first headline in the buffer, and nil if before the
7395 first headline."
7396 (let ((current-level (org-current-level))
7397 (prev-level (when (> (line-number-at-pos) 1)
7398 (save-excursion
7399 (beginning-of-line 0)
7400 (org-current-level)))))
7401 (cond ((null current-level) nil) ; Before first headline
7402 ((null prev-level) 0) ; At first headline
7403 (prev-level))))
7404
7405 (defun org-reduced-level (l)
7406 "Compute the effective level of a heading.
7407 This takes into account the setting of `org-odd-levels-only'."
7408 (cond
7409 ((zerop l) 0)
7410 (org-odd-levels-only (1+ (floor (/ l 2))))
7411 (t l)))
7412
7413 (defun org-level-increment ()
7414 "Return the number of stars that will be added or removed at a
7415 time to headlines when structure editing, based on the value of
7416 `org-odd-levels-only'."
7417 (if org-odd-levels-only 2 1))
7418
7419 (defun org-get-valid-level (level &optional change)
7420 "Rectify a level change under the influence of `org-odd-levels-only'
7421 LEVEL is a current level, CHANGE is by how much the level should be
7422 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7423 even level numbers will become the next higher odd number."
7424 (if org-odd-levels-only
7425 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7426 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7427 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7428 (max 1 (+ level (or change 0)))))
7429
7430 (if (boundp 'define-obsolete-function-alias)
7431 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7432 (define-obsolete-function-alias 'org-get-legal-level
7433 'org-get-valid-level)
7434 (define-obsolete-function-alias 'org-get-legal-level
7435 'org-get-valid-level "23.1")))
7436
7437 (defun org-promote ()
7438 "Promote the current heading higher up the tree.
7439 If the region is active in `transient-mark-mode', promote all headings
7440 in the region."
7441 (org-back-to-heading t)
7442 (let* ((level (save-match-data (funcall outline-level)))
7443 (after-change-functions (remove 'flyspell-after-change-function
7444 after-change-functions))
7445 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7446 (diff (abs (- level (length up-head) -1))))
7447 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7448 (replace-match up-head nil t)
7449 ;; Fixup tag positioning
7450 (and org-auto-align-tags (org-set-tags nil t))
7451 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7452 (run-hooks 'org-after-promote-entry-hook)))
7453
7454 (defun org-demote ()
7455 "Demote the current heading lower down the tree.
7456 If the region is active in `transient-mark-mode', demote all headings
7457 in the region."
7458 (org-back-to-heading t)
7459 (let* ((level (save-match-data (funcall outline-level)))
7460 (after-change-functions (remove 'flyspell-after-change-function
7461 after-change-functions))
7462 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7463 (diff (abs (- level (length down-head) -1))))
7464 (replace-match down-head nil t)
7465 ;; Fixup tag positioning
7466 (and org-auto-align-tags (org-set-tags nil t))
7467 (if org-adapt-indentation (org-fixup-indentation diff))
7468 (run-hooks 'org-after-demote-entry-hook)))
7469
7470 (defun org-cycle-level ()
7471 "Cycle the level of an empty headline through possible states.
7472 This goes first to child, then to parent, level, then up the hierarchy.
7473 After top level, it switches back to sibling level."
7474 (interactive)
7475 (let ((org-adapt-indentation nil))
7476 (when (org-point-at-end-of-empty-headline)
7477 (setq this-command 'org-cycle-level) ; Only needed for caching
7478 (let ((cur-level (org-current-level))
7479 (prev-level (org-get-previous-line-level)))
7480 (cond
7481 ;; If first headline in file, promote to top-level.
7482 ((= prev-level 0)
7483 (loop repeat (/ (- cur-level 1) (org-level-increment))
7484 do (org-do-promote)))
7485 ;; If same level as prev, demote one.
7486 ((= prev-level cur-level)
7487 (org-do-demote))
7488 ;; If parent is top-level, promote to top level if not already.
7489 ((= prev-level 1)
7490 (loop repeat (/ (- cur-level 1) (org-level-increment))
7491 do (org-do-promote)))
7492 ;; If top-level, return to prev-level.
7493 ((= cur-level 1)
7494 (loop repeat (/ (- prev-level 1) (org-level-increment))
7495 do (org-do-demote)))
7496 ;; If less than prev-level, promote one.
7497 ((< cur-level prev-level)
7498 (org-do-promote))
7499 ;; If deeper than prev-level, promote until higher than
7500 ;; prev-level.
7501 ((> cur-level prev-level)
7502 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7503 do (org-do-promote))))
7504 t))))
7505
7506 (defun org-map-tree (fun)
7507 "Call FUN for every heading underneath the current one."
7508 (org-back-to-heading)
7509 (let ((level (funcall outline-level)))
7510 (save-excursion
7511 (funcall fun)
7512 (while (and (progn
7513 (outline-next-heading)
7514 (> (funcall outline-level) level))
7515 (not (eobp)))
7516 (funcall fun)))))
7517
7518 (defun org-map-region (fun beg end)
7519 "Call FUN for every heading between BEG and END."
7520 (let ((org-ignore-region t))
7521 (save-excursion
7522 (setq end (copy-marker end))
7523 (goto-char beg)
7524 (if (and (re-search-forward org-outline-regexp-bol nil t)
7525 (< (point) end))
7526 (funcall fun))
7527 (while (and (progn
7528 (outline-next-heading)
7529 (< (point) end))
7530 (not (eobp)))
7531 (funcall fun)))))
7532
7533 (defvar org-property-end-re) ; silence byte-compiler
7534 (defun org-fixup-indentation (diff)
7535 "Change the indentation in the current entry by DIFF.
7536 However, if any line in the current entry has no indentation, or if it
7537 would end up with no indentation after the change, nothing at all is done."
7538 (save-excursion
7539 (let ((end (save-excursion (outline-next-heading)
7540 (point-marker)))
7541 (prohibit (if (> diff 0)
7542 "^\\S-"
7543 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7544 col)
7545 (unless (save-excursion (end-of-line 1)
7546 (re-search-forward prohibit end t))
7547 (while (and (< (point) end)
7548 (re-search-forward "^[ \t]+" end t))
7549 (goto-char (match-end 0))
7550 (setq col (current-column))
7551 (if (< diff 0) (replace-match ""))
7552 (org-indent-to-column (+ diff col))))
7553 (move-marker end nil))))
7554
7555 (defun org-convert-to-odd-levels ()
7556 "Convert an org-mode file with all levels allowed to one with odd levels.
7557 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7558 level 5 etc."
7559 (interactive)
7560 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7561 (let ((outline-level 'org-outline-level)
7562 (org-odd-levels-only nil) n)
7563 (save-excursion
7564 (goto-char (point-min))
7565 (while (re-search-forward "^\\*\\*+ " nil t)
7566 (setq n (- (length (match-string 0)) 2))
7567 (while (>= (setq n (1- n)) 0)
7568 (org-demote))
7569 (end-of-line 1))))))
7570
7571 (defun org-convert-to-oddeven-levels ()
7572 "Convert an org-mode file with only odd levels to one with odd/even levels.
7573 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7574 file contains a section with an even level, conversion would
7575 destroy the structure of the file. An error is signaled in this
7576 case."
7577 (interactive)
7578 (goto-char (point-min))
7579 ;; First check if there are no even levels
7580 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7581 (org-show-context t)
7582 (error "Not all levels are odd in this file. Conversion not possible"))
7583 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7584 (let ((outline-regexp org-outline-regexp)
7585 (outline-level 'org-outline-level)
7586 (org-odd-levels-only nil) n)
7587 (save-excursion
7588 (goto-char (point-min))
7589 (while (re-search-forward "^\\*\\*+ " nil t)
7590 (setq n (/ (1- (length (match-string 0))) 2))
7591 (while (>= (setq n (1- n)) 0)
7592 (org-promote))
7593 (end-of-line 1))))))
7594
7595 (defun org-tr-level (n)
7596 "Make N odd if required."
7597 (if org-odd-levels-only (1+ (/ n 2)) n))
7598
7599 ;;; Vertical tree motion, cutting and pasting of subtrees
7600
7601 (defun org-move-subtree-up (&optional arg)
7602 "Move the current subtree up past ARG headlines of the same level."
7603 (interactive "p")
7604 (org-move-subtree-down (- (prefix-numeric-value arg))))
7605
7606 (defun org-move-subtree-down (&optional arg)
7607 "Move the current subtree down past ARG headlines of the same level."
7608 (interactive "p")
7609 (setq arg (prefix-numeric-value arg))
7610 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7611 'org-get-last-sibling))
7612 (ins-point (make-marker))
7613 (cnt (abs arg))
7614 (col (current-column))
7615 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7616 ;; Select the tree
7617 (org-back-to-heading)
7618 (setq beg0 (point))
7619 (save-excursion
7620 (setq ne-beg (org-back-over-empty-lines))
7621 (setq beg (point)))
7622 (save-match-data
7623 (save-excursion (outline-end-of-heading)
7624 (setq folded (outline-invisible-p)))
7625 (outline-end-of-subtree))
7626 (outline-next-heading)
7627 (setq ne-end (org-back-over-empty-lines))
7628 (setq end (point))
7629 (goto-char beg0)
7630 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7631 ;; include less whitespace
7632 (save-excursion
7633 (goto-char beg)
7634 (forward-line (- ne-beg ne-end))
7635 (setq beg (point))))
7636 ;; Find insertion point, with error handling
7637 (while (> cnt 0)
7638 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7639 (progn (goto-char beg0)
7640 (error "Cannot move past superior level or buffer limit")))
7641 (setq cnt (1- cnt)))
7642 (if (> arg 0)
7643 ;; Moving forward - still need to move over subtree
7644 (progn (org-end-of-subtree t t)
7645 (save-excursion
7646 (org-back-over-empty-lines)
7647 (or (bolp) (newline)))))
7648 (setq ne-ins (org-back-over-empty-lines))
7649 (move-marker ins-point (point))
7650 (setq txt (buffer-substring beg end))
7651 (org-save-markers-in-region beg end)
7652 (delete-region beg end)
7653 (org-remove-empty-overlays-at beg)
7654 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7655 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7656 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7657 (let ((bbb (point)))
7658 (insert-before-markers txt)
7659 (org-reinstall-markers-in-region bbb)
7660 (move-marker ins-point bbb))
7661 (or (bolp) (insert "\n"))
7662 (setq ins-end (point))
7663 (goto-char ins-point)
7664 (org-skip-whitespace)
7665 (when (and (< arg 0)
7666 (org-first-sibling-p)
7667 (> ne-ins ne-beg))
7668 ;; Move whitespace back to beginning
7669 (save-excursion
7670 (goto-char ins-end)
7671 (let ((kill-whole-line t))
7672 (kill-line (- ne-ins ne-beg)) (point)))
7673 (insert (make-string (- ne-ins ne-beg) ?\n)))
7674 (move-marker ins-point nil)
7675 (if folded
7676 (hide-subtree)
7677 (org-show-entry)
7678 (show-children)
7679 (org-cycle-hide-drawers 'children))
7680 (org-clean-visibility-after-subtree-move)
7681 ;; move back to the initial column we were at
7682 (move-to-column col)))
7683
7684 (defvar org-subtree-clip ""
7685 "Clipboard for cut and paste of subtrees.
7686 This is actually only a copy of the kill, because we use the normal kill
7687 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7688
7689 (defvar org-subtree-clip-folded nil
7690 "Was the last copied subtree folded?
7691 This is used to fold the tree back after pasting.")
7692
7693 (defun org-cut-subtree (&optional n)
7694 "Cut the current subtree into the clipboard.
7695 With prefix arg N, cut this many sequential subtrees.
7696 This is a short-hand for marking the subtree and then cutting it."
7697 (interactive "p")
7698 (org-copy-subtree n 'cut))
7699
7700 (defun org-copy-subtree (&optional n cut force-store-markers)
7701 "Cut the current subtree into the clipboard.
7702 With prefix arg N, cut this many sequential subtrees.
7703 This is a short-hand for marking the subtree and then copying it.
7704 If CUT is non-nil, actually cut the subtree.
7705 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7706 of some markers in the region, even if CUT is non-nil. This is
7707 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7708 (interactive "p")
7709 (let (beg end folded (beg0 (point)))
7710 (if (org-called-interactively-p 'any)
7711 (org-back-to-heading nil) ; take what looks like a subtree
7712 (org-back-to-heading t)) ; take what is really there
7713 (org-back-over-empty-lines)
7714 (setq beg (point))
7715 (skip-chars-forward " \t\r\n")
7716 (save-match-data
7717 (save-excursion (outline-end-of-heading)
7718 (setq folded (outline-invisible-p)))
7719 (condition-case nil
7720 (org-forward-same-level (1- n) t)
7721 (error nil))
7722 (org-end-of-subtree t t))
7723 (org-back-over-empty-lines)
7724 (setq end (point))
7725 (goto-char beg0)
7726 (when (> end beg)
7727 (setq org-subtree-clip-folded folded)
7728 (when (or cut force-store-markers)
7729 (org-save-markers-in-region beg end))
7730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7731 (setq org-subtree-clip (current-kill 0))
7732 (message "%s: Subtree(s) with %d characters"
7733 (if cut "Cut" "Copied")
7734 (length org-subtree-clip)))))
7735
7736 (defun org-paste-subtree (&optional level tree for-yank)
7737 "Paste the clipboard as a subtree, with modification of headline level.
7738 The entire subtree is promoted or demoted in order to match a new headline
7739 level.
7740
7741 If the cursor is at the beginning of a headline, the same level as
7742 that headline is used to paste the tree
7743
7744 If not, the new level is derived from the *visible* headings
7745 before and after the insertion point, and taken to be the inferior headline
7746 level of the two. So if the previous visible heading is level 3 and the
7747 next is level 4 (or vice versa), level 4 will be used for insertion.
7748 This makes sure that the subtree remains an independent subtree and does
7749 not swallow low level entries.
7750
7751 You can also force a different level, either by using a numeric prefix
7752 argument, or by inserting the heading marker by hand. For example, if the
7753 cursor is after \"*****\", then the tree will be shifted to level 5.
7754
7755 If optional TREE is given, use this text instead of the kill ring.
7756
7757 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7758 move back over whitespace before inserting, and move point to the end of
7759 the inserted text when done."
7760 (interactive "P")
7761 (setq tree (or tree (and kill-ring (current-kill 0))))
7762 (unless (org-kill-is-subtree-p tree)
7763 (error "%s"
7764 (substitute-command-keys
7765 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7766 (org-with-limited-levels
7767 (let* ((visp (not (outline-invisible-p)))
7768 (txt tree)
7769 (^re_ "\\(\\*+\\)[ \t]*")
7770 (old-level (if (string-match org-outline-regexp-bol txt)
7771 (- (match-end 0) (match-beginning 0) 1)
7772 -1))
7773 (force-level (cond (level (prefix-numeric-value level))
7774 ((and (looking-at "[ \t]*$")
7775 (string-match
7776 "^\\*+$" (buffer-substring
7777 (point-at-bol) (point))))
7778 (- (match-end 1) (match-beginning 1)))
7779 ((and (bolp)
7780 (looking-at org-outline-regexp))
7781 (- (match-end 0) (point) 1))
7782 (t nil)))
7783 (previous-level (save-excursion
7784 (condition-case nil
7785 (progn
7786 (outline-previous-visible-heading 1)
7787 (if (looking-at ^re_)
7788 (- (match-end 0) (match-beginning 0) 1)
7789 1))
7790 (error 1))))
7791 (next-level (save-excursion
7792 (condition-case nil
7793 (progn
7794 (or (looking-at org-outline-regexp)
7795 (outline-next-visible-heading 1))
7796 (if (looking-at ^re_)
7797 (- (match-end 0) (match-beginning 0) 1)
7798 1))
7799 (error 1))))
7800 (new-level (or force-level (max previous-level next-level)))
7801 (shift (if (or (= old-level -1)
7802 (= new-level -1)
7803 (= old-level new-level))
7804 0
7805 (- new-level old-level)))
7806 (delta (if (> shift 0) -1 1))
7807 (func (if (> shift 0) 'org-demote 'org-promote))
7808 (org-odd-levels-only nil)
7809 beg end newend)
7810 ;; Remove the forced level indicator
7811 (if force-level
7812 (delete-region (point-at-bol) (point)))
7813 ;; Paste
7814 (beginning-of-line (if (bolp) 1 2))
7815 (unless for-yank (org-back-over-empty-lines))
7816 (setq beg (point))
7817 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7818 (insert-before-markers txt)
7819 (unless (string-match "\n\\'" txt) (insert "\n"))
7820 (setq newend (point))
7821 (org-reinstall-markers-in-region beg)
7822 (setq end (point))
7823 (goto-char beg)
7824 (skip-chars-forward " \t\n\r")
7825 (setq beg (point))
7826 (if (and (outline-invisible-p) visp)
7827 (save-excursion (outline-show-heading)))
7828 ;; Shift if necessary
7829 (unless (= shift 0)
7830 (save-restriction
7831 (narrow-to-region beg end)
7832 (while (not (= shift 0))
7833 (org-map-region func (point-min) (point-max))
7834 (setq shift (+ delta shift)))
7835 (goto-char (point-min))
7836 (setq newend (point-max))))
7837 (when (or (org-called-interactively-p 'interactive) for-yank)
7838 (message "Clipboard pasted as level %d subtree" new-level))
7839 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7840 kill-ring
7841 (eq org-subtree-clip (current-kill 0))
7842 org-subtree-clip-folded)
7843 ;; The tree was folded before it was killed/copied
7844 (hide-subtree))
7845 (and for-yank (goto-char newend)))))
7846
7847 (defun org-kill-is-subtree-p (&optional txt)
7848 "Check if the current kill is an outline subtree, or a set of trees.
7849 Returns nil if kill does not start with a headline, or if the first
7850 headline level is not the largest headline level in the tree.
7851 So this will actually accept several entries of equal levels as well,
7852 which is OK for `org-paste-subtree'.
7853 If optional TXT is given, check this string instead of the current kill."
7854 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7855 (re (org-get-limited-outline-regexp))
7856 (^re (concat "^" re))
7857 (start-level (and kill
7858 (string-match
7859 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7860 kill)
7861 (- (match-end 2) (match-beginning 2) 1)))
7862 (start (1+ (or (match-beginning 2) -1))))
7863 (if (not start-level)
7864 (progn
7865 nil) ;; does not even start with a heading
7866 (catch 'exit
7867 (while (setq start (string-match ^re kill (1+ start)))
7868 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7869 (throw 'exit nil)))
7870 t))))
7871
7872 (defvar org-markers-to-move nil
7873 "Markers that should be moved with a cut-and-paste operation.
7874 Those markers are stored together with their positions relative to
7875 the start of the region.")
7876
7877 (defun org-save-markers-in-region (beg end)
7878 "Check markers in region.
7879 If these markers are between BEG and END, record their position relative
7880 to BEG, so that after moving the block of text, we can put the markers back
7881 into place.
7882 This function gets called just before an entry or tree gets cut from the
7883 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7884 called immediately, to move the markers with the entries."
7885 (setq org-markers-to-move nil)
7886 (when (featurep 'org-clock)
7887 (org-clock-save-markers-for-cut-and-paste beg end))
7888 (when (featurep 'org-agenda)
7889 (org-agenda-save-markers-for-cut-and-paste beg end)))
7890
7891 (defun org-check-and-save-marker (marker beg end)
7892 "Check if MARKER is between BEG and END.
7893 If yes, remember the marker and the distance to BEG."
7894 (when (and (marker-buffer marker)
7895 (equal (marker-buffer marker) (current-buffer)))
7896 (if (and (>= marker beg) (< marker end))
7897 (push (cons marker (- marker beg)) org-markers-to-move))))
7898
7899 (defun org-reinstall-markers-in-region (beg)
7900 "Move all remembered markers to their position relative to BEG."
7901 (mapc (lambda (x)
7902 (move-marker (car x) (+ beg (cdr x))))
7903 org-markers-to-move)
7904 (setq org-markers-to-move nil))
7905
7906 (defun org-narrow-to-subtree ()
7907 "Narrow buffer to the current subtree."
7908 (interactive)
7909 (save-excursion
7910 (save-match-data
7911 (org-with-limited-levels
7912 (narrow-to-region
7913 (progn (org-back-to-heading t) (point))
7914 (progn (org-end-of-subtree t t)
7915 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7916 (point)))))))
7917
7918 (defun org-narrow-to-block ()
7919 "Narrow buffer to the current block."
7920 (interactive)
7921 (let* ((case-fold-search t)
7922 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7923 "^[ \t]*#\\+end_.*")))
7924 (if blockp
7925 (narrow-to-region (car blockp) (cdr blockp))
7926 (error "Not in a block"))))
7927
7928 (eval-when-compile
7929 (defvar org-property-drawer-re))
7930
7931 (defvar org-property-start-re) ;; defined below
7932 (defun org-clone-subtree-with-time-shift (n &optional shift)
7933 "Clone the task (subtree) at point N times.
7934 The clones will be inserted as siblings.
7935
7936 In interactive use, the user will be prompted for the number of
7937 clones to be produced, and for a time SHIFT, which may be a
7938 repeater as used in time stamps, for example `+3d'.
7939
7940 When a valid repeater is given and the entry contains any time
7941 stamps, the clones will become a sequence in time, with time
7942 stamps in the subtree shifted for each clone produced. If SHIFT
7943 is nil or the empty string, time stamps will be left alone. The
7944 ID property of the original subtree is removed.
7945
7946 If the original subtree did contain time stamps with a repeater,
7947 the following will happen:
7948 - the repeater will be removed in each clone
7949 - an additional clone will be produced, with the current, unshifted
7950 date(s) in the entry.
7951 - the original entry will be placed *after* all the clones, with
7952 repeater intact.
7953 - the start days in the repeater in the original entry will be shifted
7954 to past the last clone.
7955 In this way you can spell out a number of instances of a repeating task,
7956 and still retain the repeater to cover future instances of the task."
7957 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7958 (let (beg end template task idprop
7959 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7960 (drawer-re org-drawer-regexp))
7961 (if (not (and (integerp n) (> n 0)))
7962 (error "Invalid number of replications %s" n))
7963 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7964 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7965 shift)))
7966 (error "Invalid shift specification %s" shift))
7967 (when doshift
7968 (setq shift-n (string-to-number (match-string 1 shift))
7969 shift-what (cdr (assoc (match-string 2 shift)
7970 '(("d" . day) ("w" . week)
7971 ("m" . month) ("y" . year))))))
7972 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7973 (setq nmin 1 nmax n)
7974 (org-back-to-heading t)
7975 (setq beg (point))
7976 (setq idprop (org-entry-get nil "ID"))
7977 (org-end-of-subtree t t)
7978 (or (bolp) (insert "\n"))
7979 (setq end (point))
7980 (setq template (buffer-substring beg end))
7981 (when (and doshift
7982 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7983 (delete-region beg end)
7984 (setq end beg)
7985 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7986 (goto-char end)
7987 (loop for n from nmin to nmax do
7988 ;; prepare clone
7989 (with-temp-buffer
7990 (insert template)
7991 (org-mode)
7992 (goto-char (point-min))
7993 (org-show-subtree)
7994 (and idprop (if org-clone-delete-id
7995 (org-entry-delete nil "ID")
7996 (org-id-get-create t)))
7997 (unless (= n 0)
7998 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7999 (kill-whole-line))
8000 (goto-char (point-min))
8001 (while (re-search-forward drawer-re nil t)
8002 (mapc (lambda (d)
8003 (org-remove-empty-drawer-at d (point))) org-drawers)))
8004 (goto-char (point-min))
8005 (when doshift
8006 (while (re-search-forward org-ts-regexp-both nil t)
8007 (org-timestamp-change (* n shift-n) shift-what))
8008 (unless (= n n-no-remove)
8009 (goto-char (point-min))
8010 (while (re-search-forward org-ts-regexp nil t)
8011 (save-excursion
8012 (goto-char (match-beginning 0))
8013 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8014 (delete-region (match-beginning 1) (match-end 1)))))))
8015 (setq task (buffer-string)))
8016 (insert task))
8017 (goto-char beg)))
8018
8019 ;;; Outline Sorting
8020
8021 (defun org-sort (with-case)
8022 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8023 Optional argument WITH-CASE means sort case-sensitively."
8024 (interactive "P")
8025 (cond
8026 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8027 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8028 (t
8029 (org-call-with-arg 'org-sort-entries with-case))))
8030
8031 (defun org-sort-remove-invisible (s)
8032 (remove-text-properties 0 (length s) org-rm-props s)
8033 (while (string-match org-bracket-link-regexp s)
8034 (setq s (replace-match (if (match-end 2)
8035 (match-string 3 s)
8036 (match-string 1 s)) t t s)))
8037 s)
8038
8039 (defvar org-priority-regexp) ; defined later in the file
8040
8041 (defvar org-after-sorting-entries-or-items-hook nil
8042 "Hook that is run after a bunch of entries or items have been sorted.
8043 When children are sorted, the cursor is in the parent line when this
8044 hook gets called. When a region or a plain list is sorted, the cursor
8045 will be in the first entry of the sorted region/list.")
8046
8047 (defun org-sort-entries
8048 (&optional with-case sorting-type getkey-func compare-func property)
8049 "Sort entries on a certain level of an outline tree.
8050 If there is an active region, the entries in the region are sorted.
8051 Else, if the cursor is before the first entry, sort the top-level items.
8052 Else, the children of the entry at point are sorted.
8053
8054 Sorting can be alphabetically, numerically, by date/time as given by
8055 a time stamp, by a property or by priority.
8056
8057 The command prompts for the sorting type unless it has been given to the
8058 function through the SORTING-TYPE argument, which needs to be a character,
8059 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8060 precise meaning of each character:
8061
8062 n Numerically, by converting the beginning of the entry/item to a number.
8063 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8064 t By date/time, either the first active time stamp in the entry, or, if
8065 none exist, by the first inactive one.
8066 s By the scheduled date/time.
8067 d By deadline date/time.
8068 c By creation time, which is assumed to be the first inactive time stamp
8069 at the beginning of a line.
8070 p By priority according to the cookie.
8071 r By the value of a property.
8072
8073 Capital letters will reverse the sort order.
8074
8075 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8076 called with point at the beginning of the record. It must return either
8077 a string or a number that should serve as the sorting key for that record.
8078
8079 Comparing entries ignores case by default. However, with an optional argument
8080 WITH-CASE, the sorting considers case as well."
8081 (interactive "P")
8082 (let ((case-func (if with-case 'identity 'downcase))
8083 start beg end stars re re2
8084 txt what tmp)
8085 ;; Find beginning and end of region to sort
8086 (cond
8087 ((org-region-active-p)
8088 ;; we will sort the region
8089 (setq end (region-end)
8090 what "region")
8091 (goto-char (region-beginning))
8092 (if (not (org-at-heading-p)) (outline-next-heading))
8093 (setq start (point)))
8094 ((or (org-at-heading-p)
8095 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8096 ;; we will sort the children of the current headline
8097 (org-back-to-heading)
8098 (setq start (point)
8099 end (progn (org-end-of-subtree t t)
8100 (or (bolp) (insert "\n"))
8101 (org-back-over-empty-lines)
8102 (point))
8103 what "children")
8104 (goto-char start)
8105 (show-subtree)
8106 (outline-next-heading))
8107 (t
8108 ;; we will sort the top-level entries in this file
8109 (goto-char (point-min))
8110 (or (org-at-heading-p) (outline-next-heading))
8111 (setq start (point))
8112 (goto-char (point-max))
8113 (beginning-of-line 1)
8114 (when (looking-at ".*?\\S-")
8115 ;; File ends in a non-white line
8116 (end-of-line 1)
8117 (insert "\n"))
8118 (setq end (point-max))
8119 (setq what "top-level")
8120 (goto-char start)
8121 (show-all)))
8122
8123 (setq beg (point))
8124 (if (>= beg end) (error "Nothing to sort"))
8125
8126 (looking-at "\\(\\*+\\)")
8127 (setq stars (match-string 1)
8128 re (concat "^" (regexp-quote stars) " +")
8129 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8130 txt (buffer-substring beg end))
8131 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8132 (if (and (not (equal stars "*")) (string-match re2 txt))
8133 (error "Region to sort contains a level above the first entry"))
8134
8135 (unless sorting-type
8136 (message
8137 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8138 [t]ime [s]cheduled [d]eadline [c]reated
8139 A/N/T/S/D/C/P/O/F means reversed:"
8140 what)
8141 (setq sorting-type (read-char-exclusive))
8142
8143 (and (= (downcase sorting-type) ?f)
8144 (setq getkey-func
8145 (org-icompleting-read "Sort using function: "
8146 obarray 'fboundp t nil nil))
8147 (setq getkey-func (intern getkey-func)))
8148
8149 (and (= (downcase sorting-type) ?r)
8150 (setq property
8151 (org-icompleting-read "Property: "
8152 (mapcar 'list (org-buffer-property-keys t))
8153 nil t))))
8154
8155 (message "Sorting entries...")
8156
8157 (save-restriction
8158 (narrow-to-region start end)
8159 (let ((dcst (downcase sorting-type))
8160 (case-fold-search nil)
8161 (now (current-time)))
8162 (sort-subr
8163 (/= dcst sorting-type)
8164 ;; This function moves to the beginning character of the "record" to
8165 ;; be sorted.
8166 (lambda nil
8167 (if (re-search-forward re nil t)
8168 (goto-char (match-beginning 0))
8169 (goto-char (point-max))))
8170 ;; This function moves to the last character of the "record" being
8171 ;; sorted.
8172 (lambda nil
8173 (save-match-data
8174 (condition-case nil
8175 (outline-forward-same-level 1)
8176 (error
8177 (goto-char (point-max))))))
8178 ;; This function returns the value that gets sorted against.
8179 (lambda nil
8180 (cond
8181 ((= dcst ?n)
8182 (if (looking-at org-complex-heading-regexp)
8183 (string-to-number (match-string 4))
8184 nil))
8185 ((= dcst ?a)
8186 (if (looking-at org-complex-heading-regexp)
8187 (funcall case-func (match-string 4))
8188 nil))
8189 ((= dcst ?t)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (or (re-search-forward org-ts-regexp end t)
8192 (re-search-forward org-ts-regexp-both end t))
8193 (org-time-string-to-seconds (match-string 0))
8194 (org-float-time now))))
8195 ((= dcst ?c)
8196 (let ((end (save-excursion (outline-next-heading) (point))))
8197 (if (re-search-forward
8198 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8199 end t)
8200 (org-time-string-to-seconds (match-string 0))
8201 (org-float-time now))))
8202 ((= dcst ?s)
8203 (let ((end (save-excursion (outline-next-heading) (point))))
8204 (if (re-search-forward org-scheduled-time-regexp end t)
8205 (org-time-string-to-seconds (match-string 1))
8206 (org-float-time now))))
8207 ((= dcst ?d)
8208 (let ((end (save-excursion (outline-next-heading) (point))))
8209 (if (re-search-forward org-deadline-time-regexp end t)
8210 (org-time-string-to-seconds (match-string 1))
8211 (org-float-time now))))
8212 ((= dcst ?p)
8213 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8214 (string-to-char (match-string 2))
8215 org-default-priority))
8216 ((= dcst ?r)
8217 (or (org-entry-get nil property) ""))
8218 ((= dcst ?o)
8219 (if (looking-at org-complex-heading-regexp)
8220 (- 9999 (length (member (match-string 2)
8221 org-todo-keywords-1)))))
8222 ((= dcst ?f)
8223 (if getkey-func
8224 (progn
8225 (setq tmp (funcall getkey-func))
8226 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8227 tmp)
8228 (error "Invalid key function `%s'" getkey-func)))
8229 (t (error "Invalid sorting type `%c'" sorting-type))))
8230 nil
8231 (cond
8232 ((= dcst ?a) 'string<)
8233 ((= dcst ?f) compare-func)
8234 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8235 (t nil)))))
8236 (run-hooks 'org-after-sorting-entries-or-items-hook)
8237 (message "Sorting entries...done")))
8238
8239 (defun org-do-sort (table what &optional with-case sorting-type)
8240 "Sort TABLE of WHAT according to SORTING-TYPE.
8241 The user will be prompted for the SORTING-TYPE if the call to this
8242 function does not specify it. WHAT is only for the prompt, to indicate
8243 what is being sorted. The sorting key will be extracted from
8244 the car of the elements of the table.
8245 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8246 (unless sorting-type
8247 (message
8248 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8249 what)
8250 (setq sorting-type (read-char-exclusive)))
8251 (let ((dcst (downcase sorting-type))
8252 extractfun comparefun)
8253 ;; Define the appropriate functions
8254 (cond
8255 ((= dcst ?n)
8256 (setq extractfun 'string-to-number
8257 comparefun (if (= dcst sorting-type) '< '>)))
8258 ((= dcst ?a)
8259 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8260 (lambda(x) (downcase (org-sort-remove-invisible x))))
8261 comparefun (if (= dcst sorting-type)
8262 'string<
8263 (lambda (a b) (and (not (string< a b))
8264 (not (string= a b)))))))
8265 ((= dcst ?t)
8266 (setq extractfun
8267 (lambda (x)
8268 (if (or (string-match org-ts-regexp x)
8269 (string-match org-ts-regexp-both x))
8270 (org-float-time
8271 (org-time-string-to-time (match-string 0 x)))
8272 0))
8273 comparefun (if (= dcst sorting-type) '< '>)))
8274 (t (error "Invalid sorting type `%c'" sorting-type)))
8275
8276 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8277 table)
8278 (lambda (a b) (funcall comparefun (car a) (car b))))))
8279
8280
8281 ;;; The orgstruct minor mode
8282
8283 ;; Define a minor mode which can be used in other modes in order to
8284 ;; integrate the org-mode structure editing commands.
8285
8286 ;; This is really a hack, because the org-mode structure commands use
8287 ;; keys which normally belong to the major mode. Here is how it
8288 ;; works: The minor mode defines all the keys necessary to operate the
8289 ;; structure commands, but wraps the commands into a function which
8290 ;; tests if the cursor is currently at a headline or a plain list
8291 ;; item. If that is the case, the structure command is used,
8292 ;; temporarily setting many Org-mode variables like regular
8293 ;; expressions for filling etc. However, when any of those keys is
8294 ;; used at a different location, function uses `key-binding' to look
8295 ;; up if the key has an associated command in another currently active
8296 ;; keymap (minor modes, major mode, global), and executes that
8297 ;; command. There might be problems if any of the keys is otherwise
8298 ;; used as a prefix key.
8299
8300 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8301 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8302 ;; addresses this by checking explicitly for both bindings.
8303
8304 (defvar orgstruct-mode-map (make-sparse-keymap)
8305 "Keymap for the minor `orgstruct-mode'.")
8306
8307 (defvar org-local-vars nil
8308 "List of local variables, for use by `orgstruct-mode'.")
8309
8310 ;;;###autoload
8311 (define-minor-mode orgstruct-mode
8312 "Toggle the minor mode `orgstruct-mode'.
8313 This mode is for using Org-mode structure commands in other
8314 modes. The following keys behave as if Org-mode were active, if
8315 the cursor is on a headline, or on a plain list item (both as
8316 defined by Org-mode).
8317
8318 M-up Move entry/item up
8319 M-down Move entry/item down
8320 M-left Promote
8321 M-right Demote
8322 M-S-up Move entry/item up
8323 M-S-down Move entry/item down
8324 M-S-left Promote subtree
8325 M-S-right Demote subtree
8326 M-q Fill paragraph and items like in Org-mode
8327 C-c ^ Sort entries
8328 C-c - Cycle list bullet
8329 TAB Cycle item visibility
8330 M-RET Insert new heading/item
8331 S-M-RET Insert new TODO heading / Checkbox item
8332 C-c C-c Set tags / toggle checkbox"
8333 nil " OrgStruct" nil
8334 (org-load-modules-maybe)
8335 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8336
8337 ;;;###autoload
8338 (defun turn-on-orgstruct ()
8339 "Unconditionally turn on `orgstruct-mode'."
8340 (orgstruct-mode 1))
8341
8342 (defun orgstruct++-mode (&optional arg)
8343 "Toggle `orgstruct-mode', the enhanced version of it.
8344 In addition to setting orgstruct-mode, this also exports all indentation
8345 and autofilling variables from org-mode into the buffer. It will also
8346 recognize item context in multiline items.
8347 Note that turning off orgstruct-mode will *not* remove the
8348 indentation/paragraph settings. This can only be done by refreshing the
8349 major mode, for example with \\[normal-mode]."
8350 (interactive "P")
8351 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8352 (if (< arg 1)
8353 (orgstruct-mode -1)
8354 (orgstruct-mode 1)
8355 (let (var val)
8356 (mapc
8357 (lambda (x)
8358 (when (string-match
8359 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8360 (symbol-name (car x)))
8361 (setq var (car x) val (nth 1 x))
8362 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8363 org-local-vars)
8364 (org-set-local 'orgstruct-is-++ t))))
8365
8366 (defvar orgstruct-is-++ nil
8367 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8368 (make-variable-buffer-local 'orgstruct-is-++)
8369
8370 ;;;###autoload
8371 (defun turn-on-orgstruct++ ()
8372 "Unconditionally turn on `orgstruct++-mode'."
8373 (orgstruct++-mode 1))
8374
8375 (defun orgstruct-error ()
8376 "Error when there is no default binding for a structure key."
8377 (interactive)
8378 (error "This key has no function outside structure elements"))
8379
8380 (defun orgstruct-setup ()
8381 "Setup orgstruct keymaps."
8382 (let ((nfunc 0)
8383 (bindings
8384 (list
8385 '([(meta up)] org-metaup)
8386 '([(meta down)] org-metadown)
8387 '([(meta left)] org-metaleft)
8388 '([(meta right)] org-metaright)
8389 '([(meta shift up)] org-shiftmetaup)
8390 '([(meta shift down)] org-shiftmetadown)
8391 '([(meta shift left)] org-shiftmetaleft)
8392 '([(meta shift right)] org-shiftmetaright)
8393 '([?\e (up)] org-metaup)
8394 '([?\e (down)] org-metadown)
8395 '([?\e (left)] org-metaleft)
8396 '([?\e (right)] org-metaright)
8397 '([?\e (shift up)] org-shiftmetaup)
8398 '([?\e (shift down)] org-shiftmetadown)
8399 '([?\e (shift left)] org-shiftmetaleft)
8400 '([?\e (shift right)] org-shiftmetaright)
8401 '([(shift up)] org-shiftup)
8402 '([(shift down)] org-shiftdown)
8403 '([(shift left)] org-shiftleft)
8404 '([(shift right)] org-shiftright)
8405 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8406 '("\M-q" fill-paragraph)
8407 '("\C-c^" org-sort)
8408 '("\C-c-" org-cycle-list-bullet)))
8409 elt key fun cmd)
8410 (while (setq elt (pop bindings))
8411 (setq nfunc (1+ nfunc))
8412 (setq key (org-key (car elt))
8413 fun (nth 1 elt)
8414 cmd (orgstruct-make-binding fun nfunc key))
8415 (org-defkey orgstruct-mode-map key cmd))
8416
8417 ;; Special treatment needed for TAB and RET
8418 (org-defkey orgstruct-mode-map [(tab)]
8419 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8420 (org-defkey orgstruct-mode-map "\C-i"
8421 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8422
8423 (org-defkey orgstruct-mode-map "\M-\C-m"
8424 (orgstruct-make-binding 'org-insert-heading 105
8425 "\M-\C-m" [(meta return)]))
8426 (org-defkey orgstruct-mode-map [(meta return)]
8427 (orgstruct-make-binding 'org-insert-heading 106
8428 [(meta return)] "\M-\C-m"))
8429
8430 (org-defkey orgstruct-mode-map [(shift meta return)]
8431 (orgstruct-make-binding 'org-insert-todo-heading 107
8432 [(meta return)] "\M-\C-m"))
8433
8434 (org-defkey orgstruct-mode-map "\e\C-m"
8435 (orgstruct-make-binding 'org-insert-heading 108
8436 "\e\C-m" [?\e (return)]))
8437 (org-defkey orgstruct-mode-map [?\e (return)]
8438 (orgstruct-make-binding 'org-insert-heading 109
8439 [?\e (return)] "\e\C-m"))
8440 (org-defkey orgstruct-mode-map [?\e (shift return)]
8441 (orgstruct-make-binding 'org-insert-todo-heading 110
8442 [?\e (return)] "\e\C-m"))
8443
8444 (unless org-local-vars
8445 (setq org-local-vars (org-get-local-variables)))
8446
8447 t))
8448
8449 (defun orgstruct-make-binding (fun n &rest keys)
8450 "Create a function for binding in the structure minor mode.
8451 FUN is the command to call inside a table. N is used to create a unique
8452 command name. KEYS are keys that should be checked in for a command
8453 to execute outside of tables."
8454 (eval
8455 (list 'defun
8456 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8457 '(arg)
8458 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8459 "Outside of structure, run the binding of `"
8460 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8461 "'.")
8462 '(interactive "p")
8463 (list 'if
8464 `(org-context-p 'headline 'item
8465 (and orgstruct-is-++
8466 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8467 'item-body))
8468 (list 'org-run-like-in-org-mode (list 'quote fun))
8469 (list 'let '(orgstruct-mode)
8470 (list 'call-interactively
8471 (append '(or)
8472 (mapcar (lambda (k)
8473 (list 'key-binding k))
8474 keys)
8475 '('orgstruct-error))))))))
8476
8477 (defun org-context-p (&rest contexts)
8478 "Check if local context is any of CONTEXTS.
8479 Possible values in the list of contexts are `table', `headline', and `item'."
8480 (let ((pos (point)))
8481 (goto-char (point-at-bol))
8482 (prog1 (or (and (memq 'table contexts)
8483 (looking-at "[ \t]*|"))
8484 (and (memq 'headline contexts)
8485 (looking-at org-outline-regexp))
8486 (and (memq 'item contexts)
8487 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8488 (and (memq 'item-body contexts)
8489 (org-in-item-p)))
8490 (goto-char pos))))
8491
8492 (defun org-get-local-variables ()
8493 "Return a list of all local variables in an org-mode buffer."
8494 (let (varlist)
8495 (with-current-buffer (get-buffer-create "*Org tmp*")
8496 (erase-buffer)
8497 (org-mode)
8498 (setq varlist (buffer-local-variables)))
8499 (kill-buffer "*Org tmp*")
8500 (delq nil
8501 (mapcar
8502 (lambda (x)
8503 (setq x
8504 (if (symbolp x)
8505 (list x)
8506 (list (car x) (list 'quote (cdr x)))))
8507 (if (string-match
8508 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8509 (symbol-name (car x)))
8510 x nil))
8511 varlist))))
8512
8513 (defun org-clone-local-variables (from-buffer &optional regexp)
8514 "Clone local variables from FROM-BUFFER.
8515 Optional argument REGEXP selects variables to clone."
8516 (mapc
8517 (lambda (pair)
8518 (and (symbolp (car pair))
8519 (or (null regexp)
8520 (string-match regexp (symbol-name (car pair))))
8521 (set (make-local-variable (car pair))
8522 (cdr pair))))
8523 (buffer-local-variables from-buffer)))
8524
8525 ;;;###autoload
8526 (defun org-run-like-in-org-mode (cmd)
8527 "Run a command, pretending that the current buffer is in Org-mode.
8528 This will temporarily bind local variables that are typically bound in
8529 Org-mode to the values they have in Org-mode, and then interactively
8530 call CMD."
8531 (org-load-modules-maybe)
8532 (unless org-local-vars
8533 (setq org-local-vars (org-get-local-variables)))
8534 (eval (list 'let org-local-vars
8535 (list 'call-interactively (list 'quote cmd)))))
8536
8537 ;;;; Archiving
8538
8539 (defun org-get-category (&optional pos force-refresh)
8540 "Get the category applying to position POS."
8541 (save-match-data
8542 (if force-refresh (org-refresh-category-properties))
8543 (let ((pos (or pos (point))))
8544 (or (get-text-property pos 'org-category)
8545 (progn (org-refresh-category-properties)
8546 (get-text-property pos 'org-category))))))
8547
8548 (defun org-refresh-category-properties ()
8549 "Refresh category text properties in the buffer."
8550 (let ((def-cat (cond
8551 ((null org-category)
8552 (if buffer-file-name
8553 (file-name-sans-extension
8554 (file-name-nondirectory buffer-file-name))
8555 "???"))
8556 ((symbolp org-category) (symbol-name org-category))
8557 (t org-category)))
8558 beg end cat pos optionp)
8559 (org-unmodified
8560 (save-excursion
8561 (save-restriction
8562 (widen)
8563 (goto-char (point-min))
8564 (put-text-property (point) (point-max) 'org-category def-cat)
8565 (while (re-search-forward
8566 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8567 (setq pos (match-end 0)
8568 optionp (equal (char-after (match-beginning 0)) ?#)
8569 cat (org-trim (match-string 2)))
8570 (if optionp
8571 (setq beg (point-at-bol) end (point-max))
8572 (org-back-to-heading t)
8573 (setq beg (point) end (org-end-of-subtree t t)))
8574 (put-text-property beg end 'org-category cat)
8575 (put-text-property beg end 'org-category-position beg)
8576 (goto-char pos)))))))
8577
8578
8579 ;;;; Link Stuff
8580
8581 ;;; Link abbreviations
8582
8583 (defun org-link-expand-abbrev (link)
8584 "Apply replacements as defined in `org-link-abbrev-alist'."
8585 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8586 (let* ((key (match-string 1 link))
8587 (as (or (assoc key org-link-abbrev-alist-local)
8588 (assoc key org-link-abbrev-alist)))
8589 (tag (and (match-end 2) (match-string 3 link)))
8590 rpl)
8591 (if (not as)
8592 link
8593 (setq rpl (cdr as))
8594 (cond
8595 ((symbolp rpl) (funcall rpl tag))
8596 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8597 ((string-match "%h" rpl)
8598 (replace-match (url-hexify-string (or tag "")) t t rpl))
8599 (t (concat rpl tag)))))
8600 link))
8601
8602 ;;; Storing and inserting links
8603
8604 (defvar org-insert-link-history nil
8605 "Minibuffer history for links inserted with `org-insert-link'.")
8606
8607 (defvar org-stored-links nil
8608 "Contains the links stored with `org-store-link'.")
8609
8610 (defvar org-store-link-plist nil
8611 "Plist with info about the most recently link created with `org-store-link'.")
8612
8613 (defvar org-link-protocols nil
8614 "Link protocols added to Org-mode using `org-add-link-type'.")
8615
8616 (defvar org-store-link-functions nil
8617 "List of functions that are called to create and store a link.
8618 Each function will be called in turn until one returns a non-nil
8619 value. Each function should check if it is responsible for creating
8620 this link (for example by looking at the major mode).
8621 If not, it must exit and return nil.
8622 If yes, it should return a non-nil value after a calling
8623 `org-store-link-props' with a list of properties and values.
8624 Special properties are:
8625
8626 :type The link prefix, like \"http\". This must be given.
8627 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8628 This is obligatory as well.
8629 :description Optional default description for the second pair
8630 of brackets in an Org-mode link. The user can still change
8631 this when inserting this link into an Org-mode buffer.
8632
8633 In addition to these, any additional properties can be specified
8634 and then used in remember templates.")
8635
8636 (defun org-add-link-type (type &optional follow export)
8637 "Add TYPE to the list of `org-link-types'.
8638 Re-compute all regular expressions depending on `org-link-types'
8639
8640 FOLLOW and EXPORT are two functions.
8641
8642 FOLLOW should take the link path as the single argument and do whatever
8643 is necessary to follow the link, for example find a file or display
8644 a mail message.
8645
8646 EXPORT should format the link path for export to one of the export formats.
8647 It should be a function accepting three arguments:
8648
8649 path the path of the link, the text after the prefix (like \"http:\")
8650 desc the description of the link, if any, or a description added by
8651 org-export-normalize-links if there is none
8652 format the export format, a symbol like `html' or `latex' or `ascii'..
8653
8654 The function may use the FORMAT information to return different values
8655 depending on the format. The return value will be put literally into
8656 the exported file. If the return value is nil, this means Org should
8657 do what it normally does with links which do not have EXPORT defined.
8658
8659 Org-mode has a built-in default for exporting links. If you are happy with
8660 this default, there is no need to define an export function for the link
8661 type. For a simple example of an export function, see `org-bbdb.el'."
8662 (add-to-list 'org-link-types type t)
8663 (org-make-link-regexps)
8664 (if (assoc type org-link-protocols)
8665 (setcdr (assoc type org-link-protocols) (list follow export))
8666 (push (list type follow export) org-link-protocols)))
8667
8668 (defvar org-agenda-buffer-name)
8669
8670 ;;;###autoload
8671 (defun org-store-link (arg)
8672 "\\<org-mode-map>Store an org-link to the current location.
8673 This link is added to `org-stored-links' and can later be inserted
8674 into an org-buffer with \\[org-insert-link].
8675
8676 For some link types, a prefix arg is interpreted:
8677 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8678 For file links, arg negates `org-context-in-file-links'."
8679 (interactive "P")
8680 (org-load-modules-maybe)
8681 (setq org-store-link-plist nil) ; reset
8682 (org-with-limited-levels
8683 (let (link cpltxt desc description search txt custom-id agenda-link)
8684 (cond
8685
8686 ((run-hook-with-args-until-success 'org-store-link-functions)
8687 (setq link (plist-get org-store-link-plist :link)
8688 desc (or (plist-get org-store-link-plist :description) link)))
8689
8690 ((org-src-edit-buffer-p)
8691 (let (label gc)
8692 (while (or (not label)
8693 (save-excursion
8694 (save-restriction
8695 (widen)
8696 (goto-char (point-min))
8697 (re-search-forward
8698 (regexp-quote (format org-coderef-label-format label))
8699 nil t))))
8700 (when label (message "Label exists already") (sit-for 2))
8701 (setq label (read-string "Code line label: " label)))
8702 (end-of-line 1)
8703 (setq link (format org-coderef-label-format label))
8704 (setq gc (- 79 (length link)))
8705 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8706 (insert link)
8707 (setq link (concat "(" label ")") desc nil)))
8708
8709 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8710 ;; We are in the agenda, link to referenced location
8711 (let ((m (or (get-text-property (point) 'org-hd-marker)
8712 (get-text-property (point) 'org-marker))))
8713 (when m
8714 (org-with-point-at m
8715 (setq agenda-link
8716 (if (org-called-interactively-p 'any)
8717 (call-interactively 'org-store-link)
8718 (org-store-link nil)))))))
8719
8720 ((eq major-mode 'calendar-mode)
8721 (let ((cd (calendar-cursor-to-date)))
8722 (setq link
8723 (format-time-string
8724 (car org-time-stamp-formats)
8725 (apply 'encode-time
8726 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8727 nil nil nil))))
8728 (org-store-link-props :type "calendar" :date cd)))
8729
8730 ((eq major-mode 'w3-mode)
8731 (setq cpltxt (if (and (buffer-name)
8732 (not (string-match "Untitled" (buffer-name))))
8733 (buffer-name)
8734 (url-view-url t))
8735 link (org-make-link (url-view-url t)))
8736 (org-store-link-props :type "w3" :url (url-view-url t)))
8737
8738 ((eq major-mode 'w3m-mode)
8739 (setq cpltxt (or w3m-current-title w3m-current-url)
8740 link (org-make-link w3m-current-url))
8741 (org-store-link-props :type "w3m" :url (url-view-url t)))
8742
8743 ((setq search (run-hook-with-args-until-success
8744 'org-create-file-search-functions))
8745 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8746 "::" search))
8747 (setq cpltxt (or description link)))
8748
8749 ((eq major-mode 'image-mode)
8750 (setq cpltxt (concat "file:"
8751 (abbreviate-file-name buffer-file-name))
8752 link (org-make-link cpltxt))
8753 (org-store-link-props :type "image" :file buffer-file-name))
8754
8755 ((eq major-mode 'dired-mode)
8756 ;; link to the file in the current line
8757 (let ((file (dired-get-filename nil t)))
8758 (setq file (if file
8759 (abbreviate-file-name
8760 (expand-file-name (dired-get-filename nil t)))
8761 ;; otherwise, no file so use current directory.
8762 default-directory))
8763 (setq cpltxt (concat "file:" file)
8764 link (org-make-link cpltxt))))
8765
8766 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8767 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8768 (cond
8769 ((org-in-regexp "<<\\(.*?\\)>>")
8770 (setq cpltxt
8771 (concat "file:"
8772 (abbreviate-file-name
8773 (buffer-file-name (buffer-base-buffer)))
8774 "::" (match-string 1))
8775 link (org-make-link cpltxt)))
8776 ((and (featurep 'org-id)
8777 (or (eq org-link-to-org-use-id t)
8778 (and (eq org-link-to-org-use-id 'create-if-interactive)
8779 (org-called-interactively-p 'any))
8780 (and (eq org-link-to-org-use-id
8781 'create-if-interactive-and-no-custom-id)
8782 (org-called-interactively-p 'any)
8783 (not custom-id))
8784 (and org-link-to-org-use-id
8785 (org-entry-get nil "ID"))))
8786 ;; We can make a link using the ID.
8787 (setq link (condition-case nil
8788 (prog1 (org-id-store-link)
8789 (setq desc (plist-get org-store-link-plist
8790 :description)))
8791 (error
8792 ;; probably before first headline, link to file only
8793 (concat "file:"
8794 (abbreviate-file-name
8795 (buffer-file-name (buffer-base-buffer))))))))
8796 (t
8797 ;; Just link to current headline
8798 (setq cpltxt (concat "file:"
8799 (abbreviate-file-name
8800 (buffer-file-name (buffer-base-buffer)))))
8801 ;; Add a context search string
8802 (when (org-xor org-context-in-file-links arg)
8803 (setq txt (cond
8804 ((org-at-heading-p) nil)
8805 ((org-region-active-p)
8806 (buffer-substring (region-beginning) (region-end)))
8807 (t nil)))
8808 (when (or (null txt) (string-match "\\S-" txt))
8809 (setq cpltxt
8810 (concat cpltxt "::"
8811 (condition-case nil
8812 (org-make-org-heading-search-string txt)
8813 (error "")))
8814 desc (or (nth 4 (ignore-errors
8815 (org-heading-components))) "NONE"))))
8816 (if (string-match "::\\'" cpltxt)
8817 (setq cpltxt (substring cpltxt 0 -2)))
8818 (setq link (org-make-link cpltxt)))))
8819
8820 ((buffer-file-name (buffer-base-buffer))
8821 ;; Just link to this file here.
8822 (setq cpltxt (concat "file:"
8823 (abbreviate-file-name
8824 (buffer-file-name (buffer-base-buffer)))))
8825 ;; Add a context string
8826 (when (org-xor org-context-in-file-links arg)
8827 (setq txt (if (org-region-active-p)
8828 (buffer-substring (region-beginning) (region-end))
8829 (buffer-substring (point-at-bol) (point-at-eol))))
8830 ;; Only use search option if there is some text.
8831 (when (string-match "\\S-" txt)
8832 (setq cpltxt
8833 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8834 desc "NONE")))
8835 (setq link (org-make-link cpltxt)))
8836
8837 ((org-called-interactively-p 'interactive)
8838 (error "Cannot link to a buffer which is not visiting a file"))
8839
8840 (t (setq link nil)))
8841
8842 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8843 (setq link (or link cpltxt)
8844 desc (or desc cpltxt))
8845 (if (equal desc "NONE") (setq desc nil))
8846
8847 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8848 (progn
8849 (setq org-stored-links
8850 (cons (list link desc) org-stored-links))
8851 (message "Stored: %s" (or desc link))
8852 (when custom-id
8853 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8854 "::#" custom-id))
8855 (setq org-stored-links
8856 (cons (list link desc) org-stored-links))))
8857 (or agenda-link (and link (org-make-link-string link desc)))))))
8858
8859 (defun org-store-link-props (&rest plist)
8860 "Store link properties, extract names and addresses."
8861 (let (x adr)
8862 (when (setq x (plist-get plist :from))
8863 (setq adr (mail-extract-address-components x))
8864 (setq plist (plist-put plist :fromname (car adr)))
8865 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8866 (when (setq x (plist-get plist :to))
8867 (setq adr (mail-extract-address-components x))
8868 (setq plist (plist-put plist :toname (car adr)))
8869 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8870 (let ((from (plist-get plist :from))
8871 (to (plist-get plist :to)))
8872 (when (and from to org-from-is-user-regexp)
8873 (setq plist
8874 (plist-put plist :fromto
8875 (if (string-match org-from-is-user-regexp from)
8876 (concat "to %t")
8877 (concat "from %f"))))))
8878 (setq org-store-link-plist plist))
8879
8880 (defun org-add-link-props (&rest plist)
8881 "Add these properties to the link property list."
8882 (let (key value)
8883 (while plist
8884 (setq key (pop plist) value (pop plist))
8885 (setq org-store-link-plist
8886 (plist-put org-store-link-plist key value)))))
8887
8888 (defun org-email-link-description (&optional fmt)
8889 "Return the description part of an email link.
8890 This takes information from `org-store-link-plist' and formats it
8891 according to FMT (default from `org-email-link-description-format')."
8892 (setq fmt (or fmt org-email-link-description-format))
8893 (let* ((p org-store-link-plist)
8894 (to (plist-get p :toaddress))
8895 (from (plist-get p :fromaddress))
8896 (table
8897 (list
8898 (cons "%c" (plist-get p :fromto))
8899 (cons "%F" (plist-get p :from))
8900 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8901 (cons "%T" (plist-get p :to))
8902 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8903 (cons "%s" (plist-get p :subject))
8904 (cons "%d" (plist-get p :date))
8905 (cons "%m" (plist-get p :message-id)))))
8906 (when (string-match "%c" fmt)
8907 ;; Check if the user wrote this message
8908 (if (and org-from-is-user-regexp from to
8909 (save-match-data (string-match org-from-is-user-regexp from)))
8910 (setq fmt (replace-match "to %t" t t fmt))
8911 (setq fmt (replace-match "from %f" t t fmt))))
8912 (org-replace-escapes fmt table)))
8913
8914 (defun org-make-org-heading-search-string (&optional string heading)
8915 "Make search string for STRING or current headline."
8916 (interactive)
8917 (let ((s (or string (org-get-heading)))
8918 (lines org-context-in-file-links))
8919 (unless (and string (not heading))
8920 ;; We are using a headline, clean up garbage in there.
8921 (if (string-match org-todo-regexp s)
8922 (setq s (replace-match "" t t s)))
8923 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8924 (setq s (replace-match "" t t s)))
8925 (setq s (org-trim s))
8926 (if (string-match (concat "^\\(" org-quote-string "\\|"
8927 org-comment-string "\\)") s)
8928 (setq s (replace-match "" t t s)))
8929 (while (string-match org-ts-regexp s)
8930 (setq s (replace-match "" t t s))))
8931 (or string (setq s (concat "*" s))) ; Add * for headlines
8932 (when (and string (integerp lines) (> lines 0))
8933 (let ((slines (org-split-string s "\n")))
8934 (when (< lines (length slines))
8935 (setq s (mapconcat
8936 'identity
8937 (reverse (nthcdr (- (length slines) lines)
8938 (reverse slines))) "\n")))))
8939 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8940
8941 (defun org-make-link (&rest strings)
8942 "Concatenate STRINGS."
8943 (apply 'concat strings))
8944
8945 (defun org-make-link-string (link &optional description)
8946 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8947 (unless (string-match "\\S-" link)
8948 (error "Empty link"))
8949 (when (and description
8950 (stringp description)
8951 (not (string-match "\\S-" description)))
8952 (setq description nil))
8953 (when (stringp description)
8954 ;; Remove brackets from the description, they are fatal.
8955 (while (string-match "\\[" description)
8956 (setq description (replace-match "{" t t description)))
8957 (while (string-match "\\]" description)
8958 (setq description (replace-match "}" t t description))))
8959 (when (equal link description)
8960 ;; No description needed, it is identical
8961 (setq description nil))
8962 (when (and (not description)
8963 (not (string-match (org-image-file-name-regexp) link))
8964 (not (equal link (org-link-escape link))))
8965 (setq description (org-extract-attributes link)))
8966 (setq link
8967 (cond ((string-match (org-image-file-name-regexp) link) link)
8968 ((string-match org-link-types-re link)
8969 (concat (match-string 1 link)
8970 (org-link-escape (substring link (match-end 1)))))
8971 (t (org-link-escape link))))
8972 (concat "[[" link "]"
8973 (if description (concat "[" description "]") "")
8974 "]"))
8975
8976 (defconst org-link-escape-chars
8977 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8978 "List of characters that should be escaped in link.
8979 This is the list that is used for internal purposes.")
8980
8981 (defvar org-url-encoding-use-url-hexify nil)
8982
8983 (defconst org-link-escape-chars-browser
8984 '(?\ )
8985 "List of escapes for characters that are problematic in links.
8986 This is the list that is used before handing over to the browser.")
8987
8988 (defun org-link-escape (text &optional table merge)
8989 "Return percent escaped representation of TEXT.
8990 TEXT is a string with the text to escape.
8991 Optional argument TABLE is a list with characters that should be
8992 escaped. When nil, `org-link-escape-chars' is used.
8993 If optional argument MERGE is set, merge TABLE into
8994 `org-link-escape-chars'."
8995 (if (and org-url-encoding-use-url-hexify (not table))
8996 (url-hexify-string text)
8997 (cond
8998 ((and table merge)
8999 (mapc (lambda (defchr)
9000 (unless (member defchr table)
9001 (setq table (cons defchr table)))) org-link-escape-chars))
9002 ((null table)
9003 (setq table org-link-escape-chars)))
9004 (mapconcat
9005 (lambda (char)
9006 (if (or (member char table)
9007 (< char 32) (= char 37) (> char 126))
9008 (mapconcat (lambda (sequence-element)
9009 (format "%%%.2X" sequence-element))
9010 (or (encode-coding-char char 'utf-8)
9011 (error "Unable to percent escape character: %s"
9012 (char-to-string char))) "")
9013 (char-to-string char))) text "")))
9014
9015 (defun org-link-unescape (str)
9016 "Unhex hexified Unicode strings as returned from the JavaScript function
9017 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9018 (unless (and (null str) (string= "" str))
9019 (let ((pos 0) (case-fold-search t) unhexed)
9020 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9021 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9022 (setq str (replace-match unhexed t t str))
9023 (setq pos (+ pos (length unhexed))))))
9024 str)
9025
9026 (defun org-link-unescape-compound (hex)
9027 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9028 Note: this function also decodes single byte encodings like
9029 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9030 (save-match-data
9031 (let* ((bytes (cdr (split-string hex "%")))
9032 (ret "")
9033 (eat 0)
9034 (sum 0))
9035 (while bytes
9036 (let* ((val (string-to-number (pop bytes) 16))
9037 (shift-xor
9038 (if (= 0 eat)
9039 (cond
9040 ((>= val 252) (cons 6 252))
9041 ((>= val 248) (cons 5 248))
9042 ((>= val 240) (cons 4 240))
9043 ((>= val 224) (cons 3 224))
9044 ((>= val 192) (cons 2 192))
9045 (t (cons 0 0)))
9046 (cons 6 128))))
9047 (if (>= val 192) (setq eat (car shift-xor)))
9048 (setq val (logxor val (cdr shift-xor)))
9049 (setq sum (+ (lsh sum (car shift-xor)) val))
9050 (if (> eat 0) (setq eat (- eat 1)))
9051 (cond
9052 ((= 0 eat) ;multi byte
9053 (setq ret (concat ret (org-char-to-string sum)))
9054 (setq sum 0))
9055 ((not bytes) ; single byte(s)
9056 (setq ret (org-link-unescape-single-byte-sequence hex))))
9057 )) ;; end (while bytes
9058 ret )))
9059
9060 (defun org-link-unescape-single-byte-sequence (hex)
9061 "Unhexify hex-encoded single byte character sequences."
9062 (mapconcat (lambda (byte)
9063 (char-to-string (string-to-number byte 16)))
9064 (cdr (split-string hex "%")) ""))
9065
9066 (defun org-xor (a b)
9067 "Exclusive or."
9068 (if a (not b) b))
9069
9070 (defun org-fixup-message-id-for-http (s)
9071 "Replace special characters in a message id, so it can be used in an http query."
9072 (when (string-match "%" s)
9073 (setq s (mapconcat (lambda (c)
9074 (if (eq c ?%)
9075 "%25"
9076 (char-to-string c)))
9077 s "")))
9078 (while (string-match "<" s)
9079 (setq s (replace-match "%3C" t t s)))
9080 (while (string-match ">" s)
9081 (setq s (replace-match "%3E" t t s)))
9082 (while (string-match "@" s)
9083 (setq s (replace-match "%40" t t s)))
9084 s)
9085
9086 ;;;###autoload
9087 (defun org-insert-link-global ()
9088 "Insert a link like Org-mode does.
9089 This command can be called in any mode to insert a link in Org-mode syntax."
9090 (interactive)
9091 (org-load-modules-maybe)
9092 (org-run-like-in-org-mode 'org-insert-link))
9093
9094 (defun org-insert-link (&optional complete-file link-location default-description)
9095 "Insert a link. At the prompt, enter the link.
9096
9097 Completion can be used to insert any of the link protocol prefixes like
9098 http or ftp in use.
9099
9100 The history can be used to select a link previously stored with
9101 `org-store-link'. When the empty string is entered (i.e. if you just
9102 press RET at the prompt), the link defaults to the most recently
9103 stored link. As SPC triggers completion in the minibuffer, you need to
9104 use M-SPC or C-q SPC to force the insertion of a space character.
9105
9106 You will also be prompted for a description, and if one is given, it will
9107 be displayed in the buffer instead of the link.
9108
9109 If there is already a link at point, this command will allow you to edit link
9110 and description parts.
9111
9112 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9113 be selected using completion. The path to the file will be relative to the
9114 current directory if the file is in the current directory or a subdirectory.
9115 Otherwise, the link will be the absolute path as completed in the minibuffer
9116 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9117 option `org-link-file-path-type'.
9118
9119 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9120 the current directory or below.
9121
9122 With three \\[universal-argument] prefixes, negate the meaning of
9123 `org-keep-stored-link-after-insertion'.
9124
9125 If `org-make-link-description-function' is non-nil, this function will be
9126 called with the link target, and the result will be the default
9127 link description.
9128
9129 If the LINK-LOCATION parameter is non-nil, this value will be
9130 used as the link location instead of reading one interactively.
9131
9132 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9133 be used as the default description."
9134 (interactive "P")
9135 (let* ((wcf (current-window-configuration))
9136 (region (if (org-region-active-p)
9137 (buffer-substring (region-beginning) (region-end))))
9138 (remove (and region (list (region-beginning) (region-end))))
9139 (desc region)
9140 tmphist ; byte-compile incorrectly complains about this
9141 (link link-location)
9142 entry file all-prefixes)
9143 (cond
9144 (link-location) ; specified by arg, just use it.
9145 ((org-in-regexp org-bracket-link-regexp 1)
9146 ;; We do have a link at point, and we are going to edit it.
9147 (setq remove (list (match-beginning 0) (match-end 0)))
9148 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9149 (setq link (read-string "Link: "
9150 (org-link-unescape
9151 (org-match-string-no-properties 1)))))
9152 ((or (org-in-regexp org-angle-link-re)
9153 (org-in-regexp org-plain-link-re))
9154 ;; Convert to bracket link
9155 (setq remove (list (match-beginning 0) (match-end 0))
9156 link (read-string "Link: "
9157 (org-remove-angle-brackets (match-string 0)))))
9158 ((member complete-file '((4) (16)))
9159 ;; Completing read for file names.
9160 (setq link (org-file-complete-link complete-file)))
9161 (t
9162 ;; Read link, with completion for stored links.
9163 (with-output-to-temp-buffer "*Org Links*"
9164 (princ "Insert a link.
9165 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9166 (when org-stored-links
9167 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9168 (princ (mapconcat
9169 (lambda (x)
9170 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9171 (reverse org-stored-links) "\n"))))
9172 (let ((cw (selected-window)))
9173 (select-window (get-buffer-window "*Org Links*" 'visible))
9174 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9175 (unless (pos-visible-in-window-p (point-max))
9176 (org-fit-window-to-buffer))
9177 (and (window-live-p cw) (select-window cw)))
9178 ;; Fake a link history, containing the stored links.
9179 (setq tmphist (append (mapcar 'car org-stored-links)
9180 org-insert-link-history))
9181 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9182 (mapcar 'car org-link-abbrev-alist)
9183 org-link-types))
9184 (unwind-protect
9185 (progn
9186 (setq link
9187 (let ((org-completion-use-ido nil)
9188 (org-completion-use-iswitchb nil))
9189 (org-completing-read
9190 "Link: "
9191 (append
9192 (mapcar (lambda (x) (list (concat x ":")))
9193 all-prefixes)
9194 (mapcar 'car org-stored-links))
9195 nil nil nil
9196 'tmphist
9197 (car (car org-stored-links)))))
9198 (if (not (string-match "\\S-" link))
9199 (error "No link selected"))
9200 (if (or (member link all-prefixes)
9201 (and (equal ":" (substring link -1))
9202 (member (substring link 0 -1) all-prefixes)
9203 (setq link (substring link 0 -1))))
9204 (setq link (org-link-try-special-completion link))))
9205 (set-window-configuration wcf)
9206 (kill-buffer "*Org Links*"))
9207 (setq entry (assoc link org-stored-links))
9208 (or entry (push link org-insert-link-history))
9209 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9210 (not org-keep-stored-link-after-insertion))
9211 (setq org-stored-links (delq (assoc link org-stored-links)
9212 org-stored-links)))
9213 (setq desc (or desc (nth 1 entry)))))
9214
9215 (if (string-match org-plain-link-re link)
9216 ;; URL-like link, normalize the use of angular brackets.
9217 (setq link (org-make-link (org-remove-angle-brackets link))))
9218
9219 ;; Check if we are linking to the current file with a search option
9220 ;; If yes, simplify the link by using only the search option.
9221 (when (and buffer-file-name
9222 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9223 (let* ((path (match-string 1 link))
9224 (case-fold-search nil)
9225 (search (match-string 2 link)))
9226 (save-match-data
9227 (if (equal (file-truename buffer-file-name) (file-truename path))
9228 ;; We are linking to this same file, with a search option
9229 (setq link search)))))
9230
9231 ;; Check if we can/should use a relative path. If yes, simplify the link
9232 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9233 (let* ((type (match-string 1 link))
9234 (path (match-string 2 link))
9235 (origpath path)
9236 (case-fold-search nil))
9237 (cond
9238 ((or (eq org-link-file-path-type 'absolute)
9239 (equal complete-file '(16)))
9240 (setq path (abbreviate-file-name (expand-file-name path))))
9241 ((eq org-link-file-path-type 'noabbrev)
9242 (setq path (expand-file-name path)))
9243 ((eq org-link-file-path-type 'relative)
9244 (setq path (file-relative-name path)))
9245 (t
9246 (save-match-data
9247 (if (string-match (concat "^" (regexp-quote
9248 (expand-file-name
9249 (file-name-as-directory
9250 default-directory))))
9251 (expand-file-name path))
9252 ;; We are linking a file with relative path name.
9253 (setq path (substring (expand-file-name path)
9254 (match-end 0)))
9255 (setq path (abbreviate-file-name (expand-file-name path)))))))
9256 (setq link (concat type path))
9257 (if (equal desc origpath)
9258 (setq desc path))))
9259
9260 (if org-make-link-description-function
9261 (setq desc (funcall org-make-link-description-function link desc))
9262 (if default-description (setq desc default-description)))
9263
9264 (setq desc (read-string "Description: " desc))
9265 (unless (string-match "\\S-" desc) (setq desc nil))
9266 (if remove (apply 'delete-region remove))
9267 (insert (org-make-link-string link desc))))
9268
9269 (defun org-link-try-special-completion (type)
9270 "If there is completion support for link type TYPE, offer it."
9271 (let ((fun (intern (concat "org-" type "-complete-link"))))
9272 (if (functionp fun)
9273 (funcall fun)
9274 (read-string "Link (no completion support): " (concat type ":")))))
9275
9276 (defun org-file-complete-link (&optional arg)
9277 "Create a file link using completion."
9278 (let (file link)
9279 (setq file (read-file-name "File: "))
9280 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9281 (pwd1 (file-name-as-directory (abbreviate-file-name
9282 (expand-file-name ".")))))
9283 (cond
9284 ((equal arg '(16))
9285 (setq link (org-make-link
9286 "file:"
9287 (abbreviate-file-name (expand-file-name file)))))
9288 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9289 (setq link (org-make-link "file:" (match-string 1 file))))
9290 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9291 (expand-file-name file))
9292 (setq link (org-make-link
9293 "file:" (match-string 1 (expand-file-name file)))))
9294 (t (setq link (org-make-link "file:" file)))))
9295 link))
9296
9297 (defun org-completing-read (&rest args)
9298 "Completing-read with SPACE being a normal character."
9299 (let ((enable-recursive-minibuffers t)
9300 (minibuffer-local-completion-map
9301 (copy-keymap minibuffer-local-completion-map)))
9302 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9303 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9304 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9305 (apply 'org-icompleting-read args)))
9306
9307 (defun org-completing-read-no-i (&rest args)
9308 (let (org-completion-use-ido org-completion-use-iswitchb)
9309 (apply 'org-completing-read args)))
9310
9311 (defun org-iswitchb-completing-read (prompt choices &rest args)
9312 "Use iswitch as a completing-read replacement to choose from choices.
9313 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9314 from."
9315 (let* ((iswitchb-use-virtual-buffers nil)
9316 (iswitchb-make-buflist-hook
9317 (lambda ()
9318 (setq iswitchb-temp-buflist choices))))
9319 (iswitchb-read-buffer prompt)))
9320
9321 (defun org-icompleting-read (&rest args)
9322 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9323 (org-without-partial-completion
9324 (if (and org-completion-use-ido
9325 (fboundp 'ido-completing-read)
9326 (boundp 'ido-mode) ido-mode
9327 (listp (second args)))
9328 (let ((ido-enter-matching-directory nil))
9329 (apply 'ido-completing-read (concat (car args))
9330 (if (consp (car (nth 1 args)))
9331 (mapcar 'car (nth 1 args))
9332 (nth 1 args))
9333 (cddr args)))
9334 (if (and org-completion-use-iswitchb
9335 (boundp 'iswitchb-mode) iswitchb-mode
9336 (listp (second args)))
9337 (apply 'org-iswitchb-completing-read (concat (car args))
9338 (if (consp (car (nth 1 args)))
9339 (mapcar 'car (nth 1 args))
9340 (nth 1 args))
9341 (cddr args))
9342 (apply 'completing-read args)))))
9343
9344 (defun org-extract-attributes (s)
9345 "Extract the attributes cookie from a string and set as text property."
9346 (let (a attr (start 0) key value)
9347 (save-match-data
9348 (when (string-match "{{\\([^}]+\\)}}$" s)
9349 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9350 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9351 (setq key (match-string 1 a) value (match-string 2 a)
9352 start (match-end 0)
9353 attr (plist-put attr (intern key) value))))
9354 (org-add-props s nil 'org-attr attr))
9355 s))
9356
9357 (defun org-extract-attributes-from-string (tag)
9358 (let (key value attr)
9359 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9360 (setq key (match-string 1 tag) value (match-string 2 tag)
9361 tag (replace-match "" t t tag)
9362 attr (plist-put attr (intern key) value)))
9363 (cons tag attr)))
9364
9365 (defun org-attributes-to-string (plist)
9366 "Format a property list into an HTML attribute list."
9367 (let ((s "") key value)
9368 (while plist
9369 (setq key (pop plist) value (pop plist))
9370 (and value
9371 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9372 s))
9373
9374 ;;; Opening/following a link
9375
9376 (defvar org-link-search-failed nil)
9377
9378 (defvar org-open-link-functions nil
9379 "Hook for functions finding a plain text link.
9380 These functions must take a single argument, the link content.
9381 They will be called for links that look like [[link text][description]]
9382 when LINK TEXT does not have a protocol like \"http:\" and does not look
9383 like a filename (e.g. \"./blue.png\").
9384
9385 These functions will be called *before* Org attempts to resolve the
9386 link by doing text searches in the current buffer - so if you want a
9387 link \"[[target]]\" to still find \"<<target>>\", your function should
9388 handle this as a special case.
9389
9390 When the function does handle the link, it must return a non-nil value.
9391 If it decides that it is not responsible for this link, it must return
9392 nil to indicate that that Org-mode can continue with other options
9393 like exact and fuzzy text search.")
9394
9395 (defun org-next-link ()
9396 "Move forward to the next link.
9397 If the link is in hidden text, expose it."
9398 (interactive)
9399 (when (and org-link-search-failed (eq this-command last-command))
9400 (goto-char (point-min))
9401 (message "Link search wrapped back to beginning of buffer"))
9402 (setq org-link-search-failed nil)
9403 (let* ((pos (point))
9404 (ct (org-context))
9405 (a (assoc :link ct)))
9406 (if a (goto-char (nth 2 a)))
9407 (if (re-search-forward org-any-link-re nil t)
9408 (progn
9409 (goto-char (match-beginning 0))
9410 (if (outline-invisible-p) (org-show-context)))
9411 (goto-char pos)
9412 (setq org-link-search-failed t)
9413 (error "No further link found"))))
9414
9415 (defun org-previous-link ()
9416 "Move backward to the previous link.
9417 If the link is in hidden text, expose it."
9418 (interactive)
9419 (when (and org-link-search-failed (eq this-command last-command))
9420 (goto-char (point-max))
9421 (message "Link search wrapped back to end of buffer"))
9422 (setq org-link-search-failed nil)
9423 (let* ((pos (point))
9424 (ct (org-context))
9425 (a (assoc :link ct)))
9426 (if a (goto-char (nth 1 a)))
9427 (if (re-search-backward org-any-link-re nil t)
9428 (progn
9429 (goto-char (match-beginning 0))
9430 (if (outline-invisible-p) (org-show-context)))
9431 (goto-char pos)
9432 (setq org-link-search-failed t)
9433 (error "No further link found"))))
9434
9435 (defun org-translate-link (s)
9436 "Translate a link string if a translation function has been defined."
9437 (if (and org-link-translation-function
9438 (fboundp org-link-translation-function)
9439 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9440 (progn
9441 (setq s (funcall org-link-translation-function
9442 (match-string 1 s) (match-string 2 s)))
9443 (concat (car s) ":" (cdr s)))
9444 s))
9445
9446 (defun org-translate-link-from-planner (type path)
9447 "Translate a link from Emacs Planner syntax so that Org can follow it.
9448 This is still an experimental function, your mileage may vary."
9449 (cond
9450 ((member type '("http" "https" "news" "ftp"))
9451 ;; standard Internet links are the same.
9452 nil)
9453 ((and (equal type "irc") (string-match "^//" path))
9454 ;; Planner has two / at the beginning of an irc link, we have 1.
9455 ;; We should have zero, actually....
9456 (setq path (substring path 1)))
9457 ((and (equal type "lisp") (string-match "^/" path))
9458 ;; Planner has a slash, we do not.
9459 (setq type "elisp" path (substring path 1)))
9460 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9461 ;; A typical message link. Planner has the id after the final slash,
9462 ;; we separate it with a hash mark
9463 (setq path (concat (match-string 1 path) "#"
9464 (org-remove-angle-brackets (match-string 2 path)))))
9465 )
9466 (cons type path))
9467
9468 (defun org-find-file-at-mouse (ev)
9469 "Open file link or URL at mouse."
9470 (interactive "e")
9471 (mouse-set-point ev)
9472 (org-open-at-point 'in-emacs))
9473
9474 (defun org-open-at-mouse (ev)
9475 "Open file link or URL at mouse.
9476 See the docstring of `org-open-file' for details."
9477 (interactive "e")
9478 (mouse-set-point ev)
9479 (if (eq major-mode 'org-agenda-mode)
9480 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9481 (org-open-at-point))
9482
9483 (defvar org-window-config-before-follow-link nil
9484 "The window configuration before following a link.
9485 This is saved in case the need arises to restore it.")
9486
9487 (defvar org-open-link-marker (make-marker)
9488 "Marker pointing to the location where `org-open-at-point; was called.")
9489
9490 ;;;###autoload
9491 (defun org-open-at-point-global ()
9492 "Follow a link like Org-mode does.
9493 This command can be called in any mode to follow a link that has
9494 Org-mode syntax."
9495 (interactive)
9496 (org-run-like-in-org-mode 'org-open-at-point))
9497
9498 ;;;###autoload
9499 (defun org-open-link-from-string (s &optional arg reference-buffer)
9500 "Open a link in the string S, as if it was in Org-mode."
9501 (interactive "sLink: \nP")
9502 (let ((reference-buffer (or reference-buffer (current-buffer))))
9503 (with-temp-buffer
9504 (let ((org-inhibit-startup (not reference-buffer)))
9505 (org-mode)
9506 (insert s)
9507 (goto-char (point-min))
9508 (when reference-buffer
9509 (setq org-link-abbrev-alist-local
9510 (with-current-buffer reference-buffer
9511 org-link-abbrev-alist-local)))
9512 (org-open-at-point arg reference-buffer)))))
9513
9514 (defvar org-open-at-point-functions nil
9515 "Hook that is run when following a link at point.
9516
9517 Functions in this hook must return t if they identify and follow
9518 a link at point. If they don't find anything interesting at point,
9519 they must return nil.")
9520
9521 (defun org-open-at-point (&optional arg reference-buffer)
9522 "Open link at or after point.
9523 If there is no link at point, this function will search forward up to
9524 the end of the current line.
9525 Normally, files will be opened by an appropriate application. If the
9526 optional prefix argument ARG is non-nil, Emacs will visit the file.
9527 With a double prefix argument, try to open outside of Emacs, in the
9528 application the system uses for this file type."
9529 (interactive "P")
9530 ;; if in a code block, then open the block's results
9531 (unless (call-interactively #'org-babel-open-src-block-result)
9532 (org-load-modules-maybe)
9533 (move-marker org-open-link-marker (point))
9534 (setq org-window-config-before-follow-link (current-window-configuration))
9535 (org-remove-occur-highlights nil nil t)
9536 (cond
9537 ((and (org-at-heading-p)
9538 (not (org-in-regexp
9539 (concat org-plain-link-re "\\|"
9540 org-bracket-link-regexp "\\|"
9541 org-angle-link-re "\\|"
9542 "[ \t]:[^ \t\n]+:[ \t]*$")))
9543 (not (get-text-property (point) 'org-linked-text)))
9544 (or (org-offer-links-in-entry arg)
9545 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9546 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9547 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9548 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9549 (not (org-in-regexp org-bracket-link-regexp)))
9550 (org-footnote-action))
9551 (t
9552 (let (type path link line search (pos (point)))
9553 (catch 'match
9554 (save-excursion
9555 (skip-chars-forward "^]\n\r")
9556 (when (org-in-regexp org-bracket-link-regexp 1)
9557 (setq link (org-extract-attributes
9558 (org-link-unescape (org-match-string-no-properties 1))))
9559 (while (string-match " *\n *" link)
9560 (setq link (replace-match " " t t link)))
9561 (setq link (org-link-expand-abbrev link))
9562 (cond
9563 ((or (file-name-absolute-p link)
9564 (string-match "^\\.\\.?/" link))
9565 (setq type "file" path link))
9566 ((string-match org-link-re-with-space3 link)
9567 (setq type (match-string 1 link) path (match-string 2 link)))
9568 (t (setq type "thisfile" path link)))
9569 (throw 'match t)))
9570
9571 (when (get-text-property (point) 'org-linked-text)
9572 (setq type "thisfile"
9573 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9574 (1+ (point)) (point))
9575 path (buffer-substring
9576 (or (previous-single-property-change pos 'org-linked-text)
9577 (point-min))
9578 (or (next-single-property-change pos 'org-linked-text)
9579 (point-max))))
9580 (throw 'match t))
9581
9582 (save-excursion
9583 (when (or (org-in-regexp org-angle-link-re)
9584 (org-in-regexp org-plain-link-re))
9585 (setq type (match-string 1)
9586 path (org-link-unescape (match-string 2)))
9587 (throw 'match t)))
9588 (save-excursion
9589 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9590 (setq type "tags"
9591 path (match-string 1))
9592 (while (string-match ":" path)
9593 (setq path (replace-match "+" t t path)))
9594 (throw 'match t)))
9595 (when (org-in-regexp "<\\([^><\n]+\\)>")
9596 (setq type "tree-match"
9597 path (match-string 1))
9598 (throw 'match t)))
9599 (unless path
9600 (error "No link found"))
9601
9602 ;; switch back to reference buffer
9603 ;; needed when if called in a temporary buffer through
9604 ;; org-open-link-from-string
9605 (with-current-buffer (or reference-buffer (current-buffer))
9606
9607 ;; Remove any trailing spaces in path
9608 (if (string-match " +\\'" path)
9609 (setq path (replace-match "" t t path)))
9610 (if (and org-link-translation-function
9611 (fboundp org-link-translation-function))
9612 ;; Check if we need to translate the link
9613 (let ((tmp (funcall org-link-translation-function type path)))
9614 (setq type (car tmp) path (cdr tmp))))
9615
9616 (cond
9617
9618 ((assoc type org-link-protocols)
9619 (funcall (nth 1 (assoc type org-link-protocols)) path))
9620
9621 ((equal type "mailto")
9622 (let ((cmd (car org-link-mailto-program))
9623 (args (cdr org-link-mailto-program)) args1
9624 (address path) (subject "") a)
9625 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9626 (setq address (match-string 1 path)
9627 subject (org-link-escape (match-string 2 path))))
9628 (while args
9629 (cond
9630 ((not (stringp (car args))) (push (pop args) args1))
9631 (t (setq a (pop args))
9632 (if (string-match "%a" a)
9633 (setq a (replace-match address t t a)))
9634 (if (string-match "%s" a)
9635 (setq a (replace-match subject t t a)))
9636 (push a args1))))
9637 (apply cmd (nreverse args1))))
9638
9639 ((member type '("http" "https" "ftp" "news"))
9640 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9641 (org-link-escape
9642 path org-link-escape-chars-browser)
9643 path))))
9644
9645 ((string= type "doi")
9646 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9647 (org-link-escape
9648 path org-link-escape-chars-browser)
9649 path))))
9650
9651 ((member type '("message"))
9652 (browse-url (concat type ":" path)))
9653
9654 ((string= type "tags")
9655 (org-tags-view arg path))
9656
9657 ((string= type "tree-match")
9658 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9659
9660 ((string= type "file")
9661 (if (string-match "::\\([0-9]+\\)\\'" path)
9662 (setq line (string-to-number (match-string 1 path))
9663 path (substring path 0 (match-beginning 0)))
9664 (if (string-match "::\\(.+\\)\\'" path)
9665 (setq search (match-string 1 path)
9666 path (substring path 0 (match-beginning 0)))))
9667 (if (string-match "[*?{]" (file-name-nondirectory path))
9668 (dired path)
9669 (org-open-file path arg line search)))
9670
9671 ((string= type "shell")
9672 (let ((cmd path))
9673 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9674 (string-match org-confirm-shell-link-not-regexp cmd))
9675 (not org-confirm-shell-link-function)
9676 (funcall org-confirm-shell-link-function
9677 (format "Execute \"%s\" in shell? "
9678 (org-add-props cmd nil
9679 'face 'org-warning))))
9680 (progn
9681 (message "Executing %s" cmd)
9682 (shell-command cmd))
9683 (error "Abort"))))
9684
9685 ((string= type "elisp")
9686 (let ((cmd path))
9687 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9688 (string-match org-confirm-elisp-link-not-regexp cmd))
9689 (not org-confirm-elisp-link-function)
9690 (funcall org-confirm-elisp-link-function
9691 (format "Execute \"%s\" as elisp? "
9692 (org-add-props cmd nil
9693 'face 'org-warning))))
9694 (message "%s => %s" cmd
9695 (if (equal (string-to-char cmd) ?\()
9696 (eval (read cmd))
9697 (call-interactively (read cmd))))
9698 (error "Abort"))))
9699
9700 ((and (string= type "thisfile")
9701 (run-hook-with-args-until-success
9702 'org-open-link-functions path)))
9703
9704 ((string= type "thisfile")
9705 (if arg
9706 (switch-to-buffer-other-window
9707 (org-get-buffer-for-internal-link (current-buffer)))
9708 (org-mark-ring-push))
9709 (let ((cmd `(org-link-search
9710 ,path
9711 ,(cond ((equal arg '(4)) ''occur)
9712 ((equal arg '(16)) ''org-occur)
9713 (t nil))
9714 ,pos)))
9715 (condition-case nil (let ((org-link-search-inhibit-query t))
9716 (eval cmd))
9717 (error (progn (widen) (eval cmd))))))
9718
9719 (t
9720 (browse-url-at-point)))))))
9721 (move-marker org-open-link-marker nil)
9722 (run-hook-with-args 'org-follow-link-hook)))
9723
9724 (defun org-offer-links-in-entry (&optional nth zero)
9725 "Offer links in the current entry and follow the selected link.
9726 If there is only one link, follow it immediately as well.
9727 If NTH is an integer, immediately pick the NTH link found.
9728 If ZERO is a string, check also this string for a link, and if
9729 there is one, offer it as link number zero."
9730 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9731 "\\(" org-angle-link-re "\\)\\|"
9732 "\\(" org-plain-link-re "\\)"))
9733 (cnt ?0)
9734 (in-emacs (if (integerp nth) nil nth))
9735 have-zero end links link c)
9736 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9737 (push (match-string 0 zero) links)
9738 (setq cnt (1- cnt) have-zero t))
9739 (save-excursion
9740 (org-back-to-heading t)
9741 (setq end (save-excursion (outline-next-heading) (point)))
9742 (while (re-search-forward re end t)
9743 (push (match-string 0) links))
9744 (setq links (org-uniquify (reverse links))))
9745
9746 (cond
9747 ((null links)
9748 (message "No links"))
9749 ((equal (length links) 1)
9750 (setq link (list (car links))))
9751 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9752 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9753 (t ; we have to select a link
9754 (save-excursion
9755 (save-window-excursion
9756 (delete-other-windows)
9757 (with-output-to-temp-buffer "*Select Link*"
9758 (mapc (lambda (l)
9759 (if (not (string-match org-bracket-link-regexp l))
9760 (princ (format "[%c] %s\n" (incf cnt)
9761 (org-remove-angle-brackets l)))
9762 (if (match-end 3)
9763 (princ (format "[%c] %s (%s)\n" (incf cnt)
9764 (match-string 3 l) (match-string 1 l)))
9765 (princ (format "[%c] %s\n" (incf cnt)
9766 (match-string 1 l))))))
9767 links))
9768 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9769 (message "Select link to open, RET to open all:")
9770 (setq c (read-char-exclusive))
9771 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9772 (when (equal c ?q) (error "Abort"))
9773 (if (equal c ?\C-m)
9774 (setq link links)
9775 (setq nth (- c ?0))
9776 (if have-zero (setq nth (1+ nth)))
9777 (unless (and (integerp nth) (>= (length links) nth))
9778 (error "Invalid link selection"))
9779 (setq link (list (nth (1- nth) links))))))
9780 (if link
9781 (let ((buf (current-buffer)))
9782 (dolist (l link)
9783 (org-open-link-from-string l in-emacs buf))
9784 t)
9785 nil)))
9786
9787 ;; Add special file links that specify the way of opening
9788
9789 (org-add-link-type "file+sys" 'org-open-file-with-system)
9790 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9791 (defun org-open-file-with-system (path)
9792 "Open file at PATH using the system way of opening it."
9793 (org-open-file path 'system))
9794 (defun org-open-file-with-emacs (path)
9795 "Open file at PATH in Emacs."
9796 (org-open-file path 'emacs))
9797 (defun org-remove-file-link-modifiers ()
9798 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9799 (goto-char (point-min))
9800 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9801 (org-if-unprotected
9802 (replace-match "file:" t t))))
9803 (eval-after-load "org-exp"
9804 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9805 'org-remove-file-link-modifiers))
9806
9807 ;;;; Time estimates
9808
9809 (defun org-get-effort (&optional pom)
9810 "Get the effort estimate for the current entry."
9811 (org-entry-get pom org-effort-property))
9812
9813 ;;; File search
9814
9815 (defvar org-create-file-search-functions nil
9816 "List of functions to construct the right search string for a file link.
9817 These functions are called in turn with point at the location to
9818 which the link should point.
9819
9820 A function in the hook should first test if it would like to
9821 handle this file type, for example by checking the `major-mode'
9822 or the file extension. If it decides not to handle this file, it
9823 should just return nil to give other functions a chance. If it
9824 does handle the file, it must return the search string to be used
9825 when following the link. The search string will be part of the
9826 file link, given after a double colon, and `org-open-at-point'
9827 will automatically search for it. If special measures must be
9828 taken to make the search successful, another function should be
9829 added to the companion hook `org-execute-file-search-functions',
9830 which see.
9831
9832 A function in this hook may also use `setq' to set the variable
9833 `description' to provide a suggestion for the descriptive text to
9834 be used for this link when it gets inserted into an Org-mode
9835 buffer with \\[org-insert-link].")
9836
9837 (defvar org-execute-file-search-functions nil
9838 "List of functions to execute a file search triggered by a link.
9839
9840 Functions added to this hook must accept a single argument, the
9841 search string that was part of the file link, the part after the
9842 double colon. The function must first check if it would like to
9843 handle this search, for example by checking the `major-mode' or
9844 the file extension. If it decides not to handle this search, it
9845 should just return nil to give other functions a chance. If it
9846 does handle the search, it must return a non-nil value to keep
9847 other functions from trying.
9848
9849 Each function can access the current prefix argument through the
9850 variable `current-prefix-argument'. Note that a single prefix is
9851 used to force opening a link in Emacs, so it may be good to only
9852 use a numeric or double prefix to guide the search function.
9853
9854 In case this is needed, a function in this hook can also restore
9855 the window configuration before `org-open-at-point' was called using:
9856
9857 (set-window-configuration org-window-config-before-follow-link)")
9858
9859 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9860 (defun org-link-search (s &optional type avoid-pos stealth)
9861 "Search for a link search option.
9862 If S is surrounded by forward slashes, it is interpreted as a
9863 regular expression. In org-mode files, this will create an `org-occur'
9864 sparse tree. In ordinary files, `occur' will be used to list matches.
9865 If the current buffer is in `dired-mode', grep will be used to search
9866 in all files. If AVOID-POS is given, ignore matches near that position.
9867
9868 When optional argument STEALTH is non-nil, do not modify
9869 visibility around point, thus ignoring
9870 `org-show-hierarchy-above', `org-show-following-heading' and
9871 `org-show-siblings' variables."
9872 (let ((case-fold-search t)
9873 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9874 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9875 (append '(("") (" ") ("\t") ("\n"))
9876 org-emphasis-alist)
9877 "\\|") "\\)"))
9878 (pos (point))
9879 (pre nil) (post nil)
9880 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9881 (cond
9882 ;; First check if there are any special search functions
9883 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9884 ;; Now try the builtin stuff
9885 ((and (equal (string-to-char s0) ?#)
9886 (> (length s0) 1)
9887 (save-excursion
9888 (goto-char (point-min))
9889 (and
9890 (re-search-forward
9891 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9892 (setq type 'dedicated
9893 pos (match-beginning 0))))
9894 ;; There is an exact target for this
9895 (goto-char pos)
9896 (org-back-to-heading t)))
9897 ((save-excursion
9898 (goto-char (point-min))
9899 (and
9900 (re-search-forward
9901 (concat "<<" (regexp-quote s0) ">>") nil t)
9902 (setq type 'dedicated
9903 pos (match-beginning 0))))
9904 ;; There is an exact target for this
9905 (goto-char pos))
9906 ((and (string-match "^(\\(.*\\))$" s0)
9907 (save-excursion
9908 (goto-char (point-min))
9909 (and
9910 (re-search-forward
9911 (concat "[^[]" (regexp-quote
9912 (format org-coderef-label-format
9913 (match-string 1 s0))))
9914 nil t)
9915 (setq type 'dedicated
9916 pos (1+ (match-beginning 0))))))
9917 ;; There is a coderef target for this
9918 (goto-char pos))
9919 ((string-match "^/\\(.*\\)/$" s)
9920 ;; A regular expression
9921 (cond
9922 ((eq major-mode 'org-mode)
9923 (org-occur (match-string 1 s)))
9924 ;;((eq major-mode 'dired-mode)
9925 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9926 (t (org-do-occur (match-string 1 s)))))
9927 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9928 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9929 (goto-char (point-min))
9930 (cond
9931 ((let (case-fold-search)
9932 (re-search-forward (format org-complex-heading-regexp-format
9933 (regexp-quote s))
9934 nil t))
9935 ;; OK, found a match
9936 (setq type 'dedicated)
9937 (goto-char (match-beginning 0)))
9938 ((and (not org-link-search-inhibit-query)
9939 (eq org-link-search-must-match-exact-headline 'query-to-create)
9940 (y-or-n-p "No match - create this as a new heading? "))
9941 (goto-char (point-max))
9942 (or (bolp) (newline))
9943 (insert "* " s "\n")
9944 (beginning-of-line 0))
9945 (t
9946 (goto-char pos)
9947 (error "No match"))))
9948 (t
9949 ;; A normal search string
9950 (when (equal (string-to-char s) ?*)
9951 ;; Anchor on headlines, post may include tags.
9952 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9953 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9954 s (substring s 1)))
9955 (remove-text-properties
9956 0 (length s)
9957 '(face nil mouse-face nil keymap nil fontified nil) s)
9958 ;; Make a series of regular expressions to find a match
9959 (setq words (org-split-string s "[ \n\r\t]+")
9960
9961 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9962 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9963 "\\)" markers)
9964 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9965 re2a (concat "[ \t\r\n]" re2a_)
9966 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9967 re4 (concat "[^a-zA-Z_]" re4_)
9968
9969 re1 (concat pre re2 post)
9970 re3 (concat pre (if pre re4_ re4) post)
9971 re5 (concat pre ".*" re4)
9972 re2 (concat pre re2)
9973 re2a (concat pre (if pre re2a_ re2a))
9974 re4 (concat pre (if pre re4_ re4))
9975 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9976 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9977 re5 "\\)"
9978 ))
9979 (cond
9980 ((eq type 'org-occur) (org-occur reall))
9981 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9982 (t (goto-char (point-min))
9983 (setq type 'fuzzy)
9984 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9985 (org-search-not-self 1 re1 nil t)
9986 (org-search-not-self 1 re2 nil t)
9987 (org-search-not-self 1 re2a nil t)
9988 (org-search-not-self 1 re3 nil t)
9989 (org-search-not-self 1 re4 nil t)
9990 (org-search-not-self 1 re5 nil t)
9991 )
9992 (goto-char (match-beginning 1))
9993 (goto-char pos)
9994 (error "No match"))))))
9995 (and (eq major-mode 'org-mode)
9996 (not stealth)
9997 (org-show-context 'link-search))
9998 type))
9999
10000 (defun org-search-not-self (group &rest args)
10001 "Execute `re-search-forward', but only accept matches that do not
10002 enclose the position of `org-open-link-marker'."
10003 (let ((m org-open-link-marker))
10004 (catch 'exit
10005 (while (apply 're-search-forward args)
10006 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10007 (goto-char (match-end group))
10008 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10009 (> (match-beginning 0) (marker-position m))
10010 (< (match-end 0) (marker-position m)))
10011 (save-match-data
10012 (or (not (org-in-regexp
10013 org-bracket-link-analytic-regexp 1))
10014 (not (match-end 4)) ; no description
10015 (and (<= (match-beginning 4) (point))
10016 (>= (match-end 4) (point))))))
10017 (throw 'exit (point))))))))
10018
10019 (defun org-get-buffer-for-internal-link (buffer)
10020 "Return a buffer to be used for displaying the link target of internal links."
10021 (cond
10022 ((not org-display-internal-link-with-indirect-buffer)
10023 buffer)
10024 ((string-match "(Clone)$" (buffer-name buffer))
10025 (message "Buffer is already a clone, not making another one")
10026 ;; we also do not modify visibility in this case
10027 buffer)
10028 (t ; make a new indirect buffer for displaying the link
10029 (let* ((bn (buffer-name buffer))
10030 (ibn (concat bn "(Clone)"))
10031 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10032 (with-current-buffer ib (org-overview))
10033 ib))))
10034
10035 (defun org-do-occur (regexp &optional cleanup)
10036 "Call the Emacs command `occur'.
10037 If CLEANUP is non-nil, remove the printout of the regular expression
10038 in the *Occur* buffer. This is useful if the regex is long and not useful
10039 to read."
10040 (occur regexp)
10041 (when cleanup
10042 (let ((cwin (selected-window)) win beg end)
10043 (when (setq win (get-buffer-window "*Occur*"))
10044 (select-window win))
10045 (goto-char (point-min))
10046 (when (re-search-forward "match[a-z]+" nil t)
10047 (setq beg (match-end 0))
10048 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10049 (setq end (1- (match-beginning 0)))))
10050 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10051 (goto-char (point-min))
10052 (select-window cwin))))
10053
10054 ;;; The mark ring for links jumps
10055
10056 (defvar org-mark-ring nil
10057 "Mark ring for positions before jumps in Org-mode.")
10058 (defvar org-mark-ring-last-goto nil
10059 "Last position in the mark ring used to go back.")
10060 ;; Fill and close the ring
10061 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10062 (loop for i from 1 to org-mark-ring-length do
10063 (push (make-marker) org-mark-ring))
10064 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10065 org-mark-ring)
10066
10067 (defun org-mark-ring-push (&optional pos buffer)
10068 "Put the current position or POS into the mark ring and rotate it."
10069 (interactive)
10070 (setq pos (or pos (point)))
10071 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10072 (move-marker (car org-mark-ring)
10073 (or pos (point))
10074 (or buffer (current-buffer)))
10075 (message "%s"
10076 (substitute-command-keys
10077 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10078
10079 (defun org-mark-ring-goto (&optional n)
10080 "Jump to the previous position in the mark ring.
10081 With prefix arg N, jump back that many stored positions. When
10082 called several times in succession, walk through the entire ring.
10083 Org-mode commands jumping to a different position in the current file,
10084 or to another Org-mode file, automatically push the old position
10085 onto the ring."
10086 (interactive "p")
10087 (let (p m)
10088 (if (eq last-command this-command)
10089 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10090 (setq p org-mark-ring))
10091 (setq org-mark-ring-last-goto p)
10092 (setq m (car p))
10093 (org-pop-to-buffer-same-window (marker-buffer m))
10094 (goto-char m)
10095 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10096
10097 (defun org-remove-angle-brackets (s)
10098 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10099 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10100 s)
10101 (defun org-add-angle-brackets (s)
10102 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10103 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10104 s)
10105 (defun org-remove-double-quotes (s)
10106 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10107 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10108 s)
10109
10110 ;;; Following specific links
10111
10112 (defun org-follow-timestamp-link ()
10113 (cond
10114 ((org-at-date-range-p t)
10115 (let ((org-agenda-start-on-weekday)
10116 (t1 (match-string 1))
10117 (t2 (match-string 2)))
10118 (setq t1 (time-to-days (org-time-string-to-time t1))
10119 t2 (time-to-days (org-time-string-to-time t2)))
10120 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10121 ((org-at-timestamp-p t)
10122 (org-agenda-list nil (time-to-days (org-time-string-to-time
10123 (substring (match-string 1) 0 10)))
10124 1))
10125 (t (error "This should not happen"))))
10126
10127
10128 ;;; Following file links
10129 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10130 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10131 (declare-function mailcap-mime-info
10132 "mailcap" (string &optional request no-decode))
10133 (defvar org-wait nil)
10134 (defun org-open-file (path &optional in-emacs line search)
10135 "Open the file at PATH.
10136 First, this expands any special file name abbreviations. Then the
10137 configuration variable `org-file-apps' is checked if it contains an
10138 entry for this file type, and if yes, the corresponding command is launched.
10139
10140 If no application is found, Emacs simply visits the file.
10141
10142 With optional prefix argument IN-EMACS, Emacs will visit the file.
10143 With a double \\[universal-argument] \\[universal-argument] \
10144 prefix arg, Org tries to avoid opening in Emacs
10145 and to use an external application to visit the file.
10146
10147 Optional LINE specifies a line to go to, optional SEARCH a string
10148 to search for. If LINE or SEARCH is given, the file will be
10149 opened in Emacs, unless an entry from org-file-apps that makes
10150 use of groups in a regexp matches.
10151
10152 If you want to change the way frames are used when following a
10153 link, please customize `org-link-frame-setup'.
10154
10155 If the file does not exist, an error is thrown."
10156 (let* ((file (if (equal path "")
10157 buffer-file-name
10158 (substitute-in-file-name (expand-file-name path))))
10159 (file-apps (append org-file-apps (org-default-apps)))
10160 (apps (org-remove-if
10161 'org-file-apps-entry-match-against-dlink-p file-apps))
10162 (apps-dlink (org-remove-if-not
10163 'org-file-apps-entry-match-against-dlink-p file-apps))
10164 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10165 (dirp (if remp nil (file-directory-p file)))
10166 (file (if (and dirp org-open-directory-means-index-dot-org)
10167 (concat (file-name-as-directory file) "index.org")
10168 file))
10169 (a-m-a-p (assq 'auto-mode apps))
10170 (dfile (downcase file))
10171 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10172 (link (cond ((and (eq line nil)
10173 (eq search nil))
10174 file)
10175 (line
10176 (concat file "::" (number-to-string line)))
10177 (search
10178 (concat file "::" search))))
10179 (dlink (downcase link))
10180 (old-buffer (current-buffer))
10181 (old-pos (point))
10182 (old-mode major-mode)
10183 ext cmd link-match-data)
10184 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10185 (setq ext (match-string 1 dfile))
10186 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10187 (setq ext (match-string 1 dfile))))
10188 (cond
10189 ((member in-emacs '((16) system))
10190 (setq cmd (cdr (assoc 'system apps))))
10191 (in-emacs (setq cmd 'emacs))
10192 (t
10193 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10194 (and dirp (cdr (assoc 'directory apps)))
10195 ; first, try matching against apps-dlink
10196 ; if we get a match here, store the match data for later
10197 (let ((match (assoc-default dlink apps-dlink
10198 'string-match)))
10199 (if match
10200 (progn (setq link-match-data (match-data))
10201 match)
10202 (progn (setq in-emacs (or in-emacs line search))
10203 nil))) ; if we have no match in apps-dlink,
10204 ; always open the file in emacs if line or search
10205 ; is given (for backwards compatibility)
10206 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10207 'string-match)
10208 (cdr (assoc ext apps))
10209 (cdr (assoc t apps))))))
10210 (when (eq cmd 'system)
10211 (setq cmd (cdr (assoc 'system apps))))
10212 (when (eq cmd 'default)
10213 (setq cmd (cdr (assoc t apps))))
10214 (when (eq cmd 'mailcap)
10215 (require 'mailcap)
10216 (mailcap-parse-mailcaps)
10217 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10218 (command (mailcap-mime-info mime-type)))
10219 (if (stringp command)
10220 (setq cmd command)
10221 (setq cmd 'emacs))))
10222 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10223 (not (file-exists-p file))
10224 (not org-open-non-existing-files))
10225 (error "No such file: %s" file))
10226 (cond
10227 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10228 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10229 (while (string-match "['\"]%s['\"]" cmd)
10230 (setq cmd (replace-match "%s" t t cmd)))
10231 (while (string-match "%s" cmd)
10232 (setq cmd (replace-match
10233 (save-match-data
10234 (shell-quote-argument
10235 (convert-standard-filename file)))
10236 t t cmd)))
10237
10238 ;; Replace "%1", "%2" etc. in command with group matches from regex
10239 (save-match-data
10240 (let ((match-index 1)
10241 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10242 (set-match-data link-match-data)
10243 (while (<= match-index number-of-groups)
10244 (let ((regex (concat "%" (number-to-string match-index)))
10245 (replace-with (match-string match-index dlink)))
10246 (while (string-match regex cmd)
10247 (setq cmd (replace-match replace-with t t cmd))))
10248 (setq match-index (+ match-index 1)))))
10249
10250 (save-window-excursion
10251 (start-process-shell-command cmd nil cmd)
10252 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10253 ))
10254 ((or (stringp cmd)
10255 (eq cmd 'emacs))
10256 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10257 (widen)
10258 (if line (org-goto-line line)
10259 (if search (org-link-search search))))
10260 ((consp cmd)
10261 (let ((file (convert-standard-filename file)))
10262 (save-match-data
10263 (set-match-data link-match-data)
10264 (eval cmd))))
10265 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10266 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10267 (or (not (equal old-buffer (current-buffer)))
10268 (not (equal old-pos (point))))
10269 (org-mark-ring-push old-pos old-buffer))))
10270
10271 (defun org-file-apps-entry-match-against-dlink-p (entry)
10272 "This function returns non-nil if `entry' uses a regular
10273 expression which should be matched against the whole link by
10274 org-open-file.
10275
10276 It assumes that is the case when the entry uses a regular
10277 expression which has at least one grouping construct and the
10278 action is either a lisp form or a command string containing
10279 '%1', i.e. using at least one subexpression match as a
10280 parameter."
10281 (let ((selector (car entry))
10282 (action (cdr entry)))
10283 (if (stringp selector)
10284 (and (> (regexp-opt-depth selector) 0)
10285 (or (and (stringp action)
10286 (string-match "%[0-9]" action))
10287 (consp action)))
10288 nil)))
10289
10290 (defun org-default-apps ()
10291 "Return the default applications for this operating system."
10292 (cond
10293 ((eq system-type 'darwin)
10294 org-file-apps-defaults-macosx)
10295 ((eq system-type 'windows-nt)
10296 org-file-apps-defaults-windowsnt)
10297 (t org-file-apps-defaults-gnu)))
10298
10299 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10300 "Convert extensions to regular expressions in the cars of LIST.
10301 Also, weed out any non-string entries, because the return value is used
10302 only for regexp matching.
10303 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10304 point to the symbol `emacs', indicating that the file should
10305 be opened in Emacs."
10306 (append
10307 (delq nil
10308 (mapcar (lambda (x)
10309 (if (not (stringp (car x)))
10310 nil
10311 (if (string-match "\\W" (car x))
10312 x
10313 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10314 list))
10315 (if add-auto-mode
10316 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10317
10318 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10319 (defun org-file-remote-p (file)
10320 "Test whether FILE specifies a location on a remote system.
10321 Return non-nil if the location is indeed remote.
10322
10323 For example, the filename \"/user@host:/foo\" specifies a location
10324 on the system \"/user@host:\"."
10325 (cond ((fboundp 'file-remote-p)
10326 (file-remote-p file))
10327 ((fboundp 'tramp-handle-file-remote-p)
10328 (tramp-handle-file-remote-p file))
10329 ((and (boundp 'ange-ftp-name-format)
10330 (string-match (car ange-ftp-name-format) file))
10331 t)
10332 (t nil)))
10333
10334
10335 ;;;; Refiling
10336
10337 (defun org-get-org-file ()
10338 "Read a filename, with default directory `org-directory'."
10339 (let ((default (or org-default-notes-file remember-data-file)))
10340 (read-file-name (format "File name [%s]: " default)
10341 (file-name-as-directory org-directory)
10342 default)))
10343
10344 (defun org-notes-order-reversed-p ()
10345 "Check if the current file should receive notes in reversed order."
10346 (cond
10347 ((not org-reverse-note-order) nil)
10348 ((eq t org-reverse-note-order) t)
10349 ((not (listp org-reverse-note-order)) nil)
10350 (t (catch 'exit
10351 (let ((all org-reverse-note-order)
10352 entry)
10353 (while (setq entry (pop all))
10354 (if (string-match (car entry) buffer-file-name)
10355 (throw 'exit (cdr entry))))
10356 nil)))))
10357
10358 (defvar org-refile-target-table nil
10359 "The list of refile targets, created by `org-refile'.")
10360
10361 (defvar org-agenda-new-buffers nil
10362 "Buffers created to visit agenda files.")
10363
10364 (defvar org-refile-cache nil
10365 "Cache for refile targets.")
10366
10367 (defvar org-refile-markers nil
10368 "All the markers used for caching refile locations.")
10369
10370 (defun org-refile-marker (pos)
10371 "Get a new refile marker, but only if caching is in use."
10372 (if (not org-refile-use-cache)
10373 pos
10374 (let ((m (make-marker)))
10375 (move-marker m pos)
10376 (push m org-refile-markers)
10377 m)))
10378
10379 (defun org-refile-cache-clear ()
10380 "Clear the refile cache and disable all the markers."
10381 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10382 (setq org-refile-markers nil)
10383 (setq org-refile-cache nil)
10384 (message "Refile cache has been cleared"))
10385
10386 (defun org-refile-cache-check-set (set)
10387 "Check if all the markers in the cache still have live buffers."
10388 (let (marker)
10389 (catch 'exit
10390 (while (and set (setq marker (nth 3 (pop set))))
10391 ;; if org-refile-use-outline-path is 'file, marker may be nil
10392 (when (and marker (null (marker-buffer marker)))
10393 (message "not found") (sit-for 3)
10394 (throw 'exit nil)))
10395 t)))
10396
10397 (defun org-refile-cache-put (set &rest identifiers)
10398 "Push the refile targets SET into the cache, under IDENTIFIERS."
10399 (let* ((key (sha1 (prin1-to-string identifiers)))
10400 (entry (assoc key org-refile-cache)))
10401 (if entry
10402 (setcdr entry set)
10403 (push (cons key set) org-refile-cache))))
10404
10405 (defun org-refile-cache-get (&rest identifiers)
10406 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10407 (cond
10408 ((not org-refile-cache) nil)
10409 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10410 (t
10411 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10412 org-refile-cache))))
10413 (and set (org-refile-cache-check-set set) set)))))
10414
10415 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10416 "Produce a table with refile targets."
10417 (let ((case-fold-search nil)
10418 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10419 (entries (or org-refile-targets '((nil . (:level . 1)))))
10420 targets tgs txt re files f desc descre fast-path-p level pos0)
10421 (message "Getting targets...")
10422 (with-current-buffer (or default-buffer (current-buffer))
10423 (while (setq entry (pop entries))
10424 (setq files (car entry) desc (cdr entry))
10425 (setq fast-path-p nil)
10426 (cond
10427 ((null files) (setq files (list (current-buffer))))
10428 ((eq files 'org-agenda-files)
10429 (setq files (org-agenda-files 'unrestricted)))
10430 ((and (symbolp files) (fboundp files))
10431 (setq files (funcall files)))
10432 ((and (symbolp files) (boundp files))
10433 (setq files (symbol-value files))))
10434 (if (stringp files) (setq files (list files)))
10435 (cond
10436 ((eq (car desc) :tag)
10437 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10438 ((eq (car desc) :todo)
10439 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10440 ((eq (car desc) :regexp)
10441 (setq descre (cdr desc)))
10442 ((eq (car desc) :level)
10443 (setq descre (concat "^\\*\\{" (number-to-string
10444 (if org-odd-levels-only
10445 (1- (* 2 (cdr desc)))
10446 (cdr desc)))
10447 "\\}[ \t]")))
10448 ((eq (car desc) :maxlevel)
10449 (setq fast-path-p t)
10450 (setq descre (concat "^\\*\\{1," (number-to-string
10451 (if org-odd-levels-only
10452 (1- (* 2 (cdr desc)))
10453 (cdr desc)))
10454 "\\}[ \t]")))
10455 (t (error "Bad refiling target description %s" desc)))
10456 (while (setq f (pop files))
10457 (with-current-buffer
10458 (if (bufferp f) f (org-get-agenda-file-buffer f))
10459 (or
10460 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10461 (progn
10462 (if (bufferp f) (setq f (buffer-file-name
10463 (buffer-base-buffer f))))
10464 (setq f (and f (expand-file-name f)))
10465 (if (eq org-refile-use-outline-path 'file)
10466 (push (list (file-name-nondirectory f) f nil nil) tgs))
10467 (save-excursion
10468 (save-restriction
10469 (widen)
10470 (goto-char (point-min))
10471 (while (re-search-forward descre nil t)
10472 (goto-char (setq pos0 (point-at-bol)))
10473 (catch 'next
10474 (when org-refile-target-verify-function
10475 (save-match-data
10476 (or (funcall org-refile-target-verify-function)
10477 (throw 'next t))))
10478 (when (and (looking-at org-complex-heading-regexp)
10479 (not (member (match-string 4) excluded-entries))
10480 (match-string 4))
10481 (setq level (org-reduced-level
10482 (- (match-end 1) (match-beginning 1)))
10483 txt (org-link-display-format (match-string 4))
10484 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10485 re (format org-complex-heading-regexp-format
10486 (regexp-quote (match-string 4))))
10487 (when org-refile-use-outline-path
10488 (setq txt (mapconcat
10489 'org-protect-slash
10490 (append
10491 (if (eq org-refile-use-outline-path
10492 'file)
10493 (list (file-name-nondirectory
10494 (buffer-file-name
10495 (buffer-base-buffer))))
10496 (if (eq org-refile-use-outline-path
10497 'full-file-path)
10498 (list (buffer-file-name
10499 (buffer-base-buffer)))))
10500 (org-get-outline-path fast-path-p
10501 level txt)
10502 (list txt))
10503 "/")))
10504 (push (list txt f re (org-refile-marker (point)))
10505 tgs)))
10506 (when (= (point) pos0)
10507 ;; verification function has not moved point
10508 (goto-char (point-at-eol))))))))
10509 (when org-refile-use-cache
10510 (org-refile-cache-put tgs (buffer-file-name) descre))
10511 (setq targets (append tgs targets))
10512 ))))
10513 (message "Getting targets...done")
10514 (nreverse targets)))
10515
10516 (defun org-protect-slash (s)
10517 (while (string-match "/" s)
10518 (setq s (replace-match "\\" t t s)))
10519 s)
10520
10521 (defvar org-olpa (make-vector 20 nil))
10522
10523 (defun org-get-outline-path (&optional fastp level heading)
10524 "Return the outline path to the current entry, as a list.
10525
10526 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10527 routine which makes outline path derivations for an entire file,
10528 avoiding backtracing. Refile target collection makes use of that."
10529 (if fastp
10530 (progn
10531 (if (> level 19)
10532 (error "Outline path failure, more than 19 levels"))
10533 (loop for i from level upto 19 do
10534 (aset org-olpa i nil))
10535 (prog1
10536 (delq nil (append org-olpa nil))
10537 (aset org-olpa level heading)))
10538 (let (rtn case-fold-search)
10539 (save-excursion
10540 (save-restriction
10541 (widen)
10542 (while (org-up-heading-safe)
10543 (when (looking-at org-complex-heading-regexp)
10544 (push (org-match-string-no-properties 4) rtn)))
10545 rtn)))))
10546
10547 (defun org-format-outline-path (path &optional width prefix)
10548 "Format the outline path PATH for display.
10549 Width is the maximum number of characters that is available.
10550 Prefix is a prefix to be included in the returned string,
10551 such as the file name."
10552 (setq width (or width 79))
10553 (if prefix (setq width (- width (length prefix))))
10554 (if (not path)
10555 (or prefix "")
10556 (let* ((nsteps (length path))
10557 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10558 (maxwidth (if (<= total-width width)
10559 10000 ;; everything fits
10560 ;; we need to shorten the level headings
10561 (/ (- width nsteps) nsteps)))
10562 (org-odd-levels-only nil)
10563 (n 0)
10564 (total (1+ (length prefix))))
10565 (setq maxwidth (max maxwidth 10))
10566 (concat prefix
10567 (mapconcat
10568 (lambda (h)
10569 (setq n (1+ n))
10570 (if (and (= n nsteps) (< maxwidth 10000))
10571 (setq maxwidth (- total-width total)))
10572 (if (< (length h) maxwidth)
10573 (progn (setq total (+ total (length h) 1)) h)
10574 (setq h (substring h 0 (- maxwidth 2))
10575 total (+ total maxwidth 1))
10576 (if (string-match "[ \t]+\\'" h)
10577 (setq h (substring h 0 (match-beginning 0))))
10578 (setq h (concat h "..")))
10579 (org-add-props h nil 'face
10580 (nth (% (1- n) org-n-level-faces)
10581 org-level-faces))
10582 h)
10583 path "/")))))
10584
10585 (defun org-display-outline-path (&optional file current)
10586 "Display the current outline path in the echo area."
10587 (interactive "P")
10588 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10589 (case-fold-search nil)
10590 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10591 (if current (setq path (append path
10592 (save-excursion
10593 (org-back-to-heading t)
10594 (if (looking-at org-complex-heading-regexp)
10595 (list (match-string 4)))))))
10596 (message "%s"
10597 (org-format-outline-path
10598 path
10599 (1- (frame-width))
10600 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10601
10602 (defvar org-refile-history nil
10603 "History for refiling operations.")
10604
10605 (defvar org-after-refile-insert-hook nil
10606 "Hook run after `org-refile' has inserted its stuff at the new location.
10607 Note that this is still *before* the stuff will be removed from
10608 the *old* location.")
10609
10610 (defvar org-capture-last-stored-marker)
10611 (defun org-refile (&optional goto default-buffer rfloc)
10612 "Move the entry or entries at point to another heading.
10613 The list of target headings is compiled using the information in
10614 `org-refile-targets', which see.
10615
10616 At the target location, the entry is filed as a subitem of the target
10617 heading. Depending on `org-reverse-note-order', the new subitem will
10618 either be the first or the last subitem.
10619
10620 If there is an active region, all entries in that region will be moved.
10621 However, the region must fulfill the requirement that the first heading
10622 is the first one sets the top-level of the moved text - at most siblings
10623 below it are allowed.
10624
10625 With prefix arg GOTO, the command will only visit the target location
10626 and not actually move anything.
10627
10628 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10629 go to the location where the last refiling operation has put the subtree.
10630 With a prefix argument of `2', refile to the running clock.
10631
10632 RFLOC can be a refile location obtained in a different way.
10633
10634 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10635
10636 If you are using target caching (see `org-refile-use-cache'),
10637 You have to clear the target cache in order to find new targets.
10638 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10639 prefix argument (`C-u C-u C-u C-c C-w')."
10640
10641 (interactive "P")
10642 (if (member goto '(0 (64)))
10643 (org-refile-cache-clear)
10644 (let* ((cbuf (current-buffer))
10645 (regionp (org-region-active-p))
10646 (region-start (and regionp (region-beginning)))
10647 (region-end (and regionp (region-end)))
10648 (region-length (and regionp (- region-end region-start)))
10649 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10650 pos it nbuf file re level reversed)
10651 (setq last-command nil)
10652 (when regionp
10653 (goto-char region-start)
10654 (or (bolp) (goto-char (point-at-bol)))
10655 (setq region-start (point))
10656 (unless (or (org-kill-is-subtree-p
10657 (buffer-substring region-start region-end))
10658 (prog1 org-refile-active-region-within-subtree
10659 (org-toggle-heading)))
10660 (error "The region is not a (sequence of) subtree(s)")))
10661 (if (equal goto '(16))
10662 (org-refile-goto-last-stored)
10663 (when (or
10664 (and (equal goto 2)
10665 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10666 (prog1
10667 (setq it (list (or org-clock-heading "running clock")
10668 (buffer-file-name
10669 (marker-buffer org-clock-hd-marker))
10670 ""
10671 (marker-position org-clock-hd-marker)))
10672 (setq goto nil)))
10673 (setq it (or rfloc
10674 (let (heading-text)
10675 (save-excursion
10676 (unless goto
10677 (org-back-to-heading t)
10678 (setq heading-text
10679 (nth 4 (org-heading-components))))
10680 (org-refile-get-location
10681 (cond (goto "Goto")
10682 (regionp "Refile region to")
10683 (t (concat "Refile subtree \""
10684 heading-text "\" to")))
10685 default-buffer
10686 (and (not (equal '(4) goto))
10687 org-refile-allow-creating-parent-nodes)
10688 goto))))))
10689 (setq file (nth 1 it)
10690 re (nth 2 it)
10691 pos (nth 3 it))
10692 (if (and (not goto)
10693 pos
10694 (equal (buffer-file-name) file)
10695 (if regionp
10696 (and (>= pos region-start)
10697 (<= pos region-end))
10698 (and (>= pos (point))
10699 (< pos (save-excursion
10700 (org-end-of-subtree t t))))))
10701 (error "Cannot refile to position inside the tree or region"))
10702
10703 (setq nbuf (or (find-buffer-visiting file)
10704 (find-file-noselect file)))
10705 (if goto
10706 (progn
10707 (org-pop-to-buffer-same-window nbuf)
10708 (goto-char pos)
10709 (org-show-context 'org-goto))
10710 (if regionp
10711 (progn
10712 (org-kill-new (buffer-substring region-start region-end))
10713 (org-save-markers-in-region region-start region-end))
10714 (org-copy-subtree 1 nil t))
10715 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10716 (find-file-noselect file)))
10717 (setq reversed (org-notes-order-reversed-p))
10718 (save-excursion
10719 (save-restriction
10720 (widen)
10721 (if pos
10722 (progn
10723 (goto-char pos)
10724 (looking-at org-outline-regexp)
10725 (setq level (org-get-valid-level (funcall outline-level) 1))
10726 (goto-char
10727 (if reversed
10728 (or (outline-next-heading) (point-max))
10729 (or (save-excursion (org-get-next-sibling))
10730 (org-end-of-subtree t t)
10731 (point-max)))))
10732 (setq level 1)
10733 (if (not reversed)
10734 (goto-char (point-max))
10735 (goto-char (point-min))
10736 (or (outline-next-heading) (goto-char (point-max)))))
10737 (if (not (bolp)) (newline))
10738 (org-paste-subtree level)
10739 (when org-log-refile
10740 (org-add-log-setup 'refile nil nil 'findpos
10741 org-log-refile)
10742 (unless (eq org-log-refile 'note)
10743 (save-excursion (org-add-log-note))))
10744 (and org-auto-align-tags (org-set-tags nil t))
10745 (bookmark-set "org-refile-last-stored")
10746 ;; If we are refiling for capture, make sure that the
10747 ;; last-capture pointers point here
10748 (when (org-bound-and-true-p org-refile-for-capture)
10749 (bookmark-set "org-capture-last-stored-marker")
10750 (move-marker org-capture-last-stored-marker (point)))
10751 (if (fboundp 'deactivate-mark) (deactivate-mark))
10752 (run-hooks 'org-after-refile-insert-hook))))
10753 (if regionp
10754 (delete-region (point) (+ (point) region-length))
10755 (org-cut-subtree))
10756 (when (featurep 'org-inlinetask)
10757 (org-inlinetask-remove-END-maybe))
10758 (setq org-markers-to-move nil)
10759 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10760
10761 (defun org-refile-goto-last-stored ()
10762 "Go to the location where the last refile was stored."
10763 (interactive)
10764 (bookmark-jump "org-refile-last-stored")
10765 (message "This is the location of the last refile"))
10766
10767 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10768 no-exclude)
10769 "Prompt the user for a refile location, using PROMPT.
10770 PROMPT should not be suffixed with a colon and a space, because
10771 this function appends the default value from
10772 `org-refile-history' automatically, if that is not empty.
10773 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10774 this is used for the GOTO interface."
10775 (let ((org-refile-targets org-refile-targets)
10776 (org-refile-use-outline-path org-refile-use-outline-path)
10777 excluded-entries)
10778 (when (and (eq major-mode 'org-mode)
10779 (not org-refile-use-cache)
10780 (not no-exclude))
10781 (org-map-tree
10782 (lambda()
10783 (setq excluded-entries
10784 (append excluded-entries (list (org-get-heading t t)))))))
10785 (setq org-refile-target-table
10786 (org-refile-get-targets default-buffer excluded-entries)))
10787 (unless org-refile-target-table
10788 (error "No refile targets"))
10789 (let* ((prompt (concat prompt
10790 (and (car org-refile-history)
10791 (concat " (default " (car org-refile-history) ")"))
10792 ": "))
10793 (cbuf (current-buffer))
10794 (partial-completion-mode nil)
10795 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10796 (cfunc (if (and org-refile-use-outline-path
10797 org-outline-path-complete-in-steps)
10798 'org-olpath-completing-read
10799 'org-icompleting-read))
10800 (extra (if org-refile-use-outline-path "/" ""))
10801 (filename (and cfn (expand-file-name cfn)))
10802 (tbl (mapcar
10803 (lambda (x)
10804 (if (and (not (member org-refile-use-outline-path
10805 '(file full-file-path)))
10806 (not (equal filename (nth 1 x))))
10807 (cons (concat (car x) extra " ("
10808 (file-name-nondirectory (nth 1 x)) ")")
10809 (cdr x))
10810 (cons (concat (car x) extra) (cdr x))))
10811 org-refile-target-table))
10812 (completion-ignore-case t)
10813 pa answ parent-target child parent old-hist)
10814 (setq old-hist org-refile-history)
10815 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10816 nil 'org-refile-history (car org-refile-history)))
10817 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10818 (org-refile-check-position pa)
10819 (if pa
10820 (progn
10821 (when (or (not org-refile-history)
10822 (not (eq old-hist org-refile-history))
10823 (not (equal (car pa) (car org-refile-history))))
10824 (setq org-refile-history
10825 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10826 org-refile-history
10827 (cdr org-refile-history))))
10828 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10829 (pop org-refile-history)))
10830 pa)
10831 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10832 (progn
10833 (setq parent (match-string 1 answ)
10834 child (match-string 2 answ))
10835 (setq parent-target (or (assoc parent tbl)
10836 (assoc (concat parent "/") tbl)))
10837 (when (and parent-target
10838 (or (eq new-nodes t)
10839 (and (eq new-nodes 'confirm)
10840 (y-or-n-p (format "Create new node \"%s\"? "
10841 child)))))
10842 (org-refile-new-child parent-target child)))
10843 (error "Invalid target location")))))
10844
10845 (defun org-refile-check-position (refile-pointer)
10846 "Check if the refile pointer matches the readline to which it points."
10847 (let* ((file (nth 1 refile-pointer))
10848 (re (nth 2 refile-pointer))
10849 (pos (nth 3 refile-pointer))
10850 buffer)
10851 (when (org-string-nw-p re)
10852 (setq buffer (if (markerp pos)
10853 (marker-buffer pos)
10854 (or (find-buffer-visiting file)
10855 (find-file-noselect file))))
10856 (with-current-buffer buffer
10857 (save-excursion
10858 (save-restriction
10859 (widen)
10860 (goto-char pos)
10861 (beginning-of-line 1)
10862 (unless (org-looking-at-p re)
10863 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10864
10865 (defun org-refile-new-child (parent-target child)
10866 "Use refile target PARENT-TARGET to add new CHILD below it."
10867 (unless parent-target
10868 (error "Cannot find parent for new node"))
10869 (let ((file (nth 1 parent-target))
10870 (pos (nth 3 parent-target))
10871 level)
10872 (with-current-buffer (or (find-buffer-visiting file)
10873 (find-file-noselect file))
10874 (save-excursion
10875 (save-restriction
10876 (widen)
10877 (if pos
10878 (goto-char pos)
10879 (goto-char (point-max))
10880 (if (not (bolp)) (newline)))
10881 (when (looking-at org-outline-regexp)
10882 (setq level (funcall outline-level))
10883 (org-end-of-subtree t t))
10884 (org-back-over-empty-lines)
10885 (insert "\n" (make-string
10886 (if pos (org-get-valid-level level 1) 1) ?*)
10887 " " child "\n")
10888 (beginning-of-line 0)
10889 (list (concat (car parent-target) "/" child) file "" (point)))))))
10890
10891 (defun org-olpath-completing-read (prompt collection &rest args)
10892 "Read an outline path like a file name."
10893 (let ((thetable collection)
10894 (org-completion-use-ido nil) ; does not work with ido.
10895 (org-completion-use-iswitchb nil)) ; or iswitchb
10896 (apply
10897 'org-icompleting-read prompt
10898 (lambda (string predicate &optional flag)
10899 (let (rtn r f (l (length string)))
10900 (cond
10901 ((eq flag nil)
10902 ;; try completion
10903 (try-completion string thetable))
10904 ((eq flag t)
10905 ;; all-completions
10906 (setq rtn (all-completions string thetable predicate))
10907 (mapcar
10908 (lambda (x)
10909 (setq r (substring x l))
10910 (if (string-match " ([^)]*)$" x)
10911 (setq f (match-string 0 x))
10912 (setq f ""))
10913 (if (string-match "/" r)
10914 (concat string (substring r 0 (match-end 0)) f)
10915 x))
10916 rtn))
10917 ((eq flag 'lambda)
10918 ;; exact match?
10919 (assoc string thetable)))
10920 ))
10921 args)))
10922
10923 ;;;; Dynamic blocks
10924
10925 (defun org-find-dblock (name)
10926 "Find the first dynamic block with name NAME in the buffer.
10927 If not found, stay at current position and return nil."
10928 (let (pos)
10929 (save-excursion
10930 (goto-char (point-min))
10931 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10932 nil t)
10933 (match-beginning 0))))
10934 (if pos (goto-char pos))
10935 pos))
10936
10937 (defconst org-dblock-start-re
10938 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10939 "Matches the start line of a dynamic block, with parameters.")
10940
10941 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10942 "Matches the end of a dynamic block.")
10943
10944 (defun org-create-dblock (plist)
10945 "Create a dynamic block section, with parameters taken from PLIST.
10946 PLIST must contain a :name entry which is used as name of the block."
10947 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10948 (end-of-line 1)
10949 (newline))
10950 (let ((col (current-column))
10951 (name (plist-get plist :name)))
10952 (insert "#+BEGIN: " name)
10953 (while plist
10954 (if (eq (car plist) :name)
10955 (setq plist (cddr plist))
10956 (insert " " (prin1-to-string (pop plist)))))
10957 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10958 (beginning-of-line -2)))
10959
10960 (defun org-prepare-dblock ()
10961 "Prepare dynamic block for refresh.
10962 This empties the block, puts the cursor at the insert position and returns
10963 the property list including an extra property :name with the block name."
10964 (unless (looking-at org-dblock-start-re)
10965 (error "Not at a dynamic block"))
10966 (let* ((begdel (1+ (match-end 0)))
10967 (name (org-no-properties (match-string 1)))
10968 (params (append (list :name name)
10969 (read (concat "(" (match-string 3) ")")))))
10970 (save-excursion
10971 (beginning-of-line 1)
10972 (skip-chars-forward " \t")
10973 (setq params (plist-put params :indentation-column (current-column))))
10974 (unless (re-search-forward org-dblock-end-re nil t)
10975 (error "Dynamic block not terminated"))
10976 (setq params
10977 (append params
10978 (list :content (buffer-substring
10979 begdel (match-beginning 0)))))
10980 (delete-region begdel (match-beginning 0))
10981 (goto-char begdel)
10982 (open-line 1)
10983 params))
10984
10985 (defun org-map-dblocks (&optional command)
10986 "Apply COMMAND to all dynamic blocks in the current buffer.
10987 If COMMAND is not given, use `org-update-dblock'."
10988 (let ((cmd (or command 'org-update-dblock)))
10989 (save-excursion
10990 (goto-char (point-min))
10991 (while (re-search-forward org-dblock-start-re nil t)
10992 (goto-char (match-beginning 0))
10993 (save-excursion
10994 (condition-case nil
10995 (funcall cmd)
10996 (error (message "Error during update of dynamic block"))))
10997 (unless (re-search-forward org-dblock-end-re nil t)
10998 (error "Dynamic block not terminated"))))))
10999
11000 (defun org-dblock-update (&optional arg)
11001 "User command for updating dynamic blocks.
11002 Update the dynamic block at point. With prefix ARG, update all dynamic
11003 blocks in the buffer."
11004 (interactive "P")
11005 (if arg
11006 (org-update-all-dblocks)
11007 (or (looking-at org-dblock-start-re)
11008 (org-beginning-of-dblock))
11009 (org-update-dblock)))
11010
11011 (defun org-update-dblock ()
11012 "Update the dynamic block at point.
11013 This means to empty the block, parse for parameters and then call
11014 the correct writing function."
11015 (interactive)
11016 (save-window-excursion
11017 (let* ((pos (point))
11018 (line (org-current-line))
11019 (params (org-prepare-dblock))
11020 (name (plist-get params :name))
11021 (indent (plist-get params :indentation-column))
11022 (cmd (intern (concat "org-dblock-write:" name))))
11023 (message "Updating dynamic block `%s' at line %d..." name line)
11024 (funcall cmd params)
11025 (message "Updating dynamic block `%s' at line %d...done" name line)
11026 (goto-char pos)
11027 (when (and indent (> indent 0))
11028 (setq indent (make-string indent ?\ ))
11029 (save-excursion
11030 (org-beginning-of-dblock)
11031 (forward-line 1)
11032 (while (not (looking-at org-dblock-end-re))
11033 (insert indent)
11034 (beginning-of-line 2))
11035 (when (looking-at org-dblock-end-re)
11036 (and (looking-at "[ \t]+")
11037 (replace-match ""))
11038 (insert indent)))))))
11039
11040 (defun org-beginning-of-dblock ()
11041 "Find the beginning of the dynamic block at point.
11042 Error if there is no such block at point."
11043 (let ((pos (point))
11044 beg)
11045 (end-of-line 1)
11046 (if (and (re-search-backward org-dblock-start-re nil t)
11047 (setq beg (match-beginning 0))
11048 (re-search-forward org-dblock-end-re nil t)
11049 (> (match-end 0) pos))
11050 (goto-char beg)
11051 (goto-char pos)
11052 (error "Not in a dynamic block"))))
11053
11054 (defun org-update-all-dblocks ()
11055 "Update all dynamic blocks in the buffer.
11056 This function can be used in a hook."
11057 (interactive)
11058 (when (eq major-mode 'org-mode)
11059 (org-map-dblocks 'org-update-dblock)))
11060
11061
11062 ;;;; Completion
11063
11064 (defconst org-additional-option-like-keywords
11065 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11066 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11067 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11068 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11069 "BEGIN:" "END:"
11070 "ORGTBL" "TBLFM:" "TBLNAME:"
11071 "BEGIN_EXAMPLE" "END_EXAMPLE"
11072 "BEGIN_QUOTE" "END_QUOTE"
11073 "BEGIN_VERSE" "END_VERSE"
11074 "BEGIN_CENTER" "END_CENTER"
11075 "BEGIN_SRC" "END_SRC"
11076 "BEGIN_RESULT" "END_RESULT"
11077 "NAME:" "RESULTS:"
11078 "HEADER:" "HEADERS:"
11079 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11080 "CAPTION:" "LABEL:"
11081 "SETUPFILE:"
11082 "INCLUDE:"
11083 "BIND:"
11084 "MACRO:"))
11085
11086 (defcustom org-structure-template-alist
11087 '(
11088 ("s" "#+begin_src ?\n\n#+end_src"
11089 "<src lang=\"?\">\n\n</src>")
11090 ("e" "#+begin_example\n?\n#+end_example"
11091 "<example>\n?\n</example>")
11092 ("q" "#+begin_quote\n?\n#+end_quote"
11093 "<quote>\n?\n</quote>")
11094 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11095 "<verse>\n?\n</verse>")
11096 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11097 "<center>\n?\n</center>")
11098 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11099 "<literal style=\"latex\">\n?\n</literal>")
11100 ("L" "#+latex: "
11101 "<literal style=\"latex\">?</literal>")
11102 ("h" "#+begin_html\n?\n#+end_html"
11103 "<literal style=\"html\">\n?\n</literal>")
11104 ("H" "#+html: "
11105 "<literal style=\"html\">?</literal>")
11106 ("a" "#+begin_ascii\n?\n#+end_ascii")
11107 ("A" "#+ascii: ")
11108 ("i" "#+index: ?"
11109 "#+index: ?")
11110 ("I" "#+include %file ?"
11111 "<include file=%file markup=\"?\">")
11112 )
11113 "Structure completion elements.
11114 This is a list of abbreviation keys and values. The value gets inserted
11115 if you type `<' followed by the key and then press the completion key,
11116 usually `M-TAB'. %file will be replaced by a file name after prompting
11117 for the file using completion. The cursor will be placed at the position
11118 of the `?` in the template.
11119 There are two templates for each key, the first uses the original Org syntax,
11120 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11121 the default when the /org-mtags.el/ module has been loaded. See also the
11122 variable `org-mtags-prefer-muse-templates'.
11123 This is an experimental feature, it is undecided if it is going to stay in."
11124 :group 'org-completion
11125 :type '(repeat
11126 (string :tag "Key")
11127 (string :tag "Template")
11128 (string :tag "Muse Template")))
11129
11130 (defun org-try-structure-completion ()
11131 "Try to complete a structure template before point.
11132 This looks for strings like \"<e\" on an otherwise empty line and
11133 expands them."
11134 (let ((l (buffer-substring (point-at-bol) (point)))
11135 a)
11136 (when (and (looking-at "[ \t]*$")
11137 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11138 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11139 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11140 (match-beginning 1)) a)
11141 t)))
11142
11143 (defun org-complete-expand-structure-template (start cell)
11144 "Expand a structure template."
11145 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11146 (rpl (nth (if musep 2 1) cell))
11147 (ind ""))
11148 (delete-region start (point))
11149 (when (string-match "\\`#\\+" rpl)
11150 (cond
11151 ((bolp))
11152 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11153 (setq ind (buffer-substring (point-at-bol) (point))))
11154 (t (newline))))
11155 (setq start (point))
11156 (if (string-match "%file" rpl)
11157 (setq rpl (replace-match
11158 (concat
11159 "\""
11160 (save-match-data
11161 (abbreviate-file-name (read-file-name "Include file: ")))
11162 "\"")
11163 t t rpl)))
11164 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11165 (concat "\n" ind)))
11166 (insert rpl)
11167 (if (re-search-backward "\\?" start t) (delete-char 1))))
11168
11169 ;;;; TODO, DEADLINE, Comments
11170
11171 (defun org-toggle-comment ()
11172 "Change the COMMENT state of an entry."
11173 (interactive)
11174 (save-excursion
11175 (org-back-to-heading)
11176 (let (case-fold-search)
11177 (cond
11178 ((looking-at (format org-heading-keyword-regexp-format
11179 org-comment-string))
11180 (goto-char (match-end 1))
11181 (looking-at (concat " +" org-comment-string))
11182 (replace-match "" t t)
11183 (when (eolp) (insert " ")))
11184 ((looking-at org-outline-regexp)
11185 (goto-char (match-end 0))
11186 (insert org-comment-string " "))))))
11187
11188 (defvar org-last-todo-state-is-todo nil
11189 "This is non-nil when the last TODO state change led to a TODO state.
11190 If the last change removed the TODO tag or switched to DONE, then
11191 this is nil.")
11192
11193 (defvar org-setting-tags nil) ; dynamically skipped
11194
11195 (defvar org-todo-setup-filter-hook nil
11196 "Hook for functions that pre-filter todo specs.
11197 Each function takes a todo spec and returns either nil or the spec
11198 transformed into canonical form." )
11199
11200 (defvar org-todo-get-default-hook nil
11201 "Hook for functions that get a default item for todo.
11202 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11203 nil or a string to be used for the todo mark." )
11204
11205 (defvar org-agenda-headline-snapshot-before-repeat)
11206
11207 (defun org-current-effective-time ()
11208 "Return current time adjusted for `org-extend-today-until' variable"
11209 (let* ((ct (org-current-time))
11210 (dct (decode-time ct))
11211 (ct1
11212 (if (and org-use-effective-time
11213 (< (nth 2 dct) org-extend-today-until))
11214 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11215 ct)))
11216 ct1))
11217
11218 (defun org-todo-yesterday (&optional arg)
11219 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11220 (interactive "P")
11221 (if (eq major-mode 'org-agenda-mode)
11222 (apply 'org-agenda-todo-yesterday arg)
11223 (let* ((hour (third (decode-time
11224 (org-current-time))))
11225 (org-extend-today-until (1+ hour)))
11226 (org-todo arg))))
11227
11228 (defun org-todo (&optional arg)
11229 "Change the TODO state of an item.
11230 The state of an item is given by a keyword at the start of the heading,
11231 like
11232 *** TODO Write paper
11233 *** DONE Call mom
11234
11235 The different keywords are specified in the variable `org-todo-keywords'.
11236 By default the available states are \"TODO\" and \"DONE\".
11237 So for this example: when the item starts with TODO, it is changed to DONE.
11238 When it starts with DONE, the DONE is removed. And when neither TODO nor
11239 DONE are present, add TODO at the beginning of the heading.
11240
11241 With \\[universal-argument] prefix arg, use completion to determine the new \
11242 state.
11243 With numeric prefix arg, switch to that state.
11244 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11245 keywords (nextset).
11246 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11247 With a numeric prefix arg of 0, inhibit note taking for the change.
11248
11249 For calling through lisp, arg is also interpreted in the following way:
11250 'none -> empty state
11251 \"\"(empty string) -> switch to empty state
11252 'done -> switch to DONE
11253 'nextset -> switch to the next set of keywords
11254 'previousset -> switch to the previous set of keywords
11255 \"WAITING\" -> switch to the specified keyword, but only if it
11256 really is a member of `org-todo-keywords'."
11257 (interactive "P")
11258 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11259 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11260 'region-start-level 'region))
11261 org-loop-over-headlines-in-active-region)
11262 (org-map-entries
11263 `(org-todo ,arg)
11264 org-loop-over-headlines-in-active-region
11265 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11266 (if (equal arg '(16)) (setq arg 'nextset))
11267 (let ((org-blocker-hook org-blocker-hook)
11268 (case-fold-search nil))
11269 (when (equal arg '(64))
11270 (setq arg nil org-blocker-hook nil))
11271 (when (and org-blocker-hook
11272 (or org-inhibit-blocking
11273 (org-entry-get nil "NOBLOCKING")))
11274 (setq org-blocker-hook nil))
11275 (save-excursion
11276 (catch 'exit
11277 (org-back-to-heading t)
11278 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11279 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11280 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11281 (let* ((match-data (match-data))
11282 (startpos (point-at-bol))
11283 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11284 (org-log-done org-log-done)
11285 (org-log-repeat org-log-repeat)
11286 (org-todo-log-states org-todo-log-states)
11287 (org-inhibit-logging
11288 (if (equal arg 0)
11289 (progn (setq arg nil) 'note) org-inhibit-logging))
11290 (this (match-string 1))
11291 (hl-pos (match-beginning 0))
11292 (head (org-get-todo-sequence-head this))
11293 (ass (assoc head org-todo-kwd-alist))
11294 (interpret (nth 1 ass))
11295 (done-word (nth 3 ass))
11296 (final-done-word (nth 4 ass))
11297 (org-last-state (or this ""))
11298 (completion-ignore-case t)
11299 (member (member this org-todo-keywords-1))
11300 (tail (cdr member))
11301 (org-state (cond
11302 ((and org-todo-key-trigger
11303 (or (and (equal arg '(4))
11304 (eq org-use-fast-todo-selection 'prefix))
11305 (and (not arg) org-use-fast-todo-selection
11306 (not (eq org-use-fast-todo-selection
11307 'prefix)))))
11308 ;; Use fast selection
11309 (org-fast-todo-selection))
11310 ((and (equal arg '(4))
11311 (or (not org-use-fast-todo-selection)
11312 (not org-todo-key-trigger)))
11313 ;; Read a state with completion
11314 (org-icompleting-read
11315 "State: " (mapcar (lambda(x) (list x))
11316 org-todo-keywords-1)
11317 nil t))
11318 ((eq arg 'right)
11319 (if this
11320 (if tail (car tail) nil)
11321 (car org-todo-keywords-1)))
11322 ((eq arg 'left)
11323 (if (equal member org-todo-keywords-1)
11324 nil
11325 (if this
11326 (nth (- (length org-todo-keywords-1)
11327 (length tail) 2)
11328 org-todo-keywords-1)
11329 (org-last org-todo-keywords-1))))
11330 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11331 (setq arg nil))) ; hack to fall back to cycling
11332 (arg
11333 ;; user or caller requests a specific state
11334 (cond
11335 ((equal arg "") nil)
11336 ((eq arg 'none) nil)
11337 ((eq arg 'done) (or done-word (car org-done-keywords)))
11338 ((eq arg 'nextset)
11339 (or (car (cdr (member head org-todo-heads)))
11340 (car org-todo-heads)))
11341 ((eq arg 'previousset)
11342 (let ((org-todo-heads (reverse org-todo-heads)))
11343 (or (car (cdr (member head org-todo-heads)))
11344 (car org-todo-heads))))
11345 ((car (member arg org-todo-keywords-1)))
11346 ((stringp arg)
11347 (error "State `%s' not valid in this file" arg))
11348 ((nth (1- (prefix-numeric-value arg))
11349 org-todo-keywords-1))))
11350 ((null member) (or head (car org-todo-keywords-1)))
11351 ((equal this final-done-word) nil) ;; -> make empty
11352 ((null tail) nil) ;; -> first entry
11353 ((memq interpret '(type priority))
11354 (if (eq this-command last-command)
11355 (car tail)
11356 (if (> (length tail) 0)
11357 (or done-word (car org-done-keywords))
11358 nil)))
11359 (t
11360 (car tail))))
11361 (org-state (or
11362 (run-hook-with-args-until-success
11363 'org-todo-get-default-hook org-state org-last-state)
11364 org-state))
11365 (next (if org-state (concat " " org-state " ") " "))
11366 (change-plist (list :type 'todo-state-change :from this :to org-state
11367 :position startpos))
11368 dolog now-done-p)
11369 (when org-blocker-hook
11370 (setq org-last-todo-state-is-todo
11371 (not (member this org-done-keywords)))
11372 (unless (save-excursion
11373 (save-match-data
11374 (org-with-wide-buffer
11375 (run-hook-with-args-until-failure
11376 'org-blocker-hook change-plist))))
11377 (if (org-called-interactively-p 'interactive)
11378 (error "TODO state change from %s to %s blocked" this org-state)
11379 ;; fail silently
11380 (message "TODO state change from %s to %s blocked" this org-state)
11381 (throw 'exit nil))))
11382 (store-match-data match-data)
11383 (replace-match next t t)
11384 (unless (pos-visible-in-window-p hl-pos)
11385 (message "TODO state changed to %s" (org-trim next)))
11386 (unless head
11387 (setq head (org-get-todo-sequence-head org-state)
11388 ass (assoc head org-todo-kwd-alist)
11389 interpret (nth 1 ass)
11390 done-word (nth 3 ass)
11391 final-done-word (nth 4 ass)))
11392 (when (memq arg '(nextset previousset))
11393 (message "Keyword-Set %d/%d: %s"
11394 (- (length org-todo-sets) -1
11395 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11396 (length org-todo-sets)
11397 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11398 (setq org-last-todo-state-is-todo
11399 (not (member org-state org-done-keywords)))
11400 (setq now-done-p (and (member org-state org-done-keywords)
11401 (not (member this org-done-keywords))))
11402 (and logging (org-local-logging logging))
11403 (when (and (or org-todo-log-states org-log-done)
11404 (not (eq org-inhibit-logging t))
11405 (not (memq arg '(nextset previousset))))
11406 ;; we need to look at recording a time and note
11407 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11408 (nth 2 (assoc this org-todo-log-states))))
11409 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11410 (setq dolog 'time))
11411 (when (and org-state
11412 (member org-state org-not-done-keywords)
11413 (not (member this org-not-done-keywords)))
11414 ;; This is now a todo state and was not one before
11415 ;; If there was a CLOSED time stamp, get rid of it.
11416 (org-add-planning-info nil nil 'closed))
11417 (when (and now-done-p org-log-done)
11418 ;; It is now done, and it was not done before
11419 (org-add-planning-info 'closed (org-current-effective-time))
11420 (if (and (not dolog) (eq 'note org-log-done))
11421 (org-add-log-setup 'done org-state this 'findpos 'note)))
11422 (when (and org-state dolog)
11423 ;; This is a non-nil state, and we need to log it
11424 (org-add-log-setup 'state org-state this 'findpos dolog)))
11425 ;; Fixup tag positioning
11426 (org-todo-trigger-tag-changes org-state)
11427 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11428 (when org-provide-todo-statistics
11429 (org-update-parent-todo-statistics))
11430 (run-hooks 'org-after-todo-state-change-hook)
11431 (if (and arg (not (member org-state org-done-keywords)))
11432 (setq head (org-get-todo-sequence-head org-state)))
11433 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11434 ;; Do we need to trigger a repeat?
11435 (when now-done-p
11436 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11437 ;; This is for the agenda, take a snapshot of the headline.
11438 (save-match-data
11439 (setq org-agenda-headline-snapshot-before-repeat
11440 (org-get-heading))))
11441 (org-auto-repeat-maybe org-state))
11442 ;; Fixup cursor location if close to the keyword
11443 (if (and (outline-on-heading-p)
11444 (not (bolp))
11445 (save-excursion (beginning-of-line 1)
11446 (looking-at org-todo-line-regexp))
11447 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11448 (progn
11449 (goto-char (or (match-end 2) (match-end 1)))
11450 (and (looking-at " ") (just-one-space))))
11451 (when org-trigger-hook
11452 (save-excursion
11453 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11454
11455 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11456 "Block turning an entry into a TODO, using the hierarchy.
11457 This checks whether the current task should be blocked from state
11458 changes. Such blocking occurs when:
11459
11460 1. The task has children which are not all in a completed state.
11461
11462 2. A task has a parent with the property :ORDERED:, and there
11463 are siblings prior to the current task with incomplete
11464 status.
11465
11466 3. The parent of the task is blocked because it has siblings that should
11467 be done first, or is child of a block grandparent TODO entry."
11468
11469 (if (not org-enforce-todo-dependencies)
11470 t ; if locally turned off don't block
11471 (catch 'dont-block
11472 ;; If this is not a todo state change, or if this entry is already DONE,
11473 ;; do not block
11474 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11475 (member (plist-get change-plist :from)
11476 (cons 'done org-done-keywords))
11477 (member (plist-get change-plist :to)
11478 (cons 'todo org-not-done-keywords))
11479 (not (plist-get change-plist :to)))
11480 (throw 'dont-block t))
11481 ;; If this task has children, and any are undone, it's blocked
11482 (save-excursion
11483 (org-back-to-heading t)
11484 (let ((this-level (funcall outline-level)))
11485 (outline-next-heading)
11486 (let ((child-level (funcall outline-level)))
11487 (while (and (not (eobp))
11488 (> child-level this-level))
11489 ;; this todo has children, check whether they are all
11490 ;; completed
11491 (if (and (not (org-entry-is-done-p))
11492 (org-entry-is-todo-p))
11493 (throw 'dont-block nil))
11494 (outline-next-heading)
11495 (setq child-level (funcall outline-level))))))
11496 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11497 ;; any previous siblings are undone, it's blocked
11498 (save-excursion
11499 (org-back-to-heading t)
11500 (let* ((pos (point))
11501 (parent-pos (and (org-up-heading-safe) (point))))
11502 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11503 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11504 (forward-line 1)
11505 (re-search-forward org-not-done-heading-regexp pos t))
11506 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11507 ;; Search further up the hierarchy, to see if an ancestor is blocked
11508 (while t
11509 (goto-char parent-pos)
11510 (if (not (looking-at org-not-done-heading-regexp))
11511 (throw 'dont-block t)) ; do not block, parent is not a TODO
11512 (setq pos (point))
11513 (setq parent-pos (and (org-up-heading-safe) (point)))
11514 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11515 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11516 (forward-line 1)
11517 (re-search-forward org-not-done-heading-regexp pos t))
11518 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11519
11520 (defcustom org-track-ordered-property-with-tag nil
11521 "Should the ORDERED property also be shown as a tag?
11522 The ORDERED property decides if an entry should require subtasks to be
11523 completed in sequence. Since a property is not very visible, setting
11524 this option means that toggling the ORDERED property with the command
11525 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11526 not relevant for the behavior, but it makes things more visible.
11527
11528 Note that toggling the tag with tags commands will not change the property
11529 and therefore not influence behavior!
11530
11531 This can be t, meaning the tag ORDERED should be used, It can also be a
11532 string to select a different tag for this task."
11533 :group 'org-todo
11534 :type '(choice
11535 (const :tag "No tracking" nil)
11536 (const :tag "Track with ORDERED tag" t)
11537 (string :tag "Use other tag")))
11538
11539 (defun org-toggle-ordered-property ()
11540 "Toggle the ORDERED property of the current entry.
11541 For better visibility, you can track the value of this property with a tag.
11542 See variable `org-track-ordered-property-with-tag'."
11543 (interactive)
11544 (let* ((t1 org-track-ordered-property-with-tag)
11545 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11546 (save-excursion
11547 (org-back-to-heading)
11548 (if (org-entry-get nil "ORDERED")
11549 (progn
11550 (org-delete-property "ORDERED")
11551 (and tag (org-toggle-tag tag 'off))
11552 (message "Subtasks can be completed in arbitrary order"))
11553 (org-entry-put nil "ORDERED" "t")
11554 (and tag (org-toggle-tag tag 'on))
11555 (message "Subtasks must be completed in sequence")))))
11556
11557 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11558 (defun org-block-todo-from-checkboxes (change-plist)
11559 "Block turning an entry into a TODO, using checkboxes.
11560 This checks whether the current task should be blocked from state
11561 changes because there are unchecked boxes in this entry."
11562 (if (not org-enforce-todo-checkbox-dependencies)
11563 t ; if locally turned off don't block
11564 (catch 'dont-block
11565 ;; If this is not a todo state change, or if this entry is already DONE,
11566 ;; do not block
11567 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11568 (member (plist-get change-plist :from)
11569 (cons 'done org-done-keywords))
11570 (member (plist-get change-plist :to)
11571 (cons 'todo org-not-done-keywords))
11572 (not (plist-get change-plist :to)))
11573 (throw 'dont-block t))
11574 ;; If this task has checkboxes that are not checked, it's blocked
11575 (save-excursion
11576 (org-back-to-heading t)
11577 (let ((beg (point)) end)
11578 (outline-next-heading)
11579 (setq end (point))
11580 (goto-char beg)
11581 (if (org-list-search-forward
11582 (concat (org-item-beginning-re)
11583 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11584 "\\[[- ]\\]")
11585 end t)
11586 (progn
11587 (if (boundp 'org-blocked-by-checkboxes)
11588 (setq org-blocked-by-checkboxes t))
11589 (throw 'dont-block nil)))))
11590 t))) ; do not block
11591
11592 (defun org-entry-blocked-p ()
11593 "Is the current entry blocked?"
11594 (if (org-entry-get nil "NOBLOCKING")
11595 nil ;; Never block this entry
11596 (not
11597 (run-hook-with-args-until-failure
11598 'org-blocker-hook
11599 (list :type 'todo-state-change
11600 :position (point)
11601 :from 'todo
11602 :to 'done)))))
11603
11604 (defun org-update-statistics-cookies (all)
11605 "Update the statistics cookie, either from TODO or from checkboxes.
11606 This should be called with the cursor in a line with a statistics cookie."
11607 (interactive "P")
11608 (if all
11609 (progn
11610 (org-update-checkbox-count 'all)
11611 (org-map-entries 'org-update-parent-todo-statistics))
11612 (if (not (org-at-heading-p))
11613 (org-update-checkbox-count)
11614 (let ((pos (move-marker (make-marker) (point)))
11615 end l1 l2)
11616 (ignore-errors (org-back-to-heading t))
11617 (if (not (org-at-heading-p))
11618 (org-update-checkbox-count)
11619 (setq l1 (org-outline-level))
11620 (setq end (save-excursion
11621 (outline-next-heading)
11622 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11623 (point)))
11624 (if (and (save-excursion
11625 (re-search-forward
11626 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11627 (not (save-excursion (re-search-forward
11628 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11629 (org-update-checkbox-count)
11630 (if (and l2 (> l2 l1))
11631 (progn
11632 (goto-char end)
11633 (org-update-parent-todo-statistics))
11634 (goto-char pos)
11635 (beginning-of-line 1)
11636 (while (re-search-forward
11637 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11638 (point-at-eol) t)
11639 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11640 (goto-char pos)
11641 (move-marker pos nil)))))
11642
11643 (defvar org-entry-property-inherited-from) ;; defined below
11644 (defun org-update-parent-todo-statistics ()
11645 "Update any statistics cookie in the parent of the current headline.
11646 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11647 the entire subtree and this will travel up the hierarchy and update
11648 statistics everywhere."
11649 (let* ((prop (save-excursion (org-up-heading-safe)
11650 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11651 (recursive (or (not org-hierarchical-todo-statistics)
11652 (and prop (string-match "\\<recursive\\>" prop))))
11653 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11654 0))
11655 (first t)
11656 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11657 level ltoggle l1 new ndel
11658 (cnt-all 0) (cnt-done 0) is-percent kwd
11659 checkbox-beg ov ovs ove cookie-present)
11660 (catch 'exit
11661 (save-excursion
11662 (beginning-of-line 1)
11663 (setq ltoggle (funcall outline-level))
11664 ;; Three situations are to consider:
11665
11666 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11667 ;; to the top-level ancestor on the headline;
11668
11669 ;; 2. If parent has "recursive" property, repeat up to the
11670 ;; headline setting that property, taking inheritance into
11671 ;; account;
11672
11673 ;; 3. Else, move up to direct parent and proceed only once.
11674 (while (and (setq level (org-up-heading-safe))
11675 (or recursive first)
11676 (>= (point) lim))
11677 (setq first nil cookie-present nil)
11678 (unless (and level
11679 (not (string-match
11680 "\\<checkbox\\>"
11681 (downcase (or (org-entry-get nil "COOKIE_DATA")
11682 "")))))
11683 (throw 'exit nil))
11684 (while (re-search-forward box-re (point-at-eol) t)
11685 (setq cnt-all 0 cnt-done 0 cookie-present t)
11686 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11687 (save-match-data
11688 (unless (outline-next-heading) (throw 'exit nil))
11689 (while (and (looking-at org-complex-heading-regexp)
11690 (> (setq l1 (length (match-string 1))) level))
11691 (setq kwd (and (or recursive (= l1 ltoggle))
11692 (match-string 2)))
11693 (if (or (eq org-provide-todo-statistics 'all-headlines)
11694 (and (listp org-provide-todo-statistics)
11695 (or (member kwd org-provide-todo-statistics)
11696 (member kwd org-done-keywords))))
11697 (setq cnt-all (1+ cnt-all))
11698 (if (eq org-provide-todo-statistics t)
11699 (and kwd (setq cnt-all (1+ cnt-all)))))
11700 (and (member kwd org-done-keywords)
11701 (setq cnt-done (1+ cnt-done)))
11702 (outline-next-heading)))
11703 (setq new
11704 (if is-percent
11705 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11706 (format "[%d/%d]" cnt-done cnt-all))
11707 ndel (- (match-end 0) checkbox-beg))
11708 ;; handle overlays when updating cookie from column view
11709 (when (setq ov (car (overlays-at checkbox-beg)))
11710 (setq ovs (overlay-start ov) ove (overlay-end ov))
11711 (delete-overlay ov))
11712 (goto-char checkbox-beg)
11713 (insert new)
11714 (delete-region (point) (+ (point) ndel))
11715 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11716 (when ov (move-overlay ov ovs ove)))
11717 (when cookie-present
11718 (run-hook-with-args 'org-after-todo-statistics-hook
11719 cnt-done (- cnt-all cnt-done))))))
11720 (run-hooks 'org-todo-statistics-hook)))
11721
11722 (defvar org-after-todo-statistics-hook nil
11723 "Hook that is called after a TODO statistics cookie has been updated.
11724 Each function is called with two arguments: the number of not-done entries
11725 and the number of done entries.
11726
11727 For example, the following function, when added to this hook, will switch
11728 an entry to DONE when all children are done, and back to TODO when new
11729 entries are set to a TODO status. Note that this hook is only called
11730 when there is a statistics cookie in the headline!
11731
11732 (defun org-summary-todo (n-done n-not-done)
11733 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11734 (let (org-log-done org-log-states) ; turn off logging
11735 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11736 ")
11737
11738 (defvar org-todo-statistics-hook nil
11739 "Hook that is run whenever Org thinks TODO statistics should be updated.
11740 This hook runs even if there is no statistics cookie present, in which case
11741 `org-after-todo-statistics-hook' would not run.")
11742
11743 (defun org-todo-trigger-tag-changes (state)
11744 "Apply the changes defined in `org-todo-state-tags-triggers'."
11745 (let ((l org-todo-state-tags-triggers)
11746 changes)
11747 (when (or (not state) (equal state ""))
11748 (setq changes (append changes (cdr (assoc "" l)))))
11749 (when (and (stringp state) (> (length state) 0))
11750 (setq changes (append changes (cdr (assoc state l)))))
11751 (when (member state org-not-done-keywords)
11752 (setq changes (append changes (cdr (assoc 'todo l)))))
11753 (when (member state org-done-keywords)
11754 (setq changes (append changes (cdr (assoc 'done l)))))
11755 (dolist (c changes)
11756 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11757
11758 (defun org-local-logging (value)
11759 "Get logging settings from a property VALUE."
11760 (let* (words w a)
11761 ;; directly set the variables, they are already local.
11762 (setq org-log-done nil
11763 org-log-repeat nil
11764 org-todo-log-states nil)
11765 (setq words (org-split-string value))
11766 (while (setq w (pop words))
11767 (cond
11768 ((setq a (assoc w org-startup-options))
11769 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11770 (set (nth 1 a) (nth 2 a))))
11771 ((setq a (org-extract-log-state-settings w))
11772 (and (member (car a) org-todo-keywords-1)
11773 (push a org-todo-log-states)))))))
11774
11775 (defun org-get-todo-sequence-head (kwd)
11776 "Return the head of the TODO sequence to which KWD belongs.
11777 If KWD is not set, check if there is a text property remembering the
11778 right sequence."
11779 (let (p)
11780 (cond
11781 ((not kwd)
11782 (or (get-text-property (point-at-bol) 'org-todo-head)
11783 (progn
11784 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11785 nil (point-at-eol)))
11786 (get-text-property p 'org-todo-head))))
11787 ((not (member kwd org-todo-keywords-1))
11788 (car org-todo-keywords-1))
11789 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11790
11791 (defun org-fast-todo-selection ()
11792 "Fast TODO keyword selection with single keys.
11793 Returns the new TODO keyword, or nil if no state change should occur."
11794 (let* ((fulltable org-todo-key-alist)
11795 (done-keywords org-done-keywords) ;; needed for the faces.
11796 (maxlen (apply 'max (mapcar
11797 (lambda (x)
11798 (if (stringp (car x)) (string-width (car x)) 0))
11799 fulltable)))
11800 (expert nil)
11801 (fwidth (+ maxlen 3 1 3))
11802 (ncol (/ (- (window-width) 4) fwidth))
11803 tg cnt e c tbl
11804 groups ingroup)
11805 (save-excursion
11806 (save-window-excursion
11807 (if expert
11808 (set-buffer (get-buffer-create " *Org todo*"))
11809 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11810 (erase-buffer)
11811 (org-set-local 'org-done-keywords done-keywords)
11812 (setq tbl fulltable cnt 0)
11813 (while (setq e (pop tbl))
11814 (cond
11815 ((equal e '(:startgroup))
11816 (push '() groups) (setq ingroup t)
11817 (when (not (= cnt 0))
11818 (setq cnt 0)
11819 (insert "\n"))
11820 (insert "{ "))
11821 ((equal e '(:endgroup))
11822 (setq ingroup nil cnt 0)
11823 (insert "}\n"))
11824 ((equal e '(:newline))
11825 (when (not (= cnt 0))
11826 (setq cnt 0)
11827 (insert "\n")
11828 (setq e (car tbl))
11829 (while (equal (car tbl) '(:newline))
11830 (insert "\n")
11831 (setq tbl (cdr tbl)))))
11832 (t
11833 (setq tg (car e) c (cdr e))
11834 (if ingroup (push tg (car groups)))
11835 (setq tg (org-add-props tg nil 'face
11836 (org-get-todo-face tg)))
11837 (if (and (= cnt 0) (not ingroup)) (insert " "))
11838 (insert "[" c "] " tg (make-string
11839 (- fwidth 4 (length tg)) ?\ ))
11840 (when (= (setq cnt (1+ cnt)) ncol)
11841 (insert "\n")
11842 (if ingroup (insert " "))
11843 (setq cnt 0)))))
11844 (insert "\n")
11845 (goto-char (point-min))
11846 (if (not expert) (org-fit-window-to-buffer))
11847 (message "[a-z..]:Set [SPC]:clear")
11848 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11849 (cond
11850 ((or (= c ?\C-g)
11851 (and (= c ?q) (not (rassoc c fulltable))))
11852 (setq quit-flag t))
11853 ((= c ?\ ) nil)
11854 ((setq e (rassoc c fulltable) tg (car e))
11855 tg)
11856 (t (setq quit-flag t)))))))
11857
11858 (defun org-entry-is-todo-p ()
11859 (member (org-get-todo-state) org-not-done-keywords))
11860
11861 (defun org-entry-is-done-p ()
11862 (member (org-get-todo-state) org-done-keywords))
11863
11864 (defun org-get-todo-state ()
11865 (save-excursion
11866 (org-back-to-heading t)
11867 (and (looking-at org-todo-line-regexp)
11868 (match-end 2)
11869 (match-string 2))))
11870
11871 (defun org-at-date-range-p (&optional inactive-ok)
11872 "Is the cursor inside a date range?"
11873 (interactive)
11874 (save-excursion
11875 (catch 'exit
11876 (let ((pos (point)))
11877 (skip-chars-backward "^[<\r\n")
11878 (skip-chars-backward "<[")
11879 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11880 (>= (match-end 0) pos)
11881 (throw 'exit t))
11882 (skip-chars-backward "^<[\r\n")
11883 (skip-chars-backward "<[")
11884 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11885 (>= (match-end 0) pos)
11886 (throw 'exit t)))
11887 nil)))
11888
11889 (defun org-get-repeat (&optional tagline)
11890 "Check if there is a deadline/schedule with repeater in this entry."
11891 (save-match-data
11892 (save-excursion
11893 (org-back-to-heading t)
11894 (and (re-search-forward (if tagline
11895 (concat tagline "\\s-*" org-repeat-re)
11896 org-repeat-re)
11897 (org-entry-end-position) t)
11898 (match-string-no-properties 1)))))
11899
11900 (defvar org-last-changed-timestamp)
11901 (defvar org-last-inserted-timestamp)
11902 (defvar org-log-post-message)
11903 (defvar org-log-note-purpose)
11904 (defvar org-log-note-how)
11905 (defvar org-log-note-extra)
11906 (defun org-auto-repeat-maybe (done-word)
11907 "Check if the current headline contains a repeated deadline/schedule.
11908 If yes, set TODO state back to what it was and change the base date
11909 of repeating deadline/scheduled time stamps to new date.
11910 This function is run automatically after each state change to a DONE state."
11911 ;; last-state is dynamically scoped into this function
11912 (let* ((repeat (org-get-repeat))
11913 (aa (assoc org-last-state org-todo-kwd-alist))
11914 (interpret (nth 1 aa))
11915 (head (nth 2 aa))
11916 (whata '(("d" . day) ("m" . month) ("y" . year)))
11917 (msg "Entry repeats: ")
11918 (org-log-done nil)
11919 (org-todo-log-states nil)
11920 re type n what ts time to-state)
11921 (when repeat
11922 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11923 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11924 org-todo-repeat-to-state))
11925 (unless (and to-state (member to-state org-todo-keywords-1))
11926 (setq to-state (if (eq interpret 'type) org-last-state head)))
11927 (org-todo to-state)
11928 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11929 (org-entry-put nil "LAST_REPEAT" (format-time-string
11930 (org-time-stamp-format t t))))
11931 (when org-log-repeat
11932 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11933 (memq 'org-add-log-note post-command-hook))
11934 ;; OK, we are already setup for some record
11935 (if (eq org-log-repeat 'note)
11936 ;; make sure we take a note, not only a time stamp
11937 (setq org-log-note-how 'note))
11938 ;; Set up for taking a record
11939 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11940 org-last-state
11941 'findpos org-log-repeat)))
11942 (org-back-to-heading t)
11943 (org-add-planning-info nil nil 'closed)
11944 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11945 org-deadline-time-regexp "\\)\\|\\("
11946 org-ts-regexp "\\)"))
11947 (while (re-search-forward
11948 re (save-excursion (outline-next-heading) (point)) t)
11949 (setq type (if (match-end 1) org-scheduled-string
11950 (if (match-end 3) org-deadline-string "Plain:"))
11951 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11952 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11953 (setq n (string-to-number (match-string 2 ts))
11954 what (match-string 3 ts))
11955 (if (equal what "w") (setq n (* n 7) what "d"))
11956 ;; Preparation, see if we need to modify the start date for the change
11957 (when (match-end 1)
11958 (setq time (save-match-data (org-time-string-to-time ts)))
11959 (cond
11960 ((equal (match-string 1 ts) ".")
11961 ;; Shift starting date to today
11962 (org-timestamp-change
11963 (- (org-today) (time-to-days time))
11964 'day))
11965 ((equal (match-string 1 ts) "+")
11966 (let ((nshiftmax 10) (nshift 0))
11967 (while (or (= nshift 0)
11968 (<= (time-to-days time)
11969 (time-to-days (current-time))))
11970 (when (= (incf nshift) nshiftmax)
11971 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11972 (error "Abort")))
11973 (org-timestamp-change n (cdr (assoc what whata)))
11974 (org-at-timestamp-p t)
11975 (setq ts (match-string 1))
11976 (setq time (save-match-data (org-time-string-to-time ts)))))
11977 (org-timestamp-change (- n) (cdr (assoc what whata)))
11978 ;; rematch, so that we have everything in place for the real shift
11979 (org-at-timestamp-p t)
11980 (setq ts (match-string 1))
11981 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11982 (org-timestamp-change n (cdr (assoc what whata)))
11983 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11984 (setq org-log-post-message msg)
11985 (message "%s" msg))))
11986
11987 (defun org-show-todo-tree (arg)
11988 "Make a compact tree which shows all headlines marked with TODO.
11989 The tree will show the lines where the regexp matches, and all higher
11990 headlines above the match.
11991 With a \\[universal-argument] prefix, prompt for a regexp to match.
11992 With a numeric prefix N, construct a sparse tree for the Nth element
11993 of `org-todo-keywords-1'."
11994 (interactive "P")
11995 (let ((case-fold-search nil)
11996 (kwd-re
11997 (cond ((null arg) org-not-done-regexp)
11998 ((equal arg '(4))
11999 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12000 (mapcar 'list org-todo-keywords-1))))
12001 (concat "\\("
12002 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12003 "\\)\\>")))
12004 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12005 (regexp-quote (nth (1- (prefix-numeric-value arg))
12006 org-todo-keywords-1)))
12007 (t (error "Invalid prefix argument: %s" arg)))))
12008 (message "%d TODO entries found"
12009 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12010
12011 (defun org-deadline (&optional remove time)
12012 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12013 With argument REMOVE, remove any deadline from the item.
12014 With argument TIME, set the deadline at the corresponding date. TIME
12015 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12016 (interactive "P")
12017 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12018 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12019 'region-start-level 'region))
12020 org-loop-over-headlines-in-active-region)
12021 (org-map-entries
12022 `(org-deadline ',remove ,time)
12023 org-loop-over-headlines-in-active-region
12024 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12025 (let* ((old-date (org-entry-get nil "DEADLINE"))
12026 (repeater (and old-date
12027 (string-match
12028 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12029 old-date)
12030 (match-string 1 old-date))))
12031 (if remove
12032 (progn
12033 (when (and old-date org-log-redeadline)
12034 (org-add-log-setup 'deldeadline nil old-date 'findpos
12035 org-log-redeadline))
12036 (org-remove-timestamp-with-keyword org-deadline-string)
12037 (message "Item no longer has a deadline."))
12038 (org-add-planning-info 'deadline time 'closed)
12039 (when (and old-date org-log-redeadline
12040 (not (equal old-date
12041 (substring org-last-inserted-timestamp 1 -1))))
12042 (org-add-log-setup 'redeadline nil old-date 'findpos
12043 org-log-redeadline))
12044 (when repeater
12045 (save-excursion
12046 (org-back-to-heading t)
12047 (when (re-search-forward (concat org-deadline-string " "
12048 org-last-inserted-timestamp)
12049 (save-excursion
12050 (outline-next-heading) (point)) t)
12051 (goto-char (1- (match-end 0)))
12052 (insert " " repeater)
12053 (setq org-last-inserted-timestamp
12054 (concat (substring org-last-inserted-timestamp 0 -1)
12055 " " repeater
12056 (substring org-last-inserted-timestamp -1))))))
12057 (message "Deadline on %s" org-last-inserted-timestamp)))))
12058
12059 (defun org-schedule (&optional remove time)
12060 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12061 With argument REMOVE, remove any scheduling date from the item.
12062 With argument TIME, scheduled at the corresponding date. TIME can
12063 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12064 (interactive "P")
12065 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12066 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12067 'region-start-level 'region))
12068 org-loop-over-headlines-in-active-region)
12069 (org-map-entries
12070 `(org-schedule ',remove ,time)
12071 org-loop-over-headlines-in-active-region
12072 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12073 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12074 (repeater (and old-date
12075 (string-match
12076 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12077 old-date)
12078 (match-string 1 old-date))))
12079 (if remove
12080 (progn
12081 (when (and old-date org-log-reschedule)
12082 (org-add-log-setup 'delschedule nil old-date 'findpos
12083 org-log-reschedule))
12084 (org-remove-timestamp-with-keyword org-scheduled-string)
12085 (message "Item is no longer scheduled."))
12086 (org-add-planning-info 'scheduled time 'closed)
12087 (when (and old-date org-log-reschedule
12088 (not (equal old-date
12089 (substring org-last-inserted-timestamp 1 -1))))
12090 (org-add-log-setup 'reschedule nil old-date 'findpos
12091 org-log-reschedule))
12092 (when repeater
12093 (save-excursion
12094 (org-back-to-heading t)
12095 (when (re-search-forward (concat org-scheduled-string " "
12096 org-last-inserted-timestamp)
12097 (save-excursion
12098 (outline-next-heading) (point)) t)
12099 (goto-char (1- (match-end 0)))
12100 (insert " " repeater)
12101 (setq org-last-inserted-timestamp
12102 (concat (substring org-last-inserted-timestamp 0 -1)
12103 " " repeater
12104 (substring org-last-inserted-timestamp -1))))))
12105 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12106
12107 (defun org-get-scheduled-time (pom &optional inherit)
12108 "Get the scheduled time as a time tuple, of a format suitable
12109 for calling org-schedule with, or if there is no scheduling,
12110 returns nil."
12111 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12112 (when time
12113 (apply 'encode-time (org-parse-time-string time)))))
12114
12115 (defun org-get-deadline-time (pom &optional inherit)
12116 "Get the deadline as a time tuple, of a format suitable for
12117 calling org-deadline with, or if there is no scheduling, returns
12118 nil."
12119 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12120 (when time
12121 (apply 'encode-time (org-parse-time-string time)))))
12122
12123 (defun org-remove-timestamp-with-keyword (keyword)
12124 "Remove all time stamps with KEYWORD in the current entry."
12125 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12126 beg)
12127 (save-excursion
12128 (org-back-to-heading t)
12129 (setq beg (point))
12130 (outline-next-heading)
12131 (while (re-search-backward re beg t)
12132 (replace-match "")
12133 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12134 (equal (char-before) ?\ ))
12135 (backward-delete-char 1)
12136 (if (string-match "^[ \t]*$" (buffer-substring
12137 (point-at-bol) (point-at-eol)))
12138 (delete-region (point-at-bol)
12139 (min (point-max) (1+ (point-at-eol))))))))))
12140
12141 (defun org-add-planning-info (what &optional time &rest remove)
12142 "Insert new timestamp with keyword in the line directly after the headline.
12143 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12144 If non is given, the user is prompted for a date.
12145 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12146 be removed."
12147 (interactive)
12148 (let (org-time-was-given org-end-time-was-given ts
12149 end default-time default-input)
12150
12151 (catch 'exit
12152 (when (and (memq what '(scheduled deadline))
12153 (or (not time)
12154 (and (stringp time)
12155 (string-match "^[-+]+[0-9]" time))))
12156 ;; Try to get a default date/time from existing timestamp
12157 (save-excursion
12158 (org-back-to-heading t)
12159 (setq end (save-excursion (outline-next-heading) (point)))
12160 (when (re-search-forward (if (eq what 'scheduled)
12161 org-scheduled-time-regexp
12162 org-deadline-time-regexp)
12163 end t)
12164 (setq ts (match-string 1)
12165 default-time
12166 (apply 'encode-time (org-parse-time-string ts))
12167 default-input (and ts (org-get-compact-tod ts))))))
12168 (when what
12169 (setq time
12170 (if (stringp time)
12171 ;; This is a string (relative or absolute), set proper date
12172 (apply 'encode-time
12173 (org-read-date-analyze
12174 time default-time (decode-time default-time)))
12175 ;; If necessary, get the time from the user
12176 (or time (org-read-date nil 'to-time nil nil
12177 default-time default-input)))))
12178
12179 (when (and org-insert-labeled-timestamps-at-point
12180 (member what '(scheduled deadline)))
12181 (insert
12182 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12183 (org-insert-time-stamp time org-time-was-given
12184 nil nil nil (list org-end-time-was-given))
12185 (setq what nil))
12186 (save-excursion
12187 (save-restriction
12188 (let (col list elt ts buffer-invisibility-spec)
12189 (org-back-to-heading t)
12190 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12191 (goto-char (match-end 1))
12192 (setq col (current-column))
12193 (goto-char (match-end 0))
12194 (if (eobp) (insert "\n") (forward-char 1))
12195 (when (and (not what)
12196 (not (looking-at
12197 (concat "[ \t]*"
12198 org-keyword-time-not-clock-regexp))))
12199 ;; Nothing to add, nothing to remove...... :-)
12200 (throw 'exit nil))
12201 (if (and (not (looking-at org-outline-regexp))
12202 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12203 "[^\r\n]*"))
12204 (not (equal (match-string 1) org-clock-string)))
12205 (narrow-to-region (match-beginning 0) (match-end 0))
12206 (insert-before-markers "\n")
12207 (backward-char 1)
12208 (narrow-to-region (point) (point))
12209 (and org-adapt-indentation (org-indent-to-column col)))
12210 ;; Check if we have to remove something.
12211 (setq list (cons what remove))
12212 (while list
12213 (setq elt (pop list))
12214 (when (or (and (eq elt 'scheduled)
12215 (re-search-forward org-scheduled-time-regexp nil t))
12216 (and (eq elt 'deadline)
12217 (re-search-forward org-deadline-time-regexp nil t))
12218 (and (eq elt 'closed)
12219 (re-search-forward org-closed-time-regexp nil t)))
12220 (replace-match "")
12221 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12222 (and (looking-at "[ \t]+") (replace-match ""))
12223 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12224 (when what
12225 (insert
12226 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12227 (cond ((eq what 'scheduled) org-scheduled-string)
12228 ((eq what 'deadline) org-deadline-string)
12229 ((eq what 'closed) org-closed-string))
12230 " ")
12231 (setq ts (org-insert-time-stamp
12232 time
12233 (or org-time-was-given
12234 (and (eq what 'closed) org-log-done-with-time))
12235 (eq what 'closed)
12236 nil nil (list org-end-time-was-given)))
12237 (insert
12238 (if (not (or (bolp) (eq (char-before) ?\ )
12239 (memq (char-after) '(32 10))
12240 (eobp))) " " ""))
12241 (end-of-line 1))
12242 (goto-char (point-min))
12243 (widen)
12244 (if (and (looking-at "[ \t]*\n")
12245 (equal (char-before) ?\n))
12246 (delete-region (1- (point)) (point-at-eol)))
12247 ts))))))
12248
12249 (defvar org-log-note-marker (make-marker))
12250 (defvar org-log-note-purpose nil)
12251 (defvar org-log-note-state nil)
12252 (defvar org-log-note-previous-state nil)
12253 (defvar org-log-note-how nil)
12254 (defvar org-log-note-extra nil)
12255 (defvar org-log-note-window-configuration nil)
12256 (defvar org-log-note-return-to (make-marker))
12257 (defvar org-log-note-effective-time nil
12258 "Remembered current time so that dynamically scoped
12259 `org-extend-today-until' affects tha timestamps in state change
12260 log")
12261
12262 (defvar org-log-post-message nil
12263 "Message to be displayed after a log note has been stored.
12264 The auto-repeater uses this.")
12265
12266 (defun org-add-note ()
12267 "Add a note to the current entry.
12268 This is done in the same way as adding a state change note."
12269 (interactive)
12270 (org-add-log-setup 'note nil nil 'findpos nil))
12271
12272 (defvar org-property-end-re)
12273 (defun org-add-log-setup (&optional purpose state prev-state
12274 findpos how extra)
12275 "Set up the post command hook to take a note.
12276 If this is about to TODO state change, the new state is expected in STATE.
12277 When FINDPOS is non-nil, find the correct position for the note in
12278 the current entry. If not, assume that it can be inserted at point.
12279 HOW is an indicator what kind of note should be created.
12280 EXTRA is additional text that will be inserted into the notes buffer."
12281 (let* ((org-log-into-drawer (org-log-into-drawer))
12282 (drawer (cond ((stringp org-log-into-drawer)
12283 org-log-into-drawer)
12284 (org-log-into-drawer "LOGBOOK")
12285 (t nil))))
12286 (save-restriction
12287 (save-excursion
12288 (when findpos
12289 (org-back-to-heading t)
12290 (narrow-to-region (point) (save-excursion
12291 (outline-next-heading) (point)))
12292 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12293 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12294 "[^\r\n]*\\)?"))
12295 (goto-char (match-end 0))
12296 (cond
12297 (drawer
12298 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12299 nil t)
12300 (progn
12301 (goto-char (match-end 0))
12302 (or org-log-states-order-reversed
12303 (and (re-search-forward org-property-end-re nil t)
12304 (goto-char (1- (match-beginning 0))))))
12305 (insert "\n:" drawer ":\n:END:")
12306 (beginning-of-line 0)
12307 (org-indent-line-function)
12308 (beginning-of-line 2)
12309 (org-indent-line-function)
12310 (end-of-line 0)))
12311 ((and org-log-state-notes-insert-after-drawers
12312 (save-excursion
12313 (forward-line) (looking-at org-drawer-regexp)))
12314 (forward-line)
12315 (while (looking-at org-drawer-regexp)
12316 (goto-char (match-end 0))
12317 (re-search-forward org-property-end-re (point-max) t)
12318 (forward-line))
12319 (forward-line -1)))
12320 (unless org-log-states-order-reversed
12321 (and (= (char-after) ?\n) (forward-char 1))
12322 (org-skip-over-state-notes)
12323 (skip-chars-backward " \t\n\r")))
12324 (move-marker org-log-note-marker (point))
12325 (setq org-log-note-purpose purpose
12326 org-log-note-state state
12327 org-log-note-previous-state prev-state
12328 org-log-note-how how
12329 org-log-note-extra extra
12330 org-log-note-effective-time (org-current-effective-time))
12331 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12332
12333 (defun org-skip-over-state-notes ()
12334 "Skip past the list of State notes in an entry."
12335 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12336 (when (ignore-errors (goto-char (org-in-item-p)))
12337 (let* ((struct (org-list-struct))
12338 (prevs (org-list-prevs-alist struct)))
12339 (while (looking-at "[ \t]*- State")
12340 (goto-char (or (org-list-get-next-item (point) struct prevs)
12341 (org-list-get-item-end (point) struct)))))))
12342
12343 (defun org-add-log-note (&optional purpose)
12344 "Pop up a window for taking a note, and add this note later at point."
12345 (remove-hook 'post-command-hook 'org-add-log-note)
12346 (setq org-log-note-window-configuration (current-window-configuration))
12347 (delete-other-windows)
12348 (move-marker org-log-note-return-to (point))
12349 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12350 (goto-char org-log-note-marker)
12351 (org-switch-to-buffer-other-window "*Org Note*")
12352 (erase-buffer)
12353 (if (memq org-log-note-how '(time state))
12354 (let (current-prefix-arg) (org-store-log-note))
12355 (let ((org-inhibit-startup t)) (org-mode))
12356 (insert (format "# Insert note for %s.
12357 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12358 (cond
12359 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12360 ((eq org-log-note-purpose 'done) "closed todo item")
12361 ((eq org-log-note-purpose 'state)
12362 (format "state change from \"%s\" to \"%s\""
12363 (or org-log-note-previous-state "")
12364 (or org-log-note-state "")))
12365 ((eq org-log-note-purpose 'reschedule)
12366 "rescheduling")
12367 ((eq org-log-note-purpose 'delschedule)
12368 "no longer scheduled")
12369 ((eq org-log-note-purpose 'redeadline)
12370 "changing deadline")
12371 ((eq org-log-note-purpose 'deldeadline)
12372 "removing deadline")
12373 ((eq org-log-note-purpose 'refile)
12374 "refiling")
12375 ((eq org-log-note-purpose 'note)
12376 "this entry")
12377 (t (error "This should not happen")))))
12378 (if org-log-note-extra (insert org-log-note-extra))
12379 (org-set-local 'org-finish-function 'org-store-log-note)
12380 (run-hooks 'org-log-buffer-setup-hook)))
12381
12382 (defvar org-note-abort nil) ; dynamically scoped
12383 (defun org-store-log-note ()
12384 "Finish taking a log note, and insert it to where it belongs."
12385 (let ((txt (buffer-string))
12386 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12387 lines ind bul)
12388 (kill-buffer (current-buffer))
12389 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12390 (setq txt (replace-match "" t t txt)))
12391 (if (string-match "\\s-+\\'" txt)
12392 (setq txt (replace-match "" t t txt)))
12393 (setq lines (org-split-string txt "\n"))
12394 (when (and note (string-match "\\S-" note))
12395 (setq note
12396 (org-replace-escapes
12397 note
12398 (list (cons "%u" (user-login-name))
12399 (cons "%U" user-full-name)
12400 (cons "%t" (format-time-string
12401 (org-time-stamp-format 'long 'inactive)
12402 org-log-note-effective-time))
12403 (cons "%T" (format-time-string
12404 (org-time-stamp-format 'long nil)
12405 org-log-note-effective-time))
12406 (cons "%d" (format-time-string
12407 (org-time-stamp-format nil 'inactive)
12408 org-log-note-effective-time))
12409 (cons "%D" (format-time-string
12410 (org-time-stamp-format nil nil)
12411 org-log-note-effective-time))
12412 (cons "%s" (if org-log-note-state
12413 (concat "\"" org-log-note-state "\"")
12414 ""))
12415 (cons "%S" (if org-log-note-previous-state
12416 (concat "\"" org-log-note-previous-state "\"")
12417 "\"\"")))))
12418 (if lines (setq note (concat note " \\\\")))
12419 (push note lines))
12420 (when (or current-prefix-arg org-note-abort)
12421 (when org-log-into-drawer
12422 (org-remove-empty-drawer-at
12423 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12424 org-log-note-marker))
12425 (setq lines nil))
12426 (when lines
12427 (with-current-buffer (marker-buffer org-log-note-marker)
12428 (save-excursion
12429 (goto-char org-log-note-marker)
12430 (move-marker org-log-note-marker nil)
12431 (end-of-line 1)
12432 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12433 (setq ind (save-excursion
12434 (if (ignore-errors (goto-char (org-in-item-p)))
12435 (let ((struct (org-list-struct)))
12436 (org-list-get-ind
12437 (org-list-get-top-point struct) struct))
12438 (skip-chars-backward " \r\t\n")
12439 (cond
12440 ((and (org-at-heading-p)
12441 org-adapt-indentation)
12442 (1+ (org-current-level)))
12443 ((org-at-heading-p) 0)
12444 (t (org-get-indentation))))))
12445 (setq bul (org-list-bullet-string "-"))
12446 (org-indent-line-to ind)
12447 (insert bul (pop lines))
12448 (let ((ind-body (+ (length bul) ind)))
12449 (while lines
12450 (insert "\n")
12451 (org-indent-line-to ind-body)
12452 (insert (pop lines))))
12453 (message "Note stored")
12454 (org-back-to-heading t)
12455 (org-cycle-hide-drawers 'children)))))
12456 (set-window-configuration org-log-note-window-configuration)
12457 (with-current-buffer (marker-buffer org-log-note-return-to)
12458 (goto-char org-log-note-return-to))
12459 (move-marker org-log-note-return-to nil)
12460 (and org-log-post-message (message "%s" org-log-post-message)))
12461
12462 (defun org-remove-empty-drawer-at (drawer pos)
12463 "Remove an empty drawer DRAWER at position POS.
12464 POS may also be a marker."
12465 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12466 (save-excursion
12467 (save-restriction
12468 (widen)
12469 (goto-char pos)
12470 (if (org-in-regexp
12471 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12472 (replace-match ""))))))
12473
12474 (defun org-sparse-tree (&optional arg)
12475 "Create a sparse tree, prompt for the details.
12476 This command can create sparse trees. You first need to select the type
12477 of match used to create the tree:
12478
12479 t Show all TODO entries.
12480 T Show entries with a specific TODO keyword.
12481 m Show entries selected by a tags/property match.
12482 p Enter a property name and its value (both with completion on existing
12483 names/values) and show entries with that property.
12484 r Show entries matching a regular expression (`/' can be used as well)
12485 d Show deadlines due within `org-deadline-warning-days'.
12486 b Show deadlines and scheduled items before a date.
12487 a Show deadlines and scheduled items after a date."
12488 (interactive "P")
12489 (let (ans kwd value)
12490 (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")
12491 (setq ans (read-char-exclusive))
12492 (cond
12493 ((equal ans ?d)
12494 (call-interactively 'org-check-deadlines))
12495 ((equal ans ?b)
12496 (call-interactively 'org-check-before-date))
12497 ((equal ans ?a)
12498 (call-interactively 'org-check-after-date))
12499 ((equal ans ?D)
12500 (call-interactively 'org-check-dates-range))
12501 ((equal ans ?t)
12502 (org-show-todo-tree nil))
12503 ((equal ans ?T)
12504 (org-show-todo-tree '(4)))
12505 ((member ans '(?T ?m))
12506 (call-interactively 'org-match-sparse-tree))
12507 ((member ans '(?p ?P))
12508 (setq kwd (org-icompleting-read "Property: "
12509 (mapcar 'list (org-buffer-property-keys))))
12510 (setq value (org-icompleting-read "Value: "
12511 (mapcar 'list (org-property-values kwd))))
12512 (unless (string-match "\\`{.*}\\'" value)
12513 (setq value (concat "\"" value "\"")))
12514 (org-match-sparse-tree arg (concat kwd "=" value)))
12515 ((member ans '(?r ?R ?/))
12516 (call-interactively 'org-occur))
12517 (t (error "No such sparse tree command \"%c\"" ans)))))
12518
12519 (defvar org-occur-highlights nil
12520 "List of overlays used for occur matches.")
12521 (make-variable-buffer-local 'org-occur-highlights)
12522 (defvar org-occur-parameters nil
12523 "Parameters of the active org-occur calls.
12524 This is a list, each call to org-occur pushes as cons cell,
12525 containing the regular expression and the callback, onto the list.
12526 The list can contain several entries if `org-occur' has been called
12527 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12528 will only contain one set of parameters. When the highlights are
12529 removed (for example with `C-c C-c', or with the next edit (depending
12530 on `org-remove-highlights-with-change'), this variable is emptied
12531 as well.")
12532 (make-variable-buffer-local 'org-occur-parameters)
12533
12534 (defun org-occur (regexp &optional keep-previous callback)
12535 "Make a compact tree which shows all matches of REGEXP.
12536 The tree will show the lines where the regexp matches, and all higher
12537 headlines above the match. It will also show the heading after the match,
12538 to make sure editing the matching entry is easy.
12539 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12540 call to `org-occur' will be kept, to allow stacking of calls to this
12541 command.
12542 If CALLBACK is non-nil, it is a function which is called to confirm
12543 that the match should indeed be shown."
12544 (interactive "sRegexp: \nP")
12545 (when (equal regexp "")
12546 (error "Regexp cannot be empty"))
12547 (unless keep-previous
12548 (org-remove-occur-highlights nil nil t))
12549 (push (cons regexp callback) org-occur-parameters)
12550 (let ((cnt 0))
12551 (save-excursion
12552 (goto-char (point-min))
12553 (if (or (not keep-previous) ; do not want to keep
12554 (not org-occur-highlights)) ; no previous matches
12555 ;; hide everything
12556 (org-overview))
12557 (while (re-search-forward regexp nil t)
12558 (when (or (not callback)
12559 (save-match-data (funcall callback)))
12560 (setq cnt (1+ cnt))
12561 (when org-highlight-sparse-tree-matches
12562 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12563 (org-show-context 'occur-tree))))
12564 (when org-remove-highlights-with-change
12565 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12566 nil 'local))
12567 (unless org-sparse-tree-open-archived-trees
12568 (org-hide-archived-subtrees (point-min) (point-max)))
12569 (run-hooks 'org-occur-hook)
12570 (if (org-called-interactively-p 'interactive)
12571 (message "%d match(es) for regexp %s" cnt regexp))
12572 cnt))
12573
12574 (defun org-occur-next-match (&optional n reset)
12575 "Function for `next-error-function' to find sparse tree matches.
12576 N is the number of matches to move, when negative move backwards.
12577 RESET is entirely ignored - this function always goes back to the
12578 starting point when no match is found."
12579 (let* ((limit (if (< n 0) (point-min) (point-max)))
12580 (search-func (if (< n 0)
12581 'previous-single-char-property-change
12582 'next-single-char-property-change))
12583 (n (abs n))
12584 (pos (point))
12585 p1)
12586 (catch 'exit
12587 (while (setq p1 (funcall search-func (point) 'org-type))
12588 (when (equal p1 limit)
12589 (goto-char pos)
12590 (error "No more matches"))
12591 (when (equal (get-char-property p1 'org-type) 'org-occur)
12592 (setq n (1- n))
12593 (when (= n 0)
12594 (goto-char p1)
12595 (throw 'exit (point))))
12596 (goto-char p1))
12597 (goto-char p1)
12598 (error "No more matches"))))
12599
12600 (defun org-show-context (&optional key)
12601 "Make sure point and context are visible.
12602 How much context is shown depends upon the variables
12603 `org-show-hierarchy-above', `org-show-following-heading',
12604 `org-show-entry-below' and `org-show-siblings'."
12605 (let ((heading-p (org-at-heading-p t))
12606 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12607 (following-p (org-get-alist-option org-show-following-heading key))
12608 (entry-p (org-get-alist-option org-show-entry-below key))
12609 (siblings-p (org-get-alist-option org-show-siblings key)))
12610 (catch 'exit
12611 ;; Show heading or entry text
12612 (if (and heading-p (not entry-p))
12613 (org-flag-heading nil) ; only show the heading
12614 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12615 (org-show-hidden-entry))) ; show entire entry
12616 (when following-p
12617 ;; Show next sibling, or heading below text
12618 (save-excursion
12619 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12620 (org-flag-heading nil))))
12621 (when siblings-p (org-show-siblings))
12622 (when hierarchy-p
12623 ;; show all higher headings, possibly with siblings
12624 (save-excursion
12625 (while (and (condition-case nil
12626 (progn (org-up-heading-all 1) t)
12627 (error nil))
12628 (not (bobp)))
12629 (org-flag-heading nil)
12630 (when siblings-p (org-show-siblings))))))))
12631
12632 (defvar org-reveal-start-hook nil
12633 "Hook run before revealing a location.")
12634
12635 (defun org-reveal (&optional siblings)
12636 "Show current entry, hierarchy above it, and the following headline.
12637 This can be used to show a consistent set of context around locations
12638 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12639 not t for the search context.
12640
12641 With optional argument SIBLINGS, on each level of the hierarchy all
12642 siblings are shown. This repairs the tree structure to what it would
12643 look like when opened with hierarchical calls to `org-cycle'.
12644 With double optional argument \\[universal-argument] \\[universal-argument], \
12645 go to the parent and show the
12646 entire tree."
12647 (interactive "P")
12648 (run-hooks 'org-reveal-start-hook)
12649 (let ((org-show-hierarchy-above t)
12650 (org-show-following-heading t)
12651 (org-show-siblings (if siblings t org-show-siblings)))
12652 (org-show-context nil))
12653 (when (equal siblings '(16))
12654 (save-excursion
12655 (when (org-up-heading-safe)
12656 (org-show-subtree)
12657 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12658
12659 (defun org-highlight-new-match (beg end)
12660 "Highlight from BEG to END and mark the highlight is an occur headline."
12661 (let ((ov (make-overlay beg end)))
12662 (overlay-put ov 'face 'secondary-selection)
12663 (overlay-put ov 'org-type 'org-occur)
12664 (push ov org-occur-highlights)))
12665
12666 (defun org-remove-occur-highlights (&optional beg end noremove)
12667 "Remove the occur highlights from the buffer.
12668 BEG and END are ignored. If NOREMOVE is nil, remove this function
12669 from the `before-change-functions' in the current buffer."
12670 (interactive)
12671 (unless org-inhibit-highlight-removal
12672 (mapc 'delete-overlay org-occur-highlights)
12673 (setq org-occur-highlights nil)
12674 (setq org-occur-parameters nil)
12675 (unless noremove
12676 (remove-hook 'before-change-functions
12677 'org-remove-occur-highlights 'local))))
12678
12679 ;;;; Priorities
12680
12681 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12682 "Regular expression matching the priority indicator.")
12683
12684 (defvar org-remove-priority-next-time nil)
12685
12686 (defun org-priority-up ()
12687 "Increase the priority of the current item."
12688 (interactive)
12689 (org-priority 'up))
12690
12691 (defun org-priority-down ()
12692 "Decrease the priority of the current item."
12693 (interactive)
12694 (org-priority 'down))
12695
12696 (defun org-priority (&optional action)
12697 "Change the priority of an item by ARG.
12698 ACTION can be `set', `up', `down', or a character."
12699 (interactive)
12700 (unless org-enable-priority-commands
12701 (error "Priority commands are disabled"))
12702 (setq action (or action 'set))
12703 (let (current new news have remove)
12704 (save-excursion
12705 (org-back-to-heading t)
12706 (if (looking-at org-priority-regexp)
12707 (setq current (string-to-char (match-string 2))
12708 have t))
12709 (cond
12710 ((eq action 'remove)
12711 (setq remove t new ?\ ))
12712 ((or (eq action 'set)
12713 (if (featurep 'xemacs) (characterp action) (integerp action)))
12714 (if (not (eq action 'set))
12715 (setq new action)
12716 (message "Priority %c-%c, SPC to remove: "
12717 org-highest-priority org-lowest-priority)
12718 (save-match-data
12719 (setq new (read-char-exclusive))))
12720 (if (and (= (upcase org-highest-priority) org-highest-priority)
12721 (= (upcase org-lowest-priority) org-lowest-priority))
12722 (setq new (upcase new)))
12723 (cond ((equal new ?\ ) (setq remove t))
12724 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12725 (error "Priority must be between `%c' and `%c'"
12726 org-highest-priority org-lowest-priority))))
12727 ((eq action 'up)
12728 (setq new (if have
12729 (1- current) ; normal cycling
12730 ;; last priority was empty
12731 (if (eq last-command this-command)
12732 org-lowest-priority ; wrap around empty to lowest
12733 ;; default
12734 (if org-priority-start-cycle-with-default
12735 org-default-priority
12736 (1- org-default-priority))))))
12737 ((eq action 'down)
12738 (setq new (if have
12739 (1+ current) ; normal cycling
12740 ;; last priority was empty
12741 (if (eq last-command this-command)
12742 org-highest-priority ; wrap around empty to highest
12743 ;; default
12744 (if org-priority-start-cycle-with-default
12745 org-default-priority
12746 (1+ org-default-priority))))))
12747 (t (error "Invalid action")))
12748 (if (or (< (upcase new) org-highest-priority)
12749 (> (upcase new) org-lowest-priority))
12750 (if (and (memq action '(up down))
12751 (not have) (not (eq last-command this-command)))
12752 ;; `new' is from default priority
12753 (error
12754 "The default can not be set, see `org-default-priority' why")
12755 ;; normal cycling: `new' is beyond highest/lowest priority
12756 ;; and is wrapped around to the empty priority
12757 (setq remove t)))
12758 (setq news (format "%c" new))
12759 (if have
12760 (if remove
12761 (replace-match "" t t nil 1)
12762 (replace-match news t t nil 2))
12763 (if remove
12764 (error "No priority cookie found in line")
12765 (let ((case-fold-search nil))
12766 (looking-at org-todo-line-regexp))
12767 (if (match-end 2)
12768 (progn
12769 (goto-char (match-end 2))
12770 (insert " [#" news "]"))
12771 (goto-char (match-beginning 3))
12772 (insert "[#" news "] "))))
12773 (org-preserve-lc (org-set-tags nil 'align)))
12774 (if remove
12775 (message "Priority removed")
12776 (message "Priority of current item set to %s" news))))
12777
12778 (defun org-get-priority (s)
12779 "Find priority cookie and return priority."
12780 (if (functionp org-get-priority-function)
12781 (funcall org-get-priority-function)
12782 (save-match-data
12783 (if (not (string-match org-priority-regexp s))
12784 (* 1000 (- org-lowest-priority org-default-priority))
12785 (* 1000 (- org-lowest-priority
12786 (string-to-char (match-string 2 s))))))))
12787
12788 ;;;; Tags
12789
12790 (defvar org-agenda-archives-mode)
12791 (defvar org-map-continue-from nil
12792 "Position from where mapping should continue.
12793 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12794
12795 (defvar org-scanner-tags nil
12796 "The current tag list while the tags scanner is running.")
12797 (defvar org-trust-scanner-tags nil
12798 "Should `org-get-tags-at' use the tags for the scanner.
12799 This is for internal dynamical scoping only.
12800 When this is non-nil, the function `org-get-tags-at' will return the value
12801 of `org-scanner-tags' instead of building the list by itself. This
12802 can lead to large speed-ups when the tags scanner is used in a file with
12803 many entries, and when the list of tags is retrieved, for example to
12804 obtain a list of properties. Building the tags list for each entry in such
12805 a file becomes an N^2 operation - but with this variable set, it scales
12806 as N.")
12807
12808 (defun org-scan-tags (action matcher todo-only &optional start-level)
12809 "Scan headline tags with inheritance and produce output ACTION.
12810
12811 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12812 or `agenda' to produce an entry list for an agenda view. It can also be
12813 a Lisp form or a function that should be called at each matched headline, in
12814 this case the return value is a list of all return values from these calls.
12815
12816 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12817 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12818 only lines with a not-done TODO keyword are included in the output.
12819 This should be the same variable that was scoped into
12820 and set by `org-make-tags-matcher' when it constructed MATCHER.
12821
12822 START-LEVEL can be a string with asterisks, reducing the scope to
12823 headlines matching this string."
12824 (require 'org-agenda)
12825 (let* ((re (concat "^"
12826 (if start-level
12827 ;; Get the correct level to match
12828 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12829 org-outline-regexp)
12830 " *\\(\\<\\("
12831 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12832 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12833 (props (list 'face 'default
12834 'done-face 'org-agenda-done
12835 'undone-face 'default
12836 'mouse-face 'highlight
12837 'org-not-done-regexp org-not-done-regexp
12838 'org-todo-regexp org-todo-regexp
12839 'org-complex-heading-regexp org-complex-heading-regexp
12840 'help-echo
12841 (format "mouse-2 or RET jump to org file %s"
12842 (abbreviate-file-name
12843 (or (buffer-file-name (buffer-base-buffer))
12844 (buffer-name (buffer-base-buffer)))))))
12845 (case-fold-search nil)
12846 (org-map-continue-from nil)
12847 lspos tags tags-list
12848 (tags-alist (list (cons 0 org-file-tags)))
12849 (llast 0) rtn rtn1 level category i txt
12850 todo marker entry priority)
12851 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12852 (setq action (list 'lambda nil action)))
12853 (save-excursion
12854 (goto-char (point-min))
12855 (when (eq action 'sparse-tree)
12856 (org-overview)
12857 (org-remove-occur-highlights))
12858 (while (re-search-forward re nil t)
12859 (setq org-map-continue-from nil)
12860 (catch :skip
12861 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12862 tags (if (match-end 4) (org-match-string-no-properties 4)))
12863 (goto-char (setq lspos (match-beginning 0)))
12864 (setq level (org-reduced-level (funcall outline-level))
12865 category (org-get-category))
12866 (setq i llast llast level)
12867 ;; remove tag lists from same and sublevels
12868 (while (>= i level)
12869 (when (setq entry (assoc i tags-alist))
12870 (setq tags-alist (delete entry tags-alist)))
12871 (setq i (1- i)))
12872 ;; add the next tags
12873 (when tags
12874 (setq tags (org-split-string tags ":")
12875 tags-alist
12876 (cons (cons level tags) tags-alist)))
12877 ;; compile tags for current headline
12878 (setq tags-list
12879 (if org-use-tag-inheritance
12880 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12881 tags)
12882 org-scanner-tags tags-list)
12883 (when org-use-tag-inheritance
12884 (setcdr (car tags-alist)
12885 (mapcar (lambda (x)
12886 (setq x (copy-sequence x))
12887 (org-add-prop-inherited x))
12888 (cdar tags-alist))))
12889 (when (and tags org-use-tag-inheritance
12890 (or (not (eq t org-use-tag-inheritance))
12891 org-tags-exclude-from-inheritance))
12892 ;; selective inheritance, remove uninherited ones
12893 (setcdr (car tags-alist)
12894 (org-remove-uninherited-tags (cdar tags-alist))))
12895 (when (and
12896
12897 ;; eval matcher only when the todo condition is OK
12898 (and (or (not todo-only) (member todo org-not-done-keywords))
12899 (let ((case-fold-search t)) (eval matcher)))
12900
12901 ;; Call the skipper, but return t if it does not skip,
12902 ;; so that the `and' form continues evaluating
12903 (progn
12904 (unless (eq action 'sparse-tree) (org-agenda-skip))
12905 t)
12906
12907 ;; Check if timestamps are deselecting this entry
12908 (or (not todo-only)
12909 (and (member todo org-not-done-keywords)
12910 (or (not org-agenda-tags-todo-honor-ignore-options)
12911 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12912
12913 ;; Extra check for the archive tag
12914 ;; FIXME: Does the skipper already do this????
12915 (or
12916 (not (member org-archive-tag tags-list))
12917 ;; we have an archive tag, should we use this anyway?
12918 (or (not org-agenda-skip-archived-trees)
12919 (and (eq action 'agenda) org-agenda-archives-mode))))
12920
12921 ;; select this headline
12922
12923 (cond
12924 ((eq action 'sparse-tree)
12925 (and org-highlight-sparse-tree-matches
12926 (org-get-heading) (match-end 0)
12927 (org-highlight-new-match
12928 (match-beginning 1) (match-end 1)))
12929 (org-show-context 'tags-tree))
12930 ((eq action 'agenda)
12931 (setq txt (org-agenda-format-item
12932 ""
12933 (concat
12934 (if (eq org-tags-match-list-sublevels 'indented)
12935 (make-string (1- level) ?.) "")
12936 (org-get-heading))
12937 category
12938 tags-list
12939 )
12940 priority (org-get-priority txt))
12941 (goto-char lspos)
12942 (setq marker (org-agenda-new-marker))
12943 (org-add-props txt props
12944 'org-marker marker 'org-hd-marker marker 'org-category category
12945 'todo-state todo
12946 'priority priority 'type "tagsmatch")
12947 (push txt rtn))
12948 ((functionp action)
12949 (setq org-map-continue-from nil)
12950 (save-excursion
12951 (setq rtn1 (funcall action))
12952 (push rtn1 rtn)))
12953 (t (error "Invalid action")))
12954
12955 ;; if we are to skip sublevels, jump to end of subtree
12956 (unless org-tags-match-list-sublevels
12957 (org-end-of-subtree t)
12958 (backward-char 1))))
12959 ;; Get the correct position from where to continue
12960 (if org-map-continue-from
12961 (goto-char org-map-continue-from)
12962 (and (= (point) lspos) (end-of-line 1)))))
12963 (when (and (eq action 'sparse-tree)
12964 (not org-sparse-tree-open-archived-trees))
12965 (org-hide-archived-subtrees (point-min) (point-max)))
12966 (nreverse rtn)))
12967
12968 (defun org-remove-uninherited-tags (tags)
12969 "Remove all tags that are not inherited from the list TAGS."
12970 (cond
12971 ((eq org-use-tag-inheritance t)
12972 (if org-tags-exclude-from-inheritance
12973 (org-delete-all org-tags-exclude-from-inheritance tags)
12974 tags))
12975 ((not org-use-tag-inheritance) nil)
12976 ((stringp org-use-tag-inheritance)
12977 (delq nil (mapcar
12978 (lambda (x)
12979 (if (and (string-match org-use-tag-inheritance x)
12980 (not (member x org-tags-exclude-from-inheritance)))
12981 x nil))
12982 tags)))
12983 ((listp org-use-tag-inheritance)
12984 (delq nil (mapcar
12985 (lambda (x)
12986 (if (member x org-use-tag-inheritance) x nil))
12987 tags)))))
12988
12989 (defun org-match-sparse-tree (&optional todo-only match)
12990 "Create a sparse tree according to tags string MATCH.
12991 MATCH can contain positive and negative selection of tags, like
12992 \"+WORK+URGENT-WITHBOSS\".
12993 If optional argument TODO-ONLY is non-nil, only select lines that are
12994 also TODO lines."
12995 (interactive "P")
12996 (org-prepare-agenda-buffers (list (current-buffer)))
12997 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12998
12999 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13000
13001 (defvar org-cached-props nil)
13002 (defun org-cached-entry-get (pom property)
13003 (if (or (eq t org-use-property-inheritance)
13004 (and (stringp org-use-property-inheritance)
13005 (string-match org-use-property-inheritance property))
13006 (and (listp org-use-property-inheritance)
13007 (member property org-use-property-inheritance)))
13008 ;; Caching is not possible, check it directly
13009 (org-entry-get pom property 'inherit)
13010 ;; Get all properties, so that we can do complicated checks easily
13011 (cdr (assoc property (or org-cached-props
13012 (setq org-cached-props
13013 (org-entry-properties pom)))))))
13014
13015 (defun org-global-tags-completion-table (&optional files)
13016 "Return the list of all tags in all agenda buffer/files.
13017 Optional FILES argument is a list of files to which can be used
13018 instead of the agenda files."
13019 (save-excursion
13020 (org-uniquify
13021 (delq nil
13022 (apply 'append
13023 (mapcar
13024 (lambda (file)
13025 (set-buffer (find-file-noselect file))
13026 (append (org-get-buffer-tags)
13027 (mapcar (lambda (x) (if (stringp (car-safe x))
13028 (list (car-safe x)) nil))
13029 org-tag-alist)))
13030 (if (and files (car files))
13031 files
13032 (org-agenda-files))))))))
13033
13034 (defun org-make-tags-matcher (match)
13035 "Create the TAGS/TODO matcher form for the selection string MATCH.
13036
13037 The variable `todo-only' is scoped dynamically into this function; it will be
13038 set to t if the matcher restricts matching to TODO entries,
13039 otherwise will not be touched.
13040
13041 Returns a cons of the selection string MATCH and the constructed
13042 lisp form implementing the matcher. The matcher is to be
13043 evaluated at an Org entry, with point on the headline,
13044 and returns t if the entry matches the
13045 selection string MATCH. The returned lisp form references
13046 two variables with information about the entry, which must be
13047 bound around the form's evaluation: todo, the TODO keyword at the
13048 entry (or nil of none); and tags-list, the list of all tags at the
13049 entry including inherited ones. Additionally, the category
13050 of the entry (if any) must be specified as the text property
13051 'org-category on the headline.
13052
13053 See also `org-scan-tags'.
13054 "
13055 (declare (special todo-only))
13056 (unless (boundp 'todo-only)
13057 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13058 (unless match
13059 ;; Get a new match request, with completion
13060 (let ((org-last-tags-completion-table
13061 (org-global-tags-completion-table)))
13062 (setq match (org-completing-read-no-i
13063 "Match: " 'org-tags-completion-function nil nil nil
13064 'org-tags-history))))
13065
13066 ;; Parse the string and create a lisp form
13067 (let ((match0 match)
13068 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13069 minus tag mm
13070 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13071 orterms term orlist re-p str-p level-p level-op time-p
13072 prop-p pn pv po gv rest)
13073 (if (string-match "/+" match)
13074 ;; match contains also a todo-matching request
13075 (progn
13076 (setq tagsmatch (substring match 0 (match-beginning 0))
13077 todomatch (substring match (match-end 0)))
13078 (if (string-match "^!" todomatch)
13079 (setq todo-only t todomatch (substring todomatch 1)))
13080 (if (string-match "^\\s-*$" todomatch)
13081 (setq todomatch nil)))
13082 ;; only matching tags
13083 (setq tagsmatch match todomatch nil))
13084
13085 ;; Make the tags matcher
13086 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13087 (setq tagsmatcher t)
13088 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13089 (while (setq term (pop orterms))
13090 (while (and (equal (substring term -1) "\\") orterms)
13091 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13092 (while (string-match re term)
13093 (setq rest (substring term (match-end 0))
13094 minus (and (match-end 1)
13095 (equal (match-string 1 term) "-"))
13096 tag (save-match-data (replace-regexp-in-string
13097 "\\\\-" "-"
13098 (match-string 2 term)))
13099 re-p (equal (string-to-char tag) ?{)
13100 level-p (match-end 4)
13101 prop-p (match-end 5)
13102 mm (cond
13103 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13104 (level-p
13105 (setq level-op (org-op-to-function (match-string 3 term)))
13106 `(,level-op level ,(string-to-number
13107 (match-string 4 term))))
13108 (prop-p
13109 (setq pn (match-string 5 term)
13110 po (match-string 6 term)
13111 pv (match-string 7 term)
13112 re-p (equal (string-to-char pv) ?{)
13113 str-p (equal (string-to-char pv) ?\")
13114 time-p (save-match-data
13115 (string-match "^\"[[<].*[]>]\"$" pv))
13116 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13117 (if time-p (setq pv (org-matcher-time pv)))
13118 (setq po (org-op-to-function po (if time-p 'time str-p)))
13119 (cond
13120 ((equal pn "CATEGORY")
13121 (setq gv '(get-text-property (point) 'org-category)))
13122 ((equal pn "TODO")
13123 (setq gv 'todo))
13124 (t
13125 (setq gv `(org-cached-entry-get nil ,pn))))
13126 (if re-p
13127 (if (eq po 'org<>)
13128 `(not (string-match ,pv (or ,gv "")))
13129 `(string-match ,pv (or ,gv "")))
13130 (if str-p
13131 `(,po (or ,gv "") ,pv)
13132 `(,po (string-to-number (or ,gv ""))
13133 ,(string-to-number pv) ))))
13134 (t `(member ,tag tags-list)))
13135 mm (if minus (list 'not mm) mm)
13136 term rest)
13137 (push mm tagsmatcher))
13138 (push (if (> (length tagsmatcher) 1)
13139 (cons 'and tagsmatcher)
13140 (car tagsmatcher))
13141 orlist)
13142 (setq tagsmatcher nil))
13143 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13144 (setq tagsmatcher
13145 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13146 ;; Make the todo matcher
13147 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13148 (setq todomatcher t)
13149 (setq orterms (org-split-string todomatch "|") orlist nil)
13150 (while (setq term (pop orterms))
13151 (while (string-match re term)
13152 (setq minus (and (match-end 1)
13153 (equal (match-string 1 term) "-"))
13154 kwd (match-string 2 term)
13155 re-p (equal (string-to-char kwd) ?{)
13156 term (substring term (match-end 0))
13157 mm (if re-p
13158 `(string-match ,(substring kwd 1 -1) todo)
13159 (list 'equal 'todo kwd))
13160 mm (if minus (list 'not mm) mm))
13161 (push mm todomatcher))
13162 (push (if (> (length todomatcher) 1)
13163 (cons 'and todomatcher)
13164 (car todomatcher))
13165 orlist)
13166 (setq todomatcher nil))
13167 (setq todomatcher (if (> (length orlist) 1)
13168 (cons 'or orlist) (car orlist))))
13169
13170 ;; Return the string and lisp forms of the matcher
13171 (setq matcher (if todomatcher
13172 (list 'and tagsmatcher todomatcher)
13173 tagsmatcher))
13174 (when todo-only
13175 (setq matcher (list 'and '(member todo org-not-done-keywords)
13176 matcher)))
13177 (cons match0 matcher)))
13178
13179 (defun org-op-to-function (op &optional stringp)
13180 "Turn an operator into the appropriate function."
13181 (setq op
13182 (cond
13183 ((equal op "<" ) '(< string< org-time<))
13184 ((equal op ">" ) '(> org-string> org-time>))
13185 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13186 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13187 ((member op '("=" "==")) '(= string= org-time=))
13188 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13189 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13190
13191 (defun org<> (a b) (not (= a b)))
13192 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13193 (defun org-string>= (a b) (not (string< a b)))
13194 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13195 (defun org-string<> (a b) (not (string= a b)))
13196 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13197 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13198 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13199 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13200 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13201 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13202 (defun org-2ft (s)
13203 "Convert S to a floating point time.
13204 If S is already a number, just return it. If it is a string, parse
13205 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13206 (cond
13207 ((numberp s) s)
13208 ((stringp s)
13209 (condition-case nil
13210 (float-time (apply 'encode-time (org-parse-time-string s)))
13211 (error 0.)))
13212 (t 0.)))
13213
13214 (defun org-time-today ()
13215 "Time in seconds today at 0:00.
13216 Returns the float number of seconds since the beginning of the
13217 epoch to the beginning of today (00:00)."
13218 (float-time (apply 'encode-time
13219 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13220
13221 (defun org-matcher-time (s)
13222 "Interpret a time comparison value."
13223 (save-match-data
13224 (cond
13225 ((string= s "<now>") (float-time))
13226 ((string= s "<today>") (org-time-today))
13227 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13228 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13229 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13230 (+ (org-time-today)
13231 (* (string-to-number (match-string 1 s))
13232 (cdr (assoc (match-string 2 s)
13233 '(("d" . 86400.0) ("w" . 604800.0)
13234 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13235 (t (org-2ft s)))))
13236
13237 (defun org-match-any-p (re list)
13238 "Does re match any element of list?"
13239 (setq list (mapcar (lambda (x) (string-match re x)) list))
13240 (delq nil list))
13241
13242 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13243 (defvar org-tags-overlay (make-overlay 1 1))
13244 (org-detach-overlay org-tags-overlay)
13245
13246 (defun org-get-local-tags-at (&optional pos)
13247 "Get a list of tags defined in the current headline."
13248 (org-get-tags-at pos 'local))
13249
13250 (defun org-get-local-tags ()
13251 "Get a list of tags defined in the current headline."
13252 (org-get-tags-at nil 'local))
13253
13254 (defun org-get-tags-at (&optional pos local)
13255 "Get a list of all headline tags applicable at POS.
13256 POS defaults to point. If tags are inherited, the list contains
13257 the targets in the same sequence as the headlines appear, i.e.
13258 the tags of the current headline come last.
13259 When LOCAL is non-nil, only return tags from the current headline,
13260 ignore inherited ones."
13261 (interactive)
13262 (if (and org-trust-scanner-tags
13263 (or (not pos) (equal pos (point)))
13264 (not local))
13265 org-scanner-tags
13266 (let (tags ltags lastpos parent)
13267 (save-excursion
13268 (save-restriction
13269 (widen)
13270 (goto-char (or pos (point)))
13271 (save-match-data
13272 (catch 'done
13273 (condition-case nil
13274 (progn
13275 (org-back-to-heading t)
13276 (while (not (equal lastpos (point)))
13277 (setq lastpos (point))
13278 (when (looking-at
13279 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13280 (setq ltags (org-split-string
13281 (org-match-string-no-properties 1) ":"))
13282 (when parent
13283 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13284 (setq tags (append
13285 (if parent
13286 (org-remove-uninherited-tags ltags)
13287 ltags)
13288 tags)))
13289 (or org-use-tag-inheritance (throw 'done t))
13290 (if local (throw 'done t))
13291 (or (org-up-heading-safe) (error nil))
13292 (setq parent t)))
13293 (error nil)))))
13294 (if local
13295 tags
13296 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13297
13298 (defun org-add-prop-inherited (s)
13299 (add-text-properties 0 (length s) '(inherited t) s)
13300 s)
13301
13302 (defun org-toggle-tag (tag &optional onoff)
13303 "Toggle the tag TAG for the current line.
13304 If ONOFF is `on' or `off', don't toggle but set to this state."
13305 (let (res current)
13306 (save-excursion
13307 (org-back-to-heading t)
13308 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13309 (point-at-eol) t)
13310 (progn
13311 (setq current (match-string 1))
13312 (replace-match ""))
13313 (setq current ""))
13314 (setq current (nreverse (org-split-string current ":")))
13315 (cond
13316 ((eq onoff 'on)
13317 (setq res t)
13318 (or (member tag current) (push tag current)))
13319 ((eq onoff 'off)
13320 (or (not (member tag current)) (setq current (delete tag current))))
13321 (t (if (member tag current)
13322 (setq current (delete tag current))
13323 (setq res t)
13324 (push tag current))))
13325 (end-of-line 1)
13326 (if current
13327 (progn
13328 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13329 (org-set-tags nil t))
13330 (delete-horizontal-space))
13331 (run-hooks 'org-after-tags-change-hook))
13332 res))
13333
13334 (defun org-align-tags-here (to-col)
13335 ;; Assumes that this is a headline
13336 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13337 (beginning-of-line 1)
13338 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13339 (< pos (match-beginning 2)))
13340 (progn
13341 (setq tags-l (- (match-end 2) (match-beginning 2)))
13342 (goto-char (match-beginning 1))
13343 (insert " ")
13344 (delete-region (point) (1+ (match-beginning 2)))
13345 (setq ncol (max (current-column)
13346 (1+ col)
13347 (if (> to-col 0)
13348 to-col
13349 (- (abs to-col) tags-l))))
13350 (setq p (point))
13351 (insert (make-string (- ncol (current-column)) ?\ ))
13352 (setq ncol (current-column))
13353 (when indent-tabs-mode (tabify p (point-at-eol)))
13354 (org-move-to-column (min ncol col) t))
13355 (goto-char pos))))
13356
13357 (defun org-set-tags-command (&optional arg just-align)
13358 "Call the set-tags command for the current entry."
13359 (interactive "P")
13360 (if (org-at-heading-p)
13361 (org-set-tags arg just-align)
13362 (save-excursion
13363 (org-back-to-heading t)
13364 (org-set-tags arg just-align))))
13365
13366 (defun org-set-tags-to (data)
13367 "Set the tags of the current entry to DATA, replacing the current tags.
13368 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13369 If DATA is nil or the empty string, any tags will be removed."
13370 (interactive "sTags: ")
13371 (setq data
13372 (cond
13373 ((eq data nil) "")
13374 ((equal data "") "")
13375 ((stringp data)
13376 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13377 ":"))
13378 ((listp data)
13379 (concat ":" (mapconcat 'identity data ":") ":"))
13380 (t nil)))
13381 (when data
13382 (save-excursion
13383 (org-back-to-heading t)
13384 (when (looking-at org-complex-heading-regexp)
13385 (if (match-end 5)
13386 (progn
13387 (goto-char (match-beginning 5))
13388 (insert data)
13389 (delete-region (point) (point-at-eol))
13390 (org-set-tags nil 'align))
13391 (goto-char (point-at-eol))
13392 (insert " " data)
13393 (org-set-tags nil 'align)))
13394 (beginning-of-line 1)
13395 (if (looking-at ".*?\\([ \t]+\\)$")
13396 (delete-region (match-beginning 1) (match-end 1))))))
13397
13398 (defun org-align-all-tags ()
13399 "Align the tags i all headings."
13400 (interactive)
13401 (save-excursion
13402 (or (ignore-errors (org-back-to-heading t))
13403 (outline-next-heading))
13404 (if (org-at-heading-p)
13405 (org-set-tags t)
13406 (message "No headings"))))
13407
13408 (defvar org-indent-indentation-per-level)
13409 (defun org-set-tags (&optional arg just-align)
13410 "Set the tags for the current headline.
13411 With prefix ARG, realign all tags in headings in the current buffer."
13412 (interactive "P")
13413 (let* ((re org-outline-regexp-bol)
13414 (current (org-get-tags-string))
13415 (col (current-column))
13416 (org-setting-tags t)
13417 table current-tags inherited-tags ; computed below when needed
13418 tags p0 c0 c1 rpl di tc level)
13419 (if arg
13420 (save-excursion
13421 (goto-char (point-min))
13422 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13423 (while (re-search-forward re nil t)
13424 (org-set-tags nil t)
13425 (end-of-line 1)))
13426 (message "All tags realigned to column %d" org-tags-column))
13427 (if just-align
13428 (setq tags current)
13429 ;; Get a new set of tags from the user
13430 (save-excursion
13431 (setq table (append org-tag-persistent-alist
13432 (or org-tag-alist (org-get-buffer-tags))
13433 (and
13434 org-complete-tags-always-offer-all-agenda-tags
13435 (org-global-tags-completion-table
13436 (org-agenda-files))))
13437 org-last-tags-completion-table table
13438 current-tags (org-split-string current ":")
13439 inherited-tags (nreverse
13440 (nthcdr (length current-tags)
13441 (nreverse (org-get-tags-at))))
13442 tags
13443 (if (or (eq t org-use-fast-tag-selection)
13444 (and org-use-fast-tag-selection
13445 (delq nil (mapcar 'cdr table))))
13446 (org-fast-tag-selection
13447 current-tags inherited-tags table
13448 (if org-fast-tag-selection-include-todo
13449 org-todo-key-alist))
13450 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13451 (org-trim
13452 (org-icompleting-read "Tags: "
13453 'org-tags-completion-function
13454 nil nil current 'org-tags-history))))))
13455 (while (string-match "[-+&]+" tags)
13456 ;; No boolean logic, just a list
13457 (setq tags (replace-match ":" t t tags))))
13458
13459 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13460
13461 (if org-tags-sort-function
13462 (setq tags (mapconcat 'identity
13463 (sort (org-split-string
13464 tags (org-re "[^[:alnum:]_@#%]+"))
13465 org-tags-sort-function) ":")))
13466
13467 (if (string-match "\\`[\t ]*\\'" tags)
13468 (setq tags "")
13469 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13470 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13471
13472 ;; Insert new tags at the correct column
13473 (beginning-of-line 1)
13474 (setq level (or (and (looking-at org-outline-regexp)
13475 (- (match-end 0) (point) 1))
13476 1))
13477 (cond
13478 ((and (equal current "") (equal tags "")))
13479 ((re-search-forward
13480 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13481 (point-at-eol) t)
13482 (if (equal tags "")
13483 (setq rpl "")
13484 (goto-char (match-beginning 0))
13485 (setq c0 (current-column)
13486 ;; compute offset for the case of org-indent-mode active
13487 di (if org-indent-mode
13488 (* (1- org-indent-indentation-per-level) (1- level))
13489 0)
13490 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13491 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13492 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13493 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13494 (replace-match rpl t t)
13495 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13496 tags)
13497 (t (error "Tags alignment failed")))
13498 (org-move-to-column col)
13499 (unless just-align
13500 (run-hooks 'org-after-tags-change-hook)))))
13501
13502 (defun org-change-tag-in-region (beg end tag off)
13503 "Add or remove TAG for each entry in the region.
13504 This works in the agenda, and also in an org-mode buffer."
13505 (interactive
13506 (list (region-beginning) (region-end)
13507 (let ((org-last-tags-completion-table
13508 (if (eq major-mode 'org-mode)
13509 (org-get-buffer-tags)
13510 (org-global-tags-completion-table))))
13511 (org-icompleting-read
13512 "Tag: " 'org-tags-completion-function nil nil nil
13513 'org-tags-history))
13514 (progn
13515 (message "[s]et or [r]emove? ")
13516 (equal (read-char-exclusive) ?r))))
13517 (if (fboundp 'deactivate-mark) (deactivate-mark))
13518 (let ((agendap (equal major-mode 'org-agenda-mode))
13519 l1 l2 m buf pos newhead (cnt 0))
13520 (goto-char end)
13521 (setq l2 (1- (org-current-line)))
13522 (goto-char beg)
13523 (setq l1 (org-current-line))
13524 (loop for l from l1 to l2 do
13525 (org-goto-line l)
13526 (setq m (get-text-property (point) 'org-hd-marker))
13527 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13528 (and agendap m))
13529 (setq buf (if agendap (marker-buffer m) (current-buffer))
13530 pos (if agendap m (point)))
13531 (with-current-buffer buf
13532 (save-excursion
13533 (save-restriction
13534 (goto-char pos)
13535 (setq cnt (1+ cnt))
13536 (org-toggle-tag tag (if off 'off 'on))
13537 (setq newhead (org-get-heading)))))
13538 (and agendap (org-agenda-change-all-lines newhead m))))
13539 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13540
13541 (defun org-tags-completion-function (string predicate &optional flag)
13542 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13543 (confirm (lambda (x) (stringp (car x)))))
13544 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13545 (setq s1 (match-string 1 string)
13546 s2 (match-string 2 string))
13547 (setq s1 "" s2 string))
13548 (cond
13549 ((eq flag nil)
13550 ;; try completion
13551 (setq rtn (try-completion s2 ctable confirm))
13552 (if (stringp rtn)
13553 (setq rtn
13554 (concat s1 s2 (substring rtn (length s2))
13555 (if (and org-add-colon-after-tag-completion
13556 (assoc rtn ctable))
13557 ":" ""))))
13558 rtn)
13559 ((eq flag t)
13560 ;; all-completions
13561 (all-completions s2 ctable confirm)
13562 )
13563 ((eq flag 'lambda)
13564 ;; exact match?
13565 (assoc s2 ctable)))
13566 ))
13567
13568 (defun org-fast-tag-insert (kwd tags face &optional end)
13569 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13570 (insert (format "%-12s" (concat kwd ":"))
13571 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13572 (or end "")))
13573
13574 (defun org-fast-tag-show-exit (flag)
13575 (save-excursion
13576 (org-goto-line 3)
13577 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13578 (replace-match ""))
13579 (when flag
13580 (end-of-line 1)
13581 (org-move-to-column (- (window-width) 19) t)
13582 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13583
13584 (defun org-set-current-tags-overlay (current prefix)
13585 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13586 (if (featurep 'xemacs)
13587 (org-overlay-display org-tags-overlay (concat prefix s)
13588 'secondary-selection)
13589 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13590 (org-overlay-display org-tags-overlay (concat prefix s)))))
13591
13592 (defvar org-last-tag-selection-key nil)
13593 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13594 "Fast tag selection with single keys.
13595 CURRENT is the current list of tags in the headline, INHERITED is the
13596 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13597 possibly with grouping information. TODO-TABLE is a similar table with
13598 TODO keywords, should these have keys assigned to them.
13599 If the keys are nil, a-z are automatically assigned.
13600 Returns the new tags string, or nil to not change the current settings."
13601 (let* ((fulltable (append table todo-table))
13602 (maxlen (apply 'max (mapcar
13603 (lambda (x)
13604 (if (stringp (car x)) (string-width (car x)) 0))
13605 fulltable)))
13606 (buf (current-buffer))
13607 (expert (eq org-fast-tag-selection-single-key 'expert))
13608 (buffer-tags nil)
13609 (fwidth (+ maxlen 3 1 3))
13610 (ncol (/ (- (window-width) 4) fwidth))
13611 (i-face 'org-done)
13612 (c-face 'org-todo)
13613 tg cnt e c char c1 c2 ntable tbl rtn
13614 ov-start ov-end ov-prefix
13615 (exit-after-next org-fast-tag-selection-single-key)
13616 (done-keywords org-done-keywords)
13617 groups ingroup)
13618 (save-excursion
13619 (beginning-of-line 1)
13620 (if (looking-at
13621 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13622 (setq ov-start (match-beginning 1)
13623 ov-end (match-end 1)
13624 ov-prefix "")
13625 (setq ov-start (1- (point-at-eol))
13626 ov-end (1+ ov-start))
13627 (skip-chars-forward "^\n\r")
13628 (setq ov-prefix
13629 (concat
13630 (buffer-substring (1- (point)) (point))
13631 (if (> (current-column) org-tags-column)
13632 " "
13633 (make-string (- org-tags-column (current-column)) ?\ ))))))
13634 (move-overlay org-tags-overlay ov-start ov-end)
13635 (save-window-excursion
13636 (if expert
13637 (set-buffer (get-buffer-create " *Org tags*"))
13638 (delete-other-windows)
13639 (split-window-vertically)
13640 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13641 (erase-buffer)
13642 (org-set-local 'org-done-keywords done-keywords)
13643 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13644 (org-fast-tag-insert "Current" current c-face "\n\n")
13645 (org-fast-tag-show-exit exit-after-next)
13646 (org-set-current-tags-overlay current ov-prefix)
13647 (setq tbl fulltable char ?a cnt 0)
13648 (while (setq e (pop tbl))
13649 (cond
13650 ((equal (car e) :startgroup)
13651 (push '() groups) (setq ingroup t)
13652 (when (not (= cnt 0))
13653 (setq cnt 0)
13654 (insert "\n"))
13655 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13656 ((equal (car e) :endgroup)
13657 (setq ingroup nil cnt 0)
13658 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13659 ((equal e '(:newline))
13660 (when (not (= cnt 0))
13661 (setq cnt 0)
13662 (insert "\n")
13663 (setq e (car tbl))
13664 (while (equal (car tbl) '(:newline))
13665 (insert "\n")
13666 (setq tbl (cdr tbl)))))
13667 (t
13668 (setq tg (copy-sequence (car e)) c2 nil)
13669 (if (cdr e)
13670 (setq c (cdr e))
13671 ;; automatically assign a character.
13672 (setq c1 (string-to-char
13673 (downcase (substring
13674 tg (if (= (string-to-char tg) ?@) 1 0)))))
13675 (if (or (rassoc c1 ntable) (rassoc c1 table))
13676 (while (or (rassoc char ntable) (rassoc char table))
13677 (setq char (1+ char)))
13678 (setq c2 c1))
13679 (setq c (or c2 char)))
13680 (if ingroup (push tg (car groups)))
13681 (setq tg (org-add-props tg nil 'face
13682 (cond
13683 ((not (assoc tg table))
13684 (org-get-todo-face tg))
13685 ((member tg current) c-face)
13686 ((member tg inherited) i-face)
13687 (t nil))))
13688 (if (and (= cnt 0) (not ingroup)) (insert " "))
13689 (insert "[" c "] " tg (make-string
13690 (- fwidth 4 (length tg)) ?\ ))
13691 (push (cons tg c) ntable)
13692 (when (= (setq cnt (1+ cnt)) ncol)
13693 (insert "\n")
13694 (if ingroup (insert " "))
13695 (setq cnt 0)))))
13696 (setq ntable (nreverse ntable))
13697 (insert "\n")
13698 (goto-char (point-min))
13699 (if (not expert) (org-fit-window-to-buffer))
13700 (setq rtn
13701 (catch 'exit
13702 (while t
13703 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13704 (if (not groups) "no " "")
13705 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13706 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13707 (setq org-last-tag-selection-key c)
13708 (cond
13709 ((= c ?\r) (throw 'exit t))
13710 ((= c ?!)
13711 (setq groups (not groups))
13712 (goto-char (point-min))
13713 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13714 ((= c ?\C-c)
13715 (if (not expert)
13716 (org-fast-tag-show-exit
13717 (setq exit-after-next (not exit-after-next)))
13718 (setq expert nil)
13719 (delete-other-windows)
13720 (set-window-buffer (split-window-vertically) " *Org tags*")
13721 (org-switch-to-buffer-other-window " *Org tags*")
13722 (org-fit-window-to-buffer)))
13723 ((or (= c ?\C-g)
13724 (and (= c ?q) (not (rassoc c ntable))))
13725 (org-detach-overlay org-tags-overlay)
13726 (setq quit-flag t))
13727 ((= c ?\ )
13728 (setq current nil)
13729 (if exit-after-next (setq exit-after-next 'now)))
13730 ((= c ?\t)
13731 (condition-case nil
13732 (setq tg (org-icompleting-read
13733 "Tag: "
13734 (or buffer-tags
13735 (with-current-buffer buf
13736 (org-get-buffer-tags)))))
13737 (quit (setq tg "")))
13738 (when (string-match "\\S-" tg)
13739 (add-to-list 'buffer-tags (list tg))
13740 (if (member tg current)
13741 (setq current (delete tg current))
13742 (push tg current)))
13743 (if exit-after-next (setq exit-after-next 'now)))
13744 ((setq e (rassoc c todo-table) tg (car e))
13745 (with-current-buffer buf
13746 (save-excursion (org-todo tg)))
13747 (if exit-after-next (setq exit-after-next 'now)))
13748 ((setq e (rassoc c ntable) tg (car e))
13749 (if (member tg current)
13750 (setq current (delete tg current))
13751 (loop for g in groups do
13752 (if (member tg g)
13753 (mapc (lambda (x)
13754 (setq current (delete x current)))
13755 g)))
13756 (push tg current))
13757 (if exit-after-next (setq exit-after-next 'now))))
13758
13759 ;; Create a sorted list
13760 (setq current
13761 (sort current
13762 (lambda (a b)
13763 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13764 (if (eq exit-after-next 'now) (throw 'exit t))
13765 (goto-char (point-min))
13766 (beginning-of-line 2)
13767 (delete-region (point) (point-at-eol))
13768 (org-fast-tag-insert "Current" current c-face)
13769 (org-set-current-tags-overlay current ov-prefix)
13770 (while (re-search-forward
13771 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13772 (setq tg (match-string 1))
13773 (add-text-properties
13774 (match-beginning 1) (match-end 1)
13775 (list 'face
13776 (cond
13777 ((member tg current) c-face)
13778 ((member tg inherited) i-face)
13779 (t (get-text-property (match-beginning 1) 'face))))))
13780 (goto-char (point-min)))))
13781 (org-detach-overlay org-tags-overlay)
13782 (if rtn
13783 (mapconcat 'identity current ":")
13784 nil))))
13785
13786 (defun org-get-tags-string ()
13787 "Get the TAGS string in the current headline."
13788 (unless (org-at-heading-p t)
13789 (error "Not on a heading"))
13790 (save-excursion
13791 (beginning-of-line 1)
13792 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13793 (org-match-string-no-properties 1)
13794 "")))
13795
13796 (defun org-get-tags ()
13797 "Get the list of tags specified in the current headline."
13798 (org-split-string (org-get-tags-string) ":"))
13799
13800 (defun org-get-buffer-tags ()
13801 "Get a table of all tags used in the buffer, for completion."
13802 (let (tags)
13803 (save-excursion
13804 (goto-char (point-min))
13805 (while (re-search-forward
13806 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13807 (when (equal (char-after (point-at-bol 0)) ?*)
13808 (mapc (lambda (x) (add-to-list 'tags x))
13809 (org-split-string (org-match-string-no-properties 1) ":")))))
13810 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13811 (mapcar 'list tags)))
13812
13813 ;;;; The mapping API
13814
13815 ;;;###autoload
13816 (defun org-map-entries (func &optional match scope &rest skip)
13817 "Call FUNC at each headline selected by MATCH in SCOPE.
13818
13819 FUNC is a function or a lisp form. The function will be called without
13820 arguments, with the cursor positioned at the beginning of the headline.
13821 The return values of all calls to the function will be collected and
13822 returned as a list.
13823
13824 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13825 does not need to preserve point. After evaluation, the cursor will be
13826 moved to the end of the line (presumably of the headline of the
13827 processed entry) and search continues from there. Under some
13828 circumstances, this may not produce the wanted results. For example,
13829 if you have removed (e.g. archived) the current (sub)tree it could
13830 mean that the next entry will be skipped entirely. In such cases, you
13831 can specify the position from where search should continue by making
13832 FUNC set the variable `org-map-continue-from' to the desired buffer
13833 position.
13834
13835 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13836 Only headlines that are matched by this query will be considered during
13837 the iteration. When MATCH is nil or t, all headlines will be
13838 visited by the iteration.
13839
13840 SCOPE determines the scope of this command. It can be any of:
13841
13842 nil The current buffer, respecting the restriction if any
13843 tree The subtree started with the entry at point
13844 region The entries within the active region, if any
13845 region-start-level
13846 The entries within the active region, but only those at
13847 the same level than the first one.
13848 file The current buffer, without restriction
13849 file-with-archives
13850 The current buffer, and any archives associated with it
13851 agenda All agenda files
13852 agenda-with-archives
13853 All agenda files with any archive files associated with them
13854 \(file1 file2 ...)
13855 If this is a list, all files in the list will be scanned
13856
13857 The remaining args are treated as settings for the skipping facilities of
13858 the scanner. The following items can be given here:
13859
13860 archive skip trees with the archive tag.
13861 comment skip trees with the COMMENT keyword
13862 function or Emacs Lisp form:
13863 will be used as value for `org-agenda-skip-function', so whenever
13864 the function returns t, FUNC will not be called for that
13865 entry and search will continue from the point where the
13866 function leaves it.
13867
13868 If your function needs to retrieve the tags including inherited tags
13869 at the *current* entry, you can use the value of the variable
13870 `org-scanner-tags' which will be much faster than getting the value
13871 with `org-get-tags-at'. If your function gets properties with
13872 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13873 to t around the call to `org-entry-properties' to get the same speedup.
13874 Note that if your function moves around to retrieve tags and properties at
13875 a *different* entry, you cannot use these techniques."
13876 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13877 (not (org-region-active-p)))
13878 (let* ((org-agenda-archives-mode nil) ; just to make sure
13879 (org-agenda-skip-archived-trees (memq 'archive skip))
13880 (org-agenda-skip-comment-trees (memq 'comment skip))
13881 (org-agenda-skip-function
13882 (car (org-delete-all '(comment archive) skip)))
13883 (org-tags-match-list-sublevels t)
13884 (start-level (eq scope 'region-start-level))
13885 matcher file res
13886 org-todo-keywords-for-agenda
13887 org-done-keywords-for-agenda
13888 org-todo-keyword-alist-for-agenda
13889 org-drawers-for-agenda
13890 org-tag-alist-for-agenda
13891 todo-only)
13892
13893 (cond
13894 ((eq match t) (setq matcher t))
13895 ((eq match nil) (setq matcher t))
13896 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13897
13898 (save-excursion
13899 (save-restriction
13900 (cond ((eq scope 'tree)
13901 (org-back-to-heading t)
13902 (org-narrow-to-subtree)
13903 (setq scope nil))
13904 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13905 (org-region-active-p))
13906 ;; If needed, set start-level to a string like "2"
13907 (when start-level
13908 (save-excursion
13909 (goto-char (region-beginning))
13910 (unless (org-at-heading-p) (outline-next-heading))
13911 (setq start-level (org-current-level))))
13912 (narrow-to-region (region-beginning)
13913 (save-excursion
13914 (goto-char (region-end))
13915 (unless (and (bolp) (org-at-heading-p))
13916 (outline-next-heading))
13917 (point)))
13918 (setq scope nil)))
13919
13920 (if (not scope)
13921 (progn
13922 (org-prepare-agenda-buffers
13923 (list (buffer-file-name (current-buffer))))
13924 (setq res (org-scan-tags func matcher todo-only start-level)))
13925 ;; Get the right scope
13926 (cond
13927 ((and scope (listp scope) (symbolp (car scope)))
13928 (setq scope (eval scope)))
13929 ((eq scope 'agenda)
13930 (setq scope (org-agenda-files t)))
13931 ((eq scope 'agenda-with-archives)
13932 (setq scope (org-agenda-files t))
13933 (setq scope (org-add-archive-files scope)))
13934 ((eq scope 'file)
13935 (setq scope (list (buffer-file-name))))
13936 ((eq scope 'file-with-archives)
13937 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13938 (org-prepare-agenda-buffers scope)
13939 (while (setq file (pop scope))
13940 (with-current-buffer (org-find-base-buffer-visiting file)
13941 (save-excursion
13942 (save-restriction
13943 (widen)
13944 (goto-char (point-min))
13945 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13946 res)))
13947
13948 ;;;; Properties
13949
13950 ;;; Setting and retrieving properties
13951
13952 (defconst org-special-properties
13953 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13954 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13955 "The special properties valid in Org-mode.
13956
13957 These are properties that are not defined in the property drawer,
13958 but in some other way.")
13959
13960 (defconst org-default-properties
13961 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13962 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13963 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13964 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13965 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13966 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13967 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13968 "Some properties that are used by Org-mode for various purposes.
13969 Being in this list makes sure that they are offered for completion.")
13970
13971 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13972 "Regular expression matching the first line of a property drawer.")
13973
13974 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13975 "Regular expression matching the last line of a property drawer.")
13976
13977 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13978 "Regular expression matching the first line of a property drawer.")
13979
13980 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13981 "Regular expression matching the first line of a property drawer.")
13982
13983 (defconst org-property-drawer-re
13984 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13985 org-property-end-re "\\)\n?")
13986 "Matches an entire property drawer.")
13987
13988 (defconst org-clock-drawer-re
13989 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13990 org-property-end-re "\\)\n?")
13991 "Matches an entire clock drawer.")
13992
13993 (defsubst org-re-property (property)
13994 "Return a regexp matching PROPERTY.
13995 Match group 1 will be set to the value "
13996 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13997
13998 (defun org-property-action ()
13999 "Do an action on properties."
14000 (interactive)
14001 (let (c)
14002 (org-at-property-p)
14003 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14004 (setq c (read-char-exclusive))
14005 (cond
14006 ((equal c ?s)
14007 (call-interactively 'org-set-property))
14008 ((equal c ?d)
14009 (call-interactively 'org-delete-property))
14010 ((equal c ?D)
14011 (call-interactively 'org-delete-property-globally))
14012 ((equal c ?c)
14013 (call-interactively 'org-compute-property-at-point))
14014 (t (error "No such property action %c" c)))))
14015
14016 (defun org-set-effort (&optional value)
14017 "Set the effort property of the current entry.
14018 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14019 allowed value."
14020 (interactive "P")
14021 (if (equal value 0) (setq value 10))
14022 (let* ((completion-ignore-case t)
14023 (prop org-effort-property)
14024 (cur (org-entry-get nil prop))
14025 (allowed (org-property-get-allowed-values nil prop 'table))
14026 (existing (mapcar 'list (org-property-values prop)))
14027 rpl
14028 (val (cond
14029 ((stringp value) value)
14030 ((and allowed (integerp value))
14031 (or (car (nth (1- value) allowed))
14032 (car (org-last allowed))))
14033 (allowed
14034 (message "Select 1-9,0, [RET%s]: %s"
14035 (if cur (concat "=" cur) "")
14036 (mapconcat 'car allowed " "))
14037 (setq rpl (read-char-exclusive))
14038 (if (equal rpl ?\r)
14039 cur
14040 (setq rpl (- rpl ?0))
14041 (if (equal rpl 0) (setq rpl 10))
14042 (if (and (> rpl 0) (<= rpl (length allowed)))
14043 (car (nth (1- rpl) allowed))
14044 (org-completing-read "Effort: " allowed nil))))
14045 (t
14046 (let (org-completion-use-ido org-completion-use-iswitchb)
14047 (org-completing-read
14048 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14049 (concat "[" cur "]") "")
14050 ": ")
14051 existing nil nil "" nil cur))))))
14052 (unless (equal (org-entry-get nil prop) val)
14053 (org-entry-put nil prop val))
14054 (message "%s is now %s" prop val)))
14055
14056 (defun org-at-property-p ()
14057 "Is cursor inside a property drawer?"
14058 (save-excursion
14059 (beginning-of-line 1)
14060 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14061 (save-match-data ;; Used by calling procedures
14062 (let ((p (point))
14063 (range (unless (org-before-first-heading-p)
14064 (org-get-property-block))))
14065 (and range (<= (car range) p) (< p (cdr range))))))))
14066
14067 (defun org-get-property-block (&optional beg end force)
14068 "Return the (beg . end) range of the body of the property drawer.
14069 BEG and END can be beginning and end of subtree, if not given
14070 they will be found.
14071 If the drawer does not exist and FORCE is non-nil, create the drawer."
14072 (catch 'exit
14073 (save-excursion
14074 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14075 (end (or end (progn (outline-next-heading) (point)))))
14076 (goto-char beg)
14077 (if (re-search-forward org-property-start-re end t)
14078 (setq beg (1+ (match-end 0)))
14079 (if force
14080 (save-excursion
14081 (org-insert-property-drawer)
14082 (setq end (progn (outline-next-heading) (point))))
14083 (throw 'exit nil))
14084 (goto-char beg)
14085 (if (re-search-forward org-property-start-re end t)
14086 (setq beg (1+ (match-end 0)))))
14087 (if (re-search-forward org-property-end-re end t)
14088 (setq end (match-beginning 0))
14089 (or force (throw 'exit nil))
14090 (goto-char beg)
14091 (setq end beg)
14092 (org-indent-line-function)
14093 (insert ":END:\n"))
14094 (cons beg end)))))
14095
14096 (defun org-entry-properties (&optional pom which specific)
14097 "Get all properties of the entry at point-or-marker POM.
14098 This includes the TODO keyword, the tags, time strings for deadline,
14099 scheduled, and clocking, and any additional properties defined in the
14100 entry. The return value is an alist, keys may occur multiple times
14101 if the property key was used several times.
14102 POM may also be nil, in which case the current entry is used.
14103 If WHICH is nil or `all', get all properties. If WHICH is
14104 `special' or `standard', only get that subclass. If WHICH
14105 is a string only get exactly this property. SPECIFIC can be a string, the
14106 specific property we are interested in. Specifying it can speed
14107 things up because then unnecessary parsing is avoided."
14108 (setq which (or which 'all))
14109 (org-with-point-at pom
14110 (let ((clockstr (substring org-clock-string 0 -1))
14111 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14112 (case-fold-search nil)
14113 beg end range props sum-props key key1 value string clocksum)
14114 (save-excursion
14115 (when (condition-case nil
14116 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14117 (error nil))
14118 (setq beg (point))
14119 (setq sum-props (get-text-property (point) 'org-summaries))
14120 (setq clocksum (get-text-property (point) :org-clock-minutes))
14121 (outline-next-heading)
14122 (setq end (point))
14123 (when (memq which '(all special))
14124 ;; Get the special properties, like TODO and tags
14125 (goto-char beg)
14126 (when (and (or (not specific) (string= specific "TODO"))
14127 (looking-at org-todo-line-regexp) (match-end 2))
14128 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14129 (when (and (or (not specific) (string= specific "PRIORITY"))
14130 (looking-at org-priority-regexp))
14131 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14132 (when (or (not specific) (string= specific "FILE"))
14133 (push (cons "FILE" buffer-file-name) props))
14134 (when (and (or (not specific) (string= specific "TAGS"))
14135 (setq value (org-get-tags-string))
14136 (string-match "\\S-" value))
14137 (push (cons "TAGS" value) props))
14138 (when (and (or (not specific) (string= specific "ALLTAGS"))
14139 (setq value (org-get-tags-at)))
14140 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14141 ":"))
14142 props))
14143 (when (or (not specific) (string= specific "BLOCKED"))
14144 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14145 (when (or (not specific)
14146 (member specific
14147 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14148 "TIMESTAMP" "TIMESTAMP_IA")))
14149 (catch 'match
14150 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14151 (setq key (if (match-end 1)
14152 (substring (org-match-string-no-properties 1)
14153 0 -1))
14154 string (if (equal key clockstr)
14155 (org-no-properties
14156 (org-trim
14157 (buffer-substring
14158 (match-beginning 3) (goto-char
14159 (point-at-eol)))))
14160 (substring (org-match-string-no-properties 3)
14161 1 -1)))
14162 ;; Get the correct property name from the key. This is
14163 ;; necessary if the user has configured time keywords.
14164 (setq key1 (concat key ":"))
14165 (cond
14166 ((not key)
14167 (setq key
14168 (if (= (char-after (match-beginning 3)) ?\[)
14169 "TIMESTAMP_IA" "TIMESTAMP")))
14170 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14171 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14172 ((equal key1 org-closed-string) (setq key "CLOSED"))
14173 ((equal key1 org-clock-string) (setq key "CLOCK")))
14174 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14175 (progn
14176 (push (cons key string) props)
14177 ;; no need to search further if match is found
14178 (throw 'match t))
14179 (when (or (equal key "CLOCK") (not (assoc key props)))
14180 (push (cons key string) props))))))
14181 )
14182
14183 (when (memq which '(all standard))
14184 ;; Get the standard properties, like :PROP: ...
14185 (setq range (org-get-property-block beg end))
14186 (when range
14187 (goto-char (car range))
14188 (while (re-search-forward
14189 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14190 (cdr range) t)
14191 (setq key (org-match-string-no-properties 1)
14192 value (org-trim (or (org-match-string-no-properties 2) "")))
14193 (unless (member key excluded)
14194 (push (cons key (or value "")) props)))))
14195 (if clocksum
14196 (push (cons "CLOCKSUM"
14197 (org-columns-number-to-string (/ (float clocksum) 60.)
14198 'add_times))
14199 props))
14200 (unless (assoc "CATEGORY" props)
14201 (push (cons "CATEGORY" (org-get-category)) props))
14202 (append sum-props (nreverse props)))))))
14203
14204 (defun org-entry-get (pom property &optional inherit literal-nil)
14205 "Get value of PROPERTY for entry at point-or-marker POM.
14206 If INHERIT is non-nil and the entry does not have the property,
14207 then also check higher levels of the hierarchy.
14208 If INHERIT is the symbol `selective', use inheritance only if the setting
14209 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14210 If the property is present but empty, the return value is the empty string.
14211 If the property is not present at all, nil is returned.
14212
14213 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14214 do not interpret it as the list atom nil. This is used for inheritance
14215 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14216 (org-with-point-at pom
14217 (if (and inherit (if (eq inherit 'selective)
14218 (org-property-inherit-p property)
14219 t))
14220 (org-entry-get-with-inheritance property literal-nil)
14221 (if (member property org-special-properties)
14222 ;; We need a special property. Use `org-entry-properties' to
14223 ;; retrieve it, but specify the wanted property
14224 (cdr (assoc property (org-entry-properties nil 'special property)))
14225 (let ((range (unless (org-before-first-heading-p)
14226 (org-get-property-block)))
14227 (props (list (or (assoc property org-file-properties)
14228 (assoc property org-global-properties)
14229 (assoc property org-global-properties-fixed))))
14230 val)
14231 (flet ((ap (key)
14232 (when (re-search-forward
14233 (org-re-property key) (cdr range) t)
14234 (setq props
14235 (org-update-property-plist
14236 key
14237 (if (match-end 1)
14238 (org-match-string-no-properties 1) "")
14239 props)))))
14240 (when (and range (goto-char (car range)))
14241 (ap property)
14242 (goto-char (car range))
14243 (while (ap (concat property "+")))
14244 (setq val (cdr (assoc property props)))
14245 (when val (if literal-nil val (org-not-nil val))))))))))
14246
14247 (defun org-property-or-variable-value (var &optional inherit)
14248 "Check if there is a property fixing the value of VAR.
14249 If yes, return this value. If not, return the current value of the variable."
14250 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14251 (if (and prop (stringp prop) (string-match "\\S-" prop))
14252 (read prop)
14253 (symbol-value var))))
14254
14255 (defun org-entry-delete (pom property)
14256 "Delete the property PROPERTY from entry at point-or-marker POM."
14257 (org-with-point-at pom
14258 (if (member property org-special-properties)
14259 nil ; cannot delete these properties.
14260 (let ((range (org-get-property-block)))
14261 (if (and range
14262 (goto-char (car range))
14263 (re-search-forward
14264 (org-re-property property)
14265 (cdr range) t))
14266 (progn
14267 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14268 t)
14269 nil)))))
14270
14271 ;; Multi-values properties are properties that contain multiple values
14272 ;; These values are assumed to be single words, separated by whitespace.
14273 (defun org-entry-add-to-multivalued-property (pom property value)
14274 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14275 (let* ((old (org-entry-get pom property))
14276 (values (and old (org-split-string old "[ \t]"))))
14277 (setq value (org-entry-protect-space value))
14278 (unless (member value values)
14279 (setq values (cons value values))
14280 (org-entry-put pom property
14281 (mapconcat 'identity values " ")))))
14282
14283 (defun org-entry-remove-from-multivalued-property (pom property value)
14284 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14285 (let* ((old (org-entry-get pom property))
14286 (values (and old (org-split-string old "[ \t]"))))
14287 (setq value (org-entry-protect-space value))
14288 (when (member value values)
14289 (setq values (delete value values))
14290 (org-entry-put pom property
14291 (mapconcat 'identity values " ")))))
14292
14293 (defun org-entry-member-in-multivalued-property (pom property value)
14294 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14295 (let* ((old (org-entry-get pom property))
14296 (values (and old (org-split-string old "[ \t]"))))
14297 (setq value (org-entry-protect-space value))
14298 (member value values)))
14299
14300 (defun org-entry-get-multivalued-property (pom property)
14301 "Return a list of values in a multivalued property."
14302 (let* ((value (org-entry-get pom property))
14303 (values (and value (org-split-string value "[ \t]"))))
14304 (mapcar 'org-entry-restore-space values)))
14305
14306 (defun org-entry-put-multivalued-property (pom property &rest values)
14307 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14308 VALUES should be a list of strings. Spaces will be protected."
14309 (org-entry-put pom property
14310 (mapconcat 'org-entry-protect-space values " "))
14311 (let* ((value (org-entry-get pom property))
14312 (values (and value (org-split-string value "[ \t]"))))
14313 (mapcar 'org-entry-restore-space values)))
14314
14315 (defun org-entry-protect-space (s)
14316 "Protect spaces and newline in string S."
14317 (while (string-match " " s)
14318 (setq s (replace-match "%20" t t s)))
14319 (while (string-match "\n" s)
14320 (setq s (replace-match "%0A" t t s)))
14321 s)
14322
14323 (defun org-entry-restore-space (s)
14324 "Restore spaces and newline in string S."
14325 (while (string-match "%20" s)
14326 (setq s (replace-match " " t t s)))
14327 (while (string-match "%0A" s)
14328 (setq s (replace-match "\n" t t s)))
14329 s)
14330
14331 (defvar org-entry-property-inherited-from (make-marker)
14332 "Marker pointing to the entry from where a property was inherited.
14333 Each call to `org-entry-get-with-inheritance' will set this marker to the
14334 location of the entry where the inheritance search matched. If there was
14335 no match, the marker will point nowhere.
14336 Note that also `org-entry-get' calls this function, if the INHERIT flag
14337 is set.")
14338
14339 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14340 "Get entry property, and search higher levels if not present.
14341 The search will stop at the first ancestor which has the property defined.
14342 If the value found is \"nil\", return nil to show that the property
14343 should be considered as undefined (this is the meaning of nil here).
14344 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14345 (move-marker org-entry-property-inherited-from nil)
14346 (let (tmp)
14347 (unless (org-before-first-heading-p)
14348 (save-excursion
14349 (save-restriction
14350 (widen)
14351 (catch 'ex
14352 (while t
14353 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14354 (org-back-to-heading t)
14355 (move-marker org-entry-property-inherited-from (point))
14356 (throw 'ex tmp))
14357 (or (org-up-heading-safe) (throw 'ex nil)))))))
14358 (setq tmp (or tmp
14359 (cdr (assoc property org-file-properties))
14360 (cdr (assoc property org-global-properties))
14361 (cdr (assoc property org-global-properties-fixed))))
14362 (if literal-nil tmp (org-not-nil tmp))))
14363
14364 (defvar org-property-changed-functions nil
14365 "Hook called when the value of a property has changed.
14366 Each hook function should accept two arguments, the name of the property
14367 and the new value.")
14368
14369 (defun org-entry-put (pom property value)
14370 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14371 (org-with-point-at pom
14372 (org-back-to-heading t)
14373 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14374 range)
14375 (cond
14376 ((equal property "TODO")
14377 (when (and (stringp value) (string-match "\\S-" value)
14378 (not (member value org-todo-keywords-1)))
14379 (error "\"%s\" is not a valid TODO state" value))
14380 (if (or (not value)
14381 (not (string-match "\\S-" value)))
14382 (setq value 'none))
14383 (org-todo value)
14384 (org-set-tags nil 'align))
14385 ((equal property "PRIORITY")
14386 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14387 (string-to-char value) ?\ ))
14388 (org-set-tags nil 'align))
14389 ((equal property "SCHEDULED")
14390 (if (re-search-forward org-scheduled-time-regexp end t)
14391 (cond
14392 ((eq value 'earlier) (org-timestamp-change -1 'day))
14393 ((eq value 'later) (org-timestamp-change 1 'day))
14394 (t (call-interactively 'org-schedule)))
14395 (call-interactively 'org-schedule)))
14396 ((equal property "DEADLINE")
14397 (if (re-search-forward org-deadline-time-regexp end t)
14398 (cond
14399 ((eq value 'earlier) (org-timestamp-change -1 'day))
14400 ((eq value 'later) (org-timestamp-change 1 'day))
14401 (t (call-interactively 'org-deadline)))
14402 (call-interactively 'org-deadline)))
14403 ((member property org-special-properties)
14404 (error "The %s property can not yet be set with `org-entry-put'"
14405 property))
14406 (t ; a non-special property
14407 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14408 (setq range (org-get-property-block beg end 'force))
14409 (goto-char (car range))
14410 (if (re-search-forward
14411 (org-re-property property) (cdr range) t)
14412 (progn
14413 (delete-region (match-beginning 0) (match-end 0))
14414 (goto-char (match-beginning 0)))
14415 (goto-char (cdr range))
14416 (insert "\n")
14417 (backward-char 1)
14418 (org-indent-line-function))
14419 (insert ":" property ":")
14420 (and value (insert " " value))
14421 (org-indent-line-function)))))
14422 (run-hook-with-args 'org-property-changed-functions property value)))
14423
14424 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14425 "Get all property keys in the current buffer.
14426 With INCLUDE-SPECIALS, also list the special properties that reflect things
14427 like tags and TODO state.
14428 With INCLUDE-DEFAULTS, also include properties that has special meaning
14429 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14430 and others.
14431 With INCLUDE-COLUMNS, also include property names given in COLUMN
14432 formats in the current buffer."
14433 (let (rtn range cfmt s p)
14434 (save-excursion
14435 (save-restriction
14436 (widen)
14437 (goto-char (point-min))
14438 (while (re-search-forward org-property-start-re nil t)
14439 (setq range (org-get-property-block))
14440 (goto-char (car range))
14441 (while (re-search-forward
14442 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14443 (cdr range) t)
14444 (add-to-list 'rtn (org-match-string-no-properties 1)))
14445 (outline-next-heading))))
14446
14447 (when include-specials
14448 (setq rtn (append org-special-properties rtn)))
14449
14450 (when include-defaults
14451 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14452 (add-to-list 'rtn org-effort-property))
14453
14454 (when include-columns
14455 (save-excursion
14456 (save-restriction
14457 (widen)
14458 (goto-char (point-min))
14459 (while (re-search-forward
14460 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14461 nil t)
14462 (setq cfmt (match-string 2) s 0)
14463 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14464 cfmt s)
14465 (setq s (match-end 0)
14466 p (match-string 1 cfmt))
14467 (unless (or (equal p "ITEM")
14468 (member p org-special-properties))
14469 (add-to-list 'rtn (match-string 1 cfmt))))))))
14470
14471 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14472
14473 (defun org-property-values (key)
14474 "Return a list of all values of property KEY in the current buffer."
14475 (save-excursion
14476 (save-restriction
14477 (widen)
14478 (goto-char (point-min))
14479 (let ((re (org-re-property key))
14480 values)
14481 (while (re-search-forward re nil t)
14482 (add-to-list 'values (org-trim (match-string 1))))
14483 (delete "" values)))))
14484
14485 (defun org-insert-property-drawer ()
14486 "Insert a property drawer into the current entry."
14487 (interactive)
14488 (org-back-to-heading t)
14489 (looking-at org-outline-regexp)
14490 (let ((indent (if org-adapt-indentation
14491 (- (match-end 0)(match-beginning 0))
14492 0))
14493 (beg (point))
14494 (re (concat "^[ \t]*" org-keyword-time-regexp))
14495 end hiddenp)
14496 (outline-next-heading)
14497 (setq end (point))
14498 (goto-char beg)
14499 (while (re-search-forward re end t))
14500 (setq hiddenp (outline-invisible-p))
14501 (end-of-line 1)
14502 (and (equal (char-after) ?\n) (forward-char 1))
14503 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14504 (if (member (match-string 1) '("CLOCK:" ":END:"))
14505 ;; just skip this line
14506 (beginning-of-line 2)
14507 ;; Drawer start, find the end
14508 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14509 (beginning-of-line 1)))
14510 (org-skip-over-state-notes)
14511 (skip-chars-backward " \t\n\r")
14512 (if (eq (char-before) ?*) (forward-char 1))
14513 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14514 (beginning-of-line 0)
14515 (org-indent-to-column indent)
14516 (beginning-of-line 2)
14517 (org-indent-to-column indent)
14518 (beginning-of-line 0)
14519 (if hiddenp
14520 (save-excursion
14521 (org-back-to-heading t)
14522 (hide-entry))
14523 (org-flag-drawer t))))
14524
14525 (defvar org-property-set-functions-alist nil
14526 "Property set function alist.
14527 Each entry should have the following format:
14528
14529 (PROPERTY . READ-FUNCTION)
14530
14531 The read function will be called with the same argument as
14532 `org-completing-read'.")
14533
14534 (defun org-set-property-function (property)
14535 "Get the function that should be used to set PROPERTY.
14536 This is computed according to `org-property-set-functions-alist'."
14537 (or (cdr (assoc property org-property-set-functions-alist))
14538 'org-completing-read))
14539
14540 (defun org-read-property-value (property)
14541 "Read PROPERTY value from user."
14542 (let* ((completion-ignore-case t)
14543 (allowed (org-property-get-allowed-values nil property 'table))
14544 (cur (org-entry-get nil property))
14545 (prompt (concat property " value"
14546 (if (and cur (string-match "\\S-" cur))
14547 (concat " [" cur "]") "") ": "))
14548 (set-function (org-set-property-function property))
14549 (val (if allowed
14550 (funcall set-function prompt allowed nil
14551 (not (get-text-property 0 'org-unrestricted
14552 (caar allowed))))
14553 (let (org-completion-use-ido org-completion-use-iswitchb)
14554 (funcall set-function prompt
14555 (mapcar 'list (org-property-values property))
14556 nil nil "" nil cur)))))
14557 (if (equal val "")
14558 cur
14559 val)))
14560
14561 (defvar org-last-set-property nil)
14562 (defun org-read-property-name ()
14563 "Read a property name."
14564 (let* ((completion-ignore-case t)
14565 (keys (org-buffer-property-keys nil t t))
14566 (default-prop (or (save-excursion
14567 (save-match-data
14568 (beginning-of-line)
14569 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14570 (null (string= (match-string 1) "END"))
14571 (match-string 1))))
14572 org-last-set-property))
14573 (property (org-icompleting-read
14574 (concat "Property"
14575 (if default-prop (concat " [" default-prop "]") "")
14576 ": ")
14577 (mapcar 'list keys)
14578 nil nil nil nil
14579 default-prop
14580 )))
14581 (if (member property keys)
14582 property
14583 (or (cdr (assoc (downcase property)
14584 (mapcar (lambda (x) (cons (downcase x) x))
14585 keys)))
14586 property))))
14587
14588 (defun org-set-property (property value)
14589 "In the current entry, set PROPERTY to VALUE.
14590 When called interactively, this will prompt for a property name, offering
14591 completion on existing and default properties. And then it will prompt
14592 for a value, offering completion either on allowed values (via an inherited
14593 xxx_ALL property) or on existing values in other instances of this property
14594 in the current file."
14595 (interactive (list nil nil))
14596 (let* ((property (or property (org-read-property-name)))
14597 (value (or value (org-read-property-value property)))
14598 (fn (assoc property org-properties-postprocess-alist)))
14599 (setq org-last-set-property property)
14600 ;; Possibly postprocess the inserted value:
14601 (when fn (setq value (funcall (cadr fn) value)))
14602 (unless (equal (org-entry-get nil property) value)
14603 (org-entry-put nil property value))))
14604
14605 (defun org-delete-property (property)
14606 "In the current entry, delete PROPERTY."
14607 (interactive
14608 (let* ((completion-ignore-case t)
14609 (prop (org-icompleting-read "Property: "
14610 (org-entry-properties nil 'standard))))
14611 (list prop)))
14612 (message "Property %s %s" property
14613 (if (org-entry-delete nil property)
14614 "deleted"
14615 "was not present in the entry")))
14616
14617 (defun org-delete-property-globally (property)
14618 "Remove PROPERTY globally, from all entries."
14619 (interactive
14620 (let* ((completion-ignore-case t)
14621 (prop (org-icompleting-read
14622 "Globally remove property: "
14623 (mapcar 'list (org-buffer-property-keys)))))
14624 (list prop)))
14625 (save-excursion
14626 (save-restriction
14627 (widen)
14628 (goto-char (point-min))
14629 (let ((cnt 0))
14630 (while (re-search-forward
14631 (org-re-property property)
14632 nil t)
14633 (setq cnt (1+ cnt))
14634 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14635 (message "Property \"%s\" removed from %d entries" property cnt)))))
14636
14637 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14638
14639 (defun org-compute-property-at-point ()
14640 "Compute the property at point.
14641 This looks for an enclosing column format, extracts the operator and
14642 then applies it to the property in the column format's scope."
14643 (interactive)
14644 (unless (org-at-property-p)
14645 (error "Not at a property"))
14646 (let ((prop (org-match-string-no-properties 2)))
14647 (org-columns-get-format-and-top-level)
14648 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14649 (error "No operator defined for property %s" prop))
14650 (org-columns-compute prop)))
14651
14652 (defvar org-property-allowed-value-functions nil
14653 "Hook for functions supplying allowed values for a specific property.
14654 The functions must take a single argument, the name of the property, and
14655 return a flat list of allowed values. If \":ETC\" is one of
14656 the values, this means that these values are intended as defaults for
14657 completion, but that other values should be allowed too.
14658 The functions must return nil if they are not responsible for this
14659 property.")
14660
14661 (defun org-property-get-allowed-values (pom property &optional table)
14662 "Get allowed values for the property PROPERTY.
14663 When TABLE is non-nil, return an alist that can directly be used for
14664 completion."
14665 (let (vals)
14666 (cond
14667 ((equal property "TODO")
14668 (setq vals (org-with-point-at pom
14669 (append org-todo-keywords-1 '("")))))
14670 ((equal property "PRIORITY")
14671 (let ((n org-lowest-priority))
14672 (while (>= n org-highest-priority)
14673 (push (char-to-string n) vals)
14674 (setq n (1- n)))))
14675 ((member property org-special-properties))
14676 ((setq vals (run-hook-with-args-until-success
14677 'org-property-allowed-value-functions property)))
14678 (t
14679 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14680 (when (and vals (string-match "\\S-" vals))
14681 (setq vals (car (read-from-string (concat "(" vals ")"))))
14682 (setq vals (mapcar (lambda (x)
14683 (cond ((stringp x) x)
14684 ((numberp x) (number-to-string x))
14685 ((symbolp x) (symbol-name x))
14686 (t "???")))
14687 vals)))))
14688 (when (member ":ETC" vals)
14689 (setq vals (remove ":ETC" vals))
14690 (org-add-props (car vals) '(org-unrestricted t)))
14691 (if table (mapcar 'list vals) vals)))
14692
14693 (defun org-property-previous-allowed-value (&optional previous)
14694 "Switch to the next allowed value for this property."
14695 (interactive)
14696 (org-property-next-allowed-value t))
14697
14698 (defun org-property-next-allowed-value (&optional previous)
14699 "Switch to the next allowed value for this property."
14700 (interactive)
14701 (unless (org-at-property-p)
14702 (error "Not at a property"))
14703 (let* ((key (match-string 2))
14704 (value (match-string 3))
14705 (allowed (or (org-property-get-allowed-values (point) key)
14706 (and (member value '("[ ]" "[-]" "[X]"))
14707 '("[ ]" "[X]"))))
14708 nval)
14709 (unless allowed
14710 (error "Allowed values for this property have not been defined"))
14711 (if previous (setq allowed (reverse allowed)))
14712 (if (member value allowed)
14713 (setq nval (car (cdr (member value allowed)))))
14714 (setq nval (or nval (car allowed)))
14715 (if (equal nval value)
14716 (error "Only one allowed value for this property"))
14717 (org-at-property-p)
14718 (replace-match (concat " :" key ": " nval) t t)
14719 (org-indent-line-function)
14720 (beginning-of-line 1)
14721 (skip-chars-forward " \t")
14722 (run-hook-with-args 'org-property-changed-functions key nval)))
14723
14724 (defun org-find-olp (path &optional this-buffer)
14725 "Return a marker pointing to the entry at outline path OLP.
14726 If anything goes wrong, throw an error.
14727 You can wrap this call to catch the error like this:
14728
14729 (condition-case msg
14730 (org-mobile-locate-entry (match-string 4))
14731 (error (nth 1 msg)))
14732
14733 The return value will then be either a string with the error message,
14734 or a marker if everything is OK.
14735
14736 If THIS-BUFFER is set, the outline path does not contain a file,
14737 only headings."
14738 (let* ((file (if this-buffer buffer-file-name (pop path)))
14739 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14740 (level 1)
14741 (lmin 1)
14742 (lmax 1)
14743 limit re end found pos heading cnt flevel)
14744 (unless buffer (error "File not found :%s" file))
14745 (with-current-buffer buffer
14746 (save-excursion
14747 (save-restriction
14748 (widen)
14749 (setq limit (point-max))
14750 (goto-char (point-min))
14751 (while (setq heading (pop path))
14752 (setq re (format org-complex-heading-regexp-format
14753 (regexp-quote heading)))
14754 (setq cnt 0 pos (point))
14755 (while (re-search-forward re end t)
14756 (setq level (- (match-end 1) (match-beginning 1)))
14757 (if (and (>= level lmin) (<= level lmax))
14758 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14759 (when (= cnt 0) (error "Heading not found on level %d: %s"
14760 lmax heading))
14761 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14762 lmax heading))
14763 (goto-char found)
14764 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14765 (setq end (save-excursion (org-end-of-subtree t t))))
14766 (when (org-at-heading-p)
14767 (move-marker (make-marker) (point))))))))
14768
14769 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14770 "Find node HEADING in BUFFER.
14771 Return a marker to the heading if it was found, or nil if not.
14772 If POS-ONLY is set, return just the position instead of a marker.
14773
14774 The heading text must match exact, but it may have a TODO keyword,
14775 a priority cookie and tags in the standard locations."
14776 (with-current-buffer (or buffer (current-buffer))
14777 (save-excursion
14778 (save-restriction
14779 (widen)
14780 (goto-char (point-min))
14781 (let (case-fold-search)
14782 (if (re-search-forward
14783 (format org-complex-heading-regexp-format
14784 (regexp-quote heading)) nil t)
14785 (if pos-only
14786 (match-beginning 0)
14787 (move-marker (make-marker) (match-beginning 0)))))))))
14788
14789 (defun org-find-exact-heading-in-directory (heading &optional dir)
14790 "Find Org node headline HEADING in all .org files in directory DIR.
14791 When the target headline is found, return a marker to this location."
14792 (let ((files (directory-files (or dir default-directory)
14793 nil "\\`[^.#].*\\.org\\'"))
14794 file visiting m buffer)
14795 (catch 'found
14796 (while (setq file (pop files))
14797 (message "trying %s" file)
14798 (setq visiting (org-find-base-buffer-visiting file))
14799 (setq buffer (or visiting (find-file-noselect file)))
14800 (setq m (org-find-exact-headline-in-buffer
14801 heading buffer))
14802 (when (and (not m) (not visiting)) (kill-buffer buffer))
14803 (and m (throw 'found m))))))
14804
14805 (defun org-find-entry-with-id (ident)
14806 "Locate the entry that contains the ID property with exact value IDENT.
14807 IDENT can be a string, a symbol or a number, this function will search for
14808 the string representation of it.
14809 Return the position where this entry starts, or nil if there is no such entry."
14810 (interactive "sID: ")
14811 (let ((id (cond
14812 ((stringp ident) ident)
14813 ((symbol-name ident) (symbol-name ident))
14814 ((numberp ident) (number-to-string ident))
14815 (t (error "IDENT %s must be a string, symbol or number" ident))))
14816 (case-fold-search nil))
14817 (save-excursion
14818 (save-restriction
14819 (widen)
14820 (goto-char (point-min))
14821 (when (re-search-forward
14822 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14823 nil t)
14824 (org-back-to-heading t)
14825 (point))))))
14826
14827 ;;;; Timestamps
14828
14829 (defvar org-last-changed-timestamp nil)
14830 (defvar org-last-inserted-timestamp nil
14831 "The last time stamp inserted with `org-insert-time-stamp'.")
14832 (defvar org-time-was-given) ; dynamically scoped parameter
14833 (defvar org-end-time-was-given) ; dynamically scoped parameter
14834 (defvar org-ts-what) ; dynamically scoped parameter
14835
14836 (defun org-time-stamp (arg &optional inactive)
14837 "Prompt for a date/time and insert a time stamp.
14838 If the user specifies a time like HH:MM, or if this command is called
14839 with a prefix argument, the time stamp will contain date and time.
14840 Otherwise, only the date will be included. All parts of a date not
14841 specified by the user will be filled in from the current date/time.
14842 So if you press just return without typing anything, the time stamp
14843 will represent the current date/time. If there is already a timestamp
14844 at the cursor, it will be modified."
14845 (interactive "P")
14846 (let* ((ts nil)
14847 (default-time
14848 ;; Default time is either today, or, when entering a range,
14849 ;; the range start.
14850 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14851 (save-excursion
14852 (re-search-backward
14853 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14854 (- (point) 20) t)))
14855 (apply 'encode-time (org-parse-time-string (match-string 1)))
14856 (current-time)))
14857 (default-input (and ts (org-get-compact-tod ts)))
14858 (repeater (save-excursion
14859 (save-match-data
14860 (beginning-of-line)
14861 (when (re-search-forward
14862 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14863 (save-excursion (progn (end-of-line) (point))) t)
14864 (match-string 0)))))
14865 org-time-was-given org-end-time-was-given time)
14866 (cond
14867 ((and (org-at-timestamp-p t)
14868 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14869 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14870 (insert "--")
14871 (setq time (let ((this-command this-command))
14872 (org-read-date arg 'totime nil nil
14873 default-time default-input)))
14874 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14875 ((org-at-timestamp-p t)
14876 (setq time (let ((this-command this-command))
14877 (org-read-date arg 'totime nil nil default-time default-input)))
14878 (when (org-at-timestamp-p t) ; just to get the match data
14879 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14880 (replace-match "")
14881 (setq org-last-changed-timestamp
14882 (org-insert-time-stamp
14883 time (or org-time-was-given arg)
14884 inactive nil nil (list org-end-time-was-given)))
14885 (when repeater (goto-char (1- (point))) (insert " " repeater)
14886 (setq org-last-changed-timestamp
14887 (concat (substring org-last-inserted-timestamp 0 -1)
14888 " " repeater ">"))))
14889 (message "Timestamp updated"))
14890 (t
14891 (setq time (let ((this-command this-command))
14892 (org-read-date arg 'totime nil nil default-time default-input)))
14893 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14894 nil nil (list org-end-time-was-given))))))
14895
14896 ;; FIXME: can we use this for something else, like computing time differences?
14897 (defun org-get-compact-tod (s)
14898 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14899 (let* ((t1 (match-string 1 s))
14900 (h1 (string-to-number (match-string 2 s)))
14901 (m1 (string-to-number (match-string 3 s)))
14902 (t2 (and (match-end 4) (match-string 5 s)))
14903 (h2 (and t2 (string-to-number (match-string 6 s))))
14904 (m2 (and t2 (string-to-number (match-string 7 s))))
14905 dh dm)
14906 (if (not t2)
14907 t1
14908 (setq dh (- h2 h1) dm (- m2 m1))
14909 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14910 (concat t1 "+" (number-to-string dh)
14911 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14912
14913 (defun org-time-stamp-inactive (&optional arg)
14914 "Insert an inactive time stamp.
14915 An inactive time stamp is enclosed in square brackets instead of angle
14916 brackets. It is inactive in the sense that it does not trigger agenda entries,
14917 does not link to the calendar and cannot be changed with the S-cursor keys.
14918 So these are more for recording a certain time/date."
14919 (interactive "P")
14920 (org-time-stamp arg 'inactive))
14921
14922 (defvar org-date-ovl (make-overlay 1 1))
14923 (overlay-put org-date-ovl 'face 'org-date-selected)
14924 (org-detach-overlay org-date-ovl)
14925
14926 (defvar org-ans1) ; dynamically scoped parameter
14927 (defvar org-ans2) ; dynamically scoped parameter
14928
14929 (defvar org-plain-time-of-day-regexp) ; defined below
14930
14931 (defvar org-overriding-default-time nil) ; dynamically scoped
14932 (defvar org-read-date-overlay nil)
14933 (defvar org-dcst nil) ; dynamically scoped
14934 (defvar org-read-date-history nil)
14935 (defvar org-read-date-final-answer nil)
14936 (defvar org-read-date-analyze-futurep nil)
14937 (defvar org-read-date-analyze-forced-year nil)
14938
14939 (defun org-read-date (&optional org-with-time to-time from-string prompt
14940 default-time default-input)
14941 "Read a date, possibly a time, and make things smooth for the user.
14942 The prompt will suggest to enter an ISO date, but you can also enter anything
14943 which will at least partially be understood by `parse-time-string'.
14944 Unrecognized parts of the date will default to the current day, month, year,
14945 hour and minute. If this command is called to replace a timestamp at point,
14946 or to enter the second timestamp of a range, the default time is taken
14947 from the existing stamp. Furthermore, the command prefers the future,
14948 so if you are giving a date where the year is not given, and the day-month
14949 combination is already past in the current year, it will assume you
14950 mean next year. For details, see the manual. A few examples:
14951
14952 3-2-5 --> 2003-02-05
14953 feb 15 --> currentyear-02-15
14954 2/15 --> currentyear-02-15
14955 sep 12 9 --> 2009-09-12
14956 12:45 --> today 12:45
14957 22 sept 0:34 --> currentyear-09-22 0:34
14958 12 --> currentyear-currentmonth-12
14959 Fri --> nearest Friday (today or later)
14960 etc.
14961
14962 Furthermore you can specify a relative date by giving, as the *first* thing
14963 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14964 change in days weeks, months, years.
14965 With a single plus or minus, the date is relative to today. With a double
14966 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14967 +4d --> four days from today
14968 +4 --> same as above
14969 +2w --> two weeks from today
14970 ++5 --> five days from default date
14971
14972 The function understands only English month and weekday abbreviations.
14973
14974 While prompting, a calendar is popped up - you can also select the
14975 date with the mouse (button 1). The calendar shows a period of three
14976 months. To scroll it to other months, use the keys `>' and `<'.
14977 If you don't like the calendar, turn it off with
14978 \(setq org-read-date-popup-calendar nil)
14979
14980 With optional argument TO-TIME, the date will immediately be converted
14981 to an internal time.
14982 With an optional argument WITH-TIME, the prompt will suggest to also
14983 insert a time. Note that when WITH-TIME is not set, you can still
14984 enter a time, and this function will inform the calling routine about
14985 this change. The calling routine may then choose to change the format
14986 used to insert the time stamp into the buffer to include the time.
14987 With optional argument FROM-STRING, read from this string instead from
14988 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14989 the time/date that is used for everything that is not specified by the
14990 user."
14991 (require 'parse-time)
14992 (let* ((org-time-stamp-rounding-minutes
14993 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14994 (org-dcst org-display-custom-times)
14995 (ct (org-current-time))
14996 (org-def (or org-overriding-default-time default-time ct))
14997 (org-defdecode (decode-time org-def))
14998 (dummy (progn
14999 (when (< (nth 2 org-defdecode) org-extend-today-until)
15000 (setcar (nthcdr 2 org-defdecode) -1)
15001 (setcar (nthcdr 1 org-defdecode) 59)
15002 (setq org-def (apply 'encode-time org-defdecode)
15003 org-defdecode (decode-time org-def)))))
15004 (calendar-frame-setup nil)
15005 (calendar-setup nil)
15006 (calendar-move-hook nil)
15007 (calendar-view-diary-initially-flag nil)
15008 (calendar-view-holidays-initially-flag nil)
15009 (timestr (format-time-string
15010 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15011 (prompt (concat (if prompt (concat prompt " ") "")
15012 (format "Date+time [%s]: " timestr)))
15013 ans (org-ans0 "") org-ans1 org-ans2 final)
15014
15015 (cond
15016 (from-string (setq ans from-string))
15017 (org-read-date-popup-calendar
15018 (save-excursion
15019 (save-window-excursion
15020 (calendar)
15021 (unwind-protect
15022 (progn
15023 (calendar-forward-day (- (time-to-days org-def)
15024 (calendar-absolute-from-gregorian
15025 (calendar-current-date))))
15026 (org-eval-in-calendar nil t)
15027 (let* ((old-map (current-local-map))
15028 (map (copy-keymap calendar-mode-map))
15029 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15030 (org-defkey map (kbd "RET") 'org-calendar-select)
15031 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15032 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15033 (org-defkey minibuffer-local-map [(meta shift left)]
15034 (lambda () (interactive)
15035 (org-eval-in-calendar '(calendar-backward-month 1))))
15036 (org-defkey minibuffer-local-map [(meta shift right)]
15037 (lambda () (interactive)
15038 (org-eval-in-calendar '(calendar-forward-month 1))))
15039 (org-defkey minibuffer-local-map [(meta shift up)]
15040 (lambda () (interactive)
15041 (org-eval-in-calendar '(calendar-backward-year 1))))
15042 (org-defkey minibuffer-local-map [(meta shift down)]
15043 (lambda () (interactive)
15044 (org-eval-in-calendar '(calendar-forward-year 1))))
15045 (org-defkey minibuffer-local-map [?\e (shift left)]
15046 (lambda () (interactive)
15047 (org-eval-in-calendar '(calendar-backward-month 1))))
15048 (org-defkey minibuffer-local-map [?\e (shift right)]
15049 (lambda () (interactive)
15050 (org-eval-in-calendar '(calendar-forward-month 1))))
15051 (org-defkey minibuffer-local-map [?\e (shift up)]
15052 (lambda () (interactive)
15053 (org-eval-in-calendar '(calendar-backward-year 1))))
15054 (org-defkey minibuffer-local-map [?\e (shift down)]
15055 (lambda () (interactive)
15056 (org-eval-in-calendar '(calendar-forward-year 1))))
15057 (org-defkey minibuffer-local-map [(shift up)]
15058 (lambda () (interactive)
15059 (org-eval-in-calendar '(calendar-backward-week 1))))
15060 (org-defkey minibuffer-local-map [(shift down)]
15061 (lambda () (interactive)
15062 (org-eval-in-calendar '(calendar-forward-week 1))))
15063 (org-defkey minibuffer-local-map [(shift left)]
15064 (lambda () (interactive)
15065 (org-eval-in-calendar '(calendar-backward-day 1))))
15066 (org-defkey minibuffer-local-map [(shift right)]
15067 (lambda () (interactive)
15068 (org-eval-in-calendar '(calendar-forward-day 1))))
15069 (org-defkey minibuffer-local-map ">"
15070 (lambda () (interactive)
15071 (org-eval-in-calendar '(scroll-calendar-left 1))))
15072 (org-defkey minibuffer-local-map "<"
15073 (lambda () (interactive)
15074 (org-eval-in-calendar '(scroll-calendar-right 1))))
15075 (org-defkey minibuffer-local-map "\C-v"
15076 (lambda () (interactive)
15077 (org-eval-in-calendar
15078 '(calendar-scroll-left-three-months 1))))
15079 (org-defkey minibuffer-local-map "\M-v"
15080 (lambda () (interactive)
15081 (org-eval-in-calendar
15082 '(calendar-scroll-right-three-months 1))))
15083 (run-hooks 'org-read-date-minibuffer-setup-hook)
15084 (unwind-protect
15085 (progn
15086 (use-local-map map)
15087 (add-hook 'post-command-hook 'org-read-date-display)
15088 (setq org-ans0 (read-string prompt default-input
15089 'org-read-date-history nil))
15090 ;; org-ans0: from prompt
15091 ;; org-ans1: from mouse click
15092 ;; org-ans2: from calendar motion
15093 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15094 (remove-hook 'post-command-hook 'org-read-date-display)
15095 (use-local-map old-map)
15096 (when org-read-date-overlay
15097 (delete-overlay org-read-date-overlay)
15098 (setq org-read-date-overlay nil)))))
15099 (bury-buffer "*Calendar*")))))
15100
15101 (t ; Naked prompt only
15102 (unwind-protect
15103 (setq ans (read-string prompt default-input
15104 'org-read-date-history timestr))
15105 (when org-read-date-overlay
15106 (delete-overlay org-read-date-overlay)
15107 (setq org-read-date-overlay nil)))))
15108
15109 (setq final (org-read-date-analyze ans org-def org-defdecode))
15110
15111 (when org-read-date-analyze-forced-year
15112 (message "Year was forced into %s"
15113 (if org-read-date-force-compatible-dates
15114 "compatible range (1970-2037)"
15115 "range representable on this machine"))
15116 (ding))
15117
15118 ;; One round trip to get rid of 34th of August and stuff like that....
15119 (setq final (decode-time (apply 'encode-time final)))
15120
15121 (setq org-read-date-final-answer ans)
15122
15123 (if to-time
15124 (apply 'encode-time final)
15125 (if (and (boundp 'org-time-was-given) org-time-was-given)
15126 (format "%04d-%02d-%02d %02d:%02d"
15127 (nth 5 final) (nth 4 final) (nth 3 final)
15128 (nth 2 final) (nth 1 final))
15129 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15130
15131 (defvar org-def)
15132 (defvar org-defdecode)
15133 (defvar org-with-time)
15134 (defun org-read-date-display ()
15135 "Display the current date prompt interpretation in the minibuffer."
15136 (when org-read-date-display-live
15137 (when org-read-date-overlay
15138 (delete-overlay org-read-date-overlay))
15139 (when (minibufferp (current-buffer))
15140 (save-excursion
15141 (end-of-line 1)
15142 (while (not (equal (buffer-substring
15143 (max (point-min) (- (point) 4)) (point))
15144 " "))
15145 (insert " ")))
15146 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15147 " " (or org-ans1 org-ans2)))
15148 (org-end-time-was-given nil)
15149 (f (org-read-date-analyze ans org-def org-defdecode))
15150 (fmts (if org-dcst
15151 org-time-stamp-custom-formats
15152 org-time-stamp-formats))
15153 (fmt (if (or org-with-time
15154 (and (boundp 'org-time-was-given) org-time-was-given))
15155 (cdr fmts)
15156 (car fmts)))
15157 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15158 (when (and org-end-time-was-given
15159 (string-match org-plain-time-of-day-regexp txt))
15160 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15161 org-end-time-was-given
15162 (substring txt (match-end 0)))))
15163 (when org-read-date-analyze-futurep
15164 (setq txt (concat txt " (=>F)")))
15165 (setq org-read-date-overlay
15166 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15167 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15168
15169 (defun org-read-date-analyze (ans org-def org-defdecode)
15170 "Analyze the combined answer of the date prompt."
15171 ;; FIXME: cleanup and comment
15172 (let ((nowdecode (decode-time (current-time)))
15173 delta deltan deltaw deltadef year month day
15174 hour minute second wday pm h2 m2 tl wday1
15175 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15176 (setq org-read-date-analyze-futurep nil
15177 org-read-date-analyze-forced-year nil)
15178 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15179 (setq ans "+0"))
15180
15181 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15182 (setq ans (replace-match "" t t ans)
15183 deltan (car delta)
15184 deltaw (nth 1 delta)
15185 deltadef (nth 2 delta)))
15186
15187 ;; Check if there is an iso week date in there
15188 ;; If yes, store the info and postpone interpreting it until the rest
15189 ;; of the parsing is done
15190 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15191 (setq iso-year (if (match-end 1)
15192 (org-small-year-to-year
15193 (string-to-number (match-string 1 ans))))
15194 iso-weekday (if (match-end 3)
15195 (string-to-number (match-string 3 ans)))
15196 iso-week (string-to-number (match-string 2 ans)))
15197 (setq ans (replace-match "" t t ans)))
15198
15199 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15200 (when (string-match
15201 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15202 (setq year (if (match-end 2)
15203 (string-to-number (match-string 2 ans))
15204 (progn (setq kill-year t)
15205 (string-to-number (format-time-string "%Y"))))
15206 month (string-to-number (match-string 3 ans))
15207 day (string-to-number (match-string 4 ans)))
15208 (if (< year 100) (setq year (+ 2000 year)))
15209 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15210 t nil ans)))
15211
15212 ;; Help matching dotted european dates
15213 (when (string-match
15214 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15215 (setq year (if (match-end 3)
15216 (string-to-number (match-string 3 ans))
15217 (progn (setq kill-year t)
15218 (string-to-number (format-time-string "%Y"))))
15219 day (string-to-number (match-string 1 ans))
15220 month (string-to-number (match-string 2 ans))
15221 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15222 t nil ans)))
15223
15224 ;; Help matching american dates, like 5/30 or 5/30/7
15225 (when (string-match
15226 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15227 (setq year (if (match-end 4)
15228 (string-to-number (match-string 4 ans))
15229 (progn (setq kill-year t)
15230 (string-to-number (format-time-string "%Y"))))
15231 month (string-to-number (match-string 1 ans))
15232 day (string-to-number (match-string 2 ans)))
15233 (if (< year 100) (setq year (+ 2000 year)))
15234 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15235 t nil ans)))
15236 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15237 ;; If there is a time with am/pm, and *no* time without it, we convert
15238 ;; so that matching will be successful.
15239 (loop for i from 1 to 2 do ; twice, for end time as well
15240 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15241 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15242 (setq hour (string-to-number (match-string 1 ans))
15243 minute (if (match-end 3)
15244 (string-to-number (match-string 3 ans))
15245 0)
15246 pm (equal ?p
15247 (string-to-char (downcase (match-string 4 ans)))))
15248 (if (and (= hour 12) (not pm))
15249 (setq hour 0)
15250 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15251 (setq ans (replace-match (format "%02d:%02d" hour minute)
15252 t t ans))))
15253
15254 ;; Check if a time range is given as a duration
15255 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15256 (setq hour (string-to-number (match-string 1 ans))
15257 h2 (+ hour (string-to-number (match-string 3 ans)))
15258 minute (string-to-number (match-string 2 ans))
15259 m2 (+ minute (if (match-end 5) (string-to-number
15260 (match-string 5 ans))0)))
15261 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15262 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15263 t t ans)))
15264
15265 ;; Check if there is a time range
15266 (when (boundp 'org-end-time-was-given)
15267 (setq org-time-was-given nil)
15268 (when (and (string-match org-plain-time-of-day-regexp ans)
15269 (match-end 8))
15270 (setq org-end-time-was-given (match-string 8 ans))
15271 (setq ans (concat (substring ans 0 (match-beginning 7))
15272 (substring ans (match-end 7))))))
15273
15274 (setq tl (parse-time-string ans)
15275 day (or (nth 3 tl) (nth 3 org-defdecode))
15276 month (or (nth 4 tl)
15277 (if (and org-read-date-prefer-future
15278 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15279 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15280 (nth 4 org-defdecode)))
15281 year (or (and (not kill-year) (nth 5 tl))
15282 (if (and org-read-date-prefer-future
15283 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15284 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15285 (nth 5 org-defdecode)))
15286 hour (or (nth 2 tl) (nth 2 org-defdecode))
15287 minute (or (nth 1 tl) (nth 1 org-defdecode))
15288 second (or (nth 0 tl) 0)
15289 wday (nth 6 tl))
15290
15291 (when (and (eq org-read-date-prefer-future 'time)
15292 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15293 (equal day (nth 3 nowdecode))
15294 (equal month (nth 4 nowdecode))
15295 (equal year (nth 5 nowdecode))
15296 (nth 2 tl)
15297 (or (< (nth 2 tl) (nth 2 nowdecode))
15298 (and (= (nth 2 tl) (nth 2 nowdecode))
15299 (nth 1 tl)
15300 (< (nth 1 tl) (nth 1 nowdecode)))))
15301 (setq day (1+ day)
15302 futurep t))
15303
15304 ;; Special date definitions below
15305 (cond
15306 (iso-week
15307 ;; There was an iso week
15308 (require 'cal-iso)
15309 (setq futurep nil)
15310 (setq year (or iso-year year)
15311 day (or iso-weekday wday 1)
15312 wday nil ; to make sure that the trigger below does not match
15313 iso-date (calendar-gregorian-from-absolute
15314 (calendar-absolute-from-iso
15315 (list iso-week day year))))
15316 ; FIXME: Should we also push ISO weeks into the future?
15317 ; (when (and org-read-date-prefer-future
15318 ; (not iso-year)
15319 ; (< (calendar-absolute-from-gregorian iso-date)
15320 ; (time-to-days (current-time))))
15321 ; (setq year (1+ year)
15322 ; iso-date (calendar-gregorian-from-absolute
15323 ; (calendar-absolute-from-iso
15324 ; (list iso-week day year)))))
15325 (setq month (car iso-date)
15326 year (nth 2 iso-date)
15327 day (nth 1 iso-date)))
15328 (deltan
15329 (setq futurep nil)
15330 (unless deltadef
15331 (let ((now (decode-time (current-time))))
15332 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15333 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15334 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15335 ((equal deltaw "m") (setq month (+ month deltan)))
15336 ((equal deltaw "y") (setq year (+ year deltan)))))
15337 ((and wday (not (nth 3 tl)))
15338 (setq futurep nil)
15339 ;; Weekday was given, but no day, so pick that day in the week
15340 ;; on or after the derived date.
15341 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15342 (unless (equal wday wday1)
15343 (setq day (+ day (% (- wday wday1 -7) 7))))))
15344 (if (and (boundp 'org-time-was-given)
15345 (nth 2 tl))
15346 (setq org-time-was-given t))
15347 (if (< year 100) (setq year (+ 2000 year)))
15348 ;; Check of the date is representable
15349 (if org-read-date-force-compatible-dates
15350 (progn
15351 (if (< year 1970)
15352 (setq year 1970 org-read-date-analyze-forced-year t))
15353 (if (> year 2037)
15354 (setq year 2037 org-read-date-analyze-forced-year t)))
15355 (condition-case nil
15356 (ignore (encode-time second minute hour day month year))
15357 (error
15358 (setq year (nth 5 org-defdecode))
15359 (setq org-read-date-analyze-forced-year t))))
15360 (setq org-read-date-analyze-futurep futurep)
15361 (list second minute hour day month year)))
15362
15363 (defvar parse-time-weekdays)
15364 (defun org-read-date-get-relative (s today default)
15365 "Check string S for special relative date string.
15366 TODAY and DEFAULT are internal times, for today and for a default.
15367 Return shift list (N what def-flag)
15368 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15369 N is the number of WHATs to shift.
15370 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15371 the DEFAULT date rather than TODAY."
15372 (require 'parse-time)
15373 (when (and
15374 (string-match
15375 (concat
15376 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15377 "\\([0-9]+\\)?"
15378 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15379 "\\([ \t]\\|$\\)") s)
15380 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15381 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15382 (string-to-char (substring (match-string 1 s) -1))
15383 ?+))
15384 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15385 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15386 (what (if (match-end 3) (match-string 3 s) "d"))
15387 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15388 (date (if rel default today))
15389 (wday (nth 6 (decode-time date)))
15390 delta)
15391 (if wday1
15392 (progn
15393 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15394 (if (= dir ?-) (setq delta (- delta 7)))
15395 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15396 (list delta "d" rel))
15397 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15398
15399 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15400 "Turn a user-specified date into the internal representation.
15401 The internal representation needed by the calendar is (month day year).
15402 This is a wrapper to handle the brain-dead convention in calendar that
15403 user function argument order change dependent on argument order."
15404 (if (boundp 'calendar-date-style)
15405 (cond
15406 ((eq calendar-date-style 'american)
15407 (list arg1 arg2 arg3))
15408 ((eq calendar-date-style 'european)
15409 (list arg2 arg1 arg3))
15410 ((eq calendar-date-style 'iso)
15411 (list arg2 arg3 arg1)))
15412 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15413 (if (org-bound-and-true-p european-calendar-style)
15414 (list arg2 arg1 arg3)
15415 (list arg1 arg2 arg3)))))
15416
15417 (defun org-eval-in-calendar (form &optional keepdate)
15418 "Eval FORM in the calendar window and return to current window.
15419 Also, store the cursor date in variable org-ans2."
15420 (let ((sf (selected-frame))
15421 (sw (selected-window)))
15422 (select-window (get-buffer-window "*Calendar*" t))
15423 (eval form)
15424 (when (and (not keepdate) (calendar-cursor-to-date))
15425 (let* ((date (calendar-cursor-to-date))
15426 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15427 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15428 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15429 (select-window sw)
15430 (org-select-frame-set-input-focus sf)))
15431
15432 (defun org-calendar-select ()
15433 "Return to `org-read-date' with the date currently selected.
15434 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15435 (interactive)
15436 (when (calendar-cursor-to-date)
15437 (let* ((date (calendar-cursor-to-date))
15438 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15439 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15440 (if (active-minibuffer-window) (exit-minibuffer))))
15441
15442 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15443 "Insert a date stamp for the date given by the internal TIME.
15444 WITH-HM means use the stamp format that includes the time of the day.
15445 INACTIVE means use square brackets instead of angular ones, so that the
15446 stamp will not contribute to the agenda.
15447 PRE and POST are optional strings to be inserted before and after the
15448 stamp.
15449 The command returns the inserted time stamp."
15450 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15451 stamp)
15452 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15453 (insert-before-markers (or pre ""))
15454 (when (listp extra)
15455 (setq extra (car extra))
15456 (if (and (stringp extra)
15457 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15458 (setq extra (format "-%02d:%02d"
15459 (string-to-number (match-string 1 extra))
15460 (string-to-number (match-string 2 extra))))
15461 (setq extra nil)))
15462 (when extra
15463 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15464 (insert-before-markers (setq stamp (format-time-string fmt time)))
15465 (insert-before-markers (or post ""))
15466 (setq org-last-inserted-timestamp stamp)))
15467
15468 (defun org-toggle-time-stamp-overlays ()
15469 "Toggle the use of custom time stamp formats."
15470 (interactive)
15471 (setq org-display-custom-times (not org-display-custom-times))
15472 (unless org-display-custom-times
15473 (let ((p (point-min)) (bmp (buffer-modified-p)))
15474 (while (setq p (next-single-property-change p 'display))
15475 (if (and (get-text-property p 'display)
15476 (eq (get-text-property p 'face) 'org-date))
15477 (remove-text-properties
15478 p (setq p (next-single-property-change p 'display))
15479 '(display t))))
15480 (set-buffer-modified-p bmp)))
15481 (if (featurep 'xemacs)
15482 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15483 (org-restart-font-lock)
15484 (setq org-table-may-need-update t)
15485 (if org-display-custom-times
15486 (message "Time stamps are overlaid with custom format")
15487 (message "Time stamp overlays removed")))
15488
15489 (defun org-display-custom-time (beg end)
15490 "Overlay modified time stamp format over timestamp between BEG and END."
15491 (let* ((ts (buffer-substring beg end))
15492 t1 w1 with-hm tf time str w2 (off 0))
15493 (save-match-data
15494 (setq t1 (org-parse-time-string ts t))
15495 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15496 (setq off (- (match-end 0) (match-beginning 0)))))
15497 (setq end (- end off))
15498 (setq w1 (- end beg)
15499 with-hm (and (nth 1 t1) (nth 2 t1))
15500 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15501 time (org-fix-decoded-time t1)
15502 str (org-add-props
15503 (format-time-string
15504 (substring tf 1 -1) (apply 'encode-time time))
15505 nil 'mouse-face 'highlight)
15506 w2 (length str))
15507 (if (not (= w2 w1))
15508 (add-text-properties (1+ beg) (+ 2 beg)
15509 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15510 (if (featurep 'xemacs)
15511 (progn
15512 (put-text-property beg end 'invisible t)
15513 (put-text-property beg end 'end-glyph (make-glyph str)))
15514 (put-text-property beg end 'display str))))
15515
15516 (defun org-translate-time (string)
15517 "Translate all timestamps in STRING to custom format.
15518 But do this only if the variable `org-display-custom-times' is set."
15519 (when org-display-custom-times
15520 (save-match-data
15521 (let* ((start 0)
15522 (re org-ts-regexp-both)
15523 t1 with-hm inactive tf time str beg end)
15524 (while (setq start (string-match re string start))
15525 (setq beg (match-beginning 0)
15526 end (match-end 0)
15527 t1 (save-match-data
15528 (org-parse-time-string (substring string beg end) t))
15529 with-hm (and (nth 1 t1) (nth 2 t1))
15530 inactive (equal (substring string beg (1+ beg)) "[")
15531 tf (funcall (if with-hm 'cdr 'car)
15532 org-time-stamp-custom-formats)
15533 time (org-fix-decoded-time t1)
15534 str (format-time-string
15535 (concat
15536 (if inactive "[" "<") (substring tf 1 -1)
15537 (if inactive "]" ">"))
15538 (apply 'encode-time time))
15539 string (replace-match str t t string)
15540 start (+ start (length str)))))))
15541 string)
15542
15543 (defun org-fix-decoded-time (time)
15544 "Set 0 instead of nil for the first 6 elements of time.
15545 Don't touch the rest."
15546 (let ((n 0))
15547 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15548
15549 (defun org-days-to-time (timestamp-string)
15550 "Difference between TIMESTAMP-STRING and now in days."
15551 (- (time-to-days (org-time-string-to-time timestamp-string))
15552 (time-to-days (current-time))))
15553
15554 (defun org-deadline-close (timestamp-string &optional ndays)
15555 "Is the time in TIMESTAMP-STRING close to the current date?"
15556 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15557 (and (< (org-days-to-time timestamp-string) ndays)
15558 (not (org-entry-is-done-p))))
15559
15560 (defun org-get-wdays (ts)
15561 "Get the deadline lead time appropriate for timestring TS."
15562 (cond
15563 ((<= org-deadline-warning-days 0)
15564 ;; 0 or negative, enforce this value no matter what
15565 (- org-deadline-warning-days))
15566 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15567 ;; lead time is specified.
15568 (floor (* (string-to-number (match-string 1 ts))
15569 (cdr (assoc (match-string 2 ts)
15570 '(("d" . 1) ("w" . 7)
15571 ("m" . 30.4) ("y" . 365.25)))))))
15572 ;; go for the default.
15573 (t org-deadline-warning-days)))
15574
15575 (defun org-calendar-select-mouse (ev)
15576 "Return to `org-read-date' with the date currently selected.
15577 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15578 (interactive "e")
15579 (mouse-set-point ev)
15580 (when (calendar-cursor-to-date)
15581 (let* ((date (calendar-cursor-to-date))
15582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15583 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15584 (if (active-minibuffer-window) (exit-minibuffer))))
15585
15586 (defun org-check-deadlines (ndays)
15587 "Check if there are any deadlines due or past due.
15588 A deadline is considered due if it happens within `org-deadline-warning-days'
15589 days from today's date. If the deadline appears in an entry marked DONE,
15590 it is not shown. The prefix arg NDAYS can be used to test that many
15591 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15592 (interactive "P")
15593 (let* ((org-warn-days
15594 (cond
15595 ((equal ndays '(4)) 100000)
15596 (ndays (prefix-numeric-value ndays))
15597 (t (abs org-deadline-warning-days))))
15598 (case-fold-search nil)
15599 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15600 (callback
15601 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15602
15603 (message "%d deadlines past-due or due within %d days"
15604 (org-occur regexp nil callback)
15605 org-warn-days)))
15606
15607 (defun org-check-before-date (date)
15608 "Check if there are deadlines or scheduled entries before DATE."
15609 (interactive (list (org-read-date)))
15610 (let ((case-fold-search nil)
15611 (regexp (concat "\\<\\(" org-deadline-string
15612 "\\|" org-scheduled-string
15613 "\\) *<\\([^>]+\\)>"))
15614 (callback
15615 (lambda () (time-less-p
15616 (org-time-string-to-time (match-string 2))
15617 (org-time-string-to-time date)))))
15618 (message "%d entries before %s"
15619 (org-occur regexp nil callback) date)))
15620
15621 (defun org-check-after-date (date)
15622 "Check if there are deadlines or scheduled entries after DATE."
15623 (interactive (list (org-read-date)))
15624 (let ((case-fold-search nil)
15625 (regexp (concat "\\<\\(" org-deadline-string
15626 "\\|" org-scheduled-string
15627 "\\) *<\\([^>]+\\)>"))
15628 (callback
15629 (lambda () (not
15630 (time-less-p
15631 (org-time-string-to-time (match-string 2))
15632 (org-time-string-to-time date))))))
15633 (message "%d entries after %s"
15634 (org-occur regexp nil callback) date)))
15635
15636 (defun org-check-dates-range (start-date end-date)
15637 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15638 (interactive (list (org-read-date nil nil nil "Range starts")
15639 (org-read-date nil nil nil "Range end")))
15640 (let ((case-fold-search nil)
15641 (regexp (concat "\\<\\(" org-deadline-string
15642 "\\|" org-scheduled-string
15643 "\\) *<\\([^>]+\\)>"))
15644 (callback
15645 (lambda ()
15646 (let ((match (match-string 2)))
15647 (and
15648 (not (time-less-p
15649 (org-time-string-to-time match)
15650 (org-time-string-to-time start-date)))
15651 (time-less-p
15652 (org-time-string-to-time match)
15653 (org-time-string-to-time end-date)))))))
15654 (message "%d entries between %s and %s"
15655 (org-occur regexp nil callback) start-date end-date)))
15656
15657 (defun org-evaluate-time-range (&optional to-buffer)
15658 "Evaluate a time range by computing the difference between start and end.
15659 Normally the result is just printed in the echo area, but with prefix arg
15660 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15661 If the time range is actually in a table, the result is inserted into the
15662 next column.
15663 For time difference computation, a year is assumed to be exactly 365
15664 days in order to avoid rounding problems."
15665 (interactive "P")
15666 (or
15667 (org-clock-update-time-maybe)
15668 (save-excursion
15669 (unless (org-at-date-range-p t)
15670 (goto-char (point-at-bol))
15671 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15672 (if (not (org-at-date-range-p t))
15673 (error "Not at a time-stamp range, and none found in current line")))
15674 (let* ((ts1 (match-string 1))
15675 (ts2 (match-string 2))
15676 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15677 (match-end (match-end 0))
15678 (time1 (org-time-string-to-time ts1))
15679 (time2 (org-time-string-to-time ts2))
15680 (t1 (org-float-time time1))
15681 (t2 (org-float-time time2))
15682 (diff (abs (- t2 t1)))
15683 (negative (< (- t2 t1) 0))
15684 ;; (ys (floor (* 365 24 60 60)))
15685 (ds (* 24 60 60))
15686 (hs (* 60 60))
15687 (fy "%dy %dd %02d:%02d")
15688 (fy1 "%dy %dd")
15689 (fd "%dd %02d:%02d")
15690 (fd1 "%dd")
15691 (fh "%02d:%02d")
15692 y d h m align)
15693 (if havetime
15694 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15695 y 0
15696 d (floor (/ diff ds)) diff (mod diff ds)
15697 h (floor (/ diff hs)) diff (mod diff hs)
15698 m (floor (/ diff 60)))
15699 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15700 y 0
15701 d (floor (+ (/ diff ds) 0.5))
15702 h 0 m 0))
15703 (if (not to-buffer)
15704 (message "%s" (org-make-tdiff-string y d h m))
15705 (if (org-at-table-p)
15706 (progn
15707 (goto-char match-end)
15708 (setq align t)
15709 (and (looking-at " *|") (goto-char (match-end 0))))
15710 (goto-char match-end))
15711 (if (looking-at
15712 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15713 (replace-match ""))
15714 (if negative (insert " -"))
15715 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15716 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15717 (insert " " (format fh h m))))
15718 (if align (org-table-align))
15719 (message "Time difference inserted")))))
15720
15721 (defun org-make-tdiff-string (y d h m)
15722 (let ((fmt "")
15723 (l nil))
15724 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15725 l (push y l)))
15726 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15727 l (push d l)))
15728 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15729 l (push h l)))
15730 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15731 l (push m l)))
15732 (apply 'format fmt (nreverse l))))
15733
15734 (defun org-time-string-to-time (s &optional buffer pos)
15735 (condition-case errdata
15736 (apply 'encode-time (org-parse-time-string s))
15737 (error (error "Bad timestamp `%s'%s\nError was: %s"
15738 s (if (not (and buffer pos))
15739 ""
15740 (format " at %d in buffer `%s'" pos buffer))
15741 (cdr errdata)))))
15742
15743 (defun org-time-string-to-seconds (s)
15744 (org-float-time (org-time-string-to-time s)))
15745
15746 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15747 "Convert a time stamp to an absolute day number.
15748 If there is a specifier for a cyclic time stamp, get the closest date to
15749 DAYNR.
15750 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15751 The variable date is bound by the calendar when this is called."
15752 (cond
15753 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15754 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15755 daynr
15756 (+ daynr 1000)))
15757 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15758 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15759 (time-to-days (current-time))) (match-string 0 s)
15760 prefer show-all))
15761 (t (time-to-days
15762 (condition-case errdata
15763 (apply 'encode-time (org-parse-time-string s))
15764 (error (error "Bad timestamp `%s'%s\nError was: %s"
15765 s (if (not (and buffer pos))
15766 ""
15767 (format " at %d in buffer `%s'" pos buffer))
15768 (cdr errdata))))))))
15769
15770 (defun org-days-to-iso-week (days)
15771 "Return the iso week number."
15772 (require 'cal-iso)
15773 (car (calendar-iso-from-absolute days)))
15774
15775 (defun org-small-year-to-year (year)
15776 "Convert 2-digit years into 4-digit years.
15777 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15778 The year 2000 cannot be abbreviated. Any year larger than 99
15779 is returned unchanged."
15780 (if (< year 38)
15781 (setq year (+ 2000 year))
15782 (if (< year 100)
15783 (setq year (+ 1900 year))))
15784 year)
15785
15786 (defun org-time-from-absolute (d)
15787 "Return the time corresponding to date D.
15788 D may be an absolute day number, or a calendar-type list (month day year)."
15789 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15790 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15791
15792 (defun org-calendar-holiday ()
15793 "List of holidays, for Diary display in Org-mode."
15794 (require 'holidays)
15795 (let ((hl (funcall
15796 (if (fboundp 'calendar-check-holidays)
15797 'calendar-check-holidays 'check-calendar-holidays) date)))
15798 (if hl (mapconcat 'identity hl "; "))))
15799
15800 (defun org-diary-sexp-entry (sexp entry date)
15801 "Process a SEXP diary ENTRY for DATE."
15802 (require 'diary-lib)
15803 (let ((result (if calendar-debug-sexp
15804 (let ((stack-trace-on-error t))
15805 (eval (car (read-from-string sexp))))
15806 (condition-case nil
15807 (eval (car (read-from-string sexp)))
15808 (error
15809 (beep)
15810 (message "Bad sexp at line %d in %s: %s"
15811 (org-current-line)
15812 (buffer-file-name) sexp)
15813 (sleep-for 2))))))
15814 (cond ((stringp result) (split-string result "; "))
15815 ((and (consp result)
15816 (not (consp (cdr result)))
15817 (stringp (cdr result))) (cdr result))
15818 ((and (consp result)
15819 (stringp (car result))) result)
15820 (result entry)
15821 (t nil))))
15822
15823 (defun org-diary-to-ical-string (frombuf)
15824 "Get iCalendar entries from diary entries in buffer FROMBUF.
15825 This uses the icalendar.el library."
15826 (let* ((tmpdir (if (featurep 'xemacs)
15827 (temp-directory)
15828 temporary-file-directory))
15829 (tmpfile (make-temp-name
15830 (expand-file-name "orgics" tmpdir)))
15831 buf rtn b e)
15832 (with-current-buffer frombuf
15833 (icalendar-export-region (point-min) (point-max) tmpfile)
15834 (setq buf (find-buffer-visiting tmpfile))
15835 (set-buffer buf)
15836 (goto-char (point-min))
15837 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15838 (setq b (match-beginning 0)))
15839 (goto-char (point-max))
15840 (if (re-search-backward "^END:VEVENT" nil t)
15841 (setq e (match-end 0)))
15842 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15843 (kill-buffer buf)
15844 (delete-file tmpfile)
15845 rtn))
15846
15847 (defun org-closest-date (start current change prefer show-all)
15848 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15849 When PREFER is `past', return a date that is either CURRENT or past.
15850 When PREFER is `future', return a date that is either CURRENT or future.
15851 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15852 ;; Make the proper lists from the dates
15853 (catch 'exit
15854 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15855 dn dw sday cday n1 n2 n0
15856 d m y y1 y2 date1 date2 nmonths nm ny m2)
15857
15858 (setq start (org-date-to-gregorian start)
15859 current (org-date-to-gregorian
15860 (if show-all
15861 current
15862 (time-to-days (current-time))))
15863 sday (calendar-absolute-from-gregorian start)
15864 cday (calendar-absolute-from-gregorian current))
15865
15866 (if (<= cday sday) (throw 'exit sday))
15867
15868 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15869 (setq dn (string-to-number (match-string 1 change))
15870 dw (cdr (assoc (match-string 2 change) a1)))
15871 (error "Invalid change specifier: %s" change))
15872 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15873 (cond
15874 ((eq dw 'day)
15875 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15876 n2 (+ n1 dn)))
15877 ((eq dw 'year)
15878 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15879 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15880 (setq date1 (list m d y1)
15881 n1 (calendar-absolute-from-gregorian date1)
15882 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15883 n2 (calendar-absolute-from-gregorian date2)))
15884 ((eq dw 'month)
15885 ;; approx number of month between the two dates
15886 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15887 ;; How often does dn fit in there?
15888 (setq d (nth 1 start) m (car start) y (nth 2 start)
15889 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15890 m (+ m nm)
15891 ny (floor (/ m 12))
15892 y (+ y ny)
15893 m (- m (* ny 12)))
15894 (while (> m 12) (setq m (- m 12) y (1+ y)))
15895 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15896 (setq m2 (+ m dn) y2 y)
15897 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15898 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15899 (while (<= n2 cday)
15900 (setq n1 n2 m m2 y y2)
15901 (setq m2 (+ m dn) y2 y)
15902 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15903 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15904 ;; Make sure n1 is the earlier date
15905 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15906 (if show-all
15907 (cond
15908 ((eq prefer 'past) (if (= cday n2) n2 n1))
15909 ((eq prefer 'future) (if (= cday n1) n1 n2))
15910 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15911 (cond
15912 ((eq prefer 'past) (if (= cday n2) n2 n1))
15913 ((eq prefer 'future) (if (= cday n1) n1 n2))
15914 (t (if (= cday n1) n1 n2)))))))
15915
15916 (defun org-date-to-gregorian (date)
15917 "Turn any specification of DATE into a Gregorian date for the calendar."
15918 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15919 ((and (listp date) (= (length date) 3)) date)
15920 ((stringp date)
15921 (setq date (org-parse-time-string date))
15922 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15923 ((listp date)
15924 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15925
15926 (defun org-parse-time-string (s &optional nodefault)
15927 "Parse the standard Org-mode time string.
15928 This should be a lot faster than the normal `parse-time-string'.
15929 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15930 hour and minute fields will be nil if not given."
15931 (if (string-match org-ts-regexp0 s)
15932 (list 0
15933 (if (or (match-beginning 8) (not nodefault))
15934 (string-to-number (or (match-string 8 s) "0")))
15935 (if (or (match-beginning 7) (not nodefault))
15936 (string-to-number (or (match-string 7 s) "0")))
15937 (string-to-number (match-string 4 s))
15938 (string-to-number (match-string 3 s))
15939 (string-to-number (match-string 2 s))
15940 nil nil nil)
15941 (error "Not a standard Org-mode time string: %s" s)))
15942
15943 (defun org-timestamp-up (&optional arg)
15944 "Increase the date item at the cursor by one.
15945 If the cursor is on the year, change the year. If it is on the month,
15946 the day or the time, change that.
15947 With prefix ARG, change by that many units."
15948 (interactive "p")
15949 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15950
15951 (defun org-timestamp-down (&optional arg)
15952 "Decrease the date item at the cursor by one.
15953 If the cursor is on the year, change the year. If it is on the month,
15954 the day or the time, change that.
15955 With prefix ARG, change by that many units."
15956 (interactive "p")
15957 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15958
15959 (defun org-timestamp-up-day (&optional arg)
15960 "Increase the date in the time stamp by one day.
15961 With prefix ARG, change that many days."
15962 (interactive "p")
15963 (if (and (not (org-at-timestamp-p t))
15964 (org-at-heading-p))
15965 (org-todo 'up)
15966 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15967
15968 (defun org-timestamp-down-day (&optional arg)
15969 "Decrease the date in the time stamp by one day.
15970 With prefix ARG, change that many days."
15971 (interactive "p")
15972 (if (and (not (org-at-timestamp-p t))
15973 (org-at-heading-p))
15974 (org-todo 'down)
15975 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15976
15977 (defun org-at-timestamp-p (&optional inactive-ok)
15978 "Determine if the cursor is in or at a timestamp."
15979 (interactive)
15980 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15981 (pos (point))
15982 (ans (or (looking-at tsr)
15983 (save-excursion
15984 (skip-chars-backward "^[<\n\r\t")
15985 (if (> (point) (point-min)) (backward-char 1))
15986 (and (looking-at tsr)
15987 (> (- (match-end 0) pos) -1))))))
15988 (and ans
15989 (boundp 'org-ts-what)
15990 (setq org-ts-what
15991 (cond
15992 ((= pos (match-beginning 0)) 'bracket)
15993 ;; Point is considered to be "on the bracket" whether
15994 ;; it's really on it or right after it.
15995 ((or (= pos (1- (match-end 0)))
15996 (= pos (match-end 0))) 'bracket)
15997 ((org-pos-in-match-range pos 2) 'year)
15998 ((org-pos-in-match-range pos 3) 'month)
15999 ((org-pos-in-match-range pos 7) 'hour)
16000 ((org-pos-in-match-range pos 8) 'minute)
16001 ((or (org-pos-in-match-range pos 4)
16002 (org-pos-in-match-range pos 5)) 'day)
16003 ((and (> pos (or (match-end 8) (match-end 5)))
16004 (< pos (match-end 0)))
16005 (- pos (or (match-end 8) (match-end 5))))
16006 (t 'day))))
16007 ans))
16008
16009 (defun org-toggle-timestamp-type ()
16010 "Toggle the type (<active> or [inactive]) of a time stamp."
16011 (interactive)
16012 (when (org-at-timestamp-p t)
16013 (let ((beg (match-beginning 0)) (end (match-end 0))
16014 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16015 (save-excursion
16016 (goto-char beg)
16017 (while (re-search-forward "[][<>]" end t)
16018 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16019 t t)))
16020 (message "Timestamp is now %sactive"
16021 (if (equal (char-after beg) ?<) "" "in")))))
16022
16023 (defun org-timestamp-change (n &optional what updown)
16024 "Change the date in the time stamp at point.
16025 The date will be changed by N times WHAT. WHAT can be `day', `month',
16026 `year', `minute', `second'. If WHAT is not given, the cursor position
16027 in the timestamp determines what will be changed."
16028 (let ((origin (point)) origin-cat
16029 with-hm inactive
16030 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16031 org-ts-what
16032 extra rem
16033 ts time time0)
16034 (if (not (org-at-timestamp-p t))
16035 (error "Not at a timestamp"))
16036 (if (and (not what) (eq org-ts-what 'bracket))
16037 (org-toggle-timestamp-type)
16038 ;; Point isn't on brackets. Remember the part of the time-stamp
16039 ;; the point was in. Indeed, size of time-stamps may change,
16040 ;; but point must be kept in the same category nonetheless.
16041 (setq origin-cat org-ts-what)
16042 (if (and (not what) (not (eq org-ts-what 'day))
16043 org-display-custom-times
16044 (get-text-property (point) 'display)
16045 (not (get-text-property (1- (point)) 'display)))
16046 (setq org-ts-what 'day))
16047 (setq org-ts-what (or what org-ts-what)
16048 inactive (= (char-after (match-beginning 0)) ?\[)
16049 ts (match-string 0))
16050 (replace-match "")
16051 (if (string-match
16052 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16053 ts)
16054 (setq extra (match-string 1 ts)))
16055 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16056 (setq with-hm t))
16057 (setq time0 (org-parse-time-string ts))
16058 (when (and updown
16059 (eq org-ts-what 'minute)
16060 (not current-prefix-arg))
16061 ;; This looks like s-up and s-down. Change by one rounding step.
16062 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16063 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16064 (setcar (cdr time0) (+ (nth 1 time0)
16065 (if (> n 0) (- rem) (- dm rem))))))
16066 (setq time
16067 (encode-time (or (car time0) 0)
16068 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16069 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16070 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16071 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16072 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16073 (nthcdr 6 time0)))
16074 (when (and (member org-ts-what '(hour minute))
16075 extra
16076 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16077 (setq extra (org-modify-ts-extra
16078 extra
16079 (if (eq org-ts-what 'hour) 2 5)
16080 n dm)))
16081 (when (integerp org-ts-what)
16082 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16083 (if (eq what 'calendar)
16084 (let ((cal-date (org-get-date-from-calendar)))
16085 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16086 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16087 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16088 (setcar time0 (or (car time0) 0))
16089 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16090 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16091 (setq time (apply 'encode-time time0))))
16092 ;; Insert the new time-stamp, and ensure point stays in the same
16093 ;; category as before (i.e. not after the last position in that
16094 ;; category).
16095 (let ((pos (point)))
16096 ;; Stay before inserted string. `save-excursion' is of no use.
16097 (setq org-last-changed-timestamp
16098 (org-insert-time-stamp time with-hm inactive nil nil extra))
16099 (goto-char pos))
16100 (save-match-data
16101 (looking-at org-ts-regexp3)
16102 (goto-char (cond
16103 ;; `day' category ends before `hour' if any, or at
16104 ;; the end of the day name.
16105 ((eq origin-cat 'day)
16106 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16107 ((eq origin-cat 'hour) (min (match-end 7) origin))
16108 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16109 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16110 ;; `year' and `month' have both fixed size: point
16111 ;; couldn't have moved into another part.
16112 (t origin))))
16113 ;; Update clock if on a CLOCK line.
16114 (org-clock-update-time-maybe)
16115 ;; Try to recenter the calendar window, if any.
16116 (if (and org-calendar-follow-timestamp-change
16117 (get-buffer-window "*Calendar*" t)
16118 (memq org-ts-what '(day month year)))
16119 (org-recenter-calendar (time-to-days time))))))
16120
16121 (defun org-modify-ts-extra (s pos n dm)
16122 "Change the different parts of the lead-time and repeat fields in timestamp."
16123 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16124 ng h m new rem)
16125 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16126 (cond
16127 ((or (org-pos-in-match-range pos 2)
16128 (org-pos-in-match-range pos 3))
16129 (setq m (string-to-number (match-string 3 s))
16130 h (string-to-number (match-string 2 s)))
16131 (if (org-pos-in-match-range pos 2)
16132 (setq h (+ h n))
16133 (setq n (* dm (org-no-warnings (signum n))))
16134 (when (not (= 0 (setq rem (% m dm))))
16135 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16136 (setq m (+ m n)))
16137 (if (< m 0) (setq m (+ m 60) h (1- h)))
16138 (if (> m 59) (setq m (- m 60) h (1+ h)))
16139 (setq h (min 24 (max 0 h)))
16140 (setq ng 1 new (format "-%02d:%02d" h m)))
16141 ((org-pos-in-match-range pos 6)
16142 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16143 ((org-pos-in-match-range pos 5)
16144 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16145
16146 ((org-pos-in-match-range pos 9)
16147 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16148 ((org-pos-in-match-range pos 8)
16149 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16150
16151 (when ng
16152 (setq s (concat
16153 (substring s 0 (match-beginning ng))
16154 new
16155 (substring s (match-end ng))))))
16156 s))
16157
16158 (defun org-recenter-calendar (date)
16159 "If the calendar is visible, recenter it to DATE."
16160 (let ((cwin (get-buffer-window "*Calendar*" t)))
16161 (when cwin
16162 (let ((calendar-move-hook nil))
16163 (with-selected-window cwin
16164 (calendar-goto-date (if (listp date) date
16165 (calendar-gregorian-from-absolute date))))))))
16166
16167 (defun org-goto-calendar (&optional arg)
16168 "Go to the Emacs calendar at the current date.
16169 If there is a time stamp in the current line, go to that date.
16170 A prefix ARG can be used to force the current date."
16171 (interactive "P")
16172 (let ((tsr org-ts-regexp) diff
16173 (calendar-move-hook nil)
16174 (calendar-view-holidays-initially-flag nil)
16175 (calendar-view-diary-initially-flag nil))
16176 (if (or (org-at-timestamp-p)
16177 (save-excursion
16178 (beginning-of-line 1)
16179 (looking-at (concat ".*" tsr))))
16180 (let ((d1 (time-to-days (current-time)))
16181 (d2 (time-to-days
16182 (org-time-string-to-time (match-string 1)))))
16183 (setq diff (- d2 d1))))
16184 (calendar)
16185 (calendar-goto-today)
16186 (if (and diff (not arg)) (calendar-forward-day diff))))
16187
16188 (defun org-get-date-from-calendar ()
16189 "Return a list (month day year) of date at point in calendar."
16190 (with-current-buffer "*Calendar*"
16191 (save-match-data
16192 (calendar-cursor-to-date))))
16193
16194 (defun org-date-from-calendar ()
16195 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16196 If there is already a time stamp at the cursor position, update it."
16197 (interactive)
16198 (if (org-at-timestamp-p t)
16199 (org-timestamp-change 0 'calendar)
16200 (let ((cal-date (org-get-date-from-calendar)))
16201 (org-insert-time-stamp
16202 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16203
16204 (defun org-minutes-to-hh:mm-string (m)
16205 "Compute H:MM from a number of minutes."
16206 (let ((h (/ m 60)))
16207 (setq m (- m (* 60 h)))
16208 (format org-time-clocksum-format h m)))
16209
16210 (defun org-hh:mm-string-to-minutes (s)
16211 "Convert a string H:MM to a number of minutes.
16212 If the string is just a number, interpret it as minutes.
16213 In fact, the first hh:mm or number in the string will be taken,
16214 there can be extra stuff in the string.
16215 If no number is found, the return value is 0."
16216 (cond
16217 ((integerp s) s)
16218 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16219 (+ (* (string-to-number (match-string 1 s)) 60)
16220 (string-to-number (match-string 2 s))))
16221 ((string-match "\\([0-9]+\\)" s)
16222 (string-to-number (match-string 1 s)))
16223 (t 0)))
16224
16225 (defcustom org-effort-durations
16226 `(("h" . 60)
16227 ("d" . ,(* 60 8))
16228 ("w" . ,(* 60 8 5))
16229 ("m" . ,(* 60 8 5 4))
16230 ("y" . ,(* 60 8 5 40)))
16231 "Conversion factor to minutes for an effort modifier.
16232
16233 Each entry has the form (MODIFIER . MINUTES).
16234
16235 In an effort string, a number followed by MODIFIER is multiplied
16236 by the specified number of MINUTES to obtain an effort in
16237 minutes.
16238
16239 For example, if the value of this variable is ((\"hours\" . 60)), then an
16240 effort string \"2hours\" is equivalent to 120 minutes."
16241 :group 'org-agenda
16242 :version "24.1"
16243 :type '(alist :key-type (string :tag "Modifier")
16244 :value-type (number :tag "Minutes")))
16245
16246 (defun org-duration-string-to-minutes (s)
16247 "Convert a duration string S to minutes.
16248
16249 A bare number is interpreted as minutes, modifiers can be set by
16250 customizing `org-effort-durations' (which see).
16251
16252 Entries containing a colon are interpreted as H:MM by
16253 `org-hh:mm-string-to-minutes'."
16254 (let ((result 0)
16255 (re (concat "\\([0-9]+\\) *\\("
16256 (regexp-opt (mapcar 'car org-effort-durations))
16257 "\\)")))
16258 (while (string-match re s)
16259 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16260 (string-to-number (match-string 1 s))))
16261 (setq s (replace-match "" nil t s)))
16262 (incf result (org-hh:mm-string-to-minutes s))
16263 result))
16264
16265 ;;;; Files
16266
16267 (defun org-save-all-org-buffers ()
16268 "Save all Org-mode buffers without user confirmation."
16269 (interactive)
16270 (message "Saving all Org-mode buffers...")
16271 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16272 (when (featurep 'org-id) (org-id-locations-save))
16273 (message "Saving all Org-mode buffers... done"))
16274
16275 (defun org-revert-all-org-buffers ()
16276 "Revert all Org-mode buffers.
16277 Prompt for confirmation when there are unsaved changes.
16278 Be sure you know what you are doing before letting this function
16279 overwrite your changes.
16280
16281 This function is useful in a setup where one tracks org files
16282 with a version control system, to revert on one machine after pulling
16283 changes from another. I believe the procedure must be like this:
16284
16285 1. M-x org-save-all-org-buffers
16286 2. Pull changes from the other machine, resolve conflicts
16287 3. M-x org-revert-all-org-buffers"
16288 (interactive)
16289 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16290 (error "Abort"))
16291 (save-excursion
16292 (save-window-excursion
16293 (mapc
16294 (lambda (b)
16295 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16296 (with-current-buffer b buffer-file-name))
16297 (org-pop-to-buffer-same-window b)
16298 (revert-buffer t 'no-confirm)))
16299 (buffer-list))
16300 (when (and (featurep 'org-id) org-id-track-globally)
16301 (org-id-locations-load)))))
16302
16303 ;;;; Agenda files
16304
16305 ;;;###autoload
16306 (defun org-switchb (&optional arg)
16307 "Switch between Org buffers.
16308 With one prefix argument, restrict available buffers to files.
16309 With two prefix arguments, restrict available buffers to agenda files.
16310
16311 Defaults to `iswitchb' for buffer name completion.
16312 Set `org-completion-use-ido' to make it use ido instead."
16313 (interactive "P")
16314 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16315 ((equal arg '(16)) (org-buffer-list 'agenda))
16316 (t (org-buffer-list))))
16317 (org-completion-use-iswitchb org-completion-use-iswitchb)
16318 (org-completion-use-ido org-completion-use-ido))
16319 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16320 (setq org-completion-use-iswitchb t))
16321 (org-pop-to-buffer-same-window
16322 (org-icompleting-read "Org buffer: "
16323 (mapcar 'list (mapcar 'buffer-name blist))
16324 nil t))))
16325
16326 ;;; Define some older names previously used for this functionality
16327 ;;;###autoload
16328 (defalias 'org-ido-switchb 'org-switchb)
16329 ;;;###autoload
16330 (defalias 'org-iswitchb 'org-switchb)
16331
16332 (defun org-buffer-list (&optional predicate exclude-tmp)
16333 "Return a list of Org buffers.
16334 PREDICATE can be `export', `files' or `agenda'.
16335
16336 export restrict the list to Export buffers.
16337 files restrict the list to buffers visiting Org files.
16338 agenda restrict the list to buffers visiting agenda files.
16339
16340 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16341 (let* ((bfn nil)
16342 (agenda-files (and (eq predicate 'agenda)
16343 (mapcar 'file-truename (org-agenda-files t))))
16344 (filter
16345 (cond
16346 ((eq predicate 'files)
16347 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16348 ((eq predicate 'export)
16349 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16350 ((eq predicate 'agenda)
16351 (lambda (b)
16352 (with-current-buffer b
16353 (and (eq major-mode 'org-mode)
16354 (setq bfn (buffer-file-name b))
16355 (member (file-truename bfn) agenda-files)))))
16356 (t (lambda (b) (with-current-buffer b
16357 (or (eq major-mode 'org-mode)
16358 (string-match "\*Org .*Export"
16359 (buffer-name b)))))))))
16360 (delq nil
16361 (mapcar
16362 (lambda(b)
16363 (if (and (funcall filter b)
16364 (or (not exclude-tmp)
16365 (not (string-match "tmp" (buffer-name b)))))
16366 b
16367 nil))
16368 (buffer-list)))))
16369
16370 (defun org-agenda-files (&optional unrestricted archives)
16371 "Get the list of agenda files.
16372 Optional UNRESTRICTED means return the full list even if a restriction
16373 is currently in place.
16374 When ARCHIVES is t, include all archive files that are really being
16375 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16376 `org-agenda-archives-mode' is t."
16377 (let ((files
16378 (cond
16379 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16380 ((stringp org-agenda-files) (org-read-agenda-file-list))
16381 ((listp org-agenda-files) org-agenda-files)
16382 (t (error "Invalid value of `org-agenda-files'")))))
16383 (setq files (apply 'append
16384 (mapcar (lambda (f)
16385 (if (file-directory-p f)
16386 (directory-files
16387 f t org-agenda-file-regexp)
16388 (list f)))
16389 files)))
16390 (when org-agenda-skip-unavailable-files
16391 (setq files (delq nil
16392 (mapcar (function
16393 (lambda (file)
16394 (and (file-readable-p file) file)))
16395 files))))
16396 (when (or (eq archives t)
16397 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16398 (setq files (org-add-archive-files files)))
16399 files))
16400
16401 (defun org-agenda-file-p (&optional file)
16402 "Return non-nil, if FILE is an agenda file.
16403 If FILE is omitted, use the file associated with the current
16404 buffer."
16405 (member (or file (buffer-file-name))
16406 (org-agenda-files t)))
16407
16408 (defun org-edit-agenda-file-list ()
16409 "Edit the list of agenda files.
16410 Depending on setup, this either uses customize to edit the variable
16411 `org-agenda-files', or it visits the file that is holding the list. In the
16412 latter case, the buffer is set up in a way that saving it automatically kills
16413 the buffer and restores the previous window configuration."
16414 (interactive)
16415 (if (stringp org-agenda-files)
16416 (let ((cw (current-window-configuration)))
16417 (find-file org-agenda-files)
16418 (org-set-local 'org-window-configuration cw)
16419 (org-add-hook 'after-save-hook
16420 (lambda ()
16421 (set-window-configuration
16422 (prog1 org-window-configuration
16423 (kill-buffer (current-buffer))))
16424 (org-install-agenda-files-menu)
16425 (message "New agenda file list installed"))
16426 nil 'local)
16427 (message "%s" (substitute-command-keys
16428 "Edit list and finish with \\[save-buffer]")))
16429 (customize-variable 'org-agenda-files)))
16430
16431 (defun org-store-new-agenda-file-list (list)
16432 "Set new value for the agenda file list and save it correctly."
16433 (if (stringp org-agenda-files)
16434 (let ((fe (org-read-agenda-file-list t)) b u)
16435 (while (setq b (find-buffer-visiting org-agenda-files))
16436 (kill-buffer b))
16437 (with-temp-file org-agenda-files
16438 (insert
16439 (mapconcat
16440 (lambda (f) ;; Keep un-expanded entries.
16441 (if (setq u (assoc f fe))
16442 (cdr u)
16443 f))
16444 list "\n")
16445 "\n")))
16446 (let ((org-mode-hook nil) (org-inhibit-startup t)
16447 (org-insert-mode-line-in-empty-file nil))
16448 (setq org-agenda-files list)
16449 (customize-save-variable 'org-agenda-files org-agenda-files))))
16450
16451 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16452 "Read the list of agenda files from a file.
16453 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16454 filenames, used by `org-store-new-agenda-file-list' to write back
16455 un-expanded file names."
16456 (when (file-directory-p org-agenda-files)
16457 (error "`org-agenda-files' cannot be a single directory"))
16458 (when (stringp org-agenda-files)
16459 (with-temp-buffer
16460 (insert-file-contents org-agenda-files)
16461 (mapcar
16462 (lambda (f)
16463 (let ((e (expand-file-name (substitute-in-file-name f)
16464 org-directory)))
16465 (if pair-with-expansion
16466 (cons e f)
16467 e)))
16468 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16469
16470 ;;;###autoload
16471 (defun org-cycle-agenda-files ()
16472 "Cycle through the files in `org-agenda-files'.
16473 If the current buffer visits an agenda file, find the next one in the list.
16474 If the current buffer does not, find the first agenda file."
16475 (interactive)
16476 (let* ((fs (org-agenda-files t))
16477 (files (append fs (list (car fs))))
16478 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16479 file)
16480 (unless files (error "No agenda files"))
16481 (catch 'exit
16482 (while (setq file (pop files))
16483 (if (equal (file-truename file) tcf)
16484 (when (car files)
16485 (find-file (car files))
16486 (throw 'exit t))))
16487 (find-file (car fs)))
16488 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16489
16490 (defun org-agenda-file-to-front (&optional to-end)
16491 "Move/add the current file to the top of the agenda file list.
16492 If the file is not present in the list, it is added to the front. If it is
16493 present, it is moved there. With optional argument TO-END, add/move to the
16494 end of the list."
16495 (interactive "P")
16496 (let ((org-agenda-skip-unavailable-files nil)
16497 (file-alist (mapcar (lambda (x)
16498 (cons (file-truename x) x))
16499 (org-agenda-files t)))
16500 (ctf (file-truename buffer-file-name))
16501 x had)
16502 (setq x (assoc ctf file-alist) had x)
16503
16504 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16505 (if to-end
16506 (setq file-alist (append (delq x file-alist) (list x)))
16507 (setq file-alist (cons x (delq x file-alist))))
16508 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16509 (org-install-agenda-files-menu)
16510 (message "File %s to %s of agenda file list"
16511 (if had "moved" "added") (if to-end "end" "front"))))
16512
16513 (defun org-remove-file (&optional file)
16514 "Remove current file from the list of files in variable `org-agenda-files'.
16515 These are the files which are being checked for agenda entries.
16516 Optional argument FILE means use this file instead of the current."
16517 (interactive)
16518 (let* ((org-agenda-skip-unavailable-files nil)
16519 (file (or file buffer-file-name))
16520 (true-file (file-truename file))
16521 (afile (abbreviate-file-name file))
16522 (files (delq nil (mapcar
16523 (lambda (x)
16524 (if (equal true-file
16525 (file-truename x))
16526 nil x))
16527 (org-agenda-files t)))))
16528 (if (not (= (length files) (length (org-agenda-files t))))
16529 (progn
16530 (org-store-new-agenda-file-list files)
16531 (org-install-agenda-files-menu)
16532 (message "Removed file: %s" afile))
16533 (message "File was not in list: %s (not removed)" afile))))
16534
16535 (defun org-file-menu-entry (file)
16536 (vector file (list 'find-file file) t))
16537
16538 (defun org-check-agenda-file (file)
16539 "Make sure FILE exists. If not, ask user what to do."
16540 (when (not (file-exists-p file))
16541 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16542 (abbreviate-file-name file))
16543 (let ((r (downcase (read-char-exclusive))))
16544 (cond
16545 ((equal r ?r)
16546 (org-remove-file file)
16547 (throw 'nextfile t))
16548 (t (error "Abort"))))))
16549
16550 (defun org-get-agenda-file-buffer (file)
16551 "Get a buffer visiting FILE. If the buffer needs to be created, add
16552 it to the list of buffers which might be released later."
16553 (let ((buf (org-find-base-buffer-visiting file)))
16554 (if buf
16555 buf ; just return it
16556 ;; Make a new buffer and remember it
16557 (setq buf (find-file-noselect file))
16558 (if buf (push buf org-agenda-new-buffers))
16559 buf)))
16560
16561 (defun org-release-buffers (blist)
16562 "Release all buffers in list, asking the user for confirmation when needed.
16563 When a buffer is unmodified, it is just killed. When modified, it is saved
16564 \(if the user agrees) and then killed."
16565 (let (buf file)
16566 (while (setq buf (pop blist))
16567 (setq file (buffer-file-name buf))
16568 (when (and (buffer-modified-p buf)
16569 file
16570 (y-or-n-p (format "Save file %s? " file)))
16571 (with-current-buffer buf (save-buffer)))
16572 (kill-buffer buf))))
16573
16574 (defun org-prepare-agenda-buffers (files)
16575 "Create buffers for all agenda files, protect archived trees and comments."
16576 (interactive)
16577 (let ((pa '(:org-archived t))
16578 (pc '(:org-comment t))
16579 (pall '(:org-archived t :org-comment t))
16580 (inhibit-read-only t)
16581 (rea (concat ":" org-archive-tag ":"))
16582 bmp file re)
16583 (save-excursion
16584 (save-restriction
16585 (while (setq file (pop files))
16586 (catch 'nextfile
16587 (if (bufferp file)
16588 (set-buffer file)
16589 (org-check-agenda-file file)
16590 (set-buffer (org-get-agenda-file-buffer file)))
16591 (widen)
16592 (setq bmp (buffer-modified-p))
16593 (org-refresh-category-properties)
16594 (setq org-todo-keywords-for-agenda
16595 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16596 (setq org-done-keywords-for-agenda
16597 (append org-done-keywords-for-agenda org-done-keywords))
16598 (setq org-todo-keyword-alist-for-agenda
16599 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16600 (setq org-drawers-for-agenda
16601 (append org-drawers-for-agenda org-drawers))
16602 (setq org-tag-alist-for-agenda
16603 (append org-tag-alist-for-agenda org-tag-alist))
16604
16605 (save-excursion
16606 (remove-text-properties (point-min) (point-max) pall)
16607 (when org-agenda-skip-archived-trees
16608 (goto-char (point-min))
16609 (while (re-search-forward rea nil t)
16610 (if (org-at-heading-p t)
16611 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16612 (goto-char (point-min))
16613 (setq re (format org-heading-keyword-regexp-format
16614 org-comment-string))
16615 (while (re-search-forward re nil t)
16616 (add-text-properties
16617 (match-beginning 0) (org-end-of-subtree t) pc)))
16618 (set-buffer-modified-p bmp)))))
16619 (setq org-todo-keywords-for-agenda
16620 (org-uniquify org-todo-keywords-for-agenda))
16621 (setq org-todo-keyword-alist-for-agenda
16622 (org-uniquify org-todo-keyword-alist-for-agenda)
16623 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16624
16625 ;;;; Embedded LaTeX
16626
16627 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16628 "Keymap for the minor `org-cdlatex-mode'.")
16629
16630 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16631 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16632 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16633 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16634 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16635
16636 (defvar org-cdlatex-texmathp-advice-is-done nil
16637 "Flag remembering if we have applied the advice to texmathp already.")
16638
16639 (define-minor-mode org-cdlatex-mode
16640 "Toggle the minor `org-cdlatex-mode'.
16641 This mode supports entering LaTeX environment and math in LaTeX fragments
16642 in Org-mode.
16643 \\{org-cdlatex-mode-map}"
16644 nil " OCDL" nil
16645 (when org-cdlatex-mode
16646 (require 'cdlatex)
16647 (run-hooks 'cdlatex-mode-hook)
16648 (cdlatex-compute-tables))
16649 (unless org-cdlatex-texmathp-advice-is-done
16650 (setq org-cdlatex-texmathp-advice-is-done t)
16651 (defadvice texmathp (around org-math-always-on activate)
16652 "Always return t in org-mode buffers.
16653 This is because we want to insert math symbols without dollars even outside
16654 the LaTeX math segments. If Orgmode thinks that point is actually inside
16655 an embedded LaTeX fragment, let texmathp do its job.
16656 \\[org-cdlatex-mode-map]"
16657 (interactive)
16658 (let (p)
16659 (cond
16660 ((not (eq major-mode 'org-mode)) ad-do-it)
16661 ((eq this-command 'cdlatex-math-symbol)
16662 (setq ad-return-value t
16663 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16664 (t
16665 (let ((p (org-inside-LaTeX-fragment-p)))
16666 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16667 (setq ad-return-value t
16668 texmathp-why '("Org-mode embedded math" . 0))
16669 (if p ad-do-it)))))))))
16670
16671 (defun turn-on-org-cdlatex ()
16672 "Unconditionally turn on `org-cdlatex-mode'."
16673 (org-cdlatex-mode 1))
16674
16675 (defun org-inside-LaTeX-fragment-p ()
16676 "Test if point is inside a LaTeX fragment.
16677 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16678 sequence appearing also before point.
16679 Even though the matchers for math are configurable, this function assumes
16680 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16681 delimiters are skipped when they have been removed by customization.
16682 The return value is nil, or a cons cell with the delimiter and the
16683 position of this delimiter.
16684
16685 This function does a reasonably good job, but can locally be fooled by
16686 for example currency specifications. For example it will assume being in
16687 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16688 fragments that are properly closed, but during editing, we have to live
16689 with the uncertainty caused by missing closing delimiters. This function
16690 looks only before point, not after."
16691 (catch 'exit
16692 (let ((pos (point))
16693 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16694 (lim (progn
16695 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16696 (point)))
16697 dd-on str (start 0) m re)
16698 (goto-char pos)
16699 (when dodollar
16700 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16701 re (nth 1 (assoc "$" org-latex-regexps)))
16702 (while (string-match re str start)
16703 (cond
16704 ((= (match-end 0) (length str))
16705 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16706 ((= (match-end 0) (- (length str) 5))
16707 (throw 'exit nil))
16708 (t (setq start (match-end 0))))))
16709 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16710 (goto-char pos)
16711 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16712 (and (match-beginning 2) (throw 'exit nil))
16713 ;; count $$
16714 (while (re-search-backward "\\$\\$" lim t)
16715 (setq dd-on (not dd-on)))
16716 (goto-char pos)
16717 (if dd-on (cons "$$" m))))))
16718
16719 (defun org-inside-latex-macro-p ()
16720 "Is point inside a LaTeX macro or its arguments?"
16721 (save-match-data
16722 (org-in-regexp
16723 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16724
16725 (defun org-try-cdlatex-tab ()
16726 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16727 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16728 - inside a LaTeX fragment, or
16729 - after the first word in a line, where an abbreviation expansion could
16730 insert a LaTeX environment."
16731 (when org-cdlatex-mode
16732 (cond
16733 ;; Before any word on the line: No expansion possible.
16734 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16735 ;; Just after first word on the line: Expand it. Make sure it
16736 ;; cannot happen on headlines, though.
16737 ((save-excursion
16738 (skip-chars-backward "a-zA-Z0-9*")
16739 (skip-chars-backward " \t")
16740 (and (bolp) (not (org-at-heading-p))))
16741 (cdlatex-tab) t)
16742 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16743
16744 (defun org-cdlatex-underscore-caret (&optional arg)
16745 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16746 Revert to the normal definition outside of these fragments."
16747 (interactive "P")
16748 (if (org-inside-LaTeX-fragment-p)
16749 (call-interactively 'cdlatex-sub-superscript)
16750 (let (org-cdlatex-mode)
16751 (call-interactively (key-binding (vector last-input-event))))))
16752
16753 (defun org-cdlatex-math-modify (&optional arg)
16754 "Execute `cdlatex-math-modify' in LaTeX fragments.
16755 Revert to the normal definition outside of these fragments."
16756 (interactive "P")
16757 (if (org-inside-LaTeX-fragment-p)
16758 (call-interactively 'cdlatex-math-modify)
16759 (let (org-cdlatex-mode)
16760 (call-interactively (key-binding (vector last-input-event))))))
16761
16762 (defvar org-latex-fragment-image-overlays nil
16763 "List of overlays carrying the images of latex fragments.")
16764 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16765
16766 (defun org-remove-latex-fragment-image-overlays ()
16767 "Remove all overlays with LaTeX fragment images in current buffer."
16768 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16769 (setq org-latex-fragment-image-overlays nil))
16770
16771 (defun org-preview-latex-fragment (&optional subtree)
16772 "Preview the LaTeX fragment at point, or all locally or globally.
16773 If the cursor is in a LaTeX fragment, create the image and overlay
16774 it over the source code. If there is no fragment at point, display
16775 all fragments in the current text, from one headline to the next. With
16776 prefix SUBTREE, display all fragments in the current subtree. With a
16777 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16778 the cursor is before the first headline,
16779 display all fragments in the buffer.
16780 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16781 (interactive "P")
16782 (unless buffer-file-name
16783 (error "Can't preview LaTeX fragment in a non-file buffer"))
16784 (org-remove-latex-fragment-image-overlays)
16785 (save-excursion
16786 (save-restriction
16787 (let (beg end at msg)
16788 (cond
16789 ((or (equal subtree '(16))
16790 (not (save-excursion
16791 (re-search-backward org-outline-regexp-bol nil t))))
16792 (setq beg (point-min) end (point-max)
16793 msg "Creating images for buffer...%s"))
16794 ((equal subtree '(4))
16795 (org-back-to-heading)
16796 (setq beg (point) end (org-end-of-subtree t)
16797 msg "Creating images for subtree...%s"))
16798 (t
16799 (if (setq at (org-inside-LaTeX-fragment-p))
16800 (goto-char (max (point-min) (- (cdr at) 2)))
16801 (org-back-to-heading))
16802 (setq beg (point) end (progn (outline-next-heading) (point))
16803 msg (if at "Creating image...%s"
16804 "Creating images for entry...%s"))))
16805 (message msg "")
16806 (narrow-to-region beg end)
16807 (goto-char beg)
16808 (org-format-latex
16809 (concat "ltxpng/" (file-name-sans-extension
16810 (file-name-nondirectory
16811 buffer-file-name)))
16812 default-directory 'overlays msg at 'forbuffer 'dvipng)
16813 (message msg "done. Use `C-c C-c' to remove images.")))))
16814
16815 (defvar org-latex-regexps
16816 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16817 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16818 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16819 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16820 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16821 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16822 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16823 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16824 "Regular expressions for matching embedded LaTeX.")
16825
16826 (defvar org-export-have-math nil) ;; dynamic scoping
16827 (defun org-format-latex (prefix &optional dir overlays msg at
16828 forbuffer processing-type)
16829 "Replace LaTeX fragments with links to an image, and produce images.
16830 Some of the options can be changed using the variable
16831 `org-format-latex-options'."
16832 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16833 (let* ((prefixnodir (file-name-nondirectory prefix))
16834 (absprefix (expand-file-name prefix dir))
16835 (todir (file-name-directory absprefix))
16836 (opt org-format-latex-options)
16837 (matchers (plist-get opt :matchers))
16838 (re-list org-latex-regexps)
16839 (org-format-latex-header-extra
16840 (plist-get (org-infile-export-plist) :latex-header-extra))
16841 (cnt 0) txt hash link beg end re e checkdir
16842 executables-checked string
16843 m n block-type block linkfile movefile ov)
16844 ;; Check the different regular expressions
16845 (while (setq e (pop re-list))
16846 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16847 block (if block-type "\n\n" ""))
16848 (when (member m matchers)
16849 (goto-char (point-min))
16850 (while (re-search-forward re nil t)
16851 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16852 (not (get-text-property (match-beginning n)
16853 'org-protected))
16854 (or (not overlays)
16855 (not (eq (get-char-property (match-beginning n)
16856 'org-overlay-type)
16857 'org-latex-overlay))))
16858 (setq org-export-have-math t)
16859 (cond
16860 ((eq processing-type 'verbatim)
16861 ;; Leave the text verbatim, just protect it
16862 (add-text-properties (match-beginning n) (match-end n)
16863 '(org-protected t)))
16864 ((eq processing-type 'mathjax)
16865 ;; Prepare for MathJax processing
16866 (setq string (match-string n))
16867 (if (member m '("$" "$1"))
16868 (save-excursion
16869 (delete-region (match-beginning n) (match-end n))
16870 (goto-char (match-beginning n))
16871 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16872 "\\)")
16873 '(org-protected t))))
16874 (add-text-properties (match-beginning n) (match-end n)
16875 '(org-protected t))))
16876 ((eq processing-type 'dvipng)
16877 ;; Process to an image
16878 (setq txt (match-string n)
16879 beg (match-beginning n) end (match-end n)
16880 cnt (1+ cnt))
16881 (let (print-length print-level) ; make sure full list is printed
16882 (setq hash (sha1 (prin1-to-string
16883 (list org-format-latex-header
16884 org-format-latex-header-extra
16885 org-export-latex-default-packages-alist
16886 org-export-latex-packages-alist
16887 org-format-latex-options
16888 forbuffer txt)))
16889 linkfile (format "%s_%s.png" prefix hash)
16890 movefile (format "%s_%s.png" absprefix hash)))
16891 (setq link (concat block "[[file:" linkfile "]]" block))
16892 (if msg (message msg cnt))
16893 (goto-char beg)
16894 (unless checkdir ; make sure the directory exists
16895 (setq checkdir t)
16896 (or (file-directory-p todir) (make-directory todir t)))
16897
16898 (unless executables-checked
16899 (org-check-external-command
16900 "latex" "needed to convert LaTeX fragments to images")
16901 (org-check-external-command
16902 "dvipng" "needed to convert LaTeX fragments to images")
16903 (setq executables-checked t))
16904
16905 (unless (file-exists-p movefile)
16906 (org-create-formula-image
16907 txt movefile opt forbuffer))
16908 (if overlays
16909 (progn
16910 (mapc (lambda (o)
16911 (if (eq (overlay-get o 'org-overlay-type)
16912 'org-latex-overlay)
16913 (delete-overlay o)))
16914 (overlays-in beg end))
16915 (setq ov (make-overlay beg end))
16916 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16917 (if (featurep 'xemacs)
16918 (progn
16919 (overlay-put ov 'invisible t)
16920 (overlay-put
16921 ov 'end-glyph
16922 (make-glyph (vector 'png :file movefile))))
16923 (overlay-put
16924 ov 'display
16925 (list 'image :type 'png :file movefile :ascent 'center)))
16926 (push ov org-latex-fragment-image-overlays)
16927 (goto-char end))
16928 (delete-region beg end)
16929 (insert (org-add-props link
16930 (list 'org-latex-src
16931 (replace-regexp-in-string
16932 "\"" "" txt)
16933 'org-latex-src-embed-type
16934 (if block-type 'paragraph 'character))))))
16935 ((eq processing-type 'mathml)
16936 ;; Process to MathML
16937 (unless executables-checked
16938 (unless (save-match-data (org-format-latex-mathml-available-p))
16939 (error "LaTeX to MathML converter not configured"))
16940 (setq executables-checked t))
16941 (setq txt (match-string n)
16942 beg (match-beginning n) end (match-end n)
16943 cnt (1+ cnt))
16944 (if msg (message msg cnt))
16945 (goto-char beg)
16946 (delete-region beg end)
16947 (insert (org-format-latex-as-mathml
16948 txt block-type prefix dir)))
16949 (t
16950 (error "Unknown conversion type %s for latex fragments"
16951 processing-type)))))))))
16952
16953 (defun org-create-math-formula (latex-frag &optional mathml-file)
16954 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16955 Use `org-latex-to-mathml-convert-command'. If the conversion is
16956 sucessful, return the portion between \"<math...> </math>\"
16957 elements otherwise return nil. When MATHML-FILE is specified,
16958 write the results in to that file. When invoked as an
16959 interactive command, prompt for LATEX-FRAG, with initial value
16960 set to the current active region and echo the results for user
16961 inspection."
16962 (interactive (list (let ((frag (when (region-active-p)
16963 (buffer-substring-no-properties
16964 (region-beginning) (region-end)))))
16965 (read-string "LaTeX Fragment: " frag nil frag))))
16966 (unless latex-frag (error "Invalid latex-frag"))
16967 (let* ((tmp-in-file (file-relative-name
16968 (make-temp-name (expand-file-name "ltxmathml-in"))))
16969 (ignore (write-region latex-frag nil tmp-in-file))
16970 (tmp-out-file (file-relative-name
16971 (make-temp-name (expand-file-name "ltxmathml-out"))))
16972 (cmd (format-spec
16973 org-latex-to-mathml-convert-command
16974 `((?j . ,(shell-quote-argument
16975 (expand-file-name org-latex-to-mathml-jar-file)))
16976 (?I . ,(shell-quote-argument tmp-in-file))
16977 (?o . ,(shell-quote-argument tmp-out-file)))))
16978 mathml shell-command-output)
16979 (when (org-called-interactively-p 'any)
16980 (unless (org-format-latex-mathml-available-p)
16981 (error "LaTeX to MathML converter not configured")))
16982 (message "Running %s" cmd)
16983 (setq shell-command-output (shell-command-to-string cmd))
16984 (setq mathml
16985 (when (file-readable-p tmp-out-file)
16986 (with-current-buffer (find-file-noselect tmp-out-file t)
16987 (goto-char (point-min))
16988 (when (re-search-forward
16989 (concat
16990 (regexp-quote
16991 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16992 "\\(.\\|\n\\)*"
16993 (regexp-quote "</math>")) nil t)
16994 (prog1 (match-string 0) (kill-buffer))))))
16995 (cond
16996 (mathml
16997 (setq mathml
16998 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16999 (when mathml-file
17000 (write-region mathml nil mathml-file))
17001 (when (org-called-interactively-p 'any)
17002 (message mathml)))
17003 ((message "LaTeX to MathML conversion failed")
17004 (message shell-command-output)))
17005 (delete-file tmp-in-file)
17006 (when (file-exists-p tmp-out-file)
17007 (delete-file tmp-out-file))
17008 mathml))
17009
17010 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17011 prefix &optional dir)
17012 "Use `org-create-math-formula' but check local cache first."
17013 (let* ((absprefix (expand-file-name prefix dir))
17014 (print-length nil) (print-level nil)
17015 (formula-id (concat
17016 "formula-"
17017 (sha1
17018 (prin1-to-string
17019 (list latex-frag
17020 org-latex-to-mathml-convert-command)))))
17021 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17022 (formula-cache-dir (file-name-directory formula-cache)))
17023
17024 (unless (file-directory-p formula-cache-dir)
17025 (make-directory formula-cache-dir t))
17026
17027 (unless (file-exists-p formula-cache)
17028 (org-create-math-formula latex-frag formula-cache))
17029
17030 (if (file-exists-p formula-cache)
17031 ;; Successful conversion. Return the link to MathML file.
17032 (org-add-props
17033 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17034 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17035 'org-latex-src-embed-type (if latex-frag-type
17036 'paragraph 'character)))
17037 ;; Failed conversion. Return the LaTeX fragment verbatim
17038 (add-text-properties
17039 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17040 latex-frag)))
17041
17042 ;; This function borrows from Ganesh Swami's latex2png.el
17043 (defun org-create-formula-image (string tofile options buffer)
17044 "This calls dvipng."
17045 (require 'org-latex)
17046 (let* ((tmpdir (if (featurep 'xemacs)
17047 (temp-directory)
17048 temporary-file-directory))
17049 (texfilebase (make-temp-name
17050 (expand-file-name "orgtex" tmpdir)))
17051 (texfile (concat texfilebase ".tex"))
17052 (dvifile (concat texfilebase ".dvi"))
17053 (pngfile (concat texfilebase ".png"))
17054 (fnh (if (featurep 'xemacs)
17055 (font-height (face-font 'default))
17056 (face-attribute 'default :height nil)))
17057 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17058 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17059 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17060 "Black"))
17061 (bg (or (plist-get options (if buffer :background :html-background))
17062 "Transparent")))
17063 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17064 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17065 (with-temp-file texfile
17066 (insert (org-splice-latex-header
17067 org-format-latex-header
17068 org-export-latex-default-packages-alist
17069 org-export-latex-packages-alist t
17070 org-format-latex-header-extra))
17071 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17072 (require 'org-latex)
17073 (org-export-latex-fix-inputenc))
17074 (let ((dir default-directory))
17075 (condition-case nil
17076 (progn
17077 (cd tmpdir)
17078 (call-process "latex" nil nil nil texfile))
17079 (error nil))
17080 (cd dir))
17081 (if (not (file-exists-p dvifile))
17082 (progn (message "Failed to create dvi file from %s" texfile) nil)
17083 (condition-case nil
17084 (if (featurep 'xemacs)
17085 (call-process "dvipng" nil nil nil
17086 "-fg" fg "-bg" bg
17087 "-T" "tight"
17088 "-o" pngfile
17089 dvifile)
17090 (call-process "dvipng" nil nil nil
17091 "-fg" fg "-bg" bg
17092 "-D" dpi
17093 ;;"-x" scale "-y" scale
17094 "-T" "tight"
17095 "-o" pngfile
17096 dvifile))
17097 (error nil))
17098 (if (not (file-exists-p pngfile))
17099 (if org-format-latex-signal-error
17100 (error "Failed to create png file from %s" texfile)
17101 (message "Failed to create png file from %s" texfile)
17102 nil)
17103 ;; Use the requested file name and clean up
17104 (copy-file pngfile tofile 'replace)
17105 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17106 (delete-file (concat texfilebase e)))
17107 pngfile))))
17108
17109 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17110 "Fill a LaTeX header template TPL.
17111 In the template, the following place holders will be recognized:
17112
17113 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17114 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17115 [PACKAGES] \\usepackage statements for PKG
17116 [NO-PACKAGES] do not include PKG
17117 [EXTRA] the string EXTRA
17118 [NO-EXTRA] do not include EXTRA
17119
17120 For backward compatibility, if both the positive and the negative place
17121 holder is missing, the positive one (without the \"NO-\") will be
17122 assumed to be present at the end of the template.
17123 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17124 EXTRA is a string.
17125 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17126 (let (rpl (end ""))
17127 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17128 (setq rpl (if (or (match-end 1) (not def-pkg))
17129 "" (org-latex-packages-to-string def-pkg snippets-p t))
17130 tpl (replace-match rpl t t tpl))
17131 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17132
17133 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17134 (setq rpl (if (or (match-end 1) (not pkg))
17135 "" (org-latex-packages-to-string pkg snippets-p t))
17136 tpl (replace-match rpl t t tpl))
17137 (if pkg (setq end
17138 (concat end "\n"
17139 (org-latex-packages-to-string pkg snippets-p)))))
17140
17141 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17142 (setq rpl (if (or (match-end 1) (not extra))
17143 "" (concat extra "\n"))
17144 tpl (replace-match rpl t t tpl))
17145 (if (and extra (string-match "\\S-" extra))
17146 (setq end (concat end "\n" extra))))
17147
17148 (if (string-match "\\S-" end)
17149 (concat tpl "\n" end)
17150 tpl)))
17151
17152 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17153 "Turn an alist of packages into a string with the \\usepackage macros."
17154 (setq pkg (mapconcat (lambda(p)
17155 (cond
17156 ((stringp p) p)
17157 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17158 (format "%% Package %s omitted" (cadr p)))
17159 ((equal "" (car p))
17160 (format "\\usepackage{%s}" (cadr p)))
17161 (t
17162 (format "\\usepackage[%s]{%s}"
17163 (car p) (cadr p)))))
17164 pkg
17165 "\n"))
17166 (if newline (concat pkg "\n") pkg))
17167
17168 (defun org-dvipng-color (attr)
17169 "Return an rgb color specification for dvipng."
17170 (apply 'format "rgb %s %s %s"
17171 (mapcar 'org-normalize-color
17172 (if (featurep 'xemacs)
17173 (color-rgb-components
17174 (face-property 'default
17175 (cond ((eq attr :foreground) 'foreground)
17176 ((eq attr :background) 'background))))
17177 (color-values (face-attribute 'default attr nil))))))
17178
17179 (defun org-normalize-color (value)
17180 "Return string to be used as color value for an RGB component."
17181 (format "%g" (/ value 65535.0)))
17182
17183 ;; Image display
17184
17185
17186 (defvar org-inline-image-overlays nil)
17187 (make-variable-buffer-local 'org-inline-image-overlays)
17188
17189 (defun org-toggle-inline-images (&optional include-linked)
17190 "Toggle the display of inline images.
17191 INCLUDE-LINKED is passed to `org-display-inline-images'."
17192 (interactive "P")
17193 (if org-inline-image-overlays
17194 (progn
17195 (org-remove-inline-images)
17196 (message "Inline image display turned off"))
17197 (org-display-inline-images include-linked)
17198 (if org-inline-image-overlays
17199 (message "%d images displayed inline"
17200 (length org-inline-image-overlays))
17201 (message "No images to display inline"))))
17202
17203 (defun org-display-inline-images (&optional include-linked refresh beg end)
17204 "Display inline images.
17205 Normally only links without a description part are inlined, because this
17206 is how it will work for export. When INCLUDE-LINKED is set, also links
17207 with a description part will be inlined. This can be nice for a quick
17208 look at those images, but it does not reflect what exported files will look
17209 like.
17210 When REFRESH is set, refresh existing images between BEG and END.
17211 This will create new image displays only if necessary.
17212 BEG and END default to the buffer boundaries."
17213 (interactive "P")
17214 (unless refresh
17215 (org-remove-inline-images)
17216 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17217 (save-excursion
17218 (save-restriction
17219 (widen)
17220 (setq beg (or beg (point-min)) end (or end (point-max)))
17221 (goto-char beg)
17222 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17223 (substring (org-image-file-name-regexp) 0 -2)
17224 "\\)\\]" (if include-linked "" "\\]")))
17225 old file ov img)
17226 (while (re-search-forward re end t)
17227 (setq old (get-char-property-and-overlay (match-beginning 1)
17228 'org-image-overlay))
17229 (setq file (expand-file-name
17230 (concat (or (match-string 3) "") (match-string 4))))
17231 (when (file-exists-p file)
17232 (if (and (car-safe old) refresh)
17233 (image-refresh (overlay-get (cdr old) 'display))
17234 (setq img (save-match-data (create-image file)))
17235 (when img
17236 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17237 (overlay-put ov 'display img)
17238 (overlay-put ov 'face 'default)
17239 (overlay-put ov 'org-image-overlay t)
17240 (overlay-put ov 'modification-hooks
17241 (list 'org-display-inline-modification-hook))
17242 (push ov org-inline-image-overlays)))))))))
17243
17244 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17245 "Remove inline-display overlay if a corresponding region is modified."
17246 (let ((inhibit-modification-hooks t))
17247 (when (and ov after)
17248 (delete ov org-inline-image-overlays)
17249 (delete-overlay ov))))
17250
17251 (defun org-remove-inline-images ()
17252 "Remove inline display of images."
17253 (interactive)
17254 (mapc 'delete-overlay org-inline-image-overlays)
17255 (setq org-inline-image-overlays nil))
17256
17257 ;;;; Key bindings
17258
17259 ;; Outline functions from `outline-mode-prefix-map'
17260 ;; that can be remapped in Org:
17261 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17262 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17263 (define-key org-mode-map [remap outline-forward-same-level]
17264 'org-forward-same-level)
17265 (define-key org-mode-map [remap outline-backward-same-level]
17266 'org-backward-same-level)
17267 (define-key org-mode-map [remap show-branches]
17268 'org-kill-note-or-show-branches)
17269 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17270 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17271 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17272
17273 ;; Outline functions from `outline-mode-prefix-map'
17274 ;; that can not be remapped in Org:
17275 ;; - the column "key binding" shows whether the Outline function is still
17276 ;; available in Org mode on the same key that it has been bound to in
17277 ;; Outline mode:
17278 ;; - "overridden": key used for a different functionality in Org mode
17279 ;; - else: key still bound to the same Outline function in Org mode
17280 ;; | Outline function | key binding | Org replacement |
17281 ;; |------------------------------------+-------------+-----------------------|
17282 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17283 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17284 ;; | `show-children' | `C-c C-i' | visibility cycling |
17285 ;; | `hide-subtree' | overridden | visibility cycling |
17286 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17287 ;; | `hide-body' | overridden | no replacement |
17288 ;; | `show-all' | overridden | no replacement |
17289 ;; | `hide-entry' | overridden | visibility cycling |
17290 ;; | `show-entry' | overridden | no replacement |
17291 ;; | `hide-leaves' | overridden | no replacement |
17292 ;; | `hide-sublevels' | overridden | no replacement |
17293 ;; | `hide-other' | overridden | no replacement |
17294 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17295 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17296
17297 ;; Make `C-c C-x' a prefix key
17298 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17299
17300 ;; TAB key with modifiers
17301 (org-defkey org-mode-map "\C-i" 'org-cycle)
17302 (org-defkey org-mode-map [(tab)] 'org-cycle)
17303 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17304 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17305 ;; The following line is necessary under Suse GNU/Linux
17306 (unless (featurep 'xemacs)
17307 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17308 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17309 (define-key org-mode-map [backtab] 'org-shifttab)
17310
17311 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17312 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17313 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17314
17315 ;; Cursor keys with modifiers
17316 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17317 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17318 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17319 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17320
17321 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17322 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17323 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17324 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17325
17326 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17327 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17328 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17329 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17330
17331 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17332 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17333 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17334 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17335
17336 ;; Babel keys
17337 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17338 (mapc (lambda (pair)
17339 (define-key org-babel-map (car pair) (cdr pair)))
17340 org-babel-key-bindings)
17341
17342 ;;; Extra keys for tty access.
17343 ;; We only set them when really needed because otherwise the
17344 ;; menus don't show the simple keys
17345
17346 (when (or org-use-extra-keys
17347 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17348 (not window-system))
17349 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17350 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17351 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17352 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17353 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17354 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17355 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17356 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17357 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17358 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17359 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17360 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17361 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17362 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17363 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17364 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17365 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17366 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17367 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17368 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17369 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17370 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17371 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17372 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17373 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17374 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17375 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17376 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17377
17378 ;; All the other keys
17379
17380 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17381 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17382 (if (boundp 'narrow-map)
17383 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17384 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17385 (if (boundp 'narrow-map)
17386 (org-defkey narrow-map "b" 'org-narrow-to-block)
17387 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17388 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17389 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17390 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17391 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17392 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17393 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17394 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17395 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17396 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17397 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17398 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17399 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17400 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17401 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17402 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17403 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17404 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17405 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17406 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17407 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17408 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17409 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17410 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17411 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17412 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17413 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17414 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17415 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17416 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17417 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17418 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17419 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17420 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17421 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17422 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17423 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17424 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17425 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17426 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17427 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17428 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17429 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17430 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17431 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17432 (org-defkey org-mode-map "\C-c^" 'org-sort)
17433 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17434 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17435 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17436 (org-defkey org-mode-map "\C-m" 'org-return)
17437 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17438 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17439 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17440 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17441 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17442 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17443 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17444 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17445 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17446 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17447 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17448 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17449 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17450 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17451 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17452 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17453 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17454 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17455 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17456 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17457 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17458 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17459
17460 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17461 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17462 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17463 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17464
17465 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17466 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17467 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17468 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17469 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17470 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17471 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17472 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17473 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17474 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17475 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17476 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17477 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17478 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17479 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17480 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17481 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17482 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17483
17484 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17485 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17486 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17487 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17488 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17489
17490 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17491
17492 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17493
17494 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17495 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17496
17497 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17498
17499
17500 (when (featurep 'xemacs)
17501 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17502
17503
17504 (defconst org-speed-commands-default
17505 '(
17506 ("Outline Navigation")
17507 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17508 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17509 ("f" . (org-speed-move-safe 'org-forward-same-level))
17510 ("b" . (org-speed-move-safe 'org-backward-same-level))
17511 ("u" . (org-speed-move-safe 'outline-up-heading))
17512 ("j" . org-goto)
17513 ("g" . (org-refile t))
17514 ("Outline Visibility")
17515 ("c" . org-cycle)
17516 ("C" . org-shifttab)
17517 (" " . org-display-outline-path)
17518 ("Outline Structure Editing")
17519 ("U" . org-shiftmetaup)
17520 ("D" . org-shiftmetadown)
17521 ("r" . org-metaright)
17522 ("l" . org-metaleft)
17523 ("R" . org-shiftmetaright)
17524 ("L" . org-shiftmetaleft)
17525 ("i" . (progn (forward-char 1) (call-interactively
17526 'org-insert-heading-respect-content)))
17527 ("^" . org-sort)
17528 ("w" . org-refile)
17529 ("a" . org-archive-subtree-default-with-confirmation)
17530 ("." . org-mark-subtree)
17531 ("Clock Commands")
17532 ("I" . org-clock-in)
17533 ("O" . org-clock-out)
17534 ("Meta Data Editing")
17535 ("t" . org-todo)
17536 ("0" . (org-priority ?\ ))
17537 ("1" . (org-priority ?A))
17538 ("2" . (org-priority ?B))
17539 ("3" . (org-priority ?C))
17540 (";" . org-set-tags-command)
17541 ("e" . org-set-effort)
17542 ("Agenda Views etc")
17543 ("v" . org-agenda)
17544 ("/" . org-sparse-tree)
17545 ("Misc")
17546 ("o" . org-open-at-point)
17547 ("?" . org-speed-command-help)
17548 ("<" . (org-agenda-set-restriction-lock 'subtree))
17549 (">" . (org-agenda-remove-restriction-lock))
17550 )
17551 "The default speed commands.")
17552
17553 (defun org-print-speed-command (e)
17554 (if (> (length (car e)) 1)
17555 (progn
17556 (princ "\n")
17557 (princ (car e))
17558 (princ "\n")
17559 (princ (make-string (length (car e)) ?-))
17560 (princ "\n"))
17561 (princ (car e))
17562 (princ " ")
17563 (if (symbolp (cdr e))
17564 (princ (symbol-name (cdr e)))
17565 (prin1 (cdr e)))
17566 (princ "\n")))
17567
17568 (defun org-speed-command-help ()
17569 "Show the available speed commands."
17570 (interactive)
17571 (if (not org-use-speed-commands)
17572 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17573 (with-output-to-temp-buffer "*Help*"
17574 (princ "User-defined Speed commands\n===========================\n")
17575 (mapc 'org-print-speed-command org-speed-commands-user)
17576 (princ "\n")
17577 (princ "Built-in Speed commands\n=======================\n")
17578 (mapc 'org-print-speed-command org-speed-commands-default))
17579 (with-current-buffer "*Help*"
17580 (setq truncate-lines t))))
17581
17582 (defun org-speed-move-safe (cmd)
17583 "Execute CMD, but make sure that the cursor always ends up in a headline.
17584 If not, return to the original position and throw an error."
17585 (interactive)
17586 (let ((pos (point)))
17587 (call-interactively cmd)
17588 (unless (and (bolp) (org-at-heading-p))
17589 (goto-char pos)
17590 (error "Boundary reached while executing %s" cmd))))
17591
17592 (defvar org-self-insert-command-undo-counter 0)
17593
17594 (defvar org-table-auto-blank-field) ; defined in org-table.el
17595 (defvar org-speed-command nil)
17596
17597 (defun org-speed-command-default-hook (keys)
17598 "Hook for activating single-letter speed commands.
17599 `org-speed-commands-default' specifies a minimal command set.
17600 Use `org-speed-commands-user' for further customization."
17601 (when (or (and (bolp) (looking-at org-outline-regexp))
17602 (and (functionp org-use-speed-commands)
17603 (funcall org-use-speed-commands)))
17604 (cdr (assoc keys (append org-speed-commands-user
17605 org-speed-commands-default)))))
17606
17607 (defun org-babel-speed-command-hook (keys)
17608 "Hook for activating single-letter code block commands."
17609 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17610 (cdr (assoc keys org-babel-key-bindings))))
17611
17612 (defcustom org-speed-command-hook
17613 '(org-speed-command-default-hook org-babel-speed-command-hook)
17614 "Hook for activating speed commands at strategic locations.
17615 Hook functions are called in sequence until a valid handler is
17616 found.
17617
17618 Each hook takes a single argument, a user-pressed command key
17619 which is also a `self-insert-command' from the global map.
17620
17621 Within the hook, examine the cursor position and the command key
17622 and return nil or a valid handler as appropriate. Handler could
17623 be one of an interactive command, a function, or a form.
17624
17625 Set `org-use-speed-commands' to non-nil value to enable this
17626 hook. The default setting is `org-speed-command-default-hook'."
17627 :group 'org-structure
17628 :type 'hook)
17629
17630 (defun org-self-insert-command (N)
17631 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17632 If the cursor is in a table looking at whitespace, the whitespace is
17633 overwritten, and the table is not marked as requiring realignment."
17634 (interactive "p")
17635 (org-check-before-invisible-edit 'insert)
17636 (cond
17637 ((and org-use-speed-commands
17638 (setq org-speed-command
17639 (run-hook-with-args-until-success
17640 'org-speed-command-hook (this-command-keys))))
17641 (cond
17642 ((commandp org-speed-command)
17643 (setq this-command org-speed-command)
17644 (call-interactively org-speed-command))
17645 ((functionp org-speed-command)
17646 (funcall org-speed-command))
17647 ((and org-speed-command (listp org-speed-command))
17648 (eval org-speed-command))
17649 (t (let (org-use-speed-commands)
17650 (call-interactively 'org-self-insert-command)))))
17651 ((and
17652 (org-table-p)
17653 (progn
17654 ;; check if we blank the field, and if that triggers align
17655 (and (featurep 'org-table) org-table-auto-blank-field
17656 (member last-command
17657 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17658 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17659 ;; got extra space, this field does not determine column width
17660 (let (org-table-may-need-update) (org-table-blank-field))
17661 ;; no extra space, this field may determine column width
17662 (org-table-blank-field)))
17663 t)
17664 (eq N 1)
17665 (looking-at "[^|\n]* |"))
17666 (let (org-table-may-need-update)
17667 (goto-char (1- (match-end 0)))
17668 (backward-delete-char 1)
17669 (goto-char (match-beginning 0))
17670 (self-insert-command N)))
17671 (t
17672 (setq org-table-may-need-update t)
17673 (self-insert-command N)
17674 (org-fix-tags-on-the-fly)
17675 (if org-self-insert-cluster-for-undo
17676 (if (not (eq last-command 'org-self-insert-command))
17677 (setq org-self-insert-command-undo-counter 1)
17678 (if (>= org-self-insert-command-undo-counter 20)
17679 (setq org-self-insert-command-undo-counter 1)
17680 (and (> org-self-insert-command-undo-counter 0)
17681 buffer-undo-list (listp buffer-undo-list)
17682 (not (cadr buffer-undo-list)) ; remove nil entry
17683 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17684 (setq org-self-insert-command-undo-counter
17685 (1+ org-self-insert-command-undo-counter))))))))
17686
17687 (defun org-check-before-invisible-edit (kind)
17688 "Check is editing if kind KIND would be dangerous with invisible text around.
17689 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17690 ;; First, try to get out of here as quickly as possible, to reduce overhead
17691 (if (and org-catch-invisible-edits
17692 (or (not (boundp 'visible-mode)) (not visible-mode))
17693 (or (get-char-property (point) 'invisible)
17694 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17695 ;; OK, we need to take a closer look
17696 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17697 (invisible-before-point (if (bobp) nil (get-char-property
17698 (1- (point)) 'invisible)))
17699 (border-and-ok-direction
17700 (or
17701 ;; Check if we are acting predictably before invisible text
17702 (and invisible-at-point (not invisible-before-point)
17703 (memq kind '(insert delete-backward)))
17704 ;; Check if we are acting predictably after invisible text
17705 ;; This works not well, and I have turned it off. It seems
17706 ;; better to always show and stop after invisible text.
17707 ;; (and (not invisible-at-point) invisible-before-point
17708 ;; (memq kind '(insert delete)))
17709 )))
17710
17711 (when (or (memq invisible-at-point '(outline org-hide-block))
17712 (memq invisible-before-point '(outline org-hide-block)))
17713 (if (eq org-catch-invisible-edits 'error)
17714 (error "Editing in invisible areas is prohibited - make visible first"))
17715 ;; Make the area visible
17716 (save-excursion
17717 (if invisible-before-point
17718 (goto-char (previous-single-char-property-change
17719 (point) 'invisible)))
17720 (org-cycle))
17721 (cond
17722 ((eq org-catch-invisible-edits 'show)
17723 ;; That's it, we do the edit after showing
17724 (message
17725 "Unfolding invisible region around point before editing")
17726 (sit-for 1))
17727 ((and (eq org-catch-invisible-edits 'smart)
17728 border-and-ok-direction)
17729 (message "Unfolding invisible region around point before editing"))
17730 (t
17731 ;; Don't do the edit, make the user repeat it in full visibility
17732 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17733
17734 (defun org-fix-tags-on-the-fly ()
17735 (when (and (equal (char-after (point-at-bol)) ?*)
17736 (org-at-heading-p))
17737 (org-align-tags-here org-tags-column)))
17738
17739 (defun org-delete-backward-char (N)
17740 "Like `delete-backward-char', insert whitespace at field end in tables.
17741 When deleting backwards, in tables this function will insert whitespace in
17742 front of the next \"|\" separator, to keep the table aligned. The table will
17743 still be marked for re-alignment if the field did fill the entire column,
17744 because, in this case the deletion might narrow the column."
17745 (interactive "p")
17746 (org-check-before-invisible-edit 'delete-backward)
17747 (if (and (org-table-p)
17748 (eq N 1)
17749 (string-match "|" (buffer-substring (point-at-bol) (point)))
17750 (looking-at ".*?|"))
17751 (let ((pos (point))
17752 (noalign (looking-at "[^|\n\r]* |"))
17753 (c org-table-may-need-update))
17754 (backward-delete-char N)
17755 (if (not overwrite-mode)
17756 (progn
17757 (skip-chars-forward "^|")
17758 (insert " ")
17759 (goto-char (1- pos))))
17760 ;; noalign: if there were two spaces at the end, this field
17761 ;; does not determine the width of the column.
17762 (if noalign (setq org-table-may-need-update c)))
17763 (backward-delete-char N)
17764 (org-fix-tags-on-the-fly)))
17765
17766 (defun org-delete-char (N)
17767 "Like `delete-char', but insert whitespace at field end in tables.
17768 When deleting characters, in tables this function will insert whitespace in
17769 front of the next \"|\" separator, to keep the table aligned. The table will
17770 still be marked for re-alignment if the field did fill the entire column,
17771 because, in this case the deletion might narrow the column."
17772 (interactive "p")
17773 (org-check-before-invisible-edit 'delete)
17774 (if (and (org-table-p)
17775 (not (bolp))
17776 (not (= (char-after) ?|))
17777 (eq N 1))
17778 (if (looking-at ".*?|")
17779 (let ((pos (point))
17780 (noalign (looking-at "[^|\n\r]* |"))
17781 (c org-table-may-need-update))
17782 (replace-match (concat
17783 (substring (match-string 0) 1 -1)
17784 " |"))
17785 (goto-char pos)
17786 ;; noalign: if there were two spaces at the end, this field
17787 ;; does not determine the width of the column.
17788 (if noalign (setq org-table-may-need-update c)))
17789 (delete-char N))
17790 (delete-char N)
17791 (org-fix-tags-on-the-fly)))
17792
17793 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17794 (put 'org-self-insert-command 'delete-selection t)
17795 (put 'orgtbl-self-insert-command 'delete-selection t)
17796 (put 'org-delete-char 'delete-selection 'supersede)
17797 (put 'org-delete-backward-char 'delete-selection 'supersede)
17798 (put 'org-yank 'delete-selection 'yank)
17799
17800 ;; Make `flyspell-mode' delay after some commands
17801 (put 'org-self-insert-command 'flyspell-delayed t)
17802 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17803 (put 'org-delete-char 'flyspell-delayed t)
17804 (put 'org-delete-backward-char 'flyspell-delayed t)
17805
17806 ;; Make pabbrev-mode expand after org-mode commands
17807 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17808 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17809
17810 ;; How to do this: Measure non-white length of current string
17811 ;; If equal to column width, we should realign.
17812
17813 (defun org-remap (map &rest commands)
17814 "In MAP, remap the functions given in COMMANDS.
17815 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17816 (let (new old)
17817 (while commands
17818 (setq old (pop commands) new (pop commands))
17819 (if (fboundp 'command-remapping)
17820 (org-defkey map (vector 'remap old) new)
17821 (substitute-key-definition old new map global-map)))))
17822
17823 (when (eq org-enable-table-editor 'optimized)
17824 ;; If the user wants maximum table support, we need to hijack
17825 ;; some standard editing functions
17826 (org-remap org-mode-map
17827 'self-insert-command 'org-self-insert-command
17828 'delete-char 'org-delete-char
17829 'delete-backward-char 'org-delete-backward-char)
17830 (org-defkey org-mode-map "|" 'org-force-self-insert))
17831
17832 (defvar org-ctrl-c-ctrl-c-hook nil
17833 "Hook for functions attaching themselves to `C-c C-c'.
17834
17835 This can be used to add additional functionality to the C-c C-c
17836 key which executes context-dependent commands. This hook is run
17837 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17838 run after the last test.
17839
17840 Each function will be called with no arguments. The function
17841 must check if the context is appropriate for it to act. If yes,
17842 it should do its thing and then return a non-nil value. If the
17843 context is wrong, just do nothing and return nil.")
17844
17845 (defvar org-ctrl-c-ctrl-c-final-hook nil
17846 "Hook for functions attaching themselves to `C-c C-c'.
17847
17848 This can be used to add additional functionality to the C-c C-c
17849 key which executes context-dependent commands. This hook is run
17850 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17851 before the first test.
17852
17853 Each function will be called with no arguments. The function
17854 must check if the context is appropriate for it to act. If yes,
17855 it should do its thing and then return a non-nil value. If the
17856 context is wrong, just do nothing and return nil.")
17857
17858 (defvar org-tab-first-hook nil
17859 "Hook for functions to attach themselves to TAB.
17860 See `org-ctrl-c-ctrl-c-hook' for more information.
17861 This hook runs as the first action when TAB is pressed, even before
17862 `org-cycle' messes around with the `outline-regexp' to cater for
17863 inline tasks and plain list item folding.
17864 If any function in this hook returns t, any other actions that
17865 would have been caused by TAB (such as table field motion or visibility
17866 cycling) will not occur.")
17867
17868 (defvar org-tab-after-check-for-table-hook nil
17869 "Hook for functions to attach themselves to TAB.
17870 See `org-ctrl-c-ctrl-c-hook' for more information.
17871 This hook runs after it has been established that the cursor is not in a
17872 table, but before checking if the cursor is in a headline or if global cycling
17873 should be done.
17874 If any function in this hook returns t, not other actions like visibility
17875 cycling will be done.")
17876
17877 (defvar org-tab-after-check-for-cycling-hook nil
17878 "Hook for functions to attach themselves to TAB.
17879 See `org-ctrl-c-ctrl-c-hook' for more information.
17880 This hook runs after it has been established that not table field motion and
17881 not visibility should be done because of current context. This is probably
17882 the place where a package like yasnippets can hook in.")
17883
17884 (defvar org-tab-before-tab-emulation-hook nil
17885 "Hook for functions to attach themselves to TAB.
17886 See `org-ctrl-c-ctrl-c-hook' for more information.
17887 This hook runs after every other options for TAB have been exhausted, but
17888 before indentation and \t insertion takes place.")
17889
17890 (defvar org-metaleft-hook nil
17891 "Hook for functions attaching themselves to `M-left'.
17892 See `org-ctrl-c-ctrl-c-hook' for more information.")
17893 (defvar org-metaright-hook nil
17894 "Hook for functions attaching themselves to `M-right'.
17895 See `org-ctrl-c-ctrl-c-hook' for more information.")
17896 (defvar org-metaup-hook nil
17897 "Hook for functions attaching themselves to `M-up'.
17898 See `org-ctrl-c-ctrl-c-hook' for more information.")
17899 (defvar org-metadown-hook nil
17900 "Hook for functions attaching themselves to `M-down'.
17901 See `org-ctrl-c-ctrl-c-hook' for more information.")
17902 (defvar org-shiftmetaleft-hook nil
17903 "Hook for functions attaching themselves to `M-S-left'.
17904 See `org-ctrl-c-ctrl-c-hook' for more information.")
17905 (defvar org-shiftmetaright-hook nil
17906 "Hook for functions attaching themselves to `M-S-right'.
17907 See `org-ctrl-c-ctrl-c-hook' for more information.")
17908 (defvar org-shiftmetaup-hook nil
17909 "Hook for functions attaching themselves to `M-S-up'.
17910 See `org-ctrl-c-ctrl-c-hook' for more information.")
17911 (defvar org-shiftmetadown-hook nil
17912 "Hook for functions attaching themselves to `M-S-down'.
17913 See `org-ctrl-c-ctrl-c-hook' for more information.")
17914 (defvar org-metareturn-hook nil
17915 "Hook for functions attaching themselves to `M-RET'.
17916 See `org-ctrl-c-ctrl-c-hook' for more information.")
17917 (defvar org-shiftup-hook nil
17918 "Hook for functions attaching themselves to `S-up'.
17919 See `org-ctrl-c-ctrl-c-hook' for more information.")
17920 (defvar org-shiftup-final-hook nil
17921 "Hook for functions attaching themselves to `S-up'.
17922 This one runs after all other options except shift-select have been excluded.
17923 See `org-ctrl-c-ctrl-c-hook' for more information.")
17924 (defvar org-shiftdown-hook nil
17925 "Hook for functions attaching themselves to `S-down'.
17926 See `org-ctrl-c-ctrl-c-hook' for more information.")
17927 (defvar org-shiftdown-final-hook nil
17928 "Hook for functions attaching themselves to `S-down'.
17929 This one runs after all other options except shift-select have been excluded.
17930 See `org-ctrl-c-ctrl-c-hook' for more information.")
17931 (defvar org-shiftleft-hook nil
17932 "Hook for functions attaching themselves to `S-left'.
17933 See `org-ctrl-c-ctrl-c-hook' for more information.")
17934 (defvar org-shiftleft-final-hook nil
17935 "Hook for functions attaching themselves to `S-left'.
17936 This one runs after all other options except shift-select have been excluded.
17937 See `org-ctrl-c-ctrl-c-hook' for more information.")
17938 (defvar org-shiftright-hook nil
17939 "Hook for functions attaching themselves to `S-right'.
17940 See `org-ctrl-c-ctrl-c-hook' for more information.")
17941 (defvar org-shiftright-final-hook nil
17942 "Hook for functions attaching themselves to `S-right'.
17943 This one runs after all other options except shift-select have been excluded.
17944 See `org-ctrl-c-ctrl-c-hook' for more information.")
17945
17946 (defun org-modifier-cursor-error ()
17947 "Throw an error, a modified cursor command was applied in wrong context."
17948 (error "This command is active in special context like tables, headlines or items"))
17949
17950 (defun org-shiftselect-error ()
17951 "Throw an error because Shift-Cursor command was applied in wrong context."
17952 (if (and (boundp 'shift-select-mode) shift-select-mode)
17953 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17954 (error "This command works only in special context like headlines or timestamps")))
17955
17956 (defun org-call-for-shift-select (cmd)
17957 (let ((this-command-keys-shift-translated t))
17958 (call-interactively cmd)))
17959
17960 (defun org-shifttab (&optional arg)
17961 "Global visibility cycling or move to previous table field.
17962 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17963 on context.
17964 See the individual commands for more information."
17965 (interactive "P")
17966 (cond
17967 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17968 ((integerp arg)
17969 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17970 (message "Content view to level: %d" arg)
17971 (org-content (prefix-numeric-value arg2))
17972 (setq org-cycle-global-status 'overview)))
17973 (t (call-interactively 'org-global-cycle))))
17974
17975 (defun org-shiftmetaleft ()
17976 "Promote subtree or delete table column.
17977 Calls `org-promote-subtree', `org-outdent-item-tree', or
17978 `org-table-delete-column', depending on context. See the
17979 individual commands for more information."
17980 (interactive)
17981 (cond
17982 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17983 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17984 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17985 ((if (not (org-region-active-p)) (org-at-item-p)
17986 (save-excursion (goto-char (region-beginning))
17987 (org-at-item-p)))
17988 (call-interactively 'org-outdent-item-tree))
17989 (t (org-modifier-cursor-error))))
17990
17991 (defun org-shiftmetaright ()
17992 "Demote subtree or insert table column.
17993 Calls `org-demote-subtree', `org-indent-item-tree', or
17994 `org-table-insert-column', depending on context. See the
17995 individual commands for more information."
17996 (interactive)
17997 (cond
17998 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17999 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18000 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18001 ((if (not (org-region-active-p)) (org-at-item-p)
18002 (save-excursion (goto-char (region-beginning))
18003 (org-at-item-p)))
18004 (call-interactively 'org-indent-item-tree))
18005 (t (org-modifier-cursor-error))))
18006
18007 (defun org-shiftmetaup (&optional arg)
18008 "Move subtree up or kill table row.
18009 Calls `org-move-subtree-up' or `org-table-kill-row' or
18010 `org-move-item-up' depending on context. See the individual commands
18011 for more information."
18012 (interactive "P")
18013 (cond
18014 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18015 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18016 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18017 ((org-at-item-p) (call-interactively 'org-move-item-up))
18018 (t (org-modifier-cursor-error))))
18019
18020 (defun org-shiftmetadown (&optional arg)
18021 "Move subtree down or insert table row.
18022 Calls `org-move-subtree-down' or `org-table-insert-row' or
18023 `org-move-item-down', depending on context. See the individual
18024 commands for more information."
18025 (interactive "P")
18026 (cond
18027 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18028 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18029 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18030 ((org-at-item-p) (call-interactively 'org-move-item-down))
18031 (t (org-modifier-cursor-error))))
18032
18033 (defsubst org-hidden-tree-error ()
18034 (error
18035 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18036
18037 (defun org-metaleft (&optional arg)
18038 "Promote heading or move table column to left.
18039 Calls `org-do-promote' or `org-table-move-column', depending on context.
18040 With no specific context, calls the Emacs default `backward-word'.
18041 See the individual commands for more information."
18042 (interactive "P")
18043 (cond
18044 ((run-hook-with-args-until-success 'org-metaleft-hook))
18045 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18046 ((org-with-limited-levels
18047 (or (org-at-heading-p)
18048 (and (org-region-active-p)
18049 (save-excursion
18050 (goto-char (region-beginning))
18051 (org-at-heading-p)))))
18052 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18053 (call-interactively 'org-do-promote))
18054 ;; At an inline task.
18055 ((org-at-heading-p)
18056 (call-interactively 'org-inlinetask-promote))
18057 ((or (org-at-item-p)
18058 (and (org-region-active-p)
18059 (save-excursion
18060 (goto-char (region-beginning))
18061 (org-at-item-p))))
18062 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18063 (call-interactively 'org-outdent-item))
18064 (t (call-interactively 'backward-word))))
18065
18066 (defun org-metaright (&optional arg)
18067 "Demote subtree or move table column to right.
18068 Calls `org-do-demote' or `org-table-move-column', depending on context.
18069 With no specific context, calls the Emacs default `forward-word'.
18070 See the individual commands for more information."
18071 (interactive "P")
18072 (cond
18073 ((run-hook-with-args-until-success 'org-metaright-hook))
18074 ((org-at-table-p) (call-interactively 'org-table-move-column))
18075 ((org-with-limited-levels
18076 (or (org-at-heading-p)
18077 (and (org-region-active-p)
18078 (save-excursion
18079 (goto-char (region-beginning))
18080 (org-at-heading-p)))))
18081 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18082 (call-interactively 'org-do-demote))
18083 ;; At an inline task.
18084 ((org-at-heading-p)
18085 (call-interactively 'org-inlinetask-demote))
18086 ((or (org-at-item-p)
18087 (and (org-region-active-p)
18088 (save-excursion
18089 (goto-char (region-beginning))
18090 (org-at-item-p))))
18091 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18092 (call-interactively 'org-indent-item))
18093 (t (call-interactively 'forward-word))))
18094
18095 (defun org-check-for-hidden (what)
18096 "Check if there are hidden headlines/items in the current visual line.
18097 WHAT can be either `headlines' or `items'. If the current line is
18098 an outline or item heading and it has a folded subtree below it,
18099 this function returns t, nil otherwise."
18100 (let ((re (cond
18101 ((eq what 'headlines) org-outline-regexp-bol)
18102 ((eq what 'items) (org-item-beginning-re))
18103 (t (error "This should not happen"))))
18104 beg end)
18105 (save-excursion
18106 (catch 'exit
18107 (unless (org-region-active-p)
18108 (setq beg (point-at-bol))
18109 (beginning-of-line 2)
18110 (while (and (not (eobp)) ;; this is like `next-line'
18111 (get-char-property (1- (point)) 'invisible))
18112 (beginning-of-line 2))
18113 (setq end (point))
18114 (goto-char beg)
18115 (goto-char (point-at-eol))
18116 (setq end (max end (point)))
18117 (while (re-search-forward re end t)
18118 (if (get-char-property (match-beginning 0) 'invisible)
18119 (throw 'exit t))))
18120 nil))))
18121
18122 (defun org-metaup (&optional arg)
18123 "Move subtree up or move table row up.
18124 Calls `org-move-subtree-up' or `org-table-move-row' or
18125 `org-move-item-up', depending on context. See the individual commands
18126 for more information."
18127 (interactive "P")
18128 (cond
18129 ((run-hook-with-args-until-success 'org-metaup-hook))
18130 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18131 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18132 ((org-at-item-p) (call-interactively 'org-move-item-up))
18133 (t (transpose-lines 1) (beginning-of-line -1))))
18134
18135 (defun org-metadown (&optional arg)
18136 "Move subtree down or move table row down.
18137 Calls `org-move-subtree-down' or `org-table-move-row' or
18138 `org-move-item-down', depending on context. See the individual
18139 commands for more information."
18140 (interactive "P")
18141 (cond
18142 ((run-hook-with-args-until-success 'org-metadown-hook))
18143 ((org-at-table-p) (call-interactively 'org-table-move-row))
18144 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18145 ((org-at-item-p) (call-interactively 'org-move-item-down))
18146 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18147
18148 (defun org-shiftup (&optional arg)
18149 "Increase item in timestamp or increase priority of current headline.
18150 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18151 depending on context. See the individual commands for more information."
18152 (interactive "P")
18153 (cond
18154 ((run-hook-with-args-until-success 'org-shiftup-hook))
18155 ((and org-support-shift-select (org-region-active-p))
18156 (org-call-for-shift-select 'previous-line))
18157 ((org-at-timestamp-p t)
18158 (call-interactively (if org-edit-timestamp-down-means-later
18159 'org-timestamp-down 'org-timestamp-up)))
18160 ((and (not (eq org-support-shift-select 'always))
18161 org-enable-priority-commands
18162 (org-at-heading-p))
18163 (call-interactively 'org-priority-up))
18164 ((and (not org-support-shift-select) (org-at-item-p))
18165 (call-interactively 'org-previous-item))
18166 ((org-clocktable-try-shift 'up arg))
18167 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18168 (org-support-shift-select
18169 (org-call-for-shift-select 'previous-line))
18170 (t (org-shiftselect-error))))
18171
18172 (defun org-shiftdown (&optional arg)
18173 "Decrease item in timestamp or decrease priority of current headline.
18174 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18175 depending on context. See the individual commands for more information."
18176 (interactive "P")
18177 (cond
18178 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18179 ((and org-support-shift-select (org-region-active-p))
18180 (org-call-for-shift-select 'next-line))
18181 ((org-at-timestamp-p t)
18182 (call-interactively (if org-edit-timestamp-down-means-later
18183 'org-timestamp-up 'org-timestamp-down)))
18184 ((and (not (eq org-support-shift-select 'always))
18185 org-enable-priority-commands
18186 (org-at-heading-p))
18187 (call-interactively 'org-priority-down))
18188 ((and (not org-support-shift-select) (org-at-item-p))
18189 (call-interactively 'org-next-item))
18190 ((org-clocktable-try-shift 'down arg))
18191 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18192 (org-support-shift-select
18193 (org-call-for-shift-select 'next-line))
18194 (t (org-shiftselect-error))))
18195
18196 (defun org-shiftright (&optional arg)
18197 "Cycle the thing at point or in the current line, depending on context.
18198 Depending on context, this does one of the following:
18199
18200 - switch a timestamp at point one day into the future
18201 - on a headline, switch to the next TODO keyword.
18202 - on an item, switch entire list to the next bullet type
18203 - on a property line, switch to the next allowed value
18204 - on a clocktable definition line, move time block into the future"
18205 (interactive "P")
18206 (cond
18207 ((run-hook-with-args-until-success 'org-shiftright-hook))
18208 ((and org-support-shift-select (org-region-active-p))
18209 (org-call-for-shift-select 'forward-char))
18210 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18211 ((and (not (eq org-support-shift-select 'always))
18212 (org-at-heading-p))
18213 (let ((org-inhibit-logging
18214 (not org-treat-S-cursor-todo-selection-as-state-change))
18215 (org-inhibit-blocking
18216 (not org-treat-S-cursor-todo-selection-as-state-change)))
18217 (org-call-with-arg 'org-todo 'right)))
18218 ((or (and org-support-shift-select
18219 (not (eq org-support-shift-select 'always))
18220 (org-at-item-bullet-p))
18221 (and (not org-support-shift-select) (org-at-item-p)))
18222 (org-call-with-arg 'org-cycle-list-bullet nil))
18223 ((and (not (eq org-support-shift-select 'always))
18224 (org-at-property-p))
18225 (call-interactively 'org-property-next-allowed-value))
18226 ((org-clocktable-try-shift 'right arg))
18227 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18228 (org-support-shift-select
18229 (org-call-for-shift-select 'forward-char))
18230 (t (org-shiftselect-error))))
18231
18232 (defun org-shiftleft (&optional arg)
18233 "Cycle the thing at point or in the current line, depending on context.
18234 Depending on context, this does one of the following:
18235
18236 - switch a timestamp at point one day into the past
18237 - on a headline, switch to the previous TODO keyword.
18238 - on an item, switch entire list to the previous bullet type
18239 - on a property line, switch to the previous allowed value
18240 - on a clocktable definition line, move time block into the past"
18241 (interactive "P")
18242 (cond
18243 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18244 ((and org-support-shift-select (org-region-active-p))
18245 (org-call-for-shift-select 'backward-char))
18246 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18247 ((and (not (eq org-support-shift-select 'always))
18248 (org-at-heading-p))
18249 (let ((org-inhibit-logging
18250 (not org-treat-S-cursor-todo-selection-as-state-change))
18251 (org-inhibit-blocking
18252 (not org-treat-S-cursor-todo-selection-as-state-change)))
18253 (org-call-with-arg 'org-todo 'left)))
18254 ((or (and org-support-shift-select
18255 (not (eq org-support-shift-select 'always))
18256 (org-at-item-bullet-p))
18257 (and (not org-support-shift-select) (org-at-item-p)))
18258 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18259 ((and (not (eq org-support-shift-select 'always))
18260 (org-at-property-p))
18261 (call-interactively 'org-property-previous-allowed-value))
18262 ((org-clocktable-try-shift 'left arg))
18263 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18264 (org-support-shift-select
18265 (org-call-for-shift-select 'backward-char))
18266 (t (org-shiftselect-error))))
18267
18268 (defun org-shiftcontrolright ()
18269 "Switch to next TODO set."
18270 (interactive)
18271 (cond
18272 ((and org-support-shift-select (org-region-active-p))
18273 (org-call-for-shift-select 'forward-word))
18274 ((and (not (eq org-support-shift-select 'always))
18275 (org-at-heading-p))
18276 (org-call-with-arg 'org-todo 'nextset))
18277 (org-support-shift-select
18278 (org-call-for-shift-select 'forward-word))
18279 (t (org-shiftselect-error))))
18280
18281 (defun org-shiftcontrolleft ()
18282 "Switch to previous TODO set."
18283 (interactive)
18284 (cond
18285 ((and org-support-shift-select (org-region-active-p))
18286 (org-call-for-shift-select 'backward-word))
18287 ((and (not (eq org-support-shift-select 'always))
18288 (org-at-heading-p))
18289 (org-call-with-arg 'org-todo 'previousset))
18290 (org-support-shift-select
18291 (org-call-for-shift-select 'backward-word))
18292 (t (org-shiftselect-error))))
18293
18294 (defun org-shiftcontrolup ()
18295 "Change timestamps synchronously up in CLOCK log lines."
18296 (interactive)
18297 (cond ((and (not org-support-shift-select)
18298 (org-at-clock-log-p)
18299 (org-at-timestamp-p t))
18300 (org-clock-timestamps-up))
18301 (t (org-shiftselect-error))))
18302
18303 (defun org-shiftcontroldown ()
18304 "Change timestamps synchronously down in CLOCK log lines."
18305 (interactive)
18306 (cond ((and (not org-support-shift-select)
18307 (org-at-clock-log-p)
18308 (org-at-timestamp-p t))
18309 (org-clock-timestamps-down))
18310 (t (org-shiftselect-error))))
18311
18312 (defun org-ctrl-c-ret ()
18313 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18314 (interactive)
18315 (cond
18316 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18317 (t (call-interactively 'org-insert-heading))))
18318
18319 (defun org-find-visible ()
18320 (let ((s (point)))
18321 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18322 (get-char-property s 'invisible)))
18323 s))
18324 (defun org-find-invisible ()
18325 (let ((s (point)))
18326 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18327 (not (get-char-property s 'invisible))))
18328 s))
18329
18330 (defun org-copy-visible (beg end)
18331 "Copy the visible parts of the region."
18332 (interactive "r")
18333 (let (snippets s)
18334 (save-excursion
18335 (save-restriction
18336 (narrow-to-region beg end)
18337 (setq s (goto-char (point-min)))
18338 (while (not (= (point) (point-max)))
18339 (goto-char (org-find-invisible))
18340 (push (buffer-substring s (point)) snippets)
18341 (setq s (goto-char (org-find-visible))))))
18342 (kill-new (apply 'concat (nreverse snippets)))))
18343
18344 (defun org-copy-special ()
18345 "Copy region in table or copy current subtree.
18346 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18347 See the individual commands for more information."
18348 (interactive)
18349 (call-interactively
18350 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18351
18352 (defun org-cut-special ()
18353 "Cut region in table or cut current subtree.
18354 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18355 See the individual commands for more information."
18356 (interactive)
18357 (call-interactively
18358 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18359
18360 (defun org-paste-special (arg)
18361 "Paste rectangular region into table, or past subtree relative to level.
18362 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18363 See the individual commands for more information."
18364 (interactive "P")
18365 (if (org-at-table-p)
18366 (org-table-paste-rectangle)
18367 (org-paste-subtree arg)))
18368
18369 (defun org-edit-special (&optional arg)
18370 "Call a special editor for the stuff at point.
18371 When at a table, call the formula editor with `org-table-edit-formulas'.
18372 When at the first line of an src example, call `org-edit-src-code'.
18373 When in an #+include line, visit the include file. Otherwise call
18374 `ffap' to visit the file at point."
18375 (interactive)
18376 ;; possibly prep session before editing source
18377 (when arg
18378 (let* ((info (org-babel-get-src-block-info))
18379 (lang (nth 0 info))
18380 (params (nth 2 info))
18381 (session (cdr (assoc :session params))))
18382 (when (and info session) ;; we are in a source-code block with a session
18383 (funcall
18384 (intern (concat "org-babel-prep-session:" lang)) session params))))
18385 (cond ;; proceed with `org-edit-special'
18386 ((save-excursion
18387 (beginning-of-line 1)
18388 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18389 (find-file (org-trim (match-string 1))))
18390 ((org-edit-src-code))
18391 ((org-edit-fixed-width-region))
18392 ((org-at-table.el-p)
18393 (org-edit-src-code))
18394 ((or (org-at-table-p)
18395 (save-excursion
18396 (beginning-of-line 1)
18397 (looking-at "[ \t]*#\\+TBLFM:")))
18398 (call-interactively 'org-table-edit-formulas))
18399 (t (call-interactively 'ffap))))
18400
18401 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18402 (defun org-ctrl-c-ctrl-c (&optional arg)
18403 "Set tags in headline, or update according to changed information at point.
18404
18405 This command does many different things, depending on context:
18406
18407 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18408 this is what we do.
18409
18410 - If the cursor is on a statistics cookie, update it.
18411
18412 - If the cursor is in a headline, prompt for tags and insert them
18413 into the current line, aligned to `org-tags-column'. When called
18414 with prefix arg, realign all tags in the current buffer.
18415
18416 - If the cursor is in one of the special #+KEYWORD lines, this
18417 triggers scanning the buffer for these lines and updating the
18418 information.
18419
18420 - If the cursor is inside a table, realign the table. This command
18421 works even if the automatic table editor has been turned off.
18422
18423 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18424 the entire table.
18425
18426 - If the cursor is at a footnote reference or definition, jump to
18427 the corresponding definition or references, respectively.
18428
18429 - If the cursor is a the beginning of a dynamic block, update it.
18430
18431 - If the current buffer is a capture buffer, close note and file it.
18432
18433 - If the cursor is on a <<<target>>>, update radio targets and
18434 corresponding links in this buffer.
18435
18436 - If the cursor is on a numbered item in a plain list, renumber the
18437 ordered list.
18438
18439 - If the cursor is on a checkbox, toggle it.
18440
18441 - If the cursor is on a code block, evaluate it. The variable
18442 `org-confirm-babel-evaluate' can be used to control prompting
18443 before code block evaluation, by default every code block
18444 evaluation requires confirmation. Code block evaluation can be
18445 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18446 (interactive "P")
18447 (let ((org-enable-table-editor t))
18448 (cond
18449 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18450 org-occur-highlights
18451 org-latex-fragment-image-overlays)
18452 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18453 (org-remove-occur-highlights)
18454 (org-remove-latex-fragment-image-overlays)
18455 (message "Temporary highlights/overlays removed from current buffer"))
18456 ((and (local-variable-p 'org-finish-function (current-buffer))
18457 (fboundp org-finish-function))
18458 (funcall org-finish-function))
18459 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18460 ((org-in-regexp org-ts-regexp-both)
18461 (org-timestamp-change 0 'day))
18462 ((or (looking-at org-property-start-re)
18463 (org-at-property-p))
18464 (call-interactively 'org-property-action))
18465 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18466 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18467 (or (org-at-heading-p) (org-at-item-p)))
18468 (call-interactively 'org-update-statistics-cookies))
18469 ((org-at-heading-p) (call-interactively 'org-set-tags))
18470 ((org-at-table.el-p)
18471 (message "Use C-c ' to edit table.el tables"))
18472 ((org-at-table-p)
18473 (org-table-maybe-eval-formula)
18474 (if arg
18475 (call-interactively 'org-table-recalculate)
18476 (org-table-maybe-recalculate-line))
18477 (call-interactively 'org-table-align)
18478 (orgtbl-send-table 'maybe))
18479 ((or (org-footnote-at-reference-p)
18480 (org-footnote-at-definition-p))
18481 (call-interactively 'org-footnote-action))
18482 ((org-at-item-checkbox-p)
18483 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18484 ;; list only if at top item.
18485 (let* ((cbox (match-string 1))
18486 (struct (org-list-struct))
18487 (old-struct (copy-tree struct))
18488 (parents (org-list-parents-alist struct))
18489 (orderedp (org-entry-get nil "ORDERED"))
18490 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18491 block-item)
18492 ;; Use a light version of `org-toggle-checkbox' to avoid
18493 ;; computing list structure twice.
18494 (let ((new-box (cond
18495 ((equal arg '(16)) "[-]")
18496 ((equal arg '(4)) nil)
18497 ((equal "[X]" cbox) "[ ]")
18498 (t "[X]"))))
18499 (if (and firstp arg)
18500 ;; If at first item of sub-list, remove check-box from
18501 ;; every item at the same level.
18502 (mapc
18503 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18504 (org-list-get-all-items
18505 (point-at-bol) struct (org-list-prevs-alist struct)))
18506 (org-list-set-checkbox (point-at-bol) struct new-box)))
18507 ;; Replicate `org-list-write-struct', while grabbing a return
18508 ;; value from `org-list-struct-fix-box'.
18509 (org-list-struct-fix-ind struct parents 2)
18510 (org-list-struct-fix-item-end struct)
18511 (let ((prevs (org-list-prevs-alist struct)))
18512 (org-list-struct-fix-bul struct prevs)
18513 (org-list-struct-fix-ind struct parents)
18514 (setq block-item
18515 (org-list-struct-fix-box struct parents prevs orderedp)))
18516 (org-list-struct-apply-struct struct old-struct)
18517 (org-update-checkbox-count-maybe)
18518 (when block-item
18519 (message
18520 "Checkboxes were removed due to unchecked box at line %d"
18521 (org-current-line block-item)))
18522 (when firstp (org-list-send-list 'maybe))))
18523 ((org-at-item-p)
18524 ;; Cursor at an item: repair list. Do checkbox related actions
18525 ;; only if function was called with an argument. Send list only
18526 ;; if at top item.
18527 (let* ((struct (org-list-struct))
18528 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18529 old-struct)
18530 (when arg
18531 (setq old-struct (copy-tree struct))
18532 (if firstp
18533 ;; If at first item of sub-list, add check-box to every
18534 ;; item at the same level.
18535 (mapc
18536 (lambda (pos)
18537 (unless (org-list-get-checkbox pos struct)
18538 (org-list-set-checkbox pos struct "[ ]")))
18539 (org-list-get-all-items
18540 (point-at-bol) struct (org-list-prevs-alist struct)))
18541 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18542 (org-list-write-struct
18543 struct (org-list-parents-alist struct) old-struct)
18544 (when arg (org-update-checkbox-count-maybe))
18545 (when firstp (org-list-send-list 'maybe))))
18546 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18547 ;; Dynamic block
18548 (beginning-of-line 1)
18549 (save-excursion (org-update-dblock)))
18550 ((save-excursion
18551 (beginning-of-line 1)
18552 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18553 (cond
18554 ((equal (match-string 1) "TBLFM")
18555 ;; Recalculate the table before this line
18556 (save-excursion
18557 (beginning-of-line 1)
18558 (skip-chars-backward " \r\n\t")
18559 (if (org-at-table-p)
18560 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18561 (t
18562 (let ((org-inhibit-startup-visibility-stuff t)
18563 (org-startup-align-all-tables nil))
18564 (when (boundp 'org-table-coordinate-overlays)
18565 (mapc 'delete-overlay org-table-coordinate-overlays)
18566 (setq org-table-coordinate-overlays nil))
18567 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18568 (message "Local setup has been refreshed"))))
18569 ((org-clock-update-time-maybe))
18570 (t
18571 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18572 (error "C-c C-c can do nothing useful at this location"))))))
18573
18574 (defun org-mode-restart ()
18575 "Restart Org-mode, to scan again for special lines.
18576 Also updates the keyword regular expressions."
18577 (interactive)
18578 (org-mode)
18579 (message "Org-mode restarted"))
18580
18581 (defun org-kill-note-or-show-branches ()
18582 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18583 (interactive)
18584 (if (not org-finish-function)
18585 (progn
18586 (hide-subtree)
18587 (call-interactively 'show-branches))
18588 (let ((org-note-abort t))
18589 (funcall org-finish-function))))
18590
18591 (defun org-return (&optional indent)
18592 "Goto next table row or insert a newline.
18593 Calls `org-table-next-row' or `newline', depending on context.
18594 See the individual commands for more information."
18595 (interactive)
18596 (cond
18597 ((bobp) (if indent (newline-and-indent) (newline)))
18598 ((org-at-table-p)
18599 (org-table-justify-field-maybe)
18600 (call-interactively 'org-table-next-row))
18601 ;; when `newline-and-indent' is called within a list, make sure
18602 ;; text moved stays inside the item.
18603 ((and (org-in-item-p) indent)
18604 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18605 (progn
18606 (save-match-data (newline))
18607 (org-indent-line-to (length (match-string 0))))
18608 (let ((ind (org-get-indentation)))
18609 (newline)
18610 (if (org-looking-back org-list-end-re)
18611 (org-indent-line-function)
18612 (org-indent-line-to ind)))))
18613 ((and org-return-follows-link
18614 (let ((tprop (get-text-property (point) 'face)))
18615 (or (eq tprop 'org-link)
18616 (and (listp tprop) (memq 'org-link tprop)))))
18617 (call-interactively 'org-open-at-point))
18618 ((and (org-at-heading-p)
18619 (looking-at
18620 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18621 (org-show-entry)
18622 (end-of-line 1)
18623 (newline))
18624 (t (if indent (newline-and-indent) (newline)))))
18625
18626 (defun org-return-indent ()
18627 "Goto next table row or insert a newline and indent.
18628 Calls `org-table-next-row' or `newline-and-indent', depending on
18629 context. See the individual commands for more information."
18630 (interactive)
18631 (org-return t))
18632
18633 (defun org-ctrl-c-star ()
18634 "Compute table, or change heading status of lines.
18635 Calls `org-table-recalculate' or `org-toggle-heading',
18636 depending on context."
18637 (interactive)
18638 (cond
18639 ((org-at-table-p)
18640 (call-interactively 'org-table-recalculate))
18641 (t
18642 ;; Convert all lines in region to list items
18643 (call-interactively 'org-toggle-heading))))
18644
18645 (defun org-ctrl-c-minus ()
18646 "Insert separator line in table or modify bullet status of line.
18647 Also turns a plain line or a region of lines into list items.
18648 Calls `org-table-insert-hline', `org-toggle-item', or
18649 `org-cycle-list-bullet', depending on context."
18650 (interactive)
18651 (cond
18652 ((org-at-table-p)
18653 (call-interactively 'org-table-insert-hline))
18654 ((org-region-active-p)
18655 (call-interactively 'org-toggle-item))
18656 ((org-in-item-p)
18657 (call-interactively 'org-cycle-list-bullet))
18658 (t
18659 (call-interactively 'org-toggle-item))))
18660
18661 (defun org-toggle-item (arg)
18662 "Convert headings or normal lines to items, items to normal lines.
18663 If there is no active region, only the current line is considered.
18664
18665 If the first non blank line in the region is an headline, convert
18666 all headlines to items, shifting text accordingly.
18667
18668 If it is an item, convert all items to normal lines.
18669
18670 If it is normal text, change region into an item. With a prefix
18671 argument ARG, change each line in region into an item."
18672 (interactive "P")
18673 (let ((shift-text
18674 (function
18675 ;; Shift text in current section to IND, from point to END.
18676 ;; The function leaves point to END line.
18677 (lambda (ind end)
18678 (let ((min-i 1000) (end (copy-marker end)))
18679 ;; First determine the minimum indentation (MIN-I) of
18680 ;; the text.
18681 (save-excursion
18682 (catch 'exit
18683 (while (< (point) end)
18684 (let ((i (org-get-indentation)))
18685 (cond
18686 ;; Skip blank lines and inline tasks.
18687 ((looking-at "^[ \t]*$"))
18688 ((looking-at org-outline-regexp-bol))
18689 ;; We can't find less than 0 indentation.
18690 ((zerop i) (throw 'exit (setq min-i 0)))
18691 ((< i min-i) (setq min-i i))))
18692 (forward-line))))
18693 ;; Then indent each line so that a line indented to
18694 ;; MIN-I becomes indented to IND. Ignore blank lines
18695 ;; and inline tasks in the process.
18696 (let ((delta (- ind min-i)))
18697 (while (< (point) end)
18698 (unless (or (looking-at "^[ \t]*$")
18699 (looking-at org-outline-regexp-bol))
18700 (org-indent-line-to (+ (org-get-indentation) delta)))
18701 (forward-line)))))))
18702 (skip-blanks
18703 (function
18704 ;; Return beginning of first non-blank line, starting from
18705 ;; line at POS.
18706 (lambda (pos)
18707 (save-excursion
18708 (goto-char pos)
18709 (skip-chars-forward " \r\t\n")
18710 (point-at-bol)))))
18711 beg end)
18712 ;; Determine boundaries of changes.
18713 (if (org-region-active-p)
18714 (setq beg (funcall skip-blanks (region-beginning))
18715 end (copy-marker (region-end)))
18716 (setq beg (funcall skip-blanks (point-at-bol))
18717 end (copy-marker (point-at-eol))))
18718 ;; Depending on the starting line, choose an action on the text
18719 ;; between BEG and END.
18720 (org-with-limited-levels
18721 (save-excursion
18722 (goto-char beg)
18723 (cond
18724 ;; Case 1. Start at an item: de-itemize. Note that it only
18725 ;; happens when a region is active: `org-ctrl-c-minus'
18726 ;; would call `org-cycle-list-bullet' otherwise.
18727 ((org-at-item-p)
18728 (while (< (point) end)
18729 (when (org-at-item-p)
18730 (skip-chars-forward " \t")
18731 (delete-region (point) (match-end 0)))
18732 (forward-line)))
18733 ;; Case 2. Start at an heading: convert to items.
18734 ((org-at-heading-p)
18735 (let* ((bul (org-list-bullet-string "-"))
18736 (bul-len (length bul))
18737 ;; Indentation of the first heading. It should be
18738 ;; relative to the indentation of its parent, if any.
18739 (start-ind (save-excursion
18740 (cond
18741 ((not org-adapt-indentation) 0)
18742 ((not (outline-previous-heading)) 0)
18743 (t (length (match-string 0))))))
18744 ;; Level of first heading. Further headings will be
18745 ;; compared to it to determine hierarchy in the list.
18746 (ref-level (org-reduced-level (org-outline-level))))
18747 (while (< (point) end)
18748 (let* ((level (org-reduced-level (org-outline-level)))
18749 (delta (max 0 (- level ref-level))))
18750 ;; If current headline is less indented than the first
18751 ;; one, set it as reference, in order to preserve
18752 ;; subtrees.
18753 (when (< level ref-level) (setq ref-level level))
18754 (replace-match bul t t)
18755 (org-indent-line-to (+ start-ind (* delta bul-len)))
18756 ;; Ensure all text down to END (or SECTION-END) belongs
18757 ;; to the newly created item.
18758 (let ((section-end (save-excursion
18759 (or (outline-next-heading) (point)))))
18760 (forward-line)
18761 (funcall shift-text
18762 (+ start-ind (* (1+ delta) bul-len))
18763 (min end section-end)))))))
18764 ;; Case 3. Normal line with ARG: turn each non-item line into
18765 ;; an item.
18766 (arg
18767 (while (< (point) end)
18768 (unless (or (org-at-heading-p) (org-at-item-p))
18769 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18770 (replace-match
18771 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18772 (forward-line)))
18773 ;; Case 4. Normal line without ARG: make the first line of
18774 ;; region an item, and shift indentation of others
18775 ;; lines to set them as item's body.
18776 (t (let* ((bul (org-list-bullet-string "-"))
18777 (bul-len (length bul))
18778 (ref-ind (org-get-indentation)))
18779 (skip-chars-forward " \t")
18780 (insert bul)
18781 (forward-line)
18782 (while (< (point) end)
18783 ;; Ensure that lines less indented than first one
18784 ;; still get included in item body.
18785 (funcall shift-text
18786 (+ ref-ind bul-len)
18787 (min end (save-excursion (or (outline-next-heading)
18788 (point)))))
18789 (forward-line)))))))))
18790
18791 (defun org-toggle-heading (&optional nstars)
18792 "Convert headings to normal text, or items or text to headings.
18793 If there is no active region, only the current line is considered.
18794
18795 If the first non blank line is an headline, remove the stars from
18796 all headlines in the region.
18797
18798 If it is a plain list item, turn all plain list items into headings.
18799
18800 If it is a normal line, turn each and every normal line (i.e. not
18801 an heading or an item) in the region into a heading.
18802
18803 When converting a line into a heading, the number of stars is chosen
18804 such that the lines become children of the current entry. However,
18805 when a prefix argument is given, its value determines the number of
18806 stars to add."
18807 (interactive "P")
18808 (let ((skip-blanks
18809 (function
18810 ;; Return beginning of first non-blank line, starting from
18811 ;; line at POS.
18812 (lambda (pos)
18813 (save-excursion
18814 (goto-char pos)
18815 (skip-chars-forward " \r\t\n")
18816 (point-at-bol)))))
18817 beg end)
18818 ;; Determine boundaries of changes. If region ends at a bol, do
18819 ;; not consider the last line to be in the region.
18820 (if (org-region-active-p)
18821 (setq beg (funcall skip-blanks (region-beginning))
18822 end (copy-marker (save-excursion
18823 (goto-char (region-end))
18824 (if (bolp) (point) (point-at-eol)))))
18825 (setq beg (funcall skip-blanks (point-at-bol))
18826 end (copy-marker (point-at-eol))))
18827 ;; Ensure inline tasks don't count as headings.
18828 (org-with-limited-levels
18829 (save-excursion
18830 (goto-char beg)
18831 (cond
18832 ;; Case 1. Started at an heading: de-star headings.
18833 ((org-at-heading-p)
18834 (while (< (point) end)
18835 (when (org-at-heading-p t)
18836 (looking-at org-outline-regexp) (replace-match ""))
18837 (forward-line)))
18838 ;; Case 2. Started at an item: change items into headlines.
18839 ;; One star will be added by `org-list-to-subtree'.
18840 ((org-at-item-p)
18841 (let* ((stars (make-string
18842 (if nstars
18843 ;; subtract the star that will be added again by
18844 ;; `org-list-to-subtree'
18845 (1- (prefix-numeric-value current-prefix-arg))
18846 (or (org-current-level) 0))
18847 ?*))
18848 (add-stars
18849 (cond (nstars "") ; stars from prefix only
18850 ((equal stars "") "") ; before first heading
18851 (org-odd-levels-only "*") ; inside heading, odd
18852 (t "")))) ; inside heading, oddeven
18853 (while (< (point) end)
18854 (when (org-at-item-p)
18855 ;; Pay attention to cases when region ends before list.
18856 (let* ((struct (org-list-struct))
18857 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18858 (save-restriction
18859 (narrow-to-region (point) list-end)
18860 (insert
18861 (org-list-to-subtree
18862 (org-list-parse-list t)
18863 '(:istart (concat stars add-stars (funcall get-stars depth))
18864 :icount (concat stars add-stars (funcall get-stars depth))))))))
18865 (forward-line))))
18866 ;; Case 3. Started at normal text: make every line an heading,
18867 ;; skipping headlines and items.
18868 (t (let* ((stars (make-string
18869 (if nstars
18870 (prefix-numeric-value current-prefix-arg)
18871 (or (org-current-level) 0))
18872 ?*))
18873 (add-stars
18874 (cond (nstars "") ; stars from prefix only
18875 ((equal stars "") "*") ; before first heading
18876 (org-odd-levels-only "**") ; inside heading, odd
18877 (t "*"))) ; inside heading, oddeven
18878 (rpl (concat stars add-stars " ")))
18879 (while (< (point) end)
18880 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18881 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18882 (replace-match (concat rpl (match-string 2))))
18883 (forward-line)))))))))
18884
18885 (defun org-meta-return (&optional arg)
18886 "Insert a new heading or wrap a region in a table.
18887 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18888 See the individual commands for more information."
18889 (interactive "P")
18890 (cond
18891 ((run-hook-with-args-until-success 'org-metareturn-hook))
18892 ((org-at-table-p)
18893 (call-interactively 'org-table-wrap-region))
18894 (t (call-interactively 'org-insert-heading))))
18895
18896 ;;; Menu entries
18897
18898 ;; Define the Org-mode menus
18899 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18900 '("Tbl"
18901 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18902 ["Next Field" org-cycle (org-at-table-p)]
18903 ["Previous Field" org-shifttab (org-at-table-p)]
18904 ["Next Row" org-return (org-at-table-p)]
18905 "--"
18906 ["Blank Field" org-table-blank-field (org-at-table-p)]
18907 ["Edit Field" org-table-edit-field (org-at-table-p)]
18908 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18909 "--"
18910 ("Column"
18911 ["Move Column Left" org-metaleft (org-at-table-p)]
18912 ["Move Column Right" org-metaright (org-at-table-p)]
18913 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18914 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18915 ("Row"
18916 ["Move Row Up" org-metaup (org-at-table-p)]
18917 ["Move Row Down" org-metadown (org-at-table-p)]
18918 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18919 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18920 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18921 "--"
18922 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18923 ("Rectangle"
18924 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18925 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18926 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18927 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18928 "--"
18929 ("Calculate"
18930 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18931 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18932 ["Edit Formulas" org-edit-special (org-at-table-p)]
18933 "--"
18934 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18935 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18936 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18937 "--"
18938 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18939 "--"
18940 ["Sum Column/Rectangle" org-table-sum
18941 (or (org-at-table-p) (org-region-active-p))]
18942 ["Which Column?" org-table-current-column (org-at-table-p)])
18943 ["Debug Formulas"
18944 org-table-toggle-formula-debugger
18945 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18946 ["Show Col/Row Numbers"
18947 org-table-toggle-coordinate-overlays
18948 :style toggle
18949 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18950 "--"
18951 ["Create" org-table-create (and (not (org-at-table-p))
18952 org-enable-table-editor)]
18953 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18954 ["Import from File" org-table-import (not (org-at-table-p))]
18955 ["Export to File" org-table-export (org-at-table-p)]
18956 "--"
18957 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18958
18959 (easy-menu-define org-org-menu org-mode-map "Org menu"
18960 '("Org"
18961 ("Show/Hide"
18962 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18963 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18964 ["Sparse Tree..." org-sparse-tree t]
18965 ["Reveal Context" org-reveal t]
18966 ["Show All" show-all t]
18967 "--"
18968 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18969 "--"
18970 ["New Heading" org-insert-heading t]
18971 ("Navigate Headings"
18972 ["Up" outline-up-heading t]
18973 ["Next" outline-next-visible-heading t]
18974 ["Previous" outline-previous-visible-heading t]
18975 ["Next Same Level" outline-forward-same-level t]
18976 ["Previous Same Level" outline-backward-same-level t]
18977 "--"
18978 ["Jump" org-goto t])
18979 ("Edit Structure"
18980 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18981 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18982 "--"
18983 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18984 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18985 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18986 "--"
18987 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18988 "--"
18989 ["Copy visible text" org-copy-visible t]
18990 "--"
18991 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18992 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18993 ["Demote Heading" org-metaright (not (org-at-table-p))]
18994 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18995 "--"
18996 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18997 "--"
18998 ["Convert to odd levels" org-convert-to-odd-levels t]
18999 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19000 ("Editing"
19001 ["Emphasis..." org-emphasize t]
19002 ["Edit Source Example" org-edit-special t]
19003 "--"
19004 ["Footnote new/jump" org-footnote-action t]
19005 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19006 ("Archive"
19007 ["Archive (default method)" org-archive-subtree-default t]
19008 "--"
19009 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19010 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19011 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19012 )
19013 "--"
19014 ("Hyperlinks"
19015 ["Store Link (Global)" org-store-link t]
19016 ["Find existing link to here" org-occur-link-in-agenda-files t]
19017 ["Insert Link" org-insert-link t]
19018 ["Follow Link" org-open-at-point t]
19019 "--"
19020 ["Next link" org-next-link t]
19021 ["Previous link" org-previous-link t]
19022 "--"
19023 ["Descriptive Links"
19024 org-toggle-link-display
19025 :style radio
19026 :selected org-descriptive-links
19027 ]
19028 ["Literal Links"
19029 org-toggle-link-display
19030 :style radio
19031 :selected (not org-descriptive-links)])
19032 "--"
19033 ("TODO Lists"
19034 ["TODO/DONE/-" org-todo t]
19035 ("Select keyword"
19036 ["Next keyword" org-shiftright (org-at-heading-p)]
19037 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19038 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19039 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19040 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19041 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19042 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19043 "--"
19044 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19045 :selected org-enforce-todo-dependencies :style toggle :active t]
19046 "Settings for tree at point"
19047 ["Do Children sequentially" org-toggle-ordered-property :style radio
19048 :selected (org-entry-get nil "ORDERED")
19049 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19050 ["Do Children parallel" org-toggle-ordered-property :style radio
19051 :selected (not (org-entry-get nil "ORDERED"))
19052 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19053 "--"
19054 ["Set Priority" org-priority t]
19055 ["Priority Up" org-shiftup t]
19056 ["Priority Down" org-shiftdown t]
19057 "--"
19058 ["Get news from all feeds" org-feed-update-all t]
19059 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19060 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19061 ("TAGS and Properties"
19062 ["Set Tags" org-set-tags-command t]
19063 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19064 "--"
19065 ["Set property" org-set-property t]
19066 ["Column view of properties" org-columns t]
19067 ["Insert Column View DBlock" org-insert-columns-dblock t])
19068 ("Dates and Scheduling"
19069 ["Timestamp" org-time-stamp t]
19070 ["Timestamp (inactive)" org-time-stamp-inactive t]
19071 ("Change Date"
19072 ["1 Day Later" org-shiftright t]
19073 ["1 Day Earlier" org-shiftleft t]
19074 ["1 ... Later" org-shiftup t]
19075 ["1 ... Earlier" org-shiftdown t])
19076 ["Compute Time Range" org-evaluate-time-range t]
19077 ["Schedule Item" org-schedule t]
19078 ["Deadline" org-deadline t]
19079 "--"
19080 ["Custom time format" org-toggle-time-stamp-overlays
19081 :style radio :selected org-display-custom-times]
19082 "--"
19083 ["Goto Calendar" org-goto-calendar t]
19084 ["Date from Calendar" org-date-from-calendar t]
19085 "--"
19086 ["Start/Restart Timer" org-timer-start t]
19087 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19088 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19089 ["Insert Timer String" org-timer t]
19090 ["Insert Timer Item" org-timer-item t])
19091 ("Logging work"
19092 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19093 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19094 ["Clock out" org-clock-out t]
19095 ["Clock cancel" org-clock-cancel t]
19096 "--"
19097 ["Mark as default task" org-clock-mark-default-task t]
19098 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19099 ["Goto running clock" org-clock-goto t]
19100 "--"
19101 ["Display times" org-clock-display t]
19102 ["Create clock table" org-clock-report t]
19103 "--"
19104 ["Record DONE time"
19105 (progn (setq org-log-done (not org-log-done))
19106 (message "Switching to %s will %s record a timestamp"
19107 (car org-done-keywords)
19108 (if org-log-done "automatically" "not")))
19109 :style toggle :selected org-log-done])
19110 "--"
19111 ["Agenda Command..." org-agenda t]
19112 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19113 ("File List for Agenda")
19114 ("Special views current file"
19115 ["TODO Tree" org-show-todo-tree t]
19116 ["Check Deadlines" org-check-deadlines t]
19117 ["Timeline" org-timeline t]
19118 ["Tags/Property tree" org-match-sparse-tree t])
19119 "--"
19120 ["Export/Publish..." org-export t]
19121 ("LaTeX"
19122 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19123 :selected org-cdlatex-mode]
19124 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19125 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19126 ["Modify math symbol" org-cdlatex-math-modify
19127 (org-inside-LaTeX-fragment-p)]
19128 ["Insert citation" org-reftex-citation t]
19129 "--"
19130 ["Template for BEAMER" (progn (require 'org-beamer)
19131 (org-insert-beamer-options-template)) t])
19132 "--"
19133 ("MobileOrg"
19134 ["Push Files and Views" org-mobile-push t]
19135 ["Get Captured and Flagged" org-mobile-pull t]
19136 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19137 "--"
19138 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19139 "--"
19140 ("Documentation"
19141 ["Show Version" org-version t]
19142 ["Info Documentation" org-info t])
19143 ("Customize"
19144 ["Browse Org Group" org-customize t]
19145 "--"
19146 ["Expand This Menu" org-create-customize-menu
19147 (fboundp 'customize-menu-create)])
19148 ["Send bug report" org-submit-bug-report t]
19149 "--"
19150 ("Refresh/Reload"
19151 ["Refresh setup current buffer" org-mode-restart t]
19152 ["Reload Org (after update)" org-reload t]
19153 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19154 ))
19155
19156 (defun org-info (&optional node)
19157 "Read documentation for Org-mode in the info system.
19158 With optional NODE, go directly to that node."
19159 (interactive)
19160 (info (format "(org)%s" (or node ""))))
19161
19162 ;;;###autoload
19163 (defun org-submit-bug-report ()
19164 "Submit a bug report on Org-mode via mail.
19165
19166 Don't hesitate to report any problems or inaccurate documentation.
19167
19168 If you don't have setup sending mail from (X)Emacs, please copy the
19169 output buffer into your mail program, as it gives us important
19170 information about your Org-mode version and configuration."
19171 (interactive)
19172 (require 'reporter)
19173 (org-load-modules-maybe)
19174 (org-require-autoloaded-modules)
19175 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19176 (reporter-submit-bug-report
19177 "emacs-orgmode@gnu.org"
19178 (org-version)
19179 (let (list)
19180 (save-window-excursion
19181 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19182 (delete-other-windows)
19183 (erase-buffer)
19184 (insert "You are about to submit a bug report to the Org-mode mailing list.
19185
19186 We would like to add your full Org-mode and Outline configuration to the
19187 bug report. This greatly simplifies the work of the maintainer and
19188 other experts on the mailing list.
19189
19190 HOWEVER, some variables you have customized may contain private
19191 information. The names of customers, colleagues, or friends, might
19192 appear in the form of file names, tags, todo states, or search strings.
19193 If you answer yes to the prompt, you might want to check and remove
19194 such private information before sending the email.")
19195 (add-text-properties (point-min) (point-max) '(face org-warning))
19196 (when (yes-or-no-p "Include your Org-mode configuration ")
19197 (mapatoms
19198 (lambda (v)
19199 (and (boundp v)
19200 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19201 (or (and (symbol-value v)
19202 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19203 (and
19204 (get v 'custom-type) (get v 'standard-value)
19205 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19206 (push v list)))))
19207 (kill-buffer (get-buffer "*Warn about privacy*"))
19208 list))
19209 nil nil
19210 "Remember to cover the basics, that is, what you expected to happen and
19211 what in fact did happen. You don't know how to make a good report? See
19212
19213 http://orgmode.org/manual/Feedback.html#Feedback
19214
19215 Your bug report will be posted to the Org-mode mailing list.
19216 ------------------------------------------------------------------------")
19217 (save-excursion
19218 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19219 (replace-match "\\1Bug: \\3 [\\2]")))))
19220
19221
19222 (defun org-install-agenda-files-menu ()
19223 (let ((bl (buffer-list)))
19224 (save-excursion
19225 (while bl
19226 (set-buffer (pop bl))
19227 (if (eq major-mode 'org-mode) (setq bl nil)))
19228 (when (eq major-mode 'org-mode)
19229 (easy-menu-change
19230 '("Org") "File List for Agenda"
19231 (append
19232 (list
19233 ["Edit File List" (org-edit-agenda-file-list) t]
19234 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19235 ["Remove Current File from List" org-remove-file t]
19236 ["Cycle through agenda files" org-cycle-agenda-files t]
19237 ["Occur in all agenda files" org-occur-in-agenda-files t]
19238 "--")
19239 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19240
19241 ;;;; Documentation
19242
19243 ;;;###autoload
19244 (defun org-require-autoloaded-modules ()
19245 (interactive)
19246 (mapc 'require
19247 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19248 org-docbook org-exp org-html org-icalendar
19249 org-id org-latex
19250 org-publish org-remember org-table
19251 org-timer org-xoxo)))
19252
19253 ;;;###autoload
19254 (defun org-reload (&optional uncompiled)
19255 "Reload all org lisp files.
19256 With prefix arg UNCOMPILED, load the uncompiled versions."
19257 (interactive "P")
19258 (require 'find-func)
19259 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19260 (dir-org (file-name-directory (org-find-library-name "org")))
19261 (dir-org-contrib (ignore-errors
19262 (file-name-directory
19263 (org-find-library-name "org-contribdir"))))
19264 (babel-files
19265 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19266 (append (list nil "comint" "eval" "exp" "keys"
19267 "lob" "ref" "table" "tangle")
19268 (delq nil
19269 (mapcar
19270 (lambda (lang)
19271 (when (cdr lang) (symbol-name (car lang))))
19272 org-babel-load-languages)))))
19273 (files
19274 (append (directory-files dir-org t file-re)
19275 babel-files
19276 (and dir-org-contrib
19277 (directory-files dir-org-contrib t file-re))))
19278 (remove-re (concat (if (featurep 'xemacs)
19279 "org-colview" "org-colview-xemacs")
19280 "\\'")))
19281 (setq files (mapcar 'file-name-sans-extension files))
19282 (setq files (mapcar
19283 (lambda (x) (if (string-match remove-re x) nil x))
19284 files))
19285 (setq files (delq nil files))
19286 (mapc
19287 (lambda (f)
19288 (when (featurep (intern (file-name-nondirectory f)))
19289 (if (and (not uncompiled)
19290 (file-exists-p (concat f ".elc")))
19291 (load (concat f ".elc") nil nil t)
19292 (load (concat f ".el") nil nil t))))
19293 files))
19294 (org-version))
19295
19296 ;;;###autoload
19297 (defun org-customize ()
19298 "Call the customize function with org as argument."
19299 (interactive)
19300 (org-load-modules-maybe)
19301 (org-require-autoloaded-modules)
19302 (customize-browse 'org))
19303
19304 (defun org-create-customize-menu ()
19305 "Create a full customization menu for Org-mode, insert it into the menu."
19306 (interactive)
19307 (org-load-modules-maybe)
19308 (org-require-autoloaded-modules)
19309 (if (fboundp 'customize-menu-create)
19310 (progn
19311 (easy-menu-change
19312 '("Org") "Customize"
19313 `(["Browse Org group" org-customize t]
19314 "--"
19315 ,(customize-menu-create 'org)
19316 ["Set" Custom-set t]
19317 ["Save" Custom-save t]
19318 ["Reset to Current" Custom-reset-current t]
19319 ["Reset to Saved" Custom-reset-saved t]
19320 ["Reset to Standard Settings" Custom-reset-standard t]))
19321 (message "\"Org\"-menu now contains full customization menu"))
19322 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19323
19324 ;;;; Miscellaneous stuff
19325
19326 ;;; Generally useful functions
19327
19328 (defun org-get-at-bol (property)
19329 "Get text property PROPERTY at beginning of line."
19330 (get-text-property (point-at-bol) property))
19331
19332 (defun org-find-text-property-in-string (prop s)
19333 "Return the first non-nil value of property PROP in string S."
19334 (or (get-text-property 0 prop s)
19335 (get-text-property (or (next-single-property-change 0 prop s) 0)
19336 prop s)))
19337
19338 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19339 "Display the given MESSAGE as a warning."
19340 (if (fboundp 'display-warning)
19341 (display-warning 'org message
19342 (if (featurep 'xemacs) 'warning :warning))
19343 (let ((buf (get-buffer-create "*Org warnings*")))
19344 (with-current-buffer buf
19345 (goto-char (point-max))
19346 (insert "Warning (Org): " message)
19347 (unless (bolp)
19348 (newline)))
19349 (display-buffer buf)
19350 (sit-for 0))))
19351
19352 (defun org-eval (form)
19353 "Eval FORM and return result."
19354 (condition-case error
19355 (eval form)
19356 (error (format "%%![Error: %s]" error))))
19357
19358 (defun org-in-clocktable-p ()
19359 "Check if the cursor is in a clocktable."
19360 (let ((pos (point)) start)
19361 (save-excursion
19362 (end-of-line 1)
19363 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19364 (setq start (match-beginning 0))
19365 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19366 (>= (match-end 0) pos)
19367 start))))
19368
19369 (defun org-in-commented-line ()
19370 "Is point in a line starting with `#'?"
19371 (equal (char-after (point-at-bol)) ?#))
19372
19373 (defun org-in-indented-comment-line ()
19374 "Is point in a line starting with `#' after some white space?"
19375 (save-excursion
19376 (save-match-data
19377 (goto-char (point-at-bol))
19378 (looking-at "[ \t]*#"))))
19379
19380 (defun org-in-verbatim-emphasis ()
19381 (save-match-data
19382 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19383
19384 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19385 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19386 (if (and marker (marker-buffer marker)
19387 (buffer-live-p (marker-buffer marker)))
19388 (progn
19389 (org-pop-to-buffer-same-window (marker-buffer marker))
19390 (if (or (> marker (point-max)) (< marker (point-min)))
19391 (widen))
19392 (goto-char marker)
19393 (org-show-context 'org-goto))
19394 (if bookmark
19395 (bookmark-jump bookmark)
19396 (error "Cannot find location"))))
19397
19398 (defun org-quote-csv-field (s)
19399 "Quote field for inclusion in CSV material."
19400 (if (string-match "[\",]" s)
19401 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19402 s))
19403
19404 (defun org-force-self-insert (N)
19405 "Needed to enforce self-insert under remapping."
19406 (interactive "p")
19407 (self-insert-command N))
19408
19409 (defun org-string-width (s)
19410 "Compute width of string, ignoring invisible characters.
19411 This ignores character with invisibility property `org-link', and also
19412 characters with property `org-cwidth', because these will become invisible
19413 upon the next fontification round."
19414 (let (b l)
19415 (when (or (eq t buffer-invisibility-spec)
19416 (assq 'org-link buffer-invisibility-spec))
19417 (while (setq b (text-property-any 0 (length s)
19418 'invisible 'org-link s))
19419 (setq s (concat (substring s 0 b)
19420 (substring s (or (next-single-property-change
19421 b 'invisible s) (length s)))))))
19422 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19423 (setq s (concat (substring s 0 b)
19424 (substring s (or (next-single-property-change
19425 b 'org-cwidth s) (length s))))))
19426 (setq l (string-width s) b -1)
19427 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19428 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19429 l))
19430
19431 (defun org-shorten-string (s maxlength)
19432 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19433 If the string is shorter or has length MAXLENGTH, just return the
19434 original string. If it is longer, the functions finds a space in the
19435 string, breaks this string off at that locations and adds three dots
19436 as ellipsis. Including the ellipsis, the string will not be longer
19437 than MAXLENGTH. If finding a good breaking point in the string does
19438 not work, the string is just chopped off in the middle of a word
19439 if necessary."
19440 (if (<= (length s) maxlength)
19441 s
19442 (let* ((n (max (- maxlength 4) 1))
19443 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19444 (if (string-match re s)
19445 (concat (match-string 1 s) "...")
19446 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19447
19448 (defun org-get-indentation (&optional line)
19449 "Get the indentation of the current line, interpreting tabs.
19450 When LINE is given, assume it represents a line and compute its indentation."
19451 (if line
19452 (if (string-match "^ *" (org-remove-tabs line))
19453 (match-end 0))
19454 (save-excursion
19455 (beginning-of-line 1)
19456 (skip-chars-forward " \t")
19457 (current-column))))
19458
19459 (defun org-get-string-indentation (s)
19460 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19461 (let ((n -1) (i 0) (w tab-width) c)
19462 (catch 'exit
19463 (while (< (setq n (1+ n)) (length s))
19464 (setq c (aref s n))
19465 (cond ((= c ?\ ) (setq i (1+ i)))
19466 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19467 (t (throw 'exit t)))))
19468 i))
19469
19470 (defun org-remove-tabs (s &optional width)
19471 "Replace tabulators in S with spaces.
19472 Assumes that s is a single line, starting in column 0."
19473 (setq width (or width tab-width))
19474 (while (string-match "\t" s)
19475 (setq s (replace-match
19476 (make-string
19477 (- (* width (/ (+ (match-beginning 0) width) width))
19478 (match-beginning 0)) ?\ )
19479 t t s)))
19480 s)
19481
19482 (defun org-fix-indentation (line ind)
19483 "Fix indentation in LINE.
19484 IND is a cons cell with target and minimum indentation.
19485 If the current indentation in LINE is smaller than the minimum,
19486 leave it alone. If it is larger than ind, set it to the target."
19487 (let* ((l (org-remove-tabs line))
19488 (i (org-get-indentation l))
19489 (i1 (car ind)) (i2 (cdr ind)))
19490 (if (>= i i2) (setq l (substring line i2)))
19491 (if (> i1 0)
19492 (concat (make-string i1 ?\ ) l)
19493 l)))
19494
19495 (defun org-remove-indentation (code &optional n)
19496 "Remove the maximum common indentation from the lines in CODE.
19497 N may optionally be the number of spaces to remove."
19498 (with-temp-buffer
19499 (insert code)
19500 (org-do-remove-indentation n)
19501 (buffer-string)))
19502
19503 (defun org-do-remove-indentation (&optional n)
19504 "Remove the maximum common indentation from the buffer."
19505 (untabify (point-min) (point-max))
19506 (let ((min 10000) re)
19507 (if n
19508 (setq min n)
19509 (goto-char (point-min))
19510 (while (re-search-forward "^ *[^ \n]" nil t)
19511 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19512 (unless (or (= min 0) (= min 10000))
19513 (setq re (format "^ \\{%d\\}" min))
19514 (goto-char (point-min))
19515 (while (re-search-forward re nil t)
19516 (replace-match "")
19517 (end-of-line 1))
19518 min)))
19519
19520 (defun org-fill-template (template alist)
19521 "Find each %key of ALIST in TEMPLATE and replace it."
19522 (let ((case-fold-search nil)
19523 entry key value)
19524 (setq alist (sort (copy-sequence alist)
19525 (lambda (a b) (< (length (car a)) (length (car b))))))
19526 (while (setq entry (pop alist))
19527 (setq template
19528 (replace-regexp-in-string
19529 (concat "%" (regexp-quote (car entry)))
19530 (cdr entry) template t t)))
19531 template))
19532
19533 (defun org-base-buffer (buffer)
19534 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19535 (if (not buffer)
19536 buffer
19537 (or (buffer-base-buffer buffer)
19538 buffer)))
19539
19540 (defun org-trim (s)
19541 "Remove whitespace at beginning and end of string."
19542 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19543 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19544 s)
19545
19546 (defun org-wrap (string &optional width lines)
19547 "Wrap string to either a number of lines, or a width in characters.
19548 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19549 that costs. If there is a word longer than WIDTH, the text is actually
19550 wrapped to the length of that word.
19551 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19552 many lines, whatever width that takes.
19553 The return value is a list of lines, without newlines at the end."
19554 (let* ((words (org-split-string string "[ \t\n]+"))
19555 (maxword (apply 'max (mapcar 'org-string-width words)))
19556 w ll)
19557 (cond (width
19558 (org-do-wrap words (max maxword width)))
19559 (lines
19560 (setq w maxword)
19561 (setq ll (org-do-wrap words maxword))
19562 (if (<= (length ll) lines)
19563 ll
19564 (setq ll words)
19565 (while (> (length ll) lines)
19566 (setq w (1+ w))
19567 (setq ll (org-do-wrap words w)))
19568 ll))
19569 (t (error "Cannot wrap this")))))
19570
19571 (defun org-do-wrap (words width)
19572 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19573 (let (lines line)
19574 (while words
19575 (setq line (pop words))
19576 (while (and words (< (+ (length line) (length (car words))) width))
19577 (setq line (concat line " " (pop words))))
19578 (setq lines (push line lines)))
19579 (nreverse lines)))
19580
19581 (defun org-split-string (string &optional separators)
19582 "Splits STRING into substrings at SEPARATORS.
19583 No empty strings are returned if there are matches at the beginning
19584 and end of string."
19585 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19586 (start 0)
19587 notfirst
19588 (list nil))
19589 (while (and (string-match rexp string
19590 (if (and notfirst
19591 (= start (match-beginning 0))
19592 (< start (length string)))
19593 (1+ start) start))
19594 (< (match-beginning 0) (length string)))
19595 (setq notfirst t)
19596 (or (eq (match-beginning 0) 0)
19597 (and (eq (match-beginning 0) (match-end 0))
19598 (eq (match-beginning 0) start))
19599 (setq list
19600 (cons (substring string start (match-beginning 0))
19601 list)))
19602 (setq start (match-end 0)))
19603 (or (eq start (length string))
19604 (setq list
19605 (cons (substring string start)
19606 list)))
19607 (nreverse list)))
19608
19609 (defun org-quote-vert (s)
19610 "Replace \"|\" with \"\\vert\"."
19611 (while (string-match "|" s)
19612 (setq s (replace-match "\\vert" t t s)))
19613 s)
19614
19615 (defun org-uuidgen-p (s)
19616 "Is S an ID created by UUIDGEN?"
19617 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19618
19619 (defun org-context ()
19620 "Return a list of contexts of the current cursor position.
19621 If several contexts apply, all are returned.
19622 Each context entry is a list with a symbol naming the context, and
19623 two positions indicating start and end of the context. Possible
19624 contexts are:
19625
19626 :headline anywhere in a headline
19627 :headline-stars on the leading stars in a headline
19628 :todo-keyword on a TODO keyword (including DONE) in a headline
19629 :tags on the TAGS in a headline
19630 :priority on the priority cookie in a headline
19631 :item on the first line of a plain list item
19632 :item-bullet on the bullet/number of a plain list item
19633 :checkbox on the checkbox in a plain list item
19634 :table in an org-mode table
19635 :table-special on a special filed in a table
19636 :table-table in a table.el table
19637 :link on a hyperlink
19638 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19639 :target on a <<target>>
19640 :radio-target on a <<<radio-target>>>
19641 :latex-fragment on a LaTeX fragment
19642 :latex-preview on a LaTeX fragment with overlaid preview image
19643
19644 This function expects the position to be visible because it uses font-lock
19645 faces as a help to recognize the following contexts: :table-special, :link,
19646 and :keyword."
19647 (let* ((f (get-text-property (point) 'face))
19648 (faces (if (listp f) f (list f)))
19649 (p (point)) clist o)
19650 ;; First the large context
19651 (cond
19652 ((org-at-heading-p t)
19653 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19654 (when (progn
19655 (beginning-of-line 1)
19656 (looking-at org-todo-line-tags-regexp))
19657 (push (org-point-in-group p 1 :headline-stars) clist)
19658 (push (org-point-in-group p 2 :todo-keyword) clist)
19659 (push (org-point-in-group p 4 :tags) clist))
19660 (goto-char p)
19661 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19662 (if (looking-at "\\[#[A-Z0-9]\\]")
19663 (push (org-point-in-group p 0 :priority) clist)))
19664
19665 ((org-at-item-p)
19666 (push (org-point-in-group p 2 :item-bullet) clist)
19667 (push (list :item (point-at-bol)
19668 (save-excursion (org-end-of-item) (point)))
19669 clist)
19670 (and (org-at-item-checkbox-p)
19671 (push (org-point-in-group p 0 :checkbox) clist)))
19672
19673 ((org-at-table-p)
19674 (push (list :table (org-table-begin) (org-table-end)) clist)
19675 (if (memq 'org-formula faces)
19676 (push (list :table-special
19677 (previous-single-property-change p 'face)
19678 (next-single-property-change p 'face)) clist)))
19679 ((org-at-table-p 'any)
19680 (push (list :table-table) clist)))
19681 (goto-char p)
19682
19683 ;; Now the small context
19684 (cond
19685 ((org-at-timestamp-p)
19686 (push (org-point-in-group p 0 :timestamp) clist))
19687 ((memq 'org-link faces)
19688 (push (list :link
19689 (previous-single-property-change p 'face)
19690 (next-single-property-change p 'face)) clist))
19691 ((memq 'org-special-keyword faces)
19692 (push (list :keyword
19693 (previous-single-property-change p 'face)
19694 (next-single-property-change p 'face)) clist))
19695 ((org-at-target-p)
19696 (push (org-point-in-group p 0 :target) clist)
19697 (goto-char (1- (match-beginning 0)))
19698 (if (looking-at org-radio-target-regexp)
19699 (push (org-point-in-group p 0 :radio-target) clist))
19700 (goto-char p))
19701 ((setq o (car (delq nil
19702 (mapcar
19703 (lambda (x)
19704 (if (memq x org-latex-fragment-image-overlays) x))
19705 (overlays-at (point))))))
19706 (push (list :latex-fragment
19707 (overlay-start o) (overlay-end o)) clist)
19708 (push (list :latex-preview
19709 (overlay-start o) (overlay-end o)) clist))
19710 ((org-inside-LaTeX-fragment-p)
19711 ;; FIXME: positions wrong.
19712 (push (list :latex-fragment (point) (point)) clist)))
19713
19714 (setq clist (nreverse (delq nil clist)))
19715 clist))
19716
19717 ;; FIXME: Compare with at-regexp-p Do we need both?
19718 (defun org-in-regexp (re &optional nlines visually)
19719 "Check if point is inside a match of regexp.
19720 Normally only the current line is checked, but you can include NLINES extra
19721 lines both before and after point into the search.
19722 If VISUALLY is set, require that the cursor is not after the match but
19723 really on, so that the block visually is on the match."
19724 (catch 'exit
19725 (let ((pos (point))
19726 (eol (point-at-eol (+ 1 (or nlines 0))))
19727 (inc (if visually 1 0)))
19728 (save-excursion
19729 (beginning-of-line (- 1 (or nlines 0)))
19730 (while (re-search-forward re eol t)
19731 (if (and (<= (match-beginning 0) pos)
19732 (>= (+ inc (match-end 0)) pos))
19733 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19734
19735 (defun org-at-regexp-p (regexp)
19736 "Is point inside a match of REGEXP in the current line?"
19737 (catch 'exit
19738 (save-excursion
19739 (let ((pos (point)) (end (point-at-eol)))
19740 (beginning-of-line 1)
19741 (while (re-search-forward regexp end t)
19742 (if (and (<= (match-beginning 0) pos)
19743 (>= (match-end 0) pos))
19744 (throw 'exit t)))
19745 nil))))
19746
19747 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19748 "Non-nil when point is between matches of START-RE and END-RE.
19749
19750 Also return a non-nil value when point is on one of the matches.
19751
19752 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19753 buffer positions. Default values are the positions of headlines
19754 surrounding the point.
19755
19756 The functions returns a cons cell whose car (resp. cdr) is the
19757 position before START-RE (resp. after END-RE)."
19758 (save-match-data
19759 (let ((pos (point))
19760 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19761 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19762 beg end)
19763 (save-excursion
19764 ;; Point is on a block when on START-RE or if START-RE can be
19765 ;; found before it...
19766 (and (or (org-at-regexp-p start-re)
19767 (re-search-backward start-re limit-up t))
19768 (setq beg (match-beginning 0))
19769 ;; ... and END-RE after it...
19770 (goto-char (match-end 0))
19771 (re-search-forward end-re limit-down t)
19772 (> (setq end (match-end 0)) pos)
19773 ;; ... without another START-RE in-between.
19774 (goto-char (match-beginning 0))
19775 (not (re-search-backward start-re (1+ beg) t))
19776 ;; Return value.
19777 (cons beg end))))))
19778
19779 (defun org-in-block-p (names)
19780 "Non-nil when point belongs to a block whose name belongs to NAMES.
19781
19782 NAMES is a list of strings containing names of blocks.
19783
19784 Return first block name matched, or nil. Beware that in case of
19785 nested blocks, the returned name may not belong to the closest
19786 block from point."
19787 (save-match-data
19788 (catch 'exit
19789 (let ((case-fold-search t)
19790 (lim-up (save-excursion (outline-previous-heading)))
19791 (lim-down (save-excursion (outline-next-heading))))
19792 (mapc (lambda (name)
19793 (let ((n (regexp-quote name)))
19794 (when (org-between-regexps-p
19795 (concat "^[ \t]*#\\+begin_" n)
19796 (concat "^[ \t]*#\\+end_" n)
19797 lim-up lim-down)
19798 (throw 'exit n))))
19799 names))
19800 nil)))
19801
19802 (defun org-occur-in-agenda-files (regexp &optional nlines)
19803 "Call `multi-occur' with buffers for all agenda files."
19804 (interactive "sOrg-files matching: \np")
19805 (let* ((files (org-agenda-files))
19806 (tnames (mapcar 'file-truename files))
19807 (extra org-agenda-text-search-extra-files)
19808 f)
19809 (when (eq (car extra) 'agenda-archives)
19810 (setq extra (cdr extra))
19811 (setq files (org-add-archive-files files)))
19812 (while (setq f (pop extra))
19813 (unless (member (file-truename f) tnames)
19814 (add-to-list 'files f 'append)
19815 (add-to-list 'tnames (file-truename f) 'append)))
19816 (multi-occur
19817 (mapcar (lambda (x)
19818 (with-current-buffer
19819 (or (get-file-buffer x) (find-file-noselect x))
19820 (widen)
19821 (current-buffer)))
19822 files)
19823 regexp)))
19824
19825 (if (boundp 'occur-mode-find-occurrence-hook)
19826 ;; Emacs 23
19827 (add-hook 'occur-mode-find-occurrence-hook
19828 (lambda ()
19829 (when (eq major-mode 'org-mode)
19830 (org-reveal))))
19831 ;; Emacs 22
19832 (defadvice occur-mode-goto-occurrence
19833 (after org-occur-reveal activate)
19834 (and (eq major-mode 'org-mode) (org-reveal)))
19835 (defadvice occur-mode-goto-occurrence-other-window
19836 (after org-occur-reveal activate)
19837 (and (eq major-mode 'org-mode) (org-reveal)))
19838 (defadvice occur-mode-display-occurrence
19839 (after org-occur-reveal activate)
19840 (when (eq major-mode 'org-mode)
19841 (let ((pos (occur-mode-find-occurrence)))
19842 (with-current-buffer (marker-buffer pos)
19843 (save-excursion
19844 (goto-char pos)
19845 (org-reveal)))))))
19846
19847 (defun org-occur-link-in-agenda-files ()
19848 "Create a link and search for it in the agendas.
19849 The link is not stored in `org-stored-links', it is just created
19850 for the search purpose."
19851 (interactive)
19852 (let ((link (condition-case nil
19853 (org-store-link nil)
19854 (error "Unable to create a link to here"))))
19855 (org-occur-in-agenda-files (regexp-quote link))))
19856
19857 (defun org-uniquify (list)
19858 "Remove duplicate elements from LIST."
19859 (let (res)
19860 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19861 res))
19862
19863 (defun org-delete-all (elts list)
19864 "Remove all elements in ELTS from LIST."
19865 (while elts
19866 (setq list (delete (pop elts) list)))
19867 list)
19868
19869 (defun org-count (cl-item cl-seq)
19870 "Count the number of occurrences of ITEM in SEQ.
19871 Taken from `count' in cl-seq.el with all keyword arguments removed."
19872 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19873 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19874 (while (< cl-start cl-end)
19875 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19876 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19877 (setq cl-start (1+ cl-start)))
19878 cl-count))
19879
19880 (defun org-remove-if (predicate seq)
19881 "Remove everything from SEQ that fulfills PREDICATE."
19882 (let (res e)
19883 (while seq
19884 (setq e (pop seq))
19885 (if (not (funcall predicate e)) (push e res)))
19886 (nreverse res)))
19887
19888 (defun org-remove-if-not (predicate seq)
19889 "Remove everything from SEQ that does not fulfill PREDICATE."
19890 (let (res e)
19891 (while seq
19892 (setq e (pop seq))
19893 (if (funcall predicate e) (push e res)))
19894 (nreverse res)))
19895
19896 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19897 "Reduce two-argument FUNCTION across SEQ.
19898 Taken from `reduce' in cl-seq.el with all keyword arguments but
19899 \":initial-value\" removed."
19900 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19901 (cadr (memq :initial-value cl-keys)))
19902 (cl-seq (pop cl-seq))
19903 (t (funcall cl-func)))))
19904 (while cl-seq
19905 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19906 cl-accum))
19907
19908 (defun org-back-over-empty-lines ()
19909 "Move backwards over whitespace, to the beginning of the first empty line.
19910 Returns the number of empty lines passed."
19911 (let ((pos (point)))
19912 (if (cdr (assoc 'heading org-blank-before-new-entry))
19913 (skip-chars-backward " \t\n\r")
19914 (unless (eobp)
19915 (forward-line -1)))
19916 (beginning-of-line 2)
19917 (goto-char (min (point) pos))
19918 (count-lines (point) pos)))
19919
19920 (defun org-skip-whitespace ()
19921 (skip-chars-forward " \t\n\r"))
19922
19923 (defun org-point-in-group (point group &optional context)
19924 "Check if POINT is in match-group GROUP.
19925 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19926 match. If the match group does not exist or point is not inside it,
19927 return nil."
19928 (and (match-beginning group)
19929 (>= point (match-beginning group))
19930 (<= point (match-end group))
19931 (if context
19932 (list context (match-beginning group) (match-end group))
19933 t)))
19934
19935 (defun org-switch-to-buffer-other-window (&rest args)
19936 "Switch to buffer in a second window on the current frame.
19937 In particular, do not allow pop-up frames.
19938 Returns the newly created buffer."
19939 (let (pop-up-frames special-display-buffer-names special-display-regexps
19940 special-display-function)
19941 (apply 'switch-to-buffer-other-window args)))
19942
19943 (defun org-combine-plists (&rest plists)
19944 "Create a single property list from all plists in PLISTS.
19945 The process starts by copying the first list, and then setting properties
19946 from the other lists. Settings in the last list are the most significant
19947 ones and overrule settings in the other lists."
19948 (let ((rtn (copy-sequence (pop plists)))
19949 p v ls)
19950 (while plists
19951 (setq ls (pop plists))
19952 (while ls
19953 (setq p (pop ls) v (pop ls))
19954 (setq rtn (plist-put rtn p v))))
19955 rtn))
19956
19957 (defun org-move-line-down (arg)
19958 "Move the current line down. With prefix argument, move it past ARG lines."
19959 (interactive "p")
19960 (let ((col (current-column))
19961 beg end pos)
19962 (beginning-of-line 1) (setq beg (point))
19963 (beginning-of-line 2) (setq end (point))
19964 (beginning-of-line (+ 1 arg))
19965 (setq pos (move-marker (make-marker) (point)))
19966 (insert (delete-and-extract-region beg end))
19967 (goto-char pos)
19968 (org-move-to-column col)))
19969
19970 (defun org-move-line-up (arg)
19971 "Move the current line up. With prefix argument, move it past ARG lines."
19972 (interactive "p")
19973 (let ((col (current-column))
19974 beg end pos)
19975 (beginning-of-line 1) (setq beg (point))
19976 (beginning-of-line 2) (setq end (point))
19977 (beginning-of-line (- arg))
19978 (setq pos (move-marker (make-marker) (point)))
19979 (insert (delete-and-extract-region beg end))
19980 (goto-char pos)
19981 (org-move-to-column col)))
19982
19983 (defun org-replace-escapes (string table)
19984 "Replace %-escapes in STRING with values in TABLE.
19985 TABLE is an association list with keys like \"%a\" and string values.
19986 The sequences in STRING may contain normal field width and padding information,
19987 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19988 so values can contain further %-escapes if they are define later in TABLE."
19989 (let ((tbl (copy-alist table))
19990 (case-fold-search nil)
19991 (pchg 0)
19992 e re rpl)
19993 (while (setq e (pop tbl))
19994 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19995 (when (and (cdr e) (string-match re (cdr e)))
19996 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19997 (safe "SREF"))
19998 (add-text-properties 0 3 (list 'sref sref) safe)
19999 (setcdr e (replace-match safe t t (cdr e)))))
20000 (while (string-match re string)
20001 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20002 (cdr e)))
20003 (setq string (replace-match rpl t t string))))
20004 (while (setq pchg (next-property-change pchg string))
20005 (let ((sref (get-text-property pchg 'sref string)))
20006 (when (and sref (string-match "SREF" string pchg))
20007 (setq string (replace-match sref t t string)))))
20008 string))
20009
20010 (defun org-sublist (list start end)
20011 "Return a section of LIST, from START to END.
20012 Counting starts at 1."
20013 (let (rtn (c start))
20014 (setq list (nthcdr (1- start) list))
20015 (while (and list (<= c end))
20016 (push (pop list) rtn)
20017 (setq c (1+ c)))
20018 (nreverse rtn)))
20019
20020 (defun org-find-base-buffer-visiting (file)
20021 "Like `find-buffer-visiting' but always return the base buffer and
20022 not an indirect buffer."
20023 (let ((buf (or (get-file-buffer file)
20024 (find-buffer-visiting file))))
20025 (if buf
20026 (or (buffer-base-buffer buf) buf)
20027 nil)))
20028
20029 (defun org-image-file-name-regexp (&optional extensions)
20030 "Return regexp matching the file names of images.
20031 If EXTENSIONS is given, only match these."
20032 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20033 (image-file-name-regexp)
20034 (let ((image-file-name-extensions
20035 (or extensions
20036 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20037 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20038 (concat "\\."
20039 (regexp-opt (nconc (mapcar 'upcase
20040 image-file-name-extensions)
20041 image-file-name-extensions)
20042 t)
20043 "\\'"))))
20044
20045 (defun org-file-image-p (file &optional extensions)
20046 "Return non-nil if FILE is an image."
20047 (save-match-data
20048 (string-match (org-image-file-name-regexp extensions) file)))
20049
20050 (defun org-get-cursor-date ()
20051 "Return the date at cursor in as a time.
20052 This works in the calendar and in the agenda, anywhere else it just
20053 returns the current time."
20054 (let (date day defd)
20055 (cond
20056 ((eq major-mode 'calendar-mode)
20057 (setq date (calendar-cursor-to-date)
20058 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20059 ((eq major-mode 'org-agenda-mode)
20060 (setq day (get-text-property (point) 'day))
20061 (if day
20062 (setq date (calendar-gregorian-from-absolute day)
20063 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20064 (nth 2 date))))))
20065 (or defd (current-time))))
20066
20067 (defvar org-agenda-action-marker (make-marker)
20068 "Marker pointing to the entry for the next agenda action.")
20069
20070 (defun org-mark-entry-for-agenda-action ()
20071 "Mark the current entry as target of an agenda action.
20072 Agenda actions are actions executed from the agenda with the key `k',
20073 which make use of the date at the cursor."
20074 (interactive)
20075 (move-marker org-agenda-action-marker
20076 (save-excursion (org-back-to-heading t) (point))
20077 (current-buffer))
20078 (message
20079 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20080
20081 (defun org-mark-subtree ()
20082 "Mark the current subtree.
20083 This puts point at the start of the current subtree, and mark at the end.
20084
20085 If point is in an inline task, mark that task instead."
20086 (interactive)
20087 (let ((inline-task-p
20088 (and (featurep 'org-inlinetask)
20089 (org-inlinetask-in-task-p)))
20090 (beg))
20091 ;; Get beginning of subtree
20092 (cond
20093 (inline-task-p (org-inlinetask-goto-beginning))
20094 ((org-at-heading-p) (beginning-of-line))
20095 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20096 (setq beg (point))
20097 ;; Get end of it
20098 (if inline-task-p
20099 (org-inlinetask-goto-end)
20100 (org-end-of-subtree))
20101 ;; Mark zone
20102 (push-mark (point) nil t)
20103 (goto-char beg)))
20104
20105 ;;; Paragraph filling stuff.
20106 ;; We want this to be just right, so use the full arsenal.
20107
20108 (defun org-indent-line-function ()
20109 "Indent line depending on context."
20110 (interactive)
20111 (let* ((pos (point))
20112 (itemp (org-at-item-p))
20113 (case-fold-search t)
20114 (org-drawer-regexp (or org-drawer-regexp "\000"))
20115 (inline-task-p (and (featurep 'org-inlinetask)
20116 (org-inlinetask-in-task-p)))
20117 (inline-re (and inline-task-p
20118 (org-inlinetask-outline-regexp)))
20119 column)
20120 (beginning-of-line 1)
20121 (cond
20122 ;; Comments
20123 ((looking-at "# ") (setq column 0))
20124 ;; Headings
20125 ((looking-at org-outline-regexp) (setq column 0))
20126 ;; Included files
20127 ((looking-at "#\\+include:") (setq column 0))
20128 ;; Footnote definition
20129 ((looking-at org-footnote-definition-re) (setq column 0))
20130 ;; Literal examples
20131 ((looking-at "[ \t]*:\\( \\|$\\)")
20132 (setq column (org-get-indentation))) ; do nothing
20133 ;; Lists
20134 ((ignore-errors (goto-char (org-in-item-p)))
20135 (setq column (if itemp
20136 (org-get-indentation)
20137 (org-list-item-body-column (point))))
20138 (goto-char pos))
20139 ;; Drawers
20140 ((and (looking-at "[ \t]*:END:")
20141 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20142 (save-excursion
20143 (goto-char (1- (match-beginning 1)))
20144 (setq column (current-column))))
20145 ;; Special blocks
20146 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20147 (save-excursion
20148 (re-search-backward
20149 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20150 (setq column (org-get-indentation (match-string 0))))
20151 ((and (not (looking-at "[ \t]*#\\+begin_"))
20152 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20153 (save-excursion
20154 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20155 (setq column
20156 (cond ((equal (downcase (match-string 1)) "src")
20157 ;; src blocks: let `org-edit-src-exit' handle them
20158 (org-get-indentation))
20159 ((equal (downcase (match-string 1)) "example")
20160 (max (org-get-indentation)
20161 (org-get-indentation (match-string 0))))
20162 (t
20163 (org-get-indentation (match-string 0))))))
20164 ;; This line has nothing special, look at the previous relevant
20165 ;; line to compute indentation
20166 (t
20167 (beginning-of-line 0)
20168 (while (and (not (bobp))
20169 (not (looking-at org-drawer-regexp))
20170 ;; When point started in an inline task, do not move
20171 ;; above task starting line.
20172 (not (and inline-task-p (looking-at inline-re)))
20173 ;; Skip drawers, blocks, empty lines, verbatim,
20174 ;; comments, tables, footnotes definitions, lists,
20175 ;; inline tasks.
20176 (or (and (looking-at "[ \t]*:END:")
20177 (re-search-backward org-drawer-regexp nil t))
20178 (and (looking-at "[ \t]*#\\+end_")
20179 (re-search-backward "[ \t]*#\\+begin_"nil t))
20180 (looking-at "[ \t]*[\n:#|]")
20181 (looking-at org-footnote-definition-re)
20182 (and (ignore-errors (goto-char (org-in-item-p)))
20183 (goto-char
20184 (org-list-get-top-point (org-list-struct))))
20185 (and (not inline-task-p)
20186 (featurep 'org-inlinetask)
20187 (org-inlinetask-in-task-p)
20188 (or (org-inlinetask-goto-beginning) t))))
20189 (beginning-of-line 0))
20190 (cond
20191 ;; There was an heading above.
20192 ((looking-at "\\*+[ \t]+")
20193 (if (not org-adapt-indentation)
20194 (setq column 0)
20195 (goto-char (match-end 0))
20196 (setq column (current-column))))
20197 ;; A drawer had started and is unfinished
20198 ((looking-at org-drawer-regexp)
20199 (goto-char (1- (match-beginning 1)))
20200 (setq column (current-column)))
20201 ;; Else, nothing noticeable found: get indentation and go on.
20202 (t (setq column (org-get-indentation))))))
20203 ;; Now apply indentation and move cursor accordingly
20204 (goto-char pos)
20205 (if (<= (current-column) (current-indentation))
20206 (org-indent-line-to column)
20207 (save-excursion (org-indent-line-to column)))
20208 ;; Special polishing for properties, see `org-property-format'
20209 (setq column (current-column))
20210 (beginning-of-line 1)
20211 (if (looking-at
20212 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20213 (replace-match (concat (match-string 1)
20214 (format org-property-format
20215 (match-string 2) (match-string 3)))
20216 t t))
20217 (org-move-to-column column)))
20218
20219 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20220 "Variable to store copy of `adaptive-fill-regexp'.
20221 Since `adaptive-fill-regexp' is set to never match, we need to
20222 store a backup of its value before entering `org-mode' so that
20223 the functionality can be provided as a fall-back.")
20224
20225 (defun org-set-autofill-regexps ()
20226 (interactive)
20227 ;; In the paragraph separator we include headlines, because filling
20228 ;; text in a line directly attached to a headline would otherwise
20229 ;; fill the headline as well.
20230 (org-set-local 'comment-start-skip "^#+[ \t]*")
20231 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20232 ;; The paragraph starter includes hand-formatted lists.
20233 (org-set-local
20234 'paragraph-start
20235 (concat
20236 "\f" "\\|"
20237 "[ ]*$" "\\|"
20238 org-outline-regexp "\\|"
20239 "[ \t]*#" "\\|"
20240 (org-item-re) "\\|"
20241 "[ \t]*[:|]" "\\|"
20242 "\\$\\$" "\\|"
20243 "\\\\\\(begin\\|end\\|[][]\\)"))
20244 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20245 ;; But only if the user has not turned off tables or fixed-width regions
20246 (org-set-local
20247 'auto-fill-inhibit-regexp
20248 (concat org-outline-regexp
20249 "\\|#\\+"
20250 "\\|[ \t]*" org-keyword-time-regexp
20251 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20252 (concat
20253 "\\|[ \t]*["
20254 (if org-enable-table-editor "|" "")
20255 (if org-enable-fixed-width-editor ":" "")
20256 "]"))))
20257 ;; We use our own fill-paragraph function, to make sure that tables
20258 ;; and fixed-width regions are not wrapped. That function will pass
20259 ;; through to `fill-paragraph' when appropriate.
20260 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20261 ;; Prevent auto-fill from inserting unwanted new items.
20262 (if (boundp 'fill-nobreak-predicate)
20263 (org-set-local 'fill-nobreak-predicate
20264 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20265 fill-nobreak-predicate
20266 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20267 ;; Adaptive filling: To get full control, first make sure that
20268 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20269 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20270 (org-set-local 'org-adaptive-fill-regexp-backup
20271 adaptive-fill-regexp))
20272 (org-set-local 'adaptive-fill-regexp "\000")
20273 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20274 (org-set-local 'adaptive-fill-function
20275 'org-adaptive-fill-function)
20276 (org-set-local
20277 'align-mode-rules-list
20278 '((org-in-buffer-settings
20279 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20280 (modes . '(org-mode))))))
20281
20282 (defun org-fill-item-nobreak-p ()
20283 "Non-nil when a line break at point would insert a new item."
20284 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20285
20286 (defun org-fill-paragraph (&optional justify)
20287 "Re-align a table, pass through to fill-paragraph if no table."
20288 (let ((table-p (org-at-table-p))
20289 (table.el-p (org-at-table.el-p))
20290 (itemp (org-in-item-p)))
20291 (cond ((and (equal (char-after (point-at-bol)) ?*)
20292 (save-excursion (goto-char (point-at-bol))
20293 (looking-at org-outline-regexp)))
20294 t) ; skip headlines
20295 (table.el-p t) ; skip table.el tables
20296 (table-p (org-table-align) t) ; align Org tables
20297 (itemp ; align text in items
20298 (let* ((struct (save-excursion (goto-char itemp)
20299 (org-list-struct)))
20300 (parents (org-list-parents-alist struct))
20301 (children (org-list-get-children itemp struct parents))
20302 beg end prev next prefix)
20303 ;; Determine in which part of item point is: before
20304 ;; first child, after last child, between two
20305 ;; sub-lists, or simply in item if there's no child.
20306 (cond
20307 ((not children)
20308 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20309 beg itemp
20310 end (org-list-get-item-end itemp struct)))
20311 ((< (point) (setq next (car children)))
20312 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20313 beg itemp
20314 end next))
20315 ((> (point) (setq prev (car (last children))))
20316 (setq beg (org-list-get-item-end prev struct)
20317 end (org-list-get-item-end itemp struct)
20318 prefix (save-excursion
20319 (goto-char beg)
20320 (skip-chars-forward " \t")
20321 (make-string (current-column) ?\ ))))
20322 (t (catch 'exit
20323 (while (setq next (pop children))
20324 (if (> (point) next)
20325 (setq prev next)
20326 (setq beg (org-list-get-item-end prev struct)
20327 end next
20328 prefix (save-excursion
20329 (goto-char beg)
20330 (skip-chars-forward " \t")
20331 (make-string (current-column) ?\ )))
20332 (throw 'exit nil))))))
20333 ;; Use `fill-paragraph' with buffer narrowed to item
20334 ;; without any child, and with our computed PREFIX.
20335 (flet ((fill-context-prefix (from to &optional flr) prefix))
20336 (save-restriction
20337 (narrow-to-region beg end)
20338 (save-excursion (fill-paragraph justify)))) t))
20339 ;; Special case where point is not in a list but is on
20340 ;; a paragraph adjacent to a list: make sure this paragraph
20341 ;; doesn't get merged with the end of the list by narrowing
20342 ;; buffer first.
20343 ((save-excursion (forward-paragraph -1)
20344 (setq itemp (org-in-item-p)))
20345 (let ((struct (save-excursion (goto-char itemp)
20346 (org-list-struct))))
20347 (save-restriction
20348 (narrow-to-region (org-list-get-bottom-point struct)
20349 (save-excursion (forward-paragraph 1)
20350 (point)))
20351 (fill-paragraph justify) t)))
20352 ;; Else simply call `fill-paragraph'.
20353 (t nil))))
20354
20355 ;; For reference, this is the default value of adaptive-fill-regexp
20356 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20357
20358 (defun org-adaptive-fill-function ()
20359 "Return a fill prefix for org-mode files."
20360 (let (itemp)
20361 (save-excursion
20362 (cond
20363 ;; Comment line
20364 ((looking-at "#[ \t]+")
20365 (match-string-no-properties 0))
20366 ;; Plain list item
20367 ((org-at-item-p)
20368 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20369 ;; Point is in a list after `backward-paragraph': original
20370 ;; point wasn't in the list, or filling would have been taken
20371 ;; care of by `org-auto-fill-function', but the list and the
20372 ;; real paragraph are not separated by a blank line. Thus, move
20373 ;; point after the list to go back to real paragraph and
20374 ;; determine fill-prefix.
20375 ((setq itemp (org-in-item-p))
20376 (goto-char itemp)
20377 (let* ((struct (org-list-struct))
20378 (bottom (org-list-get-bottom-point struct)))
20379 (goto-char bottom)
20380 (make-string (org-get-indentation) ?\ )))
20381 ;; Other text
20382 ((looking-at org-adaptive-fill-regexp-backup)
20383 (match-string-no-properties 0))))))
20384
20385 (defun org-auto-fill-function ()
20386 "Auto-fill function."
20387 (let (itemp prefix)
20388 ;; When in a list, compute an appropriate fill-prefix and make
20389 ;; sure it will be used by `do-auto-fill'.
20390 (if (setq itemp (org-in-item-p))
20391 (progn
20392 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20393 (flet ((fill-context-prefix (from to &optional flr) prefix))
20394 (do-auto-fill)))
20395 ;; Else just use `do-auto-fill'.
20396 (do-auto-fill))))
20397
20398 ;;; Other stuff.
20399
20400 (defun org-toggle-fixed-width-section (arg)
20401 "Toggle the fixed-width export.
20402 If there is no active region, the QUOTE keyword at the current headline is
20403 inserted or removed. When present, it causes the text between this headline
20404 and the next to be exported as fixed-width text, and unmodified.
20405 If there is an active region, this command adds or removes a colon as the
20406 first character of this line. If the first character of a line is a colon,
20407 this line is also exported in fixed-width font."
20408 (interactive "P")
20409 (let* ((cc 0)
20410 (regionp (org-region-active-p))
20411 (beg (if regionp (region-beginning) (point)))
20412 (end (if regionp (region-end)))
20413 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20414 (case-fold-search nil)
20415 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20416 off)
20417 (if regionp
20418 (save-excursion
20419 (goto-char beg)
20420 (setq cc (current-column))
20421 (beginning-of-line 1)
20422 (setq off (looking-at re))
20423 (while (> nlines 0)
20424 (setq nlines (1- nlines))
20425 (beginning-of-line 1)
20426 (cond
20427 (arg
20428 (org-move-to-column cc t)
20429 (insert ": \n")
20430 (forward-line -1))
20431 ((and off (looking-at re))
20432 (replace-match "" t t nil 1))
20433 ((not off) (org-move-to-column cc t) (insert ": ")))
20434 (forward-line 1)))
20435 (save-excursion
20436 (org-back-to-heading)
20437 (cond
20438 ((looking-at (format org-heading-keyword-regexp-format
20439 org-quote-string))
20440 (goto-char (match-end 1))
20441 (looking-at (concat " +" org-quote-string))
20442 (replace-match "" t t)
20443 (when (eolp) (insert " ")))
20444 ((looking-at org-outline-regexp)
20445 (goto-char (match-end 0))
20446 (insert org-quote-string " ")))))))
20447
20448 (defun org-reftex-citation ()
20449 "Use reftex-citation to insert a citation into the buffer.
20450 This looks for a line like
20451
20452 #+BIBLIOGRAPHY: foo plain option:-d
20453
20454 and derives from it that foo.bib is the bibliography file relevant
20455 for this document. It then installs the necessary environment for RefTeX
20456 to work in this buffer and calls `reftex-citation' to insert a citation
20457 into the buffer.
20458
20459 Export of such citations to both LaTeX and HTML is handled by the contributed
20460 package org-exp-bibtex by Taru Karttunen."
20461 (interactive)
20462 (let ((reftex-docstruct-symbol 'rds)
20463 (reftex-cite-format "\\cite{%l}")
20464 rds bib)
20465 (save-excursion
20466 (save-restriction
20467 (widen)
20468 (let ((case-fold-search t)
20469 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20470 (if (not (save-excursion
20471 (or (re-search-forward re nil t)
20472 (re-search-backward re nil t))))
20473 (error "No bibliography defined in file")
20474 (setq bib (concat (match-string 1) ".bib")
20475 rds (list (list 'bib bib)))))))
20476 (call-interactively 'reftex-citation)))
20477
20478 ;;;; Functions extending outline functionality
20479
20480 (defun org-beginning-of-line (&optional arg)
20481 "Go to the beginning of the current line. If that is invisible, continue
20482 to a visible line beginning. This makes the function of C-a more intuitive.
20483 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20484 first attempt, and only move to after the tags when the cursor is already
20485 beyond the end of the headline."
20486 (interactive "P")
20487 (let ((pos (point))
20488 (special (if (consp org-special-ctrl-a/e)
20489 (car org-special-ctrl-a/e)
20490 org-special-ctrl-a/e))
20491 refpos)
20492 (if (org-bound-and-true-p line-move-visual)
20493 (beginning-of-visual-line 1)
20494 (beginning-of-line 1))
20495 (if (and arg (fboundp 'move-beginning-of-line))
20496 (call-interactively 'move-beginning-of-line)
20497 (if (bobp)
20498 nil
20499 (backward-char 1)
20500 (if (org-truely-invisible-p)
20501 (while (and (not (bobp)) (org-truely-invisible-p))
20502 (backward-char 1)
20503 (beginning-of-line 1))
20504 (forward-char 1))))
20505 (when special
20506 (cond
20507 ((and (looking-at org-complex-heading-regexp)
20508 (= (char-after (match-end 1)) ?\ ))
20509 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20510 (point-at-eol)))
20511 (goto-char
20512 (if (eq special t)
20513 (cond ((> pos refpos) refpos)
20514 ((= pos (point)) refpos)
20515 (t (point)))
20516 (cond ((> pos (point)) (point))
20517 ((not (eq last-command this-command)) (point))
20518 (t refpos)))))
20519 ((org-at-item-p)
20520 ;; Being at an item and not looking at an the item means point
20521 ;; was previously moved to beginning of a visual line, which
20522 ;; doesn't contain the item. Therefore, do nothing special,
20523 ;; just stay here.
20524 (when (looking-at org-list-full-item-re)
20525 ;; Set special position at first white space character after
20526 ;; bullet, and check-box, if any.
20527 (let ((after-bullet
20528 (let ((box (match-end 3)))
20529 (if (not box) (match-end 1)
20530 (let ((after (char-after box)))
20531 (if (and after (= after ? )) (1+ box) box))))))
20532 ;; Special case: Move point to special position when
20533 ;; currently after it or at beginning of line.
20534 (if (eq special t)
20535 (when (or (> pos after-bullet) (= (point) pos))
20536 (goto-char after-bullet))
20537 ;; Reversed case: Move point to special position when
20538 ;; point was already at beginning of line and command is
20539 ;; repeated.
20540 (when (and (= (point) pos) (eq last-command this-command))
20541 (goto-char after-bullet))))))))
20542 (org-no-warnings
20543 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20544
20545 (defun org-end-of-line (&optional arg)
20546 "Go to the end of the line.
20547 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20548 first attempt, and only move to after the tags when the cursor is already
20549 beyond the end of the headline."
20550 (interactive "P")
20551 (let ((special (if (consp org-special-ctrl-a/e)
20552 (cdr org-special-ctrl-a/e)
20553 org-special-ctrl-a/e)))
20554 (cond
20555 ((or (not special) arg
20556 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20557 (call-interactively
20558 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20559 ((fboundp 'move-end-of-line) 'move-end-of-line)
20560 (t 'end-of-line))))
20561 ((org-at-heading-p)
20562 (let ((pos (point)))
20563 (beginning-of-line 1)
20564 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20565 (if (eq special t)
20566 (if (or (< pos (match-beginning 1))
20567 (= pos (match-end 0)))
20568 (goto-char (match-beginning 1))
20569 (goto-char (match-end 0)))
20570 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20571 (goto-char (match-end 0))
20572 (goto-char (match-beginning 1))))
20573 (call-interactively (if (fboundp 'move-end-of-line)
20574 'move-end-of-line
20575 'end-of-line)))))
20576 ((org-at-drawer-p)
20577 (move-end-of-line 1)
20578 (when (overlays-at (1- (point))) (backward-char 1)))
20579 ;; At an item: Move before any hidden text.
20580 (t (call-interactively
20581 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20582 ((fboundp 'move-end-of-line) 'move-end-of-line)
20583 (t 'end-of-line)))))
20584 (org-no-warnings
20585 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20586
20587 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20588 (define-key org-mode-map "\C-e" 'org-end-of-line)
20589
20590 (defun org-backward-sentence (&optional arg)
20591 "Go to beginning of sentence, or beginning of table field.
20592 This will call `backward-sentence' or `org-table-beginning-of-field',
20593 depending on context."
20594 (interactive "P")
20595 (cond
20596 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20597 (t (call-interactively 'backward-sentence))))
20598
20599 (defun org-forward-sentence (&optional arg)
20600 "Go to end of sentence, or end of table field.
20601 This will call `forward-sentence' or `org-table-end-of-field',
20602 depending on context."
20603 (interactive "P")
20604 (cond
20605 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20606 (t (call-interactively 'forward-sentence))))
20607
20608 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20609 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20610
20611 (defun org-kill-line (&optional arg)
20612 "Kill line, to tags or end of line."
20613 (interactive "P")
20614 (cond
20615 ((or (not org-special-ctrl-k)
20616 (bolp)
20617 (not (org-at-heading-p)))
20618 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20619 org-ctrl-k-protect-subtree)
20620 (if (or (eq org-ctrl-k-protect-subtree 'error)
20621 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20622 (error "C-k aborted - would kill hidden subtree")))
20623 (call-interactively 'kill-line))
20624 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20625 (kill-region (point) (match-beginning 1))
20626 (org-set-tags nil t))
20627 (t (kill-region (point) (point-at-eol)))))
20628
20629 (define-key org-mode-map "\C-k" 'org-kill-line)
20630
20631 (defun org-yank (&optional arg)
20632 "Yank. If the kill is a subtree, treat it specially.
20633 This command will look at the current kill and check if is a single
20634 subtree, or a series of subtrees[1]. If it passes the test, and if the
20635 cursor is at the beginning of a line or after the stars of a currently
20636 empty headline, then the yank is handled specially. How exactly depends
20637 on the value of the following variables, both set by default.
20638
20639 org-yank-folded-subtrees
20640 When set, the subtree(s) will be folded after insertion, but only
20641 if doing so would now swallow text after the yanked text.
20642
20643 org-yank-adjusted-subtrees
20644 When set, the subtree will be promoted or demoted in order to
20645 fit into the local outline tree structure, which means that the level
20646 will be adjusted so that it becomes the smaller one of the two
20647 *visible* surrounding headings.
20648
20649 Any prefix to this command will cause `yank' to be called directly with
20650 no special treatment. In particular, a simple \\[universal-argument] prefix \
20651 will just
20652 plainly yank the text as it is.
20653
20654 \[1] The test checks if the first non-white line is a heading
20655 and if there are no other headings with fewer stars."
20656 (interactive "P")
20657 (org-yank-generic 'yank arg))
20658
20659 (defun org-yank-generic (command arg)
20660 "Perform some yank-like command.
20661
20662 This function implements the behavior described in the `org-yank'
20663 documentation. However, it has been generalized to work for any
20664 interactive command with similar behavior."
20665
20666 ;; pretend to be command COMMAND
20667 (setq this-command command)
20668
20669 (if arg
20670 (call-interactively command)
20671
20672 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20673 (and (org-kill-is-subtree-p)
20674 (or (bolp)
20675 (and (looking-at "[ \t]*$")
20676 (string-match
20677 "\\`\\*+\\'"
20678 (buffer-substring (point-at-bol) (point)))))))
20679 swallowp)
20680 (cond
20681 ((and subtreep org-yank-folded-subtrees)
20682 (let ((beg (point))
20683 end)
20684 (if (and subtreep org-yank-adjusted-subtrees)
20685 (org-paste-subtree nil nil 'for-yank)
20686 (call-interactively command))
20687
20688 (setq end (point))
20689 (goto-char beg)
20690 (when (and (bolp) subtreep
20691 (not (setq swallowp
20692 (org-yank-folding-would-swallow-text beg end))))
20693 (org-with-limited-levels
20694 (or (looking-at org-outline-regexp)
20695 (re-search-forward org-outline-regexp-bol end t))
20696 (while (and (< (point) end) (looking-at org-outline-regexp))
20697 (hide-subtree)
20698 (org-cycle-show-empty-lines 'folded)
20699 (condition-case nil
20700 (outline-forward-same-level 1)
20701 (error (goto-char end))))))
20702 (when swallowp
20703 (message
20704 "Inserted text not folded because that would swallow text"))
20705
20706 (goto-char end)
20707 (skip-chars-forward " \t\n\r")
20708 (beginning-of-line 1)
20709 (push-mark beg 'nomsg)))
20710 ((and subtreep org-yank-adjusted-subtrees)
20711 (let ((beg (point-at-bol)))
20712 (org-paste-subtree nil nil 'for-yank)
20713 (push-mark beg 'nomsg)))
20714 (t
20715 (call-interactively command))))))
20716
20717 (defun org-yank-folding-would-swallow-text (beg end)
20718 "Would hide-subtree at BEG swallow any text after END?"
20719 (let (level)
20720 (org-with-limited-levels
20721 (save-excursion
20722 (goto-char beg)
20723 (when (or (looking-at org-outline-regexp)
20724 (re-search-forward org-outline-regexp-bol end t))
20725 (setq level (org-outline-level)))
20726 (goto-char end)
20727 (skip-chars-forward " \t\r\n\v\f")
20728 (if (or (eobp)
20729 (and (bolp) (looking-at org-outline-regexp)
20730 (<= (org-outline-level) level)))
20731 nil ; Nothing would be swallowed
20732 t))))) ; something would swallow
20733
20734 (define-key org-mode-map "\C-y" 'org-yank)
20735
20736 (defun org-truely-invisible-p ()
20737 "Check if point is at a character currently not visible.
20738 This version does not only check the character property, but also
20739 `visible-mode'."
20740 ;; Early versions of noutline don't have `outline-invisible-p'.
20741 (if (org-bound-and-true-p visible-mode)
20742 nil
20743 (outline-invisible-p)))
20744
20745 (defun org-invisible-p2 ()
20746 "Check if point is at a character currently not visible."
20747 (save-excursion
20748 (if (and (eolp) (not (bobp))) (backward-char 1))
20749 ;; Early versions of noutline don't have `outline-invisible-p'.
20750 (outline-invisible-p)))
20751
20752 (defun org-back-to-heading (&optional invisible-ok)
20753 "Call `outline-back-to-heading', but provide a better error message."
20754 (condition-case nil
20755 (outline-back-to-heading invisible-ok)
20756 (error (error "Before first headline at position %d in buffer %s"
20757 (point) (current-buffer)))))
20758
20759 (defun org-beginning-of-defun ()
20760 "Go to the beginning of the subtree, i.e. back to the heading."
20761 (org-back-to-heading))
20762 (defun org-end-of-defun ()
20763 "Go to the end of the subtree."
20764 (org-end-of-subtree nil t))
20765
20766 (defun org-before-first-heading-p ()
20767 "Before first heading?"
20768 (save-excursion
20769 (end-of-line)
20770 (null (re-search-backward org-outline-regexp-bol nil t))))
20771
20772 (defun org-at-heading-p (&optional ignored)
20773 (outline-on-heading-p t))
20774 ;; Compatibility alias with Org versions < 7.8.03
20775 (defalias 'org-on-heading-p 'org-at-heading-p)
20776
20777 (defun org-at-drawer-p nil
20778 "Whether point is at a drawer."
20779 (save-excursion
20780 (move-beginning-of-line 1)
20781 (looking-at org-drawer-regexp)))
20782
20783 (defun org-point-at-end-of-empty-headline ()
20784 "If point is at the end of an empty headline, return t, else nil.
20785 If the heading only contains a TODO keyword, it is still still considered
20786 empty."
20787 (and (looking-at "[ \t]*$")
20788 (when org-todo-line-regexp
20789 (save-excursion
20790 (beginning-of-line 1)
20791 (let ((case-fold-search nil))
20792 (looking-at org-todo-line-regexp)
20793 (string= (match-string 3) ""))))))
20794
20795 (defun org-at-heading-or-item-p ()
20796 (or (org-at-heading-p) (org-at-item-p)))
20797
20798 (defun org-at-target-p ()
20799 (or (org-in-regexp org-radio-target-regexp)
20800 (org-in-regexp org-target-regexp)))
20801 ;; Compatibility alias with Org versions < 7.8.03
20802 (defalias 'org-on-target-p 'org-at-target-p)
20803
20804 (defun org-up-heading-all (arg)
20805 "Move to the heading line of which the present line is a subheading.
20806 This function considers both visible and invisible heading lines.
20807 With argument, move up ARG levels."
20808 (if (fboundp 'outline-up-heading-all)
20809 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20810 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20811
20812 (defun org-up-heading-safe ()
20813 "Move to the heading line of which the present line is a subheading.
20814 This version will not throw an error. It will return the level of the
20815 headline found, or nil if no higher level is found.
20816
20817 Also, this function will be a lot faster than `outline-up-heading',
20818 because it relies on stars being the outline starters. This can really
20819 make a significant difference in outlines with very many siblings."
20820 (let (start-level re)
20821 (org-back-to-heading t)
20822 (setq start-level (funcall outline-level))
20823 (if (equal start-level 1)
20824 nil
20825 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20826 (if (re-search-backward re nil t)
20827 (funcall outline-level)))))
20828
20829 (defun org-first-sibling-p ()
20830 "Is this heading the first child of its parents?"
20831 (interactive)
20832 (let ((re org-outline-regexp-bol)
20833 level l)
20834 (unless (org-at-heading-p t)
20835 (error "Not at a heading"))
20836 (setq level (funcall outline-level))
20837 (save-excursion
20838 (if (not (re-search-backward re nil t))
20839 t
20840 (setq l (funcall outline-level))
20841 (< l level)))))
20842
20843 (defun org-goto-sibling (&optional previous)
20844 "Goto the next sibling, even if it is invisible.
20845 When PREVIOUS is set, go to the previous sibling instead. Returns t
20846 when a sibling was found. When none is found, return nil and don't
20847 move point."
20848 (let ((fun (if previous 're-search-backward 're-search-forward))
20849 (pos (point))
20850 (re org-outline-regexp-bol)
20851 level l)
20852 (when (condition-case nil (org-back-to-heading t) (error nil))
20853 (setq level (funcall outline-level))
20854 (catch 'exit
20855 (or previous (forward-char 1))
20856 (while (funcall fun re nil t)
20857 (setq l (funcall outline-level))
20858 (when (< l level) (goto-char pos) (throw 'exit nil))
20859 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20860 (goto-char pos)
20861 nil))))
20862
20863 (defun org-show-siblings ()
20864 "Show all siblings of the current headline."
20865 (save-excursion
20866 (while (org-goto-sibling) (org-flag-heading nil)))
20867 (save-excursion
20868 (while (org-goto-sibling 'previous)
20869 (org-flag-heading nil))))
20870
20871 (defun org-goto-first-child ()
20872 "Goto the first child, even if it is invisible.
20873 Return t when a child was found. Otherwise don't move point and
20874 return nil."
20875 (let (level (pos (point)) (re org-outline-regexp-bol))
20876 (when (condition-case nil (org-back-to-heading t) (error nil))
20877 (setq level (outline-level))
20878 (forward-char 1)
20879 (if (and (re-search-forward re nil t) (> (outline-level) level))
20880 (progn (goto-char (match-beginning 0)) t)
20881 (goto-char pos) nil))))
20882
20883 (defun org-show-hidden-entry ()
20884 "Show an entry where even the heading is hidden."
20885 (save-excursion
20886 (org-show-entry)))
20887
20888 (defun org-flag-heading (flag &optional entry)
20889 "Flag the current heading. FLAG non-nil means make invisible.
20890 When ENTRY is non-nil, show the entire entry."
20891 (save-excursion
20892 (org-back-to-heading t)
20893 ;; Check if we should show the entire entry
20894 (if entry
20895 (progn
20896 (org-show-entry)
20897 (save-excursion
20898 (and (outline-next-heading)
20899 (org-flag-heading nil))))
20900 (outline-flag-region (max (point-min) (1- (point)))
20901 (save-excursion (outline-end-of-heading) (point))
20902 flag))))
20903
20904 (defun org-get-next-sibling ()
20905 "Move to next heading of the same level, and return point.
20906 If there is no such heading, return nil.
20907 This is like outline-next-sibling, but invisible headings are ok."
20908 (let ((level (funcall outline-level)))
20909 (outline-next-heading)
20910 (while (and (not (eobp)) (> (funcall outline-level) level))
20911 (outline-next-heading))
20912 (if (or (eobp) (< (funcall outline-level) level))
20913 nil
20914 (point))))
20915
20916 (defun org-get-last-sibling ()
20917 "Move to previous heading of the same level, and return point.
20918 If there is no such heading, return nil."
20919 (let ((opoint (point))
20920 (level (funcall outline-level)))
20921 (outline-previous-heading)
20922 (when (and (/= (point) opoint) (outline-on-heading-p t))
20923 (while (and (> (funcall outline-level) level)
20924 (not (bobp)))
20925 (outline-previous-heading))
20926 (if (< (funcall outline-level) level)
20927 nil
20928 (point)))))
20929
20930 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20931 ;; This contains an exact copy of the original function, but it uses
20932 ;; `org-back-to-heading', to make it work also in invisible
20933 ;; trees. And is uses an invisible-OK argument.
20934 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20935 ;; Furthermore, when used inside Org, finding the end of a large subtree
20936 ;; with many children and grandchildren etc, this can be much faster
20937 ;; than the outline version.
20938 (org-back-to-heading invisible-OK)
20939 (let ((first t)
20940 (level (funcall outline-level)))
20941 (if (and (eq major-mode 'org-mode) (< level 1000))
20942 ;; A true heading (not a plain list item), in Org-mode
20943 ;; This means we can easily find the end by looking
20944 ;; only for the right number of stars. Using a regexp to do
20945 ;; this is so much faster than using a Lisp loop.
20946 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20947 (forward-char 1)
20948 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20949 ;; something else, do it the slow way
20950 (while (and (not (eobp))
20951 (or first (> (funcall outline-level) level)))
20952 (setq first nil)
20953 (outline-next-heading)))
20954 (unless to-heading
20955 (if (memq (preceding-char) '(?\n ?\^M))
20956 (progn
20957 ;; Go to end of line before heading
20958 (forward-char -1)
20959 (if (memq (preceding-char) '(?\n ?\^M))
20960 ;; leave blank line before heading
20961 (forward-char -1))))))
20962 (point))
20963
20964 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20965 "Use Org version in org-mode, for dramatic speed-up."
20966 (if (eq major-mode 'org-mode)
20967 (progn
20968 (org-end-of-subtree nil t)
20969 (unless (eobp) (backward-char 1)))
20970 ad-do-it))
20971
20972 (defun org-end-of-meta-data-and-drawers ()
20973 "Jump to the first text after meta data and drawers in the current entry.
20974 This will move over empty lines, lines with planning time stamps,
20975 clocking lines, and drawers."
20976 (org-back-to-heading t)
20977 (let ((end (save-excursion (outline-next-heading) (point)))
20978 (re (concat "\\(" org-drawer-regexp "\\)"
20979 "\\|" "[ \t]*" org-keyword-time-regexp)))
20980 (forward-line 1)
20981 (while (re-search-forward re end t)
20982 (if (not (match-end 1))
20983 ;; empty or planning line
20984 (forward-line 1)
20985 ;; a drawer, find the end
20986 (re-search-forward "^[ \t]*:END:" end 'move)
20987 (forward-line 1)))
20988 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20989 (point)))
20990
20991 (defun org-forward-same-level (arg &optional invisible-ok)
20992 "Move forward to the arg'th subheading at same level as this one.
20993 Stop at the first and last subheadings of a superior heading.
20994 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20995 it wil also look at invisible ones."
20996 (interactive "p")
20997 (org-back-to-heading invisible-ok)
20998 (org-at-heading-p)
20999 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21000 (re (format "^\\*\\{1,%d\\} " level))
21001 l)
21002 (forward-char 1)
21003 (while (> arg 0)
21004 (while (and (re-search-forward re nil 'move)
21005 (setq l (- (match-end 0) (match-beginning 0) 1))
21006 (= l level)
21007 (not invisible-ok)
21008 (progn (backward-char 1) (outline-invisible-p)))
21009 (if (< l level) (setq arg 1)))
21010 (setq arg (1- arg)))
21011 (beginning-of-line 1)))
21012
21013 (defun org-backward-same-level (arg &optional invisible-ok)
21014 "Move backward to the arg'th subheading at same level as this one.
21015 Stop at the first and last subheadings of a superior heading."
21016 (interactive "p")
21017 (org-back-to-heading)
21018 (org-at-heading-p)
21019 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21020 (re (format "^\\*\\{1,%d\\} " level))
21021 l)
21022 (while (> arg 0)
21023 (while (and (re-search-backward re nil 'move)
21024 (setq l (- (match-end 0) (match-beginning 0) 1))
21025 (= l level)
21026 (not invisible-ok)
21027 (outline-invisible-p))
21028 (if (< l level) (setq arg 1)))
21029 (setq arg (1- arg)))))
21030
21031 (defun org-show-subtree ()
21032 "Show everything after this heading at deeper levels."
21033 (interactive)
21034 (outline-flag-region
21035 (point)
21036 (save-excursion
21037 (org-end-of-subtree t t))
21038 nil))
21039
21040 (defun org-show-entry ()
21041 "Show the body directly following this heading.
21042 Show the heading too, if it is currently invisible."
21043 (interactive)
21044 (save-excursion
21045 (condition-case nil
21046 (progn
21047 (org-back-to-heading t)
21048 (outline-flag-region
21049 (max (point-min) (1- (point)))
21050 (save-excursion
21051 (if (re-search-forward
21052 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21053 (match-beginning 1)
21054 (point-max)))
21055 nil)
21056 (org-cycle-hide-drawers 'children))
21057 (error nil))))
21058
21059 (defun org-make-options-regexp (kwds &optional extra)
21060 "Make a regular expression for keyword lines."
21061 (concat
21062 "^"
21063 "#?[ \t]*\\+\\("
21064 (mapconcat 'regexp-quote kwds "\\|")
21065 (if extra (concat "\\|" extra))
21066 "\\):[ \t]*"
21067 "\\(.*\\)"))
21068
21069 ;; Make isearch reveal the necessary context
21070 (defun org-isearch-end ()
21071 "Reveal context after isearch exits."
21072 (when isearch-success ; only if search was successful
21073 (if (featurep 'xemacs)
21074 ;; Under XEmacs, the hook is run in the correct place,
21075 ;; we directly show the context.
21076 (org-show-context 'isearch)
21077 ;; In Emacs the hook runs *before* restoring the overlays.
21078 ;; So we have to use a one-time post-command-hook to do this.
21079 ;; (Emacs 22 has a special variable, see function `org-mode')
21080 (unless (and (boundp 'isearch-mode-end-hook-quit)
21081 isearch-mode-end-hook-quit)
21082 ;; Only when the isearch was not quitted.
21083 (org-add-hook 'post-command-hook 'org-isearch-post-command
21084 'append 'local)))))
21085
21086 (defun org-isearch-post-command ()
21087 "Remove self from hook, and show context."
21088 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21089 (org-show-context 'isearch))
21090
21091
21092 ;;;; Integration with and fixes for other packages
21093
21094 ;;; Imenu support
21095
21096 (defvar org-imenu-markers nil
21097 "All markers currently used by Imenu.")
21098 (make-variable-buffer-local 'org-imenu-markers)
21099
21100 (defun org-imenu-new-marker (&optional pos)
21101 "Return a new marker for use by Imenu, and remember the marker."
21102 (let ((m (make-marker)))
21103 (move-marker m (or pos (point)))
21104 (push m org-imenu-markers)
21105 m))
21106
21107 (defun org-imenu-get-tree ()
21108 "Produce the index for Imenu."
21109 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21110 (setq org-imenu-markers nil)
21111 (let* ((n org-imenu-depth)
21112 (re (concat "^" (org-get-limited-outline-regexp)))
21113 (subs (make-vector (1+ n) nil))
21114 (last-level 0)
21115 m level head)
21116 (save-excursion
21117 (save-restriction
21118 (widen)
21119 (goto-char (point-max))
21120 (while (re-search-backward re nil t)
21121 (setq level (org-reduced-level (funcall outline-level)))
21122 (when (and (<= level n)
21123 (looking-at org-complex-heading-regexp))
21124 (setq head (org-link-display-format
21125 (org-match-string-no-properties 4))
21126 m (org-imenu-new-marker))
21127 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21128 (if (>= level last-level)
21129 (push (cons head m) (aref subs level))
21130 (push (cons head (aref subs (1+ level))) (aref subs level))
21131 (loop for i from (1+ level) to n do (aset subs i nil)))
21132 (setq last-level level)))))
21133 (aref subs 1)))
21134
21135 (eval-after-load "imenu"
21136 '(progn
21137 (add-hook 'imenu-after-jump-hook
21138 (lambda ()
21139 (if (eq major-mode 'org-mode)
21140 (org-show-context 'org-goto))))))
21141
21142 (defun org-link-display-format (link)
21143 "Replace a link with either the description, or the link target
21144 if no description is present"
21145 (save-match-data
21146 (if (string-match org-bracket-link-analytic-regexp link)
21147 (replace-match (if (match-end 5)
21148 (match-string 5 link)
21149 (concat (match-string 1 link)
21150 (match-string 3 link)))
21151 nil t link)
21152 link)))
21153
21154 (defun org-toggle-link-display ()
21155 "Toggle the literal or descriptive display of links."
21156 (interactive)
21157 (if org-descriptive-links
21158 (progn (org-remove-from-invisibility-spec '(org-link))
21159 (org-restart-font-lock)
21160 (setq org-descriptive-links nil))
21161 (progn (add-to-invisibility-spec '(org-link))
21162 (org-restart-font-lock)
21163 (setq org-descriptive-links t))))
21164
21165 ;; Speedbar support
21166
21167 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21168 "Overlay marking the agenda restriction line in speedbar.")
21169 (overlay-put org-speedbar-restriction-lock-overlay
21170 'face 'org-agenda-restriction-lock)
21171 (overlay-put org-speedbar-restriction-lock-overlay
21172 'help-echo "Agendas are currently limited to this item.")
21173 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21174
21175 (defun org-speedbar-set-agenda-restriction ()
21176 "Restrict future agenda commands to the location at point in speedbar.
21177 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21178 (interactive)
21179 (require 'org-agenda)
21180 (let (p m tp np dir txt)
21181 (cond
21182 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21183 'org-imenu t))
21184 (setq m (get-text-property p 'org-imenu-marker))
21185 (with-current-buffer (marker-buffer m)
21186 (goto-char m)
21187 (org-agenda-set-restriction-lock 'subtree)))
21188 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21189 'speedbar-function 'speedbar-find-file))
21190 (setq tp (previous-single-property-change
21191 (1+ p) 'speedbar-function)
21192 np (next-single-property-change
21193 tp 'speedbar-function)
21194 dir (speedbar-line-directory)
21195 txt (buffer-substring-no-properties (or tp (point-min))
21196 (or np (point-max))))
21197 (with-current-buffer (find-file-noselect
21198 (let ((default-directory dir))
21199 (expand-file-name txt)))
21200 (unless (eq major-mode 'org-mode)
21201 (error "Cannot restrict to non-Org-mode file"))
21202 (org-agenda-set-restriction-lock 'file)))
21203 (t (error "Don't know how to restrict Org-mode's agenda")))
21204 (move-overlay org-speedbar-restriction-lock-overlay
21205 (point-at-bol) (point-at-eol))
21206 (setq current-prefix-arg nil)
21207 (org-agenda-maybe-redo)))
21208
21209 (eval-after-load "speedbar"
21210 '(progn
21211 (speedbar-add-supported-extension ".org")
21212 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21213 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21214 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21215 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21216 (add-hook 'speedbar-visiting-tag-hook
21217 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21218
21219 ;;; Fixes and Hacks for problems with other packages
21220
21221 ;; Make flyspell not check words in links, to not mess up our keymap
21222 (defun org-mode-flyspell-verify ()
21223 "Don't let flyspell put overlays at active buttons, or on
21224 {todo,all-time,additional-option-like}-keywords."
21225 (let ((pos (max (1- (point)) (point-min)))
21226 (word (thing-at-point 'word)))
21227 (and (not (get-text-property pos 'keymap))
21228 (not (get-text-property pos 'org-no-flyspell))
21229 (not (member word org-todo-keywords-1))
21230 (not (member word org-all-time-keywords))
21231 (not (member word org-additional-option-like-keywords)))))
21232
21233 (defun org-remove-flyspell-overlays-in (beg end)
21234 "Remove flyspell overlays in region."
21235 (and (org-bound-and-true-p flyspell-mode)
21236 (fboundp 'flyspell-delete-region-overlays)
21237 (flyspell-delete-region-overlays beg end))
21238 (add-text-properties beg end '(org-no-flyspell t)))
21239
21240 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21241 (eval-after-load "bookmark"
21242 '(if (boundp 'bookmark-after-jump-hook)
21243 ;; We can use the hook
21244 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21245 ;; Hook not available, use advice
21246 (defadvice bookmark-jump (after org-make-visible activate)
21247 "Make the position visible."
21248 (org-bookmark-jump-unhide))))
21249
21250 ;; Make sure saveplace shows the location if it was hidden
21251 (eval-after-load "saveplace"
21252 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21253 "Make the position visible."
21254 (org-bookmark-jump-unhide)))
21255
21256 ;; Make sure ecb shows the location if it was hidden
21257 (eval-after-load "ecb"
21258 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21259 "Make hierarchy visible when jumping into location from ECB tree buffer."
21260 (if (eq major-mode 'org-mode)
21261 (org-show-context))))
21262
21263 (defun org-bookmark-jump-unhide ()
21264 "Unhide the current position, to show the bookmark location."
21265 (and (eq major-mode 'org-mode)
21266 (or (outline-invisible-p)
21267 (save-excursion (goto-char (max (point-min) (1- (point))))
21268 (outline-invisible-p)))
21269 (org-show-context 'bookmark-jump)))
21270
21271 ;; Make session.el ignore our circular variable
21272 (eval-after-load "session"
21273 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21274
21275 ;;;; Experimental code
21276
21277 (defun org-closed-in-range ()
21278 "Sparse tree of items closed in a certain time range.
21279 Still experimental, may disappear in the future."
21280 (interactive)
21281 ;; Get the time interval from the user.
21282 (let* ((time1 (org-float-time
21283 (org-read-date nil 'to-time nil "Starting date: ")))
21284 (time2 (org-float-time
21285 (org-read-date nil 'to-time nil "End date:")))
21286 ;; callback function
21287 (callback (lambda ()
21288 (let ((time
21289 (org-float-time
21290 (apply 'encode-time
21291 (org-parse-time-string
21292 (match-string 1))))))
21293 ;; check if time in interval
21294 (and (>= time time1) (<= time time2))))))
21295 ;; make tree, check each match with the callback
21296 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21297
21298 ;;;; Finish up
21299
21300 (provide 'org)
21301
21302 (run-hooks 'org-load-hook)
21303
21304 ;;; org.el ends here