]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
Merge from emacs-24
[gnu-emacs] / lisp / org / org.el
1 ;;; org.el --- Outline-based notes management and organizer
2
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
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 ;;; Commentary:
27 ;;
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
30 ;;
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
45 ;;
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
49 ;;
50 ;; http://orgmode.org/org.html#Installation
51 ;;
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
59 ;;
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
62 ;;
63 ;;; Code:
64
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
69
70 ;;;; Require other packages
71
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
75
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
79
80 (load "org-loaddefs.el" t t t)
81
82 (require 'org-macs)
83 (require 'org-compat)
84
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
87 ;;
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
94
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
99
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
103
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
113
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
139
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
162
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
165
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
181
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
209
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
268
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
278
279 ;;; Version
280 (org-check-version)
281
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message version1))
313 version1)))
314
315 (defconst org-version (org-version))
316
317 ;;; Compatibility constants
318
319 ;;; The custom variables
320
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
326
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
331
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
336
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
342
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
346
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
355
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
361
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
364
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
368
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
373
374 \(provide 'org-xyz)
375
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
444
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
448
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
452
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
457
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
478
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
532
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
540
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
543
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
550
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
559
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
565
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
573
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
576
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
584
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
587
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
590
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
594
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
598
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
610
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
615
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
620
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
625
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
635
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
642
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
647
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
654
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
662
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
668
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
674
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
687
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
692
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
697
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
708
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
718
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
721
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
730
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
740
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
750
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
756
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
762
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
769
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
771
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
782
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
788
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
802
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
809
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
813
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots.
817 When a string, use that string instead.
818 When a face, use the standard 3 dots, but with the specified face.
819 The change affects only Org-mode (which will then use its own display table).
820 Changing this requires executing `M-x org-mode RET' in a buffer to become
821 effective."
822 :group 'org-startup
823 :type '(choice (const :tag "Default" nil)
824 (face :tag "Face" :value org-warning)
825 (string :tag "String" :value "...#")))
826
827 (defvar org-display-table nil
828 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
829
830 (defgroup org-keywords nil
831 "Keywords in Org-mode."
832 :tag "Org Keywords"
833 :group 'org)
834
835 (defcustom org-deadline-string "DEADLINE:"
836 "String to mark deadline entries.
837 A deadline is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-deadline].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
843
844 (defcustom org-scheduled-string "SCHEDULED:"
845 "String to mark scheduled TODO entries.
846 A schedule is this string, followed by a time stamp. Should be a word,
847 terminated by a colon. You can insert a schedule keyword and
848 a timestamp with \\[org-schedule].
849 Changes become only effective after restarting Emacs."
850 :group 'org-keywords
851 :type 'string)
852
853 (defcustom org-closed-string "CLOSED:"
854 "String used as the prefix for timestamps logging closing a TODO entry."
855 :group 'org-keywords
856 :type 'string)
857
858 (defcustom org-clock-string "CLOCK:"
859 "String used as prefix for timestamps clocking work hours on an item."
860 :group 'org-keywords
861 :type 'string)
862
863 (defcustom org-closed-keep-when-no-todo nil
864 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
865 :group 'org-todo
866 :group 'org-keywords
867 :version "24.4"
868 :package-version '(Org . "8.0")
869 :type 'boolean)
870
871 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
872 org-scheduled-string "\\|"
873 org-deadline-string "\\|"
874 org-closed-string "\\|"
875 org-clock-string "\\)")
876 "Matches a line with planning or clock info.")
877
878 (defcustom org-comment-string "COMMENT"
879 "Entries starting with this keyword will never be exported.
880 An entry can be toggled between COMMENT and normal with
881 \\[org-toggle-comment].
882 Changes become only effective after restarting Emacs."
883 :group 'org-keywords
884 :type 'string)
885
886 (defcustom org-quote-string "QUOTE"
887 "Entries starting with this keyword will be exported in fixed-width font.
888 Quoting applies only to the text in the entry following the headline, and does
889 not extend beyond the next headline, even if that is lower level.
890 An entry can be toggled between QUOTE and normal with
891 \\[org-toggle-fixed-width-section]."
892 :group 'org-keywords
893 :type 'string)
894
895 (defconst org-repeat-re
896 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
897 "Regular expression for specifying repeated events.
898 After a match, group 1 contains the repeat expression.")
899
900 (defgroup org-structure nil
901 "Options concerning the general structure of Org-mode files."
902 :tag "Org Structure"
903 :group 'org)
904
905 (defgroup org-reveal-location nil
906 "Options about how to make context of a location visible."
907 :tag "Org Reveal Location"
908 :group 'org-structure)
909
910 (defconst org-context-choice
911 '(choice
912 (const :tag "Always" t)
913 (const :tag "Never" nil)
914 (repeat :greedy t :tag "Individual contexts"
915 (cons
916 (choice :tag "Context"
917 (const agenda)
918 (const org-goto)
919 (const occur-tree)
920 (const tags-tree)
921 (const link-search)
922 (const mark-goto)
923 (const bookmark-jump)
924 (const isearch)
925 (const default))
926 (boolean))))
927 "Contexts for the reveal options.")
928
929 (defcustom org-show-hierarchy-above '((default . t))
930 "Non-nil means show full hierarchy when revealing a location.
931 Org-mode often shows locations in an org-mode file which might have
932 been invisible before. When this is set, the hierarchy of headings
933 above the exposed location is shown.
934 Turning this off for example for sparse trees makes them very compact.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. Valid contexts are
937 agenda when exposing an entry from the agenda
938 org-goto when using the command `org-goto' on key C-c C-j
939 occur-tree when using the command `org-occur' on key C-c /
940 tags-tree when constructing a sparse tree based on tags matches
941 link-search when exposing search matches associated with a link
942 mark-goto when exposing the jump goal of a mark
943 bookmark-jump when exposing a bookmark location
944 isearch when exiting from an incremental search
945 default default for all contexts not set explicitly"
946 :group 'org-reveal-location
947 :type org-context-choice)
948
949 (defcustom org-show-following-heading '((default . nil))
950 "Non-nil means show following heading when revealing a location.
951 Org-mode often shows locations in an org-mode file which might have
952 been invisible before. When this is set, the heading following the
953 match is shown.
954 Turning this off for example for sparse trees makes them very compact,
955 but makes it harder to edit the location of the match. In such a case,
956 use the command \\[org-reveal] to show more context.
957 Instead of t, this can also be an alist specifying this option for different
958 contexts. See `org-show-hierarchy-above' for valid contexts."
959 :group 'org-reveal-location
960 :type org-context-choice)
961
962 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
963 "Non-nil means show all sibling heading when revealing a location.
964 Org-mode often shows locations in an org-mode file which might have
965 been invisible before. When this is set, the sibling of the current entry
966 heading are all made visible. If `org-show-hierarchy-above' is t,
967 the same happens on each level of the hierarchy above the current entry.
968
969 By default this is on for the isearch context, off for all other contexts.
970 Turning this off for example for sparse trees makes them very compact,
971 but makes it harder to edit the location of the match. In such a case,
972 use the command \\[org-reveal] to show more context.
973 Instead of t, this can also be an alist specifying this option for different
974 contexts. See `org-show-hierarchy-above' for valid contexts."
975 :group 'org-reveal-location
976 :type org-context-choice
977 :version "24.4"
978 :package-version '(Org . "8.0"))
979
980 (defcustom org-show-entry-below '((default . nil))
981 "Non-nil means show the entry below a headline when revealing a location.
982 Org-mode often shows locations in an org-mode file which might have
983 been invisible before. When this is set, the text below the headline that is
984 exposed is also shown.
985
986 By default this is off for all contexts.
987 Instead of t, this can also be an alist specifying this option for different
988 contexts. See `org-show-hierarchy-above' for valid contexts."
989 :group 'org-reveal-location
990 :type org-context-choice)
991
992 (defcustom org-indirect-buffer-display 'other-window
993 "How should indirect tree buffers be displayed?
994 This applies to indirect buffers created with the commands
995 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
996 Valid values are:
997 current-window Display in the current window
998 other-window Just display in another window.
999 dedicated-frame Create one new frame, and re-use it each time.
1000 new-frame Make a new frame each time. Note that in this case
1001 previously-made indirect buffers are kept, and you need to
1002 kill these buffers yourself."
1003 :group 'org-structure
1004 :group 'org-agenda-windows
1005 :type '(choice
1006 (const :tag "In current window" current-window)
1007 (const :tag "In current frame, other window" other-window)
1008 (const :tag "Each time a new frame" new-frame)
1009 (const :tag "One dedicated frame" dedicated-frame)))
1010
1011 (defcustom org-use-speed-commands nil
1012 "Non-nil means activate single letter commands at beginning of a headline.
1013 This may also be a function to test for appropriate locations where speed
1014 commands should be active."
1015 :group 'org-structure
1016 :type '(choice
1017 (const :tag "Never" nil)
1018 (const :tag "At beginning of headline stars" t)
1019 (function)))
1020
1021 (defcustom org-speed-commands-user nil
1022 "Alist of additional speed commands.
1023 This list will be checked before `org-speed-commands-default'
1024 when the variable `org-use-speed-commands' is non-nil
1025 and when the cursor is at the beginning of a headline.
1026 The car if each entry is a string with a single letter, which must
1027 be assigned to `self-insert-command' in the global map.
1028 The cdr is either a command to be called interactively, a function
1029 to be called, or a form to be evaluated.
1030 An entry that is just a list with a single string will be interpreted
1031 as a descriptive headline that will be added when listing the speed
1032 commands in the Help buffer using the `?' speed command."
1033 :group 'org-structure
1034 :type '(repeat :value ("k" . ignore)
1035 (choice :value ("k" . ignore)
1036 (list :tag "Descriptive Headline" (string :tag "Headline"))
1037 (cons :tag "Letter and Command"
1038 (string :tag "Command letter")
1039 (choice
1040 (function)
1041 (sexp))))))
1042
1043 (defcustom org-bookmark-names-plist
1044 '(:last-capture "org-capture-last-stored"
1045 :last-refile "org-refile-last-stored"
1046 :last-capture-marker "org-capture-last-stored-marker")
1047 "Names for bookmarks automatically set by some Org commands.
1048 This can provide strings as names for a number of bookmarks Org sets
1049 automatically. The following keys are currently implemented:
1050 :last-capture
1051 :last-capture-marker
1052 :last-refile
1053 When a key does not show up in the property list, the corresponding bookmark
1054 is not set."
1055 :group 'org-structure
1056 :type 'plist)
1057
1058 (defgroup org-cycle nil
1059 "Options concerning visibility cycling in Org-mode."
1060 :tag "Org Cycle"
1061 :group 'org-structure)
1062
1063 (defcustom org-cycle-skip-children-state-if-no-children t
1064 "Non-nil means skip CHILDREN state in entries that don't have any."
1065 :group 'org-cycle
1066 :type 'boolean)
1067
1068 (defcustom org-cycle-max-level nil
1069 "Maximum level which should still be subject to visibility cycling.
1070 Levels higher than this will, for cycling, be treated as text, not a headline.
1071 When `org-odd-levels-only' is set, a value of N in this variable actually
1072 means 2N-1 stars as the limiting headline.
1073 When nil, cycle all levels.
1074 Note that the limiting level of cycling is also influenced by
1075 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1076 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1077 than its value."
1078 :group 'org-cycle
1079 :type '(choice
1080 (const :tag "No limit" nil)
1081 (integer :tag "Maximum level")))
1082
1083 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1084 "Names of drawers. Drawers are not opened by cycling on the headline above.
1085 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1086 this:
1087 :DRAWERNAME:
1088 .....
1089 :END:
1090 The drawer \"PROPERTIES\" is special for capturing properties through
1091 the property API.
1092
1093 Drawers can be defined on the per-file basis with a line like:
1094
1095 #+DRAWERS: HIDDEN STATE PROPERTIES"
1096 :group 'org-structure
1097 :group 'org-cycle
1098 :type '(repeat (string :tag "Drawer Name")))
1099
1100 (defcustom org-hide-block-startup nil
1101 "Non-nil means entering Org-mode will fold all blocks.
1102 This can also be set in on a per-file basis with
1103
1104 #+STARTUP: hideblocks
1105 #+STARTUP: showblocks"
1106 :group 'org-startup
1107 :group 'org-cycle
1108 :type 'boolean)
1109
1110 (defcustom org-cycle-global-at-bob nil
1111 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1112 This makes it possible to do global cycling without having to use S-TAB or
1113 \\[universal-argument] TAB. For this special case to work, the first line
1114 of the buffer must not be a headline -- it may be empty or some other text.
1115 When used in this way, `org-cycle-hook' is disabled temporarily to make
1116 sure the cursor stays at the beginning of the buffer. When this option is
1117 nil, don't do anything special at the beginning of the buffer."
1118 :group 'org-cycle
1119 :type 'boolean)
1120
1121 (defcustom org-cycle-level-after-item/entry-creation t
1122 "Non-nil means cycle entry level or item indentation in new empty entries.
1123
1124 When the cursor is at the end of an empty headline, i.e., with only stars
1125 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1126 and then all possible ancestor states, before returning to the original state.
1127 This makes data entry extremely fast: M-RET to create a new headline,
1128 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1129
1130 When the cursor is at the end of an empty plain list item, one TAB will
1131 make it a subitem, two or more tabs will back up to make this an item
1132 higher up in the item hierarchy."
1133 :group 'org-cycle
1134 :type 'boolean)
1135
1136 (defcustom org-cycle-emulate-tab t
1137 "Where should `org-cycle' emulate TAB.
1138 nil Never
1139 white Only in completely white lines
1140 whitestart Only at the beginning of lines, before the first non-white char
1141 t Everywhere except in headlines
1142 exc-hl-bol Everywhere except at the start of a headline
1143 If TAB is used in a place where it does not emulate TAB, the current subtree
1144 visibility is cycled."
1145 :group 'org-cycle
1146 :type '(choice (const :tag "Never" nil)
1147 (const :tag "Only in completely white lines" white)
1148 (const :tag "Before first char in a line" whitestart)
1149 (const :tag "Everywhere except in headlines" t)
1150 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1151
1152 (defcustom org-cycle-separator-lines 2
1153 "Number of empty lines needed to keep an empty line between collapsed trees.
1154 If you leave an empty line between the end of a subtree and the following
1155 headline, this empty line is hidden when the subtree is folded.
1156 Org-mode will leave (exactly) one empty line visible if the number of
1157 empty lines is equal or larger to the number given in this variable.
1158 So the default 2 means at least 2 empty lines after the end of a subtree
1159 are needed to produce free space between a collapsed subtree and the
1160 following headline.
1161
1162 If the number is negative, and the number of empty lines is at least -N,
1163 all empty lines are shown.
1164
1165 Special case: when 0, never leave empty lines in collapsed view."
1166 :group 'org-cycle
1167 :type 'integer)
1168 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1169
1170 (defcustom org-pre-cycle-hook nil
1171 "Hook that is run before visibility cycling is happening.
1172 The function(s) in this hook must accept a single argument which indicates
1173 the new state that will be set right after running this hook. The
1174 argument is a symbol. Before a global state change, it can have the values
1175 `overview', `content', or `all'. Before a local state change, it can have
1176 the values `folded', `children', or `subtree'."
1177 :group 'org-cycle
1178 :type 'hook)
1179
1180 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1181 org-cycle-hide-drawers
1182 org-cycle-hide-inline-tasks
1183 org-cycle-show-empty-lines
1184 org-optimize-window-after-visibility-change)
1185 "Hook that is run after `org-cycle' has changed the buffer visibility.
1186 The function(s) in this hook must accept a single argument which indicates
1187 the new state that was set by the most recent `org-cycle' command. The
1188 argument is a symbol. After a global state change, it can have the values
1189 `overview', `contents', or `all'. After a local state change, it can have
1190 the values `folded', `children', or `subtree'."
1191 :group 'org-cycle
1192 :type 'hook)
1193
1194 (defgroup org-edit-structure nil
1195 "Options concerning structure editing in Org-mode."
1196 :tag "Org Edit Structure"
1197 :group 'org-structure)
1198
1199 (defcustom org-odd-levels-only nil
1200 "Non-nil means skip even levels and only use odd levels for the outline.
1201 This has the effect that two stars are being added/taken away in
1202 promotion/demotion commands. It also influences how levels are
1203 handled by the exporters.
1204 Changing it requires restart of `font-lock-mode' to become effective
1205 for fontification also in regions already fontified.
1206 You may also set this on a per-file basis by adding one of the following
1207 lines to the buffer:
1208
1209 #+STARTUP: odd
1210 #+STARTUP: oddeven"
1211 :group 'org-edit-structure
1212 :group 'org-appearance
1213 :type 'boolean)
1214
1215 (defcustom org-adapt-indentation t
1216 "Non-nil means adapt indentation to outline node level.
1217
1218 When this variable is set, Org assumes that you write outlines by
1219 indenting text in each node to align with the headline (after the stars).
1220 The following issues are influenced by this variable:
1221
1222 - When this is set and the *entire* text in an entry is indented, the
1223 indentation is increased by one space in a demotion command, and
1224 decreased by one in a promotion command. If any line in the entry
1225 body starts with text at column 0, indentation is not changed at all.
1226
1227 - Property drawers and planning information is inserted indented when
1228 this variable s set. When nil, they will not be indented.
1229
1230 - TAB indents a line relative to context. The lines below a headline
1231 will be indented when this variable is set.
1232
1233 Note that this is all about true indentation, by adding and removing
1234 space characters. See also `org-indent.el' which does level-dependent
1235 indentation in a virtual way, i.e. at display time in Emacs."
1236 :group 'org-edit-structure
1237 :type 'boolean)
1238
1239 (defcustom org-special-ctrl-a/e nil
1240 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1241
1242 When t, `C-a' will bring back the cursor to the beginning of the
1243 headline text, i.e. after the stars and after a possible TODO
1244 keyword. In an item, this will be the position after bullet and
1245 check-box, if any. When the cursor is already at that position,
1246 another `C-a' will bring it to the beginning of the line.
1247
1248 `C-e' will jump to the end of the headline, ignoring the presence
1249 of tags in the headline. A second `C-e' will then jump to the
1250 true end of the line, after any tags. This also means that, when
1251 this variable is non-nil, `C-e' also will never jump beyond the
1252 end of the heading of a folded section, i.e. not after the
1253 ellipses.
1254
1255 When set to the symbol `reversed', the first `C-a' or `C-e' works
1256 normally, going to the true line boundary first. Only a directly
1257 following, identical keypress will bring the cursor to the
1258 special positions.
1259
1260 This may also be a cons cell where the behavior for `C-a' and
1261 `C-e' is set separately."
1262 :group 'org-edit-structure
1263 :type '(choice
1264 (const :tag "off" nil)
1265 (const :tag "on: after stars/bullet and before tags first" t)
1266 (const :tag "reversed: true line boundary first" reversed)
1267 (cons :tag "Set C-a and C-e separately"
1268 (choice :tag "Special C-a"
1269 (const :tag "off" nil)
1270 (const :tag "on: after stars/bullet first" t)
1271 (const :tag "reversed: before stars/bullet first" reversed))
1272 (choice :tag "Special C-e"
1273 (const :tag "off" nil)
1274 (const :tag "on: before tags first" t)
1275 (const :tag "reversed: after tags first" reversed)))))
1276 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1277
1278 (defcustom org-special-ctrl-k nil
1279 "Non-nil means `C-k' will behave specially in headlines.
1280 When nil, `C-k' will call the default `kill-line' command.
1281 When t, the following will happen while the cursor is in the headline:
1282
1283 - When the cursor is at the beginning of a headline, kill the entire
1284 line and possible the folded subtree below the line.
1285 - When in the middle of the headline text, kill the headline up to the tags.
1286 - When after the headline text, kill the tags."
1287 :group 'org-edit-structure
1288 :type 'boolean)
1289
1290 (defcustom org-ctrl-k-protect-subtree nil
1291 "Non-nil means, do not delete a hidden subtree with C-k.
1292 When set to the symbol `error', simply throw an error when C-k is
1293 used to kill (part-of) a headline that has hidden text behind it.
1294 Any other non-nil value will result in a query to the user, if it is
1295 OK to kill that hidden subtree. When nil, kill without remorse."
1296 :group 'org-edit-structure
1297 :version "24.1"
1298 :type '(choice
1299 (const :tag "Do not protect hidden subtrees" nil)
1300 (const :tag "Protect hidden subtrees with a security query" t)
1301 (const :tag "Never kill a hidden subtree with C-k" error)))
1302
1303 (defcustom org-special-ctrl-o t
1304 "Non-nil means, make `C-o' insert a row in tables."
1305 :group 'org-edit-structure
1306 :type 'boolean)
1307
1308 (defcustom org-catch-invisible-edits nil
1309 "Check if in invisible region before inserting or deleting a character.
1310 Valid values are:
1311
1312 nil Do not check, so just do invisible edits.
1313 error Throw an error and do nothing.
1314 show Make point visible, and do the requested edit.
1315 show-and-error Make point visible, then throw an error and abort the edit.
1316 smart Make point visible, and do insertion/deletion if it is
1317 adjacent to visible text and the change feels predictable.
1318 Never delete a previously invisible character or add in the
1319 middle or right after an invisible region. Basically, this
1320 allows insertion and backward-delete right before ellipses.
1321 FIXME: maybe in this case we should not even show?"
1322 :group 'org-edit-structure
1323 :version "24.1"
1324 :type '(choice
1325 (const :tag "Do not check" nil)
1326 (const :tag "Throw error when trying to edit" error)
1327 (const :tag "Unhide, but do not do the edit" show-and-error)
1328 (const :tag "Show invisible part and do the edit" show)
1329 (const :tag "Be smart and do the right thing" smart)))
1330
1331 (defcustom org-yank-folded-subtrees t
1332 "Non-nil means when yanking subtrees, fold them.
1333 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1334 it starts with a heading and all other headings in it are either children
1335 or siblings, then fold all the subtrees. However, do this only if no
1336 text after the yank would be swallowed into a folded tree by this action."
1337 :group 'org-edit-structure
1338 :type 'boolean)
1339
1340 (defcustom org-yank-adjusted-subtrees nil
1341 "Non-nil means when yanking subtrees, adjust the level.
1342 With this setting, `org-paste-subtree' is used to insert the subtree, see
1343 this function for details."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1346
1347 (defcustom org-M-RET-may-split-line '((default . t))
1348 "Non-nil means M-RET will split the line at the cursor position.
1349 When nil, it will go to the end of the line before making a
1350 new line.
1351 You may also set this option in a different way for different
1352 contexts. Valid contexts are:
1353
1354 headline when creating a new headline
1355 item when creating a new item
1356 table in a table field
1357 default the value to be used for all contexts not explicitly
1358 customized"
1359 :group 'org-structure
1360 :group 'org-table
1361 :type '(choice
1362 (const :tag "Always" t)
1363 (const :tag "Never" nil)
1364 (repeat :greedy t :tag "Individual contexts"
1365 (cons
1366 (choice :tag "Context"
1367 (const headline)
1368 (const item)
1369 (const table)
1370 (const default))
1371 (boolean)))))
1372
1373
1374 (defcustom org-insert-heading-respect-content nil
1375 "Non-nil means insert new headings after the current subtree.
1376 When nil, the new heading is created directly after the current line.
1377 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1378 this variable on for the duration of the command."
1379 :group 'org-structure
1380 :type 'boolean)
1381
1382 (defcustom org-blank-before-new-entry '((heading . auto)
1383 (plain-list-item . auto))
1384 "Should `org-insert-heading' leave a blank line before new heading/item?
1385 The value is an alist, with `heading' and `plain-list-item' as CAR,
1386 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1387 which case Org will look at the surrounding headings/items and try to
1388 make an intelligent decision whether to insert a blank line or not.
1389
1390 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1391 the setting here is ignored and no empty line is inserted to avoid breaking
1392 the list structure."
1393 :group 'org-edit-structure
1394 :type '(list
1395 (cons (const heading)
1396 (choice (const :tag "Never" nil)
1397 (const :tag "Always" t)
1398 (const :tag "Auto" auto)))
1399 (cons (const plain-list-item)
1400 (choice (const :tag "Never" nil)
1401 (const :tag "Always" t)
1402 (const :tag "Auto" auto)))))
1403
1404 (defcustom org-insert-heading-hook nil
1405 "Hook being run after inserting a new heading."
1406 :group 'org-edit-structure
1407 :type 'hook)
1408
1409 (defcustom org-enable-fixed-width-editor t
1410 "Non-nil means lines starting with \":\" are treated as fixed-width.
1411 This currently only means they are never auto-wrapped.
1412 When nil, such lines will be treated like ordinary lines.
1413 See also the QUOTE keyword."
1414 :group 'org-edit-structure
1415 :type 'boolean)
1416
1417 (defcustom org-goto-auto-isearch t
1418 "Non-nil means typing characters in `org-goto' starts incremental search.
1419 When nil, you can use these keybindings to navigate the buffer:
1420
1421 q Quit the org-goto interface
1422 n Go to the next visible heading
1423 p Go to the previous visible heading
1424 f Go one heading forward on same level
1425 b Go one heading backward on same level
1426 u Go one heading up"
1427 :group 'org-edit-structure
1428 :type 'boolean)
1429
1430 (defgroup org-sparse-trees nil
1431 "Options concerning sparse trees in Org-mode."
1432 :tag "Org Sparse Trees"
1433 :group 'org-structure)
1434
1435 (defcustom org-highlight-sparse-tree-matches t
1436 "Non-nil means highlight all matches that define a sparse tree.
1437 The highlights will automatically disappear the next time the buffer is
1438 changed by an edit command."
1439 :group 'org-sparse-trees
1440 :type 'boolean)
1441
1442 (defcustom org-remove-highlights-with-change t
1443 "Non-nil means any change to the buffer will remove temporary highlights.
1444 Such highlights are created by `org-occur' and `org-clock-display'.
1445 When nil, `C-c C-c needs to be used to get rid of the highlights.
1446 The highlights created by `org-preview-latex-fragment' always need
1447 `C-c C-c' to be removed."
1448 :group 'org-sparse-trees
1449 :group 'org-time
1450 :type 'boolean)
1451
1452
1453 (defcustom org-occur-hook '(org-first-headline-recenter)
1454 "Hook that is run after `org-occur' has constructed a sparse tree.
1455 This can be used to recenter the window to show as much of the structure
1456 as possible."
1457 :group 'org-sparse-trees
1458 :type 'hook)
1459
1460 (defgroup org-imenu-and-speedbar nil
1461 "Options concerning imenu and speedbar in Org-mode."
1462 :tag "Org Imenu and Speedbar"
1463 :group 'org-structure)
1464
1465 (defcustom org-imenu-depth 2
1466 "The maximum level for Imenu access to Org-mode headlines.
1467 This also applied for speedbar access."
1468 :group 'org-imenu-and-speedbar
1469 :type 'integer)
1470
1471 (defgroup org-table nil
1472 "Options concerning tables in Org-mode."
1473 :tag "Org Table"
1474 :group 'org)
1475
1476 (defcustom org-enable-table-editor 'optimized
1477 "Non-nil means lines starting with \"|\" are handled by the table editor.
1478 When nil, such lines will be treated like ordinary lines.
1479
1480 When equal to the symbol `optimized', the table editor will be optimized to
1481 do the following:
1482 - Automatic overwrite mode in front of whitespace in table fields.
1483 This makes the structure of the table stay in tact as long as the edited
1484 field does not exceed the column width.
1485 - Minimize the number of realigns. Normally, the table is aligned each time
1486 TAB or RET are pressed to move to another field. With optimization this
1487 happens only if changes to a field might have changed the column width.
1488 Optimization requires replacing the functions `self-insert-command',
1489 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1490 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1491 very good at guessing when a re-align will be necessary, but you can always
1492 force one with \\[org-ctrl-c-ctrl-c].
1493
1494 If you would like to use the optimized version in Org-mode, but the
1495 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1496
1497 This variable can be used to turn on and off the table editor during a session,
1498 but in order to toggle optimization, a restart is required.
1499
1500 See also the variable `org-table-auto-blank-field'."
1501 :group 'org-table
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on" t)
1505 (const :tag "on, optimized" optimized)))
1506
1507 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1508 (version<= emacs-version "24.1"))
1509 "Non-nil means cluster self-insert commands for undo when possible.
1510 If this is set, then, like in the Emacs command loop, 20 consecutive
1511 characters will be undone together.
1512 This is configurable, because there is some impact on typing performance."
1513 :group 'org-table
1514 :type 'boolean)
1515
1516 (defcustom org-table-tab-recognizes-table.el t
1517 "Non-nil means TAB will automatically notice a table.el table.
1518 When it sees such a table, it moves point into it and - if necessary -
1519 calls `table-recognize-table'."
1520 :group 'org-table-editing
1521 :type 'boolean)
1522
1523 (defgroup org-link nil
1524 "Options concerning links in Org-mode."
1525 :tag "Org Link"
1526 :group 'org)
1527
1528 (defvar org-link-abbrev-alist-local nil
1529 "Buffer-local version of `org-link-abbrev-alist', which see.
1530 The value of this is taken from the #+LINK lines.")
1531 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1532
1533 (defcustom org-link-abbrev-alist nil
1534 "Alist of link abbreviations.
1535 The car of each element is a string, to be replaced at the start of a link.
1536 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1537 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1538
1539 [[linkkey:tag][description]]
1540
1541 The 'linkkey' must be a word word, starting with a letter, followed
1542 by letters, numbers, '-' or '_'.
1543
1544 If REPLACE is a string, the tag will simply be appended to create the link.
1545 If the string contains \"%s\", the tag will be inserted there. If the string
1546 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1547 at that point (see the function `url-hexify-string'). If the string contains
1548 the specifier \"%(my-function)\", then the custom function `my-function' will
1549 be invoked: this function takes the tag as its only argument and must return
1550 a string.
1551
1552 REPLACE may also be a function that will be called with the tag as the
1553 only argument to create the link, which should be returned as a string.
1554
1555 See the manual for examples."
1556 :group 'org-link
1557 :type '(repeat
1558 (cons
1559 (string :tag "Protocol")
1560 (choice
1561 (string :tag "Format")
1562 (function)))))
1563
1564 (defcustom org-descriptive-links t
1565 "Non-nil means Org will display descriptive links.
1566 E.g. [[http://orgmode.org][Org website]] will be displayed as
1567 \"Org Website\", hiding the link itself and just displaying its
1568 description. When set to `nil', Org will display the full links
1569 literally.
1570
1571 You can interactively set the value of this variable by calling
1572 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1573 :group 'org-link
1574 :type 'boolean)
1575
1576 (defcustom org-link-file-path-type 'adaptive
1577 "How the path name in file links should be stored.
1578 Valid values are:
1579
1580 relative Relative to the current directory, i.e. the directory of the file
1581 into which the link is being inserted.
1582 absolute Absolute path, if possible with ~ for home directory.
1583 noabbrev Absolute path, no abbreviation of home directory.
1584 adaptive Use relative path for files in the current directory and sub-
1585 directories of it. For other files, use an absolute path."
1586 :group 'org-link
1587 :type '(choice
1588 (const relative)
1589 (const absolute)
1590 (const noabbrev)
1591 (const adaptive)))
1592
1593 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1594 "Types of links that should be activated in Org-mode files.
1595 This is a list of symbols, each leading to the activation of a certain link
1596 type. In principle, it does not hurt to turn on most link types - there may
1597 be a small gain when turning off unused link types. The types are:
1598
1599 bracket The recommended [[link][description]] or [[link]] links with hiding.
1600 angle Links in angular brackets that may contain whitespace like
1601 <bbdb:Carsten Dominik>.
1602 plain Plain links in normal text, no whitespace, like http://google.com.
1603 radio Text that is matched by a radio target, see manual for details.
1604 tag Tag settings in a headline (link to tag search).
1605 date Time stamps (link to calendar).
1606 footnote Footnote labels.
1607
1608 Changing this variable requires a restart of Emacs to become effective."
1609 :group 'org-link
1610 :type '(set :greedy t
1611 (const :tag "Double bracket links" bracket)
1612 (const :tag "Angular bracket links" angle)
1613 (const :tag "Plain text links" plain)
1614 (const :tag "Radio target matches" radio)
1615 (const :tag "Tags" tag)
1616 (const :tag "Timestamps" date)
1617 (const :tag "Footnotes" footnote)))
1618
1619 (defcustom org-make-link-description-function nil
1620 "Function to use for generating link descriptions from links.
1621 When nil, the link location will be used. This function must take
1622 two parameters: the first one is the link, the second one is the
1623 description generated by `org-insert-link'. The function should
1624 return the description to use."
1625 :group 'org-link
1626 :type '(choice (const nil) (function)))
1627
1628 (defgroup org-link-store nil
1629 "Options concerning storing links in Org-mode."
1630 :tag "Org Store Link"
1631 :group 'org-link)
1632
1633 (defcustom org-url-hexify-p t
1634 "When non-nil, hexify URL when creating a link."
1635 :type 'boolean
1636 :version "24.3"
1637 :group 'org-link-store)
1638
1639 (defcustom org-email-link-description-format "Email %c: %.30s"
1640 "Format of the description part of a link to an email or usenet message.
1641 The following %-escapes will be replaced by corresponding information:
1642
1643 %F full \"From\" field
1644 %f name, taken from \"From\" field, address if no name
1645 %T full \"To\" field
1646 %t first name in \"To\" field, address if no name
1647 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1648 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1649 %s subject
1650 %d date
1651 %m message-id.
1652
1653 You may use normal field width specification between the % and the letter.
1654 This is for example useful to limit the length of the subject.
1655
1656 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1657 :group 'org-link-store
1658 :type 'string)
1659
1660 (defcustom org-from-is-user-regexp
1661 (let (r1 r2)
1662 (when (and user-mail-address (not (string= user-mail-address "")))
1663 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1664 (when (and user-full-name (not (string= user-full-name "")))
1665 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1666 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1667 "Regexp matched against the \"From:\" header of an email or usenet message.
1668 It should match if the message is from the user him/herself."
1669 :group 'org-link-store
1670 :type 'regexp)
1671
1672 (defcustom org-context-in-file-links t
1673 "Non-nil means file links from `org-store-link' contain context.
1674 A search string will be added to the file name with :: as separator and
1675 used to find the context when the link is activated by the command
1676 `org-open-at-point'. When this option is t, the entire active region
1677 will be placed in the search string of the file link. If set to a
1678 positive integer, only the first n lines of context will be stored.
1679
1680 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1681 negates this setting for the duration of the command."
1682 :group 'org-link-store
1683 :type '(choice boolean integer))
1684
1685 (defcustom org-keep-stored-link-after-insertion nil
1686 "Non-nil means keep link in list for entire session.
1687
1688 The command `org-store-link' adds a link pointing to the current
1689 location to an internal list. These links accumulate during a session.
1690 The command `org-insert-link' can be used to insert links into any
1691 Org-mode file (offering completion for all stored links). When this
1692 option is nil, every link which has been inserted once using \\[org-insert-link]
1693 will be removed from the list, to make completing the unused links
1694 more efficient."
1695 :group 'org-link-store
1696 :type 'boolean)
1697
1698 (defgroup org-link-follow nil
1699 "Options concerning following links in Org-mode."
1700 :tag "Org Follow Link"
1701 :group 'org-link)
1702
1703 (defcustom org-link-translation-function nil
1704 "Function to translate links with different syntax to Org syntax.
1705 This can be used to translate links created for example by the Planner
1706 or emacs-wiki packages to Org syntax.
1707 The function must accept two parameters, a TYPE containing the link
1708 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1709 which is everything after the link protocol. It should return a cons
1710 with possibly modified values of type and path.
1711 Org contains a function for this, so if you set this variable to
1712 `org-translate-link-from-planner', you should be able follow many
1713 links created by planner."
1714 :group 'org-link-follow
1715 :type '(choice (const nil) (function)))
1716
1717 (defcustom org-follow-link-hook nil
1718 "Hook that is run after a link has been followed."
1719 :group 'org-link-follow
1720 :type 'hook)
1721
1722 (defcustom org-tab-follows-link nil
1723 "Non-nil means on links TAB will follow the link.
1724 Needs to be set before org.el is loaded.
1725 This really should not be used, it does not make sense, and the
1726 implementation is bad."
1727 :group 'org-link-follow
1728 :type 'boolean)
1729
1730 (defcustom org-return-follows-link nil
1731 "Non-nil means on links RET will follow the link.
1732 In tables, the special behavior of RET has precedence."
1733 :group 'org-link-follow
1734 :type 'boolean)
1735
1736 (defcustom org-mouse-1-follows-link
1737 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1738 "Non-nil means mouse-1 on a link will follow the link.
1739 A longer mouse click will still set point. Does not work on XEmacs.
1740 Needs to be set before org.el is loaded."
1741 :group 'org-link-follow
1742 :version "24.4"
1743 :package-version '(Org . "8.3")
1744 :type '(choice
1745 (const :tag "A double click follows the link" double)
1746 (const :tag "Unconditionally follow the link with mouse-1" t)
1747 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1748
1749 (defcustom org-mark-ring-length 4
1750 "Number of different positions to be recorded in the ring.
1751 Changing this requires a restart of Emacs to work correctly."
1752 :group 'org-link-follow
1753 :type 'integer)
1754
1755 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1756 "Non-nil means internal links in Org files must exactly match a headline.
1757 When nil, the link search tries to match a phrase with all words
1758 in the search text."
1759 :group 'org-link-follow
1760 :version "24.1"
1761 :type '(choice
1762 (const :tag "Use fuzzy text search" nil)
1763 (const :tag "Match only exact headline" t)
1764 (const :tag "Match exact headline or query to create it"
1765 query-to-create)))
1766
1767 (defcustom org-link-frame-setup
1768 '((vm . vm-visit-folder-other-frame)
1769 (vm-imap . vm-visit-imap-folder-other-frame)
1770 (gnus . org-gnus-no-new-news)
1771 (file . find-file-other-window)
1772 (wl . wl-other-frame))
1773 "Setup the frame configuration for following links.
1774 When following a link with Emacs, it may often be useful to display
1775 this link in another window or frame. This variable can be used to
1776 set this up for the different types of links.
1777 For VM, use any of
1778 `vm-visit-folder'
1779 `vm-visit-folder-other-window'
1780 `vm-visit-folder-other-frame'
1781 For Gnus, use any of
1782 `gnus'
1783 `gnus-other-frame'
1784 `org-gnus-no-new-news'
1785 For FILE, use any of
1786 `find-file'
1787 `find-file-other-window'
1788 `find-file-other-frame'
1789 For Wanderlust use any of
1790 `wl'
1791 `wl-other-frame'
1792 For the calendar, use the variable `calendar-setup'.
1793 For BBDB, it is currently only possible to display the matches in
1794 another window."
1795 :group 'org-link-follow
1796 :type '(list
1797 (cons (const vm)
1798 (choice
1799 (const vm-visit-folder)
1800 (const vm-visit-folder-other-window)
1801 (const vm-visit-folder-other-frame)))
1802 (cons (const vm-imap)
1803 (choice
1804 (const vm-visit-imap-folder)
1805 (const vm-visit-imap-folder-other-window)
1806 (const vm-visit-imap-folder-other-frame)))
1807 (cons (const gnus)
1808 (choice
1809 (const gnus)
1810 (const gnus-other-frame)
1811 (const org-gnus-no-new-news)))
1812 (cons (const file)
1813 (choice
1814 (const find-file)
1815 (const find-file-other-window)
1816 (const find-file-other-frame)))
1817 (cons (const wl)
1818 (choice
1819 (const wl)
1820 (const wl-other-frame)))))
1821
1822 (defcustom org-display-internal-link-with-indirect-buffer nil
1823 "Non-nil means use indirect buffer to display infile links.
1824 Activating internal links (from one location in a file to another location
1825 in the same file) normally just jumps to the location. When the link is
1826 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1827 is displayed in
1828 another window. When this option is set, the other window actually displays
1829 an indirect buffer clone of the current buffer, to avoid any visibility
1830 changes to the current buffer."
1831 :group 'org-link-follow
1832 :type 'boolean)
1833
1834 (defcustom org-open-non-existing-files nil
1835 "Non-nil means `org-open-file' will open non-existing files.
1836 When nil, an error will be generated.
1837 This variable applies only to external applications because they
1838 might choke on non-existing files. If the link is to a file that
1839 will be opened in Emacs, the variable is ignored."
1840 :group 'org-link-follow
1841 :type 'boolean)
1842
1843 (defcustom org-open-directory-means-index-dot-org nil
1844 "Non-nil means a link to a directory really means to index.org.
1845 When nil, following a directory link will run dired or open a finder/explorer
1846 window on that directory."
1847 :group 'org-link-follow
1848 :type 'boolean)
1849
1850 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1851 "Function and arguments to call for following mailto links.
1852 This is a list with the first element being a Lisp function, and the
1853 remaining elements being arguments to the function. In string arguments,
1854 %a will be replaced by the address, and %s will be replaced by the subject
1855 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1856 :group 'org-link-follow
1857 :type '(choice
1858 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1859 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1860 (const :tag "message-mail" (message-mail "%a" "%s"))
1861 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1862
1863 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1864 "Non-nil means ask for confirmation before executing shell links.
1865 Shell links can be dangerous: just think about a link
1866
1867 [[shell:rm -rf ~/*][Google Search]]
1868
1869 This link would show up in your Org-mode document as \"Google Search\",
1870 but really it would remove your entire home directory.
1871 Therefore we advise against setting this variable to nil.
1872 Just change it to `y-or-n-p' if you want to confirm with a
1873 single keystroke rather than having to type \"yes\"."
1874 :group 'org-link-follow
1875 :type '(choice
1876 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1877 (const :tag "with y-or-n (faster)" y-or-n-p)
1878 (const :tag "no confirmation (dangerous)" nil)))
1879 (put 'org-confirm-shell-link-function
1880 'safe-local-variable
1881 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1882
1883 (defcustom org-confirm-shell-link-not-regexp ""
1884 "A regexp to skip confirmation for shell links."
1885 :group 'org-link-follow
1886 :version "24.1"
1887 :type 'regexp)
1888
1889 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1890 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1891 Elisp links can be dangerous: just think about a link
1892
1893 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1894
1895 This link would show up in your Org-mode document as \"Google Search\",
1896 but really it would remove your entire home directory.
1897 Therefore we advise against setting this variable to nil.
1898 Just change it to `y-or-n-p' if you want to confirm with a
1899 single keystroke rather than having to type \"yes\"."
1900 :group 'org-link-follow
1901 :type '(choice
1902 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1903 (const :tag "with y-or-n (faster)" y-or-n-p)
1904 (const :tag "no confirmation (dangerous)" nil)))
1905 (put 'org-confirm-shell-link-function
1906 'safe-local-variable
1907 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1908
1909 (defcustom org-confirm-elisp-link-not-regexp ""
1910 "A regexp to skip confirmation for Elisp links."
1911 :group 'org-link-follow
1912 :version "24.1"
1913 :type 'regexp)
1914
1915 (defconst org-file-apps-defaults-gnu
1916 '((remote . emacs)
1917 (system . mailcap)
1918 (t . mailcap))
1919 "Default file applications on a UNIX or GNU/Linux system.
1920 See `org-file-apps'.")
1921
1922 (defconst org-file-apps-defaults-macosx
1923 '((remote . emacs)
1924 (t . "open %s")
1925 (system . "open %s")
1926 ("ps.gz" . "gv %s")
1927 ("eps.gz" . "gv %s")
1928 ("dvi" . "xdvi %s")
1929 ("fig" . "xfig %s"))
1930 "Default file applications on a MacOS X system.
1931 The system \"open\" is known as a default, but we use X11 applications
1932 for some files for which the OS does not have a good default.
1933 See `org-file-apps'.")
1934
1935 (defconst org-file-apps-defaults-windowsnt
1936 (list
1937 '(remote . emacs)
1938 (cons t
1939 (list (if (featurep 'xemacs)
1940 'mswindows-shell-execute
1941 'w32-shell-execute)
1942 "open" 'file))
1943 (cons 'system
1944 (list (if (featurep 'xemacs)
1945 'mswindows-shell-execute
1946 'w32-shell-execute)
1947 "open" 'file)))
1948 "Default file applications on a Windows NT system.
1949 The system \"open\" is used for most files.
1950 See `org-file-apps'.")
1951
1952 (defcustom org-file-apps
1953 '((auto-mode . emacs)
1954 ("\\.mm\\'" . default)
1955 ("\\.x?html?\\'" . default)
1956 ("\\.pdf\\'" . default))
1957 "External applications for opening `file:path' items in a document.
1958 Org-mode uses system defaults for different file types, but
1959 you can use this variable to set the application for a given file
1960 extension. The entries in this list are cons cells where the car identifies
1961 files and the cdr the corresponding command. Possible values for the
1962 file identifier are
1963 \"string\" A string as a file identifier can be interpreted in different
1964 ways, depending on its contents:
1965
1966 - Alphanumeric characters only:
1967 Match links with this file extension.
1968 Example: (\"pdf\" . \"evince %s\")
1969 to open PDFs with evince.
1970
1971 - Regular expression: Match links where the
1972 filename matches the regexp. If you want to
1973 use groups here, use shy groups.
1974
1975 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1976 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1977 to open *.html and *.xhtml with firefox.
1978
1979 - Regular expression which contains (non-shy) groups:
1980 Match links where the whole link, including \"::\", and
1981 anything after that, matches the regexp.
1982 In a custom command string, %1, %2, etc. are replaced with
1983 the parts of the link that were matched by the groups.
1984 For backwards compatibility, if a command string is given
1985 that does not use any of the group matches, this case is
1986 handled identically to the second one (i.e. match against
1987 file name only).
1988 In a custom lisp form, you can access the group matches with
1989 (match-string n link).
1990
1991 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1992 to open [[file:document.pdf::5]] with evince at page 5.
1993
1994 `directory' Matches a directory
1995 `remote' Matches a remote file, accessible through tramp or efs.
1996 Remote files most likely should be visited through Emacs
1997 because external applications cannot handle such paths.
1998 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1999 so all files Emacs knows how to handle. Using this with
2000 command `emacs' will open most files in Emacs. Beware that this
2001 will also open html files inside Emacs, unless you add
2002 (\"html\" . default) to the list as well.
2003 t Default for files not matched by any of the other options.
2004 `system' The system command to open files, like `open' on Windows
2005 and Mac OS X, and mailcap under GNU/Linux. This is the command
2006 that will be selected if you call `C-c C-o' with a double
2007 \\[universal-argument] \\[universal-argument] prefix.
2008
2009 Possible values for the command are:
2010 `emacs' The file will be visited by the current Emacs process.
2011 `default' Use the default application for this file type, which is the
2012 association for t in the list, most likely in the system-specific
2013 part.
2014 This can be used to overrule an unwanted setting in the
2015 system-specific variable.
2016 `system' Use the system command for opening files, like \"open\".
2017 This command is specified by the entry whose car is `system'.
2018 Most likely, the system-specific version of this variable
2019 does define this command, but you can overrule/replace it
2020 here.
2021 string A command to be executed by a shell; %s will be replaced
2022 by the path to the file.
2023 sexp A Lisp form which will be evaluated. The file path will
2024 be available in the Lisp variable `file'.
2025 For more examples, see the system specific constants
2026 `org-file-apps-defaults-macosx'
2027 `org-file-apps-defaults-windowsnt'
2028 `org-file-apps-defaults-gnu'."
2029 :group 'org-link-follow
2030 :type '(repeat
2031 (cons (choice :value ""
2032 (string :tag "Extension")
2033 (const :tag "System command to open files" system)
2034 (const :tag "Default for unrecognized files" t)
2035 (const :tag "Remote file" remote)
2036 (const :tag "Links to a directory" directory)
2037 (const :tag "Any files that have Emacs modes"
2038 auto-mode))
2039 (choice :value ""
2040 (const :tag "Visit with Emacs" emacs)
2041 (const :tag "Use default" default)
2042 (const :tag "Use the system command" system)
2043 (string :tag "Command")
2044 (sexp :tag "Lisp form")))))
2045
2046 (defcustom org-doi-server-url "http://dx.doi.org/"
2047 "The URL of the DOI server."
2048 :type 'string
2049 :version "24.3"
2050 :group 'org-link-follow)
2051
2052 (defgroup org-refile nil
2053 "Options concerning refiling entries in Org-mode."
2054 :tag "Org Refile"
2055 :group 'org)
2056
2057 (defcustom org-directory "~/org"
2058 "Directory with org files.
2059 This is just a default location to look for Org files. There is no need
2060 at all to put your files into this directory. It is only used in the
2061 following situations:
2062
2063 1. When a capture template specifies a target file that is not an
2064 absolute path. The path will then be interpreted relative to
2065 `org-directory'
2066 2. When a capture note is filed away in an interactive way (when exiting the
2067 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2068 with `org-directory' as the default path."
2069 :group 'org-refile
2070 :group 'org-capture
2071 :type 'directory)
2072
2073 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2074 "Default target for storing notes.
2075 Used as a fall back file for org-capture.el, for templates that
2076 do not specify a target file."
2077 :group 'org-refile
2078 :group 'org-capture
2079 :type '(choice
2080 (const :tag "Default from remember-data-file" nil)
2081 file))
2082
2083 (defcustom org-goto-interface 'outline
2084 "The default interface to be used for `org-goto'.
2085 Allowed values are:
2086 outline The interface shows an outline of the relevant file
2087 and the correct heading is found by moving through
2088 the outline or by searching with incremental search.
2089 outline-path-completion Headlines in the current buffer are offered via
2090 completion. This is the interface also used by
2091 the refile command."
2092 :group 'org-refile
2093 :type '(choice
2094 (const :tag "Outline" outline)
2095 (const :tag "Outline-path-completion" outline-path-completion)))
2096
2097 (defcustom org-goto-max-level 5
2098 "Maximum target level when running `org-goto' with refile interface."
2099 :group 'org-refile
2100 :type 'integer)
2101
2102 (defcustom org-reverse-note-order nil
2103 "Non-nil means store new notes at the beginning of a file or entry.
2104 When nil, new notes will be filed to the end of a file or entry.
2105 This can also be a list with cons cells of regular expressions that
2106 are matched against file names, and values."
2107 :group 'org-capture
2108 :group 'org-refile
2109 :type '(choice
2110 (const :tag "Reverse always" t)
2111 (const :tag "Reverse never" nil)
2112 (repeat :tag "By file name regexp"
2113 (cons regexp boolean))))
2114
2115 (defcustom org-log-refile nil
2116 "Information to record when a task is refiled.
2117
2118 Possible values are:
2119
2120 nil Don't add anything
2121 time Add a time stamp to the task
2122 note Prompt for a note and add it with template `org-log-note-headings'
2123
2124 This option can also be set with on a per-file-basis with
2125
2126 #+STARTUP: nologrefile
2127 #+STARTUP: logrefile
2128 #+STARTUP: lognoterefile
2129
2130 You can have local logging settings for a subtree by setting the LOGGING
2131 property to one or more of these keywords.
2132
2133 When bulk-refiling from the agenda, the value `note' is forbidden and
2134 will temporarily be changed to `time'."
2135 :group 'org-refile
2136 :group 'org-progress
2137 :version "24.1"
2138 :type '(choice
2139 (const :tag "No logging" nil)
2140 (const :tag "Record timestamp" time)
2141 (const :tag "Record timestamp with note." note)))
2142
2143 (defcustom org-refile-targets nil
2144 "Targets for refiling entries with \\[org-refile].
2145 This is a list of cons cells. Each cell contains:
2146 - a specification of the files to be considered, either a list of files,
2147 or a symbol whose function or variable value will be used to retrieve
2148 a file name or a list of file names. If you use `org-agenda-files' for
2149 that, all agenda files will be scanned for targets. Nil means consider
2150 headings in the current buffer.
2151 - A specification of how to find candidate refile targets. This may be
2152 any of:
2153 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2154 This tag has to be present in all target headlines, inheritance will
2155 not be considered.
2156 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2157 todo keyword.
2158 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2159 headlines that are refiling targets.
2160 - a cons cell (:level . N). Any headline of level N is considered a target.
2161 Note that, when `org-odd-levels-only' is set, level corresponds to
2162 order in hierarchy, not to the number of stars.
2163 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2164 Note that, when `org-odd-levels-only' is set, level corresponds to
2165 order in hierarchy, not to the number of stars.
2166
2167 Each element of this list generates a set of possible targets.
2168 The union of these sets is presented (with completion) to
2169 the user by `org-refile'.
2170
2171 You can set the variable `org-refile-target-verify-function' to a function
2172 to verify each headline found by the simple criteria above.
2173
2174 When this variable is nil, all top-level headlines in the current buffer
2175 are used, equivalent to the value `((nil . (:level . 1))'."
2176 :group 'org-refile
2177 :type '(repeat
2178 (cons
2179 (choice :value org-agenda-files
2180 (const :tag "All agenda files" org-agenda-files)
2181 (const :tag "Current buffer" nil)
2182 (function) (variable) (file))
2183 (choice :tag "Identify target headline by"
2184 (cons :tag "Specific tag" (const :value :tag) (string))
2185 (cons :tag "TODO keyword" (const :value :todo) (string))
2186 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2187 (cons :tag "Level number" (const :value :level) (integer))
2188 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2189
2190 (defcustom org-refile-target-verify-function nil
2191 "Function to verify if the headline at point should be a refile target.
2192 The function will be called without arguments, with point at the
2193 beginning of the headline. It should return t and leave point
2194 where it is if the headline is a valid target for refiling.
2195
2196 If the target should not be selected, the function must return nil.
2197 In addition to this, it may move point to a place from where the search
2198 should be continued. For example, the function may decide that the entire
2199 subtree of the current entry should be excluded and move point to the end
2200 of the subtree."
2201 :group 'org-refile
2202 :type '(choice
2203 (const nil)
2204 (function)))
2205
2206 (defcustom org-refile-use-cache nil
2207 "Non-nil means cache refile targets to speed up the process.
2208 The cache for a particular file will be updated automatically when
2209 the buffer has been killed, or when any of the marker used for flagging
2210 refile targets no longer points at a live buffer.
2211 If you have added new entries to a buffer that might themselves be targets,
2212 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2213 find that easier, `C-u C-u C-u C-c C-w'."
2214 :group 'org-refile
2215 :version "24.1"
2216 :type 'boolean)
2217
2218 (defcustom org-refile-use-outline-path nil
2219 "Non-nil means provide refile targets as paths.
2220 So a level 3 headline will be available as level1/level2/level3.
2221
2222 When the value is `file', also include the file name (without directory)
2223 into the path. In this case, you can also stop the completion after
2224 the file name, to get entries inserted as top level in the file.
2225
2226 When `full-file-path', include the full file path."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Not" nil)
2230 (const :tag "Yes" t)
2231 (const :tag "Start with file name" file)
2232 (const :tag "Start with full file path" full-file-path)))
2233
2234 (defcustom org-outline-path-complete-in-steps t
2235 "Non-nil means complete the outline path in hierarchical steps.
2236 When Org-mode uses the refile interface to select an outline path
2237 \(see variable `org-refile-use-outline-path'), the completion of
2238 the path can be done is a single go, or if can be done in steps down
2239 the headline hierarchy. Going in steps is probably the best if you
2240 do not use a special completion package like `ido' or `icicles'.
2241 However, when using these packages, going in one step can be very
2242 fast, while still showing the whole path to the entry."
2243 :group 'org-refile
2244 :type 'boolean)
2245
2246 (defcustom org-refile-allow-creating-parent-nodes nil
2247 "Non-nil means allow to create new nodes as refile targets.
2248 New nodes are then created by adding \"/new node name\" to the completion
2249 of an existing node. When the value of this variable is `confirm',
2250 new node creation must be confirmed by the user (recommended).
2251 When nil, the completion must match an existing entry.
2252
2253 Note that, if the new heading is not seen by the criteria
2254 listed in `org-refile-targets', multiple instances of the same
2255 heading would be created by trying again to file under the new
2256 heading."
2257 :group 'org-refile
2258 :type '(choice
2259 (const :tag "Never" nil)
2260 (const :tag "Always" t)
2261 (const :tag "Prompt for confirmation" confirm)))
2262
2263 (defcustom org-refile-active-region-within-subtree nil
2264 "Non-nil means also refile active region within a subtree.
2265
2266 By default `org-refile' doesn't allow refiling regions if they
2267 don't contain a set of subtrees, but it might be convenient to
2268 do so sometimes: in that case, the first line of the region is
2269 converted to a headline before refiling."
2270 :group 'org-refile
2271 :version "24.1"
2272 :type 'boolean)
2273
2274 (defgroup org-todo nil
2275 "Options concerning TODO items in Org-mode."
2276 :tag "Org TODO"
2277 :group 'org)
2278
2279 (defgroup org-progress nil
2280 "Options concerning Progress logging in Org-mode."
2281 :tag "Org Progress"
2282 :group 'org-time)
2283
2284 (defvar org-todo-interpretation-widgets
2285 '((:tag "Sequence (cycling hits every state)" sequence)
2286 (:tag "Type (cycling directly to DONE)" type))
2287 "The available interpretation symbols for customizing `org-todo-keywords'.
2288 Interested libraries should add to this list.")
2289
2290 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2291 "List of TODO entry keyword sequences and their interpretation.
2292 \\<org-mode-map>This is a list of sequences.
2293
2294 Each sequence starts with a symbol, either `sequence' or `type',
2295 indicating if the keywords should be interpreted as a sequence of
2296 action steps, or as different types of TODO items. The first
2297 keywords are states requiring action - these states will select a headline
2298 for inclusion into the global TODO list Org-mode produces. If one of
2299 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2300 signify that no further action is necessary. If \"|\" is not found,
2301 the last keyword is treated as the only DONE state of the sequence.
2302
2303 The command \\[org-todo] cycles an entry through these states, and one
2304 additional state where no keyword is present. For details about this
2305 cycling, see the manual.
2306
2307 TODO keywords and interpretation can also be set on a per-file basis with
2308 the special #+SEQ_TODO and #+TYP_TODO lines.
2309
2310 Each keyword can optionally specify a character for fast state selection
2311 \(in combination with the variable `org-use-fast-todo-selection')
2312 and specifiers for state change logging, using the same syntax that
2313 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2314 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2315 indicates to record a time stamp each time this state is selected.
2316
2317 Each keyword may also specify if a timestamp or a note should be
2318 recorded when entering or leaving the state, by adding additional
2319 characters in the parenthesis after the keyword. This looks like this:
2320 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2321 record only the time of the state change. With X and Y being either
2322 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2323 Y when leaving the state if and only if the *target* state does not
2324 define X. You may omit any of the fast-selection key or X or /Y,
2325 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2326
2327 For backward compatibility, this variable may also be just a list
2328 of keywords. In this case the interpretation (sequence or type) will be
2329 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2330 :group 'org-todo
2331 :group 'org-keywords
2332 :type '(choice
2333 (repeat :tag "Old syntax, just keywords"
2334 (string :tag "Keyword"))
2335 (repeat :tag "New syntax"
2336 (cons
2337 (choice
2338 :tag "Interpretation"
2339 ;;Quick and dirty way to see
2340 ;;`org-todo-interpretations'. This takes the
2341 ;;place of item arguments
2342 :convert-widget
2343 (lambda (widget)
2344 (widget-put widget
2345 :args (mapcar
2346 #'(lambda (x)
2347 (widget-convert
2348 (cons 'const x)))
2349 org-todo-interpretation-widgets))
2350 widget))
2351 (repeat
2352 (string :tag "Keyword"))))))
2353
2354 (defvar org-todo-keywords-1 nil
2355 "All TODO and DONE keywords active in a buffer.")
2356 (make-variable-buffer-local 'org-todo-keywords-1)
2357 (defvar org-todo-keywords-for-agenda nil)
2358 (defvar org-done-keywords-for-agenda nil)
2359 (defvar org-drawers-for-agenda nil)
2360 (defvar org-todo-keyword-alist-for-agenda nil)
2361 (defvar org-tag-alist-for-agenda nil
2362 "Alist of all tags from all agenda files.")
2363 (defvar org-tag-groups-alist-for-agenda nil
2364 "Alist of all groups tags from all current agenda files.")
2365 (defvar org-tag-groups-alist nil)
2366 (make-variable-buffer-local 'org-tag-groups-alist)
2367 (defvar org-agenda-contributing-files nil)
2368 (defvar org-not-done-keywords nil)
2369 (make-variable-buffer-local 'org-not-done-keywords)
2370 (defvar org-done-keywords nil)
2371 (make-variable-buffer-local 'org-done-keywords)
2372 (defvar org-todo-heads nil)
2373 (make-variable-buffer-local 'org-todo-heads)
2374 (defvar org-todo-sets nil)
2375 (make-variable-buffer-local 'org-todo-sets)
2376 (defvar org-todo-log-states nil)
2377 (make-variable-buffer-local 'org-todo-log-states)
2378 (defvar org-todo-kwd-alist nil)
2379 (make-variable-buffer-local 'org-todo-kwd-alist)
2380 (defvar org-todo-key-alist nil)
2381 (make-variable-buffer-local 'org-todo-key-alist)
2382 (defvar org-todo-key-trigger nil)
2383 (make-variable-buffer-local 'org-todo-key-trigger)
2384
2385 (defcustom org-todo-interpretation 'sequence
2386 "Controls how TODO keywords are interpreted.
2387 This variable is in principle obsolete and is only used for
2388 backward compatibility, if the interpretation of todo keywords is
2389 not given already in `org-todo-keywords'. See that variable for
2390 more information."
2391 :group 'org-todo
2392 :group 'org-keywords
2393 :type '(choice (const sequence)
2394 (const type)))
2395
2396 (defcustom org-use-fast-todo-selection t
2397 "Non-nil means use the fast todo selection scheme with C-c C-t.
2398 This variable describes if and under what circumstances the cycling
2399 mechanism for TODO keywords will be replaced by a single-key, direct
2400 selection scheme.
2401
2402 When nil, fast selection is never used.
2403
2404 When the symbol `prefix', it will be used when `org-todo' is called
2405 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2406 `C-u t' in an agenda buffer.
2407
2408 When t, fast selection is used by default. In this case, the prefix
2409 argument forces cycling instead.
2410
2411 In all cases, the special interface is only used if access keys have
2412 actually been assigned by the user, i.e. if keywords in the configuration
2413 are followed by a letter in parenthesis, like TODO(t)."
2414 :group 'org-todo
2415 :type '(choice
2416 (const :tag "Never" nil)
2417 (const :tag "By default" t)
2418 (const :tag "Only with C-u C-c C-t" prefix)))
2419
2420 (defcustom org-provide-todo-statistics t
2421 "Non-nil means update todo statistics after insert and toggle.
2422 ALL-HEADLINES means update todo statistics by including headlines
2423 with no TODO keyword as well, counting them as not done.
2424 A list of TODO keywords means the same, but skip keywords that are
2425 not in this list.
2426
2427 When this is set, todo statistics is updated in the parent of the
2428 current entry each time a todo state is changed."
2429 :group 'org-todo
2430 :type '(choice
2431 (const :tag "Yes, only for TODO entries" t)
2432 (const :tag "Yes, including all entries" all-headlines)
2433 (repeat :tag "Yes, for TODOs in this list"
2434 (string :tag "TODO keyword"))
2435 (other :tag "No TODO statistics" nil)))
2436
2437 (defcustom org-hierarchical-todo-statistics t
2438 "Non-nil means TODO statistics covers just direct children.
2439 When nil, all entries in the subtree are considered.
2440 This has only an effect if `org-provide-todo-statistics' is set.
2441 To set this to nil for only a single subtree, use a COOKIE_DATA
2442 property and include the word \"recursive\" into the value."
2443 :group 'org-todo
2444 :type 'boolean)
2445
2446 (defcustom org-after-todo-state-change-hook nil
2447 "Hook which is run after the state of a TODO item was changed.
2448 The new state (a string with a TODO keyword, or nil) is available in the
2449 Lisp variable `org-state'."
2450 :group 'org-todo
2451 :type 'hook)
2452
2453 (defvar org-blocker-hook nil
2454 "Hook for functions that are allowed to block a state change.
2455
2456 Functions in this hook should not modify the buffer.
2457 Each function gets as its single argument a property list,
2458 see `org-trigger-hook' for more information about this list.
2459
2460 If any of the functions in this hook returns nil, the state change
2461 is blocked.")
2462
2463 (defvar org-trigger-hook nil
2464 "Hook for functions that are triggered by a state change.
2465
2466 Each function gets as its single argument a property list with at
2467 least the following elements:
2468
2469 (:type type-of-change :position pos-at-entry-start
2470 :from old-state :to new-state)
2471
2472 Depending on the type, more properties may be present.
2473
2474 This mechanism is currently implemented for:
2475
2476 TODO state changes
2477 ------------------
2478 :type todo-state-change
2479 :from previous state (keyword as a string), or nil, or a symbol
2480 'todo' or 'done', to indicate the general type of state.
2481 :to new state, like in :from")
2482
2483 (defcustom org-enforce-todo-dependencies nil
2484 "Non-nil means undone TODO entries will block switching the parent to DONE.
2485 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2486 be blocked if any prior sibling is not yet done.
2487 Finally, if the parent is blocked because of ordered siblings of its own,
2488 the child will also be blocked."
2489 :set (lambda (var val)
2490 (set var val)
2491 (if val
2492 (add-hook 'org-blocker-hook
2493 'org-block-todo-from-children-or-siblings-or-parent)
2494 (remove-hook 'org-blocker-hook
2495 'org-block-todo-from-children-or-siblings-or-parent)))
2496 :group 'org-todo
2497 :type 'boolean)
2498
2499 (defcustom org-enforce-todo-checkbox-dependencies nil
2500 "Non-nil means unchecked boxes will block switching the parent to DONE.
2501 When this is nil, checkboxes have no influence on switching TODO states.
2502 When non-nil, you first need to check off all check boxes before the TODO
2503 entry can be switched to DONE.
2504 This variable needs to be set before org.el is loaded, and you need to
2505 restart Emacs after a change to make the change effective. The only way
2506 to change is while Emacs is running is through the customize interface."
2507 :set (lambda (var val)
2508 (set var val)
2509 (if val
2510 (add-hook 'org-blocker-hook
2511 'org-block-todo-from-checkboxes)
2512 (remove-hook 'org-blocker-hook
2513 'org-block-todo-from-checkboxes)))
2514 :group 'org-todo
2515 :type 'boolean)
2516
2517 (defcustom org-treat-insert-todo-heading-as-state-change nil
2518 "Non-nil means inserting a TODO heading is treated as state change.
2519 So when the command \\[org-insert-todo-heading] is used, state change
2520 logging will apply if appropriate. When nil, the new TODO item will
2521 be inserted directly, and no logging will take place."
2522 :group 'org-todo
2523 :type 'boolean)
2524
2525 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2526 "Non-nil means switching TODO states with S-cursor counts as state change.
2527 This is the default behavior. However, setting this to nil allows a
2528 convenient way to select a TODO state and bypass any logging associated
2529 with that."
2530 :group 'org-todo
2531 :type 'boolean)
2532
2533 (defcustom org-todo-state-tags-triggers nil
2534 "Tag changes that should be triggered by TODO state changes.
2535 This is a list. Each entry is
2536
2537 (state-change (tag . flag) .......)
2538
2539 State-change can be a string with a state, and empty string to indicate the
2540 state that has no TODO keyword, or it can be one of the symbols `todo'
2541 or `done', meaning any not-done or done state, respectively."
2542 :group 'org-todo
2543 :group 'org-tags
2544 :type '(repeat
2545 (cons (choice :tag "When changing to"
2546 (const :tag "Not-done state" todo)
2547 (const :tag "Done state" done)
2548 (string :tag "State"))
2549 (repeat
2550 (cons :tag "Tag action"
2551 (string :tag "Tag")
2552 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2553
2554 (defcustom org-log-done nil
2555 "Information to record when a task moves to the DONE state.
2556
2557 Possible values are:
2558
2559 nil Don't add anything, just change the keyword
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2562
2563 This option can also be set with on a per-file-basis with
2564
2565 #+STARTUP: nologdone
2566 #+STARTUP: logdone
2567 #+STARTUP: lognotedone
2568
2569 You can have local logging settings for a subtree by setting the LOGGING
2570 property to one or more of these keywords."
2571 :group 'org-todo
2572 :group 'org-progress
2573 :type '(choice
2574 (const :tag "No logging" nil)
2575 (const :tag "Record CLOSED timestamp" time)
2576 (const :tag "Record CLOSED timestamp with note." note)))
2577
2578 ;; Normalize old uses of org-log-done.
2579 (cond
2580 ((eq org-log-done t) (setq org-log-done 'time))
2581 ((and (listp org-log-done) (memq 'done org-log-done))
2582 (setq org-log-done 'note)))
2583
2584 (defcustom org-log-reschedule nil
2585 "Information to record when the scheduling date of a tasks is modified.
2586
2587 Possible values are:
2588
2589 nil Don't add anything, just change the date
2590 time Add a time stamp to the task
2591 note Prompt for a note and add it with template `org-log-note-headings'
2592
2593 This option can also be set with on a per-file-basis with
2594
2595 #+STARTUP: nologreschedule
2596 #+STARTUP: logreschedule
2597 #+STARTUP: lognotereschedule"
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "No logging" nil)
2602 (const :tag "Record timestamp" time)
2603 (const :tag "Record timestamp with note." note)))
2604
2605 (defcustom org-log-redeadline nil
2606 "Information to record when the deadline date of a tasks is modified.
2607
2608 Possible values are:
2609
2610 nil Don't add anything, just change the date
2611 time Add a time stamp to the task
2612 note Prompt for a note and add it with template `org-log-note-headings'
2613
2614 This option can also be set with on a per-file-basis with
2615
2616 #+STARTUP: nologredeadline
2617 #+STARTUP: logredeadline
2618 #+STARTUP: lognoteredeadline
2619
2620 You can have local logging settings for a subtree by setting the LOGGING
2621 property to one or more of these keywords."
2622 :group 'org-todo
2623 :group 'org-progress
2624 :type '(choice
2625 (const :tag "No logging" nil)
2626 (const :tag "Record timestamp" time)
2627 (const :tag "Record timestamp with note." note)))
2628
2629 (defcustom org-log-note-clock-out nil
2630 "Non-nil means record a note when clocking out of an item.
2631 This can also be configured on a per-file basis by adding one of
2632 the following lines anywhere in the buffer:
2633
2634 #+STARTUP: lognoteclock-out
2635 #+STARTUP: nolognoteclock-out"
2636 :group 'org-todo
2637 :group 'org-progress
2638 :type 'boolean)
2639
2640 (defcustom org-log-done-with-time t
2641 "Non-nil means the CLOSED time stamp will contain date and time.
2642 When nil, only the date will be recorded."
2643 :group 'org-progress
2644 :type 'boolean)
2645
2646 (defcustom org-log-note-headings
2647 '((done . "CLOSING NOTE %t")
2648 (state . "State %-12s from %-12S %t")
2649 (note . "Note taken on %t")
2650 (reschedule . "Rescheduled from %S on %t")
2651 (delschedule . "Not scheduled, was %S on %t")
2652 (redeadline . "New deadline from %S on %t")
2653 (deldeadline . "Removed deadline, was %S on %t")
2654 (refile . "Refiled on %t")
2655 (clock-out . ""))
2656 "Headings for notes added to entries.
2657 The value is an alist, with the car being a symbol indicating the note
2658 context, and the cdr is the heading to be used. The heading may also be the
2659 empty string.
2660 %t in the heading will be replaced by a time stamp.
2661 %T will be an active time stamp instead the default inactive one
2662 %d will be replaced by a short-format time stamp.
2663 %D will be replaced by an active short-format time stamp.
2664 %s will be replaced by the new TODO state, in double quotes.
2665 %S will be replaced by the old TODO state, in double quotes.
2666 %u will be replaced by the user name.
2667 %U will be replaced by the full user name.
2668
2669 In fact, it is not a good idea to change the `state' entry, because
2670 agenda log mode depends on the format of these entries."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type '(list :greedy t
2674 (cons (const :tag "Heading when closing an item" done) string)
2675 (cons (const :tag
2676 "Heading when changing todo state (todo sequence only)"
2677 state) string)
2678 (cons (const :tag "Heading when just taking a note" note) string)
2679 (cons (const :tag "Heading when rescheduling" reschedule) string)
2680 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2681 (cons (const :tag "Heading when changing deadline" redeadline) string)
2682 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2683 (cons (const :tag "Heading when refiling" refile) string)
2684 (cons (const :tag "Heading when clocking out" clock-out) string)))
2685
2686 (unless (assq 'note org-log-note-headings)
2687 (push '(note . "%t") org-log-note-headings))
2688
2689 (defcustom org-log-into-drawer nil
2690 "Non-nil means insert state change notes and time stamps into a drawer.
2691 When nil, state changes notes will be inserted after the headline and
2692 any scheduling and clock lines, but not inside a drawer.
2693
2694 The value of this variable should be the name of the drawer to use.
2695 LOGBOOK is proposed as the default drawer for this purpose, you can
2696 also set this to a string to define the drawer of your choice.
2697
2698 A value of t is also allowed, representing \"LOGBOOK\".
2699
2700 A value of t or nil can also be set with on a per-file-basis with
2701
2702 #+STARTUP: logdrawer
2703 #+STARTUP: nologdrawer
2704
2705 If this variable is set, `org-log-state-notes-insert-after-drawers'
2706 will be ignored.
2707
2708 You can set the property LOG_INTO_DRAWER to overrule this setting for
2709 a subtree."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Not into a drawer" nil)
2714 (const :tag "LOGBOOK" t)
2715 (string :tag "Other")))
2716
2717 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2718
2719 (defun org-log-into-drawer ()
2720 "Return the value of `org-log-into-drawer', but let properties overrule.
2721 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2722 used instead of the default value."
2723 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2724 (cond
2725 ((not p) org-log-into-drawer)
2726 ((equal p "nil") nil)
2727 ((equal p "t") "LOGBOOK")
2728 (t p))))
2729
2730 (defcustom org-log-state-notes-insert-after-drawers nil
2731 "Non-nil means insert state change notes after any drawers in entry.
2732 Only the drawers that *immediately* follow the headline and the
2733 deadline/scheduled line are skipped.
2734 When nil, insert notes right after the heading and perhaps the line
2735 with deadline/scheduling if present.
2736
2737 This variable will have no effect if `org-log-into-drawer' is
2738 set."
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type 'boolean)
2742
2743 (defcustom org-log-states-order-reversed t
2744 "Non-nil means the latest state note will be directly after heading.
2745 When nil, the state change notes will be ordered according to time.
2746
2747 This option can also be set with on a per-file-basis with
2748
2749 #+STARTUP: logstatesreversed
2750 #+STARTUP: nologstatesreversed"
2751 :group 'org-todo
2752 :group 'org-progress
2753 :type 'boolean)
2754
2755 (defcustom org-todo-repeat-to-state nil
2756 "The TODO state to which a repeater should return the repeating task.
2757 By default this is the first task in a TODO sequence, or the previous state
2758 in a TODO_TYP set. But you can specify another task here.
2759 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2760 :group 'org-todo
2761 :version "24.1"
2762 :type '(choice (const :tag "Head of sequence" nil)
2763 (string :tag "Specific state")))
2764
2765 (defcustom org-log-repeat 'time
2766 "Non-nil means record moving through the DONE state when triggering repeat.
2767 An auto-repeating task is immediately switched back to TODO when
2768 marked DONE. If you are not logging state changes (by adding \"@\"
2769 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2770 record a closing note, there will be no record of the task moving
2771 through DONE. This variable forces taking a note anyway.
2772
2773 nil Don't force a record
2774 time Record a time stamp
2775 note Prompt for a note and add it with template `org-log-note-headings'
2776
2777 This option can also be set with on a per-file-basis with
2778
2779 #+STARTUP: nologrepeat
2780 #+STARTUP: logrepeat
2781 #+STARTUP: lognoterepeat
2782
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2785 :group 'org-todo
2786 :group 'org-progress
2787 :type '(choice
2788 (const :tag "Don't force a record" nil)
2789 (const :tag "Force recording the DONE state" time)
2790 (const :tag "Force recording a note with the DONE state" note)))
2791
2792
2793 (defgroup org-priorities nil
2794 "Priorities in Org-mode."
2795 :tag "Org Priorities"
2796 :group 'org-todo)
2797
2798 (defcustom org-enable-priority-commands t
2799 "Non-nil means priority commands are active.
2800 When nil, these commands will be disabled, so that you never accidentally
2801 set a priority."
2802 :group 'org-priorities
2803 :type 'boolean)
2804
2805 (defcustom org-highest-priority ?A
2806 "The highest priority of TODO items. A character like ?A, ?B etc.
2807 Must have a smaller ASCII number than `org-lowest-priority'."
2808 :group 'org-priorities
2809 :type 'character)
2810
2811 (defcustom org-lowest-priority ?C
2812 "The lowest priority of TODO items. A character like ?A, ?B etc.
2813 Must have a larger ASCII number than `org-highest-priority'."
2814 :group 'org-priorities
2815 :type 'character)
2816
2817 (defcustom org-default-priority ?B
2818 "The default priority of TODO items.
2819 This is the priority an item gets if no explicit priority is given.
2820 When starting to cycle on an empty priority the first step in the cycle
2821 depends on `org-priority-start-cycle-with-default'. The resulting first
2822 step priority must not exceed the range from `org-highest-priority' to
2823 `org-lowest-priority' which means that `org-default-priority' has to be
2824 in this range exclusive or inclusive the range boundaries. Else the
2825 first step refuses to set the default and the second will fall back
2826 to (depending on the command used) the highest or lowest priority."
2827 :group 'org-priorities
2828 :type 'character)
2829
2830 (defcustom org-priority-start-cycle-with-default t
2831 "Non-nil means start with default priority when starting to cycle.
2832 When this is nil, the first step in the cycle will be (depending on the
2833 command used) one higher or lower than the default priority.
2834 See also `org-default-priority'."
2835 :group 'org-priorities
2836 :type 'boolean)
2837
2838 (defcustom org-get-priority-function nil
2839 "Function to extract the priority from a string.
2840 The string is normally the headline. If this is nil Org computes the
2841 priority from the priority cookie like [#A] in the headline. It returns
2842 an integer, increasing by 1000 for each priority level.
2843 The user can set a different function here, which should take a string
2844 as an argument and return the numeric priority."
2845 :group 'org-priorities
2846 :version "24.1"
2847 :type '(choice
2848 (const nil)
2849 (function)))
2850
2851 (defgroup org-time nil
2852 "Options concerning time stamps and deadlines in Org-mode."
2853 :tag "Org Time"
2854 :group 'org)
2855
2856 (defcustom org-insert-labeled-timestamps-at-point nil
2857 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2858 When nil, these labeled time stamps are forces into the second line of an
2859 entry, just after the headline. When scheduling from the global TODO list,
2860 the time stamp will always be forced into the second line."
2861 :group 'org-time
2862 :type 'boolean)
2863
2864 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2865 "Formats for `format-time-string' which are used for time stamps.
2866 It is not recommended to change this constant.")
2867
2868 (defcustom org-time-stamp-rounding-minutes '(0 5)
2869 "Number of minutes to round time stamps to.
2870 These are two values, the first applies when first creating a time stamp.
2871 The second applies when changing it with the commands `S-up' and `S-down'.
2872 When changing the time stamp, this means that it will change in steps
2873 of N minutes, as given by the second value.
2874
2875 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2876 numbers should be factors of 60, so for example 5, 10, 15.
2877
2878 When this is larger than 1, you can still force an exact time stamp by using
2879 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2880 and by using a prefix arg to `S-up/down' to specify the exact number
2881 of minutes to shift."
2882 :group 'org-time
2883 :get #'(lambda (var) ; Make sure both elements are there
2884 (if (integerp (default-value var))
2885 (list (default-value var) 5)
2886 (default-value var)))
2887 :type '(list
2888 (integer :tag "when inserting times")
2889 (integer :tag "when modifying times")))
2890
2891 ;; Normalize old customizations of this variable.
2892 (when (integerp org-time-stamp-rounding-minutes)
2893 (setq org-time-stamp-rounding-minutes
2894 (list org-time-stamp-rounding-minutes
2895 org-time-stamp-rounding-minutes)))
2896
2897 (defcustom org-display-custom-times nil
2898 "Non-nil means overlay custom formats over all time stamps.
2899 The formats are defined through the variable `org-time-stamp-custom-formats'.
2900 To turn this on on a per-file basis, insert anywhere in the file:
2901 #+STARTUP: customtime"
2902 :group 'org-time
2903 :set 'set-default
2904 :type 'sexp)
2905 (make-variable-buffer-local 'org-display-custom-times)
2906
2907 (defcustom org-time-stamp-custom-formats
2908 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2909 "Custom formats for time stamps. See `format-time-string' for the syntax.
2910 These are overlaid over the default ISO format if the variable
2911 `org-display-custom-times' is set. Time like %H:%M should be at the
2912 end of the second format. The custom formats are also honored by export
2913 commands, if custom time display is turned on at the time of export."
2914 :group 'org-time
2915 :type 'sexp)
2916
2917 (defun org-time-stamp-format (&optional long inactive)
2918 "Get the right format for a time string."
2919 (let ((f (if long (cdr org-time-stamp-formats)
2920 (car org-time-stamp-formats))))
2921 (if inactive
2922 (concat "[" (substring f 1 -1) "]")
2923 f)))
2924
2925 (defcustom org-time-clocksum-format
2926 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2927 "The format string used when creating CLOCKSUM lines.
2928 This is also used when Org mode generates a time duration.
2929
2930 The value can be a single format string containing two
2931 %-sequences, which will be filled with the number of hours and
2932 minutes in that order.
2933
2934 Alternatively, the value can be a plist associating any of the
2935 keys :years, :months, :weeks, :days, :hours or :minutes with
2936 format strings. The time duration is formatted using only the
2937 time components that are needed and concatenating the results.
2938 If a time unit in absent, it falls back to the next smallest
2939 unit.
2940
2941 The keys :require-years, :require-months, :require-days,
2942 :require-weeks, :require-hours, :require-minutes are also
2943 meaningful. A non-nil value for these keys indicates that the
2944 corresponding time component should always be included, even if
2945 its value is 0.
2946
2947
2948 For example,
2949
2950 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2951 :require-minutes t)
2952
2953 means durations longer than a day will be expressed in days,
2954 hours and minutes, and durations less than a day will always be
2955 expressed in hours and minutes (even for durations less than an
2956 hour).
2957
2958 The value
2959
2960 \(:days \"%dd\" :minutes \"%dm\")
2961
2962 means durations longer than a day will be expressed in days and
2963 minutes, and durations less than a day will be expressed entirely
2964 in minutes (even for durations longer than an hour)."
2965 :group 'org-time
2966 :group 'org-clock
2967 :version "24.4"
2968 :package-version '(Org . "8.0")
2969 :type '(choice (string :tag "Format string")
2970 (set :tag "Plist"
2971 (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show years" :require-years)
2975 (const t))
2976 (group :inline t (const :tag "Months" :months)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show months" :require-months)
2980 (const t))
2981 (group :inline t (const :tag "Weeks" :weeks)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show weeks" :require-weeks)
2985 (const t))
2986 (group :inline t (const :tag "Days" :days)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show days" :require-days)
2990 (const t))
2991 (group :inline t (const :tag "Hours" :hours)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show hours" :require-hours)
2995 (const t))
2996 (group :inline t (const :tag "Minutes" :minutes)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show minutes" :require-minutes)
3000 (const t)))))
3001
3002 (defcustom org-time-clocksum-use-fractional nil
3003 "When non-nil, \\[org-clock-display] uses fractional times.
3004 See `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.3"
3008 :type 'boolean)
3009
3010 (defcustom org-time-clocksum-use-effort-durations nil
3011 "When non-nil, \\[org-clock-display] uses effort durations.
3012 E.g. by default, one day is considered to be a 8 hours effort,
3013 so a task that has been clocked for 16 hours will be displayed
3014 as during 2 days in the clock display or in the clocktable.
3015
3016 See `org-effort-durations' on how to set effort durations
3017 and `org-time-clocksum-format' for more on time clock formats."
3018 :group 'org-time
3019 :group 'org-clock
3020 :version "24.4"
3021 :package-version '(Org . "8.0")
3022 :type 'boolean)
3023
3024 (defcustom org-time-clocksum-fractional-format "%.2f"
3025 "The format string used when creating CLOCKSUM lines,
3026 or when Org mode generates a time duration, if
3027 `org-time-clocksum-use-fractional' is enabled.
3028
3029 The value can be a single format string containing one
3030 %-sequence, which will be filled with the number of hours as
3031 a float.
3032
3033 Alternatively, the value can be a plist associating any of the
3034 keys :years, :months, :weeks, :days, :hours or :minutes with
3035 a format string. The time duration is formatted using the
3036 largest time unit which gives a non-zero integer part. If all
3037 specified formats have zero integer part, the smallest time unit
3038 is used."
3039 :group 'org-time
3040 :type '(choice (string :tag "Format string")
3041 (set (group :inline t (const :tag "Years" :years)
3042 (string :tag "Format string"))
3043 (group :inline t (const :tag "Months" :months)
3044 (string :tag "Format string"))
3045 (group :inline t (const :tag "Weeks" :weeks)
3046 (string :tag "Format string"))
3047 (group :inline t (const :tag "Days" :days)
3048 (string :tag "Format string"))
3049 (group :inline t (const :tag "Hours" :hours)
3050 (string :tag "Format string"))
3051 (group :inline t (const :tag "Minutes" :minutes)
3052 (string :tag "Format string")))))
3053
3054 (defcustom org-deadline-warning-days 14
3055 "Number of days before expiration during which a deadline becomes active.
3056 This variable governs the display in sparse trees and in the agenda.
3057 When 0 or negative, it means use this number (the absolute value of it)
3058 even if a deadline has a different individual lead time specified.
3059
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :type 'integer)
3064
3065 (defcustom org-scheduled-delay-days 0
3066 "Number of days before a scheduled item becomes active.
3067 This variable governs the display in sparse trees and in the agenda.
3068 The default value (i.e. 0) means: don't delay scheduled item.
3069 When negative, it means use this number (the absolute value of it)
3070 even if a scheduled item has a different individual delay time
3071 specified.
3072
3073 Custom commands can set this variable in the options section."
3074 :group 'org-time
3075 :group 'org-agenda-daily/weekly
3076 :version "24.4"
3077 :package-version '(Org . "8.0")
3078 :type 'integer)
3079
3080 (defcustom org-read-date-prefer-future t
3081 "Non-nil means assume future for incomplete date input from user.
3082 This affects the following situations:
3083 1. The user gives a month but not a year.
3084 For example, if it is April and you enter \"feb 2\", this will be read
3085 as Feb 2, *next* year. \"May 5\", however, will be this year.
3086 2. The user gives a day, but no month.
3087 For example, if today is the 15th, and you enter \"3\", Org-mode will
3088 read this as the third of *next* month. However, if you enter \"17\",
3089 it will be considered as *this* month.
3090
3091 If you set this variable to the symbol `time', then also the following
3092 will work:
3093
3094 3. If the user gives a time.
3095 If the time is before now, it will be interpreted as tomorrow.
3096
3097 Currently none of this works for ISO week specifications.
3098
3099 When this option is nil, the current day, month and year will always be
3100 used as defaults.
3101
3102 See also `org-agenda-jump-prefer-future'."
3103 :group 'org-time
3104 :type '(choice
3105 (const :tag "Never" nil)
3106 (const :tag "Check month and day" t)
3107 (const :tag "Check month, day, and time" time)))
3108
3109 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3110 "Should the agenda jump command prefer the future for incomplete dates?
3111 The default is to do the same as configured in `org-read-date-prefer-future'.
3112 But you can also set a deviating value here.
3113 This may t or nil, or the symbol `org-read-date-prefer-future'."
3114 :group 'org-agenda
3115 :group 'org-time
3116 :version "24.1"
3117 :type '(choice
3118 (const :tag "Use org-read-date-prefer-future"
3119 org-read-date-prefer-future)
3120 (const :tag "Never" nil)
3121 (const :tag "Always" t)))
3122
3123 (defcustom org-read-date-force-compatible-dates t
3124 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3125
3126 Depending on the system Emacs is running on, certain dates cannot
3127 be represented with the type used internally to represent time.
3128 Dates between 1970-1-1 and 2038-1-1 can always be represented
3129 correctly. Some systems allow for earlier dates, some for later,
3130 some for both. One way to find out it to insert any date into an
3131 Org buffer, putting the cursor on the year and hitting S-up and
3132 S-down to test the range.
3133
3134 When this variable is set to t, the date/time prompt will not let
3135 you specify dates outside the 1970-2037 range, so it is certain that
3136 these dates will work in whatever version of Emacs you are
3137 running, and also that you can move a file from one Emacs implementation
3138 to another. WHenever Org is forcing the year for you, it will display
3139 a message and beep.
3140
3141 When this variable is nil, Org will check if the date is
3142 representable in the specific Emacs implementation you are using.
3143 If not, it will force a year, usually the current year, and beep
3144 to remind you. Currently this setting is not recommended because
3145 the likelihood that you will open your Org files in an Emacs that
3146 has limited date range is not negligible.
3147
3148 A workaround for this problem is to use diary sexp dates for time
3149 stamps outside of this range."
3150 :group 'org-time
3151 :version "24.1"
3152 :type 'boolean)
3153
3154 (defcustom org-read-date-display-live t
3155 "Non-nil means display current interpretation of date prompt live.
3156 This display will be in an overlay, in the minibuffer."
3157 :group 'org-time
3158 :type 'boolean)
3159
3160 (defcustom org-read-date-popup-calendar t
3161 "Non-nil means pop up a calendar when prompting for a date.
3162 In the calendar, the date can be selected with mouse-1. However, the
3163 minibuffer will also be active, and you can simply enter the date as well.
3164 When nil, only the minibuffer will be available."
3165 :group 'org-time
3166 :type 'boolean)
3167 (org-defvaralias 'org-popup-calendar-for-date-prompt
3168 'org-read-date-popup-calendar)
3169
3170 (make-obsolete-variable
3171 'org-read-date-minibuffer-setup-hook
3172 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3173 (defcustom org-read-date-minibuffer-setup-hook nil
3174 "Hook to be used to set up keys for the date/time interface.
3175 Add key definitions to `minibuffer-local-map', which will be a
3176 temporary copy.
3177
3178 WARNING: This option is obsolete, you should use
3179 `org-read-date-minibuffer-local-map' to set up keys."
3180 :group 'org-time
3181 :type 'hook)
3182
3183 (defcustom org-extend-today-until 0
3184 "The hour when your day really ends. Must be an integer.
3185 This has influence for the following applications:
3186 - When switching the agenda to \"today\". It it is still earlier than
3187 the time given here, the day recognized as TODAY is actually yesterday.
3188 - When a date is read from the user and it is still before the time given
3189 here, the current date and time will be assumed to be yesterday, 23:59.
3190 Also, timestamps inserted in capture templates follow this rule.
3191
3192 IMPORTANT: This is a feature whose implementation is and likely will
3193 remain incomplete. Really, it is only here because past midnight seems to
3194 be the favorite working time of John Wiegley :-)"
3195 :group 'org-time
3196 :type 'integer)
3197
3198 (defcustom org-use-effective-time nil
3199 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3200 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3201 \"effective time\" of any timestamps between midnight and 8am will be
3202 23:59 of the previous day."
3203 :group 'org-time
3204 :version "24.1"
3205 :type 'boolean)
3206
3207 (defcustom org-use-last-clock-out-time-as-effective-time nil
3208 "When non-nil, use the last clock out time for `org-todo'.
3209 Note that this option has precedence over the combined use of
3210 `org-use-effective-time' and `org-extend-today-until'."
3211 :group 'org-time
3212 :version "24.4"
3213 :package-version '(Org . "8.0")
3214 :type 'boolean)
3215
3216 (defcustom org-edit-timestamp-down-means-later nil
3217 "Non-nil means S-down will increase the time in a time stamp.
3218 When nil, S-up will increase."
3219 :group 'org-time
3220 :type 'boolean)
3221
3222 (defcustom org-calendar-follow-timestamp-change t
3223 "Non-nil means make the calendar window follow timestamp changes.
3224 When a timestamp is modified and the calendar window is visible, it will be
3225 moved to the new date."
3226 :group 'org-time
3227 :type 'boolean)
3228
3229 (defgroup org-tags nil
3230 "Options concerning tags in Org-mode."
3231 :tag "Org Tags"
3232 :group 'org)
3233
3234 (defcustom org-tag-alist nil
3235 "List of tags allowed in Org-mode files.
3236 When this list is nil, Org-mode will base TAG input on what is already in the
3237 buffer.
3238 The value of this variable is an alist, the car of each entry must be a
3239 keyword as a string, the cdr may be a character that is used to select
3240 that tag through the fast-tag-selection interface.
3241 See the manual for details."
3242 :group 'org-tags
3243 :type '(repeat
3244 (choice
3245 (cons (string :tag "Tag name")
3246 (character :tag "Access char"))
3247 (list :tag "Start radio group"
3248 (const :startgroup)
3249 (option (string :tag "Group description")))
3250 (list :tag "Group tags delimiter"
3251 (const :grouptags))
3252 (list :tag "End radio group"
3253 (const :endgroup)
3254 (option (string :tag "Group description")))
3255 (const :tag "New line" (:newline)))))
3256
3257 (defcustom org-tag-persistent-alist nil
3258 "List of tags that will always appear in all Org-mode files.
3259 This is in addition to any in buffer settings or customizations
3260 of `org-tag-alist'.
3261 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3262 The value of this variable is an alist, the car of each entry must be a
3263 keyword as a string, the cdr may be a character that is used to select
3264 that tag through the fast-tag-selection interface.
3265 See the manual for details.
3266 To disable these tags on a per-file basis, insert anywhere in the file:
3267 #+STARTUP: noptag"
3268 :group 'org-tags
3269 :type '(repeat
3270 (choice
3271 (cons (string :tag "Tag name")
3272 (character :tag "Access char"))
3273 (const :tag "Start radio group" (:startgroup))
3274 (const :tag "Group tags delimiter" (:grouptags))
3275 (const :tag "End radio group" (:endgroup))
3276 (const :tag "New line" (:newline)))))
3277
3278 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3279 "If non-nil, always offer completion for all tags of all agenda files.
3280 Instead of customizing this variable directly, you might want to
3281 set it locally for capture buffers, because there no list of
3282 tags in that file can be created dynamically (there are none).
3283
3284 (add-hook 'org-capture-mode-hook
3285 (lambda ()
3286 (set (make-local-variable
3287 'org-complete-tags-always-offer-all-agenda-tags)
3288 t)))"
3289 :group 'org-tags
3290 :version "24.1"
3291 :type 'boolean)
3292
3293 (defvar org-file-tags nil
3294 "List of tags that can be inherited by all entries in the file.
3295 The tags will be inherited if the variable `org-use-tag-inheritance'
3296 says they should be.
3297 This variable is populated from #+FILETAGS lines.")
3298
3299 (defcustom org-use-fast-tag-selection 'auto
3300 "Non-nil means use fast tag selection scheme.
3301 This is a special interface to select and deselect tags with single keys.
3302 When nil, fast selection is never used.
3303 When the symbol `auto', fast selection is used if and only if selection
3304 characters for tags have been configured, either through the variable
3305 `org-tag-alist' or through a #+TAGS line in the buffer.
3306 When t, fast selection is always used and selection keys are assigned
3307 automatically if necessary."
3308 :group 'org-tags
3309 :type '(choice
3310 (const :tag "Always" t)
3311 (const :tag "Never" nil)
3312 (const :tag "When selection characters are configured" auto)))
3313
3314 (defcustom org-fast-tag-selection-single-key nil
3315 "Non-nil means fast tag selection exits after first change.
3316 When nil, you have to press RET to exit it.
3317 During fast tag selection, you can toggle this flag with `C-c'.
3318 This variable can also have the value `expert'. In this case, the window
3319 displaying the tags menu is not even shown, until you press C-c again."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No" nil)
3323 (const :tag "Yes" t)
3324 (const :tag "Expert" expert)))
3325
3326 (defvar org-fast-tag-selection-include-todo nil
3327 "Non-nil means fast tags selection interface will also offer TODO states.
3328 This is an undocumented feature, you should not rely on it.")
3329
3330 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3331 "The column to which tags should be indented in a headline.
3332 If this number is positive, it specifies the column. If it is negative,
3333 it means that the tags should be flushright to that column. For example,
3334 -80 works well for a normal 80 character screen.
3335 When 0, place tags directly after headline text, with only one space in
3336 between."
3337 :group 'org-tags
3338 :type 'integer)
3339
3340 (defcustom org-auto-align-tags t
3341 "Non-nil keeps tags aligned when modifying headlines.
3342 Some operations (i.e. demoting) change the length of a headline and
3343 therefore shift the tags around. With this option turned on, after
3344 each such operation the tags are again aligned to `org-tags-column'."
3345 :group 'org-tags
3346 :type 'boolean)
3347
3348 (defcustom org-use-tag-inheritance t
3349 "Non-nil means tags in levels apply also for sublevels.
3350 When nil, only the tags directly given in a specific line apply there.
3351 This may also be a list of tags that should be inherited, or a regexp that
3352 matches tags that should be inherited. Additional control is possible
3353 with the variable `org-tags-exclude-from-inheritance' which gives an
3354 explicit list of tags to be excluded from inheritance, even if the value of
3355 `org-use-tag-inheritance' would select it for inheritance.
3356
3357 If this option is t, a match early-on in a tree can lead to a large
3358 number of matches in the subtree when constructing the agenda or creating
3359 a sparse tree. If you only want to see the first match in a tree during
3360 a search, check out the variable `org-tags-match-list-sublevels'."
3361 :group 'org-tags
3362 :type '(choice
3363 (const :tag "Not" nil)
3364 (const :tag "Always" t)
3365 (repeat :tag "Specific tags" (string :tag "Tag"))
3366 (regexp :tag "Tags matched by regexp")))
3367
3368 (defcustom org-tags-exclude-from-inheritance nil
3369 "List of tags that should never be inherited.
3370 This is a way to exclude a few tags from inheritance. For way to do
3371 the opposite, to actively allow inheritance for selected tags,
3372 see the variable `org-use-tag-inheritance'."
3373 :group 'org-tags
3374 :type '(repeat (string :tag "Tag")))
3375
3376 (defun org-tag-inherit-p (tag)
3377 "Check if TAG is one that should be inherited."
3378 (cond
3379 ((member tag org-tags-exclude-from-inheritance) nil)
3380 ((eq org-use-tag-inheritance t) t)
3381 ((not org-use-tag-inheritance) nil)
3382 ((stringp org-use-tag-inheritance)
3383 (string-match org-use-tag-inheritance tag))
3384 ((listp org-use-tag-inheritance)
3385 (member tag org-use-tag-inheritance))
3386 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3387
3388 (defcustom org-tags-match-list-sublevels t
3389 "Non-nil means list also sublevels of headlines matching a search.
3390 This variable applies to tags/property searches, and also to stuck
3391 projects because this search is based on a tags match as well.
3392
3393 When set to the symbol `indented', sublevels are indented with
3394 leading dots.
3395
3396 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3397 the sublevels of a headline matching a tag search often also match
3398 the same search. Listing all of them can create very long lists.
3399 Setting this variable to nil causes subtrees of a match to be skipped.
3400
3401 This variable is semi-obsolete and probably should always be true. It
3402 is better to limit inheritance to certain tags using the variables
3403 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3404 :group 'org-tags
3405 :type '(choice
3406 (const :tag "No, don't list them" nil)
3407 (const :tag "Yes, do list them" t)
3408 (const :tag "List them, indented with leading dots" indented)))
3409
3410 (defcustom org-tags-sort-function nil
3411 "When set, tags are sorted using this function as a comparator."
3412 :group 'org-tags
3413 :type '(choice
3414 (const :tag "No sorting" nil)
3415 (const :tag "Alphabetical" string<)
3416 (const :tag "Reverse alphabetical" string>)
3417 (function :tag "Custom function" nil)))
3418
3419 (defvar org-tags-history nil
3420 "History of minibuffer reads for tags.")
3421 (defvar org-last-tags-completion-table nil
3422 "The last used completion table for tags.")
3423 (defvar org-after-tags-change-hook nil
3424 "Hook that is run after the tags in a line have changed.")
3425
3426 (defgroup org-properties nil
3427 "Options concerning properties in Org-mode."
3428 :tag "Org Properties"
3429 :group 'org)
3430
3431 (defcustom org-property-format "%-10s %s"
3432 "How property key/value pairs should be formatted by `indent-line'.
3433 When `indent-line' hits a property definition, it will format the line
3434 according to this format, mainly to make sure that the values are
3435 lined-up with respect to each other."
3436 :group 'org-properties
3437 :type 'string)
3438
3439 (defcustom org-properties-postprocess-alist nil
3440 "Alist of properties and functions to adjust inserted values.
3441 Elements of this alist must be of the form
3442
3443 ([string] [function])
3444
3445 where [string] must be a property name and [function] must be a
3446 lambda expression: this lambda expression must take one argument,
3447 the value to adjust, and return the new value as a string.
3448
3449 For example, this element will allow the property \"Remaining\"
3450 to be updated wrt the relation between the \"Effort\" property
3451 and the clock summary:
3452
3453 ((\"Remaining\" (lambda(value)
3454 (let ((clocksum (org-clock-sum-current-item))
3455 (effort (org-duration-string-to-minutes
3456 (org-entry-get (point) \"Effort\"))))
3457 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3458 :group 'org-properties
3459 :version "24.1"
3460 :type '(alist :key-type (string :tag "Property")
3461 :value-type (function :tag "Function")))
3462
3463 (defcustom org-use-property-inheritance nil
3464 "Non-nil means properties apply also for sublevels.
3465
3466 This setting is chiefly used during property searches. Turning it on can
3467 cause significant overhead when doing a search, which is why it is not
3468 on by default.
3469
3470 When nil, only the properties directly given in the current entry count.
3471 When t, every property is inherited. The value may also be a list of
3472 properties that should have inheritance, or a regular expression matching
3473 properties that should be inherited.
3474
3475 However, note that some special properties use inheritance under special
3476 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3477 and the properties ending in \"_ALL\" when they are used as descriptor
3478 for valid values of a property.
3479
3480 Note for programmers:
3481 When querying an entry with `org-entry-get', you can control if inheritance
3482 should be used. By default, `org-entry-get' looks only at the local
3483 properties. You can request inheritance by setting the inherit argument
3484 to t (to force inheritance) or to `selective' (to respect the setting
3485 in this variable)."
3486 :group 'org-properties
3487 :type '(choice
3488 (const :tag "Not" nil)
3489 (const :tag "Always" t)
3490 (repeat :tag "Specific properties" (string :tag "Property"))
3491 (regexp :tag "Properties matched by regexp")))
3492
3493 (defun org-property-inherit-p (property)
3494 "Check if PROPERTY is one that should be inherited."
3495 (cond
3496 ((eq org-use-property-inheritance t) t)
3497 ((not org-use-property-inheritance) nil)
3498 ((stringp org-use-property-inheritance)
3499 (string-match org-use-property-inheritance property))
3500 ((listp org-use-property-inheritance)
3501 (member property org-use-property-inheritance))
3502 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3503
3504 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3505 "The default column format, if no other format has been defined.
3506 This variable can be set on the per-file basis by inserting a line
3507
3508 #+COLUMNS: %25ITEM ....."
3509 :group 'org-properties
3510 :type 'string)
3511
3512 (defcustom org-columns-ellipses ".."
3513 "The ellipses to be used when a field in column view is truncated.
3514 When this is the empty string, as many characters as possible are shown,
3515 but then there will be no visual indication that the field has been truncated.
3516 When this is a string of length N, the last N characters of a truncated
3517 field are replaced by this string. If the column is narrower than the
3518 ellipses string, only part of the ellipses string will be shown."
3519 :group 'org-properties
3520 :type 'string)
3521
3522 (defcustom org-columns-modify-value-for-display-function nil
3523 "Function that modifies values for display in column view.
3524 For example, it can be used to cut out a certain part from a time stamp.
3525 The function must take 2 arguments:
3526
3527 column-title The title of the column (*not* the property name)
3528 value The value that should be modified.
3529
3530 The function should return the value that should be displayed,
3531 or nil if the normal value should be used."
3532 :group 'org-properties
3533 :type '(choice (const nil) (function)))
3534
3535 (defcustom org-effort-property "Effort"
3536 "The property that is being used to keep track of effort estimates.
3537 Effort estimates given in this property need to have the format H:MM."
3538 :group 'org-properties
3539 :group 'org-progress
3540 :type '(string :tag "Property"))
3541
3542 (defconst org-global-properties-fixed
3543 '(("VISIBILITY_ALL" . "folded children content all")
3544 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3545 "List of property/value pairs that can be inherited by any entry.
3546
3547 These are fixed values, for the preset properties. The user variable
3548 that can be used to add to this list is `org-global-properties'.
3549
3550 The entries in this list are cons cells where the car is a property
3551 name and cdr is a string with the value. If the value represents
3552 multiple items like an \"_ALL\" property, separate the items by
3553 spaces.")
3554
3555 (defcustom org-global-properties nil
3556 "List of property/value pairs that can be inherited by any entry.
3557
3558 This list will be combined with the constant `org-global-properties-fixed'.
3559
3560 The entries in this list are cons cells where the car is a property
3561 name and cdr is a string with the value.
3562
3563 You can set buffer-local values for the same purpose in the variable
3564 `org-file-properties' this by adding lines like
3565
3566 #+PROPERTY: NAME VALUE"
3567 :group 'org-properties
3568 :type '(repeat
3569 (cons (string :tag "Property")
3570 (string :tag "Value"))))
3571
3572 (defvar org-file-properties nil
3573 "List of property/value pairs that can be inherited by any entry.
3574 Valid for the current buffer.
3575 This variable is populated from #+PROPERTY lines.")
3576 (make-variable-buffer-local 'org-file-properties)
3577
3578 (defgroup org-agenda nil
3579 "Options concerning agenda views in Org-mode."
3580 :tag "Org Agenda"
3581 :group 'org)
3582
3583 (defvar org-category nil
3584 "Variable used by org files to set a category for agenda display.
3585 Such files should use a file variable to set it, for example
3586
3587 # -*- mode: org; org-category: \"ELisp\"
3588
3589 or contain a special line
3590
3591 #+CATEGORY: ELisp
3592
3593 If the file does not specify a category, then file's base name
3594 is used instead.")
3595 (make-variable-buffer-local 'org-category)
3596 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3597
3598 (defcustom org-agenda-files nil
3599 "The files to be used for agenda display.
3600 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3601 \\[org-remove-file]. You can also use customize to edit the list.
3602
3603 If an entry is a directory, all files in that directory that are matched by
3604 `org-agenda-file-regexp' will be part of the file list.
3605
3606 If the value of the variable is not a list but a single file name, then
3607 the list of agenda files is actually stored and maintained in that file, one
3608 agenda file per line. In this file paths can be given relative to
3609 `org-directory'. Tilde expansion and environment variable substitution
3610 are also made."
3611 :group 'org-agenda
3612 :type '(choice
3613 (repeat :tag "List of files and directories" file)
3614 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3615
3616 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3617 "Regular expression to match files for `org-agenda-files'.
3618 If any element in the list in that variable contains a directory instead
3619 of a normal file, all files in that directory that are matched by this
3620 regular expression will be included."
3621 :group 'org-agenda
3622 :type 'regexp)
3623
3624 (defcustom org-agenda-text-search-extra-files nil
3625 "List of extra files to be searched by text search commands.
3626 These files will be searched in addition to the agenda files by the
3627 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3628 Note that these files will only be searched for text search commands,
3629 not for the other agenda views like todo lists, tag searches or the weekly
3630 agenda. This variable is intended to list notes and possibly archive files
3631 that should also be searched by these two commands.
3632 In fact, if the first element in the list is the symbol `agenda-archives',
3633 then all archive files of all agenda files will be added to the search
3634 scope."
3635 :group 'org-agenda
3636 :type '(set :greedy t
3637 (const :tag "Agenda Archives" agenda-archives)
3638 (repeat :inline t (file))))
3639
3640 (org-defvaralias 'org-agenda-multi-occur-extra-files
3641 'org-agenda-text-search-extra-files)
3642
3643 (defcustom org-agenda-skip-unavailable-files nil
3644 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3645 A nil value means to remove them, after a query, from the list."
3646 :group 'org-agenda
3647 :type 'boolean)
3648
3649 (defcustom org-calendar-to-agenda-key [?c]
3650 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3651 The command `org-calendar-goto-agenda' will be bound to this key. The
3652 default is the character `c' because then `c' can be used to switch back and
3653 forth between agenda and calendar."
3654 :group 'org-agenda
3655 :type 'sexp)
3656
3657 (defcustom org-calendar-insert-diary-entry-key [?i]
3658 "The key to be installed in `calendar-mode-map' for adding diary entries.
3659 This option is irrelevant until `org-agenda-diary-file' has been configured
3660 to point to an Org-mode file. When that is the case, the command
3661 `org-agenda-diary-entry' will be bound to the key given here, by default
3662 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3663 if you want to continue doing this, you need to change this to a different
3664 key."
3665 :group 'org-agenda
3666 :type 'sexp)
3667
3668 (defcustom org-agenda-diary-file 'diary-file
3669 "File to which to add new entries with the `i' key in agenda and calendar.
3670 When this is the symbol `diary-file', the functionality in the Emacs
3671 calendar will be used to add entries to the `diary-file'. But when this
3672 points to a file, `org-agenda-diary-entry' will be used instead."
3673 :group 'org-agenda
3674 :type '(choice
3675 (const :tag "The standard Emacs diary file" diary-file)
3676 (file :tag "Special Org file diary entries")))
3677
3678 (eval-after-load "calendar"
3679 '(progn
3680 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3681 'org-calendar-goto-agenda)
3682 (add-hook 'calendar-mode-hook
3683 (lambda ()
3684 (unless (eq org-agenda-diary-file 'diary-file)
3685 (define-key calendar-mode-map
3686 org-calendar-insert-diary-entry-key
3687 'org-agenda-diary-entry))))))
3688
3689 (defgroup org-latex nil
3690 "Options for embedding LaTeX code into Org-mode."
3691 :tag "Org LaTeX"
3692 :group 'org)
3693
3694 (defcustom org-format-latex-options
3695 '(:foreground default :background default :scale 1.0
3696 :html-foreground "Black" :html-background "Transparent"
3697 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3698 "Options for creating images from LaTeX fragments.
3699 This is a property list with the following properties:
3700 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3701 `default' means use the foreground of the default face.
3702 `auto' means use the foreground from the text face.
3703 :background the background color, or \"Transparent\".
3704 `default' means use the background of the default face.
3705 `auto' means use the background from the text face.
3706 :scale a scaling factor for the size of the images, to get more pixels
3707 :html-foreground, :html-background, :html-scale
3708 the same numbers for HTML export.
3709 :matchers a list indicating which matchers should be used to
3710 find LaTeX fragments. Valid members of this list are:
3711 \"begin\" find environments
3712 \"$1\" find single characters surrounded by $.$
3713 \"$\" find math expressions surrounded by $...$
3714 \"$$\" find math expressions surrounded by $$....$$
3715 \"\\(\" find math expressions surrounded by \\(...\\)
3716 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3717 :group 'org-latex
3718 :type 'plist)
3719
3720 (defcustom org-format-latex-signal-error t
3721 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3722 When nil, just push out a message."
3723 :group 'org-latex
3724 :version "24.1"
3725 :type 'boolean)
3726
3727 (defcustom org-latex-to-mathml-jar-file nil
3728 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3729 Use this to specify additional executable file say a jar file.
3730
3731 When using MathToWeb as the converter, specify the full-path to
3732 your mathtoweb.jar file."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type '(choice
3736 (const :tag "None" nil)
3737 (file :tag "JAR file" :must-match t)))
3738
3739 (defcustom org-latex-to-mathml-convert-command nil
3740 "Command to convert LaTeX fragments to MathML.
3741 Replace format-specifiers in the command as noted below and use
3742 `shell-command' to convert LaTeX to MathML.
3743 %j: Executable file in fully expanded form as specified by
3744 `org-latex-to-mathml-jar-file'.
3745 %I: Input LaTeX file in fully expanded form
3746 %o: Output MathML file
3747 This command is used by `org-create-math-formula'.
3748
3749 When using MathToWeb as the converter, set this to
3750 \"java -jar %j -unicode -force -df %o %I\"."
3751 :group 'org-latex
3752 :version "24.1"
3753 :type '(choice
3754 (const :tag "None" nil)
3755 (string :tag "\nShell command")))
3756
3757 (defcustom org-latex-create-formula-image-program 'dvipng
3758 "Program to convert LaTeX fragments with.
3759
3760 dvipng Process the LaTeX fragments to dvi file, then convert
3761 dvi files to png files using dvipng.
3762 This will also include processing of non-math environments.
3763 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3764 to convert pdf files to png files"
3765 :group 'org-latex
3766 :version "24.1"
3767 :type '(choice
3768 (const :tag "dvipng" dvipng)
3769 (const :tag "imagemagick" imagemagick)))
3770
3771 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3772 "Path to store latex preview images.
3773 A relative path here creates many directories relative to the
3774 processed org files paths. An absolute path puts all preview
3775 images at the same place."
3776 :group 'org-latex
3777 :version "24.3"
3778 :type 'string)
3779
3780 (defun org-format-latex-mathml-available-p ()
3781 "Return t if `org-latex-to-mathml-convert-command' is usable."
3782 (save-match-data
3783 (when (and (boundp 'org-latex-to-mathml-convert-command)
3784 org-latex-to-mathml-convert-command)
3785 (let ((executable (car (split-string
3786 org-latex-to-mathml-convert-command))))
3787 (when (executable-find executable)
3788 (if (string-match
3789 "%j" org-latex-to-mathml-convert-command)
3790 (file-readable-p org-latex-to-mathml-jar-file)
3791 t))))))
3792
3793 (defcustom org-format-latex-header "\\documentclass{article}
3794 \\usepackage[usenames]{color}
3795 \[PACKAGES]
3796 \[DEFAULT-PACKAGES]
3797 \\pagestyle{empty} % do not remove
3798 % The settings below are copied from fullpage.sty
3799 \\setlength{\\textwidth}{\\paperwidth}
3800 \\addtolength{\\textwidth}{-3cm}
3801 \\setlength{\\oddsidemargin}{1.5cm}
3802 \\addtolength{\\oddsidemargin}{-2.54cm}
3803 \\setlength{\\evensidemargin}{\\oddsidemargin}
3804 \\setlength{\\textheight}{\\paperheight}
3805 \\addtolength{\\textheight}{-\\headheight}
3806 \\addtolength{\\textheight}{-\\headsep}
3807 \\addtolength{\\textheight}{-\\footskip}
3808 \\addtolength{\\textheight}{-3cm}
3809 \\setlength{\\topmargin}{1.5cm}
3810 \\addtolength{\\topmargin}{-2.54cm}"
3811 "The document header used for processing LaTeX fragments.
3812 It is imperative that this header make sure that no page number
3813 appears on the page. The package defined in the variables
3814 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3815 will either replace the placeholder \"[PACKAGES]\" in this
3816 header, or they will be appended."
3817 :group 'org-latex
3818 :type 'string)
3819
3820 (defun org-set-packages-alist (var val)
3821 "Set the packages alist and make sure it has 3 elements per entry."
3822 (set var (mapcar (lambda (x)
3823 (if (and (consp x) (= (length x) 2))
3824 (list (car x) (nth 1 x) t)
3825 x))
3826 val)))
3827
3828 (defun org-get-packages-alist (var)
3829 "Get the packages alist and make sure it has 3 elements per entry."
3830 (mapcar (lambda (x)
3831 (if (and (consp x) (= (length x) 2))
3832 (list (car x) (nth 1 x) t)
3833 x))
3834 (default-value var)))
3835
3836 (defcustom org-latex-default-packages-alist
3837 '(("AUTO" "inputenc" t)
3838 ("T1" "fontenc" t)
3839 ("" "fixltx2e" nil)
3840 ("" "graphicx" t)
3841 ("" "longtable" nil)
3842 ("" "float" nil)
3843 ("" "wrapfig" nil)
3844 ("" "rotating" nil)
3845 ("normalem" "ulem" t)
3846 ("" "amsmath" t)
3847 ("" "textcomp" t)
3848 ("" "marvosym" t)
3849 ("" "wasysym" t)
3850 ("" "amssymb" t)
3851 ("" "hyperref" nil)
3852 "\\tolerance=1000")
3853 "Alist of default packages to be inserted in the header.
3854
3855 Change this only if one of the packages here causes an
3856 incompatibility with another package you are using.
3857
3858 The packages in this list are needed by one part or another of
3859 Org mode to function properly:
3860
3861 - inputenc, fontenc: for basic font and character selection
3862 - fixltx2e: Important patches of LaTeX itself
3863 - graphicx: for including images
3864 - longtable: For multipage tables
3865 - float, wrapfig: for figure placement
3866 - rotating: for sideways figures and tables
3867 - ulem: for underline and strike-through
3868 - amsmath: for subscript and superscript and math environments
3869 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3870 for interpreting the entities in `org-entities'. You can skip
3871 some of these packages if you don't use any of their symbols.
3872 - hyperref: for cross references
3873
3874 Therefore you should not modify this variable unless you know
3875 what you are doing. The one reason to change it anyway is that
3876 you might be loading some other package that conflicts with one
3877 of the default packages. Each element is either a cell or
3878 a string.
3879
3880 A cell is of the format:
3881
3882 \( \"options\" \"package\" SNIPPET-FLAG).
3883
3884 If SNIPPET-FLAG is non-nil, the package also needs to be included
3885 when compiling LaTeX snippets into images for inclusion into
3886 non-LaTeX output.
3887
3888 A string will be inserted as-is in the header of the document."
3889 :group 'org-latex
3890 :group 'org-export-latex
3891 :set 'org-set-packages-alist
3892 :get 'org-get-packages-alist
3893 :version "24.1"
3894 :type '(repeat
3895 (choice
3896 (list :tag "options/package pair"
3897 (string :tag "options")
3898 (string :tag "package")
3899 (boolean :tag "Snippet"))
3900 (string :tag "A line of LaTeX"))))
3901
3902 (defcustom org-latex-packages-alist nil
3903 "Alist of packages to be inserted in every LaTeX header.
3904
3905 These will be inserted after `org-latex-default-packages-alist'.
3906 Each element is either a cell or a string.
3907
3908 A cell is of the format:
3909
3910 \(\"options\" \"package\" SNIPPET-FLAG)
3911
3912 SNIPPET-FLAG, when non-nil, indicates that this package is also
3913 needed when turning LaTeX snippets into images for inclusion into
3914 non-LaTeX output.
3915
3916 A string will be inserted as-is in the header of the document.
3917
3918 Make sure that you only list packages here which:
3919
3920 - you want in every file;
3921 - do not conflict with the setup in `org-format-latex-header';
3922 - do not conflict with the default packages in
3923 `org-latex-default-packages-alist'."
3924 :group 'org-latex
3925 :group 'org-export-latex
3926 :set 'org-set-packages-alist
3927 :get 'org-get-packages-alist
3928 :type '(repeat
3929 (choice
3930 (list :tag "options/package pair"
3931 (string :tag "options")
3932 (string :tag "package")
3933 (boolean :tag "Snippet"))
3934 (string :tag "A line of LaTeX"))))
3935
3936 (defgroup org-appearance nil
3937 "Settings for Org-mode appearance."
3938 :tag "Org Appearance"
3939 :group 'org)
3940
3941 (defcustom org-level-color-stars-only nil
3942 "Non-nil means fontify only the stars in each headline.
3943 When nil, the entire headline is fontified.
3944 Changing it requires restart of `font-lock-mode' to become effective
3945 also in regions already fontified."
3946 :group 'org-appearance
3947 :type 'boolean)
3948
3949 (defcustom org-hide-leading-stars nil
3950 "Non-nil means hide the first N-1 stars in a headline.
3951 This works by using the face `org-hide' for these stars. This
3952 face is white for a light background, and black for a dark
3953 background. You may have to customize the face `org-hide' to
3954 make this work.
3955 Changing it requires restart of `font-lock-mode' to become effective
3956 also in regions already fontified.
3957 You may also set this on a per-file basis by adding one of the following
3958 lines to the buffer:
3959
3960 #+STARTUP: hidestars
3961 #+STARTUP: showstars"
3962 :group 'org-appearance
3963 :type 'boolean)
3964
3965 (defcustom org-hidden-keywords nil
3966 "List of symbols corresponding to keywords to be hidden the org buffer.
3967 For example, a value '(title) for this list will make the document's title
3968 appear in the buffer without the initial #+TITLE: keyword."
3969 :group 'org-appearance
3970 :version "24.1"
3971 :type '(set (const :tag "#+AUTHOR" author)
3972 (const :tag "#+DATE" date)
3973 (const :tag "#+EMAIL" email)
3974 (const :tag "#+TITLE" title)))
3975
3976 (defcustom org-custom-properties nil
3977 "List of properties (as strings) with a special meaning.
3978 The default use of these custom properties is to let the user
3979 hide them with `org-toggle-custom-properties-visibility'."
3980 :group 'org-properties
3981 :group 'org-appearance
3982 :version "24.3"
3983 :type '(repeat (string :tag "Property Name")))
3984
3985 (defcustom org-fontify-done-headline nil
3986 "Non-nil means change the face of a headline if it is marked DONE.
3987 Normally, only the TODO/DONE keyword indicates the state of a headline.
3988 When this is non-nil, the headline after the keyword is set to the
3989 `org-headline-done' as an additional indication."
3990 :group 'org-appearance
3991 :type 'boolean)
3992
3993 (defcustom org-fontify-emphasized-text t
3994 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3995 Changing this variable requires a restart of Emacs to take effect."
3996 :group 'org-appearance
3997 :type 'boolean)
3998
3999 (defcustom org-fontify-whole-heading-line nil
4000 "Non-nil means fontify the whole line for headings.
4001 This is useful when setting a background color for the
4002 org-level-* faces."
4003 :group 'org-appearance
4004 :type 'boolean)
4005
4006 (defcustom org-highlight-latex-and-related nil
4007 "Non-nil means highlight LaTeX related syntax in the buffer.
4008 When non nil, the value should be a list containing any of the
4009 following symbols:
4010 `latex' Highlight LaTeX snippets and environments.
4011 `script' Highlight subscript and superscript.
4012 `entities' Highlight entities."
4013 :group 'org-appearance
4014 :version "24.4"
4015 :package-version '(Org . "8.0")
4016 :type '(choice
4017 (const :tag "No highlighting" nil)
4018 (set :greedy t :tag "Highlight"
4019 (const :tag "LaTeX snippets and environments" latex)
4020 (const :tag "Subscript and superscript" script)
4021 (const :tag "Entities" entities))))
4022
4023 (defcustom org-hide-emphasis-markers nil
4024 "Non-nil mean font-lock should hide the emphasis marker characters."
4025 :group 'org-appearance
4026 :type 'boolean)
4027
4028 (defcustom org-pretty-entities nil
4029 "Non-nil means show entities as UTF8 characters.
4030 When nil, the \\name form remains in the buffer."
4031 :group 'org-appearance
4032 :version "24.1"
4033 :type 'boolean)
4034
4035 (defcustom org-pretty-entities-include-sub-superscripts t
4036 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4037 :group 'org-appearance
4038 :version "24.1"
4039 :type 'boolean)
4040
4041 (defvar org-emph-re nil
4042 "Regular expression for matching emphasis.
4043 After a match, the match groups contain these elements:
4044 0 The match of the full regular expression, including the characters
4045 before and after the proper match
4046 1 The character before the proper match, or empty at beginning of line
4047 2 The proper match, including the leading and trailing markers
4048 3 The leading marker like * or /, indicating the type of highlighting
4049 4 The text between the emphasis markers, not including the markers
4050 5 The character after the match, empty at the end of a line")
4051 (defvar org-verbatim-re nil
4052 "Regular expression for matching verbatim text.")
4053 (defvar org-emphasis-regexp-components) ; defined just below
4054 (defvar org-emphasis-alist) ; defined just below
4055 (defun org-set-emph-re (var val)
4056 "Set variable and compute the emphasis regular expression."
4057 (set var val)
4058 (when (and (boundp 'org-emphasis-alist)
4059 (boundp 'org-emphasis-regexp-components)
4060 org-emphasis-alist org-emphasis-regexp-components)
4061 (let* ((e org-emphasis-regexp-components)
4062 (pre (car e))
4063 (post (nth 1 e))
4064 (border (nth 2 e))
4065 (body (nth 3 e))
4066 (nl (nth 4 e))
4067 (body1 (concat body "*?"))
4068 (markers (mapconcat 'car org-emphasis-alist ""))
4069 (vmarkers (mapconcat
4070 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4071 org-emphasis-alist "")))
4072 ;; make sure special characters appear at the right position in the class
4073 (if (string-match "\\^" markers)
4074 (setq markers (concat (replace-match "" t t markers) "^")))
4075 (if (string-match "-" markers)
4076 (setq markers (concat (replace-match "" t t markers) "-")))
4077 (if (string-match "\\^" vmarkers)
4078 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4079 (if (string-match "-" vmarkers)
4080 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4081 (if (> nl 0)
4082 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4083 (int-to-string nl) "\\}")))
4084 ;; Make the regexp
4085 (setq org-emph-re
4086 (concat "\\([" pre "]\\|^\\)"
4087 "\\("
4088 "\\([" markers "]\\)"
4089 "\\("
4090 "[^" border "]\\|"
4091 "[^" border "]"
4092 body1
4093 "[^" border "]"
4094 "\\)"
4095 "\\3\\)"
4096 "\\([" post "]\\|$\\)"))
4097 (setq org-verbatim-re
4098 (concat "\\([" pre "]\\|^\\)"
4099 "\\("
4100 "\\([" vmarkers "]\\)"
4101 "\\("
4102 "[^" border "]\\|"
4103 "[^" border "]"
4104 body1
4105 "[^" border "]"
4106 "\\)"
4107 "\\3\\)"
4108 "\\([" post "]\\|$\\)")))))
4109
4110 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4111 ;; set this option proved cumbersome. See this message/thread:
4112 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4113 (defvar org-emphasis-regexp-components
4114 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4115 "Components used to build the regular expression for emphasis.
4116 This is a list with five entries. Terminology: In an emphasis string
4117 like \" *strong word* \", we call the initial space PREMATCH, the final
4118 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4119 and \"trong wor\" is the body. The different components in this variable
4120 specify what is allowed/forbidden in each part:
4121
4122 pre Chars allowed as prematch. Beginning of line will be allowed too.
4123 post Chars allowed as postmatch. End of line will be allowed too.
4124 border The chars *forbidden* as border characters.
4125 body-regexp A regexp like \".\" to match a body character. Don't use
4126 non-shy groups here, and don't allow newline here.
4127 newline The maximum number of newlines allowed in an emphasis exp.
4128
4129 You need to reload Org or to restart Emacs after customizing this.")
4130
4131 (defcustom org-emphasis-alist
4132 `(("*" bold)
4133 ("/" italic)
4134 ("_" underline)
4135 ("=" org-verbatim verbatim)
4136 ("~" org-code verbatim)
4137 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4138 "Alist of characters and faces to emphasize text.
4139 Text starting and ending with a special character will be emphasized,
4140 for example *bold*, _underlined_ and /italic/. This variable sets the
4141 marker characters and the face to be used by font-lock for highlighting
4142 in Org-mode Emacs buffers.
4143
4144 You need to reload Org or to restart Emacs after customizing this."
4145 :group 'org-appearance
4146 :set 'org-set-emph-re
4147 :version "24.4"
4148 :package-version '(Org . "8.0")
4149 :type '(repeat
4150 (list
4151 (string :tag "Marker character")
4152 (choice
4153 (face :tag "Font-lock-face")
4154 (plist :tag "Face property list"))
4155 (option (const verbatim)))))
4156
4157 (defvar org-protecting-blocks
4158 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4159 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4160 This is needed for font-lock setup.")
4161
4162 ;;; Miscellaneous options
4163
4164 (defgroup org-completion nil
4165 "Completion in Org-mode."
4166 :tag "Org Completion"
4167 :group 'org)
4168
4169 (defcustom org-completion-use-ido nil
4170 "Non-nil means use ido completion wherever possible.
4171 Note that `ido-mode' must be active for this variable to be relevant.
4172 If you decide to turn this variable on, you might well want to turn off
4173 `org-outline-path-complete-in-steps'.
4174 See also `org-completion-use-iswitchb'."
4175 :group 'org-completion
4176 :type 'boolean)
4177
4178 (defcustom org-completion-use-iswitchb nil
4179 "Non-nil means use iswitchb completion wherever possible.
4180 Note that `iswitchb-mode' must be active for this variable to be relevant.
4181 If you decide to turn this variable on, you might well want to turn off
4182 `org-outline-path-complete-in-steps'.
4183 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4184 :group 'org-completion
4185 :type 'boolean)
4186
4187 (defcustom org-completion-fallback-command 'hippie-expand
4188 "The expansion command called by \\[pcomplete] in normal context.
4189 Normal means, no org-mode-specific context."
4190 :group 'org-completion
4191 :type 'function)
4192
4193 ;;; Functions and variables from their packages
4194 ;; Declared here to avoid compiler warnings
4195
4196 ;; XEmacs only
4197 (defvar outline-mode-menu-heading)
4198 (defvar outline-mode-menu-show)
4199 (defvar outline-mode-menu-hide)
4200 (defvar zmacs-regions) ; XEmacs regions
4201
4202 ;; Emacs only
4203 (defvar mark-active)
4204
4205 ;; Various packages
4206 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4207 (declare-function calendar-forward-day "cal-move" (arg))
4208 (declare-function calendar-goto-date "cal-move" (date))
4209 (declare-function calendar-goto-today "cal-move" ())
4210 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4211 (defvar calc-embedded-close-formula)
4212 (defvar calc-embedded-open-formula)
4213 (declare-function cdlatex-tab "ext:cdlatex" ())
4214 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4215 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4216 (defvar font-lock-unfontify-region-function)
4217 (declare-function iswitchb-read-buffer "iswitchb"
4218 (prompt &optional default require-match start matches-set))
4219 (defvar iswitchb-temp-buflist)
4220 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4221 (defvar org-agenda-tags-todo-honor-ignore-options)
4222 (declare-function org-agenda-skip "org-agenda" ())
4223 (declare-function
4224 org-agenda-format-item "org-agenda"
4225 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4226 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4227 (declare-function org-agenda-change-all-lines "org-agenda"
4228 (newhead hdmarker &optional fixface just-this))
4229 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4230 (declare-function org-agenda-maybe-redo "org-agenda" ())
4231 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4232 (beg end))
4233 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4234 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4235 "org-agenda" (&optional end))
4236 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4237 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4238 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4239 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4240 (declare-function org-indent-mode "org-indent" (&optional arg))
4241 (declare-function parse-time-string "parse-time" (string))
4242 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4243 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4244 (defvar remember-data-file)
4245 (defvar texmathp-why)
4246 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4247 (declare-function table--at-cell-p "table" (position &optional object at-column))
4248
4249 (defvar org-latex-regexps)
4250
4251 ;;; Autoload and prepare some org modules
4252
4253 ;; Some table stuff that needs to be defined here, because it is used
4254 ;; by the functions setting up org-mode or checking for table context.
4255
4256 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4257 "Detect an org-type or table-type table.")
4258 (defconst org-table-line-regexp "^[ \t]*|"
4259 "Detect an org-type table line.")
4260 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4261 "Detect an org-type table line.")
4262 (defconst org-table-hline-regexp "^[ \t]*|-"
4263 "Detect an org-type table hline.")
4264 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4265 "Detect a table-type table hline.")
4266 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4267 "Detect the first line outside a table when searching from within it.
4268 This works for both table types.")
4269
4270 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4271 "Detect a #+TBLFM line.")
4272
4273 ;;;###autoload
4274 (defun turn-on-orgtbl ()
4275 "Unconditionally turn on `orgtbl-mode'."
4276 (require 'org-table)
4277 (orgtbl-mode 1))
4278
4279 (defun org-at-table-p (&optional table-type)
4280 "Return t if the cursor is inside an org-type table.
4281 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4282 (if org-enable-table-editor
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (looking-at (if table-type org-table-any-line-regexp
4286 org-table-line-regexp)))
4287 nil))
4288 (defsubst org-table-p () (org-at-table-p))
4289
4290 (defun org-at-table.el-p ()
4291 "Return t if and only if we are at a table.el table."
4292 (and (org-at-table-p 'any)
4293 (save-excursion
4294 (goto-char (org-table-begin 'any))
4295 (looking-at org-table1-hline-regexp))))
4296
4297 (defun org-table-recognize-table.el ()
4298 "If there is a table.el table nearby, recognize it and move into it."
4299 (if org-table-tab-recognizes-table.el
4300 (if (org-at-table.el-p)
4301 (progn
4302 (beginning-of-line 1)
4303 (if (looking-at org-table-dataline-regexp)
4304 nil
4305 (if (looking-at org-table1-hline-regexp)
4306 (progn
4307 (beginning-of-line 2)
4308 (if (looking-at org-table-any-border-regexp)
4309 (beginning-of-line -1)))))
4310 (if (re-search-forward "|" (org-table-end t) t)
4311 (progn
4312 (require 'table)
4313 (if (table--at-cell-p (point))
4314 t
4315 (message "recognizing table.el table...")
4316 (table-recognize-table)
4317 (message "recognizing table.el table...done")))
4318 (error "This should not happen"))
4319 t)
4320 nil)
4321 nil))
4322
4323 (defun org-at-table-hline-p ()
4324 "Return t if the cursor is inside a hline in a table."
4325 (if org-enable-table-editor
4326 (save-excursion
4327 (beginning-of-line 1)
4328 (looking-at org-table-hline-regexp))
4329 nil))
4330
4331 (defun org-table-map-tables (function &optional quietly)
4332 "Apply FUNCTION to the start of all tables in the buffer."
4333 (save-excursion
4334 (save-restriction
4335 (widen)
4336 (goto-char (point-min))
4337 (while (re-search-forward org-table-any-line-regexp nil t)
4338 (unless quietly
4339 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4340 (beginning-of-line 1)
4341 (when (and (looking-at org-table-line-regexp)
4342 ;; Exclude tables in src/example/verbatim/clocktable blocks
4343 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4344 (save-excursion (funcall function))
4345 (or (looking-at org-table-line-regexp)
4346 (forward-char 1)))
4347 (re-search-forward org-table-any-border-regexp nil 1))))
4348 (unless quietly (message "Mapping tables: done")))
4349
4350 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4351 (declare-function org-clock-update-mode-line "org-clock" ())
4352 (declare-function org-resolve-clocks "org-clock"
4353 (&optional also-non-dangling-p prompt last-valid))
4354
4355 (defun org-at-TBLFM-p (&optional pos)
4356 "Return t when point (or POS) is in #+TBLFM line."
4357 (save-excursion
4358 (let ((pos pos)))
4359 (goto-char (or pos (point)))
4360 (beginning-of-line 1)
4361 (looking-at org-TBLFM-regexp)))
4362
4363 (defvar org-clock-start-time)
4364 (defvar org-clock-marker (make-marker)
4365 "Marker recording the last clock-in.")
4366 (defvar org-clock-hd-marker (make-marker)
4367 "Marker recording the last clock-in, but the headline position.")
4368 (defvar org-clock-heading ""
4369 "The heading of the current clock entry.")
4370 (defun org-clock-is-active ()
4371 "Return the buffer where the clock is currently running.
4372 Return nil if no clock is running."
4373 (marker-buffer org-clock-marker))
4374
4375 (defun org-check-running-clock ()
4376 "Check if the current buffer contains the running clock.
4377 If yes, offer to stop it and to save the buffer with the changes."
4378 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4379 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4380 (buffer-name))))
4381 (org-clock-out)
4382 (when (y-or-n-p "Save changed buffer?")
4383 (save-buffer))))
4384
4385 (defun org-clocktable-try-shift (dir n)
4386 "Check if this line starts a clock table, if yes, shift the time block."
4387 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4388 (org-clocktable-shift dir n)))
4389
4390 ;;;###autoload
4391 (defun org-clock-persistence-insinuate ()
4392 "Set up hooks for clock persistence."
4393 (require 'org-clock)
4394 (add-hook 'org-mode-hook 'org-clock-load)
4395 (add-hook 'kill-emacs-hook 'org-clock-save))
4396
4397 (defgroup org-archive nil
4398 "Options concerning archiving in Org-mode."
4399 :tag "Org Archive"
4400 :group 'org-structure)
4401
4402 (defcustom org-archive-location "%s_archive::"
4403 "The location where subtrees should be archived.
4404
4405 The value of this variable is a string, consisting of two parts,
4406 separated by a double-colon. The first part is a filename and
4407 the second part is a headline.
4408
4409 When the filename is omitted, archiving happens in the same file.
4410 %s in the filename will be replaced by the current file
4411 name (without the directory part). Archiving to a different file
4412 is useful to keep archived entries from contributing to the
4413 Org-mode Agenda.
4414
4415 The archived entries will be filed as subtrees of the specified
4416 headline. When the headline is omitted, the subtrees are simply
4417 filed away at the end of the file, as top-level entries. Also in
4418 the heading you can use %s to represent the file name, this can be
4419 useful when using the same archive for a number of different files.
4420
4421 Here are a few examples:
4422 \"%s_archive::\"
4423 If the current file is Projects.org, archive in file
4424 Projects.org_archive, as top-level trees. This is the default.
4425
4426 \"::* Archived Tasks\"
4427 Archive in the current file, under the top-level headline
4428 \"* Archived Tasks\".
4429
4430 \"~/org/archive.org::\"
4431 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4432
4433 \"~/org/archive.org::* From %s\"
4434 Archive in file ~/org/archive.org (absolute path), under headlines
4435 \"From FILENAME\" where file name is the current file name.
4436
4437 \"~/org/datetree.org::datetree/* Finished Tasks\"
4438 The \"datetree/\" string is special, signifying to archive
4439 items to the datetree. Items are placed in either the CLOSED
4440 date of the item, or the current date if there is no CLOSED date.
4441 The heading will be a subentry to the current date. There doesn't
4442 need to be a heading, but there always needs to be a slash after
4443 datetree. For example, to store archived items directly in the
4444 datetree, use \"~/org/datetree.org::datetree/\".
4445
4446 \"basement::** Finished Tasks\"
4447 Archive in file ./basement (relative path), as level 3 trees
4448 below the level 2 heading \"** Finished Tasks\".
4449
4450 You may set this option on a per-file basis by adding to the buffer a
4451 line like
4452
4453 #+ARCHIVE: basement::** Finished Tasks
4454
4455 You may also define it locally for a subtree by setting an ARCHIVE property
4456 in the entry. If such a property is found in an entry, or anywhere up
4457 the hierarchy, it will be used."
4458 :group 'org-archive
4459 :type 'string)
4460
4461 (defcustom org-archive-tag "ARCHIVE"
4462 "The tag that marks a subtree as archived.
4463 An archived subtree does not open during visibility cycling, and does
4464 not contribute to the agenda listings.
4465 After changing this, font-lock must be restarted in the relevant buffers to
4466 get the proper fontification."
4467 :group 'org-archive
4468 :group 'org-keywords
4469 :type 'string)
4470
4471 (defcustom org-agenda-skip-archived-trees t
4472 "Non-nil means the agenda will skip any items located in archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4474 variable is no longer recommended, you should leave it at the value t.
4475 Instead, use the key `v' to cycle the archives-mode in the agenda."
4476 :group 'org-archive
4477 :group 'org-agenda-skip
4478 :type 'boolean)
4479
4480 (defcustom org-columns-skip-archived-trees t
4481 "Non-nil means ignore archived trees when creating column view."
4482 :group 'org-archive
4483 :group 'org-properties
4484 :type 'boolean)
4485
4486 (defcustom org-cycle-open-archived-trees nil
4487 "Non-nil means `org-cycle' will open archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE.
4489 When nil, archived trees will stay folded. You can still open them with
4490 normal outline commands like `show-all', but not with the cycling commands."
4491 :group 'org-archive
4492 :group 'org-cycle
4493 :type 'boolean)
4494
4495 (defcustom org-sparse-tree-open-archived-trees nil
4496 "Non-nil means sparse tree construction shows matches in archived trees.
4497 When nil, matches in these trees are highlighted, but the trees are kept in
4498 collapsed state."
4499 :group 'org-archive
4500 :group 'org-sparse-trees
4501 :type 'boolean)
4502
4503 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4504 "The default date type when building a sparse tree.
4505 When this is nil, a date is a scheduled or a deadline timestamp.
4506 Otherwise, these types are allowed:
4507
4508 all: all timestamps
4509 active: only active timestamps (<...>)
4510 inactive: only inactive timestamps (<...)
4511 scheduled: only scheduled timestamps
4512 deadline: only deadline timestamps"
4513 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4514 (const :tag "All timestamps" all)
4515 (const :tag "Only active timestamps" active)
4516 (const :tag "Only inactive timestamps" inactive)
4517 (const :tag "Only scheduled timestamps" scheduled)
4518 (const :tag "Only deadline timestamps" deadline)
4519 (const :tag "Only closed timestamps" closed))
4520 :version "24.3"
4521 :group 'org-sparse-trees)
4522
4523 (defun org-cycle-hide-archived-subtrees (state)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (when (and (not org-cycle-open-archived-trees)
4526 (not (memq state '(overview folded))))
4527 (save-excursion
4528 (let* ((globalp (memq state '(contents all)))
4529 (beg (if globalp (point-min) (point)))
4530 (end (if globalp (point-max) (org-end-of-subtree t))))
4531 (org-hide-archived-subtrees beg end)
4532 (goto-char beg)
4533 (if (looking-at (concat ".*:" org-archive-tag ":"))
4534 (message "%s" (substitute-command-keys
4535 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4536
4537 (defun org-force-cycle-archived ()
4538 "Cycle subtree even if it is archived."
4539 (interactive)
4540 (setq this-command 'org-cycle)
4541 (let ((org-cycle-open-archived-trees t))
4542 (call-interactively 'org-cycle)))
4543
4544 (defun org-hide-archived-subtrees (beg end)
4545 "Re-hide all archived subtrees after a visibility state change."
4546 (save-excursion
4547 (let* ((re (concat ":" org-archive-tag ":")))
4548 (goto-char beg)
4549 (while (re-search-forward re end t)
4550 (when (org-at-heading-p)
4551 (org-flag-subtree t)
4552 (org-end-of-subtree t))))))
4553
4554 (declare-function outline-end-of-heading "outline" ())
4555 (declare-function outline-flag-region "outline" (from to flag))
4556 (defun org-flag-subtree (flag)
4557 (save-excursion
4558 (org-back-to-heading t)
4559 (outline-end-of-heading)
4560 (outline-flag-region (point)
4561 (progn (org-end-of-subtree t) (point))
4562 flag)))
4563
4564 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4565
4566 ;; Declare Column View Code
4567
4568 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4569 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4570 (declare-function org-columns-compute "org-colview" (property))
4571
4572 ;; Declare ID code
4573
4574 (declare-function org-id-store-link "org-id")
4575 (declare-function org-id-locations-load "org-id")
4576 (declare-function org-id-locations-save "org-id")
4577 (defvar org-id-track-globally)
4578
4579 ;;; Variables for pre-computed regular expressions, all buffer local
4580
4581 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4582 "Matches first line of a hidden block.")
4583 (make-variable-buffer-local 'org-drawer-regexp)
4584 (defvar org-todo-regexp nil
4585 "Matches any of the TODO state keywords.")
4586 (make-variable-buffer-local 'org-todo-regexp)
4587 (defvar org-not-done-regexp nil
4588 "Matches any of the TODO state keywords except the last one.")
4589 (make-variable-buffer-local 'org-not-done-regexp)
4590 (defvar org-not-done-heading-regexp nil
4591 "Matches a TODO headline that is not done.")
4592 (make-variable-buffer-local 'org-not-done-regexp)
4593 (defvar org-todo-line-regexp nil
4594 "Matches a headline and puts TODO state into group 2 if present.")
4595 (make-variable-buffer-local 'org-todo-line-regexp)
4596 (defvar org-complex-heading-regexp nil
4597 "Matches a headline and puts everything into groups:
4598 group 1: the stars
4599 group 2: The todo keyword, maybe
4600 group 3: Priority cookie
4601 group 4: True headline
4602 group 5: Tags")
4603 (make-variable-buffer-local 'org-complex-heading-regexp)
4604 (defvar org-complex-heading-regexp-format nil
4605 "Printf format to make regexp to match an exact headline.
4606 This regexp will match the headline of any node which has the
4607 exact headline text that is put into the format, but may have any
4608 TODO state, priority and tags.")
4609 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4610 (defvar org-todo-line-tags-regexp nil
4611 "Matches a headline and puts TODO state into group 2 if present.
4612 Also put tags into group 4 if tags are present.")
4613 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4614 (defvar org-ds-keyword-length 12
4615 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4616 (make-variable-buffer-local 'org-ds-keyword-length)
4617 (defvar org-deadline-regexp nil
4618 "Matches the DEADLINE keyword.")
4619 (make-variable-buffer-local 'org-deadline-regexp)
4620 (defvar org-deadline-time-regexp nil
4621 "Matches the DEADLINE keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-deadline-time-regexp)
4623 (defvar org-deadline-time-hour-regexp nil
4624 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4626 (defvar org-deadline-line-regexp nil
4627 "Matches the DEADLINE keyword and the rest of the line.")
4628 (make-variable-buffer-local 'org-deadline-line-regexp)
4629 (defvar org-scheduled-regexp nil
4630 "Matches the SCHEDULED keyword.")
4631 (make-variable-buffer-local 'org-scheduled-regexp)
4632 (defvar org-scheduled-time-regexp nil
4633 "Matches the SCHEDULED keyword together with a time stamp.")
4634 (make-variable-buffer-local 'org-scheduled-time-regexp)
4635 (defvar org-scheduled-time-hour-regexp nil
4636 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4637 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4638 (defvar org-closed-time-regexp nil
4639 "Matches the CLOSED keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-closed-time-regexp)
4641
4642 (defvar org-keyword-time-regexp nil
4643 "Matches any of the 4 keywords, together with the time stamp.")
4644 (make-variable-buffer-local 'org-keyword-time-regexp)
4645 (defvar org-keyword-time-not-clock-regexp nil
4646 "Matches any of the 3 keywords, together with the time stamp.")
4647 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4648 (defvar org-maybe-keyword-time-regexp nil
4649 "Matches a timestamp, possibly preceded by a keyword.")
4650 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4651 (defvar org-all-time-keywords nil
4652 "List of time keywords.")
4653 (make-variable-buffer-local 'org-all-time-keywords)
4654
4655 (defconst org-plain-time-of-day-regexp
4656 (concat
4657 "\\(\\<[012]?[0-9]"
4658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4659 "\\(--?"
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\)?")
4663 "Regular expression to match a plain time or time range.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 1 the first time, range or not
4668 8 the second time, if it is a range.")
4669
4670 (defconst org-plain-time-extension-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4675 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4676 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4677 groups carry important information:
4678 0 the full match
4679 7 hours of duration
4680 9 minutes of duration")
4681
4682 (defconst org-stamp-time-of-day-regexp
4683 (concat
4684 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4685 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4686 "\\(--?"
4687 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4688 "Regular expression to match a timestamp time or time range.
4689 After a match, the following groups carry important information:
4690 0 the full match
4691 1 date plus weekday, for back referencing to make sure both times are on the same day
4692 2 the first time, range or not
4693 4 the second time, if it is a range.")
4694
4695 (defconst org-startup-options
4696 '(("fold" org-startup-folded t)
4697 ("overview" org-startup-folded t)
4698 ("nofold" org-startup-folded nil)
4699 ("showall" org-startup-folded nil)
4700 ("showeverything" org-startup-folded showeverything)
4701 ("content" org-startup-folded content)
4702 ("indent" org-startup-indented t)
4703 ("noindent" org-startup-indented nil)
4704 ("hidestars" org-hide-leading-stars t)
4705 ("showstars" org-hide-leading-stars nil)
4706 ("odd" org-odd-levels-only t)
4707 ("oddeven" org-odd-levels-only nil)
4708 ("align" org-startup-align-all-tables t)
4709 ("noalign" org-startup-align-all-tables nil)
4710 ("inlineimages" org-startup-with-inline-images t)
4711 ("noinlineimages" org-startup-with-inline-images nil)
4712 ("latexpreview" org-startup-with-latex-preview t)
4713 ("nolatexpreview" org-startup-with-latex-preview nil)
4714 ("customtime" org-display-custom-times t)
4715 ("logdone" org-log-done time)
4716 ("lognotedone" org-log-done note)
4717 ("nologdone" org-log-done nil)
4718 ("lognoteclock-out" org-log-note-clock-out t)
4719 ("nolognoteclock-out" org-log-note-clock-out nil)
4720 ("logrepeat" org-log-repeat state)
4721 ("lognoterepeat" org-log-repeat note)
4722 ("logdrawer" org-log-into-drawer t)
4723 ("nologdrawer" org-log-into-drawer nil)
4724 ("logstatesreversed" org-log-states-order-reversed t)
4725 ("nologstatesreversed" org-log-states-order-reversed nil)
4726 ("nologrepeat" org-log-repeat nil)
4727 ("logreschedule" org-log-reschedule time)
4728 ("lognotereschedule" org-log-reschedule note)
4729 ("nologreschedule" org-log-reschedule nil)
4730 ("logredeadline" org-log-redeadline time)
4731 ("lognoteredeadline" org-log-redeadline note)
4732 ("nologredeadline" org-log-redeadline nil)
4733 ("logrefile" org-log-refile time)
4734 ("lognoterefile" org-log-refile note)
4735 ("nologrefile" org-log-refile nil)
4736 ("fninline" org-footnote-define-inline t)
4737 ("nofninline" org-footnote-define-inline nil)
4738 ("fnlocal" org-footnote-section nil)
4739 ("fnauto" org-footnote-auto-label t)
4740 ("fnprompt" org-footnote-auto-label nil)
4741 ("fnconfirm" org-footnote-auto-label confirm)
4742 ("fnplain" org-footnote-auto-label plain)
4743 ("fnadjust" org-footnote-auto-adjust t)
4744 ("nofnadjust" org-footnote-auto-adjust nil)
4745 ("constcgs" constants-unit-system cgs)
4746 ("constSI" constants-unit-system SI)
4747 ("noptag" org-tag-persistent-alist nil)
4748 ("hideblocks" org-hide-block-startup t)
4749 ("nohideblocks" org-hide-block-startup nil)
4750 ("beamer" org-startup-with-beamer-mode t)
4751 ("entitiespretty" org-pretty-entities t)
4752 ("entitiesplain" org-pretty-entities nil))
4753 "Variable associated with STARTUP options for org-mode.
4754 Each element is a list of three items: the startup options (as written
4755 in the #+STARTUP line), the corresponding variable, and the value to set
4756 this variable to if the option is found. An optional forth element PUSH
4757 means to push this value onto the list in the variable.")
4758
4759 (defun org-update-property-plist (key val props)
4760 "Update PROPS with KEY and VAL."
4761 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4762 (key (if appending (substring key 0 (- (length key) 1)) key))
4763 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4764 (previous (cdr (assoc key props))))
4765 (if appending
4766 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4767 (cons (cons key val) remainder))))
4768
4769 (defconst org-block-regexp
4770 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4771 "Regular expression for hiding blocks.")
4772 (defconst org-heading-keyword-regexp-format
4773 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4774 "Printf format for a regexp matching a headline with some keyword.
4775 This regexp will match the headline of any node which has the
4776 exact keyword that is put into the format. The keyword isn't in
4777 any group by default, but the stars and the body are.")
4778 (defconst org-heading-keyword-maybe-regexp-format
4779 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4780 "Printf format for a regexp matching a headline, possibly with some keyword.
4781 This regexp can match any headline with the specified keyword, or
4782 without a keyword. The keyword isn't in any group by default,
4783 but the stars and the body are.")
4784
4785 (defcustom org-group-tags t
4786 "When non-nil (the default), use group tags.
4787 This can be turned on/off through `org-toggle-tags-groups'."
4788 :group 'org-tags
4789 :group 'org-startup
4790 :type 'boolean)
4791
4792 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4793
4794 (defun org-toggle-tags-groups ()
4795 "Toggle support for group tags.
4796 Support for group tags is controlled by the option
4797 `org-group-tags', which is non-nil by default."
4798 (interactive)
4799 (setq org-group-tags (not org-group-tags))
4800 (cond ((and (derived-mode-p 'org-agenda-mode)
4801 org-group-tags)
4802 (org-agenda-redo))
4803 ((derived-mode-p 'org-mode)
4804 (let ((org-inhibit-startup t)) (org-mode))))
4805 (message "Groups tags support has been turned %s"
4806 (if org-group-tags "on" "off")))
4807
4808 (defun org-set-regexps-and-options-for-tags ()
4809 "Precompute variables used for tags."
4810 (when (derived-mode-p 'org-mode)
4811 (org-set-local 'org-file-tags nil)
4812 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4813 (splitre "[ \t]+")
4814 (start 0)
4815 tags ftags key value)
4816 (save-excursion
4817 (save-restriction
4818 (widen)
4819 (goto-char (point-min))
4820 (while (re-search-forward re nil t)
4821 (setq key (upcase (org-match-string-no-properties 1))
4822 value (org-match-string-no-properties 2))
4823 (if (stringp value) (setq value (org-trim value)))
4824 (cond
4825 ((equal key "TAGS")
4826 (setq tags (append tags (if tags '("\\n") nil)
4827 (org-split-string value splitre))))
4828 ((equal key "FILETAGS")
4829 (when (string-match "\\S-" value)
4830 (setq ftags
4831 (append
4832 ftags
4833 (apply 'append
4834 (mapcar (lambda (x) (org-split-string x ":"))
4835 (org-split-string value)))))))))))
4836 ;; Process the file tags.
4837 (and ftags (org-set-local 'org-file-tags
4838 (mapcar 'org-add-prop-inherited ftags)))
4839 (org-set-local 'org-tag-groups-alist nil)
4840 ;; Process the tags.
4841 (when (and (not tags) org-tag-alist)
4842 (setq tags
4843 (mapcar
4844 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4845 ((eq (car tg) :endgroup) "}")
4846 ((eq (car tg) :grouptags) ":")
4847 ((eq (car tg) :newline) "\n")
4848 (t (concat (car tg)
4849 (if (characterp (cdr tg))
4850 (format "(%s)" (char-to-string (cdr tg))) "")))))
4851 org-tag-alist)))
4852 (let (e tgs g)
4853 (while (setq e (pop tags))
4854 (cond
4855 ((equal e "{")
4856 (progn (push '(:startgroup) tgs)
4857 (when (equal (nth 1 tags) ":")
4858 (push (list (replace-regexp-in-string
4859 "(.+)$" "" (nth 0 tags)))
4860 org-tag-groups-alist)
4861 (setq g 0))))
4862 ((equal e ":") (push '(:grouptags) tgs))
4863 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4864 ((equal e "\\n") (push '(:newline) tgs))
4865 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4866 (push (cons (match-string 1 e)
4867 (string-to-char (match-string 2 e))) tgs)
4868 (if (and g (> g 0))
4869 (setcar org-tag-groups-alist
4870 (append (car org-tag-groups-alist)
4871 (list (match-string 1 e)))))
4872 (if g (setq g (1+ g))))
4873 (t (push (list e) tgs)
4874 (if (and g (> g 0))
4875 (setcar org-tag-groups-alist
4876 (append (car org-tag-groups-alist) (list e))))
4877 (if g (setq g (1+ g))))))
4878 (org-set-local 'org-tag-alist nil)
4879 (while (setq e (pop tgs))
4880 (or (and (stringp (car e))
4881 (assoc (car e) org-tag-alist))
4882 (push e org-tag-alist)))
4883 ;; Return a list with tag variables
4884 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4885
4886 (defvar org-ota nil)
4887 (defun org-set-regexps-and-options ()
4888 "Precompute regular expressions used in the current buffer."
4889 (when (derived-mode-p 'org-mode)
4890 (org-set-local 'org-todo-kwd-alist nil)
4891 (org-set-local 'org-todo-key-alist nil)
4892 (org-set-local 'org-todo-key-trigger nil)
4893 (org-set-local 'org-todo-keywords-1 nil)
4894 (org-set-local 'org-done-keywords nil)
4895 (org-set-local 'org-todo-heads nil)
4896 (org-set-local 'org-todo-sets nil)
4897 (org-set-local 'org-todo-log-states nil)
4898 (org-set-local 'org-file-properties nil)
4899 (let ((re (org-make-options-regexp
4900 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4901 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4902 "SETUPFILE" "OPTIONS")
4903 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4904 (splitre "[ \t]+")
4905 (scripts org-use-sub-superscripts)
4906 kwds kws0 kwsa key log value cat arch const links hw dws
4907 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4908 (start 0))
4909 (save-excursion
4910 (save-restriction
4911 (widen)
4912 (goto-char (point-min))
4913 (while
4914 (or (and
4915 ext-setup-or-nil
4916 (not org-ota)
4917 (let (ret)
4918 (with-temp-buffer
4919 (insert ext-setup-or-nil)
4920 (let ((major-mode 'org-mode) org-ota)
4921 (setq ret (save-match-data
4922 (org-set-regexps-and-options-for-tags)))))
4923 ;; Append setupfile tags to existing tags
4924 (setq org-ota t)
4925 (setq org-file-tags
4926 (delq nil (append org-file-tags (nth 0 ret)))
4927 org-tag-alist
4928 (delq nil (append org-tag-alist (nth 1 ret)))
4929 org-tag-groups-alist
4930 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4931 (and ext-setup-or-nil
4932 (string-match re ext-setup-or-nil start)
4933 (setq start (match-end 0)))
4934 (and (setq ext-setup-or-nil nil start 0)
4935 (re-search-forward re nil t)))
4936 (setq key (upcase (match-string 1 ext-setup-or-nil))
4937 value (org-match-string-no-properties 2 ext-setup-or-nil))
4938 (if (stringp value) (setq value (org-trim value)))
4939 (cond
4940 ((equal key "CATEGORY")
4941 (setq cat value))
4942 ((member key '("SEQ_TODO" "TODO"))
4943 (push (cons 'sequence (org-split-string value splitre)) kwds))
4944 ((equal key "TYP_TODO")
4945 (push (cons 'type (org-split-string value splitre)) kwds))
4946 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4947 ;; general TODO-like setup
4948 (push (cons (intern (downcase (match-string 1 key)))
4949 (org-split-string value splitre)) kwds))
4950 ((equal key "COLUMNS")
4951 (org-set-local 'org-columns-default-format value))
4952 ((equal key "LINK")
4953 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4954 (push (cons (match-string 1 value)
4955 (org-trim (match-string 2 value)))
4956 links)))
4957 ((equal key "PRIORITIES")
4958 (setq prio (org-split-string value " +")))
4959 ((equal key "PROPERTY")
4960 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4961 (setq props (org-update-property-plist (match-string 1 value)
4962 (match-string 2 value)
4963 props))))
4964 ((equal key "DRAWERS")
4965 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4966 ((equal key "CONSTANTS")
4967 (org-table-set-constants))
4968 ((equal key "STARTUP")
4969 (let ((opts (org-split-string value splitre))
4970 l var val)
4971 (while (setq l (pop opts))
4972 (when (setq l (assoc l org-startup-options))
4973 (setq var (nth 1 l) val (nth 2 l))
4974 (if (not (nth 3 l))
4975 (set (make-local-variable var) val)
4976 (if (not (listp (symbol-value var)))
4977 (set (make-local-variable var) nil))
4978 (set (make-local-variable var) (symbol-value var))
4979 (add-to-list var val))))))
4980 ((equal key "ARCHIVE")
4981 (setq arch value)
4982 (remove-text-properties 0 (length arch)
4983 '(face t fontified t) arch))
4984 ((equal key "OPTIONS")
4985 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4986 (setq scripts (read (match-string 2 value)))))
4987 ((and (equal key "SETUPFILE")
4988 ;; Prevent checking in Gnus messages
4989 (not buffer-read-only))
4990 (setq setup-contents (org-file-contents
4991 (expand-file-name
4992 (org-remove-double-quotes value))
4993 'noerror))
4994 (if (not ext-setup-or-nil)
4995 (setq ext-setup-or-nil setup-contents start 0)
4996 (setq ext-setup-or-nil
4997 (concat (substring ext-setup-or-nil 0 start)
4998 "\n" setup-contents "\n"
4999 (substring ext-setup-or-nil start)))))))
5000 ;; search for property blocks
5001 (goto-char (point-min))
5002 (while (re-search-forward org-block-regexp nil t)
5003 (when (equal "PROPERTY" (upcase (match-string 1)))
5004 (setq value (replace-regexp-in-string
5005 "[\n\r]" " " (match-string 4)))
5006 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5007 (setq props (org-update-property-plist (match-string 1 value)
5008 (match-string 2 value)
5009 props)))))))
5010 (org-set-local 'org-use-sub-superscripts scripts)
5011 (when cat
5012 (org-set-local 'org-category (intern cat))
5013 (push (cons "CATEGORY" cat) props))
5014 (when prio
5015 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5016 (setq prio (mapcar 'string-to-char prio))
5017 (org-set-local 'org-highest-priority (nth 0 prio))
5018 (org-set-local 'org-lowest-priority (nth 1 prio))
5019 (org-set-local 'org-default-priority (nth 2 prio)))
5020 (and props (org-set-local 'org-file-properties (nreverse props)))
5021 (and drawers (org-set-local 'org-drawers drawers))
5022 (and arch (org-set-local 'org-archive-location arch))
5023 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5024 ;; Process the TODO keywords
5025 (unless kwds
5026 ;; Use the global values as if they had been given locally.
5027 (setq kwds (default-value 'org-todo-keywords))
5028 (if (stringp (car kwds))
5029 (setq kwds (list (cons org-todo-interpretation
5030 (default-value 'org-todo-keywords)))))
5031 (setq kwds (reverse kwds)))
5032 (setq kwds (nreverse kwds))
5033 (let (inter kws kw)
5034 (while (setq kws (pop kwds))
5035 (let ((kws (or
5036 (run-hook-with-args-until-success
5037 'org-todo-setup-filter-hook kws)
5038 kws)))
5039 (setq inter (pop kws) sep (member "|" kws)
5040 kws0 (delete "|" (copy-sequence kws))
5041 kwsa nil
5042 kws1 (mapcar
5043 (lambda (x)
5044 ;; 1 2
5045 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5046 (progn
5047 (setq kw (match-string 1 x)
5048 key (and (match-end 2) (match-string 2 x))
5049 log (org-extract-log-state-settings x))
5050 (push (cons kw (and key (string-to-char key))) kwsa)
5051 (and log (push log org-todo-log-states))
5052 kw)
5053 (error "Invalid TODO keyword %s" x)))
5054 kws0)
5055 kwsa (if kwsa (append '((:startgroup))
5056 (nreverse kwsa)
5057 '((:endgroup))))
5058 hw (car kws1)
5059 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5060 tail (list inter hw (car dws) (org-last dws))))
5061 (add-to-list 'org-todo-heads hw 'append)
5062 (push kws1 org-todo-sets)
5063 (setq org-done-keywords (append org-done-keywords dws nil))
5064 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5065 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5066 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5067 (setq org-todo-sets (nreverse org-todo-sets)
5068 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5069 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5070 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5071 ;; Compute the regular expressions and other local variables.
5072 ;; Using `org-outline-regexp-bol' would complicate them much,
5073 ;; because of the fixed white space at the end of that string.
5074 (if (not org-done-keywords)
5075 (setq org-done-keywords (and org-todo-keywords-1
5076 (list (org-last org-todo-keywords-1)))))
5077 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5078 (length org-scheduled-string)
5079 (length org-clock-string)
5080 (length org-closed-string)))
5081 org-drawer-regexp
5082 (concat "^[ \t]*:\\("
5083 (mapconcat 'regexp-quote org-drawers "\\|")
5084 "\\):[ \t]*$")
5085 org-not-done-keywords
5086 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5087 org-todo-regexp
5088 (concat "\\("
5089 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5090 "\\)")
5091 org-not-done-regexp
5092 (concat "\\("
5093 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5094 "\\)")
5095 org-not-done-heading-regexp
5096 (format org-heading-keyword-regexp-format org-not-done-regexp)
5097 org-todo-line-regexp
5098 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5099 org-complex-heading-regexp
5100 (concat "^\\(\\*+\\)"
5101 "\\(?: +" org-todo-regexp "\\)?"
5102 "\\(?: +\\(\\[#.\\]\\)\\)?"
5103 "\\(?: +\\(.*?\\)\\)??"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-complex-heading-regexp-format
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(\\[#.\\]\\)\\)?"
5110 "\\(?: +"
5111 ;; Stats cookies can be stuck to body.
5112 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5113 "\\(%s\\)"
5114 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5115 "\\)"
5116 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5117 "[ \t]*$")
5118 org-todo-line-tags-regexp
5119 (concat "^\\(\\*+\\)"
5120 "\\(?: +" org-todo-regexp "\\)?"
5121 "\\(?: +\\(.*?\\)\\)??"
5122 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5123 "[ \t]*$")
5124 org-deadline-regexp (concat "\\<" org-deadline-string)
5125 org-deadline-time-regexp
5126 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5127 org-deadline-time-hour-regexp
5128 (concat "\\<" org-deadline-string
5129 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5130 org-deadline-line-regexp
5131 (concat "\\<\\(" org-deadline-string "\\).*")
5132 org-scheduled-regexp
5133 (concat "\\<" org-scheduled-string)
5134 org-scheduled-time-regexp
5135 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5136 org-scheduled-time-hour-regexp
5137 (concat "\\<" org-scheduled-string
5138 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5139 org-closed-time-regexp
5140 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5141 org-keyword-time-regexp
5142 (concat "\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)"
5146 " *[[<]\\([^]>]+\\)[]>]")
5147 org-keyword-time-not-clock-regexp
5148 (concat "\\<\\(" org-scheduled-string
5149 "\\|" org-deadline-string
5150 "\\|" org-closed-string
5151 "\\)"
5152 " *[[<]\\([^]>]+\\)[]>]")
5153 org-maybe-keyword-time-regexp
5154 (concat "\\(\\<\\(" org-scheduled-string
5155 "\\|" org-deadline-string
5156 "\\|" org-closed-string
5157 "\\|" org-clock-string "\\)\\)?"
5158 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5159 org-all-time-keywords
5160 (mapcar (lambda (w) (substring w 0 -1))
5161 (list org-scheduled-string org-deadline-string
5162 org-clock-string org-closed-string)))
5163 (setq org-ota nil)
5164 (org-compute-latex-and-related-regexp))))
5165
5166 (defun org-file-contents (file &optional noerror)
5167 "Return the contents of FILE, as a string."
5168 (if (or (not file) (not (file-readable-p file)))
5169 (if (not noerror)
5170 (error "Cannot read file \"%s\"" file)
5171 (message "Cannot read file \"%s\"" file)
5172 "")
5173 (with-temp-buffer
5174 (insert-file-contents file)
5175 (buffer-string))))
5176
5177 (defun org-extract-log-state-settings (x)
5178 "Extract the log state setting from a TODO keyword string.
5179 This will extract info from a string like \"WAIT(w@/!)\"."
5180 (let (kw key log1 log2)
5181 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5182 (setq kw (match-string 1 x)
5183 key (and (match-end 2) (match-string 2 x))
5184 log1 (and (match-end 3) (match-string 3 x))
5185 log2 (and (match-end 4) (match-string 4 x)))
5186 (and (or log1 log2)
5187 (list kw
5188 (and log1 (if (equal log1 "!") 'time 'note))
5189 (and log2 (if (equal log2 "!") 'time 'note)))))))
5190
5191 (defun org-remove-keyword-keys (list)
5192 "Remove a pair of parenthesis at the end of each string in LIST."
5193 (mapcar (lambda (x)
5194 (if (string-match "(.*)$" x)
5195 (substring x 0 (match-beginning 0))
5196 x))
5197 list))
5198
5199 (defun org-assign-fast-keys (alist)
5200 "Assign fast keys to a keyword-key alist.
5201 Respect keys that are already there."
5202 (let (new e (alt ?0))
5203 (while (setq e (pop alist))
5204 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5205 (cdr e)) ;; Key already assigned.
5206 (push e new)
5207 (let ((clist (string-to-list (downcase (car e))))
5208 (used (append new alist)))
5209 (when (= (car clist) ?@)
5210 (pop clist))
5211 (while (and clist (rassoc (car clist) used))
5212 (pop clist))
5213 (unless clist
5214 (while (rassoc alt used)
5215 (incf alt)))
5216 (push (cons (car e) (or (car clist) alt)) new))))
5217 (nreverse new)))
5218
5219 ;;; Some variables used in various places
5220
5221 (defvar org-window-configuration nil
5222 "Used in various places to store a window configuration.")
5223 (defvar org-selected-window nil
5224 "Used in various places to store a window configuration.")
5225 (defvar org-finish-function nil
5226 "Function to be called when `C-c C-c' is used.
5227 This is for getting out of special buffers like capture.")
5228
5229
5230 ;; FIXME: Occasionally check by commenting these, to make sure
5231 ;; no other functions uses these, forgetting to let-bind them.
5232 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5233 (defvar org-last-state)
5234 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5235
5236 ;; Defined somewhere in this file, but used before definition.
5237 (defvar org-entities) ;; defined in org-entities.el
5238 (defvar org-struct-menu)
5239 (defvar org-org-menu)
5240 (defvar org-tbl-menu)
5241
5242 ;;;; Define the Org-mode
5243
5244 ;; We use a before-change function to check if a table might need
5245 ;; an update.
5246 (defvar org-table-may-need-update t
5247 "Indicates that a table might need an update.
5248 This variable is set by `org-before-change-function'.
5249 `org-table-align' sets it back to nil.")
5250 (defun org-before-change-function (beg end)
5251 "Every change indicates that a table might need an update."
5252 (setq org-table-may-need-update t))
5253 (defvar org-mode-map)
5254 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5255 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5256 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5257 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5258 (defvar org-table-buffer-is-an nil)
5259
5260 (defvar bidi-paragraph-direction)
5261 (defvar buffer-face-mode-face)
5262
5263 (require 'outline)
5264 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5265 (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"))
5266 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5267
5268 ;; Other stuff we need.
5269 (require 'time-date)
5270 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5271 (require 'easymenu)
5272 (require 'overlay)
5273
5274 ;; (require 'org-macs) moved higher up in the file before it is first used
5275 (require 'org-entities)
5276 ;; (require 'org-compat) moved higher up in the file before it is first used
5277 (require 'org-faces)
5278 (require 'org-list)
5279 (require 'org-pcomplete)
5280 (require 'org-src)
5281 (require 'org-footnote)
5282 (require 'org-macro)
5283
5284 ;; babel
5285 (require 'ob)
5286
5287 ;;;###autoload
5288 (define-derived-mode org-mode outline-mode "Org"
5289 "Outline-based notes management and organizer, alias
5290 \"Carsten's outline-mode for keeping track of everything.\"
5291
5292 Org-mode develops organizational tasks around a NOTES file which
5293 contains information about projects as plain text. Org-mode is
5294 implemented on top of outline-mode, which is ideal to keep the content
5295 of large files well structured. It supports ToDo items, deadlines and
5296 time stamps, which magically appear in the diary listing of the Emacs
5297 calendar. Tables are easily created with a built-in table editor.
5298 Plain text URL-like links connect to websites, emails (VM), Usenet
5299 messages (Gnus), BBDB entries, and any files related to the project.
5300 For printing and sharing of notes, an Org-mode file (or a part of it)
5301 can be exported as a structured ASCII or HTML file.
5302
5303 The following commands are available:
5304
5305 \\{org-mode-map}"
5306
5307 ;; Get rid of Outline menus, they are not needed
5308 ;; Need to do this here because define-derived-mode sets up
5309 ;; the keymap so late. Still, it is a waste to call this each time
5310 ;; we switch another buffer into org-mode.
5311 (if (featurep 'xemacs)
5312 (when (boundp 'outline-mode-menu-heading)
5313 ;; Assume this is Greg's port, it uses easymenu
5314 (easy-menu-remove outline-mode-menu-heading)
5315 (easy-menu-remove outline-mode-menu-show)
5316 (easy-menu-remove outline-mode-menu-hide))
5317 (define-key org-mode-map [menu-bar headings] 'undefined)
5318 (define-key org-mode-map [menu-bar hide] 'undefined)
5319 (define-key org-mode-map [menu-bar show] 'undefined))
5320
5321 (org-load-modules-maybe)
5322 (easy-menu-add org-org-menu)
5323 (easy-menu-add org-tbl-menu)
5324 (org-install-agenda-files-menu)
5325 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5326 (add-to-invisibility-spec '(org-cwidth))
5327 (add-to-invisibility-spec '(org-hide-block . t))
5328 (when (featurep 'xemacs)
5329 (org-set-local 'line-move-ignore-invisible t))
5330 (org-set-local 'outline-regexp org-outline-regexp)
5331 (org-set-local 'outline-level 'org-outline-level)
5332 (setq bidi-paragraph-direction 'left-to-right)
5333 (when (and org-ellipsis
5334 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5335 (fboundp 'make-glyph-code))
5336 (unless org-display-table
5337 (setq org-display-table (make-display-table)))
5338 (set-display-table-slot
5339 org-display-table 4
5340 (vconcat (mapcar
5341 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5342 org-ellipsis)))
5343 (if (stringp org-ellipsis) org-ellipsis "..."))))
5344 (setq buffer-display-table org-display-table))
5345 (org-set-regexps-and-options-for-tags)
5346 (org-set-regexps-and-options)
5347 (org-set-font-lock-defaults)
5348 (when (and org-tag-faces (not org-tags-special-faces-re))
5349 ;; tag faces set outside customize.... force initialization.
5350 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5351 ;; Calc embedded
5352 (org-set-local 'calc-embedded-open-mode "# ")
5353 ;; Modify a few syntax entries
5354 (modify-syntax-entry ?@ "w")
5355 (modify-syntax-entry ?\" "\"")
5356 (modify-syntax-entry ?\\ "_")
5357 (modify-syntax-entry ?~ "_")
5358 (if org-startup-truncated (setq truncate-lines t))
5359 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5360 (org-set-local 'font-lock-unfontify-region-function
5361 'org-unfontify-region)
5362 ;; Activate before-change-function
5363 (org-set-local 'org-table-may-need-update t)
5364 (org-add-hook 'before-change-functions 'org-before-change-function nil
5365 'local)
5366 ;; Check for running clock before killing a buffer
5367 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5368 ;; Initialize macros templates.
5369 (org-macro-initialize-templates)
5370 ;; Initialize radio targets.
5371 (org-update-radio-target-regexp)
5372 ;; Indentation.
5373 (org-set-local 'indent-line-function 'org-indent-line)
5374 (org-set-local 'indent-region-function 'org-indent-region)
5375 ;; Filling and auto-filling.
5376 (org-setup-filling)
5377 ;; Comments.
5378 (org-setup-comments-handling)
5379 ;; Beginning/end of defun
5380 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5381 (org-set-local 'end-of-defun-function
5382 (lambda ()
5383 (if (not (org-at-heading-p))
5384 (org-forward-element)
5385 (org-forward-element)
5386 (forward-char -1))))
5387 ;; Next error for sparse trees
5388 (org-set-local 'next-error-function 'org-occur-next-match)
5389 ;; Make sure dependence stuff works reliably, even for users who set it
5390 ;; too late :-(
5391 (if org-enforce-todo-dependencies
5392 (add-hook 'org-blocker-hook
5393 'org-block-todo-from-children-or-siblings-or-parent)
5394 (remove-hook 'org-blocker-hook
5395 'org-block-todo-from-children-or-siblings-or-parent))
5396 (if org-enforce-todo-checkbox-dependencies
5397 (add-hook 'org-blocker-hook
5398 'org-block-todo-from-checkboxes)
5399 (remove-hook 'org-blocker-hook
5400 'org-block-todo-from-checkboxes))
5401
5402 ;; Align options lines
5403 (org-set-local
5404 'align-mode-rules-list
5405 '((org-in-buffer-settings
5406 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5407 (modes . '(org-mode)))))
5408
5409 ;; Imenu
5410 (org-set-local 'imenu-create-index-function
5411 'org-imenu-get-tree)
5412
5413 ;; Make isearch reveal context
5414 (if (or (featurep 'xemacs)
5415 (not (boundp 'outline-isearch-open-invisible-function)))
5416 ;; Emacs 21 and XEmacs make use of the hook
5417 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5418 ;; Emacs 22 deals with this through a special variable
5419 (org-set-local 'outline-isearch-open-invisible-function
5420 (lambda (&rest ignore) (org-show-context 'isearch)))
5421 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5422
5423 ;; Setup the pcomplete hooks
5424 (set (make-local-variable 'pcomplete-command-completion-function)
5425 'org-pcomplete-initial)
5426 (set (make-local-variable 'pcomplete-command-name-function)
5427 'org-command-at-point)
5428 (set (make-local-variable 'pcomplete-default-completion-function)
5429 'ignore)
5430 (set (make-local-variable 'pcomplete-parse-arguments-function)
5431 'org-parse-arguments)
5432 (set (make-local-variable 'pcomplete-termination-string) "")
5433 (when (>= emacs-major-version 23)
5434 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5435
5436 ;; If empty file that did not turn on org-mode automatically, make it to.
5437 (if (and org-insert-mode-line-in-empty-file
5438 (org-called-interactively-p 'any)
5439 (= (point-min) (point-max)))
5440 (insert "# -*- mode: org -*-\n\n"))
5441 (unless org-inhibit-startup
5442 (org-unmodified
5443 (and org-startup-with-beamer-mode (org-beamer-mode))
5444 (when org-startup-align-all-tables
5445 (org-table-map-tables 'org-table-align 'quietly))
5446 (when org-startup-with-inline-images
5447 (org-display-inline-images))
5448 (when org-startup-with-latex-preview
5449 (org-preview-latex-fragment))
5450 (unless org-inhibit-startup-visibility-stuff
5451 (org-set-startup-visibility))))
5452 ;; Try to set org-hide correctly
5453 (let ((foreground (org-find-invisible-foreground)))
5454 (if foreground
5455 (set-face-foreground 'org-hide foreground))))
5456
5457 ;; Update `customize-package-emacs-version-alist'
5458 (add-to-list 'customize-package-emacs-version-alist
5459 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5460 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5461 ("8.2.6" . "24.4")))
5462
5463 (defvar org-mode-transpose-word-syntax-table
5464 (let ((st (make-syntax-table)))
5465 (mapc (lambda(c) (modify-syntax-entry
5466 (string-to-char (car c)) "w p" st))
5467 org-emphasis-alist)
5468 st))
5469
5470 (when (fboundp 'abbrev-table-put)
5471 (abbrev-table-put org-mode-abbrev-table
5472 :parents (list text-mode-abbrev-table)))
5473
5474 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5475
5476 (defsubst org-fix-ellipsis-at-bol ()
5477 (save-excursion (goto-char (window-start)) (recenter 0)))
5478
5479 (defun org-find-invisible-foreground ()
5480 (let ((candidates (remove
5481 "unspecified-bg"
5482 (nconc
5483 (list (face-background 'default)
5484 (face-background 'org-default))
5485 (mapcar
5486 (lambda (alist)
5487 (when (boundp alist)
5488 (cdr (assoc 'background-color (symbol-value alist)))))
5489 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5490 (list (face-foreground 'org-hide))))))
5491 (car (remove nil candidates))))
5492
5493 (defun org-current-time (&optional rounding-minutes past)
5494 "Current time, possibly rounded to ROUNDING-MINUTES.
5495 When ROUNDING-MINUTES is not an integer, fall back on the car of
5496 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5497 the rounding returns a past time."
5498 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5499 (car org-time-stamp-rounding-minutes)))
5500 (time (decode-time)) res)
5501 (if (< r 1)
5502 (current-time)
5503 (setq res
5504 (apply 'encode-time
5505 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5506 (nthcdr 2 time))))
5507 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5508 (seconds-to-time (- (org-float-time res) (* r 60)))
5509 res))))
5510
5511 (defun org-today ()
5512 "Return today date, considering `org-extend-today-until'."
5513 (time-to-days
5514 (time-subtract (current-time)
5515 (list 0 (* 3600 org-extend-today-until) 0))))
5516
5517 ;;;; Font-Lock stuff, including the activators
5518
5519 (defvar org-mouse-map (make-sparse-keymap))
5520 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5521 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5522 (when org-mouse-1-follows-link
5523 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5524 (when org-tab-follows-link
5525 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5526 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5527
5528 (require 'font-lock)
5529
5530 (defconst org-non-link-chars "]\t\n\r<>")
5531 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5532 "shell" "elisp" "doi" "message"))
5533 (defvar org-link-types-re nil
5534 "Matches a link that has a url-like prefix like \"http:\"")
5535 (defvar org-link-re-with-space nil
5536 "Matches a link with spaces, optional angular brackets around it.")
5537 (defvar org-link-re-with-space2 nil
5538 "Matches a link with spaces, optional angular brackets around it.")
5539 (defvar org-link-re-with-space3 nil
5540 "Matches a link with spaces, only for internal part in bracket links.")
5541 (defvar org-angle-link-re nil
5542 "Matches link with angular brackets, spaces are allowed.")
5543 (defvar org-plain-link-re nil
5544 "Matches plain link, without spaces.")
5545 (defvar org-bracket-link-regexp nil
5546 "Matches a link in double brackets.")
5547 (defvar org-bracket-link-analytic-regexp nil
5548 "Regular expression used to analyze links.
5549 Here is what the match groups contain after a match:
5550 1: http:
5551 2: http
5552 3: path
5553 4: [desc]
5554 5: desc")
5555 (defvar org-bracket-link-analytic-regexp++ nil
5556 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5557 (defvar org-any-link-re nil
5558 "Regular expression matching any link.")
5559
5560 (defconst org-match-sexp-depth 3
5561 "Number of stacked braces for sub/superscript matching.")
5562
5563 (defun org-create-multibrace-regexp (left right n)
5564 "Create a regular expression which will match a balanced sexp.
5565 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5566 as single character strings.
5567 The regexp returned will match the entire expression including the
5568 delimiters. It will also define a single group which contains the
5569 match except for the outermost delimiters. The maximum depth of
5570 stacked delimiters is N. Escaping delimiters is not possible."
5571 (let* ((nothing (concat "[^" left right "]*?"))
5572 (or "\\|")
5573 (re nothing)
5574 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5575 (while (> n 1)
5576 (setq n (1- n)
5577 re (concat re or next)
5578 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5579 (concat left "\\(" re "\\)" right)))
5580
5581 (defvar org-match-substring-regexp
5582 (concat
5583 "\\(\\S-\\)\\([_^]\\)\\("
5584 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5585 "\\|"
5586 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5587 "\\|"
5588 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5589 "The regular expression matching a sub- or superscript.")
5590
5591 (defvar org-match-substring-with-braces-regexp
5592 (concat
5593 "\\(\\S-\\)\\([_^]\\)\\("
5594 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5595 "\\)")
5596 "The regular expression matching a sub- or superscript, forcing braces.")
5597
5598 (defun org-make-link-regexps ()
5599 "Update the link regular expressions.
5600 This should be called after the variable `org-link-types' has changed."
5601 (let ((types-re (regexp-opt org-link-types t)))
5602 (setq org-link-types-re
5603 (concat "\\`" types-re ":")
5604 org-link-re-with-space
5605 (concat "<?" types-re ":"
5606 "\\([^" org-non-link-chars " ]"
5607 "[^" org-non-link-chars "]*"
5608 "[^" org-non-link-chars " ]\\)>?")
5609 org-link-re-with-space2
5610 (concat "<?" types-re ":"
5611 "\\([^" org-non-link-chars " ]"
5612 "[^\t\n\r]*"
5613 "[^" org-non-link-chars " ]\\)>?")
5614 org-link-re-with-space3
5615 (concat "<?" types-re ":"
5616 "\\([^" org-non-link-chars " ]"
5617 "[^\t\n\r]*\\)")
5618 org-angle-link-re
5619 (concat "<" types-re ":"
5620 "\\([^" org-non-link-chars " ]"
5621 "[^" org-non-link-chars "]*"
5622 "\\)>")
5623 org-plain-link-re
5624 (concat
5625 "\\<" types-re ":"
5626 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5627 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5628 org-bracket-link-regexp
5629 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5630 org-bracket-link-analytic-regexp
5631 (concat
5632 "\\[\\["
5633 "\\(" types-re ":\\)?"
5634 "\\([^]]+\\)"
5635 "\\]"
5636 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5637 "\\]")
5638 org-bracket-link-analytic-regexp++
5639 (concat
5640 "\\[\\["
5641 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5642 "\\([^]]+\\)"
5643 "\\]"
5644 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5645 "\\]")
5646 org-any-link-re
5647 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5648 org-angle-link-re "\\)\\|\\("
5649 org-plain-link-re "\\)"))))
5650
5651 (org-make-link-regexps)
5652
5653 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5654 "Regular expression for fast time stamp matching.")
5655 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5656 "Regular expression for fast time stamp matching.")
5657 (defconst org-ts-regexp0
5658 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5659 "Regular expression matching time strings for analysis.
5660 This one does not require the space after the date, so it can be used
5661 on a string that terminates immediately after the date.")
5662 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5663 "Regular expression matching time strings for analysis.")
5664 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5665 "Regular expression matching time stamps, with groups.")
5666 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5667 "Regular expression matching time stamps (also [..]), with groups.")
5668 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5669 "Regular expression matching a time stamp range.")
5670 (defconst org-tr-regexp-both
5671 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5672 "Regular expression matching a time stamp range.")
5673 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5674 org-ts-regexp "\\)?")
5675 "Regular expression matching a time stamp or time stamp range.")
5676 (defconst org-tsr-regexp-both
5677 (concat org-ts-regexp-both "\\(--?-?"
5678 org-ts-regexp-both "\\)?")
5679 "Regular expression matching a time stamp or time stamp range.
5680 The time stamps may be either active or inactive.")
5681
5682 (defvar org-emph-face nil)
5683
5684 (defun org-do-emphasis-faces (limit)
5685 "Run through the buffer and add overlays to emphasized strings."
5686 (let (rtn a)
5687 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5688 (let* ((border (char-after (match-beginning 3)))
5689 (bre (regexp-quote (char-to-string border))))
5690 (if (and (not (= border (char-after (match-beginning 4))))
5691 (not (save-match-data
5692 (string-match (concat bre ".*" bre)
5693 (replace-regexp-in-string
5694 "\n" " "
5695 (substring (match-string 2) 1 -1))))))
5696 (progn
5697 (setq rtn t)
5698 (setq a (assoc (match-string 3) org-emphasis-alist))
5699 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5700 'face
5701 (nth 1 a))
5702 (and (nth 2 a)
5703 (org-remove-flyspell-overlays-in
5704 (match-beginning 0) (match-end 0)))
5705 (add-text-properties (match-beginning 2) (match-end 2)
5706 '(font-lock-multiline t org-emphasis t))
5707 (when org-hide-emphasis-markers
5708 (add-text-properties (match-end 4) (match-beginning 5)
5709 '(invisible org-link))
5710 (add-text-properties (match-beginning 3) (match-end 3)
5711 '(invisible org-link))))))
5712 (goto-char (1+ (match-beginning 0))))
5713 rtn))
5714
5715 (defun org-emphasize (&optional char)
5716 "Insert or change an emphasis, i.e. a font like bold or italic.
5717 If there is an active region, change that region to a new emphasis.
5718 If there is no region, just insert the marker characters and position
5719 the cursor between them.
5720 CHAR should be the marker character. If it is a space, it means to
5721 remove the emphasis of the selected region.
5722 If CHAR is not given (for example in an interactive call) it will be
5723 prompted for."
5724 (interactive)
5725 (let ((erc org-emphasis-regexp-components)
5726 (prompt "")
5727 (string "") beg end move c s)
5728 (if (org-region-active-p)
5729 (setq beg (region-beginning) end (region-end)
5730 string (buffer-substring beg end))
5731 (setq move t))
5732
5733 (unless char
5734 (message "Emphasis marker or tag: [%s]"
5735 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5736 (setq char (read-char-exclusive)))
5737 (if (equal char ?\ )
5738 (setq s "" move nil)
5739 (unless (assoc (char-to-string char) org-emphasis-alist)
5740 (user-error "No such emphasis marker: \"%c\"" char))
5741 (setq s (char-to-string char)))
5742 (while (and (> (length string) 1)
5743 (equal (substring string 0 1) (substring string -1))
5744 (assoc (substring string 0 1) org-emphasis-alist))
5745 (setq string (substring string 1 -1)))
5746 (setq string (concat s string s))
5747 (if beg (delete-region beg end))
5748 (unless (or (bolp)
5749 (string-match (concat "[" (nth 0 erc) "\n]")
5750 (char-to-string (char-before (point)))))
5751 (insert " "))
5752 (unless (or (eobp)
5753 (string-match (concat "[" (nth 1 erc) "\n]")
5754 (char-to-string (char-after (point)))))
5755 (insert " ") (backward-char 1))
5756 (insert string)
5757 (and move (backward-char 1))))
5758
5759 (defconst org-nonsticky-props
5760 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5761
5762 (defsubst org-rear-nonsticky-at (pos)
5763 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5764
5765 (defun org-activate-plain-links (limit)
5766 "Run through the buffer and add overlays to links."
5767 (let (f hl)
5768 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5769 (not (org-in-src-block-p)))
5770 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5771 (setq f (get-text-property (match-beginning 0) 'face))
5772 (setq hl (org-match-string-no-properties 0))
5773 (if (or (eq f 'org-tag)
5774 (and (listp f) (memq 'org-tag f)))
5775 nil
5776 (add-text-properties (match-beginning 0) (match-end 0)
5777 (list 'mouse-face 'highlight
5778 'face 'org-link
5779 'htmlize-link `(:uri ,hl)
5780 'keymap org-mouse-map))
5781 (org-rear-nonsticky-at (match-end 0)))
5782 t)))
5783
5784 (defun org-activate-code (limit)
5785 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5786 (progn
5787 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5788 (remove-text-properties (match-beginning 0) (match-end 0)
5789 '(display t invisible t intangible t))
5790 t)))
5791
5792 (defcustom org-src-fontify-natively nil
5793 "When non-nil, fontify code in code blocks."
5794 :type 'boolean
5795 :version "24.1"
5796 :group 'org-appearance
5797 :group 'org-babel)
5798
5799 (defcustom org-allow-promoting-top-level-subtree nil
5800 "When non-nil, allow promoting a top level subtree.
5801 The leading star of the top level headline will be replaced
5802 by a #."
5803 :type 'boolean
5804 :version "24.1"
5805 :group 'org-appearance)
5806
5807 (defun org-fontify-meta-lines-and-blocks (limit)
5808 (condition-case nil
5809 (org-fontify-meta-lines-and-blocks-1 limit)
5810 (error (message "org-mode fontification error"))))
5811
5812 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5813 "Fontify #+ lines and blocks."
5814 (let ((case-fold-search t))
5815 (if (re-search-forward
5816 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5817 limit t)
5818 (let ((beg (match-beginning 0))
5819 (block-start (match-end 0))
5820 (block-end nil)
5821 (lang (match-string 7))
5822 (beg1 (line-beginning-position 2))
5823 (dc1 (downcase (match-string 2)))
5824 (dc3 (downcase (match-string 3)))
5825 end end1 quoting block-type ovl)
5826 (cond
5827 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5828 ;; a single line of backend-specific content
5829 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5830 (remove-text-properties (match-beginning 0) (match-end 0)
5831 '(display t invisible t intangible t))
5832 (add-text-properties (match-beginning 1) (match-end 3)
5833 '(font-lock-fontified t face org-meta-line))
5834 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5835 '(font-lock-fontified t face org-block))
5836 ; for backend-specific code
5837 t)
5838 ((and (match-end 4) (equal dc3 "+begin"))
5839 ;; Truly a block
5840 (setq block-type (downcase (match-string 5))
5841 quoting (member block-type org-protecting-blocks))
5842 (when (re-search-forward
5843 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5844 nil t) ;; on purpose, we look further than LIMIT
5845 (setq end (min (point-max) (match-end 0))
5846 end1 (min (point-max) (1- (match-beginning 0))))
5847 (setq block-end (match-beginning 0))
5848 (when quoting
5849 (remove-text-properties beg end
5850 '(display t invisible t intangible t)))
5851 (add-text-properties
5852 beg end
5853 '(font-lock-fontified t font-lock-multiline t))
5854 (add-text-properties beg beg1 '(face org-meta-line))
5855 (add-text-properties end1 (min (point-max) (1+ end))
5856 '(face org-meta-line)) ; for end_src
5857 (cond
5858 ((and lang (not (string= lang "")) org-src-fontify-natively)
5859 (org-src-font-lock-fontify-block lang block-start block-end)
5860 ;; remove old background overlays
5861 (mapc (lambda (ov)
5862 (if (eq (overlay-get ov 'face) 'org-block-background)
5863 (delete-overlay ov)))
5864 (overlays-at (/ (+ beg1 block-end) 2)))
5865 ;; add a background overlay
5866 (setq ovl (make-overlay beg1 block-end))
5867 (overlay-put ovl 'face 'org-block-background)
5868 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5869 (quoting
5870 (add-text-properties beg1 (min (point-max) (1+ end1))
5871 '(face org-block))) ; end of source block
5872 ((not org-fontify-quote-and-verse-blocks))
5873 ((string= block-type "quote")
5874 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5875 ((string= block-type "verse")
5876 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5877 (add-text-properties beg beg1 '(face org-block-begin-line))
5878 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5879 '(face org-block-end-line))
5880 t))
5881 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5882 (add-text-properties
5883 beg (match-end 3)
5884 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5885 '(font-lock-fontified t invisible t)
5886 '(font-lock-fontified t face org-document-info-keyword)))
5887 (add-text-properties
5888 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5889 (if (string-equal dc1 "+title:")
5890 '(font-lock-fontified t face org-document-title)
5891 '(font-lock-fontified t face org-document-info))))
5892 ((or (equal dc1 "+results")
5893 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5894 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5895 "+call:" "+header:" "+headers:" "+name:"))
5896 (and (match-end 4) (equal dc3 "+attr")))
5897 (add-text-properties
5898 beg (match-end 0)
5899 '(font-lock-fontified t face org-meta-line))
5900 t)
5901 ((member dc3 '(" " ""))
5902 (add-text-properties
5903 beg (match-end 0)
5904 '(font-lock-fontified t face font-lock-comment-face)))
5905 ((not (member (char-after beg) '(?\ ?\t)))
5906 ;; just any other in-buffer setting, but not indented
5907 (add-text-properties
5908 beg (match-end 0)
5909 '(font-lock-fontified t face org-meta-line))
5910 t)
5911 (t nil))))))
5912
5913 (defun org-activate-angle-links (limit)
5914 "Run through the buffer and add overlays to links."
5915 (if (and (re-search-forward org-angle-link-re limit t)
5916 (not (org-in-src-block-p)))
5917 (progn
5918 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5919 (add-text-properties (match-beginning 0) (match-end 0)
5920 (list 'mouse-face 'highlight
5921 'keymap org-mouse-map))
5922 (org-rear-nonsticky-at (match-end 0))
5923 t)))
5924
5925 (defun org-activate-footnote-links (limit)
5926 "Run through the buffer and add overlays to footnotes."
5927 (let ((fn (org-footnote-next-reference-or-definition limit)))
5928 (when fn
5929 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5930 (org-remove-flyspell-overlays-in beg end)
5931 (add-text-properties beg end
5932 (list 'mouse-face 'highlight
5933 'keymap org-mouse-map
5934 'help-echo
5935 (if (= (point-at-bol) beg)
5936 "Footnote definition"
5937 "Footnote reference")
5938 'font-lock-fontified t
5939 'font-lock-multiline t
5940 'face 'org-footnote))))))
5941
5942 (defun org-activate-bracket-links (limit)
5943 "Run through the buffer and add overlays to bracketed links."
5944 (if (and (re-search-forward org-bracket-link-regexp limit t)
5945 (not (org-in-src-block-p)))
5946 (let* ((hl (org-match-string-no-properties 1))
5947 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5948 (ip (org-maybe-intangible
5949 (list 'invisible 'org-link
5950 'keymap org-mouse-map 'mouse-face 'highlight
5951 'font-lock-multiline t 'help-echo help
5952 'htmlize-link `(:uri ,hl))))
5953 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 ;; We need to remove the invisible property here. Table narrowing
5957 ;; may have made some of this invisible.
5958 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (remove-text-properties (match-beginning 0) (match-end 0)
5960 '(invisible nil))
5961 (if (match-end 3)
5962 (progn
5963 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5964 (org-rear-nonsticky-at (match-beginning 3))
5965 (add-text-properties (match-beginning 3) (match-end 3) vp)
5966 (org-rear-nonsticky-at (match-end 3))
5967 (add-text-properties (match-end 3) (match-end 0) ip)
5968 (org-rear-nonsticky-at (match-end 0)))
5969 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5970 (org-rear-nonsticky-at (match-beginning 1))
5971 (add-text-properties (match-beginning 1) (match-end 1) vp)
5972 (org-rear-nonsticky-at (match-end 1))
5973 (add-text-properties (match-end 1) (match-end 0) ip)
5974 (org-rear-nonsticky-at (match-end 0)))
5975 t)))
5976
5977 (defun org-activate-dates (limit)
5978 "Run through the buffer and add overlays to dates."
5979 (if (and (re-search-forward org-tsr-regexp-both limit t)
5980 (not (equal (char-before (match-beginning 0)) 91)))
5981 (progn
5982 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5983 (add-text-properties (match-beginning 0) (match-end 0)
5984 (list 'mouse-face 'highlight
5985 'keymap org-mouse-map))
5986 (org-rear-nonsticky-at (match-end 0))
5987 (when org-display-custom-times
5988 (if (match-end 3)
5989 (org-display-custom-time (match-beginning 3) (match-end 3)))
5990 (org-display-custom-time (match-beginning 1) (match-end 1)))
5991 t)))
5992
5993 (defvar org-target-link-regexp nil
5994 "Regular expression matching radio targets in plain text.")
5995 (make-variable-buffer-local 'org-target-link-regexp)
5996 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5997 "Regular expression matching a link target.")
5998 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5999 "Regular expression matching a radio target.")
6000 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6001 "Regular expression matching any target.")
6002
6003 (defun org-activate-target-links (limit)
6004 "Run through the buffer and add overlays to target matches."
6005 (when org-target-link-regexp
6006 (let ((case-fold-search t))
6007 (if (re-search-forward org-target-link-regexp limit t)
6008 (progn
6009 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (add-text-properties (match-beginning 0) (match-end 0)
6011 (list 'mouse-face 'highlight
6012 'keymap org-mouse-map
6013 'help-echo "Radio target link"
6014 'org-linked-text t))
6015 (org-rear-nonsticky-at (match-end 0))
6016 t)))))
6017
6018 (defun org-update-radio-target-regexp ()
6019 "Find all radio targets in this file and update the regular expression."
6020 (interactive)
6021 (when (memq 'radio org-activate-links)
6022 (setq org-target-link-regexp
6023 (org-make-target-link-regexp (org-all-targets 'radio)))
6024 (org-restart-font-lock)))
6025
6026 (defun org-hide-wide-columns (limit)
6027 (let (s e)
6028 (setq s (text-property-any (point) (or limit (point-max))
6029 'org-cwidth t))
6030 (when s
6031 (setq e (next-single-property-change s 'org-cwidth))
6032 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6033 (goto-char e)
6034 t)))
6035
6036 (defvar org-latex-and-related-regexp nil
6037 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6038 (defvar org-match-substring-regexp)
6039 (defvar org-match-substring-with-braces-regexp)
6040
6041 (defun org-compute-latex-and-related-regexp ()
6042 "Compute regular expression for LaTeX, entities and sub/superscript.
6043 Result depends on variable `org-highlight-latex-and-related'."
6044 (org-set-local
6045 'org-latex-and-related-regexp
6046 (let* ((re-sub
6047 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6048 ((eq org-use-sub-superscripts '{})
6049 (list org-match-substring-with-braces-regexp))
6050 (org-use-sub-superscripts (list org-match-substring-regexp))))
6051 (re-latex
6052 (when (memq 'latex org-highlight-latex-and-related)
6053 (let ((matchers (plist-get org-format-latex-options :matchers)))
6054 (delq nil
6055 (mapcar (lambda (x)
6056 (and (member (car x) matchers) (nth 1 x)))
6057 org-latex-regexps)))))
6058 (re-entities
6059 (when (memq 'entities org-highlight-latex-and-related)
6060 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6061 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6062
6063 (defun org-do-latex-and-related (limit)
6064 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6065 LIMIT bounds the search for syntax to highlight. Stop at first
6066 highlighted object, if any. Return t if some highlighting was
6067 done, nil otherwise."
6068 (when (org-string-nw-p org-latex-and-related-regexp)
6069 (catch 'found
6070 (while (re-search-forward org-latex-and-related-regexp limit t)
6071 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6072 'face))
6073 '(org-code org-verbatim underline))
6074 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6075 '(?_ ?^))
6076 1
6077 0)))
6078 (font-lock-prepend-text-property
6079 (+ offset (match-beginning 0)) (match-end 0)
6080 'face 'org-latex-and-related)
6081 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6082 '(font-lock-multiline t)))
6083 (throw 'found t)))
6084 nil)))
6085
6086 (defun org-restart-font-lock ()
6087 "Restart `font-lock-mode', to force refontification."
6088 (when (and (boundp 'font-lock-mode) font-lock-mode)
6089 (font-lock-mode -1)
6090 (font-lock-mode 1)))
6091
6092 (defun org-all-targets (&optional radio)
6093 "Return a list of all targets in this file.
6094 When optional argument RADIO is non-nil, only find radio
6095 targets."
6096 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6097 (save-excursion
6098 (goto-char (point-min))
6099 (while (re-search-forward re nil t)
6100 ;; Make sure point is really within the object.
6101 (backward-char)
6102 (let ((obj (org-element-context)))
6103 (when (memq (org-element-type obj) '(radio-target target))
6104 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6105 rtn)))
6106
6107 (defun org-make-target-link-regexp (targets)
6108 "Make regular expression matching all strings in TARGETS.
6109 The regular expression finds the targets also if there is a line break
6110 between words."
6111 (and targets
6112 (concat
6113 "\\_<\\("
6114 (mapconcat
6115 (lambda (x)
6116 (setq x (regexp-quote x))
6117 (while (string-match " +" x)
6118 (setq x (replace-match "\\s-+" t t x)))
6119 x)
6120 targets
6121 "\\|")
6122 "\\)\\_>")))
6123
6124 (defun org-activate-tags (limit)
6125 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6126 (progn
6127 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6128 (add-text-properties (match-beginning 1) (match-end 1)
6129 (list 'mouse-face 'highlight
6130 'keymap org-mouse-map))
6131 (org-rear-nonsticky-at (match-end 1))
6132 t)))
6133
6134 (defun org-outline-level ()
6135 "Compute the outline level of the heading at point.
6136 If this is called at a normal headline, the level is the number of stars.
6137 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6138 (save-excursion
6139 (if (not (condition-case nil
6140 (org-back-to-heading t)
6141 (error nil)))
6142 0
6143 (looking-at org-outline-regexp)
6144 (1- (- (match-end 0) (match-beginning 0))))))
6145
6146 (defvar org-font-lock-keywords nil)
6147
6148 (defsubst org-re-property (property &optional literal)
6149 "Return a regexp matching a PROPERTY line.
6150 Match group 3 will be set to the value if it exists."
6151 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6152 (if literal property (regexp-quote property))
6153 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6154
6155 (defconst org-property-re
6156 (org-re-property ".*?" 'literal)
6157 "Regular expression matching a property line.
6158 There are four matching groups:
6159 1: :PROPKEY: including the leading and trailing colon,
6160 2: PROPKEY without the leading and trailing colon,
6161 3: PROPVAL without leading or trailing spaces,
6162 4: the indentation of the current line,
6163 5: trailing whitespace.")
6164
6165 (defvar org-font-lock-hook nil
6166 "Functions to be called for special font lock stuff.")
6167
6168 (defvar org-font-lock-set-keywords-hook nil
6169 "Functions that can manipulate `org-font-lock-extra-keywords'.
6170 This is called after `org-font-lock-extra-keywords' is defined, but before
6171 it is installed to be used by font lock. This can be useful if something
6172 needs to be inserted at a specific position in the font-lock sequence.")
6173
6174 (defun org-font-lock-hook (limit)
6175 "Run `org-font-lock-hook' within LIMIT."
6176 (run-hook-with-args 'org-font-lock-hook limit))
6177
6178 (defun org-set-font-lock-defaults ()
6179 "Set font lock defaults for the current buffer."
6180 (let* ((em org-fontify-emphasized-text)
6181 (lk org-activate-links)
6182 (org-font-lock-extra-keywords
6183 (list
6184 ;; Call the hook
6185 '(org-font-lock-hook)
6186 ;; Headlines
6187 `(,(if org-fontify-whole-heading-line
6188 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6189 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6190 (1 (org-get-level-face 1))
6191 (2 (org-get-level-face 2))
6192 (3 (org-get-level-face 3)))
6193 ;; Table lines
6194 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6195 (1 'org-table t))
6196 ;; Table internals
6197 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6198 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6199 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6200 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6201 ;; Drawers
6202 (list org-drawer-regexp '(0 'org-special-keyword t))
6203 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6204 ;; Properties
6205 (list org-property-re
6206 '(1 'org-special-keyword t)
6207 '(3 'org-property-value t))
6208 ;; Links
6209 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6210 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6211 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6212 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6213 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6214 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6215 (if (memq 'footnote lk) '(org-activate-footnote-links))
6216 ;; Targets.
6217 (list org-any-target-regexp '(0 'org-target t))
6218 ;; Diary sexps.
6219 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6220 ;; Macro
6221 '("{{{.+}}}" (0 'org-macro t))
6222 '(org-hide-wide-columns (0 nil append))
6223 ;; TODO keyword
6224 (list (format org-heading-keyword-regexp-format
6225 org-todo-regexp)
6226 '(2 (org-get-todo-face 2) t))
6227 ;; DONE
6228 (if org-fontify-done-headline
6229 (list (format org-heading-keyword-regexp-format
6230 (concat
6231 "\\(?:"
6232 (mapconcat 'regexp-quote org-done-keywords "\\|")
6233 "\\)"))
6234 '(2 'org-headline-done t))
6235 nil)
6236 ;; Priorities
6237 '(org-font-lock-add-priority-faces)
6238 ;; Tags
6239 '(org-font-lock-add-tag-faces)
6240 ;; Tags groups
6241 (if (and org-group-tags org-tag-groups-alist)
6242 (list (concat org-outline-regexp-bol ".+\\(:"
6243 (regexp-opt (mapcar 'car org-tag-groups-alist))
6244 ":\\).*$")
6245 '(1 'org-tag-group prepend)))
6246 ;; Special keywords
6247 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6248 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6249 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6250 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6251 ;; Emphasis
6252 (if em
6253 (if (featurep 'xemacs)
6254 '(org-do-emphasis-faces (0 nil append))
6255 '(org-do-emphasis-faces)))
6256 ;; Checkboxes
6257 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6258 1 'org-checkbox prepend)
6259 (if (cdr (assq 'checkbox org-list-automatic-rules))
6260 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6261 (0 (org-get-checkbox-statistics-face) t)))
6262 ;; Description list items
6263 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6264 1 'org-list-dt prepend)
6265 ;; ARCHIVEd headings
6266 (list (concat
6267 org-outline-regexp-bol
6268 "\\(.*:" org-archive-tag ":.*\\)")
6269 '(1 'org-archived prepend))
6270 ;; Specials
6271 '(org-do-latex-and-related)
6272 '(org-fontify-entities)
6273 '(org-raise-scripts)
6274 ;; Code
6275 '(org-activate-code (1 'org-code t))
6276 ;; COMMENT
6277 (list (format org-heading-keyword-regexp-format
6278 (concat "\\("
6279 org-comment-string "\\|" org-quote-string
6280 "\\)"))
6281 '(2 'org-special-keyword t))
6282 ;; Blocks and meta lines
6283 '(org-fontify-meta-lines-and-blocks))))
6284 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6285 (run-hooks 'org-font-lock-set-keywords-hook)
6286 ;; Now set the full font-lock-keywords
6287 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6288 (org-set-local 'font-lock-defaults
6289 '(org-font-lock-keywords t nil nil backward-paragraph))
6290 (kill-local-variable 'font-lock-keywords) nil))
6291
6292 (defun org-toggle-pretty-entities ()
6293 "Toggle the composition display of entities as UTF8 characters."
6294 (interactive)
6295 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6296 (org-restart-font-lock)
6297 (if org-pretty-entities
6298 (message "Entities are now displayed as UTF8 characters")
6299 (save-restriction
6300 (widen)
6301 (org-decompose-region (point-min) (point-max))
6302 (message "Entities are now displayed as plain text"))))
6303
6304 (defvar org-custom-properties-overlays nil
6305 "List of overlays used for custom properties.")
6306 (make-variable-buffer-local 'org-custom-properties-overlays)
6307
6308 (defun org-toggle-custom-properties-visibility ()
6309 "Display or hide properties in `org-custom-properties'."
6310 (interactive)
6311 (if org-custom-properties-overlays
6312 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6313 (setq org-custom-properties-overlays nil))
6314 (unless (not org-custom-properties)
6315 (save-excursion
6316 (save-restriction
6317 (widen)
6318 (goto-char (point-min))
6319 (while (re-search-forward org-property-re nil t)
6320 (mapc (lambda(p)
6321 (when (equal p (substring (match-string 1) 1 -1))
6322 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6323 (overlay-put o 'invisible t)
6324 (overlay-put o 'org-custom-property t)
6325 (push o org-custom-properties-overlays))))
6326 org-custom-properties)))))))
6327
6328 (defun org-fontify-entities (limit)
6329 "Find an entity to fontify."
6330 (let (ee)
6331 (when org-pretty-entities
6332 (catch 'match
6333 (while (re-search-forward
6334 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6335 limit t)
6336 (if (and (not (org-in-indented-comment-line))
6337 (setq ee (org-entity-get (match-string 1)))
6338 (= (length (nth 6 ee)) 1))
6339 (let*
6340 ((end (if (equal (match-string 2) "{}")
6341 (match-end 2)
6342 (match-end 1))))
6343 (add-text-properties
6344 (match-beginning 0) end
6345 (list 'font-lock-fontified t))
6346 (compose-region (match-beginning 0) end
6347 (nth 6 ee) nil)
6348 (backward-char 1)
6349 (throw 'match t))))
6350 nil))))
6351
6352 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6353 "Fontify string S like in Org-mode."
6354 (with-temp-buffer
6355 (insert s)
6356 (let ((org-odd-levels-only odd-levels))
6357 (org-mode)
6358 (org-font-lock-ensure)
6359 (buffer-string))))
6360
6361 (defvar org-m nil)
6362 (defvar org-l nil)
6363 (defvar org-f nil)
6364 (defun org-get-level-face (n)
6365 "Get the right face for match N in font-lock matching of headlines."
6366 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6367 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6368 (if org-cycle-level-faces
6369 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6370 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6371 (cond
6372 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6373 ((eq n 2) org-f)
6374 (t (if org-level-color-stars-only nil org-f))))
6375
6376
6377 (defun org-get-todo-face (kwd)
6378 "Get the right face for a TODO keyword KWD.
6379 If KWD is a number, get the corresponding match group."
6380 (if (numberp kwd) (setq kwd (match-string kwd)))
6381 (or (org-face-from-face-or-color
6382 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6383 (and (member kwd org-done-keywords) 'org-done)
6384 'org-todo))
6385
6386 (defun org-face-from-face-or-color (context inherit face-or-color)
6387 "Create a face list that inherits INHERIT, but sets the foreground color.
6388 When FACE-OR-COLOR is not a string, just return it."
6389 (if (stringp face-or-color)
6390 (list :inherit inherit
6391 (cdr (assoc context org-faces-easy-properties))
6392 face-or-color)
6393 face-or-color))
6394
6395 (defun org-font-lock-add-tag-faces (limit)
6396 "Add the special tag faces."
6397 (when (and org-tag-faces org-tags-special-faces-re)
6398 (while (re-search-forward org-tags-special-faces-re limit t)
6399 (add-text-properties (match-beginning 1) (match-end 1)
6400 (list 'face (org-get-tag-face 1)
6401 'font-lock-fontified t))
6402 (backward-char 1))))
6403
6404 (defun org-font-lock-add-priority-faces (limit)
6405 "Add the special priority faces."
6406 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6407 (when (save-match-data (org-at-heading-p))
6408 (add-text-properties
6409 (match-beginning 0) (match-end 0)
6410 (list 'face (or (org-face-from-face-or-color
6411 'priority 'org-priority
6412 (cdr (assoc (char-after (match-beginning 1))
6413 org-priority-faces)))
6414 'org-priority)
6415 'font-lock-fontified t)))))
6416
6417 (defun org-get-tag-face (kwd)
6418 "Get the right face for a TODO keyword KWD.
6419 If KWD is a number, get the corresponding match group."
6420 (if (numberp kwd) (setq kwd (match-string kwd)))
6421 (or (org-face-from-face-or-color
6422 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6423 'org-tag))
6424
6425 (defun org-unfontify-region (beg end &optional maybe_loudly)
6426 "Remove fontification and activation overlays from links."
6427 (font-lock-default-unfontify-region beg end)
6428 (let* ((buffer-undo-list t)
6429 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6430 (inhibit-modification-hooks t)
6431 deactivate-mark buffer-file-name buffer-file-truename)
6432 (org-decompose-region beg end)
6433 (remove-text-properties beg end
6434 '(mouse-face t keymap t org-linked-text t
6435 invisible t intangible t
6436 org-no-flyspell t org-emphasis t))
6437 (org-remove-font-lock-display-properties beg end)))
6438
6439 (defconst org-script-display '(((raise -0.3) (height 0.7))
6440 ((raise 0.3) (height 0.7))
6441 ((raise -0.5))
6442 ((raise 0.5)))
6443 "Display properties for showing superscripts and subscripts.")
6444
6445 (defun org-remove-font-lock-display-properties (beg end)
6446 "Remove specific display properties that have been added by font lock.
6447 The will remove the raise properties that are used to show superscripts
6448 and subscripts."
6449 (let (next prop)
6450 (while (< beg end)
6451 (setq next (next-single-property-change beg 'display nil end)
6452 prop (get-text-property beg 'display))
6453 (if (member prop org-script-display)
6454 (put-text-property beg next 'display nil))
6455 (setq beg next))))
6456
6457 (defun org-raise-scripts (limit)
6458 "Add raise properties to sub/superscripts."
6459 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6460 (if (re-search-forward
6461 (if (eq org-use-sub-superscripts t)
6462 org-match-substring-regexp
6463 org-match-substring-with-braces-regexp)
6464 limit t)
6465 (let* ((pos (point)) table-p comment-p
6466 (mpos (match-beginning 3))
6467 (emph-p (get-text-property mpos 'org-emphasis))
6468 (link-p (get-text-property mpos 'mouse-face))
6469 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6470 (goto-char (point-at-bol))
6471 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6472 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6473 (goto-char pos)
6474 ;; Handle a_b^c
6475 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6476 (if (or comment-p emph-p link-p keyw-p)
6477 t
6478 (put-text-property (match-beginning 3) (match-end 0)
6479 'display
6480 (if (equal (char-after (match-beginning 2)) ?^)
6481 (nth (if table-p 3 1) org-script-display)
6482 (nth (if table-p 2 0) org-script-display)))
6483 (add-text-properties (match-beginning 2) (match-end 2)
6484 (list 'invisible t
6485 'org-dwidth t 'org-dwidth-n 1))
6486 (if (and (eq (char-after (match-beginning 3)) ?{)
6487 (eq (char-before (match-end 3)) ?}))
6488 (progn
6489 (add-text-properties
6490 (match-beginning 3) (1+ (match-beginning 3))
6491 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6492 (add-text-properties
6493 (1- (match-end 3)) (match-end 3)
6494 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6495 t)))))
6496
6497 ;;;; Visibility cycling, including org-goto and indirect buffer
6498
6499 ;;; Cycling
6500
6501 (defvar org-cycle-global-status nil)
6502 (make-variable-buffer-local 'org-cycle-global-status)
6503 (put 'org-cycle-global-status 'org-state t)
6504 (defvar org-cycle-subtree-status nil)
6505 (make-variable-buffer-local 'org-cycle-subtree-status)
6506 (put 'org-cycle-subtree-status 'org-state t)
6507
6508 (defvar org-inlinetask-min-level)
6509
6510 (defun org-unlogged-message (&rest args)
6511 "Display a message, but avoid logging it in the *Messages* buffer."
6512 (let ((message-log-max nil))
6513 (apply 'message args)))
6514
6515 ;;;###autoload
6516 (defun org-cycle (&optional arg)
6517 "TAB-action and visibility cycling for Org-mode.
6518
6519 This is the command invoked in Org-mode by the TAB key. Its main purpose
6520 is outline visibility cycling, but it also invokes other actions
6521 in special contexts.
6522
6523 - When this function is called with a prefix argument, rotate the entire
6524 buffer through 3 states (global cycling)
6525 1. OVERVIEW: Show only top-level headlines.
6526 2. CONTENTS: Show all headlines of all levels, but no body text.
6527 3. SHOW ALL: Show everything.
6528 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6529 determined by the variable `org-startup-folded', and by any VISIBILITY
6530 properties in the buffer.
6531 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6532 including any drawers.
6533
6534 - When inside a table, re-align the table and move to the next field.
6535
6536 - When point is at the beginning of a headline, rotate the subtree started
6537 by this line through 3 different states (local cycling)
6538 1. FOLDED: Only the main headline is shown.
6539 2. CHILDREN: The main headline and the direct children are shown.
6540 From this state, you can move to one of the children
6541 and zoom in further.
6542 3. SUBTREE: Show the entire subtree, including body text.
6543 If there is no subtree, switch directly from CHILDREN to FOLDED.
6544
6545 - When point is at the beginning of an empty headline and the variable
6546 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6547 of the headline by demoting and promoting it to likely levels. This
6548 speeds up creation document structure by pressing TAB once or several
6549 times right after creating a new headline.
6550
6551 - When there is a numeric prefix, go up to a heading with level ARG, do
6552 a `show-subtree' and return to the previous cursor position. If ARG
6553 is negative, go up that many levels.
6554
6555 - When point is not at the beginning of a headline, execute the global
6556 binding for TAB, which is re-indenting the line. See the option
6557 `org-cycle-emulate-tab' for details.
6558
6559 - Special case: if point is at the beginning of the buffer and there is
6560 no headline in line 1, this function will act as if called with prefix arg
6561 (C-u TAB, same as S-TAB) also when called without prefix arg.
6562 But only if also the variable `org-cycle-global-at-bob' is t."
6563 (interactive "P")
6564 (org-load-modules-maybe)
6565 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6566 (and org-cycle-level-after-item/entry-creation
6567 (or (org-cycle-level)
6568 (org-cycle-item-indentation))))
6569 (let* ((limit-level
6570 (or org-cycle-max-level
6571 (and (boundp 'org-inlinetask-min-level)
6572 org-inlinetask-min-level
6573 (1- org-inlinetask-min-level))))
6574 (nstars (and limit-level
6575 (if org-odd-levels-only
6576 (and limit-level (1- (* limit-level 2)))
6577 limit-level)))
6578 (org-outline-regexp
6579 (if (not (derived-mode-p 'org-mode))
6580 outline-regexp
6581 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6582 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6583 (not (looking-at org-outline-regexp))))
6584 (org-cycle-hook
6585 (if bob-special
6586 (delq 'org-optimize-window-after-visibility-change
6587 (copy-sequence org-cycle-hook))
6588 org-cycle-hook))
6589 (pos (point)))
6590
6591 (if (or bob-special (equal arg '(4)))
6592 ;; special case: use global cycling
6593 (setq arg t))
6594
6595 (cond
6596
6597 ((equal arg '(16))
6598 (setq last-command 'dummy)
6599 (org-set-startup-visibility)
6600 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6601
6602 ((equal arg '(64))
6603 (show-all)
6604 (org-unlogged-message "Entire buffer visible, including drawers"))
6605
6606 ;; Try cdlatex TAB completion
6607 ((org-try-cdlatex-tab))
6608
6609 ;; Table: enter it or move to the next field.
6610 ((org-at-table-p 'any)
6611 (if (org-at-table.el-p)
6612 (message "Use C-c ' to edit table.el tables")
6613 (if arg (org-table-edit-field t)
6614 (org-table-justify-field-maybe)
6615 (call-interactively 'org-table-next-field))))
6616
6617 ((run-hook-with-args-until-success
6618 'org-tab-after-check-for-table-hook))
6619
6620 ;; Global cycling: delegate to `org-cycle-internal-global'.
6621 ((eq arg t) (org-cycle-internal-global))
6622
6623 ;; Drawers: delegate to `org-flag-drawer'.
6624 ((and org-drawers org-drawer-regexp
6625 (save-excursion
6626 (beginning-of-line 1)
6627 (looking-at org-drawer-regexp)))
6628 (org-flag-drawer ; toggle block visibility
6629 (not (get-char-property (match-end 0) 'invisible))))
6630
6631 ;; Show-subtree, ARG levels up from here.
6632 ((integerp arg)
6633 (save-excursion
6634 (org-back-to-heading)
6635 (outline-up-heading (if (< arg 0) (- arg)
6636 (- (funcall outline-level) arg)))
6637 (org-show-subtree)))
6638
6639 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6640 ((and (featurep 'org-inlinetask)
6641 (org-inlinetask-at-task-p)
6642 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6643 (org-inlinetask-toggle-visibility))
6644
6645 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6646 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6647 (save-excursion (beginning-of-line 1)
6648 (looking-at org-outline-regexp)))
6649 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6650 (org-cycle-internal-local))
6651
6652 ;; From there: TAB emulation and template completion.
6653 (buffer-read-only (org-back-to-heading))
6654
6655 ((run-hook-with-args-until-success
6656 'org-tab-after-check-for-cycling-hook))
6657
6658 ((org-try-structure-completion))
6659
6660 ((run-hook-with-args-until-success
6661 'org-tab-before-tab-emulation-hook))
6662
6663 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6664 (or (not (bolp))
6665 (not (looking-at org-outline-regexp))))
6666 (call-interactively (global-key-binding "\t")))
6667
6668 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6669 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6670 (or (and (eq org-cycle-emulate-tab 'white)
6671 (= (match-end 0) (point-at-eol)))
6672 (and (eq org-cycle-emulate-tab 'whitestart)
6673 (>= (match-end 0) pos))))
6674 t
6675 (eq org-cycle-emulate-tab t))
6676 (call-interactively (global-key-binding "\t")))
6677
6678 (t (save-excursion
6679 (org-back-to-heading)
6680 (org-cycle)))))))
6681
6682 (defun org-cycle-internal-global ()
6683 "Do the global cycling action."
6684 ;; Hack to avoid display of messages for .org attachments in Gnus
6685 (let ((ga (string-match "\\*fontification" (buffer-name))))
6686 (cond
6687 ((and (eq last-command this-command)
6688 (eq org-cycle-global-status 'overview))
6689 ;; We just created the overview - now do table of contents
6690 ;; This can be slow in very large buffers, so indicate action
6691 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6692 (unless ga (org-unlogged-message "CONTENTS..."))
6693 (org-content)
6694 (unless ga (org-unlogged-message "CONTENTS...done"))
6695 (setq org-cycle-global-status 'contents)
6696 (run-hook-with-args 'org-cycle-hook 'contents))
6697
6698 ((and (eq last-command this-command)
6699 (eq org-cycle-global-status 'contents))
6700 ;; We just showed the table of contents - now show everything
6701 (run-hook-with-args 'org-pre-cycle-hook 'all)
6702 (show-all)
6703 (unless ga (org-unlogged-message "SHOW ALL"))
6704 (setq org-cycle-global-status 'all)
6705 (run-hook-with-args 'org-cycle-hook 'all))
6706
6707 (t
6708 ;; Default action: go to overview
6709 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6710 (org-overview)
6711 (unless ga (org-unlogged-message "OVERVIEW"))
6712 (setq org-cycle-global-status 'overview)
6713 (run-hook-with-args 'org-cycle-hook 'overview)))))
6714
6715 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6716
6717 (defun org-cycle-internal-local ()
6718 "Do the local cycling action."
6719 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6720 ;; First, determine end of headline (EOH), end of subtree or item
6721 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6722 (save-excursion
6723 (if (org-at-item-p)
6724 (progn
6725 (beginning-of-line)
6726 (setq struct (org-list-struct))
6727 (setq eoh (point-at-eol))
6728 (setq eos (org-list-get-item-end-before-blank (point) struct))
6729 (setq has-children (org-list-has-child-p (point) struct)))
6730 (org-back-to-heading)
6731 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6732 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6733 (setq has-children
6734 (or (save-excursion
6735 (let ((level (funcall outline-level)))
6736 (outline-next-heading)
6737 (and (org-at-heading-p t)
6738 (> (funcall outline-level) level))))
6739 (save-excursion
6740 (org-list-search-forward (org-item-beginning-re) eos t)))))
6741 ;; Determine end invisible part of buffer (EOL)
6742 (beginning-of-line 2)
6743 ;; XEmacs doesn't have `next-single-char-property-change'
6744 (if (featurep 'xemacs)
6745 (while (and (not (eobp)) ;; this is like `next-line'
6746 (get-char-property (1- (point)) 'invisible))
6747 (beginning-of-line 2))
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (goto-char (next-single-char-property-change (point) 'invisible))
6751 (and (eolp) (beginning-of-line 2))))
6752 (setq eol (point)))
6753 ;; Find out what to do next and set `this-command'
6754 (cond
6755 ((= eos eoh)
6756 ;; Nothing is hidden behind this heading
6757 (unless (org-before-first-heading-p)
6758 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6759 (org-unlogged-message "EMPTY ENTRY")
6760 (setq org-cycle-subtree-status nil)
6761 (save-excursion
6762 (goto-char eos)
6763 (outline-next-heading)
6764 (if (outline-invisible-p) (org-flag-heading nil))))
6765 ((and (or (>= eol eos)
6766 (not (string-match "\\S-" (buffer-substring eol eos))))
6767 (or has-children
6768 (not (setq children-skipped
6769 org-cycle-skip-children-state-if-no-children))))
6770 ;; Entire subtree is hidden in one line: children view
6771 (unless (org-before-first-heading-p)
6772 (run-hook-with-args 'org-pre-cycle-hook 'children))
6773 (if (org-at-item-p)
6774 (org-list-set-item-visibility (point-at-bol) struct 'children)
6775 (org-show-entry)
6776 (org-with-limited-levels (show-children))
6777 ;; FIXME: This slows down the func way too much.
6778 ;; How keep drawers hidden in subtree anyway?
6779 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6780 ;; (org-cycle-hide-drawers 'subtree))
6781
6782 ;; Fold every list in subtree to top-level items.
6783 (when (eq org-cycle-include-plain-lists 'integrate)
6784 (save-excursion
6785 (org-back-to-heading)
6786 (while (org-list-search-forward (org-item-beginning-re) eos t)
6787 (beginning-of-line 1)
6788 (let* ((struct (org-list-struct))
6789 (prevs (org-list-prevs-alist struct))
6790 (end (org-list-get-bottom-point struct)))
6791 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6792 (org-list-get-all-items (point) struct prevs))
6793 (goto-char (if (< end eos) end eos)))))))
6794 (org-unlogged-message "CHILDREN")
6795 (save-excursion
6796 (goto-char eos)
6797 (outline-next-heading)
6798 (if (outline-invisible-p) (org-flag-heading nil)))
6799 (setq org-cycle-subtree-status 'children)
6800 (unless (org-before-first-heading-p)
6801 (run-hook-with-args 'org-cycle-hook 'children)))
6802 ((or children-skipped
6803 (and (eq last-command this-command)
6804 (eq org-cycle-subtree-status 'children)))
6805 ;; We just showed the children, or no children are there,
6806 ;; now show everything.
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6809 (outline-flag-region eoh eos nil)
6810 (org-unlogged-message
6811 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6812 (setq org-cycle-subtree-status 'subtree)
6813 (unless (org-before-first-heading-p)
6814 (run-hook-with-args 'org-cycle-hook 'subtree)))
6815 (t
6816 ;; Default action: hide the subtree.
6817 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6818 (outline-flag-region eoh eos t)
6819 (org-unlogged-message "FOLDED")
6820 (setq org-cycle-subtree-status 'folded)
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-cycle-hook 'folded))))))
6823
6824 ;;;###autoload
6825 (defun org-global-cycle (&optional arg)
6826 "Cycle the global visibility. For details see `org-cycle'.
6827 With \\[universal-argument] prefix arg, switch to startup visibility.
6828 With a numeric prefix, show all headlines up to that level."
6829 (interactive "P")
6830 (let ((org-cycle-include-plain-lists
6831 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6832 (cond
6833 ((integerp arg)
6834 (show-all)
6835 (hide-sublevels arg)
6836 (setq org-cycle-global-status 'contents))
6837 ((equal arg '(4))
6838 (org-set-startup-visibility)
6839 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6840 (t
6841 (org-cycle '(4))))))
6842
6843 (defun org-set-startup-visibility ()
6844 "Set the visibility required by startup options and properties."
6845 (cond
6846 ((eq org-startup-folded t)
6847 (org-overview))
6848 ((eq org-startup-folded 'content)
6849 (org-content))
6850 ((or (eq org-startup-folded 'showeverything)
6851 (eq org-startup-folded nil))
6852 (show-all)))
6853 (unless (eq org-startup-folded 'showeverything)
6854 (if org-hide-block-startup (org-hide-block-all))
6855 (org-set-visibility-according-to-property 'no-cleanup)
6856 (org-cycle-hide-archived-subtrees 'all)
6857 (org-cycle-hide-drawers 'all)
6858 (org-cycle-show-empty-lines t)))
6859
6860 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6861 "Switch subtree visibilities according to :VISIBILITY: property."
6862 (interactive)
6863 (let (org-show-entry-below state)
6864 (save-excursion
6865 (goto-char (point-min))
6866 (while (re-search-forward
6867 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6868 nil t)
6869 (setq state (match-string 1))
6870 (save-excursion
6871 (org-back-to-heading t)
6872 (hide-subtree)
6873 (org-reveal)
6874 (cond
6875 ((equal state '("fold" "folded"))
6876 (hide-subtree))
6877 ((equal state "children")
6878 (org-show-hidden-entry)
6879 (show-children))
6880 ((equal state "content")
6881 (save-excursion
6882 (save-restriction
6883 (org-narrow-to-subtree)
6884 (org-content))))
6885 ((member state '("all" "showall"))
6886 (show-subtree)))))
6887 (unless no-cleanup
6888 (org-cycle-hide-archived-subtrees 'all)
6889 (org-cycle-hide-drawers 'all)
6890 (org-cycle-show-empty-lines 'all)))))
6891
6892 ;; This function uses outline-regexp instead of the more fundamental
6893 ;; org-outline-regexp so that org-cycle-global works outside of Org
6894 ;; buffers, where outline-regexp is needed.
6895 (defun org-overview ()
6896 "Switch to overview mode, showing only top-level headlines.
6897 Really, this shows all headlines with level equal or greater than the level
6898 of the first headline in the buffer. This is important, because if the
6899 first headline is not level one, then (hide-sublevels 1) gives confusing
6900 results."
6901 (interactive)
6902 (let ((pos (point))
6903 (level (save-excursion
6904 (goto-char (point-min))
6905 (if (re-search-forward (concat "^" outline-regexp) nil t)
6906 (progn
6907 (goto-char (match-beginning 0))
6908 (funcall outline-level))))))
6909 (and level (hide-sublevels level))
6910 (recenter '(4))
6911 (goto-char pos)))
6912
6913 (defun org-content (&optional arg)
6914 "Show all headlines in the buffer, like a table of contents.
6915 With numerical argument N, show content up to level N."
6916 (interactive "P")
6917 (org-overview)
6918 (save-excursion
6919 ;; Visit all headings and show their offspring
6920 (and (integerp arg) (org-overview))
6921 (goto-char (point-max))
6922 (catch 'exit
6923 (while (and (progn (condition-case nil
6924 (outline-previous-visible-heading 1)
6925 (error (goto-char (point-min))))
6926 t)
6927 (looking-at org-outline-regexp))
6928 (if (integerp arg)
6929 (show-children (1- arg))
6930 (show-branches))
6931 (if (bobp) (throw 'exit nil))))))
6932
6933 (defun org-optimize-window-after-visibility-change (state)
6934 "Adjust the window after a change in outline visibility.
6935 This function is the default value of the hook `org-cycle-hook'."
6936 (when (get-buffer-window (current-buffer))
6937 (cond
6938 ((eq state 'content) nil)
6939 ((eq state 'all) nil)
6940 ((eq state 'folded) nil)
6941 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6942 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6943
6944 (defun org-remove-empty-overlays-at (pos)
6945 "Remove outline overlays that do not contain non-white stuff."
6946 (mapc
6947 (lambda (o)
6948 (and (eq 'outline (overlay-get o 'invisible))
6949 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6950 (overlay-end o))))
6951 (delete-overlay o)))
6952 (overlays-at pos)))
6953
6954 (defun org-clean-visibility-after-subtree-move ()
6955 "Fix visibility issues after moving a subtree."
6956 ;; First, find a reasonable region to look at:
6957 ;; Start two siblings above, end three below
6958 (let* ((beg (save-excursion
6959 (and (org-get-last-sibling)
6960 (org-get-last-sibling))
6961 (point)))
6962 (end (save-excursion
6963 (and (org-get-next-sibling)
6964 (org-get-next-sibling)
6965 (org-get-next-sibling))
6966 (if (org-at-heading-p)
6967 (point-at-eol)
6968 (point))))
6969 (level (looking-at "\\*+"))
6970 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6971 (save-excursion
6972 (save-restriction
6973 (narrow-to-region beg end)
6974 (when re
6975 ;; Properly fold already folded siblings
6976 (goto-char (point-min))
6977 (while (re-search-forward re nil t)
6978 (if (and (not (outline-invisible-p))
6979 (save-excursion
6980 (goto-char (point-at-eol)) (outline-invisible-p)))
6981 (hide-entry))))
6982 (org-cycle-show-empty-lines 'overview)
6983 (org-cycle-hide-drawers 'overview)))))
6984
6985 (defun org-cycle-show-empty-lines (state)
6986 "Show empty lines above all visible headlines.
6987 The region to be covered depends on STATE when called through
6988 `org-cycle-hook'. Lisp program can use t for STATE to get the
6989 entire buffer covered. Note that an empty line is only shown if there
6990 are at least `org-cycle-separator-lines' empty lines before the headline."
6991 (when (not (= org-cycle-separator-lines 0))
6992 (save-excursion
6993 (let* ((n (abs org-cycle-separator-lines))
6994 (re (cond
6995 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6996 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6997 (t (let ((ns (number-to-string (- n 2))))
6998 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6999 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7000 beg end b e)
7001 (cond
7002 ((memq state '(overview contents t))
7003 (setq beg (point-min) end (point-max)))
7004 ((memq state '(children folded))
7005 (setq beg (point) end (progn (org-end-of-subtree t t)
7006 (beginning-of-line 2)
7007 (point)))))
7008 (when beg
7009 (goto-char beg)
7010 (while (re-search-forward re end t)
7011 (unless (get-char-property (match-end 1) 'invisible)
7012 (setq e (match-end 1))
7013 (if (< org-cycle-separator-lines 0)
7014 (setq b (save-excursion
7015 (goto-char (match-beginning 0))
7016 (org-back-over-empty-lines)
7017 (if (save-excursion
7018 (goto-char (max (point-min) (1- (point))))
7019 (org-at-heading-p))
7020 (1- (point))
7021 (point))))
7022 (setq b (match-beginning 1)))
7023 (outline-flag-region b e nil)))))))
7024 ;; Never hide empty lines at the end of the file.
7025 (save-excursion
7026 (goto-char (point-max))
7027 (outline-previous-heading)
7028 (outline-end-of-heading)
7029 (if (and (looking-at "[ \t\n]+")
7030 (= (match-end 0) (point-max)))
7031 (outline-flag-region (point) (match-end 0) nil))))
7032
7033 (defun org-show-empty-lines-in-parent ()
7034 "Move to the parent and re-show empty lines before visible headlines."
7035 (save-excursion
7036 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7037 (org-cycle-show-empty-lines context))))
7038
7039 (defun org-files-list ()
7040 "Return `org-agenda-files' list, plus all open org-mode files.
7041 This is useful for operations that need to scan all of a user's
7042 open and agenda-wise Org files."
7043 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7044 (dolist (buf (buffer-list))
7045 (with-current-buffer buf
7046 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7047 (let ((file (expand-file-name (buffer-file-name))))
7048 (unless (member file files)
7049 (push file files))))))
7050 files))
7051
7052 (defsubst org-entry-beginning-position ()
7053 "Return the beginning position of the current entry."
7054 (save-excursion (outline-back-to-heading t) (point)))
7055
7056 (defsubst org-entry-end-position ()
7057 "Return the end position of the current entry."
7058 (save-excursion (outline-next-heading) (point)))
7059
7060 (defun org-cycle-hide-drawers (state)
7061 "Re-hide all drawers after a visibility state change."
7062 (when (and (derived-mode-p 'org-mode)
7063 (not (memq state '(overview folded contents))))
7064 (save-excursion
7065 (let* ((globalp (memq state '(contents all)))
7066 (beg (if globalp (point-min) (point)))
7067 (end (if globalp (point-max)
7068 (if (eq state 'children)
7069 (save-excursion (outline-next-heading) (point))
7070 (org-end-of-subtree t)))))
7071 (goto-char beg)
7072 (while (re-search-forward org-drawer-regexp end t)
7073 (org-flag-drawer t))))))
7074
7075 (defun org-cycle-hide-inline-tasks (state)
7076 "Re-hide inline tasks when switching to 'contents or 'children
7077 visibility state."
7078 (case state
7079 (contents
7080 (when (org-bound-and-true-p org-inlinetask-min-level)
7081 (hide-sublevels (1- org-inlinetask-min-level))))
7082 (children
7083 (when (featurep 'org-inlinetask)
7084 (save-excursion
7085 (while (and (outline-next-heading)
7086 (org-inlinetask-at-task-p))
7087 (org-inlinetask-toggle-visibility)
7088 (org-inlinetask-goto-end)))))))
7089
7090 (defun org-flag-drawer (flag)
7091 "When FLAG is non-nil, hide the drawer we are within.
7092 Otherwise make it visible."
7093 (save-excursion
7094 (beginning-of-line 1)
7095 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7096 (let ((b (match-end 0)))
7097 (if (re-search-forward
7098 "^[ \t]*:END:"
7099 (save-excursion (outline-next-heading) (point)) t)
7100 (outline-flag-region b (point-at-eol) flag)
7101 (user-error ":END: line missing at position %s" b))))))
7102
7103 (defun org-subtree-end-visible-p ()
7104 "Is the end of the current subtree visible?"
7105 (pos-visible-in-window-p
7106 (save-excursion (org-end-of-subtree t) (point))))
7107
7108 (defun org-first-headline-recenter (&optional N)
7109 "Move cursor to the first headline and recenter the headline.
7110 Optional argument N means put the headline into the Nth line of the window."
7111 (goto-char (point-min))
7112 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7113 (beginning-of-line)
7114 (recenter (prefix-numeric-value N))))
7115
7116 ;;; Saving and restoring visibility
7117
7118 (defun org-outline-overlay-data (&optional use-markers)
7119 "Return a list of the locations of all outline overlays.
7120 These are overlays with the `invisible' property value `outline'.
7121 The return value is a list of cons cells, with start and stop
7122 positions for each overlay.
7123 If USE-MARKERS is set, return the positions as markers."
7124 (let (beg end)
7125 (save-excursion
7126 (save-restriction
7127 (widen)
7128 (delq nil
7129 (mapcar (lambda (o)
7130 (when (eq (overlay-get o 'invisible) 'outline)
7131 (setq beg (overlay-start o)
7132 end (overlay-end o))
7133 (and beg end (> end beg)
7134 (if use-markers
7135 (cons (move-marker (make-marker) beg)
7136 (move-marker (make-marker) end))
7137 (cons beg end)))))
7138 (overlays-in (point-min) (point-max))))))))
7139
7140 (defun org-set-outline-overlay-data (data)
7141 "Create visibility overlays for all positions in DATA.
7142 DATA should have been made by `org-outline-overlay-data'."
7143 (let (o)
7144 (save-excursion
7145 (save-restriction
7146 (widen)
7147 (show-all)
7148 (mapc (lambda (c)
7149 (outline-flag-region (car c) (cdr c) t))
7150 data)))))
7151
7152 ;;; Folding of blocks
7153
7154 (defvar org-hide-block-overlays nil
7155 "Overlays hiding blocks.")
7156 (make-variable-buffer-local 'org-hide-block-overlays)
7157
7158 (defun org-block-map (function &optional start end)
7159 "Call FUNCTION at the head of all source blocks in the current buffer.
7160 Optional arguments START and END can be used to limit the range."
7161 (let ((start (or start (point-min)))
7162 (end (or end (point-max))))
7163 (save-excursion
7164 (goto-char start)
7165 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7166 (save-excursion
7167 (save-match-data
7168 (goto-char (match-beginning 0))
7169 (funcall function)))))))
7170
7171 (defun org-hide-block-toggle-all ()
7172 "Toggle the visibility of all blocks in the current buffer."
7173 (org-block-map #'org-hide-block-toggle))
7174
7175 (defun org-hide-block-all ()
7176 "Fold all blocks in the current buffer."
7177 (interactive)
7178 (org-show-block-all)
7179 (org-block-map #'org-hide-block-toggle-maybe))
7180
7181 (defun org-show-block-all ()
7182 "Unfold all blocks in the current buffer."
7183 (interactive)
7184 (mapc 'delete-overlay org-hide-block-overlays)
7185 (setq org-hide-block-overlays nil))
7186
7187 (defun org-hide-block-toggle-maybe ()
7188 "Toggle visibility of block at point."
7189 (interactive)
7190 (let ((case-fold-search t))
7191 (if (save-excursion
7192 (beginning-of-line 1)
7193 (looking-at org-block-regexp))
7194 (progn (org-hide-block-toggle)
7195 t) ;; to signal that we took action
7196 nil))) ;; to signal that we did not
7197
7198 (defun org-hide-block-toggle (&optional force)
7199 "Toggle the visibility of the current block."
7200 (interactive)
7201 (save-excursion
7202 (beginning-of-line)
7203 (if (re-search-forward org-block-regexp nil t)
7204 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7205 (end (match-end 0)) ;; end of entire body
7206 ov)
7207 (if (memq t (mapcar (lambda (overlay)
7208 (eq (overlay-get overlay 'invisible)
7209 'org-hide-block))
7210 (overlays-at start)))
7211 (if (or (not force) (eq force 'off))
7212 (mapc (lambda (ov)
7213 (when (member ov org-hide-block-overlays)
7214 (setq org-hide-block-overlays
7215 (delq ov org-hide-block-overlays)))
7216 (when (eq (overlay-get ov 'invisible)
7217 'org-hide-block)
7218 (delete-overlay ov)))
7219 (overlays-at start)))
7220 (setq ov (make-overlay start end))
7221 (overlay-put ov 'invisible 'org-hide-block)
7222 ;; make the block accessible to isearch
7223 (overlay-put
7224 ov 'isearch-open-invisible
7225 (lambda (ov)
7226 (when (member ov org-hide-block-overlays)
7227 (setq org-hide-block-overlays
7228 (delq ov org-hide-block-overlays)))
7229 (when (eq (overlay-get ov 'invisible)
7230 'org-hide-block)
7231 (delete-overlay ov))))
7232 (push ov org-hide-block-overlays)))
7233 (user-error "Not looking at a source block"))))
7234
7235 ;; org-tab-after-check-for-cycling-hook
7236 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7237 ;; Remove overlays when changing major mode
7238 (add-hook 'org-mode-hook
7239 (lambda () (org-add-hook 'change-major-mode-hook
7240 'org-show-block-all 'append 'local)))
7241
7242 ;;; Org-goto
7243
7244 (defvar org-goto-window-configuration nil)
7245 (defvar org-goto-marker nil)
7246 (defvar org-goto-map)
7247 (defun org-goto-map ()
7248 "Set the keymap `org-goto'."
7249 (setq org-goto-map
7250 (let ((map (make-sparse-keymap)))
7251 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7252 mouse-drag-region universal-argument org-occur))
7253 cmd)
7254 (while (setq cmd (pop cmds))
7255 (substitute-key-definition cmd cmd map global-map)))
7256 (suppress-keymap map)
7257 (org-defkey map "\C-m" 'org-goto-ret)
7258 (org-defkey map [(return)] 'org-goto-ret)
7259 (org-defkey map [(left)] 'org-goto-left)
7260 (org-defkey map [(right)] 'org-goto-right)
7261 (org-defkey map [(control ?g)] 'org-goto-quit)
7262 (org-defkey map "\C-i" 'org-cycle)
7263 (org-defkey map [(tab)] 'org-cycle)
7264 (org-defkey map [(down)] 'outline-next-visible-heading)
7265 (org-defkey map [(up)] 'outline-previous-visible-heading)
7266 (if org-goto-auto-isearch
7267 (if (fboundp 'define-key-after)
7268 (define-key-after map [t] 'org-goto-local-auto-isearch)
7269 nil)
7270 (org-defkey map "q" 'org-goto-quit)
7271 (org-defkey map "n" 'outline-next-visible-heading)
7272 (org-defkey map "p" 'outline-previous-visible-heading)
7273 (org-defkey map "f" 'outline-forward-same-level)
7274 (org-defkey map "b" 'outline-backward-same-level)
7275 (org-defkey map "u" 'outline-up-heading))
7276 (org-defkey map "/" 'org-occur)
7277 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7278 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7279 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7280 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7281 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7282 map)))
7283
7284 (defconst org-goto-help
7285 "Browse buffer copy, to find location or copy text.%s
7286 RET=jump to location C-g=quit and return to previous location
7287 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7288
7289 (defvar org-goto-start-pos) ; dynamically scoped parameter
7290
7291 (defun org-goto (&optional alternative-interface)
7292 "Look up a different location in the current file, keeping current visibility.
7293
7294 When you want look-up or go to a different location in a
7295 document, the fastest way is often to fold the entire buffer and
7296 then dive into the tree. This method has the disadvantage, that
7297 the previous location will be folded, which may not be what you
7298 want.
7299
7300 This command works around this by showing a copy of the current
7301 buffer in an indirect buffer, in overview mode. You can dive
7302 into the tree in that copy, use org-occur and incremental search
7303 to find a location. When pressing RET or `Q', the command
7304 returns to the original buffer in which the visibility is still
7305 unchanged. After RET it will also jump to the location selected
7306 in the indirect buffer and expose the headline hierarchy above.
7307
7308 With a prefix argument, use the alternative interface: e.g. if
7309 `org-goto-interface' is 'outline use 'outline-path-completion."
7310 (interactive "P")
7311 (org-goto-map)
7312 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7313 (org-refile-use-outline-path t)
7314 (org-refile-target-verify-function nil)
7315 (interface
7316 (if (not alternative-interface)
7317 org-goto-interface
7318 (if (eq org-goto-interface 'outline)
7319 'outline-path-completion
7320 'outline)))
7321 (org-goto-start-pos (point))
7322 (selected-point
7323 (if (eq interface 'outline)
7324 (car (org-get-location (current-buffer) org-goto-help))
7325 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7326 (org-refile-check-position pa)
7327 (nth 3 pa)))))
7328 (if selected-point
7329 (progn
7330 (org-mark-ring-push org-goto-start-pos)
7331 (goto-char selected-point)
7332 (if (or (outline-invisible-p) (org-invisible-p2))
7333 (org-show-context 'org-goto)))
7334 (message "Quit"))))
7335
7336 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7337 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7338 (defvar org-goto-local-auto-isearch-map) ; defined below
7339
7340 (defun org-get-location (buf help)
7341 "Let the user select a location in the Org-mode buffer BUF.
7342 This function uses a recursive edit. It returns the selected position
7343 or nil."
7344 (org-no-popups
7345 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7346 (isearch-hide-immediately nil)
7347 (isearch-search-fun-function
7348 (lambda () 'org-goto-local-search-headings))
7349 (org-goto-selected-point org-goto-exit-command))
7350 (save-excursion
7351 (save-window-excursion
7352 (delete-other-windows)
7353 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7354 (org-pop-to-buffer-same-window
7355 (condition-case nil
7356 (make-indirect-buffer (current-buffer) "*org-goto*")
7357 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7358 (with-output-to-temp-buffer "*Org Help*"
7359 (princ (format help (if org-goto-auto-isearch
7360 " Just type for auto-isearch."
7361 " n/p/f/b/u to navigate, q to quit."))))
7362 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7363 (setq buffer-read-only nil)
7364 (let ((org-startup-truncated t)
7365 (org-startup-folded nil)
7366 (org-startup-align-all-tables nil))
7367 (org-mode)
7368 (org-overview))
7369 (setq buffer-read-only t)
7370 (if (and (boundp 'org-goto-start-pos)
7371 (integer-or-marker-p org-goto-start-pos))
7372 (let ((org-show-hierarchy-above t)
7373 (org-show-siblings t)
7374 (org-show-following-heading t))
7375 (goto-char org-goto-start-pos)
7376 (and (outline-invisible-p) (org-show-context)))
7377 (goto-char (point-min)))
7378 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7379 (message "Select location and press RET")
7380 (use-local-map org-goto-map)
7381 (recursive-edit)))
7382 (kill-buffer "*org-goto*")
7383 (cons org-goto-selected-point org-goto-exit-command))))
7384
7385 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7386 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7387 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7388 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7389
7390 (defun org-goto-local-search-headings (string bound noerror)
7391 "Search and make sure that any matches are in headlines."
7392 (catch 'return
7393 (while (if isearch-forward
7394 (search-forward string bound noerror)
7395 (search-backward string bound noerror))
7396 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7397 (and (member :headline context)
7398 (not (member :tags context))))
7399 (throw 'return (point))))))
7400
7401 (defun org-goto-local-auto-isearch ()
7402 "Start isearch."
7403 (interactive)
7404 (goto-char (point-min))
7405 (let ((keys (this-command-keys)))
7406 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7407 (isearch-mode t)
7408 (isearch-process-search-char (string-to-char keys)))))
7409
7410 (defun org-goto-ret (&optional arg)
7411 "Finish `org-goto' by going to the new location."
7412 (interactive "P")
7413 (setq org-goto-selected-point (point)
7414 org-goto-exit-command 'return)
7415 (throw 'exit nil))
7416
7417 (defun org-goto-left ()
7418 "Finish `org-goto' by going to the new location."
7419 (interactive)
7420 (if (org-at-heading-p)
7421 (progn
7422 (beginning-of-line 1)
7423 (setq org-goto-selected-point (point)
7424 org-goto-exit-command 'left)
7425 (throw 'exit nil))
7426 (user-error "Not on a heading")))
7427
7428 (defun org-goto-right ()
7429 "Finish `org-goto' by going to the new location."
7430 (interactive)
7431 (if (org-at-heading-p)
7432 (progn
7433 (setq org-goto-selected-point (point)
7434 org-goto-exit-command 'right)
7435 (throw 'exit nil))
7436 (user-error "Not on a heading")))
7437
7438 (defun org-goto-quit ()
7439 "Finish `org-goto' without cursor motion."
7440 (interactive)
7441 (setq org-goto-selected-point nil)
7442 (setq org-goto-exit-command 'quit)
7443 (throw 'exit nil))
7444
7445 ;;; Indirect buffer display of subtrees
7446
7447 (defvar org-indirect-dedicated-frame nil
7448 "This is the frame being used for indirect tree display.")
7449 (defvar org-last-indirect-buffer nil)
7450
7451 (defun org-tree-to-indirect-buffer (&optional arg)
7452 "Create indirect buffer and narrow it to current subtree.
7453 With a numerical prefix ARG, go up to this level and then take that tree.
7454 If ARG is negative, go up that many levels.
7455
7456 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7457 indirect buffer previously made with this command, to avoid proliferation of
7458 indirect buffers. However, when you call the command with a \
7459 \\[universal-argument] prefix, or
7460 when `org-indirect-buffer-display' is `new-frame', the last buffer
7461 is kept so that you can work with several indirect buffers at the same time.
7462 If `org-indirect-buffer-display' is `dedicated-frame', the \
7463 \\[universal-argument] prefix also
7464 requests that a new frame be made for the new buffer, so that the dedicated
7465 frame is not changed."
7466 (interactive "P")
7467 (let ((cbuf (current-buffer))
7468 (cwin (selected-window))
7469 (pos (point))
7470 beg end level heading ibuf)
7471 (save-excursion
7472 (org-back-to-heading t)
7473 (when (numberp arg)
7474 (setq level (org-outline-level))
7475 (if (< arg 0) (setq arg (+ level arg)))
7476 (while (> (setq level (org-outline-level)) arg)
7477 (org-up-heading-safe)))
7478 (setq beg (point)
7479 heading (org-get-heading))
7480 (org-end-of-subtree t t)
7481 (if (org-at-heading-p) (backward-char 1))
7482 (setq end (point)))
7483 (if (and (buffer-live-p org-last-indirect-buffer)
7484 (not (eq org-indirect-buffer-display 'new-frame))
7485 (not arg))
7486 (kill-buffer org-last-indirect-buffer))
7487 (setq ibuf (org-get-indirect-buffer cbuf)
7488 org-last-indirect-buffer ibuf)
7489 (cond
7490 ((or (eq org-indirect-buffer-display 'new-frame)
7491 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7492 (select-frame (make-frame))
7493 (delete-other-windows)
7494 (org-pop-to-buffer-same-window ibuf)
7495 (org-set-frame-title heading))
7496 ((eq org-indirect-buffer-display 'dedicated-frame)
7497 (raise-frame
7498 (select-frame (or (and org-indirect-dedicated-frame
7499 (frame-live-p org-indirect-dedicated-frame)
7500 org-indirect-dedicated-frame)
7501 (setq org-indirect-dedicated-frame (make-frame)))))
7502 (delete-other-windows)
7503 (org-pop-to-buffer-same-window ibuf)
7504 (org-set-frame-title (concat "Indirect: " heading)))
7505 ((eq org-indirect-buffer-display 'current-window)
7506 (org-pop-to-buffer-same-window ibuf))
7507 ((eq org-indirect-buffer-display 'other-window)
7508 (pop-to-buffer ibuf))
7509 (t (error "Invalid value")))
7510 (if (featurep 'xemacs)
7511 (save-excursion (org-mode) (turn-on-font-lock)))
7512 (narrow-to-region beg end)
7513 (show-all)
7514 (goto-char pos)
7515 (run-hook-with-args 'org-cycle-hook 'all)
7516 (and (window-live-p cwin) (select-window cwin))))
7517
7518 (defun org-get-indirect-buffer (&optional buffer)
7519 (setq buffer (or buffer (current-buffer)))
7520 (let ((n 1) (base (buffer-name buffer)) bname)
7521 (while (buffer-live-p
7522 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7523 (setq n (1+ n)))
7524 (condition-case nil
7525 (make-indirect-buffer buffer bname 'clone)
7526 (error (make-indirect-buffer buffer bname)))))
7527
7528 (defun org-set-frame-title (title)
7529 "Set the title of the current frame to the string TITLE."
7530 ;; FIXME: how to name a single frame in XEmacs???
7531 (unless (featurep 'xemacs)
7532 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7533
7534 ;;;; Structure editing
7535
7536 ;;; Inserting headlines
7537
7538 (defun org-previous-line-empty-p (&optional next)
7539 "Is the previous line a blank line?
7540 When NEXT is non-nil, check the next line instead."
7541 (save-excursion
7542 (and (not (bobp))
7543 (or (beginning-of-line (if next 2 0)) t)
7544 (save-match-data
7545 (looking-at "[ \t]*$")))))
7546
7547 (defun org-insert-heading (&optional arg invisible-ok)
7548 "Insert a new heading or item with same depth at point.
7549
7550 If point is at the beginning of a heading or a list item, insert
7551 a heading or a list item before it.
7552
7553 If point is at the beginning of a normal line, turn this line
7554 into a heading.
7555
7556 If point is in the middle of a headline or a list item, split the
7557 headline or the item and create a new headline/item with the text
7558 in the current line after point \(see `org-M-RET-may-split-line'
7559 on how to modify this behavior).
7560
7561 With one universal prefix argument: If point is within a list,
7562 insert a heading instead of a list item. Otherwise, set the
7563 value of `org-insert-heading-respect-content' to `t' for the
7564 duration of the command.
7565
7566 With two universal prefix arguments, insert the heading at the
7567 end of the grandparent subtree. For example, if point is within
7568 a 2nd-level heading, then it will insert a 2nd-level heading at
7569 the end of the 1st-level parent heading.
7570
7571 When INVISIBLE-OK is set, stop at invisible headlines when going
7572 back. This is important for non-interactive uses of the
7573 command."
7574 (interactive "P")
7575 (if (org-called-interactively-p 'any) (org-reveal))
7576 (let ((itemp (org-in-item-p))
7577 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7578 (respect-content (or org-insert-heading-respect-content
7579 (equal arg '(4))))
7580 (initial-content "")
7581 (adjust-empty-lines t))
7582
7583 (cond
7584
7585 ((or (= (buffer-size) 0)
7586 (and (not (save-excursion
7587 (and (ignore-errors (org-back-to-heading invisible-ok))
7588 (org-at-heading-p))))
7589 (or arg (not itemp))))
7590 ;; At beginning of buffer or so high up that only a heading
7591 ;; makes sense.
7592 (insert
7593 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7594 (if (org-in-src-block-p) ",* " "* "))
7595 (run-hooks 'org-insert-heading-hook))
7596
7597 ((and itemp (not (equal arg '(4))))
7598 ;; Insert an item
7599 (org-insert-item))
7600
7601 (t
7602 ;; Maybe move at the end of the subtree
7603 (when (equal arg '(16))
7604 (org-up-heading-safe)
7605 (org-end-of-subtree t))
7606 ;; Insert a heading
7607 (save-restriction
7608 (widen)
7609 (let* ((level nil)
7610 (on-heading (org-at-heading-p))
7611 (empty-line-p (if on-heading
7612 (org-previous-line-empty-p)
7613 ;; We will decide later
7614 nil))
7615 ;; Get a level string to fall back on
7616 (fix-level
7617 (save-excursion
7618 (org-back-to-heading t)
7619 (if (org-previous-line-empty-p) (setq empty-line-p t))
7620 (looking-at org-outline-regexp)
7621 (make-string (1- (length (match-string 0))) ?*)))
7622 (stars
7623 (save-excursion
7624 (condition-case nil
7625 (progn
7626 (org-back-to-heading invisible-ok)
7627 (when (and (not on-heading)
7628 (featurep 'org-inlinetask)
7629 (integerp org-inlinetask-min-level)
7630 (>= (length (match-string 0))
7631 org-inlinetask-min-level))
7632 ;; Find a heading level before the inline task
7633 (while (and (setq level (org-up-heading-safe))
7634 (>= level org-inlinetask-min-level)))
7635 (if (org-at-heading-p)
7636 (org-back-to-heading invisible-ok)
7637 (error "This should not happen")))
7638 (unless (and (save-excursion
7639 (save-match-data
7640 (org-backward-heading-same-level
7641 1 invisible-ok))
7642 (= (point) (match-beginning 0)))
7643 (not (org-previous-line-empty-p t)))
7644 (setq empty-line-p (or empty-line-p
7645 (org-previous-line-empty-p))))
7646 (match-string 0))
7647 (error (or fix-level "* ")))))
7648 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7649 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7650 pos hide-previous previous-pos)
7651
7652 ;; If we insert after content, move there and clean up whitespace
7653 (when (and respect-content (not (org-on-heading-p)))
7654 (org-end-of-subtree nil t)
7655 (skip-chars-backward " \r\n")
7656 (and (not (looking-back "^\*+"))
7657 (looking-at "[ \t]+") (replace-match ""))
7658 (unless (eobp) (forward-char 1))
7659 (when (looking-at "^\\*")
7660 (unless (bobp) (backward-char 1))
7661 (insert "\n")))
7662
7663 ;; If we are splitting, grab the text that should be moved to the new headline
7664 (when may-split
7665 (if (org-on-heading-p)
7666 ;; This is a heading, we split intelligently (keeping tags)
7667 (let ((pos (point)))
7668 (goto-char (point-at-bol))
7669 (unless (looking-at org-complex-heading-regexp)
7670 (error "This should not happen"))
7671 (when (and (match-beginning 4)
7672 (> pos (match-beginning 4))
7673 (< pos (match-end 4)))
7674 (setq initial-content (buffer-substring pos (match-end 4)))
7675 (goto-char pos)
7676 (delete-region (point) (match-end 4))
7677 (if (looking-at "[ \t]*$")
7678 (replace-match "")
7679 (insert (make-string (length initial-content) ?\ )))
7680 (setq initial-content (org-trim initial-content)))
7681 (goto-char pos))
7682 ;; a normal line
7683 (unless (bolp)
7684 (setq initial-content (buffer-substring (point) (point-at-eol)))
7685 (delete-region (point) (point-at-eol))
7686 (setq initial-content (org-trim initial-content)))))
7687
7688 ;; If we are at the beginning of the line, insert before it. Else after
7689 (cond
7690 ((and (bolp) (looking-at "[ \t]*$")))
7691 ((and (bolp) (not (looking-at "[ \t]*$")))
7692 (open-line 1))
7693 (t
7694 (goto-char (point-at-eol))
7695 (insert "\n")))
7696
7697 ;; Insert the new heading
7698 (insert stars)
7699 (just-one-space)
7700 (insert initial-content)
7701 (when adjust-empty-lines
7702 (if (or (not blank)
7703 (and blank (not (org-previous-line-empty-p))))
7704 (org-N-empty-lines-before-current (if blank 1 0))))
7705 (run-hooks 'org-insert-heading-hook)))))))
7706
7707 (defun org-N-empty-lines-before-current (N)
7708 "Make the number of empty lines before current exactly N.
7709 So this will delete or add empty lines."
7710 (save-excursion
7711 (goto-char (point-at-bol))
7712 (if (looking-back "\\s-+" nil 'greedy)
7713 (replace-match ""))
7714 (or (bobp) (insert "\n"))
7715 (while (> N 0)
7716 (insert "\n")
7717 (setq N (1- N)))))
7718
7719 (defun org-get-heading (&optional no-tags no-todo)
7720 "Return the heading of the current entry, without the stars.
7721 When NO-TAGS is non-nil, don't include tags.
7722 When NO-TODO is non-nil, don't include TODO keywords."
7723 (save-excursion
7724 (org-back-to-heading t)
7725 (cond
7726 ((and no-tags no-todo)
7727 (looking-at org-complex-heading-regexp)
7728 (match-string 4))
7729 (no-tags
7730 (looking-at (concat org-outline-regexp
7731 "\\(.*?\\)"
7732 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7733 (match-string 1))
7734 (no-todo
7735 (looking-at org-todo-line-regexp)
7736 (match-string 3))
7737 (t (looking-at org-heading-regexp)
7738 (match-string 2)))))
7739
7740 (defvar orgstruct-mode) ; defined below
7741
7742 (defun org-heading-components ()
7743 "Return the components of the current heading.
7744 This is a list with the following elements:
7745 - the level as an integer
7746 - the reduced level, different if `org-odd-levels-only' is set.
7747 - the TODO keyword, or nil
7748 - the priority character, like ?A, or nil if no priority is given
7749 - the headline text itself, or the tags string if no headline text
7750 - the tags string, or nil."
7751 (save-excursion
7752 (org-back-to-heading t)
7753 (if (let (case-fold-search)
7754 (looking-at
7755 (if orgstruct-mode
7756 org-heading-regexp
7757 org-complex-heading-regexp)))
7758 (if orgstruct-mode
7759 (list (length (match-string 1))
7760 (org-reduced-level (length (match-string 1)))
7761 nil
7762 nil
7763 (match-string 2)
7764 nil)
7765 (list (length (match-string 1))
7766 (org-reduced-level (length (match-string 1)))
7767 (org-match-string-no-properties 2)
7768 (and (match-end 3) (aref (match-string 3) 2))
7769 (org-match-string-no-properties 4)
7770 (org-match-string-no-properties 5))))))
7771
7772 (defun org-get-entry ()
7773 "Get the entry text, after heading, entire subtree."
7774 (save-excursion
7775 (org-back-to-heading t)
7776 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7777
7778 (defun org-insert-heading-after-current ()
7779 "Insert a new heading with same level as current, after current subtree."
7780 (interactive)
7781 (org-back-to-heading)
7782 (org-insert-heading)
7783 (org-move-subtree-down)
7784 (end-of-line 1))
7785
7786 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7787 "Insert heading with `org-insert-heading-respect-content' set to t."
7788 (interactive "P")
7789 (let ((org-insert-heading-respect-content t))
7790 (org-insert-heading '(4) invisible-ok)))
7791
7792 (defun org-insert-todo-heading-respect-content (&optional force-state)
7793 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7794 (interactive "P")
7795 (let ((org-insert-heading-respect-content t))
7796 (org-insert-todo-heading force-state '(4))))
7797
7798 (defun org-insert-todo-heading (arg &optional force-heading)
7799 "Insert a new heading with the same level and TODO state as current heading.
7800 If the heading has no TODO state, or if the state is DONE, use the first
7801 state (TODO by default). Also with one prefix arg, force first state. With
7802 two prefix args, force inserting at the end of the parent subtree."
7803 (interactive "P")
7804 (when (or force-heading (not (org-insert-item 'checkbox)))
7805 (org-insert-heading (or (and (equal arg '(16)) '(16))
7806 force-heading))
7807 (save-excursion
7808 (org-back-to-heading)
7809 (outline-previous-heading)
7810 (looking-at org-todo-line-regexp))
7811 (let*
7812 ((new-mark-x
7813 (if (or (equal arg '(4))
7814 (not (match-beginning 2))
7815 (member (match-string 2) org-done-keywords))
7816 (car org-todo-keywords-1)
7817 (match-string 2)))
7818 (new-mark
7819 (or
7820 (run-hook-with-args-until-success
7821 'org-todo-get-default-hook new-mark-x nil)
7822 new-mark-x)))
7823 (beginning-of-line 1)
7824 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7825 (if org-treat-insert-todo-heading-as-state-change
7826 (org-todo new-mark)
7827 (insert new-mark " "))))
7828 (when org-provide-todo-statistics
7829 (org-update-parent-todo-statistics))))
7830
7831 (defun org-insert-subheading (arg)
7832 "Insert a new subheading and demote it.
7833 Works for outline headings and for plain lists alike."
7834 (interactive "P")
7835 (org-insert-heading arg)
7836 (cond
7837 ((org-at-heading-p) (org-do-demote))
7838 ((org-at-item-p) (org-indent-item))))
7839
7840 (defun org-insert-todo-subheading (arg)
7841 "Insert a new subheading with TODO keyword or checkbox and demote it.
7842 Works for outline headings and for plain lists alike."
7843 (interactive "P")
7844 (org-insert-todo-heading arg)
7845 (cond
7846 ((org-at-heading-p) (org-do-demote))
7847 ((org-at-item-p) (org-indent-item))))
7848
7849 ;;; Promotion and Demotion
7850
7851 (defvar org-after-demote-entry-hook nil
7852 "Hook run after an entry has been demoted.
7853 The cursor will be at the beginning of the entry.
7854 When a subtree is being demoted, the hook will be called for each node.")
7855
7856 (defvar org-after-promote-entry-hook nil
7857 "Hook run after an entry has been promoted.
7858 The cursor will be at the beginning of the entry.
7859 When a subtree is being promoted, the hook will be called for each node.")
7860
7861 (defun org-promote-subtree ()
7862 "Promote the entire subtree.
7863 See also `org-promote'."
7864 (interactive)
7865 (save-excursion
7866 (org-with-limited-levels (org-map-tree 'org-promote)))
7867 (org-fix-position-after-promote))
7868
7869 (defun org-demote-subtree ()
7870 "Demote the entire subtree. See `org-demote'.
7871 See also `org-promote'."
7872 (interactive)
7873 (save-excursion
7874 (org-with-limited-levels (org-map-tree 'org-demote)))
7875 (org-fix-position-after-promote))
7876
7877
7878 (defun org-do-promote ()
7879 "Promote the current heading higher up the tree.
7880 If the region is active in `transient-mark-mode', promote all headings
7881 in the region."
7882 (interactive)
7883 (save-excursion
7884 (if (org-region-active-p)
7885 (org-map-region 'org-promote (region-beginning) (region-end))
7886 (org-promote)))
7887 (org-fix-position-after-promote))
7888
7889 (defun org-do-demote ()
7890 "Demote the current heading lower down the tree.
7891 If the region is active in `transient-mark-mode', demote all headings
7892 in the region."
7893 (interactive)
7894 (save-excursion
7895 (if (org-region-active-p)
7896 (org-map-region 'org-demote (region-beginning) (region-end))
7897 (org-demote)))
7898 (org-fix-position-after-promote))
7899
7900 (defun org-fix-position-after-promote ()
7901 "Make sure that after pro/demotion cursor position is right."
7902 (let ((pos (point)))
7903 (when (save-excursion
7904 (beginning-of-line 1)
7905 (looking-at org-todo-line-regexp)
7906 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7907 (cond ((eobp) (insert " "))
7908 ((eolp) (insert " "))
7909 ((equal (char-after) ?\ ) (forward-char 1))))))
7910
7911 (defun org-current-level ()
7912 "Return the level of the current entry, or nil if before the first headline.
7913 The level is the number of stars at the beginning of the headline."
7914 (save-excursion
7915 (org-with-limited-levels
7916 (if (ignore-errors (org-back-to-heading t))
7917 (funcall outline-level)))))
7918
7919 (defun org-get-previous-line-level ()
7920 "Return the outline depth of the last headline before the current line.
7921 Returns 0 for the first headline in the buffer, and nil if before the
7922 first headline."
7923 (and (org-current-level)
7924 (or (and (/= (line-beginning-position) (point-min))
7925 (save-excursion (beginning-of-line 0) (org-current-level)))
7926 0)))
7927
7928 (defun org-reduced-level (l)
7929 "Compute the effective level of a heading.
7930 This takes into account the setting of `org-odd-levels-only'."
7931 (cond
7932 ((zerop l) 0)
7933 (org-odd-levels-only (1+ (floor (/ l 2))))
7934 (t l)))
7935
7936 (defun org-level-increment ()
7937 "Return the number of stars that will be added or removed at a
7938 time to headlines when structure editing, based on the value of
7939 `org-odd-levels-only'."
7940 (if org-odd-levels-only 2 1))
7941
7942 (defun org-get-valid-level (level &optional change)
7943 "Rectify a level change under the influence of `org-odd-levels-only'
7944 LEVEL is a current level, CHANGE is by how much the level should be
7945 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7946 even level numbers will become the next higher odd number."
7947 (if org-odd-levels-only
7948 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7949 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7950 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7951 (max 1 (+ level (or change 0)))))
7952
7953 (if (boundp 'define-obsolete-function-alias)
7954 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7955 (define-obsolete-function-alias 'org-get-legal-level
7956 'org-get-valid-level)
7957 (define-obsolete-function-alias 'org-get-legal-level
7958 'org-get-valid-level "23.1")))
7959
7960 (defun org-promote ()
7961 "Promote the current heading higher up the tree.
7962 If the region is active in `transient-mark-mode', promote all headings
7963 in the region."
7964 (org-back-to-heading t)
7965 (let* ((level (save-match-data (funcall outline-level)))
7966 (after-change-functions (remove 'flyspell-after-change-function
7967 after-change-functions))
7968 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7969 (diff (abs (- level (length up-head) -1))))
7970 (cond ((and (= level 1) org-called-with-limited-levels
7971 org-allow-promoting-top-level-subtree)
7972 (replace-match "# " nil t))
7973 ((= level 1)
7974 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7975 (t (replace-match up-head nil t)))
7976 ;; Fixup tag positioning
7977 (unless (= level 1)
7978 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7979 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7980 (run-hooks 'org-after-promote-entry-hook)))
7981
7982 (defun org-demote ()
7983 "Demote the current heading lower down the tree.
7984 If the region is active in `transient-mark-mode', demote all headings
7985 in the region."
7986 (org-back-to-heading t)
7987 (let* ((level (save-match-data (funcall outline-level)))
7988 (after-change-functions (remove 'flyspell-after-change-function
7989 after-change-functions))
7990 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7991 (diff (abs (- level (length down-head) -1))))
7992 (replace-match down-head nil t)
7993 ;; Fixup tag positioning
7994 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7995 (if org-adapt-indentation (org-fixup-indentation diff))
7996 (run-hooks 'org-after-demote-entry-hook)))
7997
7998 (defun org-cycle-level ()
7999 "Cycle the level of an empty headline through possible states.
8000 This goes first to child, then to parent, level, then up the hierarchy.
8001 After top level, it switches back to sibling level."
8002 (interactive)
8003 (let ((org-adapt-indentation nil))
8004 (when (org-point-at-end-of-empty-headline)
8005 (setq this-command 'org-cycle-level) ; Only needed for caching
8006 (let ((cur-level (org-current-level))
8007 (prev-level (org-get-previous-line-level)))
8008 (cond
8009 ;; If first headline in file, promote to top-level.
8010 ((= prev-level 0)
8011 (loop repeat (/ (- cur-level 1) (org-level-increment))
8012 do (org-do-promote)))
8013 ;; If same level as prev, demote one.
8014 ((= prev-level cur-level)
8015 (org-do-demote))
8016 ;; If parent is top-level, promote to top level if not already.
8017 ((= prev-level 1)
8018 (loop repeat (/ (- cur-level 1) (org-level-increment))
8019 do (org-do-promote)))
8020 ;; If top-level, return to prev-level.
8021 ((= cur-level 1)
8022 (loop repeat (/ (- prev-level 1) (org-level-increment))
8023 do (org-do-demote)))
8024 ;; If less than prev-level, promote one.
8025 ((< cur-level prev-level)
8026 (org-do-promote))
8027 ;; If deeper than prev-level, promote until higher than
8028 ;; prev-level.
8029 ((> cur-level prev-level)
8030 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8031 do (org-do-promote))))
8032 t))))
8033
8034 (defun org-map-tree (fun)
8035 "Call FUN for every heading underneath the current one."
8036 (org-back-to-heading)
8037 (let ((level (funcall outline-level)))
8038 (save-excursion
8039 (funcall fun)
8040 (while (and (progn
8041 (outline-next-heading)
8042 (> (funcall outline-level) level))
8043 (not (eobp)))
8044 (funcall fun)))))
8045
8046 (defun org-map-region (fun beg end)
8047 "Call FUN for every heading between BEG and END."
8048 (let ((org-ignore-region t))
8049 (save-excursion
8050 (setq end (copy-marker end))
8051 (goto-char beg)
8052 (if (and (re-search-forward org-outline-regexp-bol nil t)
8053 (< (point) end))
8054 (funcall fun))
8055 (while (and (progn
8056 (outline-next-heading)
8057 (< (point) end))
8058 (not (eobp)))
8059 (funcall fun)))))
8060
8061 (defvar org-property-end-re) ; silence byte-compiler
8062 (defun org-fixup-indentation (diff)
8063 "Change the indentation in the current entry by DIFF.
8064 However, if any line in the current entry has no indentation, or if it
8065 would end up with no indentation after the change, nothing at all is done."
8066 (save-excursion
8067 (let ((end (save-excursion (outline-next-heading)
8068 (point-marker)))
8069 (prohibit (if (> diff 0)
8070 "^\\S-"
8071 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8072 col)
8073 (unless (save-excursion (end-of-line 1)
8074 (re-search-forward prohibit end t))
8075 (while (and (< (point) end)
8076 (re-search-forward "^[ \t]+" end t))
8077 (goto-char (match-end 0))
8078 (setq col (current-column))
8079 (if (< diff 0) (replace-match ""))
8080 (org-indent-to-column (+ diff col))))
8081 (move-marker end nil))))
8082
8083 (defun org-convert-to-odd-levels ()
8084 "Convert an org-mode file with all levels allowed to one with odd levels.
8085 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8086 level 5 etc."
8087 (interactive)
8088 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8089 (let ((outline-level 'org-outline-level)
8090 (org-odd-levels-only nil) n)
8091 (save-excursion
8092 (goto-char (point-min))
8093 (while (re-search-forward "^\\*\\*+ " nil t)
8094 (setq n (- (length (match-string 0)) 2))
8095 (while (>= (setq n (1- n)) 0)
8096 (org-demote))
8097 (end-of-line 1))))))
8098
8099 (defun org-convert-to-oddeven-levels ()
8100 "Convert an org-mode file with only odd levels to one with odd/even levels.
8101 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8102 file contains a section with an even level, conversion would
8103 destroy the structure of the file. An error is signaled in this
8104 case."
8105 (interactive)
8106 (goto-char (point-min))
8107 ;; First check if there are no even levels
8108 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8109 (org-show-context t)
8110 (error "Not all levels are odd in this file. Conversion not possible"))
8111 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8112 (let ((outline-regexp org-outline-regexp)
8113 (outline-level 'org-outline-level)
8114 (org-odd-levels-only nil) n)
8115 (save-excursion
8116 (goto-char (point-min))
8117 (while (re-search-forward "^\\*\\*+ " nil t)
8118 (setq n (/ (1- (length (match-string 0))) 2))
8119 (while (>= (setq n (1- n)) 0)
8120 (org-promote))
8121 (end-of-line 1))))))
8122
8123 (defun org-tr-level (n)
8124 "Make N odd if required."
8125 (if org-odd-levels-only (1+ (/ n 2)) n))
8126
8127 ;;; Vertical tree motion, cutting and pasting of subtrees
8128
8129 (defun org-move-subtree-up (&optional arg)
8130 "Move the current subtree up past ARG headlines of the same level."
8131 (interactive "p")
8132 (org-move-subtree-down (- (prefix-numeric-value arg))))
8133
8134 (defun org-move-subtree-down (&optional arg)
8135 "Move the current subtree down past ARG headlines of the same level."
8136 (interactive "p")
8137 (setq arg (prefix-numeric-value arg))
8138 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8139 'org-get-last-sibling))
8140 (ins-point (make-marker))
8141 (cnt (abs arg))
8142 (col (current-column))
8143 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8144 ;; Select the tree
8145 (org-back-to-heading)
8146 (setq beg0 (point))
8147 (save-excursion
8148 (setq ne-beg (org-back-over-empty-lines))
8149 (setq beg (point)))
8150 (save-match-data
8151 (save-excursion (outline-end-of-heading)
8152 (setq folded (outline-invisible-p)))
8153 (outline-end-of-subtree))
8154 (outline-next-heading)
8155 (setq ne-end (org-back-over-empty-lines))
8156 (setq end (point))
8157 (goto-char beg0)
8158 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8159 ;; include less whitespace
8160 (save-excursion
8161 (goto-char beg)
8162 (forward-line (- ne-beg ne-end))
8163 (setq beg (point))))
8164 ;; Find insertion point, with error handling
8165 (while (> cnt 0)
8166 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8167 (progn (goto-char beg0)
8168 (user-error "Cannot move past superior level or buffer limit")))
8169 (setq cnt (1- cnt)))
8170 (if (> arg 0)
8171 ;; Moving forward - still need to move over subtree
8172 (progn (org-end-of-subtree t t)
8173 (save-excursion
8174 (org-back-over-empty-lines)
8175 (or (bolp) (newline)))))
8176 (setq ne-ins (org-back-over-empty-lines))
8177 (move-marker ins-point (point))
8178 (setq txt (buffer-substring beg end))
8179 (org-save-markers-in-region beg end)
8180 (delete-region beg end)
8181 (org-remove-empty-overlays-at beg)
8182 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8183 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8184 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8185 (let ((bbb (point)))
8186 (insert-before-markers txt)
8187 (org-reinstall-markers-in-region bbb)
8188 (move-marker ins-point bbb))
8189 (or (bolp) (insert "\n"))
8190 (setq ins-end (point))
8191 (goto-char ins-point)
8192 (org-skip-whitespace)
8193 (when (and (< arg 0)
8194 (org-first-sibling-p)
8195 (> ne-ins ne-beg))
8196 ;; Move whitespace back to beginning
8197 (save-excursion
8198 (goto-char ins-end)
8199 (let ((kill-whole-line t))
8200 (kill-line (- ne-ins ne-beg)) (point)))
8201 (insert (make-string (- ne-ins ne-beg) ?\n)))
8202 (move-marker ins-point nil)
8203 (if folded
8204 (hide-subtree)
8205 (org-show-entry)
8206 (show-children)
8207 (org-cycle-hide-drawers 'children))
8208 (org-clean-visibility-after-subtree-move)
8209 ;; move back to the initial column we were at
8210 (move-to-column col)))
8211
8212 (defvar org-subtree-clip ""
8213 "Clipboard for cut and paste of subtrees.
8214 This is actually only a copy of the kill, because we use the normal kill
8215 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8216
8217 (defvar org-subtree-clip-folded nil
8218 "Was the last copied subtree folded?
8219 This is used to fold the tree back after pasting.")
8220
8221 (defun org-cut-subtree (&optional n)
8222 "Cut the current subtree into the clipboard.
8223 With prefix arg N, cut this many sequential subtrees.
8224 This is a short-hand for marking the subtree and then cutting it."
8225 (interactive "p")
8226 (org-copy-subtree n 'cut))
8227
8228 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8229 "Copy the current subtree it in the clipboard.
8230 With prefix arg N, copy this many sequential subtrees.
8231 This is a short-hand for marking the subtree and then copying it.
8232 If CUT is non-nil, actually cut the subtree.
8233 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8234 of some markers in the region, even if CUT is non-nil. This is
8235 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8236 (interactive "p")
8237 (let (beg end folded (beg0 (point)))
8238 (if (org-called-interactively-p 'any)
8239 (org-back-to-heading nil) ; take what looks like a subtree
8240 (org-back-to-heading t)) ; take what is really there
8241 (setq beg (point))
8242 (skip-chars-forward " \t\r\n")
8243 (save-match-data
8244 (if nosubtrees
8245 (outline-next-heading)
8246 (save-excursion (outline-end-of-heading)
8247 (setq folded (outline-invisible-p)))
8248 (condition-case nil
8249 (org-forward-heading-same-level (1- n) t)
8250 (error nil))
8251 (org-end-of-subtree t t)))
8252 (setq end (point))
8253 (goto-char beg0)
8254 (when (> end beg)
8255 (setq org-subtree-clip-folded folded)
8256 (when (or cut force-store-markers)
8257 (org-save-markers-in-region beg end))
8258 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8259 (setq org-subtree-clip (current-kill 0))
8260 (message "%s: Subtree(s) with %d characters"
8261 (if cut "Cut" "Copied")
8262 (length org-subtree-clip)))))
8263
8264 (defun org-paste-subtree (&optional level tree for-yank)
8265 "Paste the clipboard as a subtree, with modification of headline level.
8266 The entire subtree is promoted or demoted in order to match a new headline
8267 level.
8268
8269 If the cursor is at the beginning of a headline, the same level as
8270 that headline is used to paste the tree.
8271
8272 If not, the new level is derived from the *visible* headings
8273 before and after the insertion point, and taken to be the inferior headline
8274 level of the two. So if the previous visible heading is level 3 and the
8275 next is level 4 (or vice versa), level 4 will be used for insertion.
8276 This makes sure that the subtree remains an independent subtree and does
8277 not swallow low level entries.
8278
8279 You can also force a different level, either by using a numeric prefix
8280 argument, or by inserting the heading marker by hand. For example, if the
8281 cursor is after \"*****\", then the tree will be shifted to level 5.
8282
8283 If optional TREE is given, use this text instead of the kill ring.
8284
8285 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8286 move back over whitespace before inserting, and move point to the end of
8287 the inserted text when done."
8288 (interactive "P")
8289 (setq tree (or tree (and kill-ring (current-kill 0))))
8290 (unless (org-kill-is-subtree-p tree)
8291 (user-error "%s"
8292 (substitute-command-keys
8293 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8294 (org-with-limited-levels
8295 (let* ((visp (not (outline-invisible-p)))
8296 (txt tree)
8297 (^re_ "\\(\\*+\\)[ \t]*")
8298 (old-level (if (string-match org-outline-regexp-bol txt)
8299 (- (match-end 0) (match-beginning 0) 1)
8300 -1))
8301 (force-level (cond (level (prefix-numeric-value level))
8302 ((and (looking-at "[ \t]*$")
8303 (string-match
8304 "^\\*+$" (buffer-substring
8305 (point-at-bol) (point))))
8306 (- (match-end 1) (match-beginning 1)))
8307 ((and (bolp)
8308 (looking-at org-outline-regexp))
8309 (- (match-end 0) (point) 1))))
8310 (previous-level (save-excursion
8311 (condition-case nil
8312 (progn
8313 (outline-previous-visible-heading 1)
8314 (if (looking-at ^re_)
8315 (- (match-end 0) (match-beginning 0) 1)
8316 1))
8317 (error 1))))
8318 (next-level (save-excursion
8319 (condition-case nil
8320 (progn
8321 (or (looking-at org-outline-regexp)
8322 (outline-next-visible-heading 1))
8323 (if (looking-at ^re_)
8324 (- (match-end 0) (match-beginning 0) 1)
8325 1))
8326 (error 1))))
8327 (new-level (or force-level (max previous-level next-level)))
8328 (shift (if (or (= old-level -1)
8329 (= new-level -1)
8330 (= old-level new-level))
8331 0
8332 (- new-level old-level)))
8333 (delta (if (> shift 0) -1 1))
8334 (func (if (> shift 0) 'org-demote 'org-promote))
8335 (org-odd-levels-only nil)
8336 beg end newend)
8337 ;; Remove the forced level indicator
8338 (if force-level
8339 (delete-region (point-at-bol) (point)))
8340 ;; Paste
8341 (beginning-of-line (if (bolp) 1 2))
8342 (setq beg (point))
8343 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8344 (insert-before-markers txt)
8345 (unless (string-match "\n\\'" txt) (insert "\n"))
8346 (setq newend (point))
8347 (org-reinstall-markers-in-region beg)
8348 (setq end (point))
8349 (goto-char beg)
8350 (skip-chars-forward " \t\n\r")
8351 (setq beg (point))
8352 (if (and (outline-invisible-p) visp)
8353 (save-excursion (outline-show-heading)))
8354 ;; Shift if necessary
8355 (unless (= shift 0)
8356 (save-restriction
8357 (narrow-to-region beg end)
8358 (while (not (= shift 0))
8359 (org-map-region func (point-min) (point-max))
8360 (setq shift (+ delta shift)))
8361 (goto-char (point-min))
8362 (setq newend (point-max))))
8363 (when (or (org-called-interactively-p 'interactive) for-yank)
8364 (message "Clipboard pasted as level %d subtree" new-level))
8365 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8366 kill-ring
8367 (eq org-subtree-clip (current-kill 0))
8368 org-subtree-clip-folded)
8369 ;; The tree was folded before it was killed/copied
8370 (hide-subtree))
8371 (and for-yank (goto-char newend)))))
8372
8373 (defun org-kill-is-subtree-p (&optional txt)
8374 "Check if the current kill is an outline subtree, or a set of trees.
8375 Returns nil if kill does not start with a headline, or if the first
8376 headline level is not the largest headline level in the tree.
8377 So this will actually accept several entries of equal levels as well,
8378 which is OK for `org-paste-subtree'.
8379 If optional TXT is given, check this string instead of the current kill."
8380 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8381 (re (org-get-limited-outline-regexp))
8382 (^re (concat "^" re))
8383 (start-level (and kill
8384 (string-match
8385 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8386 kill)
8387 (- (match-end 2) (match-beginning 2) 1)))
8388 (start (1+ (or (match-beginning 2) -1))))
8389 (if (not start-level)
8390 (progn
8391 nil) ;; does not even start with a heading
8392 (catch 'exit
8393 (while (setq start (string-match ^re kill (1+ start)))
8394 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8395 (throw 'exit nil)))
8396 t))))
8397
8398 (defvar org-markers-to-move nil
8399 "Markers that should be moved with a cut-and-paste operation.
8400 Those markers are stored together with their positions relative to
8401 the start of the region.")
8402
8403 (defun org-save-markers-in-region (beg end)
8404 "Check markers in region.
8405 If these markers are between BEG and END, record their position relative
8406 to BEG, so that after moving the block of text, we can put the markers back
8407 into place.
8408 This function gets called just before an entry or tree gets cut from the
8409 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8410 called immediately, to move the markers with the entries."
8411 (setq org-markers-to-move nil)
8412 (when (featurep 'org-clock)
8413 (org-clock-save-markers-for-cut-and-paste beg end))
8414 (when (featurep 'org-agenda)
8415 (org-agenda-save-markers-for-cut-and-paste beg end)))
8416
8417 (defun org-check-and-save-marker (marker beg end)
8418 "Check if MARKER is between BEG and END.
8419 If yes, remember the marker and the distance to BEG."
8420 (when (and (marker-buffer marker)
8421 (equal (marker-buffer marker) (current-buffer)))
8422 (if (and (>= marker beg) (< marker end))
8423 (push (cons marker (- marker beg)) org-markers-to-move))))
8424
8425 (defun org-reinstall-markers-in-region (beg)
8426 "Move all remembered markers to their position relative to BEG."
8427 (mapc (lambda (x)
8428 (move-marker (car x) (+ beg (cdr x))))
8429 org-markers-to-move)
8430 (setq org-markers-to-move nil))
8431
8432 (defun org-narrow-to-subtree ()
8433 "Narrow buffer to the current subtree."
8434 (interactive)
8435 (save-excursion
8436 (save-match-data
8437 (org-with-limited-levels
8438 (narrow-to-region
8439 (progn (org-back-to-heading t) (point))
8440 (progn (org-end-of-subtree t t)
8441 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8442 (point)))))))
8443
8444 (defun org-narrow-to-block ()
8445 "Narrow buffer to the current block."
8446 (interactive)
8447 (let* ((case-fold-search t)
8448 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8449 "^[ \t]*#\\+end_.*")))
8450 (if blockp
8451 (narrow-to-region (car blockp) (cdr blockp))
8452 (user-error "Not in a block"))))
8453
8454 (eval-when-compile
8455 (defvar org-property-drawer-re))
8456
8457 (defvar org-property-start-re) ;; defined below
8458 (defun org-clone-subtree-with-time-shift (n &optional shift)
8459 "Clone the task (subtree) at point N times.
8460 The clones will be inserted as siblings.
8461
8462 In interactive use, the user will be prompted for the number of
8463 clones to be produced. If the entry has a timestamp, the user
8464 will also be prompted for a time shift, which may be a repeater
8465 as used in time stamps, for example `+3d'. To disable this,
8466 you can call the function with a universal prefix argument.
8467
8468 When a valid repeater is given and the entry contains any time
8469 stamps, the clones will become a sequence in time, with time
8470 stamps in the subtree shifted for each clone produced. If SHIFT
8471 is nil or the empty string, time stamps will be left alone. The
8472 ID property of the original subtree is removed.
8473
8474 If the original subtree did contain time stamps with a repeater,
8475 the following will happen:
8476 - the repeater will be removed in each clone
8477 - an additional clone will be produced, with the current, unshifted
8478 date(s) in the entry.
8479 - the original entry will be placed *after* all the clones, with
8480 repeater intact.
8481 - the start days in the repeater in the original entry will be shifted
8482 to past the last clone.
8483 In this way you can spell out a number of instances of a repeating task,
8484 and still retain the repeater to cover future instances of the task."
8485 (interactive "nNumber of clones to produce: ")
8486 (let ((shift
8487 (or shift
8488 (if (and (not (equal current-prefix-arg '(4)))
8489 (save-excursion
8490 (re-search-forward org-ts-regexp-both
8491 (save-excursion
8492 (org-end-of-subtree t)
8493 (point)) t)))
8494 (read-from-minibuffer
8495 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8496 ""))) ;; No time shift
8497 (n-no-remove -1)
8498 (drawer-re org-drawer-regexp)
8499 beg end template task idprop
8500 shift-n shift-what doshift nmin nmax)
8501 (if (not (and (integerp n) (> n 0)))
8502 (error "Invalid number of replications %s" n))
8503 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8504 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8505 shift)))
8506 (error "Invalid shift specification %s" shift))
8507 (when doshift
8508 (setq shift-n (string-to-number (match-string 1 shift))
8509 shift-what (cdr (assoc (match-string 2 shift)
8510 '(("d" . day) ("w" . week)
8511 ("m" . month) ("y" . year))))))
8512 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8513 (setq nmin 1 nmax n)
8514 (org-back-to-heading t)
8515 (setq beg (point))
8516 (setq idprop (org-entry-get nil "ID"))
8517 (org-end-of-subtree t t)
8518 (or (bolp) (insert "\n"))
8519 (setq end (point))
8520 (setq template (buffer-substring beg end))
8521 (when (and doshift
8522 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8523 (delete-region beg end)
8524 (setq end beg)
8525 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8526 (goto-char end)
8527 (loop for n from nmin to nmax do
8528 ;; prepare clone
8529 (with-temp-buffer
8530 (insert template)
8531 (org-mode)
8532 (goto-char (point-min))
8533 (org-show-subtree)
8534 (and idprop (if org-clone-delete-id
8535 (org-entry-delete nil "ID")
8536 (org-id-get-create t)))
8537 (unless (= n 0)
8538 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8539 (kill-whole-line))
8540 (goto-char (point-min))
8541 (while (re-search-forward drawer-re nil t)
8542 (mapc (lambda (d)
8543 (org-remove-empty-drawer-at d (point))) org-drawers)))
8544 (goto-char (point-min))
8545 (when doshift
8546 (while (re-search-forward org-ts-regexp-both nil t)
8547 (org-timestamp-change (* n shift-n) shift-what))
8548 (unless (= n n-no-remove)
8549 (goto-char (point-min))
8550 (while (re-search-forward org-ts-regexp nil t)
8551 (save-excursion
8552 (goto-char (match-beginning 0))
8553 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8554 (delete-region (match-beginning 1) (match-end 1)))))))
8555 (setq task (buffer-string)))
8556 (insert task))
8557 (goto-char beg)))
8558
8559 ;;; Outline Sorting
8560
8561 (defun org-sort (with-case)
8562 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8563 Optional argument WITH-CASE means sort case-sensitively."
8564 (interactive "P")
8565 (cond
8566 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8567 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8568 (t
8569 (org-call-with-arg 'org-sort-entries with-case))))
8570
8571 (defun org-sort-remove-invisible (s)
8572 "Remove invisible links from string S."
8573 (remove-text-properties 0 (length s) org-rm-props s)
8574 (while (string-match org-bracket-link-regexp s)
8575 (setq s (replace-match (if (match-end 2)
8576 (match-string 3 s)
8577 (match-string 1 s)) t t s)))
8578 (let ((st (format " %s " s)))
8579 (while (string-match org-emph-re st)
8580 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8581 (setq s (substring st 1 -1)))
8582 s)
8583
8584 (defvar org-priority-regexp) ; defined later in the file
8585
8586 (defvar org-after-sorting-entries-or-items-hook nil
8587 "Hook that is run after a bunch of entries or items have been sorted.
8588 When children are sorted, the cursor is in the parent line when this
8589 hook gets called. When a region or a plain list is sorted, the cursor
8590 will be in the first entry of the sorted region/list.")
8591
8592 (defun org-sort-entries
8593 (&optional with-case sorting-type getkey-func compare-func property)
8594 "Sort entries on a certain level of an outline tree.
8595 If there is an active region, the entries in the region are sorted.
8596 Else, if the cursor is before the first entry, sort the top-level items.
8597 Else, the children of the entry at point are sorted.
8598
8599 Sorting can be alphabetically, numerically, by date/time as given by
8600 a time stamp, by a property, by priority order, or by a custom function.
8601
8602 The command prompts for the sorting type unless it has been given to the
8603 function through the SORTING-TYPE argument, which needs to be a character,
8604 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8605 precise meaning of each character:
8606
8607 n Numerically, by converting the beginning of the entry/item to a number.
8608 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8609 o By order of TODO keywords.
8610 t By date/time, either the first active time stamp in the entry, or, if
8611 none exist, by the first inactive one.
8612 s By the scheduled date/time.
8613 d By deadline date/time.
8614 c By creation time, which is assumed to be the first inactive time stamp
8615 at the beginning of a line.
8616 p By priority according to the cookie.
8617 r By the value of a property.
8618
8619 Capital letters will reverse the sort order.
8620
8621 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8622 called with point at the beginning of the record. It must return either
8623 a string or a number that should serve as the sorting key for that record.
8624
8625 Comparing entries ignores case by default. However, with an optional argument
8626 WITH-CASE, the sorting considers case as well.
8627
8628 Sorting is done against the visible part of the headlines, it ignores hidden
8629 links."
8630 (interactive "P")
8631 (let ((case-func (if with-case 'identity 'downcase))
8632 (cmstr
8633 ;; The clock marker is lost when using `sort-subr', let's
8634 ;; store the clocking string.
8635 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8636 (save-excursion
8637 (goto-char org-clock-marker)
8638 (looking-back "^.*") (match-string-no-properties 0))))
8639 start beg end stars re re2
8640 txt what tmp)
8641 ;; Find beginning and end of region to sort
8642 (cond
8643 ((org-region-active-p)
8644 ;; we will sort the region
8645 (setq end (region-end)
8646 what "region")
8647 (goto-char (region-beginning))
8648 (if (not (org-at-heading-p)) (outline-next-heading))
8649 (setq start (point)))
8650 ((or (org-at-heading-p)
8651 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8652 ;; we will sort the children of the current headline
8653 (org-back-to-heading)
8654 (setq start (point)
8655 end (progn (org-end-of-subtree t t)
8656 (or (bolp) (insert "\n"))
8657 (when (>= (org-back-over-empty-lines) 1)
8658 (forward-line 1))
8659 (point))
8660 what "children")
8661 (goto-char start)
8662 (show-subtree)
8663 (outline-next-heading))
8664 (t
8665 ;; we will sort the top-level entries in this file
8666 (goto-char (point-min))
8667 (or (org-at-heading-p) (outline-next-heading))
8668 (setq start (point))
8669 (goto-char (point-max))
8670 (beginning-of-line 1)
8671 (when (looking-at ".*?\\S-")
8672 ;; File ends in a non-white line
8673 (end-of-line 1)
8674 (insert "\n"))
8675 (setq end (point-max))
8676 (setq what "top-level")
8677 (goto-char start)
8678 (show-all)))
8679
8680 (setq beg (point))
8681 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8682
8683 (looking-at "\\(\\*+\\)")
8684 (setq stars (match-string 1)
8685 re (concat "^" (regexp-quote stars) " +")
8686 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8687 txt (buffer-substring beg end))
8688 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8689 (if (and (not (equal stars "*")) (string-match re2 txt))
8690 (user-error "Region to sort contains a level above the first entry"))
8691
8692 (unless sorting-type
8693 (message
8694 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8695 [t]ime [s]cheduled [d]eadline [c]reated
8696 A/N/P/R/O/F/T/S/D/C means reversed:"
8697 what)
8698 (setq sorting-type (read-char-exclusive))
8699
8700 (unless getkey-func
8701 (and (= (downcase sorting-type) ?f)
8702 (setq getkey-func
8703 (org-icompleting-read "Sort using function: "
8704 obarray 'fboundp t nil nil))
8705 (setq getkey-func (intern getkey-func))))
8706
8707 (and (= (downcase sorting-type) ?r)
8708 (not property)
8709 (setq property
8710 (org-icompleting-read "Property: "
8711 (mapcar 'list (org-buffer-property-keys t))
8712 nil t))))
8713
8714 (message "Sorting entries...")
8715
8716 (save-restriction
8717 (narrow-to-region start end)
8718 (let ((dcst (downcase sorting-type))
8719 (case-fold-search nil)
8720 (now (current-time)))
8721 (sort-subr
8722 (/= dcst sorting-type)
8723 ;; This function moves to the beginning character of the "record" to
8724 ;; be sorted.
8725 (lambda nil
8726 (if (re-search-forward re nil t)
8727 (goto-char (match-beginning 0))
8728 (goto-char (point-max))))
8729 ;; This function moves to the last character of the "record" being
8730 ;; sorted.
8731 (lambda nil
8732 (save-match-data
8733 (condition-case nil
8734 (outline-forward-same-level 1)
8735 (error
8736 (goto-char (point-max))))))
8737 ;; This function returns the value that gets sorted against.
8738 (lambda nil
8739 (cond
8740 ((= dcst ?n)
8741 (if (looking-at org-complex-heading-regexp)
8742 (string-to-number (org-sort-remove-invisible (match-string 4)))
8743 nil))
8744 ((= dcst ?a)
8745 (if (looking-at org-complex-heading-regexp)
8746 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8747 nil))
8748 ((= dcst ?t)
8749 (let ((end (save-excursion (outline-next-heading) (point))))
8750 (if (or (re-search-forward org-ts-regexp end t)
8751 (re-search-forward org-ts-regexp-both end t))
8752 (org-time-string-to-seconds (match-string 0))
8753 (org-float-time now))))
8754 ((= dcst ?c)
8755 (let ((end (save-excursion (outline-next-heading) (point))))
8756 (if (re-search-forward
8757 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8758 end t)
8759 (org-time-string-to-seconds (match-string 0))
8760 (org-float-time now))))
8761 ((= dcst ?s)
8762 (let ((end (save-excursion (outline-next-heading) (point))))
8763 (if (re-search-forward org-scheduled-time-regexp end t)
8764 (org-time-string-to-seconds (match-string 1))
8765 (org-float-time now))))
8766 ((= dcst ?d)
8767 (let ((end (save-excursion (outline-next-heading) (point))))
8768 (if (re-search-forward org-deadline-time-regexp end t)
8769 (org-time-string-to-seconds (match-string 1))
8770 (org-float-time now))))
8771 ((= dcst ?p)
8772 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8773 (string-to-char (match-string 2))
8774 org-default-priority))
8775 ((= dcst ?r)
8776 (or (org-entry-get nil property) ""))
8777 ((= dcst ?o)
8778 (if (looking-at org-complex-heading-regexp)
8779 (- 9999 (length (member (match-string 2)
8780 org-todo-keywords-1)))))
8781 ((= dcst ?f)
8782 (if getkey-func
8783 (progn
8784 (setq tmp (funcall getkey-func))
8785 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8786 tmp)
8787 (error "Invalid key function `%s'" getkey-func)))
8788 (t (error "Invalid sorting type `%c'" sorting-type))))
8789 nil
8790 (cond
8791 ((= dcst ?a) 'string<)
8792 ((= dcst ?f) compare-func)
8793 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8794 (run-hooks 'org-after-sorting-entries-or-items-hook)
8795 ;; Reset the clock marker if needed
8796 (when cmstr
8797 (save-excursion
8798 (goto-char start)
8799 (search-forward cmstr nil t)
8800 (move-marker org-clock-marker (point))))
8801 (message "Sorting entries...done")))
8802
8803 (defun org-do-sort (table what &optional with-case sorting-type)
8804 "Sort TABLE of WHAT according to SORTING-TYPE.
8805 The user will be prompted for the SORTING-TYPE if the call to this
8806 function does not specify it. WHAT is only for the prompt, to indicate
8807 what is being sorted. The sorting key will be extracted from
8808 the car of the elements of the table.
8809 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8810 (unless sorting-type
8811 (message
8812 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8813 what)
8814 (setq sorting-type (read-char-exclusive)))
8815 (let ((dcst (downcase sorting-type))
8816 extractfun comparefun)
8817 ;; Define the appropriate functions
8818 (cond
8819 ((= dcst ?n)
8820 (setq extractfun 'string-to-number
8821 comparefun (if (= dcst sorting-type) '< '>)))
8822 ((= dcst ?a)
8823 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8824 (lambda(x) (downcase (org-sort-remove-invisible x))))
8825 comparefun (if (= dcst sorting-type)
8826 'string<
8827 (lambda (a b) (and (not (string< a b))
8828 (not (string= a b)))))))
8829 ((= dcst ?t)
8830 (setq extractfun
8831 (lambda (x)
8832 (if (or (string-match org-ts-regexp x)
8833 (string-match org-ts-regexp-both x))
8834 (org-float-time
8835 (org-time-string-to-time (match-string 0 x)))
8836 0))
8837 comparefun (if (= dcst sorting-type) '< '>)))
8838 (t (error "Invalid sorting type `%c'" sorting-type)))
8839
8840 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8841 table)
8842 (lambda (a b) (funcall comparefun (car a) (car b))))))
8843
8844
8845 ;;; The orgstruct minor mode
8846
8847 ;; Define a minor mode which can be used in other modes in order to
8848 ;; integrate the org-mode structure editing commands.
8849
8850 ;; This is really a hack, because the org-mode structure commands use
8851 ;; keys which normally belong to the major mode. Here is how it
8852 ;; works: The minor mode defines all the keys necessary to operate the
8853 ;; structure commands, but wraps the commands into a function which
8854 ;; tests if the cursor is currently at a headline or a plain list
8855 ;; item. If that is the case, the structure command is used,
8856 ;; temporarily setting many Org-mode variables like regular
8857 ;; expressions for filling etc. However, when any of those keys is
8858 ;; used at a different location, function uses `key-binding' to look
8859 ;; up if the key has an associated command in another currently active
8860 ;; keymap (minor modes, major mode, global), and executes that
8861 ;; command. There might be problems if any of the keys is otherwise
8862 ;; used as a prefix key.
8863
8864 (defcustom orgstruct-heading-prefix-regexp ""
8865 "Regexp that matches the custom prefix of Org headlines in
8866 orgstruct(++)-mode."
8867 :group 'org
8868 :version "24.4"
8869 :package-version '(Org . "8.3")
8870 :type 'regexp)
8871 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8872
8873 (defcustom orgstruct-setup-hook nil
8874 "Hook run after orgstruct-mode-map is filled."
8875 :group 'org
8876 :version "24.4"
8877 :package-version '(Org . "8.0")
8878 :type 'hook)
8879
8880 (defvar orgstruct-initialized nil)
8881
8882 (defvar org-local-vars nil
8883 "List of local variables, for use by `orgstruct-mode'.")
8884
8885 ;;;###autoload
8886 (define-minor-mode orgstruct-mode
8887 "Toggle the minor mode `orgstruct-mode'.
8888 This mode is for using Org-mode structure commands in other
8889 modes. The following keys behave as if Org-mode were active, if
8890 the cursor is on a headline, or on a plain list item (both as
8891 defined by Org-mode)."
8892 nil " OrgStruct" (make-sparse-keymap)
8893 (funcall (if orgstruct-mode
8894 'add-to-invisibility-spec
8895 'remove-from-invisibility-spec)
8896 '(outline . t))
8897 (when orgstruct-mode
8898 (org-load-modules-maybe)
8899 (unless orgstruct-initialized
8900 (orgstruct-setup)
8901 (setq orgstruct-initialized t))))
8902
8903 ;;;###autoload
8904 (defun turn-on-orgstruct ()
8905 "Unconditionally turn on `orgstruct-mode'."
8906 (orgstruct-mode 1))
8907
8908 (defvar org-fb-vars nil)
8909 (make-variable-buffer-local 'org-fb-vars)
8910 (defun orgstruct++-mode (&optional arg)
8911 "Toggle `orgstruct-mode', the enhanced version of it.
8912 In addition to setting orgstruct-mode, this also exports all
8913 indentation and autofilling variables from org-mode into the
8914 buffer. It will also recognize item context in multiline items."
8915 (interactive "P")
8916 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8917 (if (< arg 1)
8918 (progn (orgstruct-mode -1)
8919 (mapc (lambda(v)
8920 (org-set-local (car v)
8921 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8922 org-fb-vars))
8923 (orgstruct-mode 1)
8924 (setq org-fb-vars nil)
8925 (unless org-local-vars
8926 (setq org-local-vars (org-get-local-variables)))
8927 (let (var val)
8928 (mapc
8929 (lambda (x)
8930 (when (string-match
8931 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8932 (symbol-name (car x)))
8933 (setq var (car x) val (nth 1 x))
8934 (push (list var `(quote ,(eval var))) org-fb-vars)
8935 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8936 org-local-vars)
8937 (org-set-local 'orgstruct-is-++ t))))
8938
8939 (defvar orgstruct-is-++ nil
8940 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8941 (make-variable-buffer-local 'orgstruct-is-++)
8942
8943 ;;;###autoload
8944 (defun turn-on-orgstruct++ ()
8945 "Unconditionally turn on `orgstruct++-mode'."
8946 (orgstruct++-mode 1))
8947
8948 (defun orgstruct-error ()
8949 "Error when there is no default binding for a structure key."
8950 (interactive)
8951 (funcall (if (fboundp 'user-error)
8952 'user-error
8953 'error)
8954 "This key has no function outside structure elements"))
8955
8956 (defun orgstruct-setup ()
8957 "Setup orgstruct keymap."
8958 (dolist (cell '((org-demote . t)
8959 (org-metaleft . t)
8960 (org-metaright . t)
8961 (org-promote . t)
8962 (org-shiftmetaleft . t)
8963 (org-shiftmetaright . t)
8964 org-backward-element
8965 org-backward-heading-same-level
8966 org-ctrl-c-ret
8967 org-ctrl-c-minus
8968 org-ctrl-c-star
8969 org-cycle
8970 org-forward-heading-same-level
8971 org-insert-heading
8972 org-insert-heading-respect-content
8973 org-kill-note-or-show-branches
8974 org-mark-subtree
8975 org-meta-return
8976 org-metadown
8977 org-metaup
8978 org-narrow-to-subtree
8979 org-promote-subtree
8980 org-reveal
8981 org-shiftdown
8982 org-shiftleft
8983 org-shiftmetadown
8984 org-shiftmetaup
8985 org-shiftright
8986 org-shifttab
8987 org-shifttab
8988 org-shiftup
8989 org-show-subtree
8990 org-sort
8991 org-up-element
8992 outline-demote
8993 outline-next-visible-heading
8994 outline-previous-visible-heading
8995 outline-promote
8996 outline-up-heading
8997 show-children))
8998 (let ((f (or (car-safe cell) cell))
8999 (disable-when-heading-prefix (cdr-safe cell)))
9000 (when (fboundp f)
9001 (let ((new-bindings))
9002 (dolist (binding (nconc (where-is-internal f org-mode-map)
9003 (where-is-internal f outline-mode-map)))
9004 (push binding new-bindings)
9005 ;; TODO use local-function-key-map
9006 (dolist (rep '(("<tab>" . "TAB")
9007 ("<return>" . "RET")
9008 ("<escape>" . "ESC")
9009 ("<delete>" . "DEL")))
9010 (setq binding (read-kbd-macro
9011 (let ((case-fold-search))
9012 (replace-regexp-in-string
9013 (regexp-quote (cdr rep))
9014 (car rep)
9015 (key-description binding)))))
9016 (pushnew binding new-bindings :test 'equal)))
9017 (dolist (binding new-bindings)
9018 (let ((key (lookup-key orgstruct-mode-map binding)))
9019 (when (or (not key) (numberp key))
9020 (condition-case nil
9021 (org-defkey orgstruct-mode-map
9022 binding
9023 (orgstruct-make-binding f binding disable-when-heading-prefix))
9024 (error nil)))))))))
9025 (run-hooks 'orgstruct-setup-hook))
9026
9027 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9028 "Create a function for binding in the structure minor mode.
9029 FUN is the command to call inside a table. KEY is the key that
9030 should be checked in for a command to execute outside of tables.
9031 Non-nil `disable-when-heading-prefix' means to disable the command
9032 if `orgstruct-heading-prefix-regexp' is not empty."
9033 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9034 (let ((nname name)
9035 (i 0))
9036 (while (fboundp (intern nname))
9037 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9038 (setq name (intern nname)))
9039 (eval
9040 (let ((bindings '((org-heading-regexp
9041 (concat "^"
9042 orgstruct-heading-prefix-regexp
9043 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9044 (org-outline-regexp
9045 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9046 (org-outline-regexp-bol
9047 (concat "^" org-outline-regexp))
9048 (outline-regexp org-outline-regexp)
9049 (outline-heading-end-regexp "\n")
9050 (outline-level 'org-outline-level)
9051 (outline-heading-alist))))
9052 `(defun ,name (arg)
9053 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9054 "Outside of structure, run the binding of `"
9055 (key-description key) "'."
9056 (when disable-when-heading-prefix
9057 (concat
9058 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9059 "back to the default binding due to limitations of Org's implementation of\n"
9060 "`" (symbol-name fun) "'.")))
9061 (interactive "p")
9062 (let* ((disable
9063 ,(and disable-when-heading-prefix
9064 '(not (string= orgstruct-heading-prefix-regexp ""))))
9065 (fallback
9066 (or disable
9067 (not
9068 (let* ,bindings
9069 (org-context-p 'headline 'item
9070 ,(when (memq fun
9071 '(org-insert-heading
9072 org-insert-heading-respect-content
9073 org-meta-return))
9074 '(when orgstruct-is-++
9075 'item-body))))))))
9076 (if fallback
9077 (let* ((orgstruct-mode)
9078 (binding
9079 (loop with key = ,key
9080 for rep in
9081 '(nil
9082 ("<\\([^>]*\\)tab>" . "\\1TAB")
9083 ("<\\([^>]*\\)return>" . "\\1RET")
9084 ("<\\([^>]*\\)escape>" . "\\1ESC")
9085 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9086 do
9087 (when rep
9088 (setq key (read-kbd-macro
9089 (let ((case-fold-search))
9090 (replace-regexp-in-string
9091 (car rep)
9092 (cdr rep)
9093 (key-description key))))))
9094 thereis (key-binding key))))
9095 (if (keymapp binding)
9096 (org-set-transient-map binding)
9097 (let ((func (or binding
9098 (unless disable
9099 'orgstruct-error))))
9100 (when func
9101 (call-interactively func)))))
9102 (org-run-like-in-org-mode
9103 (lambda ()
9104 (interactive)
9105 (let* ,bindings
9106 (call-interactively ',fun)))))))))
9107 name))
9108
9109 (defun org-contextualize-keys (alist contexts)
9110 "Return valid elements in ALIST depending on CONTEXTS.
9111
9112 `org-agenda-custom-commands' or `org-capture-templates' are the
9113 values used for ALIST, and `org-agenda-custom-commands-contexts'
9114 or `org-capture-templates-contexts' are the associated contexts
9115 definitions."
9116 (let ((contexts
9117 ;; normalize contexts
9118 (mapcar
9119 (lambda(c) (cond ((listp (cadr c))
9120 (list (car c) (car c) (cadr c)))
9121 ((string= "" (cadr c))
9122 (list (car c) (car c) (caddr c)))
9123 (t c))) contexts))
9124 (a alist) c r s)
9125 ;; loop over all commands or templates
9126 (while (setq c (pop a))
9127 (let (vrules repl)
9128 (cond
9129 ((not (assoc (car c) contexts))
9130 (push c r))
9131 ((and (assoc (car c) contexts)
9132 (setq vrules (org-contextualize-validate-key
9133 (car c) contexts)))
9134 (mapc (lambda (vr)
9135 (when (not (equal (car vr) (cadr vr)))
9136 (setq repl vr))) vrules)
9137 (if (not repl) (push c r)
9138 (push (cadr repl) s)
9139 (push
9140 (cons (car c)
9141 (cdr (or (assoc (cadr repl) alist)
9142 (error "Undefined key `%s' as contextual replacement for `%s'"
9143 (cadr repl) (car c)))))
9144 r))))))
9145 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9146 (delq
9147 nil
9148 (delete-dups
9149 (mapcar (lambda (x)
9150 (let ((tpl (car x)))
9151 (when (not (delq
9152 nil
9153 (mapcar (lambda(y)
9154 (equal y tpl)) s))) x)))
9155 (reverse r))))))
9156
9157 (defun org-contextualize-validate-key (key contexts)
9158 "Check CONTEXTS for agenda or capture KEY."
9159 (let (r rr res)
9160 (while (setq r (pop contexts))
9161 (mapc
9162 (lambda (rr)
9163 (when
9164 (and (equal key (car r))
9165 (if (functionp rr) (funcall rr)
9166 (or (and (eq (car rr) 'in-file)
9167 (buffer-file-name)
9168 (string-match (cdr rr) (buffer-file-name)))
9169 (and (eq (car rr) 'in-mode)
9170 (string-match (cdr rr) (symbol-name major-mode)))
9171 (and (eq (car rr) 'in-buffer)
9172 (string-match (cdr rr) (buffer-name)))
9173 (when (and (eq (car rr) 'not-in-file)
9174 (buffer-file-name))
9175 (not (string-match (cdr rr) (buffer-file-name))))
9176 (when (eq (car rr) 'not-in-mode)
9177 (not (string-match (cdr rr) (symbol-name major-mode))))
9178 (when (eq (car rr) 'not-in-buffer)
9179 (not (string-match (cdr rr) (buffer-name)))))))
9180 (push r res)))
9181 (car (last r))))
9182 (delete-dups (delq nil res))))
9183
9184 (defun org-context-p (&rest contexts)
9185 "Check if local context is any of CONTEXTS.
9186 Possible values in the list of contexts are `table', `headline', and `item'."
9187 (let ((pos (point)))
9188 (goto-char (point-at-bol))
9189 (prog1 (or (and (memq 'table contexts)
9190 (looking-at "[ \t]*|"))
9191 (and (memq 'headline contexts)
9192 (looking-at org-outline-regexp))
9193 (and (memq 'item contexts)
9194 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9195 (and (memq 'item-body contexts)
9196 (org-in-item-p)))
9197 (goto-char pos))))
9198
9199 (defun org-get-local-variables ()
9200 "Return a list of all local variables in an Org mode buffer."
9201 (let (varlist)
9202 (with-current-buffer (get-buffer-create "*Org tmp*")
9203 (erase-buffer)
9204 (org-mode)
9205 (setq varlist (buffer-local-variables)))
9206 (kill-buffer "*Org tmp*")
9207 (delq nil
9208 (mapcar
9209 (lambda (x)
9210 (setq x
9211 (if (symbolp x)
9212 (list x)
9213 (list (car x) (cdr x))))
9214 (if (and (not (get (car x) 'org-state))
9215 (string-match
9216 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9217 (symbol-name (car x))))
9218 x nil))
9219 varlist))))
9220
9221 (defun org-clone-local-variables (from-buffer &optional regexp)
9222 "Clone local variables from FROM-BUFFER.
9223 Optional argument REGEXP selects variables to clone."
9224 (mapc
9225 (lambda (pair)
9226 (and (symbolp (car pair))
9227 (or (null regexp)
9228 (string-match regexp (symbol-name (car pair))))
9229 (set (make-local-variable (car pair))
9230 (cdr pair))))
9231 (buffer-local-variables from-buffer)))
9232
9233 ;;;###autoload
9234 (defun org-run-like-in-org-mode (cmd)
9235 "Run a command, pretending that the current buffer is in Org-mode.
9236 This will temporarily bind local variables that are typically bound in
9237 Org-mode to the values they have in Org-mode, and then interactively
9238 call CMD."
9239 (org-load-modules-maybe)
9240 (unless org-local-vars
9241 (setq org-local-vars (org-get-local-variables)))
9242 (let (binds)
9243 (dolist (var org-local-vars)
9244 (when (or (not (boundp (car var)))
9245 (eq (symbol-value (car var))
9246 (default-value (car var))))
9247 (push (list (car var) `(quote ,(cadr var))) binds)))
9248 (eval `(let ,binds
9249 (call-interactively (quote ,cmd))))))
9250
9251 ;;;; Archiving
9252
9253 (defun org-get-category (&optional pos force-refresh)
9254 "Get the category applying to position POS."
9255 (save-match-data
9256 (if force-refresh (org-refresh-category-properties))
9257 (let ((pos (or pos (point))))
9258 (or (get-text-property pos 'org-category)
9259 (progn (org-refresh-category-properties)
9260 (get-text-property pos 'org-category))))))
9261
9262 (defun org-refresh-category-properties ()
9263 "Refresh category text properties in the buffer."
9264 (let ((case-fold-search t)
9265 (inhibit-read-only t)
9266 (def-cat (cond
9267 ((null org-category)
9268 (if buffer-file-name
9269 (file-name-sans-extension
9270 (file-name-nondirectory buffer-file-name))
9271 "???"))
9272 ((symbolp org-category) (symbol-name org-category))
9273 (t org-category)))
9274 beg end cat pos optionp)
9275 (org-with-silent-modifications
9276 (save-excursion
9277 (save-restriction
9278 (widen)
9279 (goto-char (point-min))
9280 (put-text-property (point) (point-max) 'org-category def-cat)
9281 (while (re-search-forward
9282 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9283 (setq pos (match-end 0)
9284 optionp (equal (char-after (match-beginning 0)) ?#)
9285 cat (org-trim (match-string 2)))
9286 (if optionp
9287 (setq beg (point-at-bol) end (point-max))
9288 (org-back-to-heading t)
9289 (setq beg (point) end (org-end-of-subtree t t)))
9290 (put-text-property beg end 'org-category cat)
9291 (put-text-property beg end 'org-category-position beg)
9292 (goto-char pos)))))))
9293
9294 (defun org-refresh-properties (dprop tprop)
9295 "Refresh buffer text properties.
9296 DPROP is the drawer property and TPROP is the corresponding text
9297 property to set."
9298 (let ((case-fold-search t)
9299 (inhibit-read-only t) p)
9300 (org-with-silent-modifications
9301 (save-excursion
9302 (save-restriction
9303 (widen)
9304 (goto-char (point-min))
9305 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9306 (setq p (org-match-string-no-properties 1))
9307 (save-excursion
9308 (org-back-to-heading t)
9309 (put-text-property
9310 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9311
9312
9313 ;;;; Link Stuff
9314
9315 ;;; Link abbreviations
9316
9317 (defun org-link-expand-abbrev (link)
9318 "Apply replacements as defined in `org-link-abbrev-alist'."
9319 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9320 (let* ((key (match-string 1 link))
9321 (as (or (assoc key org-link-abbrev-alist-local)
9322 (assoc key org-link-abbrev-alist)))
9323 (tag (and (match-end 2) (match-string 3 link)))
9324 rpl)
9325 (if (not as)
9326 link
9327 (setq rpl (cdr as))
9328 (cond
9329 ((symbolp rpl) (funcall rpl tag))
9330 ((string-match "%(\\([^)]+\\))" rpl)
9331 (replace-match
9332 (save-match-data
9333 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9334 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9335 ((string-match "%h" rpl)
9336 (replace-match (url-hexify-string (or tag "")) t t rpl))
9337 (t (concat rpl tag)))))
9338 link))
9339
9340 ;;; Storing and inserting links
9341
9342 (defvar org-insert-link-history nil
9343 "Minibuffer history for links inserted with `org-insert-link'.")
9344
9345 (defvar org-stored-links nil
9346 "Contains the links stored with `org-store-link'.")
9347
9348 (defvar org-store-link-plist nil
9349 "Plist with info about the most recently link created with `org-store-link'.")
9350
9351 (defvar org-link-protocols nil
9352 "Link protocols added to Org-mode using `org-add-link-type'.")
9353
9354 (defvar org-store-link-functions nil
9355 "List of functions that are called to create and store a link.
9356 Each function will be called in turn until one returns a non-nil
9357 value. Each function should check if it is responsible for creating
9358 this link (for example by looking at the major mode).
9359 If not, it must exit and return nil.
9360 If yes, it should return a non-nil value after a calling
9361 `org-store-link-props' with a list of properties and values.
9362 Special properties are:
9363
9364 :type The link prefix, like \"http\". This must be given.
9365 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9366 This is obligatory as well.
9367 :description Optional default description for the second pair
9368 of brackets in an Org-mode link. The user can still change
9369 this when inserting this link into an Org-mode buffer.
9370
9371 In addition to these, any additional properties can be specified
9372 and then used in capture templates.")
9373
9374 (defun org-add-link-type (type &optional follow export)
9375 "Add TYPE to the list of `org-link-types'.
9376 Re-compute all regular expressions depending on `org-link-types'
9377
9378 FOLLOW and EXPORT are two functions.
9379
9380 FOLLOW should take the link path as the single argument and do whatever
9381 is necessary to follow the link, for example find a file or display
9382 a mail message.
9383
9384 EXPORT should format the link path for export to one of the export formats.
9385 It should be a function accepting three arguments:
9386
9387 path the path of the link, the text after the prefix (like \"http:\")
9388 desc the description of the link, if any, or a description added by
9389 org-export-normalize-links if there is none
9390 format the export format, a symbol like `html' or `latex' or `ascii'..
9391
9392 The function may use the FORMAT information to return different values
9393 depending on the format. The return value will be put literally into
9394 the exported file. If the return value is nil, this means Org should
9395 do what it normally does with links which do not have EXPORT defined.
9396
9397 Org-mode has a built-in default for exporting links. If you are happy with
9398 this default, there is no need to define an export function for the link
9399 type. For a simple example of an export function, see `org-bbdb.el'."
9400 (add-to-list 'org-link-types type t)
9401 (org-make-link-regexps)
9402 (if (assoc type org-link-protocols)
9403 (setcdr (assoc type org-link-protocols) (list follow export))
9404 (push (list type follow export) org-link-protocols)))
9405
9406 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9407 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9408
9409 ;;;###autoload
9410 (defun org-store-link (arg)
9411 "\\<org-mode-map>Store an org-link to the current location.
9412 This link is added to `org-stored-links' and can later be inserted
9413 into an org-buffer with \\[org-insert-link].
9414
9415 For some link types, a prefix arg is interpreted.
9416 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9417 For file links, arg negates `org-context-in-file-links'.
9418
9419 A double prefix arg force skipping storing functions that are not
9420 part of Org's core.
9421
9422 A triple prefix arg force storing a link for each line in the
9423 active region."
9424 (interactive "P")
9425 (org-load-modules-maybe)
9426 (if (and (equal arg '(64)) (org-region-active-p))
9427 (save-excursion
9428 (let ((end (region-end)))
9429 (goto-char (region-beginning))
9430 (set-mark (point))
9431 (while (< (point-at-eol) end)
9432 (move-end-of-line 1) (activate-mark)
9433 (let (current-prefix-arg)
9434 (call-interactively 'org-store-link))
9435 (move-beginning-of-line 2)
9436 (set-mark (point)))))
9437 (org-with-limited-levels
9438 (setq org-store-link-plist nil)
9439 (let (link cpltxt desc description search
9440 txt custom-id agenda-link sfuns sfunsn)
9441 (cond
9442
9443 ;; Store a link using an external link type
9444 ((and (not (equal arg '(16)))
9445 (setq sfuns
9446 (delq
9447 nil (mapcar (lambda (f)
9448 (let (fs) (if (funcall f) (push f fs))))
9449 org-store-link-functions))
9450 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9451 (or (and (cdr sfuns)
9452 (funcall (intern
9453 (completing-read
9454 "Which function for creating the link? "
9455 sfunsn nil t (car sfunsn)))))
9456 (funcall (caar sfuns)))
9457 (setq link (plist-get org-store-link-plist :link)
9458 desc (or (plist-get org-store-link-plist
9459 :description) link))))
9460
9461 ;; Store a link from a source code buffer
9462 ((org-src-edit-buffer-p)
9463 (let (label gc)
9464 (while (or (not label)
9465 (save-excursion
9466 (save-restriction
9467 (widen)
9468 (goto-char (point-min))
9469 (re-search-forward
9470 (regexp-quote (format org-coderef-label-format label))
9471 nil t))))
9472 (when label (message "Label exists already") (sit-for 2))
9473 (setq label (read-string "Code line label: " label)))
9474 (end-of-line 1)
9475 (setq link (format org-coderef-label-format label))
9476 (setq gc (- 79 (length link)))
9477 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9478 (insert link)
9479 (setq link (concat "(" label ")") desc nil)))
9480
9481 ;; We are in the agenda, link to referenced location
9482 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9483 (let ((m (or (get-text-property (point) 'org-hd-marker)
9484 (get-text-property (point) 'org-marker))))
9485 (when m
9486 (org-with-point-at m
9487 (setq agenda-link
9488 (if (org-called-interactively-p 'any)
9489 (call-interactively 'org-store-link)
9490 (org-store-link nil)))))))
9491
9492 ((eq major-mode 'calendar-mode)
9493 (let ((cd (calendar-cursor-to-date)))
9494 (setq link
9495 (format-time-string
9496 (car org-time-stamp-formats)
9497 (apply 'encode-time
9498 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9499 nil nil nil))))
9500 (org-store-link-props :type "calendar" :date cd)))
9501
9502 ((eq major-mode 'help-mode)
9503 (setq link (concat "help:" (save-excursion
9504 (goto-char (point-min))
9505 (looking-at "^[^ ]+")
9506 (match-string 0))))
9507 (org-store-link-props :type "help"))
9508
9509 ((eq major-mode 'w3-mode)
9510 (setq cpltxt (if (and (buffer-name)
9511 (not (string-match "Untitled" (buffer-name))))
9512 (buffer-name)
9513 (url-view-url t))
9514 link (url-view-url t))
9515 (org-store-link-props :type "w3" :url (url-view-url t)))
9516
9517 ((eq major-mode 'image-mode)
9518 (setq cpltxt (concat "file:"
9519 (abbreviate-file-name buffer-file-name))
9520 link cpltxt)
9521 (org-store-link-props :type "image" :file buffer-file-name))
9522
9523 ;; In dired, store a link to the file of the current line
9524 ((eq major-mode 'dired-mode)
9525 (let ((file (dired-get-filename nil t)))
9526 (setq file (if file
9527 (abbreviate-file-name
9528 (expand-file-name (dired-get-filename nil t)))
9529 ;; otherwise, no file so use current directory.
9530 default-directory))
9531 (setq cpltxt (concat "file:" file)
9532 link cpltxt)))
9533
9534 ((setq search (run-hook-with-args-until-success
9535 'org-create-file-search-functions))
9536 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9537 "::" search))
9538 (setq cpltxt (or description link)))
9539
9540 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9541 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9542 (cond
9543 ;; Store a link using the target at point
9544 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9545 (setq cpltxt
9546 (concat "file:"
9547 (abbreviate-file-name
9548 (buffer-file-name (buffer-base-buffer)))
9549 "::" (match-string 1))
9550 link cpltxt))
9551 ((and (featurep 'org-id)
9552 (or (eq org-id-link-to-org-use-id t)
9553 (and (org-called-interactively-p 'any)
9554 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9555 (and (eq org-id-link-to-org-use-id
9556 'create-if-interactive-and-no-custom-id)
9557 (not custom-id))))
9558 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9559 ;; Store a link using the ID at point
9560 (setq link (condition-case nil
9561 (prog1 (org-id-store-link)
9562 (setq desc (or (plist-get org-store-link-plist
9563 :description)
9564 "")))
9565 (error
9566 ;; Probably before first headline, link only to file
9567 (concat "file:"
9568 (abbreviate-file-name
9569 (buffer-file-name (buffer-base-buffer))))))))
9570 (t
9571 ;; Just link to current headline
9572 (setq cpltxt (concat "file:"
9573 (abbreviate-file-name
9574 (buffer-file-name (buffer-base-buffer)))))
9575 ;; Add a context search string
9576 (when (org-xor org-context-in-file-links arg)
9577 (let* ((ee (org-element-at-point))
9578 (et (org-element-type ee))
9579 (ev (plist-get (cadr ee) :value))
9580 (ek (plist-get (cadr ee) :key))
9581 (eok (and (stringp ek) (string-match "name" ek))))
9582 (setq txt (cond
9583 ((org-at-heading-p) nil)
9584 ((and (eq et 'keyword) eok) ev)
9585 ((org-region-active-p)
9586 (buffer-substring (region-beginning) (region-end)))))
9587 (when (or (null txt) (string-match "\\S-" txt))
9588 (setq cpltxt
9589 (concat cpltxt "::"
9590 (condition-case nil
9591 (org-make-org-heading-search-string txt)
9592 (error "")))
9593 desc (or (and (eq et 'keyword) eok ev)
9594 (nth 4 (ignore-errors (org-heading-components)))
9595 "NONE")))))
9596 (if (string-match "::\\'" cpltxt)
9597 (setq cpltxt (substring cpltxt 0 -2)))
9598 (setq link cpltxt))))
9599
9600 ((buffer-file-name (buffer-base-buffer))
9601 ;; Just link to this file here.
9602 (setq cpltxt (concat "file:"
9603 (abbreviate-file-name
9604 (buffer-file-name (buffer-base-buffer)))))
9605 ;; Add a context string.
9606 (when (org-xor org-context-in-file-links arg)
9607 (setq txt (if (org-region-active-p)
9608 (buffer-substring (region-beginning) (region-end))
9609 (buffer-substring (point-at-bol) (point-at-eol))))
9610 ;; Only use search option if there is some text.
9611 (when (string-match "\\S-" txt)
9612 (setq cpltxt
9613 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9614 desc "NONE")))
9615 (setq link cpltxt))
9616
9617 ((org-called-interactively-p 'interactive)
9618 (user-error "No method for storing a link from this buffer"))
9619
9620 (t (setq link nil)))
9621
9622 ;; We're done setting link and desc, clean up
9623 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9624 (setq link (or link cpltxt)
9625 desc (or desc cpltxt))
9626 (cond ((equal desc "NONE") (setq desc nil))
9627 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9628 (let ((d0 (match-string 3 desc))
9629 (p0 (match-string 5 desc)))
9630 (setq desc
9631 (replace-regexp-in-string
9632 org-bracket-link-regexp
9633 (concat (or p0 d0)
9634 (if (equal (length (match-string 0 desc))
9635 (length desc)) "*" "")) desc)))))
9636
9637 ;; Return the link
9638 (if (not (and (or (org-called-interactively-p 'any)
9639 executing-kbd-macro) link))
9640 (or agenda-link (and link (org-make-link-string link desc)))
9641 (push (list link desc) org-stored-links)
9642 (message "Stored: %s" (or desc link))
9643 (when custom-id
9644 (setq link (concat "file:" (abbreviate-file-name
9645 (buffer-file-name)) "::#" custom-id))
9646 (push (list link desc) org-stored-links))
9647 (car org-stored-links))))))
9648
9649 (defun org-store-link-props (&rest plist)
9650 "Store link properties, extract names and addresses."
9651 (let (x adr)
9652 (when (setq x (plist-get plist :from))
9653 (setq adr (mail-extract-address-components x))
9654 (setq plist (plist-put plist :fromname (car adr)))
9655 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9656 (when (setq x (plist-get plist :to))
9657 (setq adr (mail-extract-address-components x))
9658 (setq plist (plist-put plist :toname (car adr)))
9659 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9660 (let ((from (plist-get plist :from))
9661 (to (plist-get plist :to)))
9662 (when (and from to org-from-is-user-regexp)
9663 (setq plist
9664 (plist-put plist :fromto
9665 (if (string-match org-from-is-user-regexp from)
9666 (concat "to %t")
9667 (concat "from %f"))))))
9668 (setq org-store-link-plist plist))
9669
9670 (defun org-add-link-props (&rest plist)
9671 "Add these properties to the link property list."
9672 (let (key value)
9673 (while plist
9674 (setq key (pop plist) value (pop plist))
9675 (setq org-store-link-plist
9676 (plist-put org-store-link-plist key value)))))
9677
9678 (defun org-email-link-description (&optional fmt)
9679 "Return the description part of an email link.
9680 This takes information from `org-store-link-plist' and formats it
9681 according to FMT (default from `org-email-link-description-format')."
9682 (setq fmt (or fmt org-email-link-description-format))
9683 (let* ((p org-store-link-plist)
9684 (to (plist-get p :toaddress))
9685 (from (plist-get p :fromaddress))
9686 (table
9687 (list
9688 (cons "%c" (plist-get p :fromto))
9689 (cons "%F" (plist-get p :from))
9690 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9691 (cons "%T" (plist-get p :to))
9692 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9693 (cons "%s" (plist-get p :subject))
9694 (cons "%d" (plist-get p :date))
9695 (cons "%m" (plist-get p :message-id)))))
9696 (when (string-match "%c" fmt)
9697 ;; Check if the user wrote this message
9698 (if (and org-from-is-user-regexp from to
9699 (save-match-data (string-match org-from-is-user-regexp from)))
9700 (setq fmt (replace-match "to %t" t t fmt))
9701 (setq fmt (replace-match "from %f" t t fmt))))
9702 (org-replace-escapes fmt table)))
9703
9704 (defun org-make-org-heading-search-string (&optional string)
9705 "Make search string for the current headline or STRING."
9706 (let ((s (or string
9707 (and (derived-mode-p 'org-mode)
9708 (save-excursion
9709 (org-back-to-heading t)
9710 (org-element-property :raw-value (org-element-at-point))))))
9711 (lines org-context-in-file-links))
9712 (or string (setq s (concat "*" s))) ; Add * for headlines
9713 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9714 (when (and string (integerp lines) (> lines 0))
9715 (let ((slines (org-split-string s "\n")))
9716 (when (< lines (length slines))
9717 (setq s (mapconcat
9718 'identity
9719 (reverse (nthcdr (- (length slines) lines)
9720 (reverse slines))) "\n")))))
9721 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9722
9723 (defun org-make-link-string (link &optional description)
9724 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9725 (unless (string-match "\\S-" link)
9726 (error "Empty link"))
9727 (when (and description
9728 (stringp description)
9729 (not (string-match "\\S-" description)))
9730 (setq description nil))
9731 (when (stringp description)
9732 ;; Remove brackets from the description, they are fatal.
9733 (while (string-match "\\[" description)
9734 (setq description (replace-match "{" t t description)))
9735 (while (string-match "\\]" description)
9736 (setq description (replace-match "}" t t description))))
9737 (when (equal link description)
9738 ;; No description needed, it is identical
9739 (setq description nil))
9740 (when (and (not description)
9741 (not (string-match (org-image-file-name-regexp) link))
9742 (not (equal link (org-link-escape link))))
9743 (setq description (org-extract-attributes link)))
9744 (setq link
9745 (cond ((string-match (org-image-file-name-regexp) link) link)
9746 ((string-match org-link-types-re link)
9747 (concat (match-string 1 link)
9748 (org-link-escape (substring link (match-end 1)))))
9749 (t (org-link-escape link))))
9750 (concat "[[" link "]"
9751 (if description (concat "[" description "]") "")
9752 "]"))
9753
9754 (defconst org-link-escape-chars
9755 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9756 "List of characters that should be escaped in link.
9757 This is the list that is used for internal purposes.")
9758
9759 (defconst org-link-escape-chars-browser
9760 '(?\ ?\")
9761 "List of escapes for characters that are problematic in links.
9762 This is the list that is used before handing over to the browser.")
9763
9764 (defun org-link-escape (text &optional table merge)
9765 "Return percent escaped representation of TEXT.
9766 TEXT is a string with the text to escape.
9767 Optional argument TABLE is a list with characters that should be
9768 escaped. When nil, `org-link-escape-chars' is used.
9769 If optional argument MERGE is set, merge TABLE into
9770 `org-link-escape-chars'."
9771 (cond
9772 ((and table merge)
9773 (mapc (lambda (defchr)
9774 (unless (member defchr table)
9775 (setq table (cons defchr table)))) org-link-escape-chars))
9776 ((null table)
9777 (setq table org-link-escape-chars)))
9778 (mapconcat
9779 (lambda (char)
9780 (if (or (member char table)
9781 (and (or (< char 32) (= char 37) (> char 126))
9782 org-url-hexify-p))
9783 (mapconcat (lambda (sequence-element)
9784 (format "%%%.2X" sequence-element))
9785 (or (encode-coding-char char 'utf-8)
9786 (error "Unable to percent escape character: %s"
9787 (char-to-string char))) "")
9788 (char-to-string char))) text ""))
9789
9790 (defun org-link-unescape (str)
9791 "Unhex hexified Unicode strings as returned from the JavaScript function
9792 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9793 (unless (and (null str) (string= "" str))
9794 (let ((pos 0) (case-fold-search t) unhexed)
9795 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9796 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9797 (setq str (replace-match unhexed t t str))
9798 (setq pos (+ pos (length unhexed))))))
9799 str)
9800
9801 (defun org-link-unescape-compound (hex)
9802 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9803 Note: this function also decodes single byte encodings like
9804 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9805 (save-match-data
9806 (let* ((bytes (cdr (split-string hex "%")))
9807 (ret "")
9808 (eat 0)
9809 (sum 0))
9810 (while bytes
9811 (let* ((val (string-to-number (pop bytes) 16))
9812 (shift-xor
9813 (if (= 0 eat)
9814 (cond
9815 ((>= val 252) (cons 6 252))
9816 ((>= val 248) (cons 5 248))
9817 ((>= val 240) (cons 4 240))
9818 ((>= val 224) (cons 3 224))
9819 ((>= val 192) (cons 2 192))
9820 (t (cons 0 0)))
9821 (cons 6 128))))
9822 (if (>= val 192) (setq eat (car shift-xor)))
9823 (setq val (logxor val (cdr shift-xor)))
9824 (setq sum (+ (lsh sum (car shift-xor)) val))
9825 (if (> eat 0) (setq eat (- eat 1)))
9826 (cond
9827 ((= 0 eat) ;multi byte
9828 (setq ret (concat ret (org-char-to-string sum)))
9829 (setq sum 0))
9830 ((not bytes) ; single byte(s)
9831 (setq ret (org-link-unescape-single-byte-sequence hex))))
9832 )) ;; end (while bytes
9833 ret )))
9834
9835 (defun org-link-unescape-single-byte-sequence (hex)
9836 "Unhexify hex-encoded single byte character sequences."
9837 (mapconcat (lambda (byte)
9838 (char-to-string (string-to-number byte 16)))
9839 (cdr (split-string hex "%")) ""))
9840
9841 (defun org-xor (a b)
9842 "Exclusive or."
9843 (if a (not b) b))
9844
9845 (defun org-fixup-message-id-for-http (s)
9846 "Replace special characters in a message id, so it can be used in an http query."
9847 (when (string-match "%" s)
9848 (setq s (mapconcat (lambda (c)
9849 (if (eq c ?%)
9850 "%25"
9851 (char-to-string c)))
9852 s "")))
9853 (while (string-match "<" s)
9854 (setq s (replace-match "%3C" t t s)))
9855 (while (string-match ">" s)
9856 (setq s (replace-match "%3E" t t s)))
9857 (while (string-match "@" s)
9858 (setq s (replace-match "%40" t t s)))
9859 s)
9860
9861 (defun org-link-prettify (link)
9862 "Return a human-readable representation of LINK.
9863 The car of LINK must be a raw link the cdr of LINK must be either
9864 a link description or nil."
9865 (let ((desc (or (cadr link) "<no description>")))
9866 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9867 "<" (car link) ">")))
9868
9869 ;;;###autoload
9870 (defun org-insert-link-global ()
9871 "Insert a link like Org-mode does.
9872 This command can be called in any mode to insert a link in Org-mode syntax."
9873 (interactive)
9874 (org-load-modules-maybe)
9875 (org-run-like-in-org-mode 'org-insert-link))
9876
9877 (defun org-insert-all-links (&optional keep)
9878 "Insert all links in `org-stored-links'."
9879 (interactive "P")
9880 (let ((links (copy-sequence org-stored-links)) l)
9881 (while (setq l (if keep (pop links) (pop org-stored-links)))
9882 (insert "- ")
9883 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9884 (insert "\n"))))
9885
9886 (defun org-link-fontify-links-to-this-file ()
9887 "Fontify links to the current file in `org-stored-links'."
9888 (let ((f (buffer-file-name)) a b)
9889 (setq a (mapcar (lambda(l)
9890 (let ((ll (car l)))
9891 (when (and (string-match "^file:\\(.+\\)::" ll)
9892 (equal f (expand-file-name (match-string 1 ll))))
9893 ll)))
9894 org-stored-links))
9895 (when (featurep 'org-id)
9896 (setq b (mapcar (lambda(l)
9897 (let ((ll (car l)))
9898 (when (and (string-match "^id:\\(.+\\)$" ll)
9899 (equal f (expand-file-name
9900 (or (org-id-find-id-file
9901 (match-string 1 ll)) ""))))
9902 ll)))
9903 org-stored-links)))
9904 (mapcar (lambda(l)
9905 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9906 (delq nil (append a b)))))
9907
9908 (defvar org-link-links-in-this-file nil)
9909 (defun org-insert-link (&optional complete-file link-location default-description)
9910 "Insert a link. At the prompt, enter the link.
9911
9912 Completion can be used to insert any of the link protocol prefixes like
9913 http or ftp in use.
9914
9915 The history can be used to select a link previously stored with
9916 `org-store-link'. When the empty string is entered (i.e. if you just
9917 press RET at the prompt), the link defaults to the most recently
9918 stored link. As SPC triggers completion in the minibuffer, you need to
9919 use M-SPC or C-q SPC to force the insertion of a space character.
9920
9921 You will also be prompted for a description, and if one is given, it will
9922 be displayed in the buffer instead of the link.
9923
9924 If there is already a link at point, this command will allow you to edit link
9925 and description parts.
9926
9927 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9928 be selected using completion. The path to the file will be relative to the
9929 current directory if the file is in the current directory or a subdirectory.
9930 Otherwise, the link will be the absolute path as completed in the minibuffer
9931 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9932 option `org-link-file-path-type'.
9933
9934 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9935 the current directory or below.
9936
9937 With three \\[universal-argument] prefixes, negate the meaning of
9938 `org-keep-stored-link-after-insertion'.
9939
9940 If `org-make-link-description-function' is non-nil, this function will be
9941 called with the link target, and the result will be the default
9942 link description.
9943
9944 If the LINK-LOCATION parameter is non-nil, this value will be
9945 used as the link location instead of reading one interactively.
9946
9947 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9948 be used as the default description."
9949 (interactive "P")
9950 (let* ((wcf (current-window-configuration))
9951 (origbuf (current-buffer))
9952 (region (if (org-region-active-p)
9953 (buffer-substring (region-beginning) (region-end))))
9954 (remove (and region (list (region-beginning) (region-end))))
9955 (desc region)
9956 tmphist ; byte-compile incorrectly complains about this
9957 (link link-location)
9958 (abbrevs org-link-abbrev-alist-local)
9959 entry file all-prefixes auto-desc)
9960 (cond
9961 (link-location) ; specified by arg, just use it.
9962 ((org-in-regexp org-bracket-link-regexp 1)
9963 ;; We do have a link at point, and we are going to edit it.
9964 (setq remove (list (match-beginning 0) (match-end 0)))
9965 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9966 (setq link (read-string "Link: "
9967 (org-link-unescape
9968 (org-match-string-no-properties 1)))))
9969 ((or (org-in-regexp org-angle-link-re)
9970 (org-in-regexp org-plain-link-re))
9971 ;; Convert to bracket link
9972 (setq remove (list (match-beginning 0) (match-end 0))
9973 link (read-string "Link: "
9974 (org-remove-angle-brackets (match-string 0)))))
9975 ((member complete-file '((4) (16)))
9976 ;; Completing read for file names.
9977 (setq link (org-file-complete-link complete-file)))
9978 (t
9979 ;; Read link, with completion for stored links.
9980 (org-link-fontify-links-to-this-file)
9981 (org-switch-to-buffer-other-window "*Org Links*")
9982 (with-current-buffer "*Org Links*"
9983 (erase-buffer)
9984 (insert "Insert a link.
9985 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9986 (when org-stored-links
9987 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9988 (insert (mapconcat 'org-link-prettify
9989 (reverse org-stored-links) "\n")))
9990 (goto-char (point-min)))
9991 (let ((cw (selected-window)))
9992 (select-window (get-buffer-window "*Org Links*" 'visible))
9993 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9994 (unless (pos-visible-in-window-p (point-max))
9995 (org-fit-window-to-buffer))
9996 (and (window-live-p cw) (select-window cw)))
9997 ;; Fake a link history, containing the stored links.
9998 (setq tmphist (append (mapcar 'car org-stored-links)
9999 org-insert-link-history))
10000 (setq all-prefixes (append (mapcar 'car abbrevs)
10001 (mapcar 'car org-link-abbrev-alist)
10002 org-link-types))
10003 (unwind-protect
10004 (progn
10005 (setq link
10006 (org-completing-read
10007 "Link: "
10008 (append
10009 (mapcar (lambda (x) (concat x ":"))
10010 all-prefixes)
10011 (mapcar 'car org-stored-links))
10012 nil nil nil
10013 'tmphist
10014 (caar org-stored-links)))
10015 (if (not (string-match "\\S-" link))
10016 (user-error "No link selected"))
10017 (mapc (lambda(l)
10018 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10019 org-stored-links)
10020 (if (or (member link all-prefixes)
10021 (and (equal ":" (substring link -1))
10022 (member (substring link 0 -1) all-prefixes)
10023 (setq link (substring link 0 -1))))
10024 (setq link (with-current-buffer origbuf
10025 (org-link-try-special-completion link)))))
10026 (set-window-configuration wcf)
10027 (kill-buffer "*Org Links*"))
10028 (setq entry (assoc link org-stored-links))
10029 (or entry (push link org-insert-link-history))
10030 (setq desc (or desc (nth 1 entry)))))
10031
10032 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10033 (not org-keep-stored-link-after-insertion))
10034 (setq org-stored-links (delq (assoc link org-stored-links)
10035 org-stored-links)))
10036
10037 (if (and (string-match org-plain-link-re link)
10038 (not (string-match org-ts-regexp link)))
10039 ;; URL-like link, normalize the use of angular brackets.
10040 (setq link (org-remove-angle-brackets link)))
10041
10042 ;; Check if we are linking to the current file with a search
10043 ;; option If yes, simplify the link by using only the search
10044 ;; option.
10045 (when (and buffer-file-name
10046 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10047 (let* ((path (match-string 1 link))
10048 (case-fold-search nil)
10049 (search (match-string 2 link)))
10050 (save-match-data
10051 (if (equal (file-truename buffer-file-name) (file-truename path))
10052 ;; We are linking to this same file, with a search option
10053 (setq link search)))))
10054
10055 ;; Check if we can/should use a relative path. If yes, simplify the link
10056 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10057 (let* ((type (match-string 1 link))
10058 (path (match-string 2 link))
10059 (origpath path)
10060 (case-fold-search nil))
10061 (cond
10062 ((or (eq org-link-file-path-type 'absolute)
10063 (equal complete-file '(16)))
10064 (setq path (abbreviate-file-name (expand-file-name path))))
10065 ((eq org-link-file-path-type 'noabbrev)
10066 (setq path (expand-file-name path)))
10067 ((eq org-link-file-path-type 'relative)
10068 (setq path (file-relative-name path)))
10069 (t
10070 (save-match-data
10071 (if (string-match (concat "^" (regexp-quote
10072 (expand-file-name
10073 (file-name-as-directory
10074 default-directory))))
10075 (expand-file-name path))
10076 ;; We are linking a file with relative path name.
10077 (setq path (substring (expand-file-name path)
10078 (match-end 0)))
10079 (setq path (abbreviate-file-name (expand-file-name path)))))))
10080 (setq link (concat type path))
10081 (if (equal desc origpath)
10082 (setq desc path))))
10083
10084 (if org-make-link-description-function
10085 (setq desc
10086 (or (condition-case nil
10087 (funcall org-make-link-description-function link desc)
10088 (error (progn (message "Can't get link description from `%s'"
10089 (symbol-name org-make-link-description-function))
10090 (sit-for 2) nil)))
10091 (read-string "Description: " default-description)))
10092 (if default-description (setq desc default-description)
10093 (setq desc (or (and auto-desc desc)
10094 (read-string "Description: " desc)))))
10095
10096 (unless (string-match "\\S-" desc) (setq desc nil))
10097 (if remove (apply 'delete-region remove))
10098 (insert (org-make-link-string link desc))))
10099
10100 (defun org-link-try-special-completion (type)
10101 "If there is completion support for link type TYPE, offer it."
10102 (let ((fun (intern (concat "org-" type "-complete-link"))))
10103 (if (functionp fun)
10104 (funcall fun)
10105 (read-string "Link (no completion support): " (concat type ":")))))
10106
10107 (defun org-file-complete-link (&optional arg)
10108 "Create a file link using completion."
10109 (let (file link)
10110 (setq file (org-iread-file-name "File: "))
10111 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10112 (pwd1 (file-name-as-directory (abbreviate-file-name
10113 (expand-file-name ".")))))
10114 (cond
10115 ((equal arg '(16))
10116 (setq link (concat
10117 "file:"
10118 (abbreviate-file-name (expand-file-name file)))))
10119 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10120 (setq link (concat "file:" (match-string 1 file))))
10121 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10122 (expand-file-name file))
10123 (setq link (concat
10124 "file:" (match-string 1 (expand-file-name file)))))
10125 (t (setq link (concat "file:" file)))))
10126 link))
10127
10128 (defun org-iread-file-name (&rest args)
10129 "Read-file-name using `ido-mode' speedup if available.
10130 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10131 See `read-file-name' for a description of parameters."
10132 (org-without-partial-completion
10133 (if (and org-completion-use-ido
10134 (fboundp 'ido-read-file-name)
10135 (boundp 'ido-mode) ido-mode
10136 (listp (second args)))
10137 (let ((ido-enter-matching-directory nil))
10138 (apply 'ido-read-file-name args))
10139 (apply 'read-file-name args))))
10140
10141 (defun org-completing-read (&rest args)
10142 "Completing-read with SPACE being a normal character."
10143 (let ((enable-recursive-minibuffers t)
10144 (minibuffer-local-completion-map
10145 (copy-keymap minibuffer-local-completion-map)))
10146 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10147 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10148 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10149 (apply 'org-icompleting-read args)))
10150
10151 (defun org-completing-read-no-i (&rest args)
10152 (let (org-completion-use-ido org-completion-use-iswitchb)
10153 (apply 'org-completing-read args)))
10154
10155 (defun org-iswitchb-completing-read (prompt choices &rest args)
10156 "Use iswitch as a completing-read replacement to choose from choices.
10157 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10158 from."
10159 (let* ((iswitchb-use-virtual-buffers nil)
10160 (iswitchb-make-buflist-hook
10161 (lambda ()
10162 (setq iswitchb-temp-buflist choices))))
10163 (iswitchb-read-buffer prompt)))
10164
10165 (defun org-icompleting-read (&rest args)
10166 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10167 (org-without-partial-completion
10168 (if (and org-completion-use-ido
10169 (fboundp 'ido-completing-read)
10170 (boundp 'ido-mode) ido-mode
10171 (listp (second args)))
10172 (let ((ido-enter-matching-directory nil))
10173 (apply 'ido-completing-read (concat (car args))
10174 (if (consp (car (nth 1 args)))
10175 (mapcar 'car (nth 1 args))
10176 (nth 1 args))
10177 (cddr args)))
10178 (if (and org-completion-use-iswitchb
10179 (boundp 'iswitchb-mode) iswitchb-mode
10180 (listp (second args)))
10181 (apply 'org-iswitchb-completing-read (concat (car args))
10182 (if (consp (car (nth 1 args)))
10183 (mapcar 'car (nth 1 args))
10184 (nth 1 args))
10185 (cddr args))
10186 (apply 'completing-read args)))))
10187
10188 (defun org-extract-attributes (s)
10189 "Extract the attributes cookie from a string and set as text property."
10190 (let (a attr (start 0) key value)
10191 (save-match-data
10192 (when (string-match "{{\\([^}]+\\)}}$" s)
10193 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10194 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10195 (setq key (match-string 1 a) value (match-string 2 a)
10196 start (match-end 0)
10197 attr (plist-put attr (intern key) value))))
10198 (org-add-props s nil 'org-attr attr))
10199 s))
10200
10201 ;;; Opening/following a link
10202
10203 (defvar org-link-search-failed nil)
10204
10205 (defvar org-open-link-functions nil
10206 "Hook for functions finding a plain text link.
10207 These functions must take a single argument, the link content.
10208 They will be called for links that look like [[link text][description]]
10209 when LINK TEXT does not have a protocol like \"http:\" and does not look
10210 like a filename (e.g. \"./blue.png\").
10211
10212 These functions will be called *before* Org attempts to resolve the
10213 link by doing text searches in the current buffer - so if you want a
10214 link \"[[target]]\" to still find \"<<target>>\", your function should
10215 handle this as a special case.
10216
10217 When the function does handle the link, it must return a non-nil value.
10218 If it decides that it is not responsible for this link, it must return
10219 nil to indicate that that Org-mode can continue with other options
10220 like exact and fuzzy text search.")
10221
10222 (defun org-next-link (&optional search-backward)
10223 "Move forward to the next link.
10224 If the link is in hidden text, expose it."
10225 (interactive "P")
10226 (when (and org-link-search-failed (eq this-command last-command))
10227 (goto-char (point-min))
10228 (message "Link search wrapped back to beginning of buffer"))
10229 (setq org-link-search-failed nil)
10230 (let* ((pos (point))
10231 (ct (org-context))
10232 (a (assoc :link ct))
10233 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10234 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10235 ((looking-at org-any-link-re)
10236 ;; Don't stay stuck at link without an org-link face
10237 (forward-char (if search-backward -1 1))))
10238 (if (funcall srch-fun org-any-link-re nil t)
10239 (progn
10240 (goto-char (match-beginning 0))
10241 (if (outline-invisible-p) (org-show-context)))
10242 (goto-char pos)
10243 (setq org-link-search-failed t)
10244 (message "No further link found"))))
10245
10246 (defun org-previous-link ()
10247 "Move backward to the previous link.
10248 If the link is in hidden text, expose it."
10249 (interactive)
10250 (funcall 'org-next-link t))
10251
10252 (defun org-translate-link (s)
10253 "Translate a link string if a translation function has been defined."
10254 (if (and org-link-translation-function
10255 (fboundp org-link-translation-function)
10256 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10257 (progn
10258 (setq s (funcall org-link-translation-function
10259 (match-string 1 s) (match-string 2 s)))
10260 (concat (car s) ":" (cdr s)))
10261 s))
10262
10263 (defun org-translate-link-from-planner (type path)
10264 "Translate a link from Emacs Planner syntax so that Org can follow it.
10265 This is still an experimental function, your mileage may vary."
10266 (cond
10267 ((member type '("http" "https" "news" "ftp"))
10268 ;; standard Internet links are the same.
10269 nil)
10270 ((and (equal type "irc") (string-match "^//" path))
10271 ;; Planner has two / at the beginning of an irc link, we have 1.
10272 ;; We should have zero, actually....
10273 (setq path (substring path 1)))
10274 ((and (equal type "lisp") (string-match "^/" path))
10275 ;; Planner has a slash, we do not.
10276 (setq type "elisp" path (substring path 1)))
10277 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10278 ;; A typical message link. Planner has the id after the final slash,
10279 ;; we separate it with a hash mark
10280 (setq path (concat (match-string 1 path) "#"
10281 (org-remove-angle-brackets (match-string 2 path))))))
10282 (cons type path))
10283
10284 (defun org-find-file-at-mouse (ev)
10285 "Open file link or URL at mouse."
10286 (interactive "e")
10287 (mouse-set-point ev)
10288 (org-open-at-point 'in-emacs))
10289
10290 (defun org-open-at-mouse (ev)
10291 "Open file link or URL at mouse.
10292 See the docstring of `org-open-file' for details."
10293 (interactive "e")
10294 (mouse-set-point ev)
10295 (if (eq major-mode 'org-agenda-mode)
10296 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10297 (org-open-at-point))
10298
10299 (defvar org-window-config-before-follow-link nil
10300 "The window configuration before following a link.
10301 This is saved in case the need arises to restore it.")
10302
10303 (defvar org-open-link-marker (make-marker)
10304 "Marker pointing to the location where `org-open-at-point' was called.")
10305
10306 ;;;###autoload
10307 (defun org-open-at-point-global ()
10308 "Follow a link like Org-mode does.
10309 This command can be called in any mode to follow a link that has
10310 Org-mode syntax."
10311 (interactive)
10312 (org-run-like-in-org-mode 'org-open-at-point))
10313
10314 ;;;###autoload
10315 (defun org-open-link-from-string (s &optional arg reference-buffer)
10316 "Open a link in the string S, as if it was in Org-mode."
10317 (interactive "sLink: \nP")
10318 (let ((reference-buffer (or reference-buffer (current-buffer))))
10319 (with-temp-buffer
10320 (let ((org-inhibit-startup (not reference-buffer)))
10321 (org-mode)
10322 (insert s)
10323 (goto-char (point-min))
10324 (when reference-buffer
10325 (setq org-link-abbrev-alist-local
10326 (with-current-buffer reference-buffer
10327 org-link-abbrev-alist-local)))
10328 (org-open-at-point arg reference-buffer)))))
10329
10330 (defvar org-open-at-point-functions nil
10331 "Hook that is run when following a link at point.
10332
10333 Functions in this hook must return t if they identify and follow
10334 a link at point. If they don't find anything interesting at point,
10335 they must return nil.")
10336
10337 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10338 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10339 (defun org-open-at-point (&optional arg reference-buffer)
10340 "Open link at or after point.
10341 If there is no link at point, this function will search forward up to
10342 the end of the current line.
10343 Normally, files will be opened by an appropriate application. If the
10344 optional prefix argument ARG is non-nil, Emacs will visit the file.
10345 With a double prefix argument, try to open outside of Emacs, in the
10346 application the system uses for this file type."
10347 (interactive "P")
10348 ;; if in a code block, then open the block's results
10349 (unless (call-interactively #'org-babel-open-src-block-result)
10350 (org-load-modules-maybe)
10351 (move-marker org-open-link-marker (point))
10352 (setq org-window-config-before-follow-link (current-window-configuration))
10353 (org-remove-occur-highlights nil nil t)
10354 (cond
10355 ((and (org-at-heading-p)
10356 (not (org-at-timestamp-p t))
10357 (not (org-in-regexp
10358 (concat org-plain-link-re "\\|"
10359 org-bracket-link-regexp "\\|"
10360 org-angle-link-re "\\|"
10361 "[ \t]:[^ \t\n]+:[ \t]*$")))
10362 (not (get-text-property (point) 'org-linked-text)))
10363 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10364 (lk0 (car lkall))
10365 (lk (if (stringp lk0) (list lk0) lk0))
10366 (lkend (cdr lkall)))
10367 (mapcar (lambda(l)
10368 (search-forward l nil lkend)
10369 (goto-char (match-beginning 0))
10370 (org-open-at-point))
10371 lk))
10372 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10373 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10374 ((and (org-at-timestamp-p t)
10375 (not (org-in-regexp org-bracket-link-regexp)))
10376 (org-follow-timestamp-link))
10377 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10378 (not (org-in-regexp org-any-link-re)))
10379 (org-footnote-action))
10380 (t
10381 (let (type path link line search (pos (point)))
10382 (catch 'match
10383 (save-excursion
10384 (or (org-in-regexp org-plain-link-re)
10385 (skip-chars-forward "^]\n\r"))
10386 (when (org-in-regexp org-bracket-link-regexp 1)
10387 (setq link (org-extract-attributes
10388 (org-link-unescape (org-match-string-no-properties 1))))
10389 (while (string-match " *\n *" link)
10390 (setq link (replace-match " " t t link)))
10391 (setq link (org-link-expand-abbrev link))
10392 (cond
10393 ((or (file-name-absolute-p link)
10394 (string-match "^\\.\\.?/" link))
10395 (setq type "file" path link))
10396 ((string-match org-link-re-with-space3 link)
10397 (setq type (match-string 1 link) path (match-string 2 link)))
10398 ((string-match "^help:+\\(.+\\)" link)
10399 (setq type "help" path (match-string 1 link)))
10400 (t (setq type "thisfile" path link)))
10401 (throw 'match t)))
10402
10403 (when (get-text-property (point) 'org-linked-text)
10404 (setq type "thisfile"
10405 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10406 (1+ (point)) (point))
10407 path (buffer-substring
10408 (or (previous-single-property-change pos 'org-linked-text)
10409 (point-min))
10410 (or (next-single-property-change pos 'org-linked-text)
10411 (point-max)))
10412 ;; Ensure we will search for a <<<radio>>> link, not
10413 ;; a simple reference like <<ref>>
10414 path (concat "<" path))
10415 (throw 'match t))
10416
10417 (save-excursion
10418 (when (or (org-in-regexp org-angle-link-re)
10419 (let ((match (org-in-regexp org-plain-link-re)))
10420 ;; Check a plain link is not within a bracket link
10421 (and match
10422 (save-excursion
10423 (save-match-data
10424 (progn
10425 (goto-char (car match))
10426 (not (org-in-regexp org-bracket-link-regexp)))))))
10427 (let ((line_ending (save-excursion (end-of-line) (point))))
10428 ;; We are in a line before a plain or bracket link
10429 (or (re-search-forward org-plain-link-re line_ending t)
10430 (re-search-forward org-bracket-link-regexp line_ending t))))
10431 (setq type (match-string 1)
10432 path (org-link-unescape (match-string 2)))
10433 (throw 'match t)))
10434 (save-excursion
10435 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10436 (setq type "tags"
10437 path (match-string 1))
10438 (while (string-match ":" path)
10439 (setq path (replace-match "+" t t path)))
10440 (throw 'match t)))
10441 (when (org-in-regexp "<\\([^><\n]+\\)>")
10442 (setq type "tree-match"
10443 path (match-string 1))
10444 (throw 'match t)))
10445 (unless path
10446 (user-error "No link found"))
10447
10448 ;; switch back to reference buffer
10449 ;; needed when if called in a temporary buffer through
10450 ;; org-open-link-from-string
10451 (with-current-buffer (or reference-buffer (current-buffer))
10452
10453 ;; Remove any trailing spaces in path
10454 (if (string-match " +\\'" path)
10455 (setq path (replace-match "" t t path)))
10456 (if (and org-link-translation-function
10457 (fboundp org-link-translation-function))
10458 ;; Check if we need to translate the link
10459 (let ((tmp (funcall org-link-translation-function type path)))
10460 (setq type (car tmp) path (cdr tmp))))
10461
10462 (cond
10463
10464 ((assoc type org-link-protocols)
10465 (funcall (nth 1 (assoc type org-link-protocols)) path))
10466
10467 ((equal type "help")
10468 (let ((f-or-v (intern path)))
10469 (cond ((fboundp f-or-v)
10470 (describe-function f-or-v))
10471 ((boundp f-or-v)
10472 (describe-variable f-or-v))
10473 (t (error "Not a known function or variable")))))
10474
10475 ((equal type "mailto")
10476 (let ((cmd (car org-link-mailto-program))
10477 (args (cdr org-link-mailto-program)) args1
10478 (address path) (subject "") a)
10479 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10480 (setq address (match-string 1 path)
10481 subject (org-link-escape (match-string 2 path))))
10482 (while args
10483 (cond
10484 ((not (stringp (car args))) (push (pop args) args1))
10485 (t (setq a (pop args))
10486 (if (string-match "%a" a)
10487 (setq a (replace-match address t t a)))
10488 (if (string-match "%s" a)
10489 (setq a (replace-match subject t t a)))
10490 (push a args1))))
10491 (apply cmd (nreverse args1))))
10492
10493 ((member type '("http" "https" "ftp" "news"))
10494 (browse-url
10495 (concat type ":"
10496 (if (org-string-match-p
10497 (concat "[[:nonascii:]"
10498 org-link-escape-chars-browser "]")
10499 path)
10500 (org-link-escape path org-link-escape-chars-browser)
10501 path))))
10502
10503 ((string= type "doi")
10504 (browse-url
10505 (concat org-doi-server-url
10506 (if (org-string-match-p
10507 (concat "[[:nonascii:]"
10508 org-link-escape-chars-browser "]")
10509 path)
10510 (org-link-escape path org-link-escape-chars-browser)
10511 path))))
10512
10513 ((member type '("message"))
10514 (browse-url (concat type ":" path)))
10515
10516 ((string= type "tags")
10517 (org-tags-view arg path))
10518
10519 ((string= type "tree-match")
10520 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10521
10522 ((string= type "file")
10523 (if (string-match "::\\([0-9]+\\)\\'" path)
10524 (setq line (string-to-number (match-string 1 path))
10525 path (substring path 0 (match-beginning 0)))
10526 (if (string-match "::\\(.+\\)\\'" path)
10527 (setq search (match-string 1 path)
10528 path (substring path 0 (match-beginning 0)))))
10529 (if (string-match "[*?{]" (file-name-nondirectory path))
10530 (dired path)
10531 (org-open-file path arg line search)))
10532
10533 ((string= type "shell")
10534 (let ((buf (generate-new-buffer "*Org Shell Output"))
10535 (cmd path))
10536 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10537 (string-match org-confirm-shell-link-not-regexp cmd))
10538 (not org-confirm-shell-link-function)
10539 (funcall org-confirm-shell-link-function
10540 (format "Execute \"%s\" in shell? "
10541 (org-add-props cmd nil
10542 'face 'org-warning))))
10543 (progn
10544 (message "Executing %s" cmd)
10545 (shell-command cmd buf)
10546 (if (featurep 'midnight)
10547 (setq clean-buffer-list-kill-buffer-names
10548 (cons buf clean-buffer-list-kill-buffer-names))))
10549 (error "Abort"))))
10550
10551 ((string= type "elisp")
10552 (let ((cmd path))
10553 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10554 (string-match org-confirm-elisp-link-not-regexp cmd))
10555 (not org-confirm-elisp-link-function)
10556 (funcall org-confirm-elisp-link-function
10557 (format "Execute \"%s\" as elisp? "
10558 (org-add-props cmd nil
10559 'face 'org-warning))))
10560 (message "%s => %s" cmd
10561 (if (equal (string-to-char cmd) ?\()
10562 (eval (read cmd))
10563 (call-interactively (read cmd))))
10564 (error "Abort"))))
10565
10566 ((and (string= type "thisfile")
10567 (or (run-hook-with-args-until-success
10568 'org-open-link-functions path)
10569 (and link
10570 (string-match "^id:" link)
10571 (or (featurep 'org-id) (require 'org-id))
10572 (progn
10573 (funcall (nth 1 (assoc "id" org-link-protocols))
10574 (substring path 3))
10575 t)))))
10576
10577 ((string= type "thisfile")
10578 (if arg
10579 (switch-to-buffer-other-window
10580 (org-get-buffer-for-internal-link (current-buffer)))
10581 (org-mark-ring-push))
10582 (let ((cmd `(org-link-search
10583 ,path
10584 ,(cond ((equal arg '(4)) ''occur)
10585 ((equal arg '(16)) ''org-occur))
10586 ,pos)))
10587 (condition-case nil (let ((org-link-search-inhibit-query t))
10588 (eval cmd))
10589 (error (progn (widen) (eval cmd))))))
10590
10591 (t (browse-url-at-point)))))))
10592 (move-marker org-open-link-marker nil)
10593 (run-hook-with-args 'org-follow-link-hook)))
10594
10595 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10596 "Offer links in the current entry and return the selected link.
10597 If there is only one link, return it.
10598 If NTH is an integer, return the NTH link found.
10599 If ZERO is a string, check also this string for a link, and if
10600 there is one, return it."
10601 (with-current-buffer buffer
10602 (save-excursion
10603 (save-restriction
10604 (widen)
10605 (goto-char marker)
10606 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10607 "\\(" org-angle-link-re "\\)\\|"
10608 "\\(" org-plain-link-re "\\)"))
10609 (cnt ?0)
10610 (in-emacs (if (integerp nth) nil nth))
10611 have-zero end links link c)
10612 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10613 (push (match-string 0 zero) links)
10614 (setq cnt (1- cnt) have-zero t))
10615 (save-excursion
10616 (org-back-to-heading t)
10617 (setq end (save-excursion (outline-next-heading) (point)))
10618 (while (re-search-forward re end t)
10619 (push (match-string 0) links))
10620 (setq links (org-uniquify (reverse links))))
10621 (cond
10622 ((null links)
10623 (message "No links"))
10624 ((equal (length links) 1)
10625 (setq link (car links)))
10626 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10627 (setq link (nth (if have-zero nth (1- nth)) links)))
10628 (t ; we have to select a link
10629 (save-excursion
10630 (save-window-excursion
10631 (delete-other-windows)
10632 (with-output-to-temp-buffer "*Select Link*"
10633 (mapc (lambda (l)
10634 (if (not (string-match org-bracket-link-regexp l))
10635 (princ (format "[%c] %s\n" (incf cnt)
10636 (org-remove-angle-brackets l)))
10637 (if (match-end 3)
10638 (princ (format "[%c] %s (%s)\n" (incf cnt)
10639 (match-string 3 l) (match-string 1 l)))
10640 (princ (format "[%c] %s\n" (incf cnt)
10641 (match-string 1 l))))))
10642 links))
10643 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10644 (message "Select link to open, RET to open all:")
10645 (setq c (read-char-exclusive))
10646 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10647 (when (equal c ?q) (error "Abort"))
10648 (if (equal c ?\C-m)
10649 (setq link links)
10650 (setq nth (- c ?0))
10651 (if have-zero (setq nth (1+ nth)))
10652 (unless (and (integerp nth) (>= (length links) nth))
10653 (user-error "Invalid link selection"))
10654 (setq link (nth (1- nth) links)))))
10655 (cons link end))))))
10656
10657 ;; Add special file links that specify the way of opening
10658
10659 (org-add-link-type "file+sys" 'org-open-file-with-system)
10660 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10661 (defun org-open-file-with-system (path)
10662 "Open file at PATH using the system way of opening it."
10663 (org-open-file path 'system))
10664 (defun org-open-file-with-emacs (path)
10665 "Open file at PATH in Emacs."
10666 (org-open-file path 'emacs))
10667
10668
10669 ;;; File search
10670
10671 (defvar org-create-file-search-functions nil
10672 "List of functions to construct the right search string for a file link.
10673 These functions are called in turn with point at the location to
10674 which the link should point.
10675
10676 A function in the hook should first test if it would like to
10677 handle this file type, for example by checking the `major-mode'
10678 or the file extension. If it decides not to handle this file, it
10679 should just return nil to give other functions a chance. If it
10680 does handle the file, it must return the search string to be used
10681 when following the link. The search string will be part of the
10682 file link, given after a double colon, and `org-open-at-point'
10683 will automatically search for it. If special measures must be
10684 taken to make the search successful, another function should be
10685 added to the companion hook `org-execute-file-search-functions',
10686 which see.
10687
10688 A function in this hook may also use `setq' to set the variable
10689 `description' to provide a suggestion for the descriptive text to
10690 be used for this link when it gets inserted into an Org-mode
10691 buffer with \\[org-insert-link].")
10692
10693 (defvar org-execute-file-search-functions nil
10694 "List of functions to execute a file search triggered by a link.
10695
10696 Functions added to this hook must accept a single argument, the
10697 search string that was part of the file link, the part after the
10698 double colon. The function must first check if it would like to
10699 handle this search, for example by checking the `major-mode' or
10700 the file extension. If it decides not to handle this search, it
10701 should just return nil to give other functions a chance. If it
10702 does handle the search, it must return a non-nil value to keep
10703 other functions from trying.
10704
10705 Each function can access the current prefix argument through the
10706 variable `current-prefix-arg'. Note that a single prefix is used
10707 to force opening a link in Emacs, so it may be good to only use a
10708 numeric or double prefix to guide the search function.
10709
10710 In case this is needed, a function in this hook can also restore
10711 the window configuration before `org-open-at-point' was called using:
10712
10713 (set-window-configuration org-window-config-before-follow-link)")
10714
10715 (defun org-link-search (s &optional type avoid-pos stealth)
10716 "Search for a link search option.
10717 If S is surrounded by forward slashes, it is interpreted as a
10718 regular expression. In org-mode files, this will create an `org-occur'
10719 sparse tree. In ordinary files, `occur' will be used to list matches.
10720 If the current buffer is in `dired-mode', grep will be used to search
10721 in all files. If AVOID-POS is given, ignore matches near that position.
10722
10723 When optional argument STEALTH is non-nil, do not modify
10724 visibility around point, thus ignoring
10725 `org-show-hierarchy-above', `org-show-following-heading' and
10726 `org-show-siblings' variables."
10727 (let ((case-fold-search t)
10728 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10729 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10730 (append '(("") (" ") ("\t") ("\n"))
10731 org-emphasis-alist)
10732 "\\|") "\\)"))
10733 (pos (point))
10734 (pre nil) (post nil)
10735 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10736 (cond
10737 ;; First check if there are any special search functions
10738 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10739 ;; Now try the builtin stuff
10740 ((and (equal (string-to-char s0) ?#)
10741 (> (length s0) 1)
10742 (save-excursion
10743 (goto-char (point-min))
10744 (and
10745 (re-search-forward
10746 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10747 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10748 (setq type 'dedicated
10749 pos (match-beginning 0))))
10750 ;; There is an exact target for this
10751 (goto-char pos)
10752 (org-back-to-heading t)))
10753 ((save-excursion
10754 (goto-char (point-min))
10755 (and
10756 (re-search-forward
10757 (concat "<<" (regexp-quote s0) ">>") nil t)
10758 (setq type 'dedicated
10759 pos (match-beginning 0))))
10760 ;; There is an exact target for this
10761 (goto-char pos))
10762 ((save-excursion
10763 (goto-char (point-min))
10764 (and
10765 (re-search-forward
10766 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10767 (setq type 'dedicated pos (match-beginning 0))))
10768 ;; Found an element with a matching #+name affiliated keyword.
10769 (goto-char pos))
10770 ((and (string-match "^(\\(.*\\))$" s0)
10771 (save-excursion
10772 (goto-char (point-min))
10773 (and
10774 (re-search-forward
10775 (concat "[^[]" (regexp-quote
10776 (format org-coderef-label-format
10777 (match-string 1 s0))))
10778 nil t)
10779 (setq type 'dedicated
10780 pos (1+ (match-beginning 0))))))
10781 ;; There is a coderef target for this
10782 (goto-char pos))
10783 ((string-match "^/\\(.*\\)/$" s)
10784 ;; A regular expression
10785 (cond
10786 ((derived-mode-p 'org-mode)
10787 (org-occur (match-string 1 s)))
10788 (t (org-do-occur (match-string 1 s)))))
10789 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10790 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10791 (goto-char (point-min))
10792 (cond
10793 ((let (case-fold-search)
10794 (re-search-forward (format org-complex-heading-regexp-format
10795 (regexp-quote s))
10796 nil t))
10797 ;; OK, found a match
10798 (setq type 'dedicated)
10799 (goto-char (match-beginning 0)))
10800 ((and (not org-link-search-inhibit-query)
10801 (eq org-link-search-must-match-exact-headline 'query-to-create)
10802 (y-or-n-p "No match - create this as a new heading? "))
10803 (goto-char (point-max))
10804 (or (bolp) (newline))
10805 (insert "* " s "\n")
10806 (beginning-of-line 0))
10807 (t
10808 (goto-char pos)
10809 (error "No match"))))
10810 (t
10811 ;; A normal search string
10812 (when (equal (string-to-char s) ?*)
10813 ;; Anchor on headlines, post may include tags.
10814 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10815 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10816 s (substring s 1)))
10817 (remove-text-properties
10818 0 (length s)
10819 '(face nil mouse-face nil keymap nil fontified nil) s)
10820 ;; Make a series of regular expressions to find a match
10821 (setq words (org-split-string s "[ \n\r\t]+")
10822
10823 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10824 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10825 "\\)" markers)
10826 re2a_ (concat "\\(" (mapconcat 'downcase words
10827 "[ \t\r\n]+") "\\)[ \t\r\n]")
10828 re2a (concat "[ \t\r\n]" re2a_)
10829 re4_ (concat "\\(" (mapconcat 'downcase words
10830 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10831 re4 (concat "[^a-zA-Z_]" re4_)
10832
10833 re1 (concat pre re2 post)
10834 re3 (concat pre (if pre re4_ re4) post)
10835 re5 (concat pre ".*" re4)
10836 re2 (concat pre re2)
10837 re2a (concat pre (if pre re2a_ re2a))
10838 re4 (concat pre (if pre re4_ re4))
10839 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10840 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10841 re5 "\\)"))
10842 (cond
10843 ((eq type 'org-occur) (org-occur reall))
10844 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10845 (t (goto-char (point-min))
10846 (setq type 'fuzzy)
10847 (if (or (and (org-search-not-self 1 re0 nil t)
10848 (setq type 'dedicated))
10849 (org-search-not-self 1 re1 nil t)
10850 (org-search-not-self 1 re2 nil t)
10851 (org-search-not-self 1 re2a nil t)
10852 (org-search-not-self 1 re3 nil t)
10853 (org-search-not-self 1 re4 nil t)
10854 (org-search-not-self 1 re5 nil t))
10855 (goto-char (match-beginning 1))
10856 (goto-char pos)
10857 (error "No match"))))))
10858 (and (derived-mode-p 'org-mode)
10859 (not stealth)
10860 (org-show-context 'link-search))
10861 type))
10862
10863 (defun org-search-not-self (group &rest args)
10864 "Execute `re-search-forward', but only accept matches that do not
10865 enclose the position of `org-open-link-marker'."
10866 (let ((m org-open-link-marker))
10867 (catch 'exit
10868 (while (apply 're-search-forward args)
10869 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10870 (goto-char (match-end group))
10871 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10872 (> (match-beginning 0) (marker-position m))
10873 (< (match-end 0) (marker-position m)))
10874 (save-match-data
10875 (or (not (org-in-regexp
10876 org-bracket-link-analytic-regexp 1))
10877 (not (match-end 4)) ; no description
10878 (and (<= (match-beginning 4) (point))
10879 (>= (match-end 4) (point))))))
10880 (throw 'exit (point))))))))
10881
10882 (defun org-get-buffer-for-internal-link (buffer)
10883 "Return a buffer to be used for displaying the link target of internal links."
10884 (cond
10885 ((not org-display-internal-link-with-indirect-buffer)
10886 buffer)
10887 ((string-match "(Clone)$" (buffer-name buffer))
10888 (message "Buffer is already a clone, not making another one")
10889 ;; we also do not modify visibility in this case
10890 buffer)
10891 (t ; make a new indirect buffer for displaying the link
10892 (let* ((bn (buffer-name buffer))
10893 (ibn (concat bn "(Clone)"))
10894 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10895 (with-current-buffer ib (org-overview))
10896 ib))))
10897
10898 (defun org-do-occur (regexp &optional cleanup)
10899 "Call the Emacs command `occur'.
10900 If CLEANUP is non-nil, remove the printout of the regular expression
10901 in the *Occur* buffer. This is useful if the regex is long and not useful
10902 to read."
10903 (occur regexp)
10904 (when cleanup
10905 (let ((cwin (selected-window)) win beg end)
10906 (when (setq win (get-buffer-window "*Occur*"))
10907 (select-window win))
10908 (goto-char (point-min))
10909 (when (re-search-forward "match[a-z]+" nil t)
10910 (setq beg (match-end 0))
10911 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10912 (setq end (1- (match-beginning 0)))))
10913 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10914 (goto-char (point-min))
10915 (select-window cwin))))
10916
10917 ;;; The mark ring for links jumps
10918
10919 (defvar org-mark-ring nil
10920 "Mark ring for positions before jumps in Org-mode.")
10921 (defvar org-mark-ring-last-goto nil
10922 "Last position in the mark ring used to go back.")
10923 ;; Fill and close the ring
10924 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10925 (loop for i from 1 to org-mark-ring-length do
10926 (push (make-marker) org-mark-ring))
10927 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10928 org-mark-ring)
10929
10930 (defun org-mark-ring-push (&optional pos buffer)
10931 "Put the current position or POS into the mark ring and rotate it."
10932 (interactive)
10933 (setq pos (or pos (point)))
10934 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10935 (move-marker (car org-mark-ring)
10936 (or pos (point))
10937 (or buffer (current-buffer)))
10938 (message "%s"
10939 (substitute-command-keys
10940 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10941
10942 (defun org-mark-ring-goto (&optional n)
10943 "Jump to the previous position in the mark ring.
10944 With prefix arg N, jump back that many stored positions. When
10945 called several times in succession, walk through the entire ring.
10946 Org-mode commands jumping to a different position in the current file,
10947 or to another Org-mode file, automatically push the old position
10948 onto the ring."
10949 (interactive "p")
10950 (let (p m)
10951 (if (eq last-command this-command)
10952 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10953 (setq p org-mark-ring))
10954 (setq org-mark-ring-last-goto p)
10955 (setq m (car p))
10956 (org-pop-to-buffer-same-window (marker-buffer m))
10957 (goto-char m)
10958 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10959
10960 (defun org-remove-angle-brackets (s)
10961 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10962 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10963 s)
10964 (defun org-add-angle-brackets (s)
10965 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10966 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10967 s)
10968 (defun org-remove-double-quotes (s)
10969 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10970 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10971 s)
10972
10973 ;;; Following specific links
10974
10975 (defun org-follow-timestamp-link ()
10976 "Open an agenda view for the time-stamp date/range at point."
10977 (cond
10978 ((org-at-date-range-p t)
10979 (let ((org-agenda-start-on-weekday)
10980 (t1 (match-string 1))
10981 (t2 (match-string 2)) tt1 tt2)
10982 (setq tt1 (time-to-days (org-time-string-to-time t1))
10983 tt2 (time-to-days (org-time-string-to-time t2)))
10984 (let ((org-agenda-buffer-tmp-name
10985 (format "*Org Agenda(a:%s)"
10986 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10987 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10988 ((org-at-timestamp-p t)
10989 (let ((org-agenda-buffer-tmp-name
10990 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10991 (org-agenda-list nil (time-to-days (org-time-string-to-time
10992 (substring (match-string 1) 0 10)))
10993 1)))
10994 (t (error "This should not happen"))))
10995
10996
10997 ;;; Following file links
10998 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10999 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11000 (declare-function mailcap-mime-info
11001 "mailcap" (string &optional request no-decode))
11002 (defvar org-wait nil)
11003 (defun org-open-file (path &optional in-emacs line search)
11004 "Open the file at PATH.
11005 First, this expands any special file name abbreviations. Then the
11006 configuration variable `org-file-apps' is checked if it contains an
11007 entry for this file type, and if yes, the corresponding command is launched.
11008
11009 If no application is found, Emacs simply visits the file.
11010
11011 With optional prefix argument IN-EMACS, Emacs will visit the file.
11012 With a double \\[universal-argument] \\[universal-argument] \
11013 prefix arg, Org tries to avoid opening in Emacs
11014 and to use an external application to visit the file.
11015
11016 Optional LINE specifies a line to go to, optional SEARCH a string
11017 to search for. If LINE or SEARCH is given, the file will be
11018 opened in Emacs, unless an entry from org-file-apps that makes
11019 use of groups in a regexp matches.
11020
11021 If you want to change the way frames are used when following a
11022 link, please customize `org-link-frame-setup'.
11023
11024 If the file does not exist, an error is thrown."
11025 (let* ((file (if (equal path "")
11026 buffer-file-name
11027 (substitute-in-file-name (expand-file-name path))))
11028 (file-apps (append org-file-apps (org-default-apps)))
11029 (apps (org-remove-if
11030 'org-file-apps-entry-match-against-dlink-p file-apps))
11031 (apps-dlink (org-remove-if-not
11032 'org-file-apps-entry-match-against-dlink-p file-apps))
11033 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11034 (dirp (if remp nil (file-directory-p file)))
11035 (file (if (and dirp org-open-directory-means-index-dot-org)
11036 (concat (file-name-as-directory file) "index.org")
11037 file))
11038 (a-m-a-p (assq 'auto-mode apps))
11039 (dfile (downcase file))
11040 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11041 (link (cond ((and (eq line nil)
11042 (eq search nil))
11043 file)
11044 (line
11045 (concat file "::" (number-to-string line)))
11046 (search
11047 (concat file "::" search))))
11048 (dlink (downcase link))
11049 (old-buffer (current-buffer))
11050 (old-pos (point))
11051 (old-mode major-mode)
11052 ext cmd link-match-data)
11053 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11054 (setq ext (match-string 1 dfile))
11055 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11056 (setq ext (match-string 1 dfile))))
11057 (cond
11058 ((member in-emacs '((16) system))
11059 (setq cmd (cdr (assoc 'system apps))))
11060 (in-emacs (setq cmd 'emacs))
11061 (t
11062 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11063 (and dirp (cdr (assoc 'directory apps)))
11064 ; first, try matching against apps-dlink
11065 ; if we get a match here, store the match data for later
11066 (let ((match (assoc-default dlink apps-dlink
11067 'string-match)))
11068 (if match
11069 (progn (setq link-match-data (match-data))
11070 match)
11071 (progn (setq in-emacs (or in-emacs line search))
11072 nil))) ; if we have no match in apps-dlink,
11073 ; always open the file in emacs if line or search
11074 ; is given (for backwards compatibility)
11075 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11076 'string-match)
11077 (cdr (assoc ext apps))
11078 (cdr (assoc t apps))))))
11079 (when (eq cmd 'system)
11080 (setq cmd (cdr (assoc 'system apps))))
11081 (when (eq cmd 'default)
11082 (setq cmd (cdr (assoc t apps))))
11083 (when (eq cmd 'mailcap)
11084 (require 'mailcap)
11085 (mailcap-parse-mailcaps)
11086 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11087 (command (mailcap-mime-info mime-type)))
11088 (if (stringp command)
11089 (setq cmd command)
11090 (setq cmd 'emacs))))
11091 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11092 (not (file-exists-p file))
11093 (not org-open-non-existing-files))
11094 (user-error "No such file: %s" file))
11095 (cond
11096 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11097 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11098 (while (string-match "['\"]%s['\"]" cmd)
11099 (setq cmd (replace-match "%s" t t cmd)))
11100 (while (string-match "%s" cmd)
11101 (setq cmd (replace-match
11102 (save-match-data
11103 (shell-quote-argument
11104 (convert-standard-filename file)))
11105 t t cmd)))
11106
11107 ;; Replace "%1", "%2" etc. in command with group matches from regex
11108 (save-match-data
11109 (let ((match-index 1)
11110 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11111 (set-match-data link-match-data)
11112 (while (<= match-index number-of-groups)
11113 (let ((regex (concat "%" (number-to-string match-index)))
11114 (replace-with (match-string match-index dlink)))
11115 (while (string-match regex cmd)
11116 (setq cmd (replace-match replace-with t t cmd))))
11117 (setq match-index (+ match-index 1)))))
11118
11119 (save-window-excursion
11120 (message "Running %s...done" cmd)
11121 (start-process-shell-command cmd nil cmd)
11122 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11123 ((or (stringp cmd)
11124 (eq cmd 'emacs))
11125 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11126 (widen)
11127 (if line (org-goto-line line)
11128 (if search (org-link-search search))))
11129 ((consp cmd)
11130 (let ((file (convert-standard-filename file)))
11131 (save-match-data
11132 (set-match-data link-match-data)
11133 (eval cmd))))
11134 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11135 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11136 (or (not (equal old-buffer (current-buffer)))
11137 (not (equal old-pos (point))))
11138 (org-mark-ring-push old-pos old-buffer))))
11139
11140 (defun org-file-apps-entry-match-against-dlink-p (entry)
11141 "This function returns non-nil if `entry' uses a regular
11142 expression which should be matched against the whole link by
11143 org-open-file.
11144
11145 It assumes that is the case when the entry uses a regular
11146 expression which has at least one grouping construct and the
11147 action is either a lisp form or a command string containing
11148 '%1', i.e. using at least one subexpression match as a
11149 parameter."
11150 (let ((selector (car entry))
11151 (action (cdr entry)))
11152 (if (stringp selector)
11153 (and (> (regexp-opt-depth selector) 0)
11154 (or (and (stringp action)
11155 (string-match "%[0-9]" action))
11156 (consp action)))
11157 nil)))
11158
11159 (defun org-default-apps ()
11160 "Return the default applications for this operating system."
11161 (cond
11162 ((eq system-type 'darwin)
11163 org-file-apps-defaults-macosx)
11164 ((eq system-type 'windows-nt)
11165 org-file-apps-defaults-windowsnt)
11166 (t org-file-apps-defaults-gnu)))
11167
11168 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11169 "Convert extensions to regular expressions in the cars of LIST.
11170 Also, weed out any non-string entries, because the return value is used
11171 only for regexp matching.
11172 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11173 point to the symbol `emacs', indicating that the file should
11174 be opened in Emacs."
11175 (append
11176 (delq nil
11177 (mapcar (lambda (x)
11178 (if (not (stringp (car x)))
11179 nil
11180 (if (string-match "\\W" (car x))
11181 x
11182 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11183 list))
11184 (if add-auto-mode
11185 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11186
11187 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11188 (defun org-file-remote-p (file)
11189 "Test whether FILE specifies a location on a remote system.
11190 Return non-nil if the location is indeed remote.
11191
11192 For example, the filename \"/user@host:/foo\" specifies a location
11193 on the system \"/user@host:\"."
11194 (cond ((fboundp 'file-remote-p)
11195 (file-remote-p file))
11196 ((fboundp 'tramp-handle-file-remote-p)
11197 (tramp-handle-file-remote-p file))
11198 ((and (boundp 'ange-ftp-name-format)
11199 (string-match (car ange-ftp-name-format) file))
11200 t)))
11201
11202
11203 ;;;; Refiling
11204
11205 (defun org-get-org-file ()
11206 "Read a filename, with default directory `org-directory'."
11207 (let ((default (or org-default-notes-file remember-data-file)))
11208 (read-file-name (format "File name [%s]: " default)
11209 (file-name-as-directory org-directory)
11210 default)))
11211
11212 (defun org-notes-order-reversed-p ()
11213 "Check if the current file should receive notes in reversed order."
11214 (cond
11215 ((not org-reverse-note-order) nil)
11216 ((eq t org-reverse-note-order) t)
11217 ((not (listp org-reverse-note-order)) nil)
11218 (t (catch 'exit
11219 (let ((all org-reverse-note-order)
11220 entry)
11221 (while (setq entry (pop all))
11222 (if (string-match (car entry) buffer-file-name)
11223 (throw 'exit (cdr entry))))
11224 nil)))))
11225
11226 (defvar org-refile-target-table nil
11227 "The list of refile targets, created by `org-refile'.")
11228
11229 (defvar org-agenda-new-buffers nil
11230 "Buffers created to visit agenda files.")
11231
11232 (defvar org-refile-cache nil
11233 "Cache for refile targets.")
11234
11235 (defvar org-refile-markers nil
11236 "All the markers used for caching refile locations.")
11237
11238 (defun org-refile-marker (pos)
11239 "Get a new refile marker, but only if caching is in use."
11240 (if (not org-refile-use-cache)
11241 pos
11242 (let ((m (make-marker)))
11243 (move-marker m pos)
11244 (push m org-refile-markers)
11245 m)))
11246
11247 (defun org-refile-cache-clear ()
11248 "Clear the refile cache and disable all the markers."
11249 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11250 (setq org-refile-markers nil)
11251 (setq org-refile-cache nil)
11252 (message "Refile cache has been cleared"))
11253
11254 (defun org-refile-cache-check-set (set)
11255 "Check if all the markers in the cache still have live buffers."
11256 (let (marker)
11257 (catch 'exit
11258 (while (and set (setq marker (nth 3 (pop set))))
11259 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11260 (when (and marker (null (marker-buffer marker)))
11261 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11262 (sit-for 3)
11263 (throw 'exit nil)))
11264 t)))
11265
11266 (defun org-refile-cache-put (set &rest identifiers)
11267 "Push the refile targets SET into the cache, under IDENTIFIERS."
11268 (let* ((key (sha1 (prin1-to-string identifiers)))
11269 (entry (assoc key org-refile-cache)))
11270 (if entry
11271 (setcdr entry set)
11272 (push (cons key set) org-refile-cache))))
11273
11274 (defun org-refile-cache-get (&rest identifiers)
11275 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11276 (cond
11277 ((not org-refile-cache) nil)
11278 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11279 (t
11280 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11281 org-refile-cache))))
11282 (and set (org-refile-cache-check-set set) set)))))
11283
11284 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11285 "Produce a table with refile targets."
11286 (let ((case-fold-search nil)
11287 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11288 (entries (or org-refile-targets '((nil . (:level . 1)))))
11289 targets tgs txt re files f desc descre fast-path-p level pos0)
11290 (message "Getting targets...")
11291 (with-current-buffer (or default-buffer (current-buffer))
11292 (while (setq entry (pop entries))
11293 (setq files (car entry) desc (cdr entry))
11294 (setq fast-path-p nil)
11295 (cond
11296 ((null files) (setq files (list (current-buffer))))
11297 ((eq files 'org-agenda-files)
11298 (setq files (org-agenda-files 'unrestricted)))
11299 ((and (symbolp files) (fboundp files))
11300 (setq files (funcall files)))
11301 ((and (symbolp files) (boundp files))
11302 (setq files (symbol-value files))))
11303 (if (stringp files) (setq files (list files)))
11304 (cond
11305 ((eq (car desc) :tag)
11306 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11307 ((eq (car desc) :todo)
11308 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11309 ((eq (car desc) :regexp)
11310 (setq descre (cdr desc)))
11311 ((eq (car desc) :level)
11312 (setq descre (concat "^\\*\\{" (number-to-string
11313 (if org-odd-levels-only
11314 (1- (* 2 (cdr desc)))
11315 (cdr desc)))
11316 "\\}[ \t]")))
11317 ((eq (car desc) :maxlevel)
11318 (setq fast-path-p t)
11319 (setq descre (concat "^\\*\\{1," (number-to-string
11320 (if org-odd-levels-only
11321 (1- (* 2 (cdr desc)))
11322 (cdr desc)))
11323 "\\}[ \t]")))
11324 (t (error "Bad refiling target description %s" desc)))
11325 (while (setq f (pop files))
11326 (with-current-buffer
11327 (if (bufferp f) f (org-get-agenda-file-buffer f))
11328 (or
11329 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11330 (progn
11331 (if (bufferp f) (setq f (buffer-file-name
11332 (buffer-base-buffer f))))
11333 (setq f (and f (expand-file-name f)))
11334 (if (eq org-refile-use-outline-path 'file)
11335 (push (list (file-name-nondirectory f) f nil nil) tgs))
11336 (save-excursion
11337 (save-restriction
11338 (widen)
11339 (goto-char (point-min))
11340 (while (re-search-forward descre nil t)
11341 (goto-char (setq pos0 (point-at-bol)))
11342 (catch 'next
11343 (when org-refile-target-verify-function
11344 (save-match-data
11345 (or (funcall org-refile-target-verify-function)
11346 (throw 'next t))))
11347 (when (and (looking-at org-complex-heading-regexp)
11348 (not (member (match-string 4) excluded-entries))
11349 (match-string 4))
11350 (setq level (org-reduced-level
11351 (- (match-end 1) (match-beginning 1)))
11352 txt (org-link-display-format (match-string 4))
11353 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11354 re (format org-complex-heading-regexp-format
11355 (regexp-quote (match-string 4))))
11356 (when org-refile-use-outline-path
11357 (setq txt (mapconcat
11358 'org-protect-slash
11359 (append
11360 (if (eq org-refile-use-outline-path
11361 'file)
11362 (list (file-name-nondirectory
11363 (buffer-file-name
11364 (buffer-base-buffer))))
11365 (if (eq org-refile-use-outline-path
11366 'full-file-path)
11367 (list (buffer-file-name
11368 (buffer-base-buffer)))))
11369 (org-get-outline-path fast-path-p
11370 level txt)
11371 (list txt))
11372 "/")))
11373 (push (list txt f re (org-refile-marker (point)))
11374 tgs)))
11375 (when (= (point) pos0)
11376 ;; verification function has not moved point
11377 (goto-char (point-at-eol))))))))
11378 (when org-refile-use-cache
11379 (org-refile-cache-put tgs (buffer-file-name) descre))
11380 (setq targets (append tgs targets))))))
11381 (message "Getting targets...done")
11382 (nreverse targets)))
11383
11384 (defun org-protect-slash (s)
11385 (while (string-match "/" s)
11386 (setq s (replace-match "\\" t t s)))
11387 s)
11388
11389 (defvar org-olpa (make-vector 20 nil))
11390
11391 (defun org-get-outline-path (&optional fastp level heading)
11392 "Return the outline path to the current entry, as a list.
11393
11394 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11395 routine which makes outline path derivations for an entire file,
11396 avoiding backtracing. Refile target collection makes use of that."
11397 (if fastp
11398 (progn
11399 (if (> level 19)
11400 (error "Outline path failure, more than 19 levels"))
11401 (loop for i from level upto 19 do
11402 (aset org-olpa i nil))
11403 (prog1
11404 (delq nil (append org-olpa nil))
11405 (aset org-olpa level heading)))
11406 (let (rtn case-fold-search)
11407 (save-excursion
11408 (save-restriction
11409 (widen)
11410 (while (org-up-heading-safe)
11411 (when (looking-at org-complex-heading-regexp)
11412 (push (org-trim
11413 (replace-regexp-in-string
11414 ;; Remove statistical/checkboxes cookies
11415 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11416 (org-match-string-no-properties 4)))
11417 rtn)))
11418 rtn)))))
11419
11420 (defun org-format-outline-path (path &optional width prefix separator)
11421 "Format the outline path PATH for display.
11422 WIDTH is the maximum number of characters that is available.
11423 PREFIX is a prefix to be included in the returned string,
11424 such as the file name.
11425 SEPARATOR is inserted between the different parts of the path,
11426 the default is \"/\"."
11427 (setq width (or width 79))
11428 (if prefix (setq width (- width (length prefix))))
11429 (if (not path)
11430 (or prefix "")
11431 (let* ((nsteps (length path))
11432 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11433 (maxwidth (if (<= total-width width)
11434 10000 ;; everything fits
11435 ;; we need to shorten the level headings
11436 (/ (- width nsteps) nsteps)))
11437 (org-odd-levels-only nil)
11438 (n 0)
11439 (total (1+ (length prefix))))
11440 (setq maxwidth (max maxwidth 10))
11441 (concat prefix
11442 (if prefix (or separator "/"))
11443 (mapconcat
11444 (lambda (h)
11445 (setq n (1+ n))
11446 (if (and (= n nsteps) (< maxwidth 10000))
11447 (setq maxwidth (- total-width total)))
11448 (if (< (length h) maxwidth)
11449 (progn (setq total (+ total (length h) 1)) h)
11450 (setq h (substring h 0 (- maxwidth 2))
11451 total (+ total maxwidth 1))
11452 (if (string-match "[ \t]+\\'" h)
11453 (setq h (substring h 0 (match-beginning 0))))
11454 (setq h (concat h "..")))
11455 (org-add-props h nil 'face
11456 (nth (% (1- n) org-n-level-faces)
11457 org-level-faces))
11458 h)
11459 path (or separator "/"))))))
11460
11461 (defun org-display-outline-path (&optional file current separator just-return-string)
11462 "Display the current outline path in the echo area.
11463
11464 If FILE is non-nil, prepend the output with the file name.
11465 If CURRENT is non-nil, append the current heading to the output.
11466 SEPARATOR is passed through to `org-format-outline-path'. It separates
11467 the different parts of the path and defaults to \"/\".
11468 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11469 (interactive "P")
11470 (let* (case-fold-search
11471 (bfn (buffer-file-name (buffer-base-buffer)))
11472 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11473 res)
11474 (if current (setq path (append path
11475 (save-excursion
11476 (org-back-to-heading t)
11477 (if (looking-at org-complex-heading-regexp)
11478 (list (match-string 4)))))))
11479 (setq res
11480 (org-format-outline-path
11481 path
11482 (1- (frame-width))
11483 (and file bfn (concat (file-name-nondirectory bfn) separator))
11484 separator))
11485 (if just-return-string
11486 (org-no-properties res)
11487 (org-unlogged-message "%s" res))))
11488
11489 (defvar org-refile-history nil
11490 "History for refiling operations.")
11491
11492 (defvar org-after-refile-insert-hook nil
11493 "Hook run after `org-refile' has inserted its stuff at the new location.
11494 Note that this is still *before* the stuff will be removed from
11495 the *old* location.")
11496
11497 (defvar org-capture-last-stored-marker)
11498 (defvar org-refile-keep nil
11499 "Non-nil means `org-refile' will copy instead of refile.")
11500
11501 (defun org-copy ()
11502 "Like `org-refile', but copy."
11503 (interactive)
11504 (let ((org-refile-keep t))
11505 (funcall 'org-refile nil nil nil "Copy")))
11506
11507 (defun org-refile (&optional goto default-buffer rfloc msg)
11508 "Move the entry or entries at point to another heading.
11509 The list of target headings is compiled using the information in
11510 `org-refile-targets', which see.
11511
11512 At the target location, the entry is filed as a subitem of the target
11513 heading. Depending on `org-reverse-note-order', the new subitem will
11514 either be the first or the last subitem.
11515
11516 If there is an active region, all entries in that region will be moved.
11517 However, the region must fulfill the requirement that the first heading
11518 is the first one sets the top-level of the moved text - at most siblings
11519 below it are allowed.
11520
11521 With prefix arg GOTO, the command will only visit the target location
11522 and not actually move anything.
11523
11524 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11525 go to the location where the last refiling operation has put the subtree.
11526
11527 With a numeric prefix argument of `2', refile to the running clock.
11528
11529 With a numeric prefix argument of `3', emulate `org-refile-keep'
11530 being set to `t' and copy to the target location, don't move it.
11531 Beware that keeping refiled entries may result in duplicated ID
11532 properties.
11533
11534 RFLOC can be a refile location obtained in a different way.
11535
11536 MSG is a string to replace \"Refile\" in the default prompt with
11537 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11538
11539 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11540
11541 If you are using target caching (see `org-refile-use-cache'),
11542 you have to clear the target cache in order to find new targets.
11543 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11544 prefix argument (`C-u C-u C-u C-c C-w')."
11545
11546 (interactive "P")
11547 (if (member goto '(0 (64)))
11548 (org-refile-cache-clear)
11549 (let* ((actionmsg (cond (msg msg)
11550 ((equal goto 3) "Refile (and keep)")
11551 (t "Refile")))
11552 (cbuf (current-buffer))
11553 (regionp (org-region-active-p))
11554 (region-start (and regionp (region-beginning)))
11555 (region-end (and regionp (region-end)))
11556 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11557 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11558 pos it nbuf file re level reversed)
11559 (setq last-command nil)
11560 (when regionp
11561 (goto-char region-start)
11562 (or (bolp) (goto-char (point-at-bol)))
11563 (setq region-start (point))
11564 (unless (or (org-kill-is-subtree-p
11565 (buffer-substring region-start region-end))
11566 (prog1 org-refile-active-region-within-subtree
11567 (let ((s (point-at-eol)))
11568 (org-toggle-heading)
11569 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11570 (user-error "The region is not a (sequence of) subtree(s)")))
11571 (if (equal goto '(16))
11572 (org-refile-goto-last-stored)
11573 (when (or
11574 (and (equal goto 2)
11575 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11576 (prog1
11577 (setq it (list (or org-clock-heading "running clock")
11578 (buffer-file-name
11579 (marker-buffer org-clock-hd-marker))
11580 ""
11581 (marker-position org-clock-hd-marker)))
11582 (setq goto nil)))
11583 (setq it (or rfloc
11584 (let (heading-text)
11585 (save-excursion
11586 (unless (and goto (listp goto))
11587 (org-back-to-heading t)
11588 (setq heading-text
11589 (nth 4 (org-heading-components))))
11590
11591 (org-refile-get-location
11592 (cond ((and goto (listp goto)) "Goto")
11593 (regionp (concat actionmsg " region to"))
11594 (t (concat actionmsg " subtree \""
11595 heading-text "\" to")))
11596 default-buffer
11597 (and (not (equal '(4) goto))
11598 org-refile-allow-creating-parent-nodes)
11599 goto))))))
11600 (setq file (nth 1 it)
11601 re (nth 2 it)
11602 pos (nth 3 it))
11603 (if (and (not goto)
11604 pos
11605 (equal (buffer-file-name) file)
11606 (if regionp
11607 (and (>= pos region-start)
11608 (<= pos region-end))
11609 (and (>= pos (point))
11610 (< pos (save-excursion
11611 (org-end-of-subtree t t))))))
11612 (error "Cannot refile to position inside the tree or region"))
11613
11614 (setq nbuf (or (find-buffer-visiting file)
11615 (find-file-noselect file)))
11616 (if (and goto (not (equal goto 3)))
11617 (progn
11618 (org-pop-to-buffer-same-window nbuf)
11619 (goto-char pos)
11620 (org-show-context 'org-goto))
11621 (if regionp
11622 (progn
11623 (org-kill-new (buffer-substring region-start region-end))
11624 (org-save-markers-in-region region-start region-end))
11625 (org-copy-subtree 1 nil t))
11626 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11627 (find-file-noselect file)))
11628 (setq reversed (org-notes-order-reversed-p))
11629 (save-excursion
11630 (save-restriction
11631 (widen)
11632 (if pos
11633 (progn
11634 (goto-char pos)
11635 (looking-at org-outline-regexp)
11636 (setq level (org-get-valid-level (funcall outline-level) 1))
11637 (goto-char
11638 (if reversed
11639 (or (outline-next-heading) (point-max))
11640 (or (save-excursion (org-get-next-sibling))
11641 (org-end-of-subtree t t)
11642 (point-max)))))
11643 (setq level 1)
11644 (if (not reversed)
11645 (goto-char (point-max))
11646 (goto-char (point-min))
11647 (or (outline-next-heading) (goto-char (point-max)))))
11648 (if (not (bolp)) (newline))
11649 (org-paste-subtree level)
11650 (when org-log-refile
11651 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11652 (unless (eq org-log-refile 'note)
11653 (save-excursion (org-add-log-note))))
11654 (and org-auto-align-tags
11655 (let ((org-loop-over-headlines-in-active-region nil))
11656 (org-set-tags nil t)))
11657 (let ((bookmark-name (plist-get org-bookmark-names-plist
11658 :last-refile)))
11659 (when bookmark-name
11660 (with-demoted-errors
11661 (bookmark-set bookmark-name))))
11662 ;; If we are refiling for capture, make sure that the
11663 ;; last-capture pointers point here
11664 (when (org-bound-and-true-p org-refile-for-capture)
11665 (let ((bookmark-name (plist-get org-bookmark-names-plist
11666 :last-capture-marker)))
11667 (when bookmark-name
11668 (with-demoted-errors
11669 (bookmark-set bookmark-name))))
11670 (move-marker org-capture-last-stored-marker (point)))
11671 (if (fboundp 'deactivate-mark) (deactivate-mark))
11672 (run-hooks 'org-after-refile-insert-hook))))
11673 (unless org-refile-keep
11674 (if regionp
11675 (delete-region (point) (+ (point) (- region-end region-start)))
11676 (delete-region
11677 (and (org-back-to-heading t) (point))
11678 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11679 (when (featurep 'org-inlinetask)
11680 (org-inlinetask-remove-END-maybe))
11681 (setq org-markers-to-move nil)
11682 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11683
11684 (defun org-refile-goto-last-stored ()
11685 "Go to the location where the last refile was stored."
11686 (interactive)
11687 (bookmark-jump "org-refile-last-stored")
11688 (message "This is the location of the last refile"))
11689
11690 (defun org-refile--get-location (refloc tbl)
11691 "When user refile to REFLOC, find the associated target in TBL.
11692 Also check `org-refile-target-table'."
11693 (car (delq
11694 nil
11695 (mapcar
11696 (lambda (r) (or (assoc r tbl)
11697 (assoc r org-refile-target-table)))
11698 (list (replace-regexp-in-string "/$" "" refloc)
11699 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11700
11701 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11702 no-exclude)
11703 "Prompt the user for a refile location, using PROMPT.
11704 PROMPT should not be suffixed with a colon and a space, because
11705 this function appends the default value from
11706 `org-refile-history' automatically, if that is not empty.
11707 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11708 this is used for the GOTO interface."
11709 (let ((org-refile-targets org-refile-targets)
11710 (org-refile-use-outline-path org-refile-use-outline-path)
11711 excluded-entries)
11712 (when (and (derived-mode-p 'org-mode)
11713 (not org-refile-use-cache)
11714 (not no-exclude))
11715 (org-map-tree
11716 (lambda()
11717 (setq excluded-entries
11718 (append excluded-entries (list (org-get-heading t t)))))))
11719 (setq org-refile-target-table
11720 (org-refile-get-targets default-buffer excluded-entries)))
11721 (unless org-refile-target-table
11722 (user-error "No refile targets"))
11723 (let* ((cbuf (current-buffer))
11724 (partial-completion-mode nil)
11725 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11726 (cfunc (if (and org-refile-use-outline-path
11727 org-outline-path-complete-in-steps)
11728 'org-olpath-completing-read
11729 'org-icompleting-read))
11730 (extra (if org-refile-use-outline-path "/" ""))
11731 (cbnex (concat (buffer-name) extra))
11732 (filename (and cfn (expand-file-name cfn)))
11733 (tbl (mapcar
11734 (lambda (x)
11735 (if (and (not (member org-refile-use-outline-path
11736 '(file full-file-path)))
11737 (not (equal filename (nth 1 x))))
11738 (cons (concat (car x) extra " ("
11739 (file-name-nondirectory (nth 1 x)) ")")
11740 (cdr x))
11741 (cons (concat (car x) extra) (cdr x))))
11742 org-refile-target-table))
11743 (completion-ignore-case t)
11744 cdef
11745 (prompt (concat prompt
11746 (or (and (car org-refile-history)
11747 (concat " (default " (car org-refile-history) ")"))
11748 (and (assoc cbnex tbl) (setq cdef cbnex)
11749 (concat " (default " cbnex ")"))) ": "))
11750 pa answ parent-target child parent old-hist)
11751 (setq old-hist org-refile-history)
11752 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11753 nil 'org-refile-history (or cdef (car org-refile-history))))
11754 (if (setq pa (org-refile--get-location answ tbl))
11755 (progn
11756 (org-refile-check-position pa)
11757 (when (or (not org-refile-history)
11758 (not (eq old-hist org-refile-history))
11759 (not (equal (car pa) (car org-refile-history))))
11760 (setq org-refile-history
11761 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11762 org-refile-history
11763 (cdr org-refile-history))))
11764 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11765 (pop org-refile-history)))
11766 pa)
11767 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11768 (progn
11769 (setq parent (match-string 1 answ)
11770 child (match-string 2 answ))
11771 (setq parent-target (org-refile--get-location parent tbl))
11772 (when (and parent-target
11773 (or (eq new-nodes t)
11774 (and (eq new-nodes 'confirm)
11775 (y-or-n-p (format "Create new node \"%s\"? "
11776 child)))))
11777 (org-refile-new-child parent-target child)))
11778 (user-error "Invalid target location")))))
11779
11780 (declare-function org-string-nw-p "org-macs" (s))
11781 (defun org-refile-check-position (refile-pointer)
11782 "Check if the refile pointer matches the headline to which it points."
11783 (let* ((file (nth 1 refile-pointer))
11784 (re (nth 2 refile-pointer))
11785 (pos (nth 3 refile-pointer))
11786 buffer)
11787 (if (and (not (markerp pos)) (not file))
11788 (user-error "Please save the buffer to a file before refiling")
11789 (when (org-string-nw-p re)
11790 (setq buffer (if (markerp pos)
11791 (marker-buffer pos)
11792 (or (find-buffer-visiting file)
11793 (find-file-noselect file))))
11794 (with-current-buffer buffer
11795 (save-excursion
11796 (save-restriction
11797 (widen)
11798 (goto-char pos)
11799 (beginning-of-line 1)
11800 (unless (org-looking-at-p re)
11801 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11802
11803 (defun org-refile-new-child (parent-target child)
11804 "Use refile target PARENT-TARGET to add new CHILD below it."
11805 (unless parent-target
11806 (error "Cannot find parent for new node"))
11807 (let ((file (nth 1 parent-target))
11808 (pos (nth 3 parent-target))
11809 level)
11810 (with-current-buffer (or (find-buffer-visiting file)
11811 (find-file-noselect file))
11812 (save-excursion
11813 (save-restriction
11814 (widen)
11815 (if pos
11816 (goto-char pos)
11817 (goto-char (point-max))
11818 (if (not (bolp)) (newline)))
11819 (when (looking-at org-outline-regexp)
11820 (setq level (funcall outline-level))
11821 (org-end-of-subtree t t))
11822 (org-back-over-empty-lines)
11823 (insert "\n" (make-string
11824 (if pos (org-get-valid-level level 1) 1) ?*)
11825 " " child "\n")
11826 (beginning-of-line 0)
11827 (list (concat (car parent-target) "/" child) file "" (point)))))))
11828
11829 (defun org-olpath-completing-read (prompt collection &rest args)
11830 "Read an outline path like a file name."
11831 (let ((thetable collection)
11832 (org-completion-use-ido nil) ; does not work with ido.
11833 (org-completion-use-iswitchb nil)) ; or iswitchb
11834 (apply
11835 'org-icompleting-read prompt
11836 (lambda (string predicate &optional flag)
11837 (let (rtn r f (l (length string)))
11838 (cond
11839 ((eq flag nil)
11840 ;; try completion
11841 (try-completion string thetable))
11842 ((eq flag t)
11843 ;; all-completions
11844 (setq rtn (all-completions string thetable predicate))
11845 (mapcar
11846 (lambda (x)
11847 (setq r (substring x l))
11848 (if (string-match " ([^)]*)$" x)
11849 (setq f (match-string 0 x))
11850 (setq f ""))
11851 (if (string-match "/" r)
11852 (concat string (substring r 0 (match-end 0)) f)
11853 x))
11854 rtn))
11855 ((eq flag 'lambda)
11856 ;; exact match?
11857 (assoc string thetable)))))
11858 args)))
11859
11860 ;;;; Dynamic blocks
11861
11862 (defun org-find-dblock (name)
11863 "Find the first dynamic block with name NAME in the buffer.
11864 If not found, stay at current position and return nil."
11865 (let ((case-fold-search t) pos)
11866 (save-excursion
11867 (goto-char (point-min))
11868 (setq pos (and (re-search-forward
11869 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11870 (match-beginning 0))))
11871 (if pos (goto-char pos))
11872 pos))
11873
11874 (defconst org-dblock-start-re
11875 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11876 "Matches the start line of a dynamic block, with parameters.")
11877
11878 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11879 "Matches the end of a dynamic block.")
11880
11881 (defun org-create-dblock (plist)
11882 "Create a dynamic block section, with parameters taken from PLIST.
11883 PLIST must contain a :name entry which is used as name of the block."
11884 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11885 (end-of-line 1)
11886 (newline))
11887 (let ((col (current-column))
11888 (name (plist-get plist :name)))
11889 (insert "#+BEGIN: " name)
11890 (while plist
11891 (if (eq (car plist) :name)
11892 (setq plist (cddr plist))
11893 (insert " " (prin1-to-string (pop plist)))))
11894 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11895 (beginning-of-line -2)))
11896
11897 (defun org-prepare-dblock ()
11898 "Prepare dynamic block for refresh.
11899 This empties the block, puts the cursor at the insert position and returns
11900 the property list including an extra property :name with the block name."
11901 (unless (looking-at org-dblock-start-re)
11902 (user-error "Not at a dynamic block"))
11903 (let* ((begdel (1+ (match-end 0)))
11904 (name (org-no-properties (match-string 1)))
11905 (params (append (list :name name)
11906 (read (concat "(" (match-string 3) ")")))))
11907 (save-excursion
11908 (beginning-of-line 1)
11909 (skip-chars-forward " \t")
11910 (setq params (plist-put params :indentation-column (current-column))))
11911 (unless (re-search-forward org-dblock-end-re nil t)
11912 (error "Dynamic block not terminated"))
11913 (setq params
11914 (append params
11915 (list :content (buffer-substring
11916 begdel (match-beginning 0)))))
11917 (delete-region begdel (match-beginning 0))
11918 (goto-char begdel)
11919 (open-line 1)
11920 params))
11921
11922 (defun org-map-dblocks (&optional command)
11923 "Apply COMMAND to all dynamic blocks in the current buffer.
11924 If COMMAND is not given, use `org-update-dblock'."
11925 (let ((cmd (or command 'org-update-dblock)))
11926 (save-excursion
11927 (goto-char (point-min))
11928 (while (re-search-forward org-dblock-start-re nil t)
11929 (goto-char (match-beginning 0))
11930 (save-excursion
11931 (condition-case nil
11932 (funcall cmd)
11933 (error (message "Error during update of dynamic block"))))
11934 (unless (re-search-forward org-dblock-end-re nil t)
11935 (error "Dynamic block not terminated"))))))
11936
11937 (defun org-dblock-update (&optional arg)
11938 "User command for updating dynamic blocks.
11939 Update the dynamic block at point. With prefix ARG, update all dynamic
11940 blocks in the buffer."
11941 (interactive "P")
11942 (if arg
11943 (org-update-all-dblocks)
11944 (or (looking-at org-dblock-start-re)
11945 (org-beginning-of-dblock))
11946 (org-update-dblock)))
11947
11948 (defun org-update-dblock ()
11949 "Update the dynamic block at point.
11950 This means to empty the block, parse for parameters and then call
11951 the correct writing function."
11952 (interactive)
11953 (save-excursion
11954 (let* ((win (selected-window))
11955 (pos (point))
11956 (line (org-current-line))
11957 (params (org-prepare-dblock))
11958 (name (plist-get params :name))
11959 (indent (plist-get params :indentation-column))
11960 (cmd (intern (concat "org-dblock-write:" name))))
11961 (message "Updating dynamic block `%s' at line %d..." name line)
11962 (funcall cmd params)
11963 (message "Updating dynamic block `%s' at line %d...done" name line)
11964 (goto-char pos)
11965 (when (and indent (> indent 0))
11966 (setq indent (make-string indent ?\ ))
11967 (save-excursion
11968 (select-window win)
11969 (org-beginning-of-dblock)
11970 (forward-line 1)
11971 (while (not (looking-at org-dblock-end-re))
11972 (insert indent)
11973 (beginning-of-line 2))
11974 (when (looking-at org-dblock-end-re)
11975 (and (looking-at "[ \t]+")
11976 (replace-match ""))
11977 (insert indent)))))))
11978
11979 (defun org-beginning-of-dblock ()
11980 "Find the beginning of the dynamic block at point.
11981 Error if there is no such block at point."
11982 (let ((pos (point))
11983 beg)
11984 (end-of-line 1)
11985 (if (and (re-search-backward org-dblock-start-re nil t)
11986 (setq beg (match-beginning 0))
11987 (re-search-forward org-dblock-end-re nil t)
11988 (> (match-end 0) pos))
11989 (goto-char beg)
11990 (goto-char pos)
11991 (error "Not in a dynamic block"))))
11992
11993 (defun org-update-all-dblocks ()
11994 "Update all dynamic blocks in the buffer.
11995 This function can be used in a hook."
11996 (interactive)
11997 (when (derived-mode-p 'org-mode)
11998 (org-map-dblocks 'org-update-dblock)))
11999
12000
12001 ;;;; Completion
12002
12003 (declare-function org-export-backend-name "org-export" (cl-x))
12004 (declare-function org-export-backend-options "org-export" (cl-x))
12005 (defun org-get-export-keywords ()
12006 "Return a list of all currently understood export keywords.
12007 Export keywords include options, block names, attributes and
12008 keywords relative to each registered export back-end."
12009 (let (keywords)
12010 (dolist (backend
12011 (org-bound-and-true-p org-export--registered-backends)
12012 (delq nil keywords))
12013 ;; Back-end name (for keywords, like #+LATEX:)
12014 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12015 (dolist (option-entry (org-export-backend-options backend))
12016 ;; Back-end options.
12017 (push (nth 1 option-entry) keywords)))))
12018
12019 (defconst org-options-keywords
12020 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12021 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12022 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12023 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12024 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12025
12026 (defcustom org-structure-template-alist
12027 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12028 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12029 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12030 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12031 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12032 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12033 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12034 "<literal style=\"latex\">\n?\n</literal>")
12035 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12036 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12037 "<literal style=\"html\">\n?\n</literal>")
12038 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12039 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12040 ("A" "#+ASCII: " "")
12041 ("i" "#+INDEX: ?" "#+INDEX: ?")
12042 ("I" "#+INCLUDE: %file ?"
12043 "<include file=%file markup=\"?\">"))
12044 "Structure completion elements.
12045 This is a list of abbreviation keys and values. The value gets inserted
12046 if you type `<' followed by the key and then press the completion key,
12047 usually `M-TAB'. %file will be replaced by a file name after prompting
12048 for the file using completion. The cursor will be placed at the position
12049 of the `?` in the template.
12050 There are two templates for each key, the first uses the original Org syntax,
12051 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12052 the default when the /org-mtags.el/ module has been loaded. See also the
12053 variable `org-mtags-prefer-muse-templates'."
12054 :group 'org-completion
12055 :type '(repeat
12056 (list
12057 (string :tag "Key")
12058 (string :tag "Template")
12059 (string :tag "Muse Template"))))
12060
12061 (defun org-try-structure-completion ()
12062 "Try to complete a structure template before point.
12063 This looks for strings like \"<e\" on an otherwise empty line and
12064 expands them."
12065 (let ((l (buffer-substring (point-at-bol) (point)))
12066 a)
12067 (when (and (looking-at "[ \t]*$")
12068 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12069 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12070 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12071 (match-beginning 1)) a)
12072 t)))
12073
12074 (defun org-complete-expand-structure-template (start cell)
12075 "Expand a structure template."
12076 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12077 (rpl (nth (if musep 2 1) cell))
12078 (ind ""))
12079 (delete-region start (point))
12080 (when (string-match "\\`#\\+" rpl)
12081 (cond
12082 ((bolp))
12083 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12084 (setq ind (buffer-substring (point-at-bol) (point))))
12085 (t (newline))))
12086 (setq start (point))
12087 (if (string-match "%file" rpl)
12088 (setq rpl (replace-match
12089 (concat
12090 "\""
12091 (save-match-data
12092 (abbreviate-file-name (read-file-name "Include file: ")))
12093 "\"")
12094 t t rpl)))
12095 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12096 (concat "\n" ind)))
12097 (insert rpl)
12098 (if (re-search-backward "\\?" start t) (delete-char 1))))
12099
12100 ;;;; TODO, DEADLINE, Comments
12101
12102 (defun org-toggle-comment ()
12103 "Change the COMMENT state of an entry."
12104 (interactive)
12105 (save-excursion
12106 (org-back-to-heading)
12107 (let (case-fold-search)
12108 (cond
12109 ((looking-at (format org-heading-keyword-regexp-format
12110 org-comment-string))
12111 (goto-char (match-end 1))
12112 (looking-at (concat " +" org-comment-string))
12113 (replace-match "" t t)
12114 (when (eolp) (insert " ")))
12115 ((looking-at org-outline-regexp)
12116 (goto-char (match-end 0))
12117 (insert org-comment-string " "))))))
12118
12119 (defvar org-last-todo-state-is-todo nil
12120 "This is non-nil when the last TODO state change led to a TODO state.
12121 If the last change removed the TODO tag or switched to DONE, then
12122 this is nil.")
12123
12124 (defvar org-setting-tags nil) ; dynamically skipped
12125
12126 (defvar org-todo-setup-filter-hook nil
12127 "Hook for functions that pre-filter todo specs.
12128 Each function takes a todo spec and returns either nil or the spec
12129 transformed into canonical form." )
12130
12131 (defvar org-todo-get-default-hook nil
12132 "Hook for functions that get a default item for todo.
12133 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12134 nil or a string to be used for the todo mark." )
12135
12136 (defvar org-agenda-headline-snapshot-before-repeat)
12137
12138 (defun org-current-effective-time ()
12139 "Return current time adjusted for `org-extend-today-until' variable."
12140 (let* ((ct (org-current-time))
12141 (dct (decode-time ct))
12142 (ct1
12143 (cond
12144 (org-use-last-clock-out-time-as-effective-time
12145 (or (org-clock-get-last-clock-out-time) ct))
12146 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12147 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12148 (t ct))))
12149 ct1))
12150
12151 (defun org-todo-yesterday (&optional arg)
12152 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12153 (interactive "P")
12154 (if (eq major-mode 'org-agenda-mode)
12155 (apply 'org-agenda-todo-yesterday arg)
12156 (let* ((hour (third (decode-time
12157 (org-current-time))))
12158 (org-extend-today-until (1+ hour)))
12159 (org-todo arg))))
12160
12161 (defvar org-block-entry-blocking ""
12162 "First entry preventing the TODO state change.")
12163
12164 (defun org-todo (&optional arg)
12165 "Change the TODO state of an item.
12166 The state of an item is given by a keyword at the start of the heading,
12167 like
12168 *** TODO Write paper
12169 *** DONE Call mom
12170
12171 The different keywords are specified in the variable `org-todo-keywords'.
12172 By default the available states are \"TODO\" and \"DONE\".
12173 So for this example: when the item starts with TODO, it is changed to DONE.
12174 When it starts with DONE, the DONE is removed. And when neither TODO nor
12175 DONE are present, add TODO at the beginning of the heading.
12176
12177 With \\[universal-argument] prefix arg, use completion to determine the new \
12178 state.
12179 With numeric prefix arg, switch to that state.
12180 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12181 keywords (nextset).
12182 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12183 With a numeric prefix arg of 0, inhibit note taking for the change.
12184
12185 For calling through lisp, arg is also interpreted in the following way:
12186 'none -> empty state
12187 \"\"(empty string) -> switch to empty state
12188 'done -> switch to DONE
12189 'nextset -> switch to the next set of keywords
12190 'previousset -> switch to the previous set of keywords
12191 \"WAITING\" -> switch to the specified keyword, but only if it
12192 really is a member of `org-todo-keywords'."
12193 (interactive "P")
12194 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12195 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12196 'region-start-level 'region))
12197 org-loop-over-headlines-in-active-region)
12198 (org-map-entries
12199 `(org-todo ,arg)
12200 org-loop-over-headlines-in-active-region
12201 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12202 (if (equal arg '(16)) (setq arg 'nextset))
12203 (let ((org-blocker-hook org-blocker-hook)
12204 commentp
12205 case-fold-search)
12206 (when (equal arg '(64))
12207 (setq arg nil org-blocker-hook nil))
12208 (when (and org-blocker-hook
12209 (or org-inhibit-blocking
12210 (org-entry-get nil "NOBLOCKING")))
12211 (setq org-blocker-hook nil))
12212 (save-excursion
12213 (catch 'exit
12214 (org-back-to-heading t)
12215 (when (looking-at (concat "^\\*+ " org-comment-string))
12216 (org-toggle-comment)
12217 (setq commentp t))
12218 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12219 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12220 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12221 (let* ((match-data (match-data))
12222 (startpos (point-at-bol))
12223 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12224 (org-log-done org-log-done)
12225 (org-log-repeat org-log-repeat)
12226 (org-todo-log-states org-todo-log-states)
12227 (org-inhibit-logging
12228 (if (equal arg 0)
12229 (progn (setq arg nil) 'note) org-inhibit-logging))
12230 (this (match-string 1))
12231 (hl-pos (match-beginning 0))
12232 (head (org-get-todo-sequence-head this))
12233 (ass (assoc head org-todo-kwd-alist))
12234 (interpret (nth 1 ass))
12235 (done-word (nth 3 ass))
12236 (final-done-word (nth 4 ass))
12237 (org-last-state (or this ""))
12238 (completion-ignore-case t)
12239 (member (member this org-todo-keywords-1))
12240 (tail (cdr member))
12241 (org-state (cond
12242 ((and org-todo-key-trigger
12243 (or (and (equal arg '(4))
12244 (eq org-use-fast-todo-selection 'prefix))
12245 (and (not arg) org-use-fast-todo-selection
12246 (not (eq org-use-fast-todo-selection
12247 'prefix)))))
12248 ;; Use fast selection
12249 (org-fast-todo-selection))
12250 ((and (equal arg '(4))
12251 (or (not org-use-fast-todo-selection)
12252 (not org-todo-key-trigger)))
12253 ;; Read a state with completion
12254 (org-icompleting-read
12255 "State: " (mapcar 'list org-todo-keywords-1)
12256 nil t))
12257 ((eq arg 'right)
12258 (if this
12259 (if tail (car tail) nil)
12260 (car org-todo-keywords-1)))
12261 ((eq arg 'left)
12262 (if (equal member org-todo-keywords-1)
12263 nil
12264 (if this
12265 (nth (- (length org-todo-keywords-1)
12266 (length tail) 2)
12267 org-todo-keywords-1)
12268 (org-last org-todo-keywords-1))))
12269 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12270 (setq arg nil))) ; hack to fall back to cycling
12271 (arg
12272 ;; user or caller requests a specific state
12273 (cond
12274 ((equal arg "") nil)
12275 ((eq arg 'none) nil)
12276 ((eq arg 'done) (or done-word (car org-done-keywords)))
12277 ((eq arg 'nextset)
12278 (or (car (cdr (member head org-todo-heads)))
12279 (car org-todo-heads)))
12280 ((eq arg 'previousset)
12281 (let ((org-todo-heads (reverse org-todo-heads)))
12282 (or (car (cdr (member head org-todo-heads)))
12283 (car org-todo-heads))))
12284 ((car (member arg org-todo-keywords-1)))
12285 ((stringp arg)
12286 (user-error "State `%s' not valid in this file" arg))
12287 ((nth (1- (prefix-numeric-value arg))
12288 org-todo-keywords-1))))
12289 ((null member) (or head (car org-todo-keywords-1)))
12290 ((equal this final-done-word) nil) ;; -> make empty
12291 ((null tail) nil) ;; -> first entry
12292 ((memq interpret '(type priority))
12293 (if (eq this-command last-command)
12294 (car tail)
12295 (if (> (length tail) 0)
12296 (or done-word (car org-done-keywords))
12297 nil)))
12298 (t
12299 (car tail))))
12300 (org-state (or
12301 (run-hook-with-args-until-success
12302 'org-todo-get-default-hook org-state org-last-state)
12303 org-state))
12304 (next (if org-state (concat " " org-state " ") " "))
12305 (change-plist (list :type 'todo-state-change :from this :to org-state
12306 :position startpos))
12307 dolog now-done-p)
12308 (when org-blocker-hook
12309 (setq org-last-todo-state-is-todo
12310 (not (member this org-done-keywords)))
12311 (unless (save-excursion
12312 (save-match-data
12313 (org-with-wide-buffer
12314 (run-hook-with-args-until-failure
12315 'org-blocker-hook change-plist))))
12316 (if (org-called-interactively-p 'interactive)
12317 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12318 this org-state org-block-entry-blocking)
12319 ;; fail silently
12320 (message "TODO state change from %s to %s blocked (by \"%s\")"
12321 this org-state org-block-entry-blocking)
12322 (throw 'exit nil))))
12323 (store-match-data match-data)
12324 (replace-match next t t)
12325 (unless (pos-visible-in-window-p hl-pos)
12326 (message "TODO state changed to %s" (org-trim next)))
12327 (unless head
12328 (setq head (org-get-todo-sequence-head org-state)
12329 ass (assoc head org-todo-kwd-alist)
12330 interpret (nth 1 ass)
12331 done-word (nth 3 ass)
12332 final-done-word (nth 4 ass)))
12333 (when (memq arg '(nextset previousset))
12334 (message "Keyword-Set %d/%d: %s"
12335 (- (length org-todo-sets) -1
12336 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12337 (length org-todo-sets)
12338 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12339 (setq org-last-todo-state-is-todo
12340 (not (member org-state org-done-keywords)))
12341 (setq now-done-p (and (member org-state org-done-keywords)
12342 (not (member this org-done-keywords))))
12343 (and logging (org-local-logging logging))
12344 (when (and (or org-todo-log-states org-log-done)
12345 (not (eq org-inhibit-logging t))
12346 (not (memq arg '(nextset previousset))))
12347 ;; we need to look at recording a time and note
12348 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12349 (nth 2 (assoc this org-todo-log-states))))
12350 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12351 (setq dolog 'time))
12352 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12353 (and org-state
12354 (member org-state org-not-done-keywords)
12355 (not (member this org-not-done-keywords))))
12356 ;; This is now a todo state and was not one before
12357 ;; If there was a CLOSED time stamp, get rid of it.
12358 (org-add-planning-info nil nil 'closed))
12359 (when (and now-done-p org-log-done)
12360 ;; It is now done, and it was not done before
12361 (org-add-planning-info 'closed (org-current-effective-time))
12362 (if (and (not dolog) (eq 'note org-log-done))
12363 (org-add-log-setup 'done org-state this 'findpos 'note)))
12364 (when (and org-state dolog)
12365 ;; This is a non-nil state, and we need to log it
12366 (org-add-log-setup 'state org-state this 'findpos dolog)))
12367 ;; Fixup tag positioning
12368 (org-todo-trigger-tag-changes org-state)
12369 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12370 (when org-provide-todo-statistics
12371 (org-update-parent-todo-statistics))
12372 (run-hooks 'org-after-todo-state-change-hook)
12373 (if (and arg (not (member org-state org-done-keywords)))
12374 (setq head (org-get-todo-sequence-head org-state)))
12375 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12376 ;; Do we need to trigger a repeat?
12377 (when now-done-p
12378 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12379 ;; This is for the agenda, take a snapshot of the headline.
12380 (save-match-data
12381 (setq org-agenda-headline-snapshot-before-repeat
12382 (org-get-heading))))
12383 (org-auto-repeat-maybe org-state))
12384 ;; Fixup cursor location if close to the keyword
12385 (if (and (outline-on-heading-p)
12386 (not (bolp))
12387 (save-excursion (beginning-of-line 1)
12388 (looking-at org-todo-line-regexp))
12389 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12390 (progn
12391 (goto-char (or (match-end 2) (match-end 1)))
12392 (and (looking-at " ") (just-one-space))))
12393 (when org-trigger-hook
12394 (save-excursion
12395 (run-hook-with-args 'org-trigger-hook change-plist)))
12396 (when commentp (org-toggle-comment))))))))
12397
12398 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12399 "Block turning an entry into a TODO, using the hierarchy.
12400 This checks whether the current task should be blocked from state
12401 changes. Such blocking occurs when:
12402
12403 1. The task has children which are not all in a completed state.
12404
12405 2. A task has a parent with the property :ORDERED:, and there
12406 are siblings prior to the current task with incomplete
12407 status.
12408
12409 3. The parent of the task is blocked because it has siblings that should
12410 be done first, or is child of a block grandparent TODO entry."
12411
12412 (if (not org-enforce-todo-dependencies)
12413 t ; if locally turned off don't block
12414 (catch 'dont-block
12415 ;; If this is not a todo state change, or if this entry is already DONE,
12416 ;; do not block
12417 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12418 (member (plist-get change-plist :from)
12419 (cons 'done org-done-keywords))
12420 (member (plist-get change-plist :to)
12421 (cons 'todo org-not-done-keywords))
12422 (not (plist-get change-plist :to)))
12423 (throw 'dont-block t))
12424 ;; If this task has children, and any are undone, it's blocked
12425 (save-excursion
12426 (org-back-to-heading t)
12427 (let ((this-level (funcall outline-level)))
12428 (outline-next-heading)
12429 (let ((child-level (funcall outline-level)))
12430 (while (and (not (eobp))
12431 (> child-level this-level))
12432 ;; this todo has children, check whether they are all
12433 ;; completed
12434 (if (and (not (org-entry-is-done-p))
12435 (org-entry-is-todo-p))
12436 (progn (setq org-block-entry-blocking (org-get-heading))
12437 (throw 'dont-block nil)))
12438 (outline-next-heading)
12439 (setq child-level (funcall outline-level))))))
12440 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12441 ;; any previous siblings are undone, it's blocked
12442 (save-excursion
12443 (org-back-to-heading t)
12444 (let* ((pos (point))
12445 (parent-pos (and (org-up-heading-safe) (point))))
12446 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12447 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12448 (forward-line 1)
12449 (re-search-forward org-not-done-heading-regexp pos t))
12450 (setq org-block-entry-blocking (match-string 0))
12451 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12452 ;; Search further up the hierarchy, to see if an ancestor is blocked
12453 (while t
12454 (goto-char parent-pos)
12455 (if (not (looking-at org-not-done-heading-regexp))
12456 (throw 'dont-block t)) ; do not block, parent is not a TODO
12457 (setq pos (point))
12458 (setq parent-pos (and (org-up-heading-safe) (point)))
12459 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12460 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12461 (forward-line 1)
12462 (re-search-forward org-not-done-heading-regexp pos t)
12463 (setq org-block-entry-blocking (org-get-heading)))
12464 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12465
12466 (defcustom org-track-ordered-property-with-tag nil
12467 "Should the ORDERED property also be shown as a tag?
12468 The ORDERED property decides if an entry should require subtasks to be
12469 completed in sequence. Since a property is not very visible, setting
12470 this option means that toggling the ORDERED property with the command
12471 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12472 not relevant for the behavior, but it makes things more visible.
12473
12474 Note that toggling the tag with tags commands will not change the property
12475 and therefore not influence behavior!
12476
12477 This can be t, meaning the tag ORDERED should be used, It can also be a
12478 string to select a different tag for this task."
12479 :group 'org-todo
12480 :type '(choice
12481 (const :tag "No tracking" nil)
12482 (const :tag "Track with ORDERED tag" t)
12483 (string :tag "Use other tag")))
12484
12485 (defun org-toggle-ordered-property ()
12486 "Toggle the ORDERED property of the current entry.
12487 For better visibility, you can track the value of this property with a tag.
12488 See variable `org-track-ordered-property-with-tag'."
12489 (interactive)
12490 (let* ((t1 org-track-ordered-property-with-tag)
12491 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12492 (save-excursion
12493 (org-back-to-heading)
12494 (if (org-entry-get nil "ORDERED")
12495 (progn
12496 (org-delete-property "ORDERED" "PROPERTIES")
12497 (and tag (org-toggle-tag tag 'off))
12498 (message "Subtasks can be completed in arbitrary order"))
12499 (org-entry-put nil "ORDERED" "t")
12500 (and tag (org-toggle-tag tag 'on))
12501 (message "Subtasks must be completed in sequence")))))
12502
12503 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12504 (defun org-block-todo-from-checkboxes (change-plist)
12505 "Block turning an entry into a TODO, using checkboxes.
12506 This checks whether the current task should be blocked from state
12507 changes because there are unchecked boxes in this entry."
12508 (if (not org-enforce-todo-checkbox-dependencies)
12509 t ; if locally turned off don't block
12510 (catch 'dont-block
12511 ;; If this is not a todo state change, or if this entry is already DONE,
12512 ;; do not block
12513 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12514 (member (plist-get change-plist :from)
12515 (cons 'done org-done-keywords))
12516 (member (plist-get change-plist :to)
12517 (cons 'todo org-not-done-keywords))
12518 (not (plist-get change-plist :to)))
12519 (throw 'dont-block t))
12520 ;; If this task has checkboxes that are not checked, it's blocked
12521 (save-excursion
12522 (org-back-to-heading t)
12523 (let ((beg (point)) end)
12524 (outline-next-heading)
12525 (setq end (point))
12526 (goto-char beg)
12527 (if (org-list-search-forward
12528 (concat (org-item-beginning-re)
12529 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12530 "\\[[- ]\\]")
12531 end t)
12532 (progn
12533 (if (boundp 'org-blocked-by-checkboxes)
12534 (setq org-blocked-by-checkboxes t))
12535 (throw 'dont-block nil)))))
12536 t))) ; do not block
12537
12538 (defun org-entry-blocked-p ()
12539 "Is the current entry blocked?"
12540 (org-with-silent-modifications
12541 (if (org-entry-get nil "NOBLOCKING")
12542 nil ;; Never block this entry
12543 (not (run-hook-with-args-until-failure
12544 'org-blocker-hook
12545 (list :type 'todo-state-change
12546 :position (point)
12547 :from 'todo
12548 :to 'done))))))
12549
12550 (defun org-update-statistics-cookies (all)
12551 "Update the statistics cookie, either from TODO or from checkboxes.
12552 This should be called with the cursor in a line with a statistics cookie."
12553 (interactive "P")
12554 (if all
12555 (progn
12556 (org-update-checkbox-count 'all)
12557 (org-map-entries 'org-update-parent-todo-statistics))
12558 (if (not (org-at-heading-p))
12559 (org-update-checkbox-count)
12560 (let ((pos (point-marker))
12561 end l1 l2)
12562 (ignore-errors (org-back-to-heading t))
12563 (if (not (org-at-heading-p))
12564 (org-update-checkbox-count)
12565 (setq l1 (org-outline-level))
12566 (setq end (save-excursion
12567 (outline-next-heading)
12568 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12569 (point)))
12570 (if (and (save-excursion
12571 (re-search-forward
12572 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12573 (not (save-excursion (re-search-forward
12574 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12575 (org-update-checkbox-count)
12576 (if (and l2 (> l2 l1))
12577 (progn
12578 (goto-char end)
12579 (org-update-parent-todo-statistics))
12580 (goto-char pos)
12581 (beginning-of-line 1)
12582 (while (re-search-forward
12583 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12584 (point-at-eol) t)
12585 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12586 (goto-char pos)
12587 (move-marker pos nil)))))
12588
12589 (defvar org-entry-property-inherited-from) ;; defined below
12590 (defun org-update-parent-todo-statistics ()
12591 "Update any statistics cookie in the parent of the current headline.
12592 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12593 the entire subtree and this will travel up the hierarchy and update
12594 statistics everywhere."
12595 (let* ((prop (save-excursion (org-up-heading-safe)
12596 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12597 (recursive (or (not org-hierarchical-todo-statistics)
12598 (and prop (string-match "\\<recursive\\>" prop))))
12599 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12600 0))
12601 (first t)
12602 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12603 level ltoggle l1 new ndel
12604 (cnt-all 0) (cnt-done 0) is-percent kwd
12605 checkbox-beg ov ovs ove cookie-present)
12606 (catch 'exit
12607 (save-excursion
12608 (beginning-of-line 1)
12609 (setq ltoggle (funcall outline-level))
12610 ;; Three situations are to consider:
12611
12612 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12613 ;; to the top-level ancestor on the headline;
12614
12615 ;; 2. If parent has "recursive" property, repeat up to the
12616 ;; headline setting that property, taking inheritance into
12617 ;; account;
12618
12619 ;; 3. Else, move up to direct parent and proceed only once.
12620 (while (and (setq level (org-up-heading-safe))
12621 (or recursive first)
12622 (>= (point) lim))
12623 (setq first nil cookie-present nil)
12624 (unless (and level
12625 (not (string-match
12626 "\\<checkbox\\>"
12627 (downcase (or (org-entry-get nil "COOKIE_DATA")
12628 "")))))
12629 (throw 'exit nil))
12630 (while (re-search-forward box-re (point-at-eol) t)
12631 (setq cnt-all 0 cnt-done 0 cookie-present t)
12632 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12633 (save-match-data
12634 (unless (outline-next-heading) (throw 'exit nil))
12635 (while (and (looking-at org-complex-heading-regexp)
12636 (> (setq l1 (length (match-string 1))) level))
12637 (setq kwd (and (or recursive (= l1 ltoggle))
12638 (match-string 2)))
12639 (if (or (eq org-provide-todo-statistics 'all-headlines)
12640 (and (listp org-provide-todo-statistics)
12641 (or (member kwd org-provide-todo-statistics)
12642 (member kwd org-done-keywords))))
12643 (setq cnt-all (1+ cnt-all))
12644 (if (eq org-provide-todo-statistics t)
12645 (and kwd (setq cnt-all (1+ cnt-all)))))
12646 (and (member kwd org-done-keywords)
12647 (setq cnt-done (1+ cnt-done)))
12648 (outline-next-heading)))
12649 (setq new
12650 (if is-percent
12651 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12652 (format "[%d/%d]" cnt-done cnt-all))
12653 ndel (- (match-end 0) checkbox-beg))
12654 ;; handle overlays when updating cookie from column view
12655 (when (setq ov (car (overlays-at checkbox-beg)))
12656 (setq ovs (overlay-start ov) ove (overlay-end ov))
12657 (delete-overlay ov))
12658 (goto-char checkbox-beg)
12659 (insert new)
12660 (delete-region (point) (+ (point) ndel))
12661 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12662 (when ov (move-overlay ov ovs ove)))
12663 (when cookie-present
12664 (run-hook-with-args 'org-after-todo-statistics-hook
12665 cnt-done (- cnt-all cnt-done))))))
12666 (run-hooks 'org-todo-statistics-hook)))
12667
12668 (defvar org-after-todo-statistics-hook nil
12669 "Hook that is called after a TODO statistics cookie has been updated.
12670 Each function is called with two arguments: the number of not-done entries
12671 and the number of done entries.
12672
12673 For example, the following function, when added to this hook, will switch
12674 an entry to DONE when all children are done, and back to TODO when new
12675 entries are set to a TODO status. Note that this hook is only called
12676 when there is a statistics cookie in the headline!
12677
12678 (defun org-summary-todo (n-done n-not-done)
12679 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12680 (let (org-log-done org-log-states) ; turn off logging
12681 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12682 ")
12683
12684 (defvar org-todo-statistics-hook nil
12685 "Hook that is run whenever Org thinks TODO statistics should be updated.
12686 This hook runs even if there is no statistics cookie present, in which case
12687 `org-after-todo-statistics-hook' would not run.")
12688
12689 (defun org-todo-trigger-tag-changes (state)
12690 "Apply the changes defined in `org-todo-state-tags-triggers'."
12691 (let ((l org-todo-state-tags-triggers)
12692 changes)
12693 (when (or (not state) (equal state ""))
12694 (setq changes (append changes (cdr (assoc "" l)))))
12695 (when (and (stringp state) (> (length state) 0))
12696 (setq changes (append changes (cdr (assoc state l)))))
12697 (when (member state org-not-done-keywords)
12698 (setq changes (append changes (cdr (assoc 'todo l)))))
12699 (when (member state org-done-keywords)
12700 (setq changes (append changes (cdr (assoc 'done l)))))
12701 (dolist (c changes)
12702 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12703
12704 (defun org-local-logging (value)
12705 "Get logging settings from a property VALUE."
12706 (let* (words w a)
12707 ;; directly set the variables, they are already local.
12708 (setq org-log-done nil
12709 org-log-repeat nil
12710 org-todo-log-states nil)
12711 (setq words (org-split-string value))
12712 (while (setq w (pop words))
12713 (cond
12714 ((setq a (assoc w org-startup-options))
12715 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12716 (set (nth 1 a) (nth 2 a))))
12717 ((setq a (org-extract-log-state-settings w))
12718 (and (member (car a) org-todo-keywords-1)
12719 (push a org-todo-log-states)))))))
12720
12721 (defun org-get-todo-sequence-head (kwd)
12722 "Return the head of the TODO sequence to which KWD belongs.
12723 If KWD is not set, check if there is a text property remembering the
12724 right sequence."
12725 (let (p)
12726 (cond
12727 ((not kwd)
12728 (or (get-text-property (point-at-bol) 'org-todo-head)
12729 (progn
12730 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12731 nil (point-at-eol)))
12732 (get-text-property p 'org-todo-head))))
12733 ((not (member kwd org-todo-keywords-1))
12734 (car org-todo-keywords-1))
12735 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12736
12737 (defun org-fast-todo-selection ()
12738 "Fast TODO keyword selection with single keys.
12739 Returns the new TODO keyword, or nil if no state change should occur."
12740 (let* ((fulltable org-todo-key-alist)
12741 (done-keywords org-done-keywords) ;; needed for the faces.
12742 (maxlen (apply 'max (mapcar
12743 (lambda (x)
12744 (if (stringp (car x)) (string-width (car x)) 0))
12745 fulltable)))
12746 (expert nil)
12747 (fwidth (+ maxlen 3 1 3))
12748 (ncol (/ (- (window-width) 4) fwidth))
12749 tg cnt e c tbl
12750 groups ingroup)
12751 (save-excursion
12752 (save-window-excursion
12753 (if expert
12754 (set-buffer (get-buffer-create " *Org todo*"))
12755 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12756 (erase-buffer)
12757 (org-set-local 'org-done-keywords done-keywords)
12758 (setq tbl fulltable cnt 0)
12759 (while (setq e (pop tbl))
12760 (cond
12761 ((equal e '(:startgroup))
12762 (push '() groups) (setq ingroup t)
12763 (when (not (= cnt 0))
12764 (setq cnt 0)
12765 (insert "\n"))
12766 (insert "{ "))
12767 ((equal e '(:endgroup))
12768 (setq ingroup nil cnt 0)
12769 (insert "}\n"))
12770 ((equal e '(:newline))
12771 (when (not (= cnt 0))
12772 (setq cnt 0)
12773 (insert "\n")
12774 (setq e (car tbl))
12775 (while (equal (car tbl) '(:newline))
12776 (insert "\n")
12777 (setq tbl (cdr tbl)))))
12778 (t
12779 (setq tg (car e) c (cdr e))
12780 (if ingroup (push tg (car groups)))
12781 (setq tg (org-add-props tg nil 'face
12782 (org-get-todo-face tg)))
12783 (if (and (= cnt 0) (not ingroup)) (insert " "))
12784 (insert "[" c "] " tg (make-string
12785 (- fwidth 4 (length tg)) ?\ ))
12786 (when (= (setq cnt (1+ cnt)) ncol)
12787 (insert "\n")
12788 (if ingroup (insert " "))
12789 (setq cnt 0)))))
12790 (insert "\n")
12791 (goto-char (point-min))
12792 (if (not expert) (org-fit-window-to-buffer))
12793 (message "[a-z..]:Set [SPC]:clear")
12794 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12795 (cond
12796 ((or (= c ?\C-g)
12797 (and (= c ?q) (not (rassoc c fulltable))))
12798 (setq quit-flag t))
12799 ((= c ?\ ) nil)
12800 ((setq e (rassoc c fulltable) tg (car e))
12801 tg)
12802 (t (setq quit-flag t)))))))
12803
12804 (defun org-entry-is-todo-p ()
12805 (member (org-get-todo-state) org-not-done-keywords))
12806
12807 (defun org-entry-is-done-p ()
12808 (member (org-get-todo-state) org-done-keywords))
12809
12810 (defun org-get-todo-state ()
12811 "Return the TODO keyword of the current subtree."
12812 (save-excursion
12813 (org-back-to-heading t)
12814 (and (looking-at org-todo-line-regexp)
12815 (match-end 2)
12816 (match-string 2))))
12817
12818 (defun org-at-date-range-p (&optional inactive-ok)
12819 "Is the cursor inside a date range?"
12820 (interactive)
12821 (save-excursion
12822 (catch 'exit
12823 (let ((pos (point)))
12824 (skip-chars-backward "^[<\r\n")
12825 (skip-chars-backward "<[")
12826 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12827 (>= (match-end 0) pos)
12828 (throw 'exit t))
12829 (skip-chars-backward "^<[\r\n")
12830 (skip-chars-backward "<[")
12831 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12832 (>= (match-end 0) pos)
12833 (throw 'exit t)))
12834 nil)))
12835
12836 (defun org-get-repeat (&optional tagline)
12837 "Check if there is a deadline/schedule with repeater in this entry."
12838 (save-match-data
12839 (save-excursion
12840 (org-back-to-heading t)
12841 (and (re-search-forward (if tagline
12842 (concat tagline "\\s-*" org-repeat-re)
12843 org-repeat-re)
12844 (org-entry-end-position) t)
12845 (match-string-no-properties 1)))))
12846
12847 (defvar org-last-changed-timestamp)
12848 (defvar org-last-inserted-timestamp)
12849 (defvar org-log-post-message)
12850 (defvar org-log-note-purpose)
12851 (defvar org-log-note-how)
12852 (defvar org-log-note-extra)
12853 (defun org-auto-repeat-maybe (done-word)
12854 "Check if the current headline contains a repeated deadline/schedule.
12855 If yes, set TODO state back to what it was and change the base date
12856 of repeating deadline/scheduled time stamps to new date.
12857 This function is run automatically after each state change to a DONE state."
12858 ;; last-state is dynamically scoped into this function
12859 (let* ((repeat (org-get-repeat))
12860 (aa (assoc org-last-state org-todo-kwd-alist))
12861 (interpret (nth 1 aa))
12862 (head (nth 2 aa))
12863 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12864 (msg "Entry repeats: ")
12865 (org-log-done nil)
12866 (org-todo-log-states nil)
12867 re type n what ts time to-state)
12868 (when repeat
12869 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12870 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12871 org-todo-repeat-to-state))
12872 (unless (and to-state (member to-state org-todo-keywords-1))
12873 (setq to-state (if (eq interpret 'type) org-last-state head)))
12874 (org-todo to-state)
12875 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12876 (org-entry-put nil "LAST_REPEAT" (format-time-string
12877 (org-time-stamp-format t t))))
12878 (when org-log-repeat
12879 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12880 (memq 'org-add-log-note post-command-hook))
12881 ;; OK, we are already setup for some record
12882 (if (eq org-log-repeat 'note)
12883 ;; make sure we take a note, not only a time stamp
12884 (setq org-log-note-how 'note))
12885 ;; Set up for taking a record
12886 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12887 org-last-state
12888 'findpos org-log-repeat)))
12889 (org-back-to-heading t)
12890 (org-add-planning-info nil nil 'closed)
12891 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12892 org-deadline-time-regexp "\\)\\|\\("
12893 org-ts-regexp "\\)"))
12894 (while (re-search-forward
12895 re (save-excursion (outline-next-heading) (point)) t)
12896 (setq type (if (match-end 1) org-scheduled-string
12897 (if (match-end 3) org-deadline-string "Plain:"))
12898 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12899 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12900 (setq n (string-to-number (match-string 2 ts))
12901 what (match-string 3 ts))
12902 (if (equal what "w") (setq n (* n 7) what "d"))
12903 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12904 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12905 ;; Preparation, see if we need to modify the start date for the change
12906 (when (match-end 1)
12907 (setq time (save-match-data (org-time-string-to-time ts)))
12908 (cond
12909 ((equal (match-string 1 ts) ".")
12910 ;; Shift starting date to today
12911 (org-timestamp-change
12912 (- (org-today) (time-to-days time))
12913 'day))
12914 ((equal (match-string 1 ts) "+")
12915 (let ((nshiftmax 10) (nshift 0))
12916 (while (or (= nshift 0)
12917 (<= (time-to-days time)
12918 (time-to-days (current-time))))
12919 (when (= (incf nshift) nshiftmax)
12920 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12921 (error "Abort")))
12922 (org-timestamp-change n (cdr (assoc what whata)))
12923 (org-at-timestamp-p t)
12924 (setq ts (match-string 1))
12925 (setq time (save-match-data (org-time-string-to-time ts)))))
12926 (org-timestamp-change (- n) (cdr (assoc what whata)))
12927 ;; rematch, so that we have everything in place for the real shift
12928 (org-at-timestamp-p t)
12929 (setq ts (match-string 1))
12930 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12931 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12932 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12933 (setq org-log-post-message msg)
12934 (message "%s" msg))))
12935
12936 (defun org-show-todo-tree (arg)
12937 "Make a compact tree which shows all headlines marked with TODO.
12938 The tree will show the lines where the regexp matches, and all higher
12939 headlines above the match.
12940 With a \\[universal-argument] prefix, prompt for a regexp to match.
12941 With a numeric prefix N, construct a sparse tree for the Nth element
12942 of `org-todo-keywords-1'."
12943 (interactive "P")
12944 (let ((case-fold-search nil)
12945 (kwd-re
12946 (cond ((null arg) org-not-done-regexp)
12947 ((equal arg '(4))
12948 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12949 (mapcar 'list org-todo-keywords-1))))
12950 (concat "\\("
12951 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12952 "\\)\\>")))
12953 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12954 (regexp-quote (nth (1- (prefix-numeric-value arg))
12955 org-todo-keywords-1)))
12956 (t (user-error "Invalid prefix argument: %s" arg)))))
12957 (message "%d TODO entries found"
12958 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12959
12960 (defun org-deadline (arg &optional time)
12961 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12962 With one universal prefix argument, remove any deadline from the item.
12963 With two universal prefix arguments, prompt for a warning delay.
12964 With argument TIME, set the deadline at the corresponding date. TIME
12965 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12966 (interactive "P")
12967 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12968 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12969 'region-start-level 'region))
12970 org-loop-over-headlines-in-active-region)
12971 (org-map-entries
12972 `(org-deadline ',arg ,time)
12973 org-loop-over-headlines-in-active-region
12974 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12975 (let* ((old-date (org-entry-get nil "DEADLINE"))
12976 (old-date-time (if old-date (org-time-string-to-time old-date)))
12977 (repeater (and old-date
12978 (string-match
12979 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12980 old-date)
12981 (match-string 1 old-date))))
12982 (cond
12983 ((equal arg '(4))
12984 (when (and old-date org-log-redeadline)
12985 (org-add-log-setup 'deldeadline nil old-date 'findpos
12986 org-log-redeadline))
12987 (org-remove-timestamp-with-keyword org-deadline-string)
12988 (message "Item no longer has a deadline."))
12989 ((equal arg '(16))
12990 (save-excursion
12991 (org-back-to-heading t)
12992 (if (re-search-forward
12993 org-deadline-time-regexp
12994 (save-excursion (outline-next-heading) (point)) t)
12995 (let* ((rpl0 (match-string 1))
12996 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12997 (replace-match
12998 (concat org-deadline-string
12999 " <" rpl
13000 (format " -%dd"
13001 (abs
13002 (- (time-to-days
13003 (save-match-data
13004 (org-read-date nil t nil "Warn starting from" old-date-time)))
13005 (time-to-days old-date-time))))
13006 ">") t t))
13007 (user-error "No deadline information to update"))))
13008 (t
13009 (org-add-planning-info 'deadline time 'closed)
13010 (when (and old-date org-log-redeadline
13011 (not (equal old-date
13012 (substring org-last-inserted-timestamp 1 -1))))
13013 (org-add-log-setup 'redeadline nil old-date 'findpos
13014 org-log-redeadline))
13015 (when repeater
13016 (save-excursion
13017 (org-back-to-heading t)
13018 (when (re-search-forward (concat org-deadline-string " "
13019 org-last-inserted-timestamp)
13020 (save-excursion
13021 (outline-next-heading) (point)) t)
13022 (goto-char (1- (match-end 0)))
13023 (insert " " repeater)
13024 (setq org-last-inserted-timestamp
13025 (concat (substring org-last-inserted-timestamp 0 -1)
13026 " " repeater
13027 (substring org-last-inserted-timestamp -1))))))
13028 (message "Deadline on %s" org-last-inserted-timestamp))))))
13029
13030 (defun org-schedule (arg &optional time)
13031 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13032 With one universal prefix argument, remove any scheduling date from the item.
13033 With two universal prefix arguments, prompt for a delay cookie.
13034 With argument TIME, scheduled at the corresponding date. TIME can
13035 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13036 (interactive "P")
13037 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13038 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13039 'region-start-level 'region))
13040 org-loop-over-headlines-in-active-region)
13041 (org-map-entries
13042 `(org-schedule ',arg ,time)
13043 org-loop-over-headlines-in-active-region
13044 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13045 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13046 (old-date-time (if old-date (org-time-string-to-time old-date)))
13047 (repeater (and old-date
13048 (string-match
13049 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13050 old-date)
13051 (match-string 1 old-date))))
13052 (cond
13053 ((equal arg '(4))
13054 (progn
13055 (when (and old-date org-log-reschedule)
13056 (org-add-log-setup 'delschedule nil old-date 'findpos
13057 org-log-reschedule))
13058 (org-remove-timestamp-with-keyword org-scheduled-string)
13059 (message "Item is no longer scheduled.")))
13060 ((equal arg '(16))
13061 (save-excursion
13062 (org-back-to-heading t)
13063 (if (re-search-forward
13064 org-scheduled-time-regexp
13065 (save-excursion (outline-next-heading) (point)) t)
13066 (let* ((rpl0 (match-string 1))
13067 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13068 (replace-match
13069 (concat org-scheduled-string
13070 " <" rpl
13071 (format " -%dd"
13072 (abs
13073 (- (time-to-days
13074 (save-match-data
13075 (org-read-date nil t nil "Delay until" old-date-time)))
13076 (time-to-days old-date-time))))
13077 ">") t t))
13078 (user-error "No scheduled information to update"))))
13079 (t
13080 (org-add-planning-info 'scheduled time 'closed)
13081 (when (and old-date org-log-reschedule
13082 (not (equal old-date
13083 (substring org-last-inserted-timestamp 1 -1))))
13084 (org-add-log-setup 'reschedule nil old-date 'findpos
13085 org-log-reschedule))
13086 (when repeater
13087 (save-excursion
13088 (org-back-to-heading t)
13089 (when (re-search-forward (concat org-scheduled-string " "
13090 org-last-inserted-timestamp)
13091 (save-excursion
13092 (outline-next-heading) (point)) t)
13093 (goto-char (1- (match-end 0)))
13094 (insert " " repeater)
13095 (setq org-last-inserted-timestamp
13096 (concat (substring org-last-inserted-timestamp 0 -1)
13097 " " repeater
13098 (substring org-last-inserted-timestamp -1))))))
13099 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13100
13101 (defun org-get-scheduled-time (pom &optional inherit)
13102 "Get the scheduled time as a time tuple, of a format suitable
13103 for calling org-schedule with, or if there is no scheduling,
13104 returns nil."
13105 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13106 (when time
13107 (apply 'encode-time (org-parse-time-string time)))))
13108
13109 (defun org-get-deadline-time (pom &optional inherit)
13110 "Get the deadline as a time tuple, of a format suitable for
13111 calling org-deadline with, or if there is no scheduling, returns
13112 nil."
13113 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13114 (when time
13115 (apply 'encode-time (org-parse-time-string time)))))
13116
13117 (defun org-remove-timestamp-with-keyword (keyword)
13118 "Remove all time stamps with KEYWORD in the current entry."
13119 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13120 beg)
13121 (save-excursion
13122 (org-back-to-heading t)
13123 (setq beg (point))
13124 (outline-next-heading)
13125 (while (re-search-backward re beg t)
13126 (replace-match "")
13127 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13128 (equal (char-before) ?\ ))
13129 (backward-delete-char 1)
13130 (if (string-match "^[ \t]*$" (buffer-substring
13131 (point-at-bol) (point-at-eol)))
13132 (delete-region (point-at-bol)
13133 (min (point-max) (1+ (point-at-eol))))))))))
13134
13135 (defvar org-time-was-given) ; dynamically scoped parameter
13136 (defvar org-end-time-was-given) ; dynamically scoped parameter
13137
13138 (defun org-add-planning-info (what &optional time &rest remove)
13139 "Insert new timestamp with keyword in the line directly after the headline.
13140 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13141 If non is given, the user is prompted for a date.
13142 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13143 be removed."
13144 (interactive)
13145 (let (org-time-was-given org-end-time-was-given ts
13146 end default-time default-input)
13147
13148 (catch 'exit
13149 (when (and (memq what '(scheduled deadline))
13150 (or (not time)
13151 (and (stringp time)
13152 (string-match "^[-+]+[0-9]" time))))
13153 ;; Try to get a default date/time from existing timestamp
13154 (save-excursion
13155 (org-back-to-heading t)
13156 (setq end (save-excursion (outline-next-heading) (point)))
13157 (when (re-search-forward (if (eq what 'scheduled)
13158 org-scheduled-time-regexp
13159 org-deadline-time-regexp)
13160 end t)
13161 (setq ts (match-string 1)
13162 default-time
13163 (apply 'encode-time (org-parse-time-string ts))
13164 default-input (and ts (org-get-compact-tod ts))))))
13165 (when what
13166 (setq time
13167 (if (stringp time)
13168 ;; This is a string (relative or absolute), set proper date
13169 (apply 'encode-time
13170 (org-read-date-analyze
13171 time default-time (decode-time default-time)))
13172 ;; If necessary, get the time from the user
13173 (or time (org-read-date nil 'to-time nil nil
13174 default-time default-input)))))
13175
13176 (when (and org-insert-labeled-timestamps-at-point
13177 (member what '(scheduled deadline)))
13178 (insert
13179 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13180 (org-insert-time-stamp time org-time-was-given
13181 nil nil nil (list org-end-time-was-given))
13182 (setq what nil))
13183 (save-excursion
13184 (save-restriction
13185 (let (col list elt ts buffer-invisibility-spec)
13186 (org-back-to-heading t)
13187 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13188 (goto-char (match-end 1))
13189 (setq col (current-column))
13190 (goto-char (match-end 0))
13191 (if (eobp) (insert "\n") (forward-char 1))
13192 (when (and (not what)
13193 (not (looking-at
13194 (concat "[ \t]*"
13195 org-keyword-time-not-clock-regexp))))
13196 ;; Nothing to add, nothing to remove...... :-)
13197 (throw 'exit nil))
13198 (if (and (not (looking-at org-outline-regexp))
13199 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13200 "[^\r\n]*"))
13201 (not (equal (match-string 1) org-clock-string)))
13202 (narrow-to-region (match-beginning 0) (match-end 0))
13203 (insert-before-markers "\n")
13204 (backward-char 1)
13205 (narrow-to-region (point) (point))
13206 (and org-adapt-indentation (org-indent-to-column col)))
13207 ;; Check if we have to remove something.
13208 (setq list (cons what remove))
13209 (while list
13210 (setq elt (pop list))
13211 (when (or (and (eq elt 'scheduled)
13212 (re-search-forward org-scheduled-time-regexp nil t))
13213 (and (eq elt 'deadline)
13214 (re-search-forward org-deadline-time-regexp nil t))
13215 (and (eq elt 'closed)
13216 (re-search-forward org-closed-time-regexp nil t)))
13217 (replace-match "")
13218 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13219 (and (looking-at "[ \t]+") (replace-match ""))
13220 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13221 (when what
13222 (insert
13223 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13224 (cond ((eq what 'scheduled) org-scheduled-string)
13225 ((eq what 'deadline) org-deadline-string)
13226 ((eq what 'closed) org-closed-string))
13227 " ")
13228 (setq ts (org-insert-time-stamp
13229 time
13230 (or org-time-was-given
13231 (and (eq what 'closed) org-log-done-with-time))
13232 (eq what 'closed)
13233 nil nil (list org-end-time-was-given)))
13234 (insert
13235 (if (not (or (bolp) (eq (char-before) ?\ )
13236 (memq (char-after) '(32 10))
13237 (eobp))) " " ""))
13238 (end-of-line 1))
13239 (goto-char (point-min))
13240 (widen)
13241 (if (and (looking-at "[ \t]*\n")
13242 (equal (char-before) ?\n))
13243 (delete-region (1- (point)) (point-at-eol)))
13244 ts))))))
13245
13246 (defvar org-log-note-marker (make-marker))
13247 (defvar org-log-note-purpose nil)
13248 (defvar org-log-note-state nil)
13249 (defvar org-log-note-previous-state nil)
13250 (defvar org-log-note-how nil)
13251 (defvar org-log-note-extra nil)
13252 (defvar org-log-note-window-configuration nil)
13253 (defvar org-log-note-return-to (make-marker))
13254 (defvar org-log-note-effective-time nil
13255 "Remembered current time so that dynamically scoped
13256 `org-extend-today-until' affects tha timestamps in state change
13257 log")
13258
13259 (defvar org-log-post-message nil
13260 "Message to be displayed after a log note has been stored.
13261 The auto-repeater uses this.")
13262
13263 (defun org-add-note ()
13264 "Add a note to the current entry.
13265 This is done in the same way as adding a state change note."
13266 (interactive)
13267 (org-add-log-setup 'note nil nil 'findpos nil))
13268
13269 (defvar org-property-end-re)
13270 (defun org-add-log-setup (&optional purpose state prev-state
13271 findpos how extra)
13272 "Set up the post command hook to take a note.
13273 If this is about to TODO state change, the new state is expected in STATE.
13274 When FINDPOS is non-nil, find the correct position for the note in
13275 the current entry. If not, assume that it can be inserted at point.
13276 HOW is an indicator what kind of note should be created.
13277 EXTRA is additional text that will be inserted into the notes buffer."
13278 (let* ((org-log-into-drawer (org-log-into-drawer))
13279 (drawer (cond ((stringp org-log-into-drawer)
13280 org-log-into-drawer)
13281 (org-log-into-drawer "LOGBOOK"))))
13282 (save-restriction
13283 (save-excursion
13284 (when findpos
13285 (org-back-to-heading t)
13286 (narrow-to-region (point) (save-excursion
13287 (outline-next-heading) (point)))
13288 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13289 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13290 "[^\r\n]*\\)?"))
13291 (goto-char (match-end 0))
13292 (cond
13293 (drawer
13294 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13295 nil t)
13296 (progn
13297 (goto-char (match-end 0))
13298 (or org-log-states-order-reversed
13299 (and (re-search-forward org-property-end-re nil t)
13300 (goto-char (1- (match-beginning 0))))))
13301 (insert "\n:" drawer ":\n:END:")
13302 (beginning-of-line 0)
13303 (org-indent-line)
13304 (beginning-of-line 2)
13305 (org-indent-line)
13306 (end-of-line 0)))
13307 ((and org-log-state-notes-insert-after-drawers
13308 (save-excursion
13309 (forward-line) (looking-at org-drawer-regexp)))
13310 (forward-line)
13311 (while (looking-at org-drawer-regexp)
13312 (goto-char (match-end 0))
13313 (re-search-forward org-property-end-re (point-max) t)
13314 (forward-line))
13315 (forward-line -1)))
13316 (unless org-log-states-order-reversed
13317 (and (= (char-after) ?\n) (forward-char 1))
13318 (org-skip-over-state-notes)
13319 (skip-chars-backward " \t\n\r")))
13320 (move-marker org-log-note-marker (point))
13321 (setq org-log-note-purpose purpose
13322 org-log-note-state state
13323 org-log-note-previous-state prev-state
13324 org-log-note-how how
13325 org-log-note-extra extra
13326 org-log-note-effective-time (org-current-effective-time))
13327 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13328
13329 (defun org-skip-over-state-notes ()
13330 "Skip past the list of State notes in an entry."
13331 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13332 (when (ignore-errors (goto-char (org-in-item-p)))
13333 (let* ((struct (org-list-struct))
13334 (prevs (org-list-prevs-alist struct)))
13335 (while (looking-at "[ \t]*- State")
13336 (goto-char (or (org-list-get-next-item (point) struct prevs)
13337 (org-list-get-item-end (point) struct)))))))
13338
13339 (defun org-add-log-note (&optional purpose)
13340 "Pop up a window for taking a note, and add this note later at point."
13341 (remove-hook 'post-command-hook 'org-add-log-note)
13342 (setq org-log-note-window-configuration (current-window-configuration))
13343 (delete-other-windows)
13344 (move-marker org-log-note-return-to (point))
13345 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13346 (goto-char org-log-note-marker)
13347 (org-switch-to-buffer-other-window "*Org Note*")
13348 (erase-buffer)
13349 (if (memq org-log-note-how '(time state))
13350 (let (current-prefix-arg) (org-store-log-note))
13351 (let ((org-inhibit-startup t)) (org-mode))
13352 (insert (format "# Insert note for %s.
13353 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13354 (cond
13355 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13356 ((eq org-log-note-purpose 'done) "closed todo item")
13357 ((eq org-log-note-purpose 'state)
13358 (format "state change from \"%s\" to \"%s\""
13359 (or org-log-note-previous-state "")
13360 (or org-log-note-state "")))
13361 ((eq org-log-note-purpose 'reschedule)
13362 "rescheduling")
13363 ((eq org-log-note-purpose 'delschedule)
13364 "no longer scheduled")
13365 ((eq org-log-note-purpose 'redeadline)
13366 "changing deadline")
13367 ((eq org-log-note-purpose 'deldeadline)
13368 "removing deadline")
13369 ((eq org-log-note-purpose 'refile)
13370 "refiling")
13371 ((eq org-log-note-purpose 'note)
13372 "this entry")
13373 (t (error "This should not happen")))))
13374 (if org-log-note-extra (insert org-log-note-extra))
13375 (org-set-local 'org-finish-function 'org-store-log-note)
13376 (run-hooks 'org-log-buffer-setup-hook)))
13377
13378 (defvar org-note-abort nil) ; dynamically scoped
13379 (defun org-store-log-note ()
13380 "Finish taking a log note, and insert it to where it belongs."
13381 (let ((txt (buffer-string)))
13382 (kill-buffer (current-buffer))
13383 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13384 lines ind bul)
13385 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13386 (setq txt (replace-match "" t t txt)))
13387 (if (string-match "\\s-+\\'" txt)
13388 (setq txt (replace-match "" t t txt)))
13389 (setq lines (org-split-string txt "\n"))
13390 (when (and note (string-match "\\S-" note))
13391 (setq note
13392 (org-replace-escapes
13393 note
13394 (list (cons "%u" (user-login-name))
13395 (cons "%U" user-full-name)
13396 (cons "%t" (format-time-string
13397 (org-time-stamp-format 'long 'inactive)
13398 org-log-note-effective-time))
13399 (cons "%T" (format-time-string
13400 (org-time-stamp-format 'long nil)
13401 org-log-note-effective-time))
13402 (cons "%d" (format-time-string
13403 (org-time-stamp-format nil 'inactive)
13404 org-log-note-effective-time))
13405 (cons "%D" (format-time-string
13406 (org-time-stamp-format nil nil)
13407 org-log-note-effective-time))
13408 (cons "%s" (if org-log-note-state
13409 (concat "\"" org-log-note-state "\"")
13410 ""))
13411 (cons "%S" (if org-log-note-previous-state
13412 (concat "\"" org-log-note-previous-state "\"")
13413 "\"\"")))))
13414 (if lines (setq note (concat note " \\\\")))
13415 (push note lines))
13416 (when (or current-prefix-arg org-note-abort)
13417 (when org-log-into-drawer
13418 (org-remove-empty-drawer-at
13419 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13420 org-log-note-marker))
13421 (setq lines nil))
13422 (when lines
13423 (with-current-buffer (marker-buffer org-log-note-marker)
13424 (save-excursion
13425 (goto-char org-log-note-marker)
13426 (move-marker org-log-note-marker nil)
13427 (end-of-line 1)
13428 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13429 (setq ind (save-excursion
13430 (if (ignore-errors (goto-char (org-in-item-p)))
13431 (let ((struct (org-list-struct)))
13432 (org-list-get-ind
13433 (org-list-get-top-point struct) struct))
13434 (skip-chars-backward " \r\t\n")
13435 (cond
13436 ((and (org-at-heading-p)
13437 org-adapt-indentation)
13438 (1+ (org-current-level)))
13439 ((org-at-heading-p) 0)
13440 (t (org-get-indentation))))))
13441 (setq bul (org-list-bullet-string "-"))
13442 (org-indent-line-to ind)
13443 (insert bul (pop lines))
13444 (let ((ind-body (+ (length bul) ind)))
13445 (while lines
13446 (insert "\n")
13447 (org-indent-line-to ind-body)
13448 (insert (pop lines))))
13449 (message "Note stored")
13450 (org-back-to-heading t)
13451 (org-cycle-hide-drawers 'children))
13452 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13453 ;; from within `org-add-log-note' because `buffer-undo-list'
13454 ;; is then modified outside of `org-with-remote-undo'.
13455 (when (eq this-command 'org-agenda-todo)
13456 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13457 ;; Don't add undo information when called from `org-agenda-todo'
13458 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13459 (set-window-configuration org-log-note-window-configuration)
13460 (with-current-buffer (marker-buffer org-log-note-return-to)
13461 (goto-char org-log-note-return-to))
13462 (move-marker org-log-note-return-to nil)
13463 (and org-log-post-message (message "%s" org-log-post-message))))
13464
13465 (defun org-remove-empty-drawer-at (drawer pos)
13466 "Remove an empty drawer DRAWER at position POS.
13467 POS may also be a marker."
13468 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13469 (save-excursion
13470 (save-restriction
13471 (widen)
13472 (goto-char pos)
13473 (if (org-in-regexp
13474 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13475 (replace-match ""))))))
13476
13477 (defvar org-ts-type nil)
13478 (defun org-sparse-tree (&optional arg type)
13479 "Create a sparse tree, prompt for the details.
13480 This command can create sparse trees. You first need to select the type
13481 of match used to create the tree:
13482
13483 t Show all TODO entries.
13484 T Show entries with a specific TODO keyword.
13485 m Show entries selected by a tags/property match.
13486 p Enter a property name and its value (both with completion on existing
13487 names/values) and show entries with that property.
13488 r Show entries matching a regular expression (`/' can be used as well).
13489 b Show deadlines and scheduled items before a date.
13490 a Show deadlines and scheduled items after a date.
13491 d Show deadlines due within `org-deadline-warning-days'.
13492 D Show deadlines and scheduled items between a date range."
13493 (interactive "P")
13494 (setq type (or type org-sparse-tree-default-date-type))
13495 (setq org-ts-type type)
13496 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13497 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13498 [c]ycle through date types: %s"
13499 (case type
13500 (all "all timestamps")
13501 (scheduled "only scheduled")
13502 (deadline "only deadline")
13503 (active "only active timestamps")
13504 (inactive "only inactive timestamps")
13505 (scheduled-or-deadline "scheduled/deadline")
13506 (closed "with a closed time-stamp")
13507 (otherwise "scheduled/deadline")))
13508 (let ((answer (read-char-exclusive)))
13509 (case answer
13510 (?c
13511 (org-sparse-tree
13512 arg
13513 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13514 inactive closed)))))
13515 (?d (call-interactively #'org-check-deadlines))
13516 (?b (call-interactively #'org-check-before-date))
13517 (?a (call-interactively #'org-check-after-date))
13518 (?D (call-interactively #'org-check-dates-range))
13519 (?t (call-interactively #'org-show-todo-tree))
13520 (?T (org-show-todo-tree '(4)))
13521 (?m (call-interactively #'org-match-sparse-tree))
13522 ((?p ?P)
13523 (let* ((kwd (org-icompleting-read
13524 "Property: " (mapcar #'list (org-buffer-property-keys))))
13525 (value (org-icompleting-read
13526 "Value: " (mapcar #'list (org-property-values kwd)))))
13527 (unless (string-match "\\`{.*}\\'" value)
13528 (setq value (concat "\"" value "\"")))
13529 (org-match-sparse-tree arg (concat kwd "=" value))))
13530 ((?r ?R ?/) (call-interactively #'org-occur))
13531 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13532
13533 (defvar org-occur-highlights nil
13534 "List of overlays used for occur matches.")
13535 (make-variable-buffer-local 'org-occur-highlights)
13536 (defvar org-occur-parameters nil
13537 "Parameters of the active org-occur calls.
13538 This is a list, each call to org-occur pushes as cons cell,
13539 containing the regular expression and the callback, onto the list.
13540 The list can contain several entries if `org-occur' has been called
13541 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13542 will only contain one set of parameters. When the highlights are
13543 removed (for example with `C-c C-c', or with the next edit (depending
13544 on `org-remove-highlights-with-change'), this variable is emptied
13545 as well.")
13546 (make-variable-buffer-local 'org-occur-parameters)
13547
13548 (defun org-occur (regexp &optional keep-previous callback)
13549 "Make a compact tree which shows all matches of REGEXP.
13550 The tree will show the lines where the regexp matches, and all higher
13551 headlines above the match. It will also show the heading after the match,
13552 to make sure editing the matching entry is easy.
13553 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13554 call to `org-occur' will be kept, to allow stacking of calls to this
13555 command.
13556 If CALLBACK is non-nil, it is a function which is called to confirm
13557 that the match should indeed be shown."
13558 (interactive "sRegexp: \nP")
13559 (when (equal regexp "")
13560 (user-error "Regexp cannot be empty"))
13561 (unless keep-previous
13562 (org-remove-occur-highlights nil nil t))
13563 (push (cons regexp callback) org-occur-parameters)
13564 (let ((cnt 0))
13565 (save-excursion
13566 (goto-char (point-min))
13567 (if (or (not keep-previous) ; do not want to keep
13568 (not org-occur-highlights)) ; no previous matches
13569 ;; hide everything
13570 (org-overview))
13571 (while (re-search-forward regexp nil t)
13572 (when (or (not callback)
13573 (save-match-data (funcall callback)))
13574 (setq cnt (1+ cnt))
13575 (when org-highlight-sparse-tree-matches
13576 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13577 (org-show-context 'occur-tree))))
13578 (when org-remove-highlights-with-change
13579 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13580 nil 'local))
13581 (unless org-sparse-tree-open-archived-trees
13582 (org-hide-archived-subtrees (point-min) (point-max)))
13583 (run-hooks 'org-occur-hook)
13584 (if (org-called-interactively-p 'interactive)
13585 (message "%d match(es) for regexp %s" cnt regexp))
13586 cnt))
13587
13588 (defun org-occur-next-match (&optional n reset)
13589 "Function for `next-error-function' to find sparse tree matches.
13590 N is the number of matches to move, when negative move backwards.
13591 RESET is entirely ignored - this function always goes back to the
13592 starting point when no match is found."
13593 (let* ((limit (if (< n 0) (point-min) (point-max)))
13594 (search-func (if (< n 0)
13595 'previous-single-char-property-change
13596 'next-single-char-property-change))
13597 (n (abs n))
13598 (pos (point))
13599 p1)
13600 (catch 'exit
13601 (while (setq p1 (funcall search-func (point) 'org-type))
13602 (when (equal p1 limit)
13603 (goto-char pos)
13604 (error "No more matches"))
13605 (when (equal (get-char-property p1 'org-type) 'org-occur)
13606 (setq n (1- n))
13607 (when (= n 0)
13608 (goto-char p1)
13609 (throw 'exit (point))))
13610 (goto-char p1))
13611 (goto-char p1)
13612 (error "No more matches"))))
13613
13614 (defun org-show-context (&optional key)
13615 "Make sure point and context are visible.
13616 How much context is shown depends upon the variables
13617 `org-show-hierarchy-above', `org-show-following-heading',
13618 `org-show-entry-below' and `org-show-siblings'."
13619 (let ((heading-p (org-at-heading-p t))
13620 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13621 (following-p (org-get-alist-option org-show-following-heading key))
13622 (entry-p (org-get-alist-option org-show-entry-below key))
13623 (siblings-p (org-get-alist-option org-show-siblings key)))
13624 ;; Show heading or entry text
13625 (if (and heading-p (not entry-p))
13626 (org-flag-heading nil) ; only show the heading
13627 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13628 (org-show-hidden-entry))) ; show entire entry
13629 (when following-p
13630 ;; Show next sibling, or heading below text
13631 (save-excursion
13632 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13633 (org-flag-heading nil))))
13634 (when siblings-p (org-show-siblings))
13635 (when hierarchy-p
13636 ;; show all higher headings, possibly with siblings
13637 (save-excursion
13638 (while (and (condition-case nil
13639 (progn (org-up-heading-all 1) t)
13640 (error nil))
13641 (not (bobp)))
13642 (org-flag-heading nil)
13643 (when siblings-p (org-show-siblings)))))
13644 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13645
13646 (defvar org-reveal-start-hook nil
13647 "Hook run before revealing a location.")
13648
13649 (defun org-reveal (&optional siblings)
13650 "Show current entry, hierarchy above it, and the following headline.
13651 This can be used to show a consistent set of context around locations
13652 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13653 not t for the search context.
13654
13655 With optional argument SIBLINGS, on each level of the hierarchy all
13656 siblings are shown. This repairs the tree structure to what it would
13657 look like when opened with hierarchical calls to `org-cycle'.
13658 With double optional argument \\[universal-argument] \\[universal-argument], \
13659 go to the parent and show the
13660 entire tree."
13661 (interactive "P")
13662 (run-hooks 'org-reveal-start-hook)
13663 (let ((org-show-hierarchy-above t)
13664 (org-show-following-heading t)
13665 (org-show-siblings (if siblings t org-show-siblings)))
13666 (org-show-context nil))
13667 (when (equal siblings '(16))
13668 (save-excursion
13669 (when (org-up-heading-safe)
13670 (org-show-subtree)
13671 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13672
13673 (defun org-highlight-new-match (beg end)
13674 "Highlight from BEG to END and mark the highlight is an occur headline."
13675 (let ((ov (make-overlay beg end)))
13676 (overlay-put ov 'face 'secondary-selection)
13677 (overlay-put ov 'org-type 'org-occur)
13678 (push ov org-occur-highlights)))
13679
13680 (defun org-remove-occur-highlights (&optional beg end noremove)
13681 "Remove the occur highlights from the buffer.
13682 BEG and END are ignored. If NOREMOVE is nil, remove this function
13683 from the `before-change-functions' in the current buffer."
13684 (interactive)
13685 (unless org-inhibit-highlight-removal
13686 (mapc 'delete-overlay org-occur-highlights)
13687 (setq org-occur-highlights nil)
13688 (setq org-occur-parameters nil)
13689 (unless noremove
13690 (remove-hook 'before-change-functions
13691 'org-remove-occur-highlights 'local))))
13692
13693 ;;;; Priorities
13694
13695 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13696 "Regular expression matching the priority indicator.")
13697
13698 (defvar org-remove-priority-next-time nil)
13699
13700 (defun org-priority-up ()
13701 "Increase the priority of the current item."
13702 (interactive)
13703 (org-priority 'up))
13704
13705 (defun org-priority-down ()
13706 "Decrease the priority of the current item."
13707 (interactive)
13708 (org-priority 'down))
13709
13710 (defun org-priority (&optional action show)
13711 "Change the priority of an item.
13712 ACTION can be `set', `up', `down', or a character."
13713 (interactive "P")
13714 (if (equal action '(4))
13715 (org-show-priority)
13716 (unless org-enable-priority-commands
13717 (user-error "Priority commands are disabled"))
13718 (setq action (or action 'set))
13719 (let (current new news have remove)
13720 (save-excursion
13721 (org-back-to-heading t)
13722 (if (looking-at org-priority-regexp)
13723 (setq current (string-to-char (match-string 2))
13724 have t))
13725 (cond
13726 ((eq action 'remove)
13727 (setq remove t new ?\ ))
13728 ((or (eq action 'set)
13729 (if (featurep 'xemacs) (characterp action) (integerp action)))
13730 (if (not (eq action 'set))
13731 (setq new action)
13732 (message "Priority %c-%c, SPC to remove: "
13733 org-highest-priority org-lowest-priority)
13734 (save-match-data
13735 (setq new (read-char-exclusive))))
13736 (if (and (= (upcase org-highest-priority) org-highest-priority)
13737 (= (upcase org-lowest-priority) org-lowest-priority))
13738 (setq new (upcase new)))
13739 (cond ((equal new ?\ ) (setq remove t))
13740 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13741 (user-error "Priority must be between `%c' and `%c'"
13742 org-highest-priority org-lowest-priority))))
13743 ((eq action 'up)
13744 (setq new (if have
13745 (1- current) ; normal cycling
13746 ;; last priority was empty
13747 (if (eq last-command this-command)
13748 org-lowest-priority ; wrap around empty to lowest
13749 ;; default
13750 (if org-priority-start-cycle-with-default
13751 org-default-priority
13752 (1- org-default-priority))))))
13753 ((eq action 'down)
13754 (setq new (if have
13755 (1+ current) ; normal cycling
13756 ;; last priority was empty
13757 (if (eq last-command this-command)
13758 org-highest-priority ; wrap around empty to highest
13759 ;; default
13760 (if org-priority-start-cycle-with-default
13761 org-default-priority
13762 (1+ org-default-priority))))))
13763 (t (user-error "Invalid action")))
13764 (if (or (< (upcase new) org-highest-priority)
13765 (> (upcase new) org-lowest-priority))
13766 (if (and (memq action '(up down))
13767 (not have) (not (eq last-command this-command)))
13768 ;; `new' is from default priority
13769 (error
13770 "The default can not be set, see `org-default-priority' why")
13771 ;; normal cycling: `new' is beyond highest/lowest priority
13772 ;; and is wrapped around to the empty priority
13773 (setq remove t)))
13774 (setq news (format "%c" new))
13775 (if have
13776 (if remove
13777 (replace-match "" t t nil 1)
13778 (replace-match news t t nil 2))
13779 (if remove
13780 (user-error "No priority cookie found in line")
13781 (let ((case-fold-search nil))
13782 (looking-at org-todo-line-regexp))
13783 (if (match-end 2)
13784 (progn
13785 (goto-char (match-end 2))
13786 (insert " [#" news "]"))
13787 (goto-char (match-beginning 3))
13788 (insert "[#" news "] "))))
13789 (org-preserve-lc (org-set-tags nil 'align)))
13790 (if remove
13791 (message "Priority removed")
13792 (message "Priority of current item set to %s" news)))))
13793
13794 (defun org-show-priority ()
13795 "Show the priority of the current item.
13796 This priority is composed of the main priority given with the [#A] cookies,
13797 and by additional input from the age of a schedules or deadline entry."
13798 (interactive)
13799 (let ((pri (if (eq major-mode 'org-agenda-mode)
13800 (org-get-at-bol 'priority)
13801 (save-excursion
13802 (save-match-data
13803 (beginning-of-line)
13804 (and (looking-at org-heading-regexp)
13805 (org-get-priority (match-string 0))))))))
13806 (message "Priority is %d" (if pri pri -1000))))
13807
13808 (defun org-get-priority (s)
13809 "Find priority cookie and return priority."
13810 (save-match-data
13811 (if (functionp org-get-priority-function)
13812 (funcall org-get-priority-function)
13813 (if (not (string-match org-priority-regexp s))
13814 (* 1000 (- org-lowest-priority org-default-priority))
13815 (* 1000 (- org-lowest-priority
13816 (string-to-char (match-string 2 s))))))))
13817
13818 ;;;; Tags
13819
13820 (defvar org-agenda-archives-mode)
13821 (defvar org-map-continue-from nil
13822 "Position from where mapping should continue.
13823 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13824
13825 (defvar org-scanner-tags nil
13826 "The current tag list while the tags scanner is running.")
13827 (defvar org-trust-scanner-tags nil
13828 "Should `org-get-tags-at' use the tags for the scanner.
13829 This is for internal dynamical scoping only.
13830 When this is non-nil, the function `org-get-tags-at' will return the value
13831 of `org-scanner-tags' instead of building the list by itself. This
13832 can lead to large speed-ups when the tags scanner is used in a file with
13833 many entries, and when the list of tags is retrieved, for example to
13834 obtain a list of properties. Building the tags list for each entry in such
13835 a file becomes an N^2 operation - but with this variable set, it scales
13836 as N.")
13837
13838 (defun org-scan-tags (action matcher todo-only &optional start-level)
13839 "Sca headline tags with inheritance and produce output ACTION.
13840
13841 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13842 or `agenda' to produce an entry list for an agenda view. It can also be
13843 a Lisp form or a function that should be called at each matched headline, in
13844 this case the return value is a list of all return values from these calls.
13845
13846 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13847 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13848 only lines with a not-done TODO keyword are included in the output.
13849 This should be the same variable that was scoped into
13850 and set by `org-make-tags-matcher' when it constructed MATCHER.
13851
13852 START-LEVEL can be a string with asterisks, reducing the scope to
13853 headlines matching this string."
13854 (require 'org-agenda)
13855 (let* ((re (concat "^"
13856 (if start-level
13857 ;; Get the correct level to match
13858 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13859 org-outline-regexp)
13860 " *\\(\\<\\("
13861 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13862 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13863 (props (list 'face 'default
13864 'done-face 'org-agenda-done
13865 'undone-face 'default
13866 'mouse-face 'highlight
13867 'org-not-done-regexp org-not-done-regexp
13868 'org-todo-regexp org-todo-regexp
13869 'org-complex-heading-regexp org-complex-heading-regexp
13870 'help-echo
13871 (format "mouse-2 or RET jump to org file %s"
13872 (abbreviate-file-name
13873 (or (buffer-file-name (buffer-base-buffer))
13874 (buffer-name (buffer-base-buffer)))))))
13875 (org-map-continue-from nil)
13876 lspos tags tags-list
13877 (tags-alist (list (cons 0 org-file-tags)))
13878 (llast 0) rtn rtn1 level category i txt
13879 todo marker entry priority)
13880 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13881 (setq action (list 'lambda nil action)))
13882 (save-excursion
13883 (goto-char (point-min))
13884 (when (eq action 'sparse-tree)
13885 (org-overview)
13886 (org-remove-occur-highlights))
13887 (while (let (case-fold-search)
13888 (re-search-forward re nil t))
13889 (setq org-map-continue-from nil)
13890 (catch :skip
13891 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13892 tags (if (match-end 4) (org-match-string-no-properties 4)))
13893 (goto-char (setq lspos (match-beginning 0)))
13894 (setq level (org-reduced-level (org-outline-level))
13895 category (org-get-category))
13896 (setq i llast llast level)
13897 ;; remove tag lists from same and sublevels
13898 (while (>= i level)
13899 (when (setq entry (assoc i tags-alist))
13900 (setq tags-alist (delete entry tags-alist)))
13901 (setq i (1- i)))
13902 ;; add the next tags
13903 (when tags
13904 (setq tags (org-split-string tags ":")
13905 tags-alist
13906 (cons (cons level tags) tags-alist)))
13907 ;; compile tags for current headline
13908 (setq tags-list
13909 (if org-use-tag-inheritance
13910 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13911 tags)
13912 org-scanner-tags tags-list)
13913 (when org-use-tag-inheritance
13914 (setcdr (car tags-alist)
13915 (mapcar (lambda (x)
13916 (setq x (copy-sequence x))
13917 (org-add-prop-inherited x))
13918 (cdar tags-alist))))
13919 (when (and tags org-use-tag-inheritance
13920 (or (not (eq t org-use-tag-inheritance))
13921 org-tags-exclude-from-inheritance))
13922 ;; selective inheritance, remove uninherited ones
13923 (setcdr (car tags-alist)
13924 (org-remove-uninherited-tags (cdar tags-alist))))
13925 (when (and
13926
13927 ;; eval matcher only when the todo condition is OK
13928 (and (or (not todo-only) (member todo org-not-done-keywords))
13929 (let ((case-fold-search t) (org-trust-scanner-tags t))
13930 (eval matcher)))
13931
13932 ;; Call the skipper, but return t if it does not skip,
13933 ;; so that the `and' form continues evaluating
13934 (progn
13935 (unless (eq action 'sparse-tree) (org-agenda-skip))
13936 t)
13937
13938 ;; Check if timestamps are deselecting this entry
13939 (or (not todo-only)
13940 (and (member todo org-not-done-keywords)
13941 (or (not org-agenda-tags-todo-honor-ignore-options)
13942 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13943
13944 ;; select this headline
13945 (cond
13946 ((eq action 'sparse-tree)
13947 (and org-highlight-sparse-tree-matches
13948 (org-get-heading) (match-end 0)
13949 (org-highlight-new-match
13950 (match-beginning 1) (match-end 1)))
13951 (org-show-context 'tags-tree))
13952 ((eq action 'agenda)
13953 (setq txt (org-agenda-format-item
13954 ""
13955 (concat
13956 (if (eq org-tags-match-list-sublevels 'indented)
13957 (make-string (1- level) ?.) "")
13958 (org-get-heading))
13959 level category
13960 tags-list)
13961 priority (org-get-priority txt))
13962 (goto-char lspos)
13963 (setq marker (org-agenda-new-marker))
13964 (org-add-props txt props
13965 'org-marker marker 'org-hd-marker marker 'org-category category
13966 'todo-state todo
13967 'priority priority 'type "tagsmatch")
13968 (push txt rtn))
13969 ((functionp action)
13970 (setq org-map-continue-from nil)
13971 (save-excursion
13972 (setq rtn1 (funcall action))
13973 (push rtn1 rtn)))
13974 (t (user-error "Invalid action")))
13975
13976 ;; if we are to skip sublevels, jump to end of subtree
13977 (unless org-tags-match-list-sublevels
13978 (org-end-of-subtree t)
13979 (backward-char 1))))
13980 ;; Get the correct position from where to continue
13981 (if org-map-continue-from
13982 (goto-char org-map-continue-from)
13983 (and (= (point) lspos) (end-of-line 1)))))
13984 (when (and (eq action 'sparse-tree)
13985 (not org-sparse-tree-open-archived-trees))
13986 (org-hide-archived-subtrees (point-min) (point-max)))
13987 (nreverse rtn)))
13988
13989 (defun org-remove-uninherited-tags (tags)
13990 "Remove all tags that are not inherited from the list TAGS."
13991 (cond
13992 ((eq org-use-tag-inheritance t)
13993 (if org-tags-exclude-from-inheritance
13994 (org-delete-all org-tags-exclude-from-inheritance tags)
13995 tags))
13996 ((not org-use-tag-inheritance) nil)
13997 ((stringp org-use-tag-inheritance)
13998 (delq nil (mapcar
13999 (lambda (x)
14000 (if (and (string-match org-use-tag-inheritance x)
14001 (not (member x org-tags-exclude-from-inheritance)))
14002 x nil))
14003 tags)))
14004 ((listp org-use-tag-inheritance)
14005 (delq nil (mapcar
14006 (lambda (x)
14007 (if (member x org-use-tag-inheritance) x nil))
14008 tags)))))
14009
14010 (defun org-match-sparse-tree (&optional todo-only match)
14011 "Create a sparse tree according to tags string MATCH.
14012 MATCH can contain positive and negative selection of tags, like
14013 \"+WORK+URGENT-WITHBOSS\".
14014 If optional argument TODO-ONLY is non-nil, only select lines that are
14015 also TODO lines."
14016 (interactive "P")
14017 (org-agenda-prepare-buffers (list (current-buffer)))
14018 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14019
14020 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14021
14022 (defvar org-cached-props nil)
14023 (defun org-cached-entry-get (pom property)
14024 (if (or (eq t org-use-property-inheritance)
14025 (and (stringp org-use-property-inheritance)
14026 (string-match org-use-property-inheritance property))
14027 (and (listp org-use-property-inheritance)
14028 (member property org-use-property-inheritance)))
14029 ;; Caching is not possible, check it directly
14030 (org-entry-get pom property 'inherit)
14031 ;; Get all properties, so that we can do complicated checks easily
14032 (cdr (assoc property (or org-cached-props
14033 (setq org-cached-props
14034 (org-entry-properties pom)))))))
14035
14036 (defun org-global-tags-completion-table (&optional files)
14037 "Return the list of all tags in all agenda buffer/files.
14038 Optional FILES argument is a list of files which can be used
14039 instead of the agenda files."
14040 (save-excursion
14041 (org-uniquify
14042 (delq nil
14043 (apply 'append
14044 (mapcar
14045 (lambda (file)
14046 (set-buffer (find-file-noselect file))
14047 (append (org-get-buffer-tags)
14048 (mapcar (lambda (x) (if (stringp (car-safe x))
14049 (list (car-safe x)) nil))
14050 org-tag-alist)))
14051 (if (and files (car files))
14052 files
14053 (org-agenda-files))))))))
14054
14055 (defun org-make-tags-matcher (match)
14056 "Create the TAGS/TODO matcher form for the selection string MATCH.
14057
14058 The variable `todo-only' is scoped dynamically into this function.
14059 It will be set to t if the matcher restricts matching to TODO entries,
14060 otherwise will not be touched.
14061
14062 Returns a cons of the selection string MATCH and the constructed
14063 lisp form implementing the matcher. The matcher is to be evaluated
14064 at an Org entry, with point on the headline, and returns t if the
14065 entry matches the selection string MATCH. The returned lisp form
14066 references two variables with information about the entry, which
14067 must be bound around the form's evaluation: todo, the TODO keyword
14068 at the entry (or nil of none); and tags-list, the list of all tags
14069 at the entry including inherited ones. Additionally, the category
14070 of the entry (if any) must be specified as the text property
14071 'org-category on the headline.
14072
14073 See also `org-scan-tags'.
14074 "
14075 (declare (special todo-only))
14076 (unless (boundp 'todo-only)
14077 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14078 (unless match
14079 ;; Get a new match request, with completion against the global
14080 ;; tags table and the local tags in current buffer
14081 (let ((org-last-tags-completion-table
14082 (org-uniquify
14083 (delq nil (append (org-get-buffer-tags)
14084 (org-global-tags-completion-table))))))
14085 (setq match (org-completing-read-no-i
14086 "Match: " 'org-tags-completion-function nil nil nil
14087 'org-tags-history))))
14088
14089 ;; Parse the string and create a lisp form
14090 (let ((match0 match)
14091 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14092 minus tag mm
14093 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14094 orterms term orlist re-p str-p level-p level-op time-p
14095 prop-p pn pv po gv rest (start 0) (ss 0))
14096 ;; Expand group tags
14097 (setq match (org-tags-expand match))
14098
14099 ;; Check if there is a TODO part of this match, which would be the
14100 ;; part after a "/". TO make sure that this slash is not part of
14101 ;; a property value to be matched against, we also check that there
14102 ;; is no " after that slash.
14103 ;; First, find the last slash
14104 (while (string-match "/+" match ss)
14105 (setq start (match-beginning 0) ss (match-end 0)))
14106 (if (and (string-match "/+" match start)
14107 (not (save-match-data (string-match "\"" match start))))
14108 ;; match contains also a todo-matching request
14109 (progn
14110 (setq tagsmatch (substring match 0 (match-beginning 0))
14111 todomatch (substring match (match-end 0)))
14112 (if (string-match "^!" todomatch)
14113 (setq todo-only t todomatch (substring todomatch 1)))
14114 (if (string-match "^\\s-*$" todomatch)
14115 (setq todomatch nil)))
14116 ;; only matching tags
14117 (setq tagsmatch match todomatch nil))
14118
14119 ;; Make the tags matcher
14120 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14121 (setq tagsmatcher t)
14122 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14123 (while (setq term (pop orterms))
14124 (while (and (equal (substring term -1) "\\") orterms)
14125 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14126 (while (string-match re term)
14127 (setq rest (substring term (match-end 0))
14128 minus (and (match-end 1)
14129 (equal (match-string 1 term) "-"))
14130 tag (save-match-data (replace-regexp-in-string
14131 "\\\\-" "-"
14132 (match-string 2 term)))
14133 re-p (equal (string-to-char tag) ?{)
14134 level-p (match-end 4)
14135 prop-p (match-end 5)
14136 mm (cond
14137 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14138 (level-p
14139 (setq level-op (org-op-to-function (match-string 3 term)))
14140 `(,level-op level ,(string-to-number
14141 (match-string 4 term))))
14142 (prop-p
14143 (setq pn (match-string 5 term)
14144 po (match-string 6 term)
14145 pv (match-string 7 term)
14146 re-p (equal (string-to-char pv) ?{)
14147 str-p (equal (string-to-char pv) ?\")
14148 time-p (save-match-data
14149 (string-match "^\"[[<].*[]>]\"$" pv))
14150 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14151 (if time-p (setq pv (org-matcher-time pv)))
14152 (setq po (org-op-to-function po (if time-p 'time str-p)))
14153 (cond
14154 ((equal pn "CATEGORY")
14155 (setq gv '(get-text-property (point) 'org-category)))
14156 ((equal pn "TODO")
14157 (setq gv 'todo))
14158 (t
14159 (setq gv `(org-cached-entry-get nil ,pn))))
14160 (if re-p
14161 (if (eq po 'org<>)
14162 `(not (string-match ,pv (or ,gv "")))
14163 `(string-match ,pv (or ,gv "")))
14164 (if str-p
14165 `(,po (or ,gv "") ,pv)
14166 `(,po (string-to-number (or ,gv ""))
14167 ,(string-to-number pv) ))))
14168 (t `(member ,tag tags-list)))
14169 mm (if minus (list 'not mm) mm)
14170 term rest)
14171 (push mm tagsmatcher))
14172 (push (if (> (length tagsmatcher) 1)
14173 (cons 'and tagsmatcher)
14174 (car tagsmatcher))
14175 orlist)
14176 (setq tagsmatcher nil))
14177 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14178 (setq tagsmatcher
14179 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14180 ;; Make the todo matcher
14181 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14182 (setq todomatcher t)
14183 (setq orterms (org-split-string todomatch "|") orlist nil)
14184 (while (setq term (pop orterms))
14185 (while (string-match re term)
14186 (setq minus (and (match-end 1)
14187 (equal (match-string 1 term) "-"))
14188 kwd (match-string 2 term)
14189 re-p (equal (string-to-char kwd) ?{)
14190 term (substring term (match-end 0))
14191 mm (if re-p
14192 `(string-match ,(substring kwd 1 -1) todo)
14193 (list 'equal 'todo kwd))
14194 mm (if minus (list 'not mm) mm))
14195 (push mm todomatcher))
14196 (push (if (> (length todomatcher) 1)
14197 (cons 'and todomatcher)
14198 (car todomatcher))
14199 orlist)
14200 (setq todomatcher nil))
14201 (setq todomatcher (if (> (length orlist) 1)
14202 (cons 'or orlist) (car orlist))))
14203
14204 ;; Return the string and lisp forms of the matcher
14205 (setq matcher (if todomatcher
14206 (list 'and tagsmatcher todomatcher)
14207 tagsmatcher))
14208 (when todo-only
14209 (setq matcher (list 'and '(member todo org-not-done-keywords)
14210 matcher)))
14211 (cons match0 matcher)))
14212
14213 (defun org-tags-expand (match &optional single-as-list downcased)
14214 "Expand group tags in MATCH.
14215
14216 This replaces every group tag in MATCH with a regexp tag search.
14217 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14218 will be replaced like this:
14219
14220 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14221 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14222 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14223
14224 Replacing by a regexp preserves the structure of the match.
14225 E.g., this expansion
14226
14227 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14228
14229 will match anything tagged with \"Lab\" and \"Home\", or tagged
14230 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14231
14232 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14233 assumed to be a single group tag, and the function will return
14234 the list of tags in this group.
14235
14236 When DOWNCASE is non-nil, expand downcased TAGS."
14237 (if org-group-tags
14238 (let* ((case-fold-search t)
14239 (stable org-mode-syntax-table)
14240 (tal (or org-tag-groups-alist-for-agenda
14241 org-tag-groups-alist))
14242 (tal (if downcased
14243 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14244 (tml (mapcar 'car tal))
14245 (rtnmatch match) rpl)
14246 ;; @ and _ are allowed as word-components in tags
14247 (modify-syntax-entry ?@ "w" stable)
14248 (modify-syntax-entry ?_ "w" stable)
14249 (while (and tml
14250 (with-syntax-table stable
14251 (string-match
14252 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14253 (regexp-opt tml) "\\>\\)") rtnmatch)))
14254 (let* ((dir (match-string 1 rtnmatch))
14255 (tag (match-string 2 rtnmatch))
14256 (tag (if downcased (downcase tag) tag)))
14257 (setq tml (delete tag tml))
14258 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14259 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14260 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14261 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14262 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14263 (if single-as-list
14264 (or (reverse rpl) (list rtnmatch))
14265 rtnmatch))
14266 (if single-as-list (list (if downcased (downcase match) match))
14267 match)))
14268
14269 (defun org-op-to-function (op &optional stringp)
14270 "Turn an operator into the appropriate function."
14271 (setq op
14272 (cond
14273 ((equal op "<" ) '(< string< org-time<))
14274 ((equal op ">" ) '(> org-string> org-time>))
14275 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14276 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14277 ((member op '("=" "==")) '(= string= org-time=))
14278 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14279 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14280
14281 (defun org<> (a b) (not (= a b)))
14282 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14283 (defun org-string>= (a b) (not (string< a b)))
14284 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14285 (defun org-string<> (a b) (not (string= a b)))
14286 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14287 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14288 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14289 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14290 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14291 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14292 (defun org-2ft (s)
14293 "Convert S to a floating point time.
14294 If S is already a number, just return it. If it is a string, parse
14295 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14296 (cond
14297 ((numberp s) s)
14298 ((stringp s)
14299 (condition-case nil
14300 (float-time (apply 'encode-time (org-parse-time-string s)))
14301 (error 0.)))
14302 (t 0.)))
14303
14304 (defun org-time-today ()
14305 "Time in seconds today at 0:00.
14306 Returns the float number of seconds since the beginning of the
14307 epoch to the beginning of today (00:00)."
14308 (float-time (apply 'encode-time
14309 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14310
14311 (defun org-matcher-time (s)
14312 "Interpret a time comparison value."
14313 (save-match-data
14314 (cond
14315 ((string= s "<now>") (float-time))
14316 ((string= s "<today>") (org-time-today))
14317 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14318 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14319 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14320 (+ (org-time-today)
14321 (* (string-to-number (match-string 1 s))
14322 (cdr (assoc (match-string 2 s)
14323 '(("d" . 86400.0) ("w" . 604800.0)
14324 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14325 (t (org-2ft s)))))
14326
14327 (defun org-match-any-p (re list)
14328 "Does re match any element of list?"
14329 (setq list (mapcar (lambda (x) (string-match re x)) list))
14330 (delq nil list))
14331
14332 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14333 (defvar org-tags-overlay (make-overlay 1 1))
14334 (org-detach-overlay org-tags-overlay)
14335
14336 (defun org-get-local-tags-at (&optional pos)
14337 "Get a list of tags defined in the current headline."
14338 (org-get-tags-at pos 'local))
14339
14340 (defun org-get-local-tags ()
14341 "Get a list of tags defined in the current headline."
14342 (org-get-tags-at nil 'local))
14343
14344 (defun org-get-tags-at (&optional pos local)
14345 "Get a list of all headline tags applicable at POS.
14346 POS defaults to point. If tags are inherited, the list contains
14347 the targets in the same sequence as the headlines appear, i.e.
14348 the tags of the current headline come last.
14349 When LOCAL is non-nil, only return tags from the current headline,
14350 ignore inherited ones."
14351 (interactive)
14352 (if (and org-trust-scanner-tags
14353 (or (not pos) (equal pos (point)))
14354 (not local))
14355 org-scanner-tags
14356 (let (tags ltags lastpos parent)
14357 (save-excursion
14358 (save-restriction
14359 (widen)
14360 (goto-char (or pos (point)))
14361 (save-match-data
14362 (catch 'done
14363 (condition-case nil
14364 (progn
14365 (org-back-to-heading t)
14366 (while (not (equal lastpos (point)))
14367 (setq lastpos (point))
14368 (when (looking-at
14369 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14370 (setq ltags (org-split-string
14371 (org-match-string-no-properties 1) ":"))
14372 (when parent
14373 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14374 (setq tags (append
14375 (if parent
14376 (org-remove-uninherited-tags ltags)
14377 ltags)
14378 tags)))
14379 (or org-use-tag-inheritance (throw 'done t))
14380 (if local (throw 'done t))
14381 (or (org-up-heading-safe) (error nil))
14382 (setq parent t)))
14383 (error nil)))))
14384 (if local
14385 tags
14386 (reverse (delete-dups
14387 (reverse (append
14388 (org-remove-uninherited-tags
14389 org-file-tags) tags)))))))))
14390
14391 (defun org-add-prop-inherited (s)
14392 (add-text-properties 0 (length s) '(inherited t) s)
14393 s)
14394
14395 (defun org-toggle-tag (tag &optional onoff)
14396 "Toggle the tag TAG for the current line.
14397 If ONOFF is `on' or `off', don't toggle but set to this state."
14398 (let (res current)
14399 (save-excursion
14400 (org-back-to-heading t)
14401 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14402 (point-at-eol) t)
14403 (progn
14404 (setq current (match-string 1))
14405 (replace-match ""))
14406 (setq current ""))
14407 (setq current (nreverse (org-split-string current ":")))
14408 (cond
14409 ((eq onoff 'on)
14410 (setq res t)
14411 (or (member tag current) (push tag current)))
14412 ((eq onoff 'off)
14413 (or (not (member tag current)) (setq current (delete tag current))))
14414 (t (if (member tag current)
14415 (setq current (delete tag current))
14416 (setq res t)
14417 (push tag current))))
14418 (end-of-line 1)
14419 (if current
14420 (progn
14421 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14422 (org-set-tags nil t))
14423 (delete-horizontal-space))
14424 (run-hooks 'org-after-tags-change-hook))
14425 res))
14426
14427 (defun org-align-tags-here (to-col)
14428 ;; Assumes that this is a headline
14429 "Align tags on the current headline to TO-COL."
14430 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14431 (beginning-of-line 1)
14432 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14433 (< pos (match-beginning 2)))
14434 (progn
14435 (setq tags-l (- (match-end 2) (match-beginning 2)))
14436 (goto-char (match-beginning 1))
14437 (insert " ")
14438 (delete-region (point) (1+ (match-beginning 2)))
14439 (setq ncol (max (current-column)
14440 (1+ col)
14441 (if (> to-col 0)
14442 to-col
14443 (- (abs to-col) tags-l))))
14444 (setq p (point))
14445 (insert (make-string (- ncol (current-column)) ?\ ))
14446 (setq ncol (current-column))
14447 (when indent-tabs-mode (tabify p (point-at-eol)))
14448 (org-move-to-column (min ncol col)))
14449 (goto-char pos))))
14450
14451 (defun org-set-tags-command (&optional arg just-align)
14452 "Call the set-tags command for the current entry."
14453 (interactive "P")
14454 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14455 (org-set-tags arg just-align)
14456 (save-excursion
14457 (unless (and (org-region-active-p)
14458 org-loop-over-headlines-in-active-region)
14459 (org-back-to-heading t))
14460 (org-set-tags arg just-align))))
14461
14462 (defun org-set-tags-to (data)
14463 "Set the tags of the current entry to DATA, replacing the current tags.
14464 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14465 If DATA is nil or the empty string, any tags will be removed."
14466 (interactive "sTags: ")
14467 (setq data
14468 (cond
14469 ((eq data nil) "")
14470 ((equal data "") "")
14471 ((stringp data)
14472 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14473 ":"))
14474 ((listp data)
14475 (concat ":" (mapconcat 'identity data ":") ":"))))
14476 (when data
14477 (save-excursion
14478 (org-back-to-heading t)
14479 (when (looking-at org-complex-heading-regexp)
14480 (if (match-end 5)
14481 (progn
14482 (goto-char (match-beginning 5))
14483 (insert data)
14484 (delete-region (point) (point-at-eol))
14485 (org-set-tags nil 'align))
14486 (goto-char (point-at-eol))
14487 (insert " " data)
14488 (org-set-tags nil 'align)))
14489 (beginning-of-line 1)
14490 (if (looking-at ".*?\\([ \t]+\\)$")
14491 (delete-region (match-beginning 1) (match-end 1))))))
14492
14493 (defun org-align-all-tags ()
14494 "Align the tags i all headings."
14495 (interactive)
14496 (save-excursion
14497 (or (ignore-errors (org-back-to-heading t))
14498 (outline-next-heading))
14499 (if (org-at-heading-p)
14500 (org-set-tags t)
14501 (message "No headings"))))
14502
14503 (defvar org-indent-indentation-per-level)
14504 (defun org-set-tags (&optional arg just-align)
14505 "Set the tags for the current headline.
14506 With prefix ARG, realign all tags in headings in the current buffer.
14507 When JUST-ALIGN is non-nil, only align tags."
14508 (interactive "P")
14509 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14510 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14511 'region-start-level 'region))
14512 org-loop-over-headlines-in-active-region)
14513 (org-map-entries
14514 ;; We don't use ARG and JUST-ALIGN here because these args
14515 ;; are not useful when looping over headlines.
14516 `(org-set-tags)
14517 org-loop-over-headlines-in-active-region
14518 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14519 (let* ((re org-outline-regexp-bol)
14520 (current (unless arg (org-get-tags-string)))
14521 (col (current-column))
14522 (org-setting-tags t)
14523 table current-tags inherited-tags ; computed below when needed
14524 tags p0 c0 c1 rpl di tc level)
14525 (if arg
14526 (save-excursion
14527 (goto-char (point-min))
14528 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14529 (while (re-search-forward re nil t)
14530 (org-set-tags nil t)
14531 (end-of-line 1)))
14532 (message "All tags realigned to column %d" org-tags-column))
14533 (if just-align
14534 (setq tags current)
14535 ;; Get a new set of tags from the user
14536 (save-excursion
14537 (setq table (append org-tag-persistent-alist
14538 (or org-tag-alist (org-get-buffer-tags))
14539 (and
14540 org-complete-tags-always-offer-all-agenda-tags
14541 (org-global-tags-completion-table
14542 (org-agenda-files))))
14543 org-last-tags-completion-table table
14544 current-tags (org-split-string current ":")
14545 inherited-tags (nreverse
14546 (nthcdr (length current-tags)
14547 (nreverse (org-get-tags-at))))
14548 tags
14549 (if (or (eq t org-use-fast-tag-selection)
14550 (and org-use-fast-tag-selection
14551 (delq nil (mapcar 'cdr table))))
14552 (org-fast-tag-selection
14553 current-tags inherited-tags table
14554 (if org-fast-tag-selection-include-todo
14555 org-todo-key-alist))
14556 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14557 (org-trim
14558 (org-icompleting-read "Tags: "
14559 'org-tags-completion-function
14560 nil nil current 'org-tags-history))))))
14561 (while (string-match "[-+&]+" tags)
14562 ;; No boolean logic, just a list
14563 (setq tags (replace-match ":" t t tags))))
14564
14565 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14566
14567 (if org-tags-sort-function
14568 (setq tags (mapconcat 'identity
14569 (sort (org-split-string
14570 tags (org-re "[^[:alnum:]_@#%]+"))
14571 org-tags-sort-function) ":")))
14572
14573 (if (string-match "\\`[\t ]*\\'" tags)
14574 (setq tags "")
14575 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14576 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14577
14578 ;; Insert new tags at the correct column
14579 (beginning-of-line 1)
14580 (setq level (or (and (looking-at org-outline-regexp)
14581 (- (match-end 0) (point) 1))
14582 1))
14583 (cond
14584 ((and (equal current "") (equal tags "")))
14585 ((re-search-forward
14586 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14587 (point-at-eol) t)
14588 (if (equal tags "")
14589 (setq rpl "")
14590 (goto-char (match-beginning 0))
14591 (setq c0 (current-column)
14592 ;; compute offset for the case of org-indent-mode active
14593 di (if (org-bound-and-true-p org-indent-mode)
14594 (* (1- org-indent-indentation-per-level) (1- level))
14595 0)
14596 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14597 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14598 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14599 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14600 (replace-match rpl t t)
14601 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14602 tags)
14603 (t (error "Tags alignment failed")))
14604 (org-move-to-column col)
14605 (unless just-align
14606 (run-hooks 'org-after-tags-change-hook))))))
14607
14608 (defun org-change-tag-in-region (beg end tag off)
14609 "Add or remove TAG for each entry in the region.
14610 This works in the agenda, and also in an org-mode buffer."
14611 (interactive
14612 (list (region-beginning) (region-end)
14613 (let ((org-last-tags-completion-table
14614 (if (derived-mode-p 'org-mode)
14615 (org-uniquify
14616 (delq nil (append (org-get-buffer-tags)
14617 (org-global-tags-completion-table))))
14618 (org-global-tags-completion-table))))
14619 (org-icompleting-read
14620 "Tag: " 'org-tags-completion-function nil nil nil
14621 'org-tags-history))
14622 (progn
14623 (message "[s]et or [r]emove? ")
14624 (equal (read-char-exclusive) ?r))))
14625 (if (fboundp 'deactivate-mark) (deactivate-mark))
14626 (let ((agendap (equal major-mode 'org-agenda-mode))
14627 l1 l2 m buf pos newhead (cnt 0))
14628 (goto-char end)
14629 (setq l2 (1- (org-current-line)))
14630 (goto-char beg)
14631 (setq l1 (org-current-line))
14632 (loop for l from l1 to l2 do
14633 (org-goto-line l)
14634 (setq m (get-text-property (point) 'org-hd-marker))
14635 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14636 (and agendap m))
14637 (setq buf (if agendap (marker-buffer m) (current-buffer))
14638 pos (if agendap m (point)))
14639 (with-current-buffer buf
14640 (save-excursion
14641 (save-restriction
14642 (goto-char pos)
14643 (setq cnt (1+ cnt))
14644 (org-toggle-tag tag (if off 'off 'on))
14645 (setq newhead (org-get-heading)))))
14646 (and agendap (org-agenda-change-all-lines newhead m))))
14647 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14648
14649 (defun org-tags-completion-function (string predicate &optional flag)
14650 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14651 (confirm (lambda (x) (stringp (car x)))))
14652 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14653 (setq s1 (match-string 1 string)
14654 s2 (match-string 2 string))
14655 (setq s1 "" s2 string))
14656 (cond
14657 ((eq flag nil)
14658 ;; try completion
14659 (setq rtn (try-completion s2 ctable confirm))
14660 (if (stringp rtn)
14661 (setq rtn
14662 (concat s1 s2 (substring rtn (length s2))
14663 (if (and org-add-colon-after-tag-completion
14664 (assoc rtn ctable))
14665 ":" ""))))
14666 rtn)
14667 ((eq flag t)
14668 ;; all-completions
14669 (all-completions s2 ctable confirm))
14670 ((eq flag 'lambda)
14671 ;; exact match?
14672 (assoc s2 ctable)))))
14673
14674 (defun org-fast-tag-insert (kwd tags face &optional end)
14675 "Insert KDW, and the TAGS, the latter with face FACE.
14676 Also insert END."
14677 (insert (format "%-12s" (concat kwd ":"))
14678 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14679 (or end "")))
14680
14681 (defun org-fast-tag-show-exit (flag)
14682 (save-excursion
14683 (org-goto-line 3)
14684 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14685 (replace-match ""))
14686 (when flag
14687 (end-of-line 1)
14688 (org-move-to-column (- (window-width) 19) t)
14689 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14690
14691 (defun org-set-current-tags-overlay (current prefix)
14692 "Add an overlay to CURRENT tag with PREFIX."
14693 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14694 (if (featurep 'xemacs)
14695 (org-overlay-display org-tags-overlay (concat prefix s)
14696 'secondary-selection)
14697 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14698 (org-overlay-display org-tags-overlay (concat prefix s)))))
14699
14700 (defvar org-last-tag-selection-key nil)
14701 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14702 "Fast tag selection with single keys.
14703 CURRENT is the current list of tags in the headline, INHERITED is the
14704 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14705 possibly with grouping information. TODO-TABLE is a similar table with
14706 TODO keywords, should these have keys assigned to them.
14707 If the keys are nil, a-z are automatically assigned.
14708 Returns the new tags string, or nil to not change the current settings."
14709 (let* ((fulltable (append table todo-table))
14710 (maxlen (apply 'max (mapcar
14711 (lambda (x)
14712 (if (stringp (car x)) (string-width (car x)) 0))
14713 fulltable)))
14714 (buf (current-buffer))
14715 (expert (eq org-fast-tag-selection-single-key 'expert))
14716 (buffer-tags nil)
14717 (fwidth (+ maxlen 3 1 3))
14718 (ncol (/ (- (window-width) 4) fwidth))
14719 (i-face 'org-done)
14720 (c-face 'org-todo)
14721 tg cnt e c char c1 c2 ntable tbl rtn
14722 ov-start ov-end ov-prefix
14723 (exit-after-next org-fast-tag-selection-single-key)
14724 (done-keywords org-done-keywords)
14725 groups ingroup)
14726 (save-excursion
14727 (beginning-of-line 1)
14728 (if (looking-at
14729 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14730 (setq ov-start (match-beginning 1)
14731 ov-end (match-end 1)
14732 ov-prefix "")
14733 (setq ov-start (1- (point-at-eol))
14734 ov-end (1+ ov-start))
14735 (skip-chars-forward "^\n\r")
14736 (setq ov-prefix
14737 (concat
14738 (buffer-substring (1- (point)) (point))
14739 (if (> (current-column) org-tags-column)
14740 " "
14741 (make-string (- org-tags-column (current-column)) ?\ ))))))
14742 (move-overlay org-tags-overlay ov-start ov-end)
14743 (save-window-excursion
14744 (if expert
14745 (set-buffer (get-buffer-create " *Org tags*"))
14746 (delete-other-windows)
14747 (split-window-vertically)
14748 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14749 (erase-buffer)
14750 (org-set-local 'org-done-keywords done-keywords)
14751 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14752 (org-fast-tag-insert "Current" current c-face "\n\n")
14753 (org-fast-tag-show-exit exit-after-next)
14754 (org-set-current-tags-overlay current ov-prefix)
14755 (setq tbl fulltable char ?a cnt 0)
14756 (while (setq e (pop tbl))
14757 (cond
14758 ((equal (car e) :startgroup)
14759 (push '() groups) (setq ingroup t)
14760 (when (not (= cnt 0))
14761 (setq cnt 0)
14762 (insert "\n"))
14763 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14764 ((equal (car e) :endgroup)
14765 (setq ingroup nil cnt 0)
14766 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14767 ((equal e '(:newline))
14768 (when (not (= cnt 0))
14769 (setq cnt 0)
14770 (insert "\n")
14771 (setq e (car tbl))
14772 (while (equal (car tbl) '(:newline))
14773 (insert "\n")
14774 (setq tbl (cdr tbl)))))
14775 ((equal e '(:grouptags)) nil)
14776 (t
14777 (setq tg (copy-sequence (car e)) c2 nil)
14778 (if (cdr e)
14779 (setq c (cdr e))
14780 ;; automatically assign a character.
14781 (setq c1 (string-to-char
14782 (downcase (substring
14783 tg (if (= (string-to-char tg) ?@) 1 0)))))
14784 (if (or (rassoc c1 ntable) (rassoc c1 table))
14785 (while (or (rassoc char ntable) (rassoc char table))
14786 (setq char (1+ char)))
14787 (setq c2 c1))
14788 (setq c (or c2 char)))
14789 (if ingroup (push tg (car groups)))
14790 (setq tg (org-add-props tg nil 'face
14791 (cond
14792 ((not (assoc tg table))
14793 (org-get-todo-face tg))
14794 ((member tg current) c-face)
14795 ((member tg inherited) i-face))))
14796 (if (equal (caar tbl) :grouptags)
14797 (org-add-props tg nil 'face 'org-tag-group))
14798 (if (and (= cnt 0) (not ingroup)) (insert " "))
14799 (insert "[" c "] " tg (make-string
14800 (- fwidth 4 (length tg)) ?\ ))
14801 (push (cons tg c) ntable)
14802 (when (= (setq cnt (1+ cnt)) ncol)
14803 (insert "\n")
14804 (if ingroup (insert " "))
14805 (setq cnt 0)))))
14806 (setq ntable (nreverse ntable))
14807 (insert "\n")
14808 (goto-char (point-min))
14809 (if (not expert) (org-fit-window-to-buffer))
14810 (setq rtn
14811 (catch 'exit
14812 (while t
14813 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14814 (if (not groups) "no " "")
14815 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14816 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14817 (setq org-last-tag-selection-key c)
14818 (cond
14819 ((= c ?\r) (throw 'exit t))
14820 ((= c ?!)
14821 (setq groups (not groups))
14822 (goto-char (point-min))
14823 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14824 ((= c ?\C-c)
14825 (if (not expert)
14826 (org-fast-tag-show-exit
14827 (setq exit-after-next (not exit-after-next)))
14828 (setq expert nil)
14829 (delete-other-windows)
14830 (set-window-buffer (split-window-vertically) " *Org tags*")
14831 (org-switch-to-buffer-other-window " *Org tags*")
14832 (org-fit-window-to-buffer)))
14833 ((or (= c ?\C-g)
14834 (and (= c ?q) (not (rassoc c ntable))))
14835 (org-detach-overlay org-tags-overlay)
14836 (setq quit-flag t))
14837 ((= c ?\ )
14838 (setq current nil)
14839 (if exit-after-next (setq exit-after-next 'now)))
14840 ((= c ?\t)
14841 (condition-case nil
14842 (setq tg (org-icompleting-read
14843 "Tag: "
14844 (or buffer-tags
14845 (with-current-buffer buf
14846 (org-get-buffer-tags)))))
14847 (quit (setq tg "")))
14848 (when (string-match "\\S-" tg)
14849 (add-to-list 'buffer-tags (list tg))
14850 (if (member tg current)
14851 (setq current (delete tg current))
14852 (push tg current)))
14853 (if exit-after-next (setq exit-after-next 'now)))
14854 ((setq e (rassoc c todo-table) tg (car e))
14855 (with-current-buffer buf
14856 (save-excursion (org-todo tg)))
14857 (if exit-after-next (setq exit-after-next 'now)))
14858 ((setq e (rassoc c ntable) tg (car e))
14859 (if (member tg current)
14860 (setq current (delete tg current))
14861 (loop for g in groups do
14862 (if (member tg g)
14863 (mapc (lambda (x)
14864 (setq current (delete x current)))
14865 g)))
14866 (push tg current))
14867 (if exit-after-next (setq exit-after-next 'now))))
14868
14869 ;; Create a sorted list
14870 (setq current
14871 (sort current
14872 (lambda (a b)
14873 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14874 (if (eq exit-after-next 'now) (throw 'exit t))
14875 (goto-char (point-min))
14876 (beginning-of-line 2)
14877 (delete-region (point) (point-at-eol))
14878 (org-fast-tag-insert "Current" current c-face)
14879 (org-set-current-tags-overlay current ov-prefix)
14880 (while (re-search-forward
14881 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14882 (setq tg (match-string 1))
14883 (add-text-properties
14884 (match-beginning 1) (match-end 1)
14885 (list 'face
14886 (cond
14887 ((member tg current) c-face)
14888 ((member tg inherited) i-face)
14889 (t (get-text-property (match-beginning 1) 'face))))))
14890 (goto-char (point-min)))))
14891 (org-detach-overlay org-tags-overlay)
14892 (if rtn
14893 (mapconcat 'identity current ":")
14894 nil))))
14895
14896 (defun org-get-tags-string ()
14897 "Get the TAGS string in the current headline."
14898 (unless (org-at-heading-p t)
14899 (user-error "Not on a heading"))
14900 (save-excursion
14901 (beginning-of-line 1)
14902 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14903 (org-match-string-no-properties 1)
14904 "")))
14905
14906 (defun org-get-tags ()
14907 "Get the list of tags specified in the current headline."
14908 (org-split-string (org-get-tags-string) ":"))
14909
14910 (defun org-get-buffer-tags ()
14911 "Get a table of all tags used in the buffer, for completion."
14912 (let (tags)
14913 (save-excursion
14914 (goto-char (point-min))
14915 (while (re-search-forward
14916 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14917 (when (equal (char-after (point-at-bol 0)) ?*)
14918 (mapc (lambda (x) (add-to-list 'tags x))
14919 (org-split-string (org-match-string-no-properties 1) ":")))))
14920 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14921 (mapcar 'list tags)))
14922
14923 ;;;; The mapping API
14924
14925 (defun org-map-entries (func &optional match scope &rest skip)
14926 "Call FUNC at each headline selected by MATCH in SCOPE.
14927
14928 FUNC is a function or a lisp form. The function will be called without
14929 arguments, with the cursor positioned at the beginning of the headline.
14930 The return values of all calls to the function will be collected and
14931 returned as a list.
14932
14933 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14934 does not need to preserve point. After evaluation, the cursor will be
14935 moved to the end of the line (presumably of the headline of the
14936 processed entry) and search continues from there. Under some
14937 circumstances, this may not produce the wanted results. For example,
14938 if you have removed (e.g. archived) the current (sub)tree it could
14939 mean that the next entry will be skipped entirely. In such cases, you
14940 can specify the position from where search should continue by making
14941 FUNC set the variable `org-map-continue-from' to the desired buffer
14942 position.
14943
14944 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14945 Only headlines that are matched by this query will be considered during
14946 the iteration. When MATCH is nil or t, all headlines will be
14947 visited by the iteration.
14948
14949 SCOPE determines the scope of this command. It can be any of:
14950
14951 nil The current buffer, respecting the restriction if any
14952 tree The subtree started with the entry at point
14953 region The entries within the active region, if any
14954 region-start-level
14955 The entries within the active region, but only those at
14956 the same level than the first one.
14957 file The current buffer, without restriction
14958 file-with-archives
14959 The current buffer, and any archives associated with it
14960 agenda All agenda files
14961 agenda-with-archives
14962 All agenda files with any archive files associated with them
14963 \(file1 file2 ...)
14964 If this is a list, all files in the list will be scanned
14965
14966 The remaining args are treated as settings for the skipping facilities of
14967 the scanner. The following items can be given here:
14968
14969 archive skip trees with the archive tag
14970 comment skip trees with the COMMENT keyword
14971 function or Emacs Lisp form:
14972 will be used as value for `org-agenda-skip-function', so
14973 whenever the function returns a position, FUNC will not be
14974 called for that entry and search will continue from the
14975 position returned
14976
14977 If your function needs to retrieve the tags including inherited tags
14978 at the *current* entry, you can use the value of the variable
14979 `org-scanner-tags' which will be much faster than getting the value
14980 with `org-get-tags-at'. If your function gets properties with
14981 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14982 to t around the call to `org-entry-properties' to get the same speedup.
14983 Note that if your function moves around to retrieve tags and properties at
14984 a *different* entry, you cannot use these techniques."
14985 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14986 (not (org-region-active-p)))
14987 (let* ((org-agenda-archives-mode nil) ; just to make sure
14988 (org-agenda-skip-archived-trees (memq 'archive skip))
14989 (org-agenda-skip-comment-trees (memq 'comment skip))
14990 (org-agenda-skip-function
14991 (car (org-delete-all '(comment archive) skip)))
14992 (org-tags-match-list-sublevels t)
14993 (start-level (eq scope 'region-start-level))
14994 matcher file res
14995 org-todo-keywords-for-agenda
14996 org-done-keywords-for-agenda
14997 org-todo-keyword-alist-for-agenda
14998 org-drawers-for-agenda
14999 org-tag-alist-for-agenda
15000 todo-only)
15001
15002 (cond
15003 ((eq match t) (setq matcher t))
15004 ((eq match nil) (setq matcher t))
15005 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15006
15007 (save-excursion
15008 (save-restriction
15009 (cond ((eq scope 'tree)
15010 (org-back-to-heading t)
15011 (org-narrow-to-subtree)
15012 (setq scope nil))
15013 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15014 (org-region-active-p))
15015 ;; If needed, set start-level to a string like "2"
15016 (when start-level
15017 (save-excursion
15018 (goto-char (region-beginning))
15019 (unless (org-at-heading-p) (outline-next-heading))
15020 (setq start-level (org-current-level))))
15021 (narrow-to-region (region-beginning)
15022 (save-excursion
15023 (goto-char (region-end))
15024 (unless (and (bolp) (org-at-heading-p))
15025 (outline-next-heading))
15026 (point)))
15027 (setq scope nil)))
15028
15029 (if (not scope)
15030 (progn
15031 (org-agenda-prepare-buffers
15032 (list (buffer-file-name (current-buffer))))
15033 (setq res (org-scan-tags func matcher todo-only start-level)))
15034 ;; Get the right scope
15035 (cond
15036 ((and scope (listp scope) (symbolp (car scope)))
15037 (setq scope (eval scope)))
15038 ((eq scope 'agenda)
15039 (setq scope (org-agenda-files t)))
15040 ((eq scope 'agenda-with-archives)
15041 (setq scope (org-agenda-files t))
15042 (setq scope (org-add-archive-files scope)))
15043 ((eq scope 'file)
15044 (setq scope (list (buffer-file-name))))
15045 ((eq scope 'file-with-archives)
15046 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15047 (org-agenda-prepare-buffers scope)
15048 (while (setq file (pop scope))
15049 (with-current-buffer (org-find-base-buffer-visiting file)
15050 (save-excursion
15051 (save-restriction
15052 (widen)
15053 (goto-char (point-min))
15054 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15055 res)))
15056
15057 ;;;; Properties
15058
15059 ;;; Setting and retrieving properties
15060
15061 (defconst org-special-properties
15062 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15063 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15064 "The special properties valid in Org-mode.
15065
15066 These are properties that are not defined in the property drawer,
15067 but in some other way.")
15068
15069 (defconst org-default-properties
15070 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15071 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15072 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15073 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15074 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15075 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15076 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15077 "Some properties that are used by Org-mode for various purposes.
15078 Being in this list makes sure that they are offered for completion.")
15079
15080 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15081 "Regular expression matching the first line of a property drawer.")
15082
15083 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15084 "Regular expression matching the last line of a property drawer.")
15085
15086 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15087 "Regular expression matching the first line of a property drawer.")
15088
15089 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15090 "Regular expression matching the first line of a property drawer.")
15091
15092 (defconst org-property-drawer-re
15093 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15094 org-property-end-re "\\)\n?")
15095 "Matches an entire property drawer.")
15096
15097 (defconst org-clock-drawer-re
15098 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15099 org-property-end-re "\\)\n?")
15100 "Matches an entire clock drawer.")
15101
15102 (defun org-property-action ()
15103 "Do an action on properties."
15104 (interactive)
15105 (let (c)
15106 (org-at-property-p)
15107 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15108 (setq c (read-char-exclusive))
15109 (cond
15110 ((equal c ?s)
15111 (call-interactively 'org-set-property))
15112 ((equal c ?d)
15113 (call-interactively 'org-delete-property))
15114 ((equal c ?D)
15115 (call-interactively 'org-delete-property-globally))
15116 ((equal c ?c)
15117 (call-interactively 'org-compute-property-at-point))
15118 (t (user-error "No such property action %c" c)))))
15119
15120 (defun org-inc-effort ()
15121 "Increment the value of the effort property in the current entry."
15122 (interactive)
15123 (org-set-effort nil t))
15124
15125 (defvar org-clock-effort) ;; Defined in org-clock.el
15126 (defvar org-clock-current-task) ;; Defined in org-clock.el
15127 (defun org-set-effort (&optional value increment)
15128 "Set the effort property of the current entry.
15129 With numerical prefix arg, use the nth allowed value, 0 stands for the
15130 10th allowed value.
15131
15132 When INCREMENT is non-nil, set the property to the next allowed value."
15133 (interactive "P")
15134 (if (equal value 0) (setq value 10))
15135 (let* ((completion-ignore-case t)
15136 (prop org-effort-property)
15137 (cur (org-entry-get nil prop))
15138 (allowed (org-property-get-allowed-values nil prop 'table))
15139 (existing (mapcar 'list (org-property-values prop)))
15140 (heading (nth 4 (org-heading-components)))
15141 rpl
15142 (val (cond
15143 ((stringp value) value)
15144 ((and allowed (integerp value))
15145 (or (car (nth (1- value) allowed))
15146 (car (org-last allowed))))
15147 ((and allowed increment)
15148 (or (caadr (member (list cur) allowed))
15149 (user-error "Allowed effort values are not set")))
15150 (allowed
15151 (message "Select 1-9,0, [RET%s]: %s"
15152 (if cur (concat "=" cur) "")
15153 (mapconcat 'car allowed " "))
15154 (setq rpl (read-char-exclusive))
15155 (if (equal rpl ?\r)
15156 cur
15157 (setq rpl (- rpl ?0))
15158 (if (equal rpl 0) (setq rpl 10))
15159 (if (and (> rpl 0) (<= rpl (length allowed)))
15160 (car (nth (1- rpl) allowed))
15161 (org-completing-read "Effort: " allowed nil))))
15162 (t
15163 (let (org-completion-use-ido org-completion-use-iswitchb)
15164 (org-completing-read
15165 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15166 (concat "[" cur "]") "")
15167 ": ")
15168 existing nil nil "" nil cur))))))
15169 (unless (equal (org-entry-get nil prop) val)
15170 (org-entry-put nil prop val))
15171 (save-excursion
15172 (org-back-to-heading t)
15173 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15174 (when (string= heading org-clock-current-task)
15175 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15176 (org-clock-update-mode-line))
15177 (message "%s is now %s" prop val)))
15178
15179 (defun org-at-property-p ()
15180 "Is cursor inside a property drawer?"
15181 (save-excursion
15182 (when (equal 'node-property (car (org-element-at-point)))
15183 (beginning-of-line 1)
15184 (looking-at org-property-re))))
15185
15186 (defun org-get-property-block (&optional beg end force)
15187 "Return the (beg . end) range of the body of the property drawer.
15188 BEG and END are the beginning and end of the current subtree, or of
15189 the part before the first headline. If they are not given, they will
15190 be found. If the drawer does not exist and FORCE is non-nil, create
15191 the drawer."
15192 (catch 'exit
15193 (save-excursion
15194 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15195 (progn (org-back-to-heading t) (point))))
15196 (end (or end (and (not (outline-next-heading)) (point-max))
15197 (point))))
15198 (goto-char beg)
15199 (if (re-search-forward org-property-start-re end t)
15200 (setq beg (1+ (match-end 0)))
15201 (if force
15202 (save-excursion
15203 (org-insert-property-drawer)
15204 (setq end (progn (outline-next-heading) (point))))
15205 (throw 'exit nil))
15206 (goto-char beg)
15207 (if (re-search-forward org-property-start-re end t)
15208 (setq beg (1+ (match-end 0)))))
15209 (if (re-search-forward org-property-end-re end t)
15210 (setq end (match-beginning 0))
15211 (or force (throw 'exit nil))
15212 (goto-char beg)
15213 (setq end beg)
15214 (org-indent-line)
15215 (insert ":END:\n"))
15216 (cons beg end)))))
15217
15218 (defun org-entry-properties (&optional pom which specific)
15219 "Get all properties of the entry at point-or-marker POM.
15220 This includes the TODO keyword, the tags, time strings for deadline,
15221 scheduled, and clocking, and any additional properties defined in the
15222 entry. The return value is an alist, keys may occur multiple times
15223 if the property key was used several times.
15224 POM may also be nil, in which case the current entry is used.
15225 If WHICH is nil or `all', get all properties. If WHICH is
15226 `special' or `standard', only get that subclass. If WHICH
15227 is a string only get exactly this property. SPECIFIC can be a string, the
15228 specific property we are interested in. Specifying it can speed
15229 things up because then unnecessary parsing is avoided."
15230 (setq which (or which 'all))
15231 (org-with-wide-buffer
15232 (org-with-point-at pom
15233 (let ((clockstr (substring org-clock-string 0 -1))
15234 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15235 (case-fold-search nil)
15236 beg end range props sum-props key key1 value string clocksum clocksumt)
15237 (when (and (derived-mode-p 'org-mode)
15238 (ignore-errors (org-back-to-heading t)))
15239 (setq beg (point))
15240 (setq sum-props (get-text-property (point) 'org-summaries))
15241 (setq clocksum (get-text-property (point) :org-clock-minutes)
15242 clocksumt (get-text-property (point) :org-clock-minutes-today))
15243 (outline-next-heading)
15244 (setq end (point))
15245 (when (memq which '(all special))
15246 ;; Get the special properties, like TODO and tags
15247 (goto-char beg)
15248 (when (and (or (not specific) (string= specific "TODO"))
15249 (looking-at org-todo-line-regexp) (match-end 2))
15250 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15251 (when (and (or (not specific) (string= specific "PRIORITY"))
15252 (looking-at org-priority-regexp))
15253 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15254 (when (or (not specific) (string= specific "FILE"))
15255 (push (cons "FILE" buffer-file-name) props))
15256 (when (and (or (not specific) (string= specific "TAGS"))
15257 (setq value (org-get-tags-string))
15258 (string-match "\\S-" value))
15259 (push (cons "TAGS" value) props))
15260 (when (and (or (not specific) (string= specific "ALLTAGS"))
15261 (setq value (org-get-tags-at)))
15262 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15263 ":"))
15264 props))
15265 (when (or (not specific) (string= specific "BLOCKED"))
15266 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15267 (when (or (not specific)
15268 (member specific
15269 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15270 "TIMESTAMP" "TIMESTAMP_IA")))
15271 (catch 'match
15272 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15273 (setq key (if (match-end 1)
15274 (substring (org-match-string-no-properties 1)
15275 0 -1))
15276 string (if (equal key clockstr)
15277 (org-trim
15278 (buffer-substring-no-properties
15279 (match-beginning 3) (goto-char
15280 (point-at-eol))))
15281 (substring (org-match-string-no-properties 3)
15282 1 -1)))
15283 ;; Get the correct property name from the key. This is
15284 ;; necessary if the user has configured time keywords.
15285 (setq key1 (concat key ":"))
15286 (cond
15287 ((not key)
15288 (setq key
15289 (if (= (char-after (match-beginning 3)) ?\[)
15290 "TIMESTAMP_IA" "TIMESTAMP")))
15291 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15292 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15293 ((equal key1 org-closed-string) (setq key "CLOSED"))
15294 ((equal key1 org-clock-string) (setq key "CLOCK")))
15295 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15296 (progn
15297 (push (cons key string) props)
15298 ;; no need to search further if match is found
15299 (throw 'match t))
15300 (when (or (equal key "CLOCK") (not (assoc key props)))
15301 (push (cons key string) props)))))))
15302
15303 (when (memq which '(all standard))
15304 ;; Get the standard properties, like :PROP: ...
15305 (setq range (org-get-property-block beg end))
15306 (when range
15307 (goto-char (car range))
15308 (while (re-search-forward org-property-re
15309 (cdr range) t)
15310 (setq key (org-match-string-no-properties 2)
15311 value (org-trim (or (org-match-string-no-properties 3) "")))
15312 (unless (member key excluded)
15313 (push (cons key (or value "")) props)))))
15314 (if clocksum
15315 (push (cons "CLOCKSUM"
15316 (org-columns-number-to-string (/ (float clocksum) 60.)
15317 'add_times))
15318 props))
15319 (if clocksumt
15320 (push (cons "CLOCKSUM_T"
15321 (org-columns-number-to-string (/ (float clocksumt) 60.)
15322 'add_times))
15323 props))
15324 (unless (assoc "CATEGORY" props)
15325 (push (cons "CATEGORY" (org-get-category)) props))
15326 (append sum-props (nreverse props)))))))
15327
15328 (defun org-entry-get (pom property &optional inherit literal-nil)
15329 "Get value of PROPERTY for entry or content at point-or-marker POM.
15330 If INHERIT is non-nil and the entry does not have the property,
15331 then also check higher levels of the hierarchy.
15332 If INHERIT is the symbol `selective', use inheritance only if the setting
15333 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15334 If the property is present but empty, the return value is the empty string.
15335 If the property is not present at all, nil is returned.
15336
15337 Return the value as a string.
15338
15339 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15340 do not interpret it as the list atom nil. This is used for inheritance
15341 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15342 (org-with-point-at pom
15343 (if (and inherit (if (eq inherit 'selective)
15344 (org-property-inherit-p property)
15345 t))
15346 (org-entry-get-with-inheritance property literal-nil)
15347 (if (member property org-special-properties)
15348 ;; We need a special property. Use `org-entry-properties'
15349 ;; to retrieve it, but specify the wanted property
15350 (cdr (assoc property (org-entry-properties nil 'special property)))
15351 (org-with-wide-buffer
15352 (let ((range (org-get-property-block)))
15353 (when (and range (not (eq (car range) (cdr range)))
15354 (save-excursion
15355 (goto-char (car range))
15356 (re-search-forward
15357 (concat (org-re-property property) "\\|"
15358 (org-re-property (concat property "+")))
15359 (cdr range) t)))
15360 (let* ((props
15361 (list (or (assoc property org-file-properties)
15362 (assoc property org-global-properties)
15363 (assoc property org-global-properties-fixed))))
15364 (ap (lambda (key)
15365 (when (re-search-forward
15366 (org-re-property key) (cdr range) t)
15367 (setq props
15368 (org-update-property-plist
15369 key
15370 (if (match-end 3)
15371 (org-match-string-no-properties 3) "")
15372 props)))))
15373 val)
15374 (goto-char (car range))
15375 (funcall ap property)
15376 (goto-char (car range))
15377 (while (funcall ap (concat property "+")))
15378 (setq val (cdr (assoc property props)))
15379 (when val (if literal-nil val (org-not-nil val)))))))))))
15380
15381 (defun org-property-or-variable-value (var &optional inherit)
15382 "Check if there is a property fixing the value of VAR.
15383 If yes, return this value. If not, return the current value of the variable."
15384 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15385 (if (and prop (stringp prop) (string-match "\\S-" prop))
15386 (read prop)
15387 (symbol-value var))))
15388
15389 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15390 "Delete the property PROPERTY from entry at point-or-marker POM.
15391 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15392 an empty drawer to delete."
15393 (org-with-point-at pom
15394 (if (member property org-special-properties)
15395 nil ; cannot delete these properties.
15396 (let ((range (org-get-property-block)))
15397 (if (and range
15398 (goto-char (car range))
15399 (re-search-forward
15400 (org-re-property property)
15401 (cdr range) t))
15402 (progn
15403 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15404 (and delete-empty-drawer
15405 (org-remove-empty-drawer-at
15406 delete-empty-drawer (car range)))
15407 t)
15408 nil)))))
15409
15410 ;; Multi-values properties are properties that contain multiple values
15411 ;; These values are assumed to be single words, separated by whitespace.
15412 (defun org-entry-add-to-multivalued-property (pom property value)
15413 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15414 (let* ((old (org-entry-get pom property))
15415 (values (and old (org-split-string old "[ \t]"))))
15416 (setq value (org-entry-protect-space value))
15417 (unless (member value values)
15418 (setq values (append values (list value)))
15419 (org-entry-put pom property
15420 (mapconcat 'identity values " ")))))
15421
15422 (defun org-entry-remove-from-multivalued-property (pom property value)
15423 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15424 (let* ((old (org-entry-get pom property))
15425 (values (and old (org-split-string old "[ \t]"))))
15426 (setq value (org-entry-protect-space value))
15427 (when (member value values)
15428 (setq values (delete value values))
15429 (org-entry-put pom property
15430 (mapconcat 'identity values " ")))))
15431
15432 (defun org-entry-member-in-multivalued-property (pom property value)
15433 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15434 (let* ((old (org-entry-get pom property))
15435 (values (and old (org-split-string old "[ \t]"))))
15436 (setq value (org-entry-protect-space value))
15437 (member value values)))
15438
15439 (defun org-entry-get-multivalued-property (pom property)
15440 "Return a list of values in a multivalued property."
15441 (let* ((value (org-entry-get pom property))
15442 (values (and value (org-split-string value "[ \t]"))))
15443 (mapcar 'org-entry-restore-space values)))
15444
15445 (defun org-entry-put-multivalued-property (pom property &rest values)
15446 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15447 VALUES should be a list of strings. Spaces will be protected."
15448 (org-entry-put pom property
15449 (mapconcat 'org-entry-protect-space values " "))
15450 (let* ((value (org-entry-get pom property))
15451 (values (and value (org-split-string value "[ \t]"))))
15452 (mapcar 'org-entry-restore-space values)))
15453
15454 (defun org-entry-protect-space (s)
15455 "Protect spaces and newline in string S."
15456 (while (string-match " " s)
15457 (setq s (replace-match "%20" t t s)))
15458 (while (string-match "\n" s)
15459 (setq s (replace-match "%0A" t t s)))
15460 s)
15461
15462 (defun org-entry-restore-space (s)
15463 "Restore spaces and newline in string S."
15464 (while (string-match "%20" s)
15465 (setq s (replace-match " " t t s)))
15466 (while (string-match "%0A" s)
15467 (setq s (replace-match "\n" t t s)))
15468 s)
15469
15470 (defvar org-entry-property-inherited-from (make-marker)
15471 "Marker pointing to the entry from where a property was inherited.
15472 Each call to `org-entry-get-with-inheritance' will set this marker to the
15473 location of the entry where the inheritance search matched. If there was
15474 no match, the marker will point nowhere.
15475 Note that also `org-entry-get' calls this function, if the INHERIT flag
15476 is set.")
15477
15478 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15479 "Get PROPERTY of entry or content at point, search higher levels if needed.
15480 The search will stop at the first ancestor which has the property defined.
15481 If the value found is \"nil\", return nil to show that the property
15482 should be considered as undefined (this is the meaning of nil here).
15483 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15484 (move-marker org-entry-property-inherited-from nil)
15485 (let (tmp)
15486 (save-excursion
15487 (save-restriction
15488 (widen)
15489 (catch 'ex
15490 (while t
15491 (when (setq tmp (org-entry-get nil property nil literal-nil))
15492 (or (ignore-errors (org-back-to-heading t))
15493 (goto-char (point-min)))
15494 (move-marker org-entry-property-inherited-from (point))
15495 (throw 'ex tmp))
15496 (or (ignore-errors (org-up-heading-safe))
15497 (throw 'ex nil))))))
15498 (setq tmp (or tmp
15499 (cdr (assoc property org-file-properties))
15500 (cdr (assoc property org-global-properties))
15501 (cdr (assoc property org-global-properties-fixed))))
15502 (if literal-nil tmp (org-not-nil tmp))))
15503
15504 (defvar org-property-changed-functions nil
15505 "Hook called when the value of a property has changed.
15506 Each hook function should accept two arguments, the name of the property
15507 and the new value.")
15508
15509 (defun org-entry-put (pom property value)
15510 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15511 If the value is `nil', it is converted to the empty string.
15512 If it is not a string, an error is raised."
15513 (cond ((null value) (setq value ""))
15514 ((not (stringp value))
15515 (error "Properties values should be strings.")))
15516 (org-with-point-at pom
15517 (org-back-to-heading t)
15518 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15519 range)
15520 (cond
15521 ((equal property "TODO")
15522 (when (and (string-match "\\S-" value)
15523 (not (member value org-todo-keywords-1)))
15524 (user-error "\"%s\" is not a valid TODO state" value))
15525 (if (or (not value)
15526 (not (string-match "\\S-" value)))
15527 (setq value 'none))
15528 (org-todo value)
15529 (org-set-tags nil 'align))
15530 ((equal property "PRIORITY")
15531 (org-priority (if (and value (string-match "\\S-" value))
15532 (string-to-char value) ?\ ))
15533 (org-set-tags nil 'align))
15534 ((equal property "CLOCKSUM")
15535 (if (not (re-search-forward
15536 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15537 (error "Cannot find a clock log")
15538 (goto-char (- (match-end 1) 2))
15539 (cond
15540 ((eq value 'earlier) (org-timestamp-down))
15541 ((eq value 'later) (org-timestamp-up)))
15542 (org-clock-sum-current-item)))
15543 ((equal property "SCHEDULED")
15544 (if (re-search-forward org-scheduled-time-regexp end t)
15545 (cond
15546 ((eq value 'earlier) (org-timestamp-change -1 'day))
15547 ((eq value 'later) (org-timestamp-change 1 'day))
15548 (t (call-interactively 'org-schedule)))
15549 (call-interactively 'org-schedule)))
15550 ((equal property "DEADLINE")
15551 (if (re-search-forward org-deadline-time-regexp end t)
15552 (cond
15553 ((eq value 'earlier) (org-timestamp-change -1 'day))
15554 ((eq value 'later) (org-timestamp-change 1 'day))
15555 (t (call-interactively 'org-deadline)))
15556 (call-interactively 'org-deadline)))
15557 ((member property org-special-properties)
15558 (error "The %s property can not yet be set with `org-entry-put'"
15559 property))
15560 (t ; a non-special property
15561 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15562 (setq range (org-get-property-block beg end 'force))
15563 (goto-char (car range))
15564 (if (re-search-forward
15565 (org-re-property property) (cdr range) t)
15566 (progn
15567 (delete-region (match-beginning 0) (match-end 0))
15568 (goto-char (match-beginning 0)))
15569 (goto-char (cdr range))
15570 (insert "\n")
15571 (backward-char 1)
15572 (org-indent-line))
15573 (insert ":" property ":")
15574 (and value (insert " " value))
15575 (org-indent-line)))))
15576 (run-hook-with-args 'org-property-changed-functions property value)))
15577
15578 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15579 "Get all property keys in the current buffer.
15580 With INCLUDE-SPECIALS, also list the special properties that reflect things
15581 like tags and TODO state.
15582 With INCLUDE-DEFAULTS, also include properties that has special meaning
15583 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15584 and others.
15585 With INCLUDE-COLUMNS, also include property names given in COLUMN
15586 formats in the current buffer."
15587 (let (rtn range cfmt s p)
15588 (save-excursion
15589 (save-restriction
15590 (widen)
15591 (goto-char (point-min))
15592 (while (re-search-forward org-property-start-re nil t)
15593 (setq range (org-get-property-block))
15594 (goto-char (car range))
15595 (while (re-search-forward org-property-re
15596 (cdr range) t)
15597 (add-to-list 'rtn (org-match-string-no-properties 2)))
15598 (outline-next-heading))))
15599
15600 (when include-specials
15601 (setq rtn (append org-special-properties rtn)))
15602
15603 (when include-defaults
15604 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15605 (add-to-list 'rtn org-effort-property))
15606
15607 (when include-columns
15608 (save-excursion
15609 (save-restriction
15610 (widen)
15611 (goto-char (point-min))
15612 (while (re-search-forward
15613 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15614 nil t)
15615 (setq cfmt (match-string 2) s 0)
15616 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15617 cfmt s)
15618 (setq s (match-end 0)
15619 p (match-string 1 cfmt))
15620 (unless (or (equal p "ITEM")
15621 (member p org-special-properties))
15622 (add-to-list 'rtn (match-string 1 cfmt))))))))
15623
15624 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15625
15626 (defun org-property-values (key)
15627 "Return a list of all values of property KEY in the current buffer."
15628 (save-excursion
15629 (save-restriction
15630 (widen)
15631 (goto-char (point-min))
15632 (let ((re (org-re-property key))
15633 values)
15634 (while (re-search-forward re nil t)
15635 (add-to-list 'values (org-trim (match-string 3))))
15636 (delete "" values)))))
15637
15638 (defun org-insert-property-drawer ()
15639 "Insert a property drawer into the current entry."
15640 (org-back-to-heading t)
15641 (looking-at org-outline-regexp)
15642 (let ((indent (if org-adapt-indentation
15643 (- (match-end 0) (match-beginning 0))
15644 0))
15645 (beg (point))
15646 (re (concat "^[ \t]*" org-keyword-time-regexp))
15647 end hiddenp)
15648 (outline-next-heading)
15649 (setq end (point))
15650 (goto-char beg)
15651 (while (re-search-forward re end t))
15652 (setq hiddenp (outline-invisible-p))
15653 (end-of-line 1)
15654 (and (equal (char-after) ?\n) (forward-char 1))
15655 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15656 (if (member (match-string 1) '("CLOCK:" ":END:"))
15657 ;; just skip this line
15658 (beginning-of-line 2)
15659 ;; Drawer start, find the end
15660 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15661 (beginning-of-line 1)))
15662 (org-skip-over-state-notes)
15663 (skip-chars-backward " \t\n\r")
15664 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15665 (forward-char 1))
15666 (goto-char (point-at-eol))
15667 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15668 (beginning-of-line 0)
15669 (org-indent-to-column indent)
15670 (beginning-of-line 2)
15671 (org-indent-to-column indent)
15672 (beginning-of-line 0)
15673 (if hiddenp
15674 (save-excursion
15675 (org-back-to-heading t)
15676 (hide-entry))
15677 (org-flag-drawer t))))
15678
15679 (defun org-insert-drawer (&optional arg drawer)
15680 "Insert a drawer at point.
15681
15682 Optional argument DRAWER, when non-nil, is a string representing
15683 drawer's name. Otherwise, the user is prompted for a name.
15684
15685 If a region is active, insert the drawer around that region
15686 instead.
15687
15688 Point is left between drawer's boundaries."
15689 (interactive "P")
15690 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15691 "LOGBOOK"))
15692 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15693 ;; internally by Org. They are meant to be inserted
15694 ;; automatically.
15695 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15696 ;; Remove system drawers from list. Note: For some reason,
15697 ;; `org-completing-read' ignores the predicate while
15698 ;; `completing-read' handles it fine.
15699 (drawer (if arg "PROPERTIES"
15700 (or drawer
15701 (completing-read
15702 "Drawer: " org-drawers
15703 (lambda (d) (not (member d system-drawers))))))))
15704 (cond
15705 ;; With C-u, fall back on `org-insert-property-drawer'
15706 (arg (org-insert-property-drawer))
15707 ;; With an active region, insert a drawer at point.
15708 ((not (org-region-active-p))
15709 (progn
15710 (unless (bolp) (insert "\n"))
15711 (insert (format ":%s:\n\n:END:\n" drawer))
15712 (forward-line -2)))
15713 ;; Otherwise, insert the drawer at point
15714 (t
15715 (let ((rbeg (region-beginning))
15716 (rend (copy-marker (region-end))))
15717 (unwind-protect
15718 (progn
15719 (goto-char rbeg)
15720 (beginning-of-line)
15721 (when (save-excursion
15722 (re-search-forward org-outline-regexp-bol rend t))
15723 (user-error "Drawers cannot contain headlines"))
15724 ;; Position point at the beginning of the first
15725 ;; non-blank line in region. Insert drawer's opening
15726 ;; there, then indent it.
15727 (org-skip-whitespace)
15728 (beginning-of-line)
15729 (insert ":" drawer ":\n")
15730 (forward-line -1)
15731 (indent-for-tab-command)
15732 ;; Move point to the beginning of the first blank line
15733 ;; after the last non-blank line in region. Insert
15734 ;; drawer's closing, then indent it.
15735 (goto-char rend)
15736 (skip-chars-backward " \r\t\n")
15737 (insert "\n:END:")
15738 (deactivate-mark t)
15739 (indent-for-tab-command)
15740 (unless (eolp) (insert "\n")))
15741 ;; Clear marker, whatever the outcome of insertion is.
15742 (set-marker rend nil)))))))
15743
15744 (defvar org-property-set-functions-alist nil
15745 "Property set function alist.
15746 Each entry should have the following format:
15747
15748 (PROPERTY . READ-FUNCTION)
15749
15750 The read function will be called with the same argument as
15751 `org-completing-read'.")
15752
15753 (defun org-set-property-function (property)
15754 "Get the function that should be used to set PROPERTY.
15755 This is computed according to `org-property-set-functions-alist'."
15756 (or (cdr (assoc property org-property-set-functions-alist))
15757 'org-completing-read))
15758
15759 (defun org-read-property-value (property)
15760 "Read PROPERTY value from user."
15761 (let* ((completion-ignore-case t)
15762 (allowed (org-property-get-allowed-values nil property 'table))
15763 (cur (org-entry-get nil property))
15764 (prompt (concat property " value"
15765 (if (and cur (string-match "\\S-" cur))
15766 (concat " [" cur "]") "") ": "))
15767 (set-function (org-set-property-function property))
15768 (val (if allowed
15769 (funcall set-function prompt allowed nil
15770 (not (get-text-property 0 'org-unrestricted
15771 (caar allowed))))
15772 (let (org-completion-use-ido org-completion-use-iswitchb)
15773 (funcall set-function prompt
15774 (mapcar 'list (org-property-values property))
15775 nil nil "" nil cur)))))
15776 (if (equal val "")
15777 cur
15778 val)))
15779
15780 (defvar org-last-set-property nil)
15781 (defvar org-last-set-property-value nil)
15782 (defun org-read-property-name ()
15783 "Read a property name."
15784 (let* ((completion-ignore-case t)
15785 (keys (org-buffer-property-keys nil t t))
15786 (default-prop (or (save-excursion
15787 (save-match-data
15788 (beginning-of-line)
15789 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15790 (null (string= (match-string 1) "END"))
15791 (match-string 1))))
15792 org-last-set-property))
15793 (property (org-icompleting-read
15794 (concat "Property"
15795 (if default-prop (concat " [" default-prop "]") "")
15796 ": ")
15797 (mapcar 'list keys)
15798 nil nil nil nil
15799 default-prop)))
15800 (if (member property keys)
15801 property
15802 (or (cdr (assoc (downcase property)
15803 (mapcar (lambda (x) (cons (downcase x) x))
15804 keys)))
15805 property))))
15806
15807 (defun org-set-property-and-value (use-last)
15808 "Allow to set [PROPERTY]: [value] direction from prompt.
15809 When use-default, don't even ask, just use the last
15810 \"[PROPERTY]: [value]\" string from the history."
15811 (interactive "P")
15812 (let* ((completion-ignore-case t)
15813 (pv (or (and use-last org-last-set-property-value)
15814 (org-completing-read
15815 "Enter a \"[Property]: [value]\" pair: "
15816 nil nil nil nil nil
15817 org-last-set-property-value)))
15818 prop val)
15819 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15820 (setq prop (match-string 1 pv)
15821 val (match-string 2 pv))
15822 (org-set-property prop val))))
15823
15824 (defun org-set-property (property value)
15825 "In the current entry, set PROPERTY to VALUE.
15826 When called interactively, this will prompt for a property name, offering
15827 completion on existing and default properties. And then it will prompt
15828 for a value, offering completion either on allowed values (via an inherited
15829 xxx_ALL property) or on existing values in other instances of this property
15830 in the current file."
15831 (interactive (list nil nil))
15832 (let* ((property (or property (org-read-property-name)))
15833 (value (or value (org-read-property-value property)))
15834 (fn (cdr (assoc property org-properties-postprocess-alist))))
15835 (setq org-last-set-property property)
15836 (setq org-last-set-property-value (concat property ": " value))
15837 ;; Possibly postprocess the inserted value:
15838 (when fn (setq value (funcall fn value)))
15839 (unless (equal (org-entry-get nil property) value)
15840 (org-entry-put nil property value))))
15841
15842 (defun org-delete-property (property &optional delete-empty-drawer)
15843 "In the current entry, delete PROPERTY.
15844 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15845 an empty drawer to delete."
15846 (interactive
15847 (let* ((completion-ignore-case t)
15848 (cat (org-entry-get (point) "CATEGORY"))
15849 (props0 (org-entry-properties nil 'standard))
15850 (props (if cat props0
15851 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15852 (prop (if (< 1 (length props))
15853 (org-icompleting-read "Property: " props nil t)
15854 (caar props))))
15855 (list prop)))
15856 (if (org-entry-delete nil property delete-empty-drawer)
15857 (message "Property %s deleted" property)))
15858
15859 (defun org-delete-property-globally (property)
15860 "Remove PROPERTY globally, from all entries."
15861 (interactive
15862 (let* ((completion-ignore-case t)
15863 (prop (org-icompleting-read
15864 "Globally remove property: "
15865 (mapcar 'list (org-buffer-property-keys)))))
15866 (list prop)))
15867 (save-excursion
15868 (save-restriction
15869 (widen)
15870 (goto-char (point-min))
15871 (let ((cnt 0))
15872 (while (re-search-forward
15873 (org-re-property property)
15874 nil t)
15875 (setq cnt (1+ cnt))
15876 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15877 (message "Property \"%s\" removed from %d entries" property cnt)))))
15878
15879 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15880
15881 (defun org-compute-property-at-point ()
15882 "Compute the property at point.
15883 This looks for an enclosing column format, extracts the operator and
15884 then applies it to the property in the column format's scope."
15885 (interactive)
15886 (unless (org-at-property-p)
15887 (user-error "Not at a property"))
15888 (let ((prop (org-match-string-no-properties 2)))
15889 (org-columns-get-format-and-top-level)
15890 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15891 (user-error "No operator defined for property %s" prop))
15892 (org-columns-compute prop)))
15893
15894 (defvar org-property-allowed-value-functions nil
15895 "Hook for functions supplying allowed values for a specific property.
15896 The functions must take a single argument, the name of the property, and
15897 return a flat list of allowed values. If \":ETC\" is one of
15898 the values, this means that these values are intended as defaults for
15899 completion, but that other values should be allowed too.
15900 The functions must return nil if they are not responsible for this
15901 property.")
15902
15903 (defun org-property-get-allowed-values (pom property &optional table)
15904 "Get allowed values for the property PROPERTY.
15905 When TABLE is non-nil, return an alist that can directly be used for
15906 completion."
15907 (let (vals)
15908 (cond
15909 ((equal property "TODO")
15910 (setq vals (org-with-point-at pom
15911 (append org-todo-keywords-1 '("")))))
15912 ((equal property "PRIORITY")
15913 (let ((n org-lowest-priority))
15914 (while (>= n org-highest-priority)
15915 (push (char-to-string n) vals)
15916 (setq n (1- n)))))
15917 ((member property org-special-properties))
15918 ((setq vals (run-hook-with-args-until-success
15919 'org-property-allowed-value-functions property)))
15920 (t
15921 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15922 (when (and vals (string-match "\\S-" vals))
15923 (setq vals (car (read-from-string (concat "(" vals ")"))))
15924 (setq vals (mapcar (lambda (x)
15925 (cond ((stringp x) x)
15926 ((numberp x) (number-to-string x))
15927 ((symbolp x) (symbol-name x))
15928 (t "???")))
15929 vals)))))
15930 (when (member ":ETC" vals)
15931 (setq vals (remove ":ETC" vals))
15932 (org-add-props (car vals) '(org-unrestricted t)))
15933 (if table (mapcar 'list vals) vals)))
15934
15935 (defun org-property-previous-allowed-value (&optional previous)
15936 "Switch to the next allowed value for this property."
15937 (interactive)
15938 (org-property-next-allowed-value t))
15939
15940 (defun org-property-next-allowed-value (&optional previous)
15941 "Switch to the next allowed value for this property."
15942 (interactive)
15943 (unless (org-at-property-p)
15944 (user-error "Not at a property"))
15945 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15946 (key (match-string 2))
15947 (value (match-string 3))
15948 (allowed (or (org-property-get-allowed-values (point) key)
15949 (and (member value '("[ ]" "[-]" "[X]"))
15950 '("[ ]" "[X]"))))
15951 (heading (save-match-data (nth 4 (org-heading-components))))
15952 nval)
15953 (unless allowed
15954 (user-error "Allowed values for this property have not been defined"))
15955 (if previous (setq allowed (reverse allowed)))
15956 (if (member value allowed)
15957 (setq nval (car (cdr (member value allowed)))))
15958 (setq nval (or nval (car allowed)))
15959 (if (equal nval value)
15960 (user-error "Only one allowed value for this property"))
15961 (org-at-property-p)
15962 (replace-match (concat " :" key ": " nval) t t)
15963 (org-indent-line)
15964 (beginning-of-line 1)
15965 (skip-chars-forward " \t")
15966 (when (equal prop org-effort-property)
15967 (save-excursion
15968 (org-back-to-heading t)
15969 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15970 (when (string= org-clock-current-task heading)
15971 (setq org-clock-effort nval)
15972 (org-clock-update-mode-line)))
15973 (run-hook-with-args 'org-property-changed-functions key nval)))
15974
15975 (defun org-find-olp (path &optional this-buffer)
15976 "Return a marker pointing to the entry at outline path OLP.
15977 If anything goes wrong, throw an error.
15978 You can wrap this call to catch the error like this:
15979
15980 (condition-case msg
15981 (org-mobile-locate-entry (match-string 4))
15982 (error (nth 1 msg)))
15983
15984 The return value will then be either a string with the error message,
15985 or a marker if everything is OK.
15986
15987 If THIS-BUFFER is set, the outline path does not contain a file,
15988 only headings."
15989 (let* ((file (if this-buffer buffer-file-name (pop path)))
15990 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15991 (level 1)
15992 (lmin 1)
15993 (lmax 1)
15994 limit re end found pos heading cnt flevel)
15995 (unless buffer (error "File not found :%s" file))
15996 (with-current-buffer buffer
15997 (save-excursion
15998 (save-restriction
15999 (widen)
16000 (setq limit (point-max))
16001 (goto-char (point-min))
16002 (while (setq heading (pop path))
16003 (setq re (format org-complex-heading-regexp-format
16004 (regexp-quote heading)))
16005 (setq cnt 0 pos (point))
16006 (while (re-search-forward re end t)
16007 (setq level (- (match-end 1) (match-beginning 1)))
16008 (if (and (>= level lmin) (<= level lmax))
16009 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16010 (when (= cnt 0) (error "Heading not found on level %d: %s"
16011 lmax heading))
16012 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16013 lmax heading))
16014 (goto-char found)
16015 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16016 (setq end (save-excursion (org-end-of-subtree t t))))
16017 (when (org-at-heading-p)
16018 (point-marker)))))))
16019
16020 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16021 "Find node HEADING in BUFFER.
16022 Return a marker to the heading if it was found, or nil if not.
16023 If POS-ONLY is set, return just the position instead of a marker.
16024
16025 The heading text must match exact, but it may have a TODO keyword,
16026 a priority cookie and tags in the standard locations."
16027 (with-current-buffer (or buffer (current-buffer))
16028 (save-excursion
16029 (save-restriction
16030 (widen)
16031 (goto-char (point-min))
16032 (let (case-fold-search)
16033 (if (re-search-forward
16034 (format org-complex-heading-regexp-format
16035 (regexp-quote heading)) nil t)
16036 (if pos-only
16037 (match-beginning 0)
16038 (move-marker (make-marker) (match-beginning 0)))))))))
16039
16040 (defun org-find-exact-heading-in-directory (heading &optional dir)
16041 "Find Org node headline HEADING in all .org files in directory DIR.
16042 When the target headline is found, return a marker to this location."
16043 (let ((files (directory-files (or dir default-directory)
16044 nil "\\`[^.#].*\\.org\\'"))
16045 file visiting m buffer)
16046 (catch 'found
16047 (while (setq file (pop files))
16048 (message "trying %s" file)
16049 (setq visiting (org-find-base-buffer-visiting file))
16050 (setq buffer (or visiting (find-file-noselect file)))
16051 (setq m (org-find-exact-headline-in-buffer
16052 heading buffer))
16053 (when (and (not m) (not visiting)) (kill-buffer buffer))
16054 (and m (throw 'found m))))))
16055
16056 (defun org-find-entry-with-id (ident)
16057 "Locate the entry that contains the ID property with exact value IDENT.
16058 IDENT can be a string, a symbol or a number, this function will search for
16059 the string representation of it.
16060 Return the position where this entry starts, or nil if there is no such entry."
16061 (interactive "sID: ")
16062 (let ((id (cond
16063 ((stringp ident) ident)
16064 ((symbol-name ident) (symbol-name ident))
16065 ((numberp ident) (number-to-string ident))
16066 (t (error "IDENT %s must be a string, symbol or number" ident))))
16067 (case-fold-search nil))
16068 (save-excursion
16069 (save-restriction
16070 (widen)
16071 (goto-char (point-min))
16072 (when (re-search-forward
16073 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16074 nil t)
16075 (org-back-to-heading t)
16076 (point))))))
16077
16078 ;;;; Timestamps
16079
16080 (defvar org-last-changed-timestamp nil)
16081 (defvar org-last-inserted-timestamp nil
16082 "The last time stamp inserted with `org-insert-time-stamp'.")
16083 (defvar org-ts-what) ; dynamically scoped parameter
16084
16085 (defun org-time-stamp (arg &optional inactive)
16086 "Prompt for a date/time and insert a time stamp.
16087 If the user specifies a time like HH:MM or if this command is
16088 called with at least one prefix argument, the time stamp contains
16089 the date and the time. Otherwise, only the date is be included.
16090
16091 All parts of a date not specified by the user is filled in from
16092 the current date/time. So if you just press return without
16093 typing anything, the time stamp will represent the current
16094 date/time.
16095
16096 If there is already a timestamp at the cursor, it will be
16097 modified.
16098
16099 With two universal prefix arguments, insert an active timestamp
16100 with the current time without prompting the user.
16101
16102 When called from lisp, the timestamp is inactive if INACTIVE is
16103 non-nil."
16104 (interactive "P")
16105 (let* ((ts nil)
16106 (default-time
16107 ;; Default time is either today, or, when entering a range,
16108 ;; the range start.
16109 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16110 (save-excursion
16111 (re-search-backward
16112 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16113 (- (point) 20) t)))
16114 (apply 'encode-time (org-parse-time-string (match-string 1)))
16115 (current-time)))
16116 (default-input (and ts (org-get-compact-tod ts)))
16117 (repeater (save-excursion
16118 (save-match-data
16119 (beginning-of-line)
16120 (when (re-search-forward
16121 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16122 (save-excursion (progn (end-of-line) (point))) t)
16123 (match-string 0)))))
16124 org-time-was-given org-end-time-was-given time)
16125 (cond
16126 ((and (org-at-timestamp-p t)
16127 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16128 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16129 (insert "--")
16130 (setq time (let ((this-command this-command))
16131 (org-read-date arg 'totime nil nil
16132 default-time default-input inactive)))
16133 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16134 ((org-at-timestamp-p t)
16135 (setq time (let ((this-command this-command))
16136 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16137 (when (org-at-timestamp-p t) ; just to get the match data
16138 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16139 (replace-match "")
16140 (setq org-last-changed-timestamp
16141 (org-insert-time-stamp
16142 time (or org-time-was-given arg)
16143 inactive nil nil (list org-end-time-was-given)))
16144 (when repeater (goto-char (1- (point))) (insert " " repeater)
16145 (setq org-last-changed-timestamp
16146 (concat (substring org-last-inserted-timestamp 0 -1)
16147 " " repeater ">"))))
16148 (message "Timestamp updated"))
16149 ((equal arg '(16))
16150 (org-insert-time-stamp (current-time) t inactive))
16151 (t
16152 (setq time (let ((this-command this-command))
16153 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16154 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16155 nil nil (list org-end-time-was-given))))))
16156
16157 ;; FIXME: can we use this for something else, like computing time differences?
16158 (defun org-get-compact-tod (s)
16159 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16160 (let* ((t1 (match-string 1 s))
16161 (h1 (string-to-number (match-string 2 s)))
16162 (m1 (string-to-number (match-string 3 s)))
16163 (t2 (and (match-end 4) (match-string 5 s)))
16164 (h2 (and t2 (string-to-number (match-string 6 s))))
16165 (m2 (and t2 (string-to-number (match-string 7 s))))
16166 dh dm)
16167 (if (not t2)
16168 t1
16169 (setq dh (- h2 h1) dm (- m2 m1))
16170 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16171 (concat t1 "+" (number-to-string dh)
16172 (and (/= 0 dm) (format ":%02d" dm)))))))
16173
16174 (defun org-time-stamp-inactive (&optional arg)
16175 "Insert an inactive time stamp.
16176 An inactive time stamp is enclosed in square brackets instead of angle
16177 brackets. It is inactive in the sense that it does not trigger agenda entries,
16178 does not link to the calendar and cannot be changed with the S-cursor keys.
16179 So these are more for recording a certain time/date."
16180 (interactive "P")
16181 (org-time-stamp arg 'inactive))
16182
16183 (defvar org-date-ovl (make-overlay 1 1))
16184 (overlay-put org-date-ovl 'face 'org-date-selected)
16185 (org-detach-overlay org-date-ovl)
16186
16187 (defvar org-ans1) ; dynamically scoped parameter
16188 (defvar org-ans2) ; dynamically scoped parameter
16189
16190 (defvar org-plain-time-of-day-regexp) ; defined below
16191
16192 (defvar org-overriding-default-time nil) ; dynamically scoped
16193 (defvar org-read-date-overlay nil)
16194 (defvar org-dcst nil) ; dynamically scoped
16195 (defvar org-read-date-history nil)
16196 (defvar org-read-date-final-answer nil)
16197 (defvar org-read-date-analyze-futurep nil)
16198 (defvar org-read-date-analyze-forced-year nil)
16199 (defvar org-read-date-inactive)
16200
16201 (defvar org-read-date-minibuffer-local-map
16202 (let* ((org-replace-disputed-keys nil)
16203 (map (make-sparse-keymap)))
16204 (set-keymap-parent map minibuffer-local-map)
16205 (org-defkey map (kbd ".")
16206 (lambda () (interactive)
16207 ;; Are we at the beginning of the prompt?
16208 (if (looking-back "^[^:]+: ")
16209 (org-eval-in-calendar '(calendar-goto-today))
16210 (insert "."))))
16211 (org-defkey map (kbd "C-.")
16212 (lambda () (interactive)
16213 (org-eval-in-calendar '(calendar-goto-today))))
16214 (org-defkey map [(meta shift left)]
16215 (lambda () (interactive)
16216 (org-eval-in-calendar '(calendar-backward-month 1))))
16217 (org-defkey map [(meta shift right)]
16218 (lambda () (interactive)
16219 (org-eval-in-calendar '(calendar-forward-month 1))))
16220 (org-defkey map [(meta shift up)]
16221 (lambda () (interactive)
16222 (org-eval-in-calendar '(calendar-backward-year 1))))
16223 (org-defkey map [(meta shift down)]
16224 (lambda () (interactive)
16225 (org-eval-in-calendar '(calendar-forward-year 1))))
16226 (org-defkey map [?\e (shift left)]
16227 (lambda () (interactive)
16228 (org-eval-in-calendar '(calendar-backward-month 1))))
16229 (org-defkey map [?\e (shift right)]
16230 (lambda () (interactive)
16231 (org-eval-in-calendar '(calendar-forward-month 1))))
16232 (org-defkey map [?\e (shift up)]
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-backward-year 1))))
16235 (org-defkey map [?\e (shift down)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-forward-year 1))))
16238 (org-defkey map [(shift up)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-backward-week 1))))
16241 (org-defkey map [(shift down)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-forward-week 1))))
16244 (org-defkey map [(shift left)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-backward-day 1))))
16247 (org-defkey map [(shift right)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-forward-day 1))))
16250 (org-defkey map "!"
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(diary-view-entries))
16253 (message "")))
16254 (org-defkey map ">"
16255 (lambda () (interactive)
16256 (org-eval-in-calendar '(scroll-calendar-left 1))))
16257 (org-defkey map "<"
16258 (lambda () (interactive)
16259 (org-eval-in-calendar '(scroll-calendar-right 1))))
16260 (org-defkey map "\C-v"
16261 (lambda () (interactive)
16262 (org-eval-in-calendar
16263 '(calendar-scroll-left-three-months 1))))
16264 (org-defkey map "\M-v"
16265 (lambda () (interactive)
16266 (org-eval-in-calendar
16267 '(calendar-scroll-right-three-months 1))))
16268 map)
16269 "Keymap for minibuffer commands when using `org-read-date'.")
16270
16271 (defvar org-def)
16272 (defvar org-defdecode)
16273 (defvar org-with-time)
16274
16275 (defun org-read-date (&optional org-with-time to-time from-string prompt
16276 default-time default-input inactive)
16277 "Read a date, possibly a time, and make things smooth for the user.
16278 The prompt will suggest to enter an ISO date, but you can also enter anything
16279 which will at least partially be understood by `parse-time-string'.
16280 Unrecognized parts of the date will default to the current day, month, year,
16281 hour and minute. If this command is called to replace a timestamp at point,
16282 or to enter the second timestamp of a range, the default time is taken
16283 from the existing stamp. Furthermore, the command prefers the future,
16284 so if you are giving a date where the year is not given, and the day-month
16285 combination is already past in the current year, it will assume you
16286 mean next year. For details, see the manual. A few examples:
16287
16288 3-2-5 --> 2003-02-05
16289 feb 15 --> currentyear-02-15
16290 2/15 --> currentyear-02-15
16291 sep 12 9 --> 2009-09-12
16292 12:45 --> today 12:45
16293 22 sept 0:34 --> currentyear-09-22 0:34
16294 12 --> currentyear-currentmonth-12
16295 Fri --> nearest Friday after today
16296 -Tue --> last Tuesday
16297 etc.
16298
16299 Furthermore you can specify a relative date by giving, as the *first* thing
16300 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16301 change in days weeks, months, years.
16302 With a single plus or minus, the date is relative to today. With a double
16303 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16304 +4d --> four days from today
16305 +4 --> same as above
16306 +2w --> two weeks from today
16307 ++5 --> five days from default date
16308
16309 The function understands only English month and weekday abbreviations.
16310
16311 While prompting, a calendar is popped up - you can also select the
16312 date with the mouse (button 1). The calendar shows a period of three
16313 months. To scroll it to other months, use the keys `>' and `<'.
16314 If you don't like the calendar, turn it off with
16315 \(setq org-read-date-popup-calendar nil)
16316
16317 With optional argument TO-TIME, the date will immediately be converted
16318 to an internal time.
16319 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16320 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16321 still enter a time, and this function will inform the calling routine
16322 about this change. The calling routine may then choose to change the
16323 format used to insert the time stamp into the buffer to include the time.
16324 With optional argument FROM-STRING, read from this string instead from
16325 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16326 the time/date that is used for everything that is not specified by the
16327 user."
16328 (require 'parse-time)
16329 (let* ((org-time-stamp-rounding-minutes
16330 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16331 (org-dcst org-display-custom-times)
16332 (ct (org-current-time))
16333 (org-def (or org-overriding-default-time default-time ct))
16334 (org-defdecode (decode-time org-def))
16335 (dummy (progn
16336 (when (< (nth 2 org-defdecode) org-extend-today-until)
16337 (setcar (nthcdr 2 org-defdecode) -1)
16338 (setcar (nthcdr 1 org-defdecode) 59)
16339 (setq org-def (apply 'encode-time org-defdecode)
16340 org-defdecode (decode-time org-def)))))
16341 (mouse-autoselect-window nil) ; Don't let the mouse jump
16342 (calendar-frame-setup nil)
16343 (calendar-setup nil)
16344 (calendar-move-hook nil)
16345 (calendar-view-diary-initially-flag nil)
16346 (calendar-view-holidays-initially-flag nil)
16347 (timestr (format-time-string
16348 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16349 (prompt (concat (if prompt (concat prompt " ") "")
16350 (format "Date+time [%s]: " timestr)))
16351 ans (org-ans0 "") org-ans1 org-ans2 final)
16352
16353 (cond
16354 (from-string (setq ans from-string))
16355 (org-read-date-popup-calendar
16356 (save-excursion
16357 (save-window-excursion
16358 (calendar)
16359 (org-eval-in-calendar '(setq cursor-type nil) t)
16360 (unwind-protect
16361 (progn
16362 (calendar-forward-day (- (time-to-days org-def)
16363 (calendar-absolute-from-gregorian
16364 (calendar-current-date))))
16365 (org-eval-in-calendar nil t)
16366 (let* ((old-map (current-local-map))
16367 (map (copy-keymap calendar-mode-map))
16368 (minibuffer-local-map
16369 (copy-keymap org-read-date-minibuffer-local-map)))
16370 (org-defkey map (kbd "RET") 'org-calendar-select)
16371 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16372 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16373 (unwind-protect
16374 (progn
16375 (use-local-map map)
16376 (setq org-read-date-inactive inactive)
16377 (add-hook 'post-command-hook 'org-read-date-display)
16378 (setq org-ans0 (read-string prompt default-input
16379 'org-read-date-history nil))
16380 ;; org-ans0: from prompt
16381 ;; org-ans1: from mouse click
16382 ;; org-ans2: from calendar motion
16383 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16384 (remove-hook 'post-command-hook 'org-read-date-display)
16385 (use-local-map old-map)
16386 (when org-read-date-overlay
16387 (delete-overlay org-read-date-overlay)
16388 (setq org-read-date-overlay nil)))))
16389 (bury-buffer "*Calendar*")))))
16390
16391 (t ; Naked prompt only
16392 (unwind-protect
16393 (setq ans (read-string prompt default-input
16394 'org-read-date-history timestr))
16395 (when org-read-date-overlay
16396 (delete-overlay org-read-date-overlay)
16397 (setq org-read-date-overlay nil)))))
16398
16399 (setq final (org-read-date-analyze ans org-def org-defdecode))
16400
16401 (when org-read-date-analyze-forced-year
16402 (message "Year was forced into %s"
16403 (if org-read-date-force-compatible-dates
16404 "compatible range (1970-2037)"
16405 "range representable on this machine"))
16406 (ding))
16407
16408 ;; One round trip to get rid of 34th of August and stuff like that....
16409 (setq final (decode-time (apply 'encode-time final)))
16410
16411 (setq org-read-date-final-answer ans)
16412
16413 (if to-time
16414 (apply 'encode-time final)
16415 (if (and (boundp 'org-time-was-given) org-time-was-given)
16416 (format "%04d-%02d-%02d %02d:%02d"
16417 (nth 5 final) (nth 4 final) (nth 3 final)
16418 (nth 2 final) (nth 1 final))
16419 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16420
16421 (defun org-read-date-display ()
16422 "Display the current date prompt interpretation in the minibuffer."
16423 (when org-read-date-display-live
16424 (when org-read-date-overlay
16425 (delete-overlay org-read-date-overlay))
16426 (when (minibufferp (current-buffer))
16427 (save-excursion
16428 (end-of-line 1)
16429 (while (not (equal (buffer-substring
16430 (max (point-min) (- (point) 4)) (point))
16431 " "))
16432 (insert " ")))
16433 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16434 " " (or org-ans1 org-ans2)))
16435 (org-end-time-was-given nil)
16436 (f (org-read-date-analyze ans org-def org-defdecode))
16437 (fmts (if org-dcst
16438 org-time-stamp-custom-formats
16439 org-time-stamp-formats))
16440 (fmt (if (or org-with-time
16441 (and (boundp 'org-time-was-given) org-time-was-given))
16442 (cdr fmts)
16443 (car fmts)))
16444 (txt (format-time-string fmt (apply 'encode-time f)))
16445 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16446 (txt (concat "=> " txt)))
16447 (when (and org-end-time-was-given
16448 (string-match org-plain-time-of-day-regexp txt))
16449 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16450 org-end-time-was-given
16451 (substring txt (match-end 0)))))
16452 (when org-read-date-analyze-futurep
16453 (setq txt (concat txt " (=>F)")))
16454 (setq org-read-date-overlay
16455 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16456 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16457
16458 (defun org-read-date-analyze (ans org-def org-defdecode)
16459 "Analyze the combined answer of the date prompt."
16460 ;; FIXME: cleanup and comment
16461 (let ((nowdecode (decode-time (current-time)))
16462 delta deltan deltaw deltadef year month day
16463 hour minute second wday pm h2 m2 tl wday1
16464 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16465 (setq org-read-date-analyze-futurep nil
16466 org-read-date-analyze-forced-year nil)
16467 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16468 (setq ans "+0"))
16469
16470 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16471 (setq ans (replace-match "" t t ans)
16472 deltan (car delta)
16473 deltaw (nth 1 delta)
16474 deltadef (nth 2 delta)))
16475
16476 ;; Check if there is an iso week date in there. If yes, store the
16477 ;; info and postpone interpreting it until the rest of the parsing
16478 ;; is done.
16479 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16480 (setq iso-year (if (match-end 1)
16481 (org-small-year-to-year
16482 (string-to-number (match-string 1 ans))))
16483 iso-weekday (if (match-end 3)
16484 (string-to-number (match-string 3 ans)))
16485 iso-week (string-to-number (match-string 2 ans)))
16486 (setq ans (replace-match "" t t ans)))
16487
16488 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16489 (when (string-match
16490 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16491 (setq year (if (match-end 2)
16492 (string-to-number (match-string 2 ans))
16493 (progn (setq kill-year t)
16494 (string-to-number (format-time-string "%Y"))))
16495 month (string-to-number (match-string 3 ans))
16496 day (string-to-number (match-string 4 ans)))
16497 (if (< year 100) (setq year (+ 2000 year)))
16498 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16499 t nil ans)))
16500
16501 ;; Help matching dotted european dates
16502 (when (string-match
16503 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16504 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16505 (setq kill-year t)
16506 (string-to-number (format-time-string "%Y")))
16507 day (string-to-number (match-string 1 ans))
16508 month (string-to-number (match-string 2 ans))
16509 ans (replace-match (format "%04d-%02d-%02d" year month day)
16510 t nil ans)))
16511
16512 ;; Help matching american dates, like 5/30 or 5/30/7
16513 (when (string-match
16514 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16515 (setq year (if (match-end 4)
16516 (string-to-number (match-string 4 ans))
16517 (progn (setq kill-year t)
16518 (string-to-number (format-time-string "%Y"))))
16519 month (string-to-number (match-string 1 ans))
16520 day (string-to-number (match-string 2 ans)))
16521 (if (< year 100) (setq year (+ 2000 year)))
16522 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16523 t nil ans)))
16524 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16525 ;; If there is a time with am/pm, and *no* time without it, we convert
16526 ;; so that matching will be successful.
16527 (loop for i from 1 to 2 do ; twice, for end time as well
16528 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16529 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16530 (setq hour (string-to-number (match-string 1 ans))
16531 minute (if (match-end 3)
16532 (string-to-number (match-string 3 ans))
16533 0)
16534 pm (equal ?p
16535 (string-to-char (downcase (match-string 4 ans)))))
16536 (if (and (= hour 12) (not pm))
16537 (setq hour 0)
16538 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16539 (setq ans (replace-match (format "%02d:%02d" hour minute)
16540 t t ans))))
16541
16542 ;; Check if a time range is given as a duration
16543 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16544 (setq hour (string-to-number (match-string 1 ans))
16545 h2 (+ hour (string-to-number (match-string 3 ans)))
16546 minute (string-to-number (match-string 2 ans))
16547 m2 (+ minute (if (match-end 5) (string-to-number
16548 (match-string 5 ans))0)))
16549 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16550 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16551 t t ans)))
16552
16553 ;; Check if there is a time range
16554 (when (boundp 'org-end-time-was-given)
16555 (setq org-time-was-given nil)
16556 (when (and (string-match org-plain-time-of-day-regexp ans)
16557 (match-end 8))
16558 (setq org-end-time-was-given (match-string 8 ans))
16559 (setq ans (concat (substring ans 0 (match-beginning 7))
16560 (substring ans (match-end 7))))))
16561
16562 (setq tl (parse-time-string ans)
16563 day (or (nth 3 tl) (nth 3 org-defdecode))
16564 month (or (nth 4 tl)
16565 (if (and org-read-date-prefer-future
16566 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16567 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16568 (nth 4 org-defdecode)))
16569 year (or (and (not kill-year) (nth 5 tl))
16570 (if (and org-read-date-prefer-future
16571 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16572 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16573 (nth 5 org-defdecode)))
16574 hour (or (nth 2 tl) (nth 2 org-defdecode))
16575 minute (or (nth 1 tl) (nth 1 org-defdecode))
16576 second (or (nth 0 tl) 0)
16577 wday (nth 6 tl))
16578
16579 (when (and (eq org-read-date-prefer-future 'time)
16580 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16581 (equal day (nth 3 nowdecode))
16582 (equal month (nth 4 nowdecode))
16583 (equal year (nth 5 nowdecode))
16584 (nth 2 tl)
16585 (or (< (nth 2 tl) (nth 2 nowdecode))
16586 (and (= (nth 2 tl) (nth 2 nowdecode))
16587 (nth 1 tl)
16588 (< (nth 1 tl) (nth 1 nowdecode)))))
16589 (setq day (1+ day)
16590 futurep t))
16591
16592 ;; Special date definitions below
16593 (cond
16594 (iso-week
16595 ;; There was an iso week
16596 (require 'cal-iso)
16597 (setq futurep nil)
16598 (setq year (or iso-year year)
16599 day (or iso-weekday wday 1)
16600 wday nil ; to make sure that the trigger below does not match
16601 iso-date (calendar-gregorian-from-absolute
16602 (calendar-absolute-from-iso
16603 (list iso-week day year))))
16604 ; FIXME: Should we also push ISO weeks into the future?
16605 ; (when (and org-read-date-prefer-future
16606 ; (not iso-year)
16607 ; (< (calendar-absolute-from-gregorian iso-date)
16608 ; (time-to-days (current-time))))
16609 ; (setq year (1+ year)
16610 ; iso-date (calendar-gregorian-from-absolute
16611 ; (calendar-absolute-from-iso
16612 ; (list iso-week day year)))))
16613 (setq month (car iso-date)
16614 year (nth 2 iso-date)
16615 day (nth 1 iso-date)))
16616 (deltan
16617 (setq futurep nil)
16618 (unless deltadef
16619 (let ((now (decode-time (current-time))))
16620 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16621 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16622 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16623 ((equal deltaw "m") (setq month (+ month deltan)))
16624 ((equal deltaw "y") (setq year (+ year deltan)))))
16625 ((and wday (not (nth 3 tl)))
16626 ;; Weekday was given, but no day, so pick that day in the week
16627 ;; on or after the derived date.
16628 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16629 (unless (equal wday wday1)
16630 (setq day (+ day (% (- wday wday1 -7) 7))))))
16631 (if (and (boundp 'org-time-was-given)
16632 (nth 2 tl))
16633 (setq org-time-was-given t))
16634 (if (< year 100) (setq year (+ 2000 year)))
16635 ;; Check of the date is representable
16636 (if org-read-date-force-compatible-dates
16637 (progn
16638 (if (< year 1970)
16639 (setq year 1970 org-read-date-analyze-forced-year t))
16640 (if (> year 2037)
16641 (setq year 2037 org-read-date-analyze-forced-year t)))
16642 (condition-case nil
16643 (ignore (encode-time second minute hour day month year))
16644 (error
16645 (setq year (nth 5 org-defdecode))
16646 (setq org-read-date-analyze-forced-year t))))
16647 (setq org-read-date-analyze-futurep futurep)
16648 (list second minute hour day month year)))
16649
16650 (defvar parse-time-weekdays)
16651 (defun org-read-date-get-relative (s today default)
16652 "Check string S for special relative date string.
16653 TODAY and DEFAULT are internal times, for today and for a default.
16654 Return shift list (N what def-flag)
16655 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16656 N is the number of WHATs to shift.
16657 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16658 the DEFAULT date rather than TODAY."
16659 (require 'parse-time)
16660 (when (and
16661 (string-match
16662 (concat
16663 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16664 "\\([0-9]+\\)?"
16665 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16666 "\\([ \t]\\|$\\)") s)
16667 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16668 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16669 (string-to-char (substring (match-string 1 s) -1))
16670 ?+))
16671 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16672 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16673 (what (if (match-end 3) (match-string 3 s) "d"))
16674 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16675 (date (if rel default today))
16676 (wday (nth 6 (decode-time date)))
16677 delta)
16678 (if wday1
16679 (progn
16680 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16681 (if (= delta 0) (setq delta 7))
16682 (if (= dir ?-)
16683 (progn
16684 (setq delta (- delta 7))
16685 (if (= delta 0) (setq delta -7))))
16686 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16687 (list delta "d" rel))
16688 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16689
16690 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16691 "Turn a user-specified date into the internal representation.
16692 The internal representation needed by the calendar is (month day year).
16693 This is a wrapper to handle the brain-dead convention in calendar that
16694 user function argument order change dependent on argument order."
16695 (if (boundp 'calendar-date-style)
16696 (cond
16697 ((eq calendar-date-style 'american)
16698 (list arg1 arg2 arg3))
16699 ((eq calendar-date-style 'european)
16700 (list arg2 arg1 arg3))
16701 ((eq calendar-date-style 'iso)
16702 (list arg2 arg3 arg1)))
16703 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16704 (if (org-bound-and-true-p european-calendar-style)
16705 (list arg2 arg1 arg3)
16706 (list arg1 arg2 arg3)))))
16707
16708 (defun org-eval-in-calendar (form &optional keepdate)
16709 "Eval FORM in the calendar window and return to current window.
16710 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16711 otherwise stick to the current value of `org-ans2'."
16712 (let ((sf (selected-frame))
16713 (sw (selected-window)))
16714 (select-window (get-buffer-window "*Calendar*" t))
16715 (eval form)
16716 (when (and (not keepdate) (calendar-cursor-to-date))
16717 (let* ((date (calendar-cursor-to-date))
16718 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16719 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16720 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16721 (select-window sw)
16722 (org-select-frame-set-input-focus sf)))
16723
16724 (defun org-calendar-select ()
16725 "Return to `org-read-date' with the date currently selected.
16726 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16727 (interactive)
16728 (when (calendar-cursor-to-date)
16729 (let* ((date (calendar-cursor-to-date))
16730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16731 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16732 (if (active-minibuffer-window) (exit-minibuffer))))
16733
16734 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16735 "Insert a date stamp for the date given by the internal TIME.
16736 WITH-HM means use the stamp format that includes the time of the day.
16737 INACTIVE means use square brackets instead of angular ones, so that the
16738 stamp will not contribute to the agenda.
16739 PRE and POST are optional strings to be inserted before and after the
16740 stamp.
16741 The command returns the inserted time stamp."
16742 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16743 stamp)
16744 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16745 (insert-before-markers (or pre ""))
16746 (when (listp extra)
16747 (setq extra (car extra))
16748 (if (and (stringp extra)
16749 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16750 (setq extra (format "-%02d:%02d"
16751 (string-to-number (match-string 1 extra))
16752 (string-to-number (match-string 2 extra))))
16753 (setq extra nil)))
16754 (when extra
16755 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16756 (insert-before-markers (setq stamp (format-time-string fmt time)))
16757 (insert-before-markers (or post ""))
16758 (setq org-last-inserted-timestamp stamp)))
16759
16760 (defun org-toggle-time-stamp-overlays ()
16761 "Toggle the use of custom time stamp formats."
16762 (interactive)
16763 (setq org-display-custom-times (not org-display-custom-times))
16764 (unless org-display-custom-times
16765 (let ((p (point-min)) (bmp (buffer-modified-p)))
16766 (while (setq p (next-single-property-change p 'display))
16767 (if (and (get-text-property p 'display)
16768 (eq (get-text-property p 'face) 'org-date))
16769 (remove-text-properties
16770 p (setq p (next-single-property-change p 'display))
16771 '(display t))))
16772 (set-buffer-modified-p bmp)))
16773 (if (featurep 'xemacs)
16774 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16775 (org-restart-font-lock)
16776 (setq org-table-may-need-update t)
16777 (if org-display-custom-times
16778 (message "Time stamps are overlaid with custom format")
16779 (message "Time stamp overlays removed")))
16780
16781 (defun org-display-custom-time (beg end)
16782 "Overlay modified time stamp format over timestamp between BEG and END."
16783 (let* ((ts (buffer-substring beg end))
16784 t1 w1 with-hm tf time str w2 (off 0))
16785 (save-match-data
16786 (setq t1 (org-parse-time-string ts t))
16787 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16788 (setq off (- (match-end 0) (match-beginning 0)))))
16789 (setq end (- end off))
16790 (setq w1 (- end beg)
16791 with-hm (and (nth 1 t1) (nth 2 t1))
16792 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16793 time (org-fix-decoded-time t1)
16794 str (org-add-props
16795 (format-time-string
16796 (substring tf 1 -1) (apply 'encode-time time))
16797 nil 'mouse-face 'highlight)
16798 w2 (length str))
16799 (if (not (= w2 w1))
16800 (add-text-properties (1+ beg) (+ 2 beg)
16801 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16802 (if (featurep 'xemacs)
16803 (progn
16804 (put-text-property beg end 'invisible t)
16805 (put-text-property beg end 'end-glyph (make-glyph str)))
16806 (put-text-property beg end 'display str))))
16807
16808 (defun org-translate-time (string)
16809 "Translate all timestamps in STRING to custom format.
16810 But do this only if the variable `org-display-custom-times' is set."
16811 (when org-display-custom-times
16812 (save-match-data
16813 (let* ((start 0)
16814 (re org-ts-regexp-both)
16815 t1 with-hm inactive tf time str beg end)
16816 (while (setq start (string-match re string start))
16817 (setq beg (match-beginning 0)
16818 end (match-end 0)
16819 t1 (save-match-data
16820 (org-parse-time-string (substring string beg end) t))
16821 with-hm (and (nth 1 t1) (nth 2 t1))
16822 inactive (equal (substring string beg (1+ beg)) "[")
16823 tf (funcall (if with-hm 'cdr 'car)
16824 org-time-stamp-custom-formats)
16825 time (org-fix-decoded-time t1)
16826 str (format-time-string
16827 (concat
16828 (if inactive "[" "<") (substring tf 1 -1)
16829 (if inactive "]" ">"))
16830 (apply 'encode-time time))
16831 string (replace-match str t t string)
16832 start (+ start (length str)))))))
16833 string)
16834
16835 (defun org-fix-decoded-time (time)
16836 "Set 0 instead of nil for the first 6 elements of time.
16837 Don't touch the rest."
16838 (let ((n 0))
16839 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16840
16841 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16842
16843 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16844 "Difference between TIMESTAMP-STRING and now in days.
16845 If SECONDS is non-nil, return the difference in seconds."
16846 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16847 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16848 (funcall fdiff (current-time)))))
16849
16850 (defun org-deadline-close (timestamp-string &optional ndays)
16851 "Is the time in TIMESTAMP-STRING close to the current date?"
16852 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16853 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16854 (not (org-entry-is-done-p))))
16855
16856 (defun org-get-wdays (ts &optional delay zero-delay)
16857 "Get the deadline lead time appropriate for timestring TS.
16858 When DELAY is non-nil, get the delay time for scheduled items
16859 instead of the deadline lead time. When ZERO-DELAY is non-nil
16860 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16861 don't try to find the delay cookie in the scheduled timestamp."
16862 (let ((tv (if delay org-scheduled-delay-days
16863 org-deadline-warning-days)))
16864 (cond
16865 ((or (and delay (< tv 0))
16866 (and delay zero-delay (<= tv 0))
16867 (and (not delay) (<= tv 0)))
16868 ;; Enforce this value no matter what
16869 (- tv))
16870 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16871 ;; lead time is specified.
16872 (floor (* (string-to-number (match-string 1 ts))
16873 (cdr (assoc (match-string 2 ts)
16874 '(("d" . 1) ("w" . 7)
16875 ("m" . 30.4) ("y" . 365.25)
16876 ("h" . 0.041667)))))))
16877 ;; go for the default.
16878 (t tv))))
16879
16880 (defun org-calendar-select-mouse (ev)
16881 "Return to `org-read-date' with the date currently selected.
16882 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16883 (interactive "e")
16884 (mouse-set-point ev)
16885 (when (calendar-cursor-to-date)
16886 (let* ((date (calendar-cursor-to-date))
16887 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16888 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16889 (if (active-minibuffer-window) (exit-minibuffer))))
16890
16891 (defun org-check-deadlines (ndays)
16892 "Check if there are any deadlines due or past due.
16893 A deadline is considered due if it happens within `org-deadline-warning-days'
16894 days from today's date. If the deadline appears in an entry marked DONE,
16895 it is not shown. The prefix arg NDAYS can be used to test that many
16896 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16897 (interactive "P")
16898 (let* ((org-warn-days
16899 (cond
16900 ((equal ndays '(4)) 100000)
16901 (ndays (prefix-numeric-value ndays))
16902 (t (abs org-deadline-warning-days))))
16903 (case-fold-search nil)
16904 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16905 (callback
16906 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16907
16908 (message "%d deadlines past-due or due within %d days"
16909 (org-occur regexp nil callback)
16910 org-warn-days)))
16911
16912 (defsubst org-re-timestamp (type)
16913 "Return a regexp for timestamp TYPE.
16914 Allowed values for TYPE are:
16915
16916 all: all timestamps
16917 active: only active timestamps (<...>)
16918 inactive: only inactive timestamps ([...])
16919 scheduled: only scheduled timestamps
16920 deadline: only deadline timestamps
16921 closed: only closed time-stamps
16922
16923 When TYPE is nil, fall back on returning a regexp that matches
16924 both scheduled and deadline timestamps."
16925 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16926 ((eq type 'active) org-ts-regexp)
16927 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16928 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16929 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16930 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16931 ((eq type 'scheduled-or-deadline)
16932 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16933
16934 (defun org-check-before-date (date)
16935 "Check if there are deadlines or scheduled entries before DATE."
16936 (interactive (list (org-read-date)))
16937 (let ((case-fold-search nil)
16938 (regexp (org-re-timestamp org-ts-type))
16939 (callback
16940 (lambda () (time-less-p
16941 (org-time-string-to-time (match-string 1))
16942 (org-time-string-to-time date)))))
16943 (message "%d entries before %s"
16944 (org-occur regexp nil callback) date)))
16945
16946 (defun org-check-after-date (date)
16947 "Check if there are deadlines or scheduled entries after DATE."
16948 (interactive (list (org-read-date)))
16949 (let ((case-fold-search nil)
16950 (regexp (org-re-timestamp org-ts-type))
16951 (callback
16952 (lambda () (not
16953 (time-less-p
16954 (org-time-string-to-time (match-string 1))
16955 (org-time-string-to-time date))))))
16956 (message "%d entries after %s"
16957 (org-occur regexp nil callback) date)))
16958
16959 (defun org-check-dates-range (start-date end-date)
16960 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16961 (interactive (list (org-read-date nil nil nil "Range starts")
16962 (org-read-date nil nil nil "Range end")))
16963 (let ((case-fold-search nil)
16964 (regexp (org-re-timestamp org-ts-type))
16965 (callback
16966 (lambda ()
16967 (let ((match (match-string 1)))
16968 (and
16969 (not (time-less-p
16970 (org-time-string-to-time match)
16971 (org-time-string-to-time start-date)))
16972 (time-less-p
16973 (org-time-string-to-time match)
16974 (org-time-string-to-time end-date)))))))
16975 (message "%d entries between %s and %s"
16976 (org-occur regexp nil callback) start-date end-date)))
16977
16978 (defun org-evaluate-time-range (&optional to-buffer)
16979 "Evaluate a time range by computing the difference between start and end.
16980 Normally the result is just printed in the echo area, but with prefix arg
16981 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16982 If the time range is actually in a table, the result is inserted into the
16983 next column.
16984 For time difference computation, a year is assumed to be exactly 365
16985 days in order to avoid rounding problems."
16986 (interactive "P")
16987 (or
16988 (org-clock-update-time-maybe)
16989 (save-excursion
16990 (unless (org-at-date-range-p t)
16991 (goto-char (point-at-bol))
16992 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16993 (if (not (org-at-date-range-p t))
16994 (user-error "Not at a time-stamp range, and none found in current line")))
16995 (let* ((ts1 (match-string 1))
16996 (ts2 (match-string 2))
16997 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16998 (match-end (match-end 0))
16999 (time1 (org-time-string-to-time ts1))
17000 (time2 (org-time-string-to-time ts2))
17001 (t1 (org-float-time time1))
17002 (t2 (org-float-time time2))
17003 (diff (abs (- t2 t1)))
17004 (negative (< (- t2 t1) 0))
17005 ;; (ys (floor (* 365 24 60 60)))
17006 (ds (* 24 60 60))
17007 (hs (* 60 60))
17008 (fy "%dy %dd %02d:%02d")
17009 (fy1 "%dy %dd")
17010 (fd "%dd %02d:%02d")
17011 (fd1 "%dd")
17012 (fh "%02d:%02d")
17013 y d h m align)
17014 (if havetime
17015 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17016 y 0
17017 d (floor (/ diff ds)) diff (mod diff ds)
17018 h (floor (/ diff hs)) diff (mod diff hs)
17019 m (floor (/ diff 60)))
17020 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17021 y 0
17022 d (floor (+ (/ diff ds) 0.5))
17023 h 0 m 0))
17024 (if (not to-buffer)
17025 (message "%s" (org-make-tdiff-string y d h m))
17026 (if (org-at-table-p)
17027 (progn
17028 (goto-char match-end)
17029 (setq align t)
17030 (and (looking-at " *|") (goto-char (match-end 0))))
17031 (goto-char match-end))
17032 (if (looking-at
17033 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17034 (replace-match ""))
17035 (if negative (insert " -"))
17036 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17037 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17038 (insert " " (format fh h m))))
17039 (if align (org-table-align))
17040 (message "Time difference inserted")))))
17041
17042 (defun org-make-tdiff-string (y d h m)
17043 (let ((fmt "")
17044 (l nil))
17045 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17046 l (push y l)))
17047 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17048 l (push d l)))
17049 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17050 l (push h l)))
17051 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17052 l (push m l)))
17053 (apply 'format fmt (nreverse l))))
17054
17055 (defun org-time-string-to-time (s &optional buffer pos)
17056 "Convert a timestamp string into internal time."
17057 (condition-case errdata
17058 (apply 'encode-time (org-parse-time-string s))
17059 (error (error "Bad timestamp `%s'%s\nError was: %s"
17060 s (if (not (and buffer pos))
17061 ""
17062 (format " at %d in buffer `%s'" pos buffer))
17063 (cdr errdata)))))
17064
17065 (defun org-time-string-to-seconds (s)
17066 "Convert a timestamp string to a number of seconds."
17067 (org-float-time (org-time-string-to-time s)))
17068
17069 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17070 "Convert a time stamp to an absolute day number.
17071 If there is a specifier for a cyclic time stamp, get the closest
17072 date to DAYNR.
17073 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17074 The variable `date' is bound by the calendar when this is called."
17075 (cond
17076 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17077 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17078 daynr
17079 (+ daynr 1000)))
17080 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17081 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17082 (time-to-days (current-time))) (match-string 0 s)
17083 prefer show-all))
17084 (t (time-to-days
17085 (condition-case errdata
17086 (apply 'encode-time (org-parse-time-string s))
17087 (error (error "Bad timestamp `%s'%s\nError was: %s"
17088 s (if (not (and buffer pos))
17089 ""
17090 (format " at %d in buffer `%s'" pos buffer))
17091 (cdr errdata))))))))
17092
17093 (defun org-days-to-iso-week (days)
17094 "Return the iso week number."
17095 (require 'cal-iso)
17096 (car (calendar-iso-from-absolute days)))
17097
17098 (defun org-small-year-to-year (year)
17099 "Convert 2-digit years into 4-digit years.
17100 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17101 The year 2000 cannot be abbreviated. Any year larger than 99
17102 is returned unchanged."
17103 (if (< year 38)
17104 (setq year (+ 2000 year))
17105 (if (< year 100)
17106 (setq year (+ 1900 year))))
17107 year)
17108
17109 (defun org-time-from-absolute (d)
17110 "Return the time corresponding to date D.
17111 D may be an absolute day number, or a calendar-type list (month day year)."
17112 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17113 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17114
17115 (defun org-calendar-holiday ()
17116 "List of holidays, for Diary display in Org-mode."
17117 (require 'holidays)
17118 (let ((hl (funcall
17119 (if (fboundp 'calendar-check-holidays)
17120 'calendar-check-holidays 'check-calendar-holidays) date)))
17121 (if hl (mapconcat 'identity hl "; "))))
17122
17123 (defun org-diary-sexp-entry (sexp entry date)
17124 "Process a SEXP diary ENTRY for DATE."
17125 (require 'diary-lib)
17126 (let ((result (if calendar-debug-sexp
17127 (let ((stack-trace-on-error t))
17128 (eval (car (read-from-string sexp))))
17129 (condition-case nil
17130 (eval (car (read-from-string sexp)))
17131 (error
17132 (beep)
17133 (message "Bad sexp at line %d in %s: %s"
17134 (org-current-line)
17135 (buffer-file-name) sexp)
17136 (sleep-for 2))))))
17137 (cond ((stringp result) (split-string result "; "))
17138 ((and (consp result)
17139 (not (consp (cdr result)))
17140 (stringp (cdr result))) (cdr result))
17141 ((and (consp result)
17142 (stringp (car result))) result)
17143 (result entry))))
17144
17145 (defun org-diary-to-ical-string (frombuf)
17146 "Get iCalendar entries from diary entries in buffer FROMBUF.
17147 This uses the icalendar.el library."
17148 (let* ((tmpdir (if (featurep 'xemacs)
17149 (temp-directory)
17150 temporary-file-directory))
17151 (tmpfile (make-temp-name
17152 (expand-file-name "orgics" tmpdir)))
17153 buf rtn b e)
17154 (with-current-buffer frombuf
17155 (icalendar-export-region (point-min) (point-max) tmpfile)
17156 (setq buf (find-buffer-visiting tmpfile))
17157 (set-buffer buf)
17158 (goto-char (point-min))
17159 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17160 (setq b (match-beginning 0)))
17161 (goto-char (point-max))
17162 (if (re-search-backward "^END:VEVENT" nil t)
17163 (setq e (match-end 0)))
17164 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17165 (kill-buffer buf)
17166 (delete-file tmpfile)
17167 rtn))
17168
17169 (defun org-closest-date (start current change prefer show-all)
17170 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17171 When PREFER is `past', return a date that is either CURRENT or past.
17172 When PREFER is `future', return a date that is either CURRENT or future.
17173 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17174 ;; Make the proper lists from the dates
17175 (catch 'exit
17176 (let ((a1 '(("h" . hour)
17177 ("d" . day)
17178 ("w" . week)
17179 ("m" . month)
17180 ("y" . year)))
17181 (shour (nth 2 (org-parse-time-string start)))
17182 dn dw sday cday n1 n2 n0
17183 d m y y1 y2 date1 date2 nmonths nm ny m2)
17184
17185 (setq start (org-date-to-gregorian start)
17186 current (org-date-to-gregorian
17187 (if show-all
17188 current
17189 (time-to-days (current-time))))
17190 sday (calendar-absolute-from-gregorian start)
17191 cday (calendar-absolute-from-gregorian current))
17192
17193 (if (<= cday sday) (throw 'exit sday))
17194
17195 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17196 (setq dn (string-to-number (match-string 1 change))
17197 dw (cdr (assoc (match-string 2 change) a1)))
17198 (user-error "Invalid change specifier: %s" change))
17199 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17200 (cond
17201 ((eq dw 'hour)
17202 (let ((missing-hours
17203 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17204 dn)))
17205 (setq n1 (if (zerop missing-hours) cday
17206 (- cday (1+ (floor (/ missing-hours 24)))))
17207 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17208 ((eq dw 'day)
17209 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17210 n2 (+ n1 dn)))
17211 ((eq dw 'year)
17212 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17213 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17214 (setq date1 (list m d y1)
17215 n1 (calendar-absolute-from-gregorian date1)
17216 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17217 n2 (calendar-absolute-from-gregorian date2)))
17218 ((eq dw 'month)
17219 ;; approx number of month between the two dates
17220 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17221 ;; How often does dn fit in there?
17222 (setq d (nth 1 start) m (car start) y (nth 2 start)
17223 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17224 m (+ m nm)
17225 ny (floor (/ m 12))
17226 y (+ y ny)
17227 m (- m (* ny 12)))
17228 (while (> m 12) (setq m (- m 12) y (1+ y)))
17229 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17230 (setq m2 (+ m dn) y2 y)
17231 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17232 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17233 (while (<= n2 cday)
17234 (setq n1 n2 m m2 y y2)
17235 (setq m2 (+ m dn) y2 y)
17236 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17237 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17238 ;; Make sure n1 is the earlier date
17239 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17240 (if show-all
17241 (cond
17242 ((eq prefer 'past) (if (= cday n2) n2 n1))
17243 ((eq prefer 'future) (if (= cday n1) n1 n2))
17244 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17245 (cond
17246 ((eq prefer 'past) (if (= cday n2) n2 n1))
17247 ((eq prefer 'future) (if (= cday n1) n1 n2))
17248 (t (if (= cday n1) n1 n2)))))))
17249
17250 (defun org-date-to-gregorian (date)
17251 "Turn any specification of DATE into a Gregorian date for the calendar."
17252 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17253 ((and (listp date) (= (length date) 3)) date)
17254 ((stringp date)
17255 (setq date (org-parse-time-string date))
17256 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17257 ((listp date)
17258 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17259
17260 (defun org-parse-time-string (s &optional nodefault)
17261 "Parse the standard Org-mode time string.
17262 This should be a lot faster than the normal `parse-time-string'.
17263 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17264 hour and minute fields will be nil if not given."
17265 (cond ((string-match org-ts-regexp0 s)
17266 (list 0
17267 (if (or (match-beginning 8) (not nodefault))
17268 (string-to-number (or (match-string 8 s) "0")))
17269 (if (or (match-beginning 7) (not nodefault))
17270 (string-to-number (or (match-string 7 s) "0")))
17271 (string-to-number (match-string 4 s))
17272 (string-to-number (match-string 3 s))
17273 (string-to-number (match-string 2 s))
17274 nil nil nil))
17275 ((string-match "^<[^>]+>$" s)
17276 (decode-time (seconds-to-time (org-matcher-time s))))
17277 (t (error "Not a standard Org-mode time string: %s" s))))
17278
17279 (defun org-timestamp-up (&optional arg)
17280 "Increase the date item at the cursor by one.
17281 If the cursor is on the year, change the year. If it is on the month,
17282 the day or the time, change that.
17283 With prefix ARG, change by that many units."
17284 (interactive "p")
17285 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17286
17287 (defun org-timestamp-down (&optional arg)
17288 "Decrease the date item at the cursor by one.
17289 If the cursor is on the year, change the year. If it is on the month,
17290 the day or the time, change that.
17291 With prefix ARG, change by that many units."
17292 (interactive "p")
17293 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17294
17295 (defun org-timestamp-up-day (&optional arg)
17296 "Increase the date in the time stamp by one day.
17297 With prefix ARG, change that many days."
17298 (interactive "p")
17299 (if (and (not (org-at-timestamp-p t))
17300 (org-at-heading-p))
17301 (org-todo 'up)
17302 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17303
17304 (defun org-timestamp-down-day (&optional arg)
17305 "Decrease the date in the time stamp by one day.
17306 With prefix ARG, change that many days."
17307 (interactive "p")
17308 (if (and (not (org-at-timestamp-p t))
17309 (org-at-heading-p))
17310 (org-todo 'down)
17311 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17312
17313 (defun org-at-timestamp-p (&optional inactive-ok)
17314 "Determine if the cursor is in or at a timestamp."
17315 (interactive)
17316 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17317 (pos (point))
17318 (ans (or (looking-at tsr)
17319 (save-excursion
17320 (skip-chars-backward "^[<\n\r\t")
17321 (if (> (point) (point-min)) (backward-char 1))
17322 (and (looking-at tsr)
17323 (> (- (match-end 0) pos) -1))))))
17324 (and ans
17325 (boundp 'org-ts-what)
17326 (setq org-ts-what
17327 (cond
17328 ((= pos (match-beginning 0)) 'bracket)
17329 ;; Point is considered to be "on the bracket" whether
17330 ;; it's really on it or right after it.
17331 ((= pos (1- (match-end 0))) 'bracket)
17332 ((= pos (match-end 0)) 'after)
17333 ((org-pos-in-match-range pos 2) 'year)
17334 ((org-pos-in-match-range pos 3) 'month)
17335 ((org-pos-in-match-range pos 7) 'hour)
17336 ((org-pos-in-match-range pos 8) 'minute)
17337 ((or (org-pos-in-match-range pos 4)
17338 (org-pos-in-match-range pos 5)) 'day)
17339 ((and (> pos (or (match-end 8) (match-end 5)))
17340 (< pos (match-end 0)))
17341 (- pos (or (match-end 8) (match-end 5))))
17342 (t 'day))))
17343 ans))
17344
17345 (defun org-toggle-timestamp-type ()
17346 "Toggle the type (<active> or [inactive]) of a time stamp."
17347 (interactive)
17348 (when (org-at-timestamp-p t)
17349 (let ((beg (match-beginning 0)) (end (match-end 0))
17350 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17351 (save-excursion
17352 (goto-char beg)
17353 (while (re-search-forward "[][<>]" end t)
17354 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17355 t t)))
17356 (message "Timestamp is now %sactive"
17357 (if (equal (char-after beg) ?<) "" "in")))))
17358
17359 (defun org-at-clock-log-p nil
17360 "Is the cursor on the clock log line?"
17361 (save-excursion
17362 (move-beginning-of-line 1)
17363 (looking-at "^[ \t]*CLOCK:")))
17364
17365 (defvar org-clock-history) ; defined in org-clock.el
17366 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17367 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17368 "Change the date in the time stamp at point.
17369 The date will be changed by N times WHAT. WHAT can be `day', `month',
17370 `year', `minute', `second'. If WHAT is not given, the cursor position
17371 in the timestamp determines what will be changed.
17372 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17373 (let ((origin (point)) origin-cat
17374 with-hm inactive
17375 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17376 org-ts-what
17377 extra rem
17378 ts time time0 fixnext clrgx)
17379 (if (not (org-at-timestamp-p t))
17380 (user-error "Not at a timestamp"))
17381 (if (and (not what) (eq org-ts-what 'bracket))
17382 (org-toggle-timestamp-type)
17383 ;; Point isn't on brackets. Remember the part of the time-stamp
17384 ;; the point was in. Indeed, size of time-stamps may change,
17385 ;; but point must be kept in the same category nonetheless.
17386 (setq origin-cat org-ts-what)
17387 (if (and (not what) (not (eq org-ts-what 'day))
17388 org-display-custom-times
17389 (get-text-property (point) 'display)
17390 (not (get-text-property (1- (point)) 'display)))
17391 (setq org-ts-what 'day))
17392 (setq org-ts-what (or what org-ts-what)
17393 inactive (= (char-after (match-beginning 0)) ?\[)
17394 ts (match-string 0))
17395 (replace-match "")
17396 (when (string-match
17397 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17398 ts)
17399 (setq extra (match-string 1 ts))
17400 (if suppress-tmp-delay
17401 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17402 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17403 (setq with-hm t))
17404 (setq time0 (org-parse-time-string ts))
17405 (when (and updown
17406 (eq org-ts-what 'minute)
17407 (not current-prefix-arg))
17408 ;; This looks like s-up and s-down. Change by one rounding step.
17409 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17410 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17411 (setcar (cdr time0) (+ (nth 1 time0)
17412 (if (> n 0) (- rem) (- dm rem))))))
17413 (setq time
17414 (encode-time (or (car time0) 0)
17415 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17416 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17417 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17418 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17419 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17420 (nthcdr 6 time0)))
17421 (when (and (member org-ts-what '(hour minute))
17422 extra
17423 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17424 (setq extra (org-modify-ts-extra
17425 extra
17426 (if (eq org-ts-what 'hour) 2 5)
17427 n dm)))
17428 (when (integerp org-ts-what)
17429 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17430 (if (eq what 'calendar)
17431 (let ((cal-date (org-get-date-from-calendar)))
17432 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17433 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17434 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17435 (setcar time0 (or (car time0) 0))
17436 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17437 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17438 (setq time (apply 'encode-time time0))))
17439 ;; Insert the new time-stamp, and ensure point stays in the same
17440 ;; category as before (i.e. not after the last position in that
17441 ;; category).
17442 (let ((pos (point)))
17443 ;; Stay before inserted string. `save-excursion' is of no use.
17444 (setq org-last-changed-timestamp
17445 (org-insert-time-stamp time with-hm inactive nil nil extra))
17446 (goto-char pos))
17447 (save-match-data
17448 (looking-at org-ts-regexp3)
17449 (goto-char (cond
17450 ;; `day' category ends before `hour' if any, or at
17451 ;; the end of the day name.
17452 ((eq origin-cat 'day)
17453 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17454 ((eq origin-cat 'hour) (min (match-end 7) origin))
17455 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17456 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17457 ;; `year' and `month' have both fixed size: point
17458 ;; couldn't have moved into another part.
17459 (t origin))))
17460 ;; Update clock if on a CLOCK line.
17461 (org-clock-update-time-maybe)
17462 ;; Maybe adjust the closest clock in `org-clock-history'
17463 (when org-clock-adjust-closest
17464 (if (not (and (org-at-clock-log-p)
17465 (< 1 (length (delq nil (mapcar 'marker-position
17466 org-clock-history))))))
17467 (message "No clock to adjust")
17468 (cond ((save-excursion ; fix previous clock?
17469 (re-search-backward org-ts-regexp0 nil t)
17470 (org-looking-back (concat org-clock-string " \\[")))
17471 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17472 ((save-excursion ; fix next clock?
17473 (re-search-backward org-ts-regexp0 nil t)
17474 (looking-at (concat org-ts-regexp0 "\\] =>")))
17475 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17476 (save-window-excursion
17477 ;; Find closest clock to point, adjust the previous/next one in history
17478 (let* ((p (save-excursion (org-back-to-heading t)))
17479 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17480 (clfixnth
17481 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17482 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17483 (if (not clfixpos)
17484 (message "No clock to adjust")
17485 (save-excursion
17486 (org-goto-marker-or-bmk clfixpos)
17487 (org-show-subtree)
17488 (when (re-search-forward clrgx nil t)
17489 (goto-char (match-beginning 1))
17490 (let (org-clock-adjust-closest)
17491 (org-timestamp-change n org-ts-what updown))
17492 (message "Clock adjusted in %s for heading: %s"
17493 (file-name-nondirectory (buffer-file-name))
17494 (org-get-heading t t)))))))))
17495 ;; Try to recenter the calendar window, if any.
17496 (if (and org-calendar-follow-timestamp-change
17497 (get-buffer-window "*Calendar*" t)
17498 (memq org-ts-what '(day month year)))
17499 (org-recenter-calendar (time-to-days time))))))
17500
17501 (defun org-modify-ts-extra (s pos n dm)
17502 "Change the different parts of the lead-time and repeat fields in timestamp."
17503 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17504 ng h m new rem)
17505 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17506 (cond
17507 ((or (org-pos-in-match-range pos 2)
17508 (org-pos-in-match-range pos 3))
17509 (setq m (string-to-number (match-string 3 s))
17510 h (string-to-number (match-string 2 s)))
17511 (if (org-pos-in-match-range pos 2)
17512 (setq h (+ h n))
17513 (setq n (* dm (org-no-warnings (signum n))))
17514 (when (not (= 0 (setq rem (% m dm))))
17515 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17516 (setq m (+ m n)))
17517 (if (< m 0) (setq m (+ m 60) h (1- h)))
17518 (if (> m 59) (setq m (- m 60) h (1+ h)))
17519 (setq h (min 24 (max 0 h)))
17520 (setq ng 1 new (format "-%02d:%02d" h m)))
17521 ((org-pos-in-match-range pos 6)
17522 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17523 ((org-pos-in-match-range pos 5)
17524 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17525
17526 ((org-pos-in-match-range pos 9)
17527 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17528 ((org-pos-in-match-range pos 8)
17529 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17530
17531 (when ng
17532 (setq s (concat
17533 (substring s 0 (match-beginning ng))
17534 new
17535 (substring s (match-end ng))))))
17536 s))
17537
17538 (defun org-recenter-calendar (date)
17539 "If the calendar is visible, recenter it to DATE."
17540 (let ((cwin (get-buffer-window "*Calendar*" t)))
17541 (when cwin
17542 (let ((calendar-move-hook nil))
17543 (with-selected-window cwin
17544 (calendar-goto-date (if (listp date) date
17545 (calendar-gregorian-from-absolute date))))))))
17546
17547 (defun org-goto-calendar (&optional arg)
17548 "Go to the Emacs calendar at the current date.
17549 If there is a time stamp in the current line, go to that date.
17550 A prefix ARG can be used to force the current date."
17551 (interactive "P")
17552 (let ((tsr org-ts-regexp) diff
17553 (calendar-move-hook nil)
17554 (calendar-view-holidays-initially-flag nil)
17555 (calendar-view-diary-initially-flag nil))
17556 (if (or (org-at-timestamp-p)
17557 (save-excursion
17558 (beginning-of-line 1)
17559 (looking-at (concat ".*" tsr))))
17560 (let ((d1 (time-to-days (current-time)))
17561 (d2 (time-to-days
17562 (org-time-string-to-time (match-string 1)))))
17563 (setq diff (- d2 d1))))
17564 (calendar)
17565 (calendar-goto-today)
17566 (if (and diff (not arg)) (calendar-forward-day diff))))
17567
17568 (defun org-get-date-from-calendar ()
17569 "Return a list (month day year) of date at point in calendar."
17570 (with-current-buffer "*Calendar*"
17571 (save-match-data
17572 (calendar-cursor-to-date))))
17573
17574 (defun org-date-from-calendar ()
17575 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17576 If there is already a time stamp at the cursor position, update it."
17577 (interactive)
17578 (if (org-at-timestamp-p t)
17579 (org-timestamp-change 0 'calendar)
17580 (let ((cal-date (org-get-date-from-calendar)))
17581 (org-insert-time-stamp
17582 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17583
17584 (defcustom org-effort-durations
17585 `(("h" . 60)
17586 ("d" . ,(* 60 8))
17587 ("w" . ,(* 60 8 5))
17588 ("m" . ,(* 60 8 5 4))
17589 ("y" . ,(* 60 8 5 40)))
17590 "Conversion factor to minutes for an effort modifier.
17591
17592 Each entry has the form (MODIFIER . MINUTES).
17593
17594 In an effort string, a number followed by MODIFIER is multiplied
17595 by the specified number of MINUTES to obtain an effort in
17596 minutes.
17597
17598 For example, if the value of this variable is ((\"hours\" . 60)), then an
17599 effort string \"2hours\" is equivalent to 120 minutes."
17600 :group 'org-agenda
17601 :version "24.1"
17602 :type '(alist :key-type (string :tag "Modifier")
17603 :value-type (number :tag "Minutes")))
17604
17605 (defun org-minutes-to-clocksum-string (m)
17606 "Format number of minutes as a clocksum string.
17607 The format is determined by `org-time-clocksum-format',
17608 `org-time-clocksum-use-fractional' and
17609 `org-time-clocksum-fractional-format' and
17610 `org-time-clocksum-use-effort-durations'."
17611 (let ((clocksum "")
17612 (m (round m)) ; Don't allow fractions of minutes
17613 h d w mo y fmt n)
17614 (setq h (if org-time-clocksum-use-effort-durations
17615 (cdr (assoc "h" org-effort-durations)) 60)
17616 d (if org-time-clocksum-use-effort-durations
17617 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17618 w (if org-time-clocksum-use-effort-durations
17619 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17620 mo (if org-time-clocksum-use-effort-durations
17621 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17622 y (if org-time-clocksum-use-effort-durations
17623 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17624 ;; fractional format
17625 (if org-time-clocksum-use-fractional
17626 (cond
17627 ;; single format string
17628 ((stringp org-time-clocksum-fractional-format)
17629 (format org-time-clocksum-fractional-format (/ m (float h))))
17630 ;; choice of fractional formats for different time units
17631 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17632 (> (/ (truncate m) (* y d h)) 0))
17633 (format fmt (/ m (* y d (float h)))))
17634 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17635 (> (/ (truncate m) (* mo d h)) 0))
17636 (format fmt (/ m (* mo d (float h)))))
17637 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17638 (> (/ (truncate m) (* w d h)) 0))
17639 (format fmt (/ m (* w d (float h)))))
17640 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17641 (> (/ (truncate m) (* d h)) 0))
17642 (format fmt (/ m (* d (float h)))))
17643 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17644 (> (/ (truncate m) h) 0))
17645 (format fmt (/ m (float h))))
17646 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17647 (format fmt m))
17648 ;; fall back to smallest time unit with a format
17649 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17650 (format fmt (/ m (float h))))
17651 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17652 (format fmt (/ m (* d (float h)))))
17653 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17654 (format fmt (/ m (* w d (float h)))))
17655 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17656 (format fmt (/ m (* mo d (float h)))))
17657 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17658 (format fmt (/ m (* y d (float h))))))
17659 ;; standard (non-fractional) format, with single format string
17660 (if (stringp org-time-clocksum-format)
17661 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17662 ;; separate formats components
17663 (and (setq fmt (plist-get org-time-clocksum-format :years))
17664 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17665 (plist-get org-time-clocksum-format :require-years))
17666 (setq clocksum (concat clocksum (format fmt n))
17667 m (- m (* n y d h))))
17668 (and (setq fmt (plist-get org-time-clocksum-format :months))
17669 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17670 (plist-get org-time-clocksum-format :require-months))
17671 (setq clocksum (concat clocksum (format fmt n))
17672 m (- m (* n mo d h))))
17673 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17674 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17675 (plist-get org-time-clocksum-format :require-weeks))
17676 (setq clocksum (concat clocksum (format fmt n))
17677 m (- m (* n w d h))))
17678 (and (setq fmt (plist-get org-time-clocksum-format :days))
17679 (or (> (setq n (/ (truncate m) (* d h))) 0)
17680 (plist-get org-time-clocksum-format :require-days))
17681 (setq clocksum (concat clocksum (format fmt n))
17682 m (- m (* n d h))))
17683 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17684 (or (> (setq n (/ (truncate m) h)) 0)
17685 (plist-get org-time-clocksum-format :require-hours))
17686 (setq clocksum (concat clocksum (format fmt n))
17687 m (- m (* n h))))
17688 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17689 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17690 (setq clocksum (concat clocksum (format fmt m))))
17691 ;; return formatted time duration
17692 clocksum))))
17693
17694 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17695 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17696 "Org mode version 8.0")
17697
17698 (defun org-hours-to-clocksum-string (n)
17699 (org-minutes-to-clocksum-string (* n 60)))
17700
17701 (defun org-hh:mm-string-to-minutes (s)
17702 "Convert a string H:MM to a number of minutes.
17703 If the string is just a number, interpret it as minutes.
17704 In fact, the first hh:mm or number in the string will be taken,
17705 there can be extra stuff in the string.
17706 If no number is found, the return value is 0."
17707 (cond
17708 ((integerp s) s)
17709 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17710 (+ (* (string-to-number (match-string 1 s)) 60)
17711 (string-to-number (match-string 2 s))))
17712 ((string-match "\\([0-9]+\\)" s)
17713 (string-to-number (match-string 1 s)))
17714 (t 0)))
17715
17716 (defcustom org-image-actual-width t
17717 "Should we use the actual width of images when inlining them?
17718
17719 When set to `t', always use the image width.
17720
17721 When set to a number, use imagemagick (when available) to set
17722 the image's width to this value.
17723
17724 When set to a number in a list, try to get the width from any
17725 #+ATTR.* keyword if it matches a width specification like
17726
17727 #+ATTR_HTML: :width 300px
17728
17729 and fall back on that number if none is found.
17730
17731 When set to nil, try to get the width from an #+ATTR.* keyword
17732 and fall back on the original width if none is found.
17733
17734 This requires Emacs >= 24.1, build with imagemagick support."
17735 :group 'org-appearance
17736 :version "24.4"
17737 :package-version '(Org . "8.0")
17738 :type '(choice
17739 (const :tag "Use the image width" t)
17740 (integer :tag "Use a number of pixels")
17741 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17742 (const :tag "Use #+ATTR* or don't resize" nil)))
17743
17744 (defcustom org-agenda-inhibit-startup nil
17745 "Inhibit startup when preparing agenda buffers.
17746 When this variable is `t' (the default), the initialization of
17747 the Org agenda buffers is inhibited: e.g. the visibility state
17748 is not set, the tables are not re-aligned, etc."
17749 :type 'boolean
17750 :version "24.3"
17751 :group 'org-agenda)
17752
17753 (defcustom org-agenda-ignore-drawer-properties nil
17754 "Avoid updating text properties when building the agenda.
17755 Properties are used to prepare buffers for effort estimates, appointments,
17756 and subtree-local categories.
17757 If you don't use these in the agenda, you can add them to this list and
17758 agenda building will be a bit faster.
17759 The value is a list, with zero or more of the symbols `effort', `appt',
17760 or `category'."
17761 :type '(set :greedy t
17762 (const effort)
17763 (const appt)
17764 (const category))
17765 :version "24.3"
17766 :group 'org-agenda)
17767
17768 (defun org-duration-string-to-minutes (s &optional output-to-string)
17769 "Convert a duration string S to minutes.
17770
17771 A bare number is interpreted as minutes, modifiers can be set by
17772 customizing `org-effort-durations' (which see).
17773
17774 Entries containing a colon are interpreted as H:MM by
17775 `org-hh:mm-string-to-minutes'."
17776 (let ((result 0)
17777 (re (concat "\\([0-9.]+\\) *\\("
17778 (regexp-opt (mapcar 'car org-effort-durations))
17779 "\\)")))
17780 (while (string-match re s)
17781 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17782 (string-to-number (match-string 1 s))))
17783 (setq s (replace-match "" nil t s)))
17784 (setq result (floor result))
17785 (incf result (org-hh:mm-string-to-minutes s))
17786 (if output-to-string (number-to-string result) result)))
17787
17788 ;;;; Files
17789
17790 (defun org-save-all-org-buffers ()
17791 "Save all Org-mode buffers without user confirmation."
17792 (interactive)
17793 (message "Saving all Org-mode buffers...")
17794 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17795 (when (featurep 'org-id) (org-id-locations-save))
17796 (message "Saving all Org-mode buffers... done"))
17797
17798 (defun org-revert-all-org-buffers ()
17799 "Revert all Org-mode buffers.
17800 Prompt for confirmation when there are unsaved changes.
17801 Be sure you know what you are doing before letting this function
17802 overwrite your changes.
17803
17804 This function is useful in a setup where one tracks org files
17805 with a version control system, to revert on one machine after pulling
17806 changes from another. I believe the procedure must be like this:
17807
17808 1. M-x org-save-all-org-buffers
17809 2. Pull changes from the other machine, resolve conflicts
17810 3. M-x org-revert-all-org-buffers"
17811 (interactive)
17812 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17813 (user-error "Abort"))
17814 (save-excursion
17815 (save-window-excursion
17816 (mapc
17817 (lambda (b)
17818 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17819 (with-current-buffer b buffer-file-name))
17820 (org-pop-to-buffer-same-window b)
17821 (revert-buffer t 'no-confirm)))
17822 (buffer-list))
17823 (when (and (featurep 'org-id) org-id-track-globally)
17824 (org-id-locations-load)))))
17825
17826 ;;;; Agenda files
17827
17828 ;;;###autoload
17829 (defun org-switchb (&optional arg)
17830 "Switch between Org buffers.
17831 With one prefix argument, restrict available buffers to files.
17832 With two prefix arguments, restrict available buffers to agenda files.
17833
17834 Defaults to `iswitchb' for buffer name completion.
17835 Set `org-completion-use-ido' to make it use ido instead."
17836 (interactive "P")
17837 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17838 ((equal arg '(16)) (org-buffer-list 'agenda))
17839 (t (org-buffer-list))))
17840 (org-completion-use-iswitchb org-completion-use-iswitchb)
17841 (org-completion-use-ido org-completion-use-ido))
17842 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17843 (setq org-completion-use-iswitchb t))
17844 (org-pop-to-buffer-same-window
17845 (org-icompleting-read "Org buffer: "
17846 (mapcar 'list (mapcar 'buffer-name blist))
17847 nil t))))
17848
17849 ;;; Define some older names previously used for this functionality
17850 ;;;###autoload
17851 (defalias 'org-ido-switchb 'org-switchb)
17852 ;;;###autoload
17853 (defalias 'org-iswitchb 'org-switchb)
17854
17855 (defun org-buffer-list (&optional predicate exclude-tmp)
17856 "Return a list of Org buffers.
17857 PREDICATE can be `export', `files' or `agenda'.
17858
17859 export restrict the list to Export buffers.
17860 files restrict the list to buffers visiting Org files.
17861 agenda restrict the list to buffers visiting agenda files.
17862
17863 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17864 (let* ((bfn nil)
17865 (agenda-files (and (eq predicate 'agenda)
17866 (mapcar 'file-truename (org-agenda-files t))))
17867 (filter
17868 (cond
17869 ((eq predicate 'files)
17870 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17871 ((eq predicate 'export)
17872 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17873 ((eq predicate 'agenda)
17874 (lambda (b)
17875 (with-current-buffer b
17876 (and (derived-mode-p 'org-mode)
17877 (setq bfn (buffer-file-name b))
17878 (member (file-truename bfn) agenda-files)))))
17879 (t (lambda (b) (with-current-buffer b
17880 (or (derived-mode-p 'org-mode)
17881 (string-match "\*Org .*Export"
17882 (buffer-name b)))))))))
17883 (delq nil
17884 (mapcar
17885 (lambda(b)
17886 (if (and (funcall filter b)
17887 (or (not exclude-tmp)
17888 (not (string-match "tmp" (buffer-name b)))))
17889 b
17890 nil))
17891 (buffer-list)))))
17892
17893 (defun org-agenda-files (&optional unrestricted archives)
17894 "Get the list of agenda files.
17895 Optional UNRESTRICTED means return the full list even if a restriction
17896 is currently in place.
17897 When ARCHIVES is t, include all archive files that are really being
17898 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17899 `org-agenda-archives-mode' is t."
17900 (let ((files
17901 (cond
17902 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17903 ((stringp org-agenda-files) (org-read-agenda-file-list))
17904 ((listp org-agenda-files) org-agenda-files)
17905 (t (error "Invalid value of `org-agenda-files'")))))
17906 (setq files (apply 'append
17907 (mapcar (lambda (f)
17908 (if (file-directory-p f)
17909 (directory-files
17910 f t org-agenda-file-regexp)
17911 (list f)))
17912 files)))
17913 (when org-agenda-skip-unavailable-files
17914 (setq files (delq nil
17915 (mapcar (function
17916 (lambda (file)
17917 (and (file-readable-p file) file)))
17918 files))))
17919 (when (or (eq archives t)
17920 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17921 (setq files (org-add-archive-files files)))
17922 files))
17923
17924 (defun org-agenda-file-p (&optional file)
17925 "Return non-nil, if FILE is an agenda file.
17926 If FILE is omitted, use the file associated with the current
17927 buffer."
17928 (member (or file (buffer-file-name))
17929 (org-agenda-files t)))
17930
17931 (defun org-edit-agenda-file-list ()
17932 "Edit the list of agenda files.
17933 Depending on setup, this either uses customize to edit the variable
17934 `org-agenda-files', or it visits the file that is holding the list. In the
17935 latter case, the buffer is set up in a way that saving it automatically kills
17936 the buffer and restores the previous window configuration."
17937 (interactive)
17938 (if (stringp org-agenda-files)
17939 (let ((cw (current-window-configuration)))
17940 (find-file org-agenda-files)
17941 (org-set-local 'org-window-configuration cw)
17942 (org-add-hook 'after-save-hook
17943 (lambda ()
17944 (set-window-configuration
17945 (prog1 org-window-configuration
17946 (kill-buffer (current-buffer))))
17947 (org-install-agenda-files-menu)
17948 (message "New agenda file list installed"))
17949 nil 'local)
17950 (message "%s" (substitute-command-keys
17951 "Edit list and finish with \\[save-buffer]")))
17952 (customize-variable 'org-agenda-files)))
17953
17954 (defun org-store-new-agenda-file-list (list)
17955 "Set new value for the agenda file list and save it correctly."
17956 (if (stringp org-agenda-files)
17957 (let ((fe (org-read-agenda-file-list t)) b u)
17958 (while (setq b (find-buffer-visiting org-agenda-files))
17959 (kill-buffer b))
17960 (with-temp-file org-agenda-files
17961 (insert
17962 (mapconcat
17963 (lambda (f) ;; Keep un-expanded entries.
17964 (if (setq u (assoc f fe))
17965 (cdr u)
17966 f))
17967 list "\n")
17968 "\n")))
17969 (let ((org-mode-hook nil) (org-inhibit-startup t)
17970 (org-insert-mode-line-in-empty-file nil))
17971 (setq org-agenda-files list)
17972 (customize-save-variable 'org-agenda-files org-agenda-files))))
17973
17974 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17975 "Read the list of agenda files from a file.
17976 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17977 filenames, used by `org-store-new-agenda-file-list' to write back
17978 un-expanded file names."
17979 (when (file-directory-p org-agenda-files)
17980 (error "`org-agenda-files' cannot be a single directory"))
17981 (when (stringp org-agenda-files)
17982 (with-temp-buffer
17983 (insert-file-contents org-agenda-files)
17984 (mapcar
17985 (lambda (f)
17986 (let ((e (expand-file-name (substitute-in-file-name f)
17987 org-directory)))
17988 (if pair-with-expansion
17989 (cons e f)
17990 e)))
17991 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17992
17993 ;;;###autoload
17994 (defun org-cycle-agenda-files ()
17995 "Cycle through the files in `org-agenda-files'.
17996 If the current buffer visits an agenda file, find the next one in the list.
17997 If the current buffer does not, find the first agenda file."
17998 (interactive)
17999 (let* ((fs (org-agenda-files t))
18000 (files (append fs (list (car fs))))
18001 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18002 file)
18003 (unless files (user-error "No agenda files"))
18004 (catch 'exit
18005 (while (setq file (pop files))
18006 (if (equal (file-truename file) tcf)
18007 (when (car files)
18008 (find-file (car files))
18009 (throw 'exit t))))
18010 (find-file (car fs)))
18011 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18012
18013 (defun org-agenda-file-to-front (&optional to-end)
18014 "Move/add the current file to the top of the agenda file list.
18015 If the file is not present in the list, it is added to the front. If it is
18016 present, it is moved there. With optional argument TO-END, add/move to the
18017 end of the list."
18018 (interactive "P")
18019 (let ((org-agenda-skip-unavailable-files nil)
18020 (file-alist (mapcar (lambda (x)
18021 (cons (file-truename x) x))
18022 (org-agenda-files t)))
18023 (ctf (file-truename
18024 (or buffer-file-name
18025 (user-error "Please save the current buffer to a file"))))
18026 x had)
18027 (setq x (assoc ctf file-alist) had x)
18028
18029 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18030 (if to-end
18031 (setq file-alist (append (delq x file-alist) (list x)))
18032 (setq file-alist (cons x (delq x file-alist))))
18033 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18034 (org-install-agenda-files-menu)
18035 (message "File %s to %s of agenda file list"
18036 (if had "moved" "added") (if to-end "end" "front"))))
18037
18038 (defun org-remove-file (&optional file)
18039 "Remove current file from the list of files in variable `org-agenda-files'.
18040 These are the files which are being checked for agenda entries.
18041 Optional argument FILE means use this file instead of the current."
18042 (interactive)
18043 (let* ((org-agenda-skip-unavailable-files nil)
18044 (file (or file buffer-file-name
18045 (user-error "Current buffer does not visit a file")))
18046 (true-file (file-truename file))
18047 (afile (abbreviate-file-name file))
18048 (files (delq nil (mapcar
18049 (lambda (x)
18050 (if (equal true-file
18051 (file-truename x))
18052 nil x))
18053 (org-agenda-files t)))))
18054 (if (not (= (length files) (length (org-agenda-files t))))
18055 (progn
18056 (org-store-new-agenda-file-list files)
18057 (org-install-agenda-files-menu)
18058 (message "Removed file: %s" afile))
18059 (message "File was not in list: %s (not removed)" afile))))
18060
18061 (defun org-file-menu-entry (file)
18062 (vector file (list 'find-file file) t))
18063
18064 (defun org-check-agenda-file (file)
18065 "Make sure FILE exists. If not, ask user what to do."
18066 (when (not (file-exists-p file))
18067 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18068 (abbreviate-file-name file))
18069 (let ((r (downcase (read-char-exclusive))))
18070 (cond
18071 ((equal r ?r)
18072 (org-remove-file file)
18073 (throw 'nextfile t))
18074 (t (error "Abort"))))))
18075
18076 (defun org-get-agenda-file-buffer (file)
18077 "Get a buffer visiting FILE. If the buffer needs to be created, add
18078 it to the list of buffers which might be released later."
18079 (let ((buf (org-find-base-buffer-visiting file)))
18080 (if buf
18081 buf ; just return it
18082 ;; Make a new buffer and remember it
18083 (setq buf (find-file-noselect file))
18084 (if buf (push buf org-agenda-new-buffers))
18085 buf)))
18086
18087 (defun org-release-buffers (blist)
18088 "Release all buffers in list, asking the user for confirmation when needed.
18089 When a buffer is unmodified, it is just killed. When modified, it is saved
18090 \(if the user agrees) and then killed."
18091 (let (buf file)
18092 (while (setq buf (pop blist))
18093 (setq file (buffer-file-name buf))
18094 (when (and (buffer-modified-p buf)
18095 file
18096 (y-or-n-p (format "Save file %s? " file)))
18097 (with-current-buffer buf (save-buffer)))
18098 (kill-buffer buf))))
18099
18100 (defun org-agenda-prepare-buffers (files)
18101 "Create buffers for all agenda files, protect archived trees and comments."
18102 (interactive)
18103 (let ((pa '(:org-archived t))
18104 (pc '(:org-comment t))
18105 (pall '(:org-archived t :org-comment t))
18106 (inhibit-read-only t)
18107 (org-inhibit-startup org-agenda-inhibit-startup)
18108 (rea (concat ":" org-archive-tag ":"))
18109 file re pos)
18110 (setq org-tag-alist-for-agenda nil
18111 org-tag-groups-alist-for-agenda nil)
18112 (save-excursion
18113 (save-restriction
18114 (while (setq file (pop files))
18115 (catch 'nextfile
18116 (if (bufferp file)
18117 (set-buffer file)
18118 (org-check-agenda-file file)
18119 (set-buffer (org-get-agenda-file-buffer file)))
18120 (widen)
18121 (org-set-regexps-and-options-for-tags)
18122 (setq pos (point))
18123 (goto-char (point-min))
18124 (let ((case-fold-search t))
18125 (when (search-forward "#+setupfile" nil t)
18126 ;; Don't set all regexps and options systematically as
18127 ;; this is only run for setting agenda tags from setup
18128 ;; file
18129 (org-set-regexps-and-options)))
18130 (or (memq 'category org-agenda-ignore-drawer-properties)
18131 (org-refresh-category-properties))
18132 (or (memq 'effort org-agenda-ignore-drawer-properties)
18133 (org-refresh-properties org-effort-property 'org-effort))
18134 (or (memq 'appt org-agenda-ignore-drawer-properties)
18135 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18136 (setq org-todo-keywords-for-agenda
18137 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18138 (setq org-done-keywords-for-agenda
18139 (append org-done-keywords-for-agenda org-done-keywords))
18140 (setq org-todo-keyword-alist-for-agenda
18141 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18142 (setq org-drawers-for-agenda
18143 (append org-drawers-for-agenda org-drawers))
18144 (setq org-tag-alist-for-agenda
18145 (org-uniquify
18146 (append org-tag-alist-for-agenda
18147 org-tag-alist
18148 org-tag-persistent-alist)))
18149 (if org-group-tags
18150 (setq org-tag-groups-alist-for-agenda
18151 (org-uniquify-alist
18152 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18153 (org-with-silent-modifications
18154 (save-excursion
18155 (remove-text-properties (point-min) (point-max) pall)
18156 (when org-agenda-skip-archived-trees
18157 (goto-char (point-min))
18158 (while (re-search-forward rea nil t)
18159 (if (org-at-heading-p t)
18160 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18161 (goto-char (point-min))
18162 (setq re (format org-heading-keyword-regexp-format
18163 org-comment-string))
18164 (while (re-search-forward re nil t)
18165 (add-text-properties
18166 (match-beginning 0) (org-end-of-subtree t) pc))))
18167 (goto-char pos)))))
18168 (setq org-todo-keywords-for-agenda
18169 (org-uniquify org-todo-keywords-for-agenda))
18170 (setq org-todo-keyword-alist-for-agenda
18171 (org-uniquify org-todo-keyword-alist-for-agenda))))
18172
18173 \f
18174 ;;;; CDLaTeX minor mode
18175
18176 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18177 "Keymap for the minor `org-cdlatex-mode'.")
18178
18179 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18180 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18181 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18182 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18183 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18184
18185 (defvar org-cdlatex-texmathp-advice-is-done nil
18186 "Flag remembering if we have applied the advice to texmathp already.")
18187
18188 (define-minor-mode org-cdlatex-mode
18189 "Toggle the minor `org-cdlatex-mode'.
18190 This mode supports entering LaTeX environment and math in LaTeX fragments
18191 in Org-mode.
18192 \\{org-cdlatex-mode-map}"
18193 nil " OCDL" nil
18194 (when org-cdlatex-mode
18195 (require 'cdlatex)
18196 (run-hooks 'cdlatex-mode-hook)
18197 (cdlatex-compute-tables))
18198 (unless org-cdlatex-texmathp-advice-is-done
18199 (setq org-cdlatex-texmathp-advice-is-done t)
18200 (defadvice texmathp (around org-math-always-on activate)
18201 "Always return t in org-mode buffers.
18202 This is because we want to insert math symbols without dollars even outside
18203 the LaTeX math segments. If Orgmode thinks that point is actually inside
18204 an embedded LaTeX fragment, let texmathp do its job.
18205 \\[org-cdlatex-mode-map]"
18206 (interactive)
18207 (let (p)
18208 (cond
18209 ((not (derived-mode-p 'org-mode)) ad-do-it)
18210 ((eq this-command 'cdlatex-math-symbol)
18211 (setq ad-return-value t
18212 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18213 (t
18214 (let ((p (org-inside-LaTeX-fragment-p)))
18215 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18216 (setq ad-return-value t
18217 texmathp-why '("Org-mode embedded math" . 0))
18218 (if p ad-do-it)))))))))
18219
18220 (defun turn-on-org-cdlatex ()
18221 "Unconditionally turn on `org-cdlatex-mode'."
18222 (org-cdlatex-mode 1))
18223
18224 (defun org-try-cdlatex-tab ()
18225 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18226 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18227 - inside a LaTeX fragment, or
18228 - after the first word in a line, where an abbreviation expansion could
18229 insert a LaTeX environment."
18230 (when org-cdlatex-mode
18231 (cond
18232 ;; Before any word on the line: No expansion possible.
18233 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18234 ;; Just after first word on the line: Expand it. Make sure it
18235 ;; cannot happen on headlines, though.
18236 ((save-excursion
18237 (skip-chars-backward "a-zA-Z0-9*")
18238 (skip-chars-backward " \t")
18239 (and (bolp) (not (org-at-heading-p))))
18240 (cdlatex-tab) t)
18241 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18242
18243 (defun org-cdlatex-underscore-caret (&optional arg)
18244 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18245 Revert to the normal definition outside of these fragments."
18246 (interactive "P")
18247 (if (org-inside-LaTeX-fragment-p)
18248 (call-interactively 'cdlatex-sub-superscript)
18249 (let (org-cdlatex-mode)
18250 (call-interactively (key-binding (vector last-input-event))))))
18251
18252 (defun org-cdlatex-math-modify (&optional arg)
18253 "Execute `cdlatex-math-modify' in LaTeX fragments.
18254 Revert to the normal definition outside of these fragments."
18255 (interactive "P")
18256 (if (org-inside-LaTeX-fragment-p)
18257 (call-interactively 'cdlatex-math-modify)
18258 (let (org-cdlatex-mode)
18259 (call-interactively (key-binding (vector last-input-event))))))
18260
18261
18262 \f
18263 ;;;; LaTeX fragments
18264
18265 (defvar org-latex-regexps
18266 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18267 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18268 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18269 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18270 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18271 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18272 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18273 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18274 "Regular expressions for matching embedded LaTeX.")
18275
18276 (defun org-inside-LaTeX-fragment-p ()
18277 "Test if point is inside a LaTeX fragment.
18278 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18279 sequence appearing also before point.
18280 Even though the matchers for math are configurable, this function assumes
18281 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18282 delimiters are skipped when they have been removed by customization.
18283 The return value is nil, or a cons cell with the delimiter and the
18284 position of this delimiter.
18285
18286 This function does a reasonably good job, but can locally be fooled by
18287 for example currency specifications. For example it will assume being in
18288 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18289 fragments that are properly closed, but during editing, we have to live
18290 with the uncertainty caused by missing closing delimiters. This function
18291 looks only before point, not after."
18292 (catch 'exit
18293 (let ((pos (point))
18294 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18295 (lim (progn
18296 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18297 (point)))
18298 dd-on str (start 0) m re)
18299 (goto-char pos)
18300 (when dodollar
18301 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18302 re (nth 1 (assoc "$" org-latex-regexps)))
18303 (while (string-match re str start)
18304 (cond
18305 ((= (match-end 0) (length str))
18306 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18307 ((= (match-end 0) (- (length str) 5))
18308 (throw 'exit nil))
18309 (t (setq start (match-end 0))))))
18310 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18311 (goto-char pos)
18312 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18313 (and (match-beginning 2) (throw 'exit nil))
18314 ;; count $$
18315 (while (re-search-backward "\\$\\$" lim t)
18316 (setq dd-on (not dd-on)))
18317 (goto-char pos)
18318 (if dd-on (cons "$$" m))))))
18319
18320 (defun org-inside-latex-macro-p ()
18321 "Is point inside a LaTeX macro or its arguments?"
18322 (save-match-data
18323 (org-in-regexp
18324 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18325
18326 (defvar org-latex-fragment-image-overlays nil
18327 "List of overlays carrying the images of latex fragments.")
18328 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18329
18330 (defun org-remove-latex-fragment-image-overlays ()
18331 "Remove all overlays with LaTeX fragment images in current buffer."
18332 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18333 (setq org-latex-fragment-image-overlays nil))
18334
18335 (defun org-preview-latex-fragment (&optional subtree)
18336 "Preview the LaTeX fragment at point, or all locally or globally.
18337 If the cursor is in a LaTeX fragment, create the image and overlay
18338 it over the source code. If there is no fragment at point, display
18339 all fragments in the current text, from one headline to the next. With
18340 prefix SUBTREE, display all fragments in the current subtree. With a
18341 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18342 the cursor is before the first headline,
18343 display all fragments in the buffer.
18344 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18345 (interactive "P")
18346 (unless buffer-file-name
18347 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18348 (when (display-graphic-p)
18349 (org-remove-latex-fragment-image-overlays)
18350 (save-excursion
18351 (save-restriction
18352 (let (beg end at msg)
18353 (cond
18354 ((or (equal subtree '(16))
18355 (not (save-excursion
18356 (re-search-backward org-outline-regexp-bol nil t))))
18357 (setq beg (point-min) end (point-max)
18358 msg "Creating images for buffer...%s"))
18359 ((equal subtree '(4))
18360 (org-back-to-heading)
18361 (setq beg (point) end (org-end-of-subtree t)
18362 msg "Creating images for subtree...%s"))
18363 (t
18364 (if (setq at (org-inside-LaTeX-fragment-p))
18365 (goto-char (max (point-min) (- (cdr at) 2)))
18366 (org-back-to-heading))
18367 (setq beg (point) end (progn (outline-next-heading) (point))
18368 msg (if at "Creating image...%s"
18369 "Creating images for entry...%s"))))
18370 (message msg "")
18371 (narrow-to-region beg end)
18372 (goto-char beg)
18373 (org-format-latex
18374 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18375 (file-name-nondirectory
18376 buffer-file-name)))
18377 default-directory 'overlays msg at 'forbuffer
18378 org-latex-create-formula-image-program)
18379 (message msg "done. Use `C-c C-c' to remove images."))))))
18380
18381 (defun org-format-latex (prefix &optional dir overlays msg at
18382 forbuffer processing-type)
18383 "Replace LaTeX fragments with links to an image, and produce images.
18384 Some of the options can be changed using the variable
18385 `org-format-latex-options'."
18386 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18387 (let* ((prefixnodir (file-name-nondirectory prefix))
18388 (absprefix (expand-file-name prefix dir))
18389 (todir (file-name-directory absprefix))
18390 (opt org-format-latex-options)
18391 (optnew org-format-latex-options)
18392 (matchers (plist-get opt :matchers))
18393 (re-list org-latex-regexps)
18394 (cnt 0) txt hash link beg end re e checkdir
18395 string
18396 m n block-type block linkfile movefile ov)
18397 ;; Check the different regular expressions
18398 (while (setq e (pop re-list))
18399 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18400 block (if block-type "\n\n" ""))
18401 (when (member m matchers)
18402 (goto-char (point-min))
18403 (while (re-search-forward re nil t)
18404 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18405 (or (not overlays)
18406 (not (eq (get-char-property (match-beginning n)
18407 'org-overlay-type)
18408 'org-latex-overlay))))
18409 (cond
18410 ((eq processing-type 'verbatim))
18411 ((eq processing-type 'mathjax)
18412 ;; Prepare for MathJax processing.
18413 (setq string (match-string n))
18414 (when (member m '("$" "$1"))
18415 (save-excursion
18416 (delete-region (match-beginning n) (match-end n))
18417 (goto-char (match-beginning n))
18418 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18419 ((or (eq processing-type 'dvipng)
18420 (eq processing-type 'imagemagick))
18421 ;; Process to an image.
18422 (setq txt (match-string n)
18423 beg (match-beginning n) end (match-end n)
18424 cnt (1+ cnt))
18425 (let ((face (face-at-point))
18426 (fg (plist-get opt :foreground))
18427 (bg (plist-get opt :background))
18428 ;; Ensure full list is printed.
18429 print-length print-level)
18430 (when forbuffer
18431 ;; Get the colors from the face at point.
18432 (goto-char beg)
18433 (when (eq fg 'auto)
18434 (setq fg (face-attribute face :foreground nil 'default)))
18435 (when (eq bg 'auto)
18436 (setq bg (face-attribute face :background nil 'default)))
18437 (setq optnew (copy-sequence opt))
18438 (plist-put optnew :foreground fg)
18439 (plist-put optnew :background bg))
18440 (setq hash (sha1 (prin1-to-string
18441 (list org-format-latex-header
18442 org-latex-default-packages-alist
18443 org-latex-packages-alist
18444 org-format-latex-options
18445 forbuffer txt fg bg)))
18446 linkfile (format "%s_%s.png" prefix hash)
18447 movefile (format "%s_%s.png" absprefix hash)))
18448 (setq link (concat block "[[file:" linkfile "]]" block))
18449 (if msg (message msg cnt))
18450 (goto-char beg)
18451 (unless checkdir ; Ensure the directory exists.
18452 (setq checkdir t)
18453 (or (file-directory-p todir) (make-directory todir t)))
18454 (unless (file-exists-p movefile)
18455 (org-create-formula-image
18456 txt movefile optnew forbuffer processing-type))
18457 (if overlays
18458 (progn
18459 (mapc (lambda (o)
18460 (if (eq (overlay-get o 'org-overlay-type)
18461 'org-latex-overlay)
18462 (delete-overlay o)))
18463 (overlays-in beg end))
18464 (setq ov (make-overlay beg end))
18465 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18466 (if (featurep 'xemacs)
18467 (progn
18468 (overlay-put ov 'invisible t)
18469 (overlay-put
18470 ov 'end-glyph
18471 (make-glyph (vector 'png :file movefile))))
18472 (overlay-put
18473 ov 'display
18474 (list 'image :type 'png :file movefile :ascent 'center)))
18475 (push ov org-latex-fragment-image-overlays)
18476 (goto-char end))
18477 (delete-region beg end)
18478 (insert (org-add-props link
18479 (list 'org-latex-src
18480 (replace-regexp-in-string
18481 "\"" "" txt)
18482 'org-latex-src-embed-type
18483 (if block-type 'paragraph 'character))))))
18484 ((eq processing-type 'mathml)
18485 ;; Process to MathML
18486 (unless (save-match-data (org-format-latex-mathml-available-p))
18487 (user-error "LaTeX to MathML converter not configured"))
18488 (setq txt (match-string n)
18489 beg (match-beginning n) end (match-end n)
18490 cnt (1+ cnt))
18491 (if msg (message msg cnt))
18492 (goto-char beg)
18493 (delete-region beg end)
18494 (insert (org-format-latex-as-mathml
18495 txt block-type prefix dir)))
18496 (t
18497 (error "Unknown conversion type %s for LaTeX fragments"
18498 processing-type)))))))))
18499
18500 (defun org-create-math-formula (latex-frag &optional mathml-file)
18501 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18502 Use `org-latex-to-mathml-convert-command'. If the conversion is
18503 sucessful, return the portion between \"<math...> </math>\"
18504 elements otherwise return nil. When MATHML-FILE is specified,
18505 write the results in to that file. When invoked as an
18506 interactive command, prompt for LATEX-FRAG, with initial value
18507 set to the current active region and echo the results for user
18508 inspection."
18509 (interactive (list (let ((frag (when (org-region-active-p)
18510 (buffer-substring-no-properties
18511 (region-beginning) (region-end)))))
18512 (read-string "LaTeX Fragment: " frag nil frag))))
18513 (unless latex-frag (error "Invalid LaTeX fragment"))
18514 (let* ((tmp-in-file (file-relative-name
18515 (make-temp-name (expand-file-name "ltxmathml-in"))))
18516 (ignore (write-region latex-frag nil tmp-in-file))
18517 (tmp-out-file (file-relative-name
18518 (make-temp-name (expand-file-name "ltxmathml-out"))))
18519 (cmd (format-spec
18520 org-latex-to-mathml-convert-command
18521 `((?j . ,(shell-quote-argument
18522 (expand-file-name org-latex-to-mathml-jar-file)))
18523 (?I . ,(shell-quote-argument tmp-in-file))
18524 (?o . ,(shell-quote-argument tmp-out-file)))))
18525 mathml shell-command-output)
18526 (when (org-called-interactively-p 'any)
18527 (unless (org-format-latex-mathml-available-p)
18528 (user-error "LaTeX to MathML converter not configured")))
18529 (message "Running %s" cmd)
18530 (setq shell-command-output (shell-command-to-string cmd))
18531 (setq mathml
18532 (when (file-readable-p tmp-out-file)
18533 (with-current-buffer (find-file-noselect tmp-out-file t)
18534 (goto-char (point-min))
18535 (when (re-search-forward
18536 (concat
18537 (regexp-quote
18538 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18539 "\\(.\\|\n\\)*"
18540 (regexp-quote "</math>")) nil t)
18541 (prog1 (match-string 0) (kill-buffer))))))
18542 (cond
18543 (mathml
18544 (setq mathml
18545 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18546 (when mathml-file
18547 (write-region mathml nil mathml-file))
18548 (when (org-called-interactively-p 'any)
18549 (message mathml)))
18550 ((message "LaTeX to MathML conversion failed")
18551 (message shell-command-output)))
18552 (delete-file tmp-in-file)
18553 (when (file-exists-p tmp-out-file)
18554 (delete-file tmp-out-file))
18555 mathml))
18556
18557 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18558 prefix &optional dir)
18559 "Use `org-create-math-formula' but check local cache first."
18560 (let* ((absprefix (expand-file-name prefix dir))
18561 (print-length nil) (print-level nil)
18562 (formula-id (concat
18563 "formula-"
18564 (sha1
18565 (prin1-to-string
18566 (list latex-frag
18567 org-latex-to-mathml-convert-command)))))
18568 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18569 (formula-cache-dir (file-name-directory formula-cache)))
18570
18571 (unless (file-directory-p formula-cache-dir)
18572 (make-directory formula-cache-dir t))
18573
18574 (unless (file-exists-p formula-cache)
18575 (org-create-math-formula latex-frag formula-cache))
18576
18577 (if (file-exists-p formula-cache)
18578 ;; Successful conversion. Return the link to MathML file.
18579 (org-add-props
18580 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18581 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18582 'org-latex-src-embed-type (if latex-frag-type
18583 'paragraph 'character)))
18584 ;; Failed conversion. Return the LaTeX fragment verbatim
18585 latex-frag)))
18586
18587 (defun org-create-formula-image (string tofile options buffer &optional type)
18588 "Create an image from LaTeX source using dvipng or convert.
18589 This function calls either `org-create-formula-image-with-dvipng'
18590 or `org-create-formula-image-with-imagemagick' depending on the
18591 value of `org-latex-create-formula-image-program' or on the value
18592 of the optional TYPE variable.
18593
18594 Note: ultimately these two function should be combined as they
18595 share a good deal of logic."
18596 (org-check-external-command
18597 "latex" "needed to convert LaTeX fragments to images")
18598 (funcall
18599 (case (or type org-latex-create-formula-image-program)
18600 ('dvipng
18601 (org-check-external-command
18602 "dvipng" "needed to convert LaTeX fragments to images")
18603 #'org-create-formula-image-with-dvipng)
18604 ('imagemagick
18605 (org-check-external-command
18606 "convert" "you need to install imagemagick")
18607 #'org-create-formula-image-with-imagemagick)
18608 (t (error
18609 "Invalid value of `org-latex-create-formula-image-program'")))
18610 string tofile options buffer))
18611
18612 (declare-function org-export-get-backend "ox" (name))
18613 (declare-function org-export--get-global-options "ox" (&optional backend))
18614 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18615 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18616 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18617 (defun org-create-formula--latex-header ()
18618 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18619 (let ((info (org-combine-plists (org-export--get-global-options
18620 (org-export-get-backend 'latex))
18621 (org-export--get-inbuffer-options
18622 (org-export-get-backend 'latex)))))
18623 (org-latex-guess-babel-language
18624 (org-latex-guess-inputenc
18625 (org-splice-latex-header
18626 org-format-latex-header
18627 org-latex-default-packages-alist
18628 org-latex-packages-alist t
18629 (plist-get info :latex-header)))
18630 info)))
18631
18632 ;; This function borrows from Ganesh Swami's latex2png.el
18633 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18634 "This calls dvipng."
18635 (require 'ox-latex)
18636 (let* ((tmpdir (if (featurep 'xemacs)
18637 (temp-directory)
18638 temporary-file-directory))
18639 (texfilebase (make-temp-name
18640 (expand-file-name "orgtex" tmpdir)))
18641 (texfile (concat texfilebase ".tex"))
18642 (dvifile (concat texfilebase ".dvi"))
18643 (pngfile (concat texfilebase ".png"))
18644 (fnh (if (featurep 'xemacs)
18645 (font-height (face-font 'default))
18646 (face-attribute 'default :height nil)))
18647 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18648 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18649 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18650 "Black"))
18651 (bg (or (plist-get options (if buffer :background :html-background))
18652 "Transparent")))
18653 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18654 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18655 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18656 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18657 (let ((latex-header (org-create-formula--latex-header)))
18658 (with-temp-file texfile
18659 (insert latex-header)
18660 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18661 (let ((dir default-directory))
18662 (condition-case nil
18663 (progn
18664 (cd tmpdir)
18665 (call-process "latex" nil nil nil texfile))
18666 (error nil))
18667 (cd dir))
18668 (if (not (file-exists-p dvifile))
18669 (progn (message "Failed to create dvi file from %s" texfile) nil)
18670 (condition-case nil
18671 (if (featurep 'xemacs)
18672 (call-process "dvipng" nil nil nil
18673 "-fg" fg "-bg" bg
18674 "-T" "tight"
18675 "-o" pngfile
18676 dvifile)
18677 (call-process "dvipng" nil nil nil
18678 "-fg" fg "-bg" bg
18679 "-D" dpi
18680 ;;"-x" scale "-y" scale
18681 "-T" "tight"
18682 "-o" pngfile
18683 dvifile))
18684 (error nil))
18685 (if (not (file-exists-p pngfile))
18686 (if org-format-latex-signal-error
18687 (error "Failed to create png file from %s" texfile)
18688 (message "Failed to create png file from %s" texfile)
18689 nil)
18690 ;; Use the requested file name and clean up
18691 (copy-file pngfile tofile 'replace)
18692 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18693 (if (file-exists-p (concat texfilebase e))
18694 (delete-file (concat texfilebase e))))
18695 pngfile))))
18696
18697 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18698 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18699 "This calls convert, which is included into imagemagick."
18700 (require 'ox-latex)
18701 (let* ((tmpdir (if (featurep 'xemacs)
18702 (temp-directory)
18703 temporary-file-directory))
18704 (texfilebase (make-temp-name
18705 (expand-file-name "orgtex" tmpdir)))
18706 (texfile (concat texfilebase ".tex"))
18707 (pdffile (concat texfilebase ".pdf"))
18708 (pngfile (concat texfilebase ".png"))
18709 (fnh (if (featurep 'xemacs)
18710 (font-height (face-font 'default))
18711 (face-attribute 'default :height nil)))
18712 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18713 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18714 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18715 "black"))
18716 (bg (or (plist-get options (if buffer :background :html-background))
18717 "white")))
18718 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18719 (setq fg (org-latex-color-format fg)))
18720 (if (eq bg 'default) (setq bg (org-latex-color :background))
18721 (setq bg (org-latex-color-format
18722 (if (string= bg "Transparent") "white" bg))))
18723 (let ((latex-header (org-create-formula--latex-header)))
18724 (with-temp-file texfile
18725 (insert latex-header)
18726 (insert "\n\\begin{document}\n"
18727 "\\definecolor{fg}{rgb}{" fg "}\n"
18728 "\\definecolor{bg}{rgb}{" bg "}\n"
18729 "\n\\pagecolor{bg}\n"
18730 "\n{\\color{fg}\n"
18731 string
18732 "\n}\n"
18733 "\n\\end{document}\n")))
18734 (org-latex-compile texfile t)
18735 (if (not (file-exists-p pdffile))
18736 (progn (message "Failed to create pdf file from %s" texfile) nil)
18737 (condition-case nil
18738 (if (featurep 'xemacs)
18739 (call-process "convert" nil nil nil
18740 "-density" "96"
18741 "-trim"
18742 "-antialias"
18743 pdffile
18744 "-quality" "100"
18745 ;; "-sharpen" "0x1.0"
18746 pngfile)
18747 (call-process "convert" nil nil nil
18748 "-density" dpi
18749 "-trim"
18750 "-antialias"
18751 pdffile
18752 "-quality" "100"
18753 ;; "-sharpen" "0x1.0"
18754 pngfile))
18755 (error nil))
18756 (if (not (file-exists-p pngfile))
18757 (if org-format-latex-signal-error
18758 (error "Failed to create png file from %s" texfile)
18759 (message "Failed to create png file from %s" texfile)
18760 nil)
18761 ;; Use the requested file name and clean up
18762 (copy-file pngfile tofile 'replace)
18763 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18764 (if (file-exists-p (concat texfilebase e))
18765 (delete-file (concat texfilebase e))))
18766 pngfile))))
18767
18768 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18769 "Fill a LaTeX header template TPL.
18770 In the template, the following place holders will be recognized:
18771
18772 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18773 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18774 [PACKAGES] \\usepackage statements for PKG
18775 [NO-PACKAGES] do not include PKG
18776 [EXTRA] the string EXTRA
18777 [NO-EXTRA] do not include EXTRA
18778
18779 For backward compatibility, if both the positive and the negative place
18780 holder is missing, the positive one (without the \"NO-\") will be
18781 assumed to be present at the end of the template.
18782 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18783 EXTRA is a string.
18784 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18785 (let (rpl (end ""))
18786 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18787 (setq rpl (if (or (match-end 1) (not def-pkg))
18788 "" (org-latex-packages-to-string def-pkg snippets-p t))
18789 tpl (replace-match rpl t t tpl))
18790 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18791
18792 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18793 (setq rpl (if (or (match-end 1) (not pkg))
18794 "" (org-latex-packages-to-string pkg snippets-p t))
18795 tpl (replace-match rpl t t tpl))
18796 (if pkg (setq end
18797 (concat end "\n"
18798 (org-latex-packages-to-string pkg snippets-p)))))
18799
18800 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18801 (setq rpl (if (or (match-end 1) (not extra))
18802 "" (concat extra "\n"))
18803 tpl (replace-match rpl t t tpl))
18804 (if (and extra (string-match "\\S-" extra))
18805 (setq end (concat end "\n" extra))))
18806
18807 (if (string-match "\\S-" end)
18808 (concat tpl "\n" end)
18809 tpl)))
18810
18811 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18812 "Turn an alist of packages into a string with the \\usepackage macros."
18813 (setq pkg (mapconcat (lambda(p)
18814 (cond
18815 ((stringp p) p)
18816 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18817 (format "%% Package %s omitted" (cadr p)))
18818 ((equal "" (car p))
18819 (format "\\usepackage{%s}" (cadr p)))
18820 (t
18821 (format "\\usepackage[%s]{%s}"
18822 (car p) (cadr p)))))
18823 pkg
18824 "\n"))
18825 (if newline (concat pkg "\n") pkg))
18826
18827 (defun org-dvipng-color (attr)
18828 "Return a RGB color specification for dvipng."
18829 (apply 'format "rgb %s %s %s"
18830 (mapcar 'org-normalize-color
18831 (if (featurep 'xemacs)
18832 (color-rgb-components
18833 (face-property 'default
18834 (cond ((eq attr :foreground) 'foreground)
18835 ((eq attr :background) 'background))))
18836 (color-values (face-attribute 'default attr nil))))))
18837
18838 (defun org-dvipng-color-format (color-name)
18839 "Convert COLOR-NAME to a RGB color value for dvipng."
18840 (apply 'format "rgb %s %s %s"
18841 (mapcar 'org-normalize-color
18842 (color-values color-name))))
18843
18844 (defun org-latex-color (attr)
18845 "Return a RGB color for the LaTeX color package."
18846 (apply 'format "%s,%s,%s"
18847 (mapcar 'org-normalize-color
18848 (if (featurep 'xemacs)
18849 (color-rgb-components
18850 (face-property 'default
18851 (cond ((eq attr :foreground) 'foreground)
18852 ((eq attr :background) 'background))))
18853 (color-values (face-attribute 'default attr nil))))))
18854
18855 (defun org-latex-color-format (color-name)
18856 "Convert COLOR-NAME to a RGB color value."
18857 (apply 'format "%s,%s,%s"
18858 (mapcar 'org-normalize-color
18859 (color-values color-name))))
18860
18861 (defun org-normalize-color (value)
18862 "Return string to be used as color value for an RGB component."
18863 (format "%g" (/ value 65535.0)))
18864
18865
18866 \f
18867 ;; Image display
18868
18869 (defvar org-inline-image-overlays nil)
18870 (make-variable-buffer-local 'org-inline-image-overlays)
18871
18872 (defun org-toggle-inline-images (&optional include-linked)
18873 "Toggle the display of inline images.
18874 INCLUDE-LINKED is passed to `org-display-inline-images'."
18875 (interactive "P")
18876 (if org-inline-image-overlays
18877 (progn
18878 (org-remove-inline-images)
18879 (message "Inline image display turned off"))
18880 (org-display-inline-images include-linked)
18881 (if (and (org-called-interactively-p)
18882 org-inline-image-overlays)
18883 (message "%d images displayed inline"
18884 (length org-inline-image-overlays))
18885 (message "No images to display inline"))))
18886
18887 (defun org-redisplay-inline-images ()
18888 "Refresh the display of inline images."
18889 (interactive)
18890 (if (not org-inline-image-overlays)
18891 (org-toggle-inline-images)
18892 (org-toggle-inline-images)
18893 (org-toggle-inline-images)))
18894
18895 (defun org-display-inline-images (&optional include-linked refresh beg end)
18896 "Display inline images.
18897 Normally only links without a description part are inlined, because this
18898 is how it will work for export. When INCLUDE-LINKED is set, also links
18899 with a description part will be inlined. This can be nice for a quick
18900 look at those images, but it does not reflect what exported files will look
18901 like.
18902 When REFRESH is set, refresh existing images between BEG and END.
18903 This will create new image displays only if necessary.
18904 BEG and END default to the buffer boundaries."
18905 (interactive "P")
18906 (when (display-graphic-p)
18907 (unless refresh
18908 (org-remove-inline-images)
18909 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18910 (save-excursion
18911 (save-restriction
18912 (widen)
18913 (setq beg (or beg (point-min)) end (or end (point-max)))
18914 (goto-char beg)
18915 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18916 (substring (org-image-file-name-regexp) 0 -2)
18917 "\\)\\]" (if include-linked "" "\\]")))
18918 (case-fold-search t)
18919 old file ov img type attrwidth width)
18920 (while (re-search-forward re end t)
18921 (setq old (get-char-property-and-overlay (match-beginning 1)
18922 'org-image-overlay)
18923 file (expand-file-name
18924 (concat (or (match-string 3) "") (match-string 4))))
18925 (when (image-type-available-p 'imagemagick)
18926 (setq attrwidth (if (or (listp org-image-actual-width)
18927 (null org-image-actual-width))
18928 (save-excursion
18929 (save-match-data
18930 (when (re-search-backward
18931 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18932 (save-excursion
18933 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18934 (string-to-number (match-string 1))))))
18935 width (cond ((eq org-image-actual-width t) nil)
18936 ((null org-image-actual-width) attrwidth)
18937 ((numberp org-image-actual-width)
18938 org-image-actual-width)
18939 ((listp org-image-actual-width)
18940 (or attrwidth (car org-image-actual-width))))
18941 type (if width 'imagemagick)))
18942 (when (file-exists-p file)
18943 (if (and (car-safe old) refresh)
18944 (image-refresh (overlay-get (cdr old) 'display))
18945 (setq img (save-match-data (create-image file type nil :width width)))
18946 (when img
18947 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18948 (overlay-put ov 'display img)
18949 (overlay-put ov 'face 'default)
18950 (overlay-put ov 'org-image-overlay t)
18951 (overlay-put ov 'modification-hooks
18952 (list 'org-display-inline-remove-overlay))
18953 (push ov org-inline-image-overlays))))))))))
18954
18955 (define-obsolete-function-alias
18956 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18957
18958 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18959 "Remove inline-display overlay if a corresponding region is modified."
18960 (let ((inhibit-modification-hooks t))
18961 (when (and ov after)
18962 (delete ov org-inline-image-overlays)
18963 (delete-overlay ov))))
18964
18965 (defun org-remove-inline-images ()
18966 "Remove inline display of images."
18967 (interactive)
18968 (mapc 'delete-overlay org-inline-image-overlays)
18969 (setq org-inline-image-overlays nil))
18970
18971 ;;;; Key bindings
18972
18973 ;; Outline functions from `outline-mode-prefix-map'
18974 ;; that can be remapped in Org:
18975 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18976 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18977 (define-key org-mode-map [remap outline-forward-same-level]
18978 'org-forward-heading-same-level)
18979 (define-key org-mode-map [remap outline-backward-same-level]
18980 'org-backward-heading-same-level)
18981 (define-key org-mode-map [remap show-branches]
18982 'org-kill-note-or-show-branches)
18983 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18984 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18985 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18986
18987 ;; Outline functions from `outline-mode-prefix-map' that can not
18988 ;; be remapped in Org:
18989 ;;
18990 ;; - the column "key binding" shows whether the Outline function is still
18991 ;; available in Org mode on the same key that it has been bound to in
18992 ;; Outline mode:
18993 ;; - "overridden": key used for a different functionality in Org mode
18994 ;; - else: key still bound to the same Outline function in Org mode
18995 ;;
18996 ;; | Outline function | key binding | Org replacement |
18997 ;; |------------------------------------+-------------+-----------------------|
18998 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18999 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19000 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19001 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19002 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19003 ;; | `show-entry' | overridden | no replacement |
19004 ;; | `show-children' | `C-c C-i' | visibility cycling |
19005 ;; | `show-branches' | `C-c C-k' | still same function |
19006 ;; | `show-subtree' | overridden | visibility cycling |
19007 ;; | `show-all' | overridden | no replacement |
19008 ;; | `hide-subtree' | overridden | visibility cycling |
19009 ;; | `hide-body' | overridden | no replacement |
19010 ;; | `hide-entry' | overridden | visibility cycling |
19011 ;; | `hide-leaves' | overridden | no replacement |
19012 ;; | `hide-sublevels' | overridden | no replacement |
19013 ;; | `hide-other' | overridden | no replacement |
19014
19015 ;; Make `C-c C-x' a prefix key
19016 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19017
19018 ;; TAB key with modifiers
19019 (org-defkey org-mode-map "\C-i" 'org-cycle)
19020 (org-defkey org-mode-map [(tab)] 'org-cycle)
19021 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19022 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19023 ;; The following line is necessary under Suse GNU/Linux
19024 (unless (featurep 'xemacs)
19025 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19026 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19027 (define-key org-mode-map [backtab] 'org-shifttab)
19028
19029 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19030 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19031 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19032
19033 ;; Cursor keys with modifiers
19034 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19035 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19036 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19037 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19038
19039 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19040 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19041 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19042 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19043
19044 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19045 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19046 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19047 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19048
19049 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19050 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19051 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19052 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19053
19054 ;; Babel keys
19055 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19056 (mapc (lambda (pair)
19057 (define-key org-babel-map (car pair) (cdr pair)))
19058 org-babel-key-bindings)
19059
19060 ;;; Extra keys for tty access.
19061 ;; We only set them when really needed because otherwise the
19062 ;; menus don't show the simple keys
19063
19064 (when (or org-use-extra-keys
19065 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19066 (not window-system))
19067 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19068 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19069 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19070 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19071 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19072 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19073 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19074 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19075 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19076 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19077 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19078 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19079 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19080 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19081 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19082 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19083 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19084 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19085 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19086 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19087 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19088 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19089 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19090 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19091 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19092 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19093 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19094 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19095
19096 ;; All the other keys
19097
19098 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19099 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19100 (if (boundp 'narrow-map)
19101 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19102 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19103 (if (boundp 'narrow-map)
19104 (org-defkey narrow-map "b" 'org-narrow-to-block)
19105 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19106 (if (boundp 'narrow-map)
19107 (org-defkey narrow-map "e" 'org-narrow-to-element)
19108 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19109 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19110 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19111 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19112 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19113 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19114 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19115 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19116 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19117 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19118 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19119 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19120 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19121 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19122 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19123 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19124 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19125 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19126 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19127 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19128 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19129 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19130 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19131 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19132 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19133 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19134 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19135 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19136 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19137 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19138 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19139 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19140 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19141 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19142 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19143 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19144 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19145 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19146 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19147 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19148 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19149 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19150 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19151 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19152 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19153 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19154 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19155 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19156 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19157 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19158 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19159 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19160 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19161 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19162 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19163 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19164 (org-defkey org-mode-map "\C-c^" 'org-sort)
19165 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19166 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19167 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19168 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19169 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19170 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19171 (org-defkey org-mode-map "\C-m" 'org-return)
19172 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19173 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19174 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19175 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19176 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19177 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19178 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19179 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19180 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19181 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19182 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19183 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19184 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19185 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19186 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19187 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19188 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19189 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19190 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19191 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19192 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19193 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19194 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19195
19196 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19197 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19198 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19199
19200 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19201 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19202 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19203 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19204 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19205 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19206 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19207 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19208 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19209 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19210 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19211 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19212 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19213 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19214 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19215 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19216 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19217 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19218 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19219 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19220 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19221 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19222 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19223
19224 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19225 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19226 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19227 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19228 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19229
19230 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19231
19232 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19233
19234 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19235 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19236
19237 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19238
19239
19240 (when (featurep 'xemacs)
19241 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19242
19243
19244 (defconst org-speed-commands-default
19245 '(
19246 ("Outline Navigation")
19247 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19248 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19249 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19250 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19251 ("F" . org-next-block)
19252 ("B" . org-previous-block)
19253 ("u" . (org-speed-move-safe 'outline-up-heading))
19254 ("j" . org-goto)
19255 ("g" . (org-refile t))
19256 ("Outline Visibility")
19257 ("c" . org-cycle)
19258 ("C" . org-shifttab)
19259 (" " . org-display-outline-path)
19260 ("s" . org-narrow-to-subtree)
19261 ("=" . org-columns)
19262 ("Outline Structure Editing")
19263 ("U" . org-shiftmetaup)
19264 ("D" . org-shiftmetadown)
19265 ("r" . org-metaright)
19266 ("l" . org-metaleft)
19267 ("R" . org-shiftmetaright)
19268 ("L" . org-shiftmetaleft)
19269 ("i" . (progn (forward-char 1) (call-interactively
19270 'org-insert-heading-respect-content)))
19271 ("^" . org-sort)
19272 ("w" . org-refile)
19273 ("a" . org-archive-subtree-default-with-confirmation)
19274 ("@" . org-mark-subtree)
19275 ("#" . org-toggle-comment)
19276 ("Clock Commands")
19277 ("I" . org-clock-in)
19278 ("O" . org-clock-out)
19279 ("Meta Data Editing")
19280 ("t" . org-todo)
19281 ("," . (org-priority))
19282 ("0" . (org-priority ?\ ))
19283 ("1" . (org-priority ?A))
19284 ("2" . (org-priority ?B))
19285 ("3" . (org-priority ?C))
19286 (":" . org-set-tags-command)
19287 ("e" . org-set-effort)
19288 ("E" . org-inc-effort)
19289 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19290 (org-entry-put (point) "APPT_WARNTIME" m)))
19291 ("Agenda Views etc")
19292 ("v" . org-agenda)
19293 ("/" . org-sparse-tree)
19294 ("Misc")
19295 ("o" . org-open-at-point)
19296 ("?" . org-speed-command-help)
19297 ("<" . (org-agenda-set-restriction-lock 'subtree))
19298 (">" . (org-agenda-remove-restriction-lock))
19299 )
19300 "The default speed commands.")
19301
19302 (defun org-print-speed-command (e)
19303 (if (> (length (car e)) 1)
19304 (progn
19305 (princ "\n")
19306 (princ (car e))
19307 (princ "\n")
19308 (princ (make-string (length (car e)) ?-))
19309 (princ "\n"))
19310 (princ (car e))
19311 (princ " ")
19312 (if (symbolp (cdr e))
19313 (princ (symbol-name (cdr e)))
19314 (prin1 (cdr e)))
19315 (princ "\n")))
19316
19317 (defun org-speed-command-help ()
19318 "Show the available speed commands."
19319 (interactive)
19320 (if (not org-use-speed-commands)
19321 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19322 (with-output-to-temp-buffer "*Help*"
19323 (princ "User-defined Speed commands\n===========================\n")
19324 (mapc 'org-print-speed-command org-speed-commands-user)
19325 (princ "\n")
19326 (princ "Built-in Speed commands\n=======================\n")
19327 (mapc 'org-print-speed-command org-speed-commands-default))
19328 (with-current-buffer "*Help*"
19329 (setq truncate-lines t))))
19330
19331 (defun org-speed-move-safe (cmd)
19332 "Execute CMD, but make sure that the cursor always ends up in a headline.
19333 If not, return to the original position and throw an error."
19334 (interactive)
19335 (let ((pos (point)))
19336 (call-interactively cmd)
19337 (unless (and (bolp) (org-at-heading-p))
19338 (goto-char pos)
19339 (error "Boundary reached while executing %s" cmd))))
19340
19341 (defvar org-self-insert-command-undo-counter 0)
19342
19343 (defvar org-table-auto-blank-field) ; defined in org-table.el
19344 (defvar org-speed-command nil)
19345
19346 (define-obsolete-function-alias
19347 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19348
19349 (defun org-speed-command-activate (keys)
19350 "Hook for activating single-letter speed commands.
19351 `org-speed-commands-default' specifies a minimal command set.
19352 Use `org-speed-commands-user' for further customization."
19353 (when (or (and (bolp) (looking-at org-outline-regexp))
19354 (and (functionp org-use-speed-commands)
19355 (funcall org-use-speed-commands)))
19356 (cdr (assoc keys (append org-speed-commands-user
19357 org-speed-commands-default)))))
19358
19359 (define-obsolete-function-alias
19360 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19361
19362 (defun org-babel-speed-command-activate (keys)
19363 "Hook for activating single-letter code block commands."
19364 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19365 (cdr (assoc keys org-babel-key-bindings))))
19366
19367 (defcustom org-speed-command-hook
19368 '(org-speed-command-default-hook org-babel-speed-command-hook)
19369 "Hook for activating speed commands at strategic locations.
19370 Hook functions are called in sequence until a valid handler is
19371 found.
19372
19373 Each hook takes a single argument, a user-pressed command key
19374 which is also a `self-insert-command' from the global map.
19375
19376 Within the hook, examine the cursor position and the command key
19377 and return nil or a valid handler as appropriate. Handler could
19378 be one of an interactive command, a function, or a form.
19379
19380 Set `org-use-speed-commands' to non-nil value to enable this
19381 hook. The default setting is `org-speed-command-activate'."
19382 :group 'org-structure
19383 :version "24.1"
19384 :type 'hook)
19385
19386 (defun org-self-insert-command (N)
19387 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19388 If the cursor is in a table looking at whitespace, the whitespace is
19389 overwritten, and the table is not marked as requiring realignment."
19390 (interactive "p")
19391 (org-check-before-invisible-edit 'insert)
19392 (cond
19393 ((and org-use-speed-commands
19394 (setq org-speed-command
19395 (run-hook-with-args-until-success
19396 'org-speed-command-hook (this-command-keys))))
19397 (cond
19398 ((commandp org-speed-command)
19399 (setq this-command org-speed-command)
19400 (call-interactively org-speed-command))
19401 ((functionp org-speed-command)
19402 (funcall org-speed-command))
19403 ((and org-speed-command (listp org-speed-command))
19404 (eval org-speed-command))
19405 (t (let (org-use-speed-commands)
19406 (call-interactively 'org-self-insert-command)))))
19407 ((and
19408 (org-table-p)
19409 (progn
19410 ;; check if we blank the field, and if that triggers align
19411 (and (featurep 'org-table) org-table-auto-blank-field
19412 (member last-command
19413 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19414 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19415 ;; got extra space, this field does not determine column width
19416 (let (org-table-may-need-update) (org-table-blank-field))
19417 ;; no extra space, this field may determine column width
19418 (org-table-blank-field)))
19419 t)
19420 (eq N 1)
19421 (looking-at "[^|\n]* |"))
19422 (let (org-table-may-need-update)
19423 (goto-char (1- (match-end 0)))
19424 (backward-delete-char 1)
19425 (goto-char (match-beginning 0))
19426 (self-insert-command N)))
19427 (t
19428 (setq org-table-may-need-update t)
19429 (self-insert-command N)
19430 (org-fix-tags-on-the-fly)
19431 (if org-self-insert-cluster-for-undo
19432 (if (not (eq last-command 'org-self-insert-command))
19433 (setq org-self-insert-command-undo-counter 1)
19434 (if (>= org-self-insert-command-undo-counter 20)
19435 (setq org-self-insert-command-undo-counter 1)
19436 (and (> org-self-insert-command-undo-counter 0)
19437 buffer-undo-list (listp buffer-undo-list)
19438 (not (cadr buffer-undo-list)) ; remove nil entry
19439 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19440 (setq org-self-insert-command-undo-counter
19441 (1+ org-self-insert-command-undo-counter))))))))
19442
19443 (defun org-check-before-invisible-edit (kind)
19444 "Check is editing if kind KIND would be dangerous with invisible text around.
19445 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19446 ;; First, try to get out of here as quickly as possible, to reduce overhead
19447 (if (and org-catch-invisible-edits
19448 (or (not (boundp 'visible-mode)) (not visible-mode))
19449 (or (get-char-property (point) 'invisible)
19450 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19451 ;; OK, we need to take a closer look
19452 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19453 (invisible-before-point (if (bobp) nil (get-char-property
19454 (1- (point)) 'invisible)))
19455 (border-and-ok-direction
19456 (or
19457 ;; Check if we are acting predictably before invisible text
19458 (and invisible-at-point (not invisible-before-point)
19459 (memq kind '(insert delete-backward)))
19460 ;; Check if we are acting predictably after invisible text
19461 ;; This works not well, and I have turned it off. It seems
19462 ;; better to always show and stop after invisible text.
19463 ;; (and (not invisible-at-point) invisible-before-point
19464 ;; (memq kind '(insert delete)))
19465 )))
19466 (when (or (memq invisible-at-point '(outline org-hide-block t))
19467 (memq invisible-before-point '(outline org-hide-block t)))
19468 (if (eq org-catch-invisible-edits 'error)
19469 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19470 (if (and org-custom-properties-overlays
19471 (y-or-n-p "Display invisible properties in this buffer? "))
19472 (org-toggle-custom-properties-visibility)
19473 ;; Make the area visible
19474 (save-excursion
19475 (if invisible-before-point
19476 (goto-char (previous-single-char-property-change
19477 (point) 'invisible)))
19478 (show-subtree))
19479 (cond
19480 ((eq org-catch-invisible-edits 'show)
19481 ;; That's it, we do the edit after showing
19482 (message
19483 "Unfolding invisible region around point before editing")
19484 (sit-for 1))
19485 ((and (eq org-catch-invisible-edits 'smart)
19486 border-and-ok-direction)
19487 (message "Unfolding invisible region around point before editing"))
19488 (t
19489 ;; Don't do the edit, make the user repeat it in full visibility
19490 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19491
19492 (defun org-fix-tags-on-the-fly ()
19493 (when (and (equal (char-after (point-at-bol)) ?*)
19494 (org-at-heading-p))
19495 (org-align-tags-here org-tags-column)))
19496
19497 (defun org-delete-backward-char (N)
19498 "Like `delete-backward-char', insert whitespace at field end in tables.
19499 When deleting backwards, in tables this function will insert whitespace in
19500 front of the next \"|\" separator, to keep the table aligned. The table will
19501 still be marked for re-alignment if the field did fill the entire column,
19502 because, in this case the deletion might narrow the column."
19503 (interactive "p")
19504 (save-match-data
19505 (org-check-before-invisible-edit 'delete-backward)
19506 (if (and (org-table-p)
19507 (eq N 1)
19508 (string-match "|" (buffer-substring (point-at-bol) (point)))
19509 (looking-at ".*?|"))
19510 (let ((pos (point))
19511 (noalign (looking-at "[^|\n\r]* |"))
19512 (c org-table-may-need-update))
19513 (backward-delete-char N)
19514 (if (not overwrite-mode)
19515 (progn
19516 (skip-chars-forward "^|")
19517 (insert " ")
19518 (goto-char (1- pos))))
19519 ;; noalign: if there were two spaces at the end, this field
19520 ;; does not determine the width of the column.
19521 (if noalign (setq org-table-may-need-update c)))
19522 (backward-delete-char N)
19523 (org-fix-tags-on-the-fly))))
19524
19525 (defun org-delete-char (N)
19526 "Like `delete-char', but insert whitespace at field end in tables.
19527 When deleting characters, in tables this function will insert whitespace in
19528 front of the next \"|\" separator, to keep the table aligned. The table will
19529 still be marked for re-alignment if the field did fill the entire column,
19530 because, in this case the deletion might narrow the column."
19531 (interactive "p")
19532 (save-match-data
19533 (org-check-before-invisible-edit 'delete)
19534 (if (and (org-table-p)
19535 (not (bolp))
19536 (not (= (char-after) ?|))
19537 (eq N 1))
19538 (if (looking-at ".*?|")
19539 (let ((pos (point))
19540 (noalign (looking-at "[^|\n\r]* |"))
19541 (c org-table-may-need-update))
19542 (replace-match
19543 (concat (substring (match-string 0) 1 -1) " |") nil t)
19544 (goto-char pos)
19545 ;; noalign: if there were two spaces at the end, this field
19546 ;; does not determine the width of the column.
19547 (if noalign (setq org-table-may-need-update c)))
19548 (delete-char N))
19549 (delete-char N)
19550 (org-fix-tags-on-the-fly))))
19551
19552 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19553 (put 'org-self-insert-command 'delete-selection
19554 (lambda ()
19555 (not (run-hook-with-args-until-success
19556 'self-insert-uses-region-functions))))
19557 (put 'orgtbl-self-insert-command 'delete-selection
19558 (lambda ()
19559 (not (run-hook-with-args-until-success
19560 'self-insert-uses-region-functions))))
19561 (put 'org-delete-char 'delete-selection 'supersede)
19562 (put 'org-delete-backward-char 'delete-selection 'supersede)
19563 (put 'org-yank 'delete-selection 'yank)
19564
19565 ;; Make `flyspell-mode' delay after some commands
19566 (put 'org-self-insert-command 'flyspell-delayed t)
19567 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19568 (put 'org-delete-char 'flyspell-delayed t)
19569 (put 'org-delete-backward-char 'flyspell-delayed t)
19570
19571 ;; Make pabbrev-mode expand after org-mode commands
19572 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19573 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19574
19575 (defun org-remap (map &rest commands)
19576 "In MAP, remap the functions given in COMMANDS.
19577 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19578 (let (new old)
19579 (while commands
19580 (setq old (pop commands) new (pop commands))
19581 (if (fboundp 'command-remapping)
19582 (org-defkey map (vector 'remap old) new)
19583 (substitute-key-definition old new map global-map)))))
19584
19585 (defun org-transpose-words ()
19586 "Transpose words for Org.
19587 This uses the `org-mode-transpose-word-syntax-table' syntax
19588 table, which interprets characters in `org-emphasis-alist' as
19589 word constituents."
19590 (interactive)
19591 (with-syntax-table org-mode-transpose-word-syntax-table
19592 (call-interactively 'transpose-words)))
19593 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19594
19595 (when (eq org-enable-table-editor 'optimized)
19596 ;; If the user wants maximum table support, we need to hijack
19597 ;; some standard editing functions
19598 (org-remap org-mode-map
19599 'self-insert-command 'org-self-insert-command
19600 'delete-char 'org-delete-char
19601 'delete-backward-char 'org-delete-backward-char)
19602 (org-defkey org-mode-map "|" 'org-force-self-insert))
19603
19604 (defvar org-ctrl-c-ctrl-c-hook nil
19605 "Hook for functions attaching themselves to `C-c C-c'.
19606
19607 This can be used to add additional functionality to the C-c C-c
19608 key which executes context-dependent commands. This hook is run
19609 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19610 run after the last test.
19611
19612 Each function will be called with no arguments. The function
19613 must check if the context is appropriate for it to act. If yes,
19614 it should do its thing and then return a non-nil value. If the
19615 context is wrong, just do nothing and return nil.")
19616
19617 (defvar org-ctrl-c-ctrl-c-final-hook nil
19618 "Hook for functions attaching themselves to `C-c C-c'.
19619
19620 This can be used to add additional functionality to the C-c C-c
19621 key which executes context-dependent commands. This hook is run
19622 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19623 before the first test.
19624
19625 Each function will be called with no arguments. The function
19626 must check if the context is appropriate for it to act. If yes,
19627 it should do its thing and then return a non-nil value. If the
19628 context is wrong, just do nothing and return nil.")
19629
19630 (defvar org-tab-first-hook nil
19631 "Hook for functions to attach themselves to TAB.
19632 See `org-ctrl-c-ctrl-c-hook' for more information.
19633 This hook runs as the first action when TAB is pressed, even before
19634 `org-cycle' messes around with the `outline-regexp' to cater for
19635 inline tasks and plain list item folding.
19636 If any function in this hook returns t, any other actions that
19637 would have been caused by TAB (such as table field motion or visibility
19638 cycling) will not occur.")
19639
19640 (defvar org-tab-after-check-for-table-hook nil
19641 "Hook for functions to attach themselves to TAB.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.
19643 This hook runs after it has been established that the cursor is not in a
19644 table, but before checking if the cursor is in a headline or if global cycling
19645 should be done.
19646 If any function in this hook returns t, not other actions like visibility
19647 cycling will be done.")
19648
19649 (defvar org-tab-after-check-for-cycling-hook nil
19650 "Hook for functions to attach themselves to TAB.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.
19652 This hook runs after it has been established that not table field motion and
19653 not visibility should be done because of current context. This is probably
19654 the place where a package like yasnippets can hook in.")
19655
19656 (defvar org-tab-before-tab-emulation-hook nil
19657 "Hook for functions to attach themselves to TAB.
19658 See `org-ctrl-c-ctrl-c-hook' for more information.
19659 This hook runs after every other options for TAB have been exhausted, but
19660 before indentation and \t insertion takes place.")
19661
19662 (defvar org-metaleft-hook nil
19663 "Hook for functions attaching themselves to `M-left'.
19664 See `org-ctrl-c-ctrl-c-hook' for more information.")
19665 (defvar org-metaright-hook nil
19666 "Hook for functions attaching themselves to `M-right'.
19667 See `org-ctrl-c-ctrl-c-hook' for more information.")
19668 (defvar org-metaup-hook nil
19669 "Hook for functions attaching themselves to `M-up'.
19670 See `org-ctrl-c-ctrl-c-hook' for more information.")
19671 (defvar org-metadown-hook nil
19672 "Hook for functions attaching themselves to `M-down'.
19673 See `org-ctrl-c-ctrl-c-hook' for more information.")
19674 (defvar org-shiftmetaleft-hook nil
19675 "Hook for functions attaching themselves to `M-S-left'.
19676 See `org-ctrl-c-ctrl-c-hook' for more information.")
19677 (defvar org-shiftmetaright-hook nil
19678 "Hook for functions attaching themselves to `M-S-right'.
19679 See `org-ctrl-c-ctrl-c-hook' for more information.")
19680 (defvar org-shiftmetaup-hook nil
19681 "Hook for functions attaching themselves to `M-S-up'.
19682 See `org-ctrl-c-ctrl-c-hook' for more information.")
19683 (defvar org-shiftmetadown-hook nil
19684 "Hook for functions attaching themselves to `M-S-down'.
19685 See `org-ctrl-c-ctrl-c-hook' for more information.")
19686 (defvar org-metareturn-hook nil
19687 "Hook for functions attaching themselves to `M-RET'.
19688 See `org-ctrl-c-ctrl-c-hook' for more information.")
19689 (defvar org-shiftup-hook nil
19690 "Hook for functions attaching themselves to `S-up'.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.")
19692 (defvar org-shiftup-final-hook nil
19693 "Hook for functions attaching themselves to `S-up'.
19694 This one runs after all other options except shift-select have been excluded.
19695 See `org-ctrl-c-ctrl-c-hook' for more information.")
19696 (defvar org-shiftdown-hook nil
19697 "Hook for functions attaching themselves to `S-down'.
19698 See `org-ctrl-c-ctrl-c-hook' for more information.")
19699 (defvar org-shiftdown-final-hook nil
19700 "Hook for functions attaching themselves to `S-down'.
19701 This one runs after all other options except shift-select have been excluded.
19702 See `org-ctrl-c-ctrl-c-hook' for more information.")
19703 (defvar org-shiftleft-hook nil
19704 "Hook for functions attaching themselves to `S-left'.
19705 See `org-ctrl-c-ctrl-c-hook' for more information.")
19706 (defvar org-shiftleft-final-hook nil
19707 "Hook for functions attaching themselves to `S-left'.
19708 This one runs after all other options except shift-select have been excluded.
19709 See `org-ctrl-c-ctrl-c-hook' for more information.")
19710 (defvar org-shiftright-hook nil
19711 "Hook for functions attaching themselves to `S-right'.
19712 See `org-ctrl-c-ctrl-c-hook' for more information.")
19713 (defvar org-shiftright-final-hook nil
19714 "Hook for functions attaching themselves to `S-right'.
19715 This one runs after all other options except shift-select have been excluded.
19716 See `org-ctrl-c-ctrl-c-hook' for more information.")
19717
19718 (defun org-modifier-cursor-error ()
19719 "Throw an error, a modified cursor command was applied in wrong context."
19720 (user-error "This command is active in special context like tables, headlines or items"))
19721
19722 (defun org-shiftselect-error ()
19723 "Throw an error because Shift-Cursor command was applied in wrong context."
19724 (if (and (boundp 'shift-select-mode) shift-select-mode)
19725 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19726 (user-error "This command works only in special context like headlines or timestamps")))
19727
19728 (defun org-call-for-shift-select (cmd)
19729 (let ((this-command-keys-shift-translated t))
19730 (call-interactively cmd)))
19731
19732 (defun org-shifttab (&optional arg)
19733 "Global visibility cycling or move to previous table field.
19734 Call `org-table-previous-field' within a table.
19735 When ARG is nil, cycle globally through visibility states.
19736 When ARG is a numeric prefix, show contents of this level."
19737 (interactive "P")
19738 (cond
19739 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19740 ((integerp arg)
19741 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19742 (message "Content view to level: %d" arg)
19743 (org-content (prefix-numeric-value arg2))
19744 (org-cycle-show-empty-lines t)
19745 (setq org-cycle-global-status 'overview)))
19746 (t (call-interactively 'org-global-cycle))))
19747
19748 (defun org-shiftmetaleft ()
19749 "Promote subtree or delete table column.
19750 Calls `org-promote-subtree', `org-outdent-item-tree', or
19751 `org-table-delete-column', depending on context. See the
19752 individual commands for more information."
19753 (interactive)
19754 (cond
19755 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19756 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19757 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19758 ((if (not (org-region-active-p)) (org-at-item-p)
19759 (save-excursion (goto-char (region-beginning))
19760 (org-at-item-p)))
19761 (call-interactively 'org-outdent-item-tree))
19762 (t (org-modifier-cursor-error))))
19763
19764 (defun org-shiftmetaright ()
19765 "Demote subtree or insert table column.
19766 Calls `org-demote-subtree', `org-indent-item-tree', or
19767 `org-table-insert-column', depending on context. See the
19768 individual commands for more information."
19769 (interactive)
19770 (cond
19771 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19772 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19773 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19774 ((if (not (org-region-active-p)) (org-at-item-p)
19775 (save-excursion (goto-char (region-beginning))
19776 (org-at-item-p)))
19777 (call-interactively 'org-indent-item-tree))
19778 (t (org-modifier-cursor-error))))
19779
19780 (defun org-shiftmetaup (&optional arg)
19781 "Move subtree up or kill table row.
19782 Calls `org-move-subtree-up' or `org-table-kill-row' or
19783 `org-move-item-up' or `org-timestamp-up', depending on context.
19784 See the individual commands for more information."
19785 (interactive "P")
19786 (cond
19787 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19788 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19789 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19790 ((org-at-item-p) (call-interactively 'org-move-item-up))
19791 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19792 (call-interactively 'org-timestamp-up)))
19793 (t (call-interactively 'org-drag-line-backward))))
19794
19795 (defun org-shiftmetadown (&optional arg)
19796 "Move subtree down or insert table row.
19797 Calls `org-move-subtree-down' or `org-table-insert-row' or
19798 `org-move-item-down' or `org-timestamp-up', depending on context.
19799 See the individual commands for more information."
19800 (interactive "P")
19801 (cond
19802 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19803 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19804 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19805 ((org-at-item-p) (call-interactively 'org-move-item-down))
19806 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19807 (call-interactively 'org-timestamp-down)))
19808 (t (call-interactively 'org-drag-line-forward))))
19809
19810 (defsubst org-hidden-tree-error ()
19811 (user-error
19812 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19813
19814 (defun org-metaleft (&optional arg)
19815 "Promote heading or move table column to left.
19816 Calls `org-do-promote' or `org-table-move-column', depending on context.
19817 With no specific context, calls the Emacs default `backward-word'.
19818 See the individual commands for more information."
19819 (interactive "P")
19820 (cond
19821 ((run-hook-with-args-until-success 'org-metaleft-hook))
19822 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19823 ((org-with-limited-levels
19824 (or (org-at-heading-p)
19825 (and (org-region-active-p)
19826 (save-excursion
19827 (goto-char (region-beginning))
19828 (org-at-heading-p)))))
19829 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19830 (call-interactively 'org-do-promote))
19831 ;; At an inline task.
19832 ((org-at-heading-p)
19833 (call-interactively 'org-inlinetask-promote))
19834 ((or (org-at-item-p)
19835 (and (org-region-active-p)
19836 (save-excursion
19837 (goto-char (region-beginning))
19838 (org-at-item-p))))
19839 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19840 (call-interactively 'org-outdent-item))
19841 (t (call-interactively 'backward-word))))
19842
19843 (defun org-metaright (&optional arg)
19844 "Demote a subtree, a list item or move table column to right.
19845 In front of a drawer or a block keyword, indent it correctly.
19846 With no specific context, calls the Emacs default `forward-word'.
19847 See the individual commands for more information."
19848 (interactive "P")
19849 (cond
19850 ((run-hook-with-args-until-success 'org-metaright-hook))
19851 ((org-at-table-p) (call-interactively 'org-table-move-column))
19852 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19853 ((org-at-block-p) (call-interactively 'org-indent-block))
19854 ((org-with-limited-levels
19855 (or (org-at-heading-p)
19856 (and (org-region-active-p)
19857 (save-excursion
19858 (goto-char (region-beginning))
19859 (org-at-heading-p)))))
19860 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19861 (call-interactively 'org-do-demote))
19862 ;; At an inline task.
19863 ((org-at-heading-p)
19864 (call-interactively 'org-inlinetask-demote))
19865 ((or (org-at-item-p)
19866 (and (org-region-active-p)
19867 (save-excursion
19868 (goto-char (region-beginning))
19869 (org-at-item-p))))
19870 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19871 (call-interactively 'org-indent-item))
19872 (t (call-interactively 'forward-word))))
19873
19874 (defun org-check-for-hidden (what)
19875 "Check if there are hidden headlines/items in the current visual line.
19876 WHAT can be either `headlines' or `items'. If the current line is
19877 an outline or item heading and it has a folded subtree below it,
19878 this function returns t, nil otherwise."
19879 (let ((re (cond
19880 ((eq what 'headlines) org-outline-regexp-bol)
19881 ((eq what 'items) (org-item-beginning-re))
19882 (t (error "This should not happen"))))
19883 beg end)
19884 (save-excursion
19885 (catch 'exit
19886 (unless (org-region-active-p)
19887 (setq beg (point-at-bol))
19888 (beginning-of-line 2)
19889 (while (and (not (eobp)) ;; this is like `next-line'
19890 (get-char-property (1- (point)) 'invisible))
19891 (beginning-of-line 2))
19892 (setq end (point))
19893 (goto-char beg)
19894 (goto-char (point-at-eol))
19895 (setq end (max end (point)))
19896 (while (re-search-forward re end t)
19897 (if (get-char-property (match-beginning 0) 'invisible)
19898 (throw 'exit t))))
19899 nil))))
19900
19901 (defun org-metaup (&optional arg)
19902 "Move subtree up or move table row up.
19903 Calls `org-move-subtree-up' or `org-table-move-row' or
19904 `org-move-item-up', depending on context. See the individual commands
19905 for more information."
19906 (interactive "P")
19907 (cond
19908 ((run-hook-with-args-until-success 'org-metaup-hook))
19909 ((org-region-active-p)
19910 (let* ((a (min (region-beginning) (region-end)))
19911 (b (1- (max (region-beginning) (region-end))))
19912 (c (save-excursion (goto-char a)
19913 (move-beginning-of-line 0)))
19914 (d (save-excursion (goto-char a)
19915 (move-end-of-line 0) (point))))
19916 (transpose-regions a b c d)
19917 (goto-char c)))
19918 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19919 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19920 ((org-at-item-p) (call-interactively 'org-move-item-up))
19921 (t (org-drag-element-backward))))
19922
19923 (defun org-metadown (&optional arg)
19924 "Move subtree down or move table row down.
19925 Calls `org-move-subtree-down' or `org-table-move-row' or
19926 `org-move-item-down', depending on context. See the individual
19927 commands for more information."
19928 (interactive "P")
19929 (cond
19930 ((run-hook-with-args-until-success 'org-metadown-hook))
19931 ((org-region-active-p)
19932 (let* ((a (min (region-beginning) (region-end)))
19933 (b (max (region-beginning) (region-end)))
19934 (c (save-excursion (goto-char b)
19935 (move-beginning-of-line 1)))
19936 (d (save-excursion (goto-char b)
19937 (move-end-of-line 1) (1+ (point)))))
19938 (transpose-regions a b c d)
19939 (goto-char d)))
19940 ((org-at-table-p) (call-interactively 'org-table-move-row))
19941 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19942 ((org-at-item-p) (call-interactively 'org-move-item-down))
19943 (t (org-drag-element-forward))))
19944
19945 (defun org-shiftup (&optional arg)
19946 "Increase item in timestamp or increase priority of current headline.
19947 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19948 depending on context. See the individual commands for more information."
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-shiftup-hook))
19952 ((and org-support-shift-select (org-region-active-p))
19953 (org-call-for-shift-select 'previous-line))
19954 ((org-at-timestamp-p t)
19955 (call-interactively (if org-edit-timestamp-down-means-later
19956 'org-timestamp-down 'org-timestamp-up)))
19957 ((and (not (eq org-support-shift-select 'always))
19958 org-enable-priority-commands
19959 (org-at-heading-p))
19960 (call-interactively 'org-priority-up))
19961 ((and (not org-support-shift-select) (org-at-item-p))
19962 (call-interactively 'org-previous-item))
19963 ((org-clocktable-try-shift 'up arg))
19964 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19965 (org-support-shift-select
19966 (org-call-for-shift-select 'previous-line))
19967 (t (org-shiftselect-error))))
19968
19969 (defun org-shiftdown (&optional arg)
19970 "Decrease item in timestamp or decrease priority of current headline.
19971 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19972 depending on context. See the individual commands for more information."
19973 (interactive "P")
19974 (cond
19975 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19976 ((and org-support-shift-select (org-region-active-p))
19977 (org-call-for-shift-select 'next-line))
19978 ((org-at-timestamp-p t)
19979 (call-interactively (if org-edit-timestamp-down-means-later
19980 'org-timestamp-up 'org-timestamp-down)))
19981 ((and (not (eq org-support-shift-select 'always))
19982 org-enable-priority-commands
19983 (org-at-heading-p))
19984 (call-interactively 'org-priority-down))
19985 ((and (not org-support-shift-select) (org-at-item-p))
19986 (call-interactively 'org-next-item))
19987 ((org-clocktable-try-shift 'down arg))
19988 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19989 (org-support-shift-select
19990 (org-call-for-shift-select 'next-line))
19991 (t (org-shiftselect-error))))
19992
19993 (defun org-shiftright (&optional arg)
19994 "Cycle the thing at point or in the current line, depending on context.
19995 Depending on context, this does one of the following:
19996
19997 - switch a timestamp at point one day into the future
19998 - on a headline, switch to the next TODO keyword.
19999 - on an item, switch entire list to the next bullet type
20000 - on a property line, switch to the next allowed value
20001 - on a clocktable definition line, move time block into the future"
20002 (interactive "P")
20003 (cond
20004 ((run-hook-with-args-until-success 'org-shiftright-hook))
20005 ((and org-support-shift-select (org-region-active-p))
20006 (org-call-for-shift-select 'forward-char))
20007 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20008 ((and (not (eq org-support-shift-select 'always))
20009 (org-at-heading-p))
20010 (let ((org-inhibit-logging
20011 (not org-treat-S-cursor-todo-selection-as-state-change))
20012 (org-inhibit-blocking
20013 (not org-treat-S-cursor-todo-selection-as-state-change)))
20014 (org-call-with-arg 'org-todo 'right)))
20015 ((or (and org-support-shift-select
20016 (not (eq org-support-shift-select 'always))
20017 (org-at-item-bullet-p))
20018 (and (not org-support-shift-select) (org-at-item-p)))
20019 (org-call-with-arg 'org-cycle-list-bullet nil))
20020 ((and (not (eq org-support-shift-select 'always))
20021 (org-at-property-p))
20022 (call-interactively 'org-property-next-allowed-value))
20023 ((org-clocktable-try-shift 'right arg))
20024 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20025 (org-support-shift-select
20026 (org-call-for-shift-select 'forward-char))
20027 (t (org-shiftselect-error))))
20028
20029 (defun org-shiftleft (&optional arg)
20030 "Cycle the thing at point or in the current line, depending on context.
20031 Depending on context, this does one of the following:
20032
20033 - switch a timestamp at point one day into the past
20034 - on a headline, switch to the previous TODO keyword.
20035 - on an item, switch entire list to the previous bullet type
20036 - on a property line, switch to the previous allowed value
20037 - on a clocktable definition line, move time block into the past"
20038 (interactive "P")
20039 (cond
20040 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20041 ((and org-support-shift-select (org-region-active-p))
20042 (org-call-for-shift-select 'backward-char))
20043 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20044 ((and (not (eq org-support-shift-select 'always))
20045 (org-at-heading-p))
20046 (let ((org-inhibit-logging
20047 (not org-treat-S-cursor-todo-selection-as-state-change))
20048 (org-inhibit-blocking
20049 (not org-treat-S-cursor-todo-selection-as-state-change)))
20050 (org-call-with-arg 'org-todo 'left)))
20051 ((or (and org-support-shift-select
20052 (not (eq org-support-shift-select 'always))
20053 (org-at-item-bullet-p))
20054 (and (not org-support-shift-select) (org-at-item-p)))
20055 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20056 ((and (not (eq org-support-shift-select 'always))
20057 (org-at-property-p))
20058 (call-interactively 'org-property-previous-allowed-value))
20059 ((org-clocktable-try-shift 'left arg))
20060 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20061 (org-support-shift-select
20062 (org-call-for-shift-select 'backward-char))
20063 (t (org-shiftselect-error))))
20064
20065 (defun org-shiftcontrolright ()
20066 "Switch to next TODO set."
20067 (interactive)
20068 (cond
20069 ((and org-support-shift-select (org-region-active-p))
20070 (org-call-for-shift-select 'forward-word))
20071 ((and (not (eq org-support-shift-select 'always))
20072 (org-at-heading-p))
20073 (org-call-with-arg 'org-todo 'nextset))
20074 (org-support-shift-select
20075 (org-call-for-shift-select 'forward-word))
20076 (t (org-shiftselect-error))))
20077
20078 (defun org-shiftcontrolleft ()
20079 "Switch to previous TODO set."
20080 (interactive)
20081 (cond
20082 ((and org-support-shift-select (org-region-active-p))
20083 (org-call-for-shift-select 'backward-word))
20084 ((and (not (eq org-support-shift-select 'always))
20085 (org-at-heading-p))
20086 (org-call-with-arg 'org-todo 'previousset))
20087 (org-support-shift-select
20088 (org-call-for-shift-select 'backward-word))
20089 (t (org-shiftselect-error))))
20090
20091 (defun org-shiftcontrolup (&optional n)
20092 "Change timestamps synchronously up in CLOCK log lines.
20093 Optional argument N tells to change by that many units."
20094 (interactive "P")
20095 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20096 (let (org-support-shift-select)
20097 (org-clock-timestamps-up n))
20098 (user-error "Not at a clock log")))
20099
20100 (defun org-shiftcontroldown (&optional n)
20101 "Change timestamps synchronously down in CLOCK log lines.
20102 Optional argument N tells to change by that many units."
20103 (interactive "P")
20104 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20105 (let (org-support-shift-select)
20106 (org-clock-timestamps-down n))
20107 (user-error "Not at a clock log")))
20108
20109 (defun org-ctrl-c-ret ()
20110 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20111 (interactive)
20112 (cond
20113 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20114 (t (call-interactively 'org-insert-heading))))
20115
20116 (defun org-find-visible ()
20117 (let ((s (point)))
20118 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20119 (get-char-property s 'invisible)))
20120 s))
20121 (defun org-find-invisible ()
20122 (let ((s (point)))
20123 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20124 (not (get-char-property s 'invisible))))
20125 s))
20126
20127 (defun org-copy-visible (beg end)
20128 "Copy the visible parts of the region."
20129 (interactive "r")
20130 (let (snippets s)
20131 (save-excursion
20132 (save-restriction
20133 (narrow-to-region beg end)
20134 (setq s (goto-char (point-min)))
20135 (while (not (= (point) (point-max)))
20136 (goto-char (org-find-invisible))
20137 (push (buffer-substring s (point)) snippets)
20138 (setq s (goto-char (org-find-visible))))))
20139 (kill-new (apply 'concat (nreverse snippets)))))
20140
20141 (defun org-copy-special ()
20142 "Copy region in table or copy current subtree.
20143 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20144 See the individual commands for more information."
20145 (interactive)
20146 (call-interactively
20147 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20148
20149 (defun org-cut-special ()
20150 "Cut region in table or cut current subtree.
20151 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20152 See the individual commands for more information."
20153 (interactive)
20154 (call-interactively
20155 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20156
20157 (defun org-paste-special (arg)
20158 "Paste rectangular region into table, or past subtree relative to level.
20159 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20160 See the individual commands for more information."
20161 (interactive "P")
20162 (if (org-at-table-p)
20163 (org-table-paste-rectangle)
20164 (org-paste-subtree arg)))
20165
20166 (defsubst org-in-fixed-width-region-p ()
20167 "Is point in a fixed-width region?"
20168 (save-match-data
20169 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20170
20171 (defun org-edit-special (&optional arg)
20172 "Call a special editor for the element at point.
20173 When at a table, call the formula editor with `org-table-edit-formulas'.
20174 When in a source code block, call `org-edit-src-code'.
20175 When in a fixed-width region, call `org-edit-fixed-width-region'.
20176 When at an #+INCLUDE keyword, visit the included file.
20177 On a link, call `ffap' to visit the link at point.
20178 Otherwise, return a user error."
20179 (interactive "P")
20180 (let ((element (org-element-at-point)))
20181 (assert (not buffer-read-only) nil
20182 "Buffer is read-only: %s" (buffer-name))
20183 (case (org-element-type element)
20184 (src-block
20185 (if (not arg) (org-edit-src-code)
20186 (let* ((info (org-babel-get-src-block-info))
20187 (lang (nth 0 info))
20188 (params (nth 2 info))
20189 (session (cdr (assq :session params))))
20190 (if (not session) (org-edit-src-code)
20191 ;; At a src-block with a session and function called with
20192 ;; an ARG: switch to the buffer related to the inferior
20193 ;; process.
20194 (switch-to-buffer
20195 (funcall (intern (concat "org-babel-prep-session:" lang))
20196 session params))))))
20197 (keyword
20198 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20199 (find-file
20200 (org-remove-double-quotes
20201 (car (org-split-string (org-element-property :value element)))))
20202 (user-error "No special environment to edit here")))
20203 (table
20204 (if (eq (org-element-property :type element) 'table.el)
20205 (org-edit-src-code)
20206 (call-interactively 'org-table-edit-formulas)))
20207 ;; Only Org tables contain `table-row' type elements.
20208 (table-row (call-interactively 'org-table-edit-formulas))
20209 ((example-block export-block) (org-edit-src-code))
20210 (fixed-width (org-edit-fixed-width-region))
20211 (otherwise
20212 ;; No notable element at point. Though, we may be at a link,
20213 ;; which is an object. Thus, scan deeper.
20214 (if (eq (org-element-type (org-element-context element)) 'link)
20215 (call-interactively 'ffap)
20216 (user-error "No special environment to edit here"))))))
20217
20218 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20219 (defun org-ctrl-c-ctrl-c (&optional arg)
20220 "Set tags in headline, or update according to changed information at point.
20221
20222 This command does many different things, depending on context:
20223
20224 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20225 this is what we do.
20226
20227 - If the cursor is on a statistics cookie, update it.
20228
20229 - If the cursor is in a headline, prompt for tags and insert them
20230 into the current line, aligned to `org-tags-column'. When called
20231 with prefix arg, realign all tags in the current buffer.
20232
20233 - If the cursor is in one of the special #+KEYWORD lines, this
20234 triggers scanning the buffer for these lines and updating the
20235 information.
20236
20237 - If the cursor is inside a table, realign the table. This command
20238 works even if the automatic table editor has been turned off.
20239
20240 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20241 the entire table.
20242
20243 - If the cursor is at a footnote reference or definition, jump to
20244 the corresponding definition or references, respectively.
20245
20246 - If the cursor is a the beginning of a dynamic block, update it.
20247
20248 - If the current buffer is a capture buffer, close note and file it.
20249
20250 - If the cursor is on a <<<target>>>, update radio targets and
20251 corresponding links in this buffer.
20252
20253 - If the cursor is on a numbered item in a plain list, renumber the
20254 ordered list.
20255
20256 - If the cursor is on a checkbox, toggle it.
20257
20258 - If the cursor is on a code block, evaluate it. The variable
20259 `org-confirm-babel-evaluate' can be used to control prompting
20260 before code block evaluation, by default every code block
20261 evaluation requires confirmation. Code block evaluation can be
20262 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20263 (interactive "P")
20264 (cond
20265 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20266 org-occur-highlights
20267 org-latex-fragment-image-overlays)
20268 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20269 (org-remove-occur-highlights)
20270 (org-remove-latex-fragment-image-overlays)
20271 (message "Temporary highlights/overlays removed from current buffer"))
20272 ((and (local-variable-p 'org-finish-function (current-buffer))
20273 (fboundp org-finish-function))
20274 (funcall org-finish-function))
20275 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20276 (t
20277 (let* ((context (org-element-context)) (type (org-element-type context)))
20278 ;; Test if point is within a blank line.
20279 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20280 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20281 (user-error "C-c C-c can do nothing useful at this location"))
20282 (case type
20283 ;; When at a link, act according to the parent instead.
20284 (link (setq context (org-element-property :parent context))
20285 (setq type (org-element-type context)))
20286 ;; Unsupported object types: refer to the first supported
20287 ;; element or object containing it.
20288 ((bold code entity export-snippet inline-babel-call inline-src-block
20289 italic latex-fragment line-break macro strike-through subscript
20290 superscript underline verbatim)
20291 (while (and (setq context (org-element-property :parent context))
20292 (not (memq (setq type (org-element-type context))
20293 '(radio-target paragraph verse-block
20294 table-cell)))))))
20295 ;; For convenience: at the first line of a paragraph on the
20296 ;; same line as an item, apply function on that item instead.
20297 (when (eq type 'paragraph)
20298 (let ((parent (org-element-property :parent context)))
20299 (when (and (eq (org-element-type parent) 'item)
20300 (= (point-at-bol) (org-element-property :begin parent)))
20301 (setq context parent type 'item))))
20302 ;; Act according to type of element or object at point.
20303 (case type
20304 (clock (org-clock-update-time-maybe))
20305 (dynamic-block
20306 (save-excursion
20307 (goto-char (org-element-property :post-affiliated context))
20308 (org-update-dblock)))
20309 (footnote-definition
20310 (goto-char (org-element-property :post-affiliated context))
20311 (call-interactively 'org-footnote-action))
20312 (footnote-reference (call-interactively 'org-footnote-action))
20313 ((headline inlinetask)
20314 (save-excursion (goto-char (org-element-property :begin context))
20315 (call-interactively 'org-set-tags)))
20316 (item
20317 ;; At an item: a double C-u set checkbox to "[-]"
20318 ;; unconditionally, whereas a single one will toggle its
20319 ;; presence. Without an universal argument, if the item
20320 ;; has a checkbox, toggle it. Otherwise repair the list.
20321 (let* ((box (org-element-property :checkbox context))
20322 (struct (org-element-property :structure context))
20323 (old-struct (copy-tree struct))
20324 (parents (org-list-parents-alist struct))
20325 (prevs (org-list-prevs-alist struct))
20326 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20327 (org-list-set-checkbox
20328 (org-element-property :begin context) struct
20329 (cond ((equal arg '(16)) "[-]")
20330 ((and (not box) (equal arg '(4))) "[ ]")
20331 ((or (not box) (equal arg '(4))) nil)
20332 ((eq box 'on) "[ ]")
20333 (t "[X]")))
20334 ;; Mimic `org-list-write-struct' but with grabbing
20335 ;; a return value from `org-list-struct-fix-box'.
20336 (org-list-struct-fix-ind struct parents 2)
20337 (org-list-struct-fix-item-end struct)
20338 (org-list-struct-fix-bul struct prevs)
20339 (org-list-struct-fix-ind struct parents)
20340 (let ((block-item
20341 (org-list-struct-fix-box struct parents prevs orderedp)))
20342 (if (and box (equal struct old-struct))
20343 (if (equal arg '(16))
20344 (message "Checkboxes already reset")
20345 (user-error "Cannot toggle this checkbox: %s"
20346 (if (eq box 'on)
20347 "all subitems checked"
20348 "unchecked subitems")))
20349 (org-list-struct-apply-struct struct old-struct)
20350 (org-update-checkbox-count-maybe))
20351 (when block-item
20352 (message "Checkboxes were removed due to empty box at line %d"
20353 (org-current-line block-item))))))
20354 (keyword
20355 (let ((org-inhibit-startup-visibility-stuff t)
20356 (org-startup-align-all-tables nil))
20357 (when (boundp 'org-table-coordinate-overlays)
20358 (mapc 'delete-overlay org-table-coordinate-overlays)
20359 (setq org-table-coordinate-overlays nil))
20360 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20361 (message "Local setup has been refreshed"))
20362 (plain-list
20363 ;; At a plain list, with a double C-u argument, set
20364 ;; checkboxes of each item to "[-]", whereas a single one
20365 ;; will toggle their presence according to the state of the
20366 ;; first item in the list. Without an argument, repair the
20367 ;; list.
20368 (let* ((begin (org-element-property :contents-begin context))
20369 (beginm (move-marker (make-marker) begin))
20370 (struct (org-element-property :structure context))
20371 (old-struct (copy-tree struct))
20372 (first-box (save-excursion
20373 (goto-char begin)
20374 (looking-at org-list-full-item-re)
20375 (match-string-no-properties 3)))
20376 (new-box (cond ((equal arg '(16)) "[-]")
20377 ((equal arg '(4)) (unless first-box "[ ]"))
20378 ((equal first-box "[X]") "[ ]")
20379 (t "[X]"))))
20380 (cond
20381 (arg
20382 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20383 (org-list-get-all-items
20384 begin struct (org-list-prevs-alist struct))))
20385 ((and first-box (eq (point) begin))
20386 ;; For convenience, when point is at bol on the first
20387 ;; item of the list and no argument is provided, simply
20388 ;; toggle checkbox of that item, if any.
20389 (org-list-set-checkbox begin struct new-box)))
20390 (org-list-write-struct
20391 struct (org-list-parents-alist struct) old-struct)
20392 (org-update-checkbox-count-maybe)
20393 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20394 ((property-drawer node-property)
20395 (call-interactively 'org-property-action))
20396 ((radio-target target)
20397 (call-interactively 'org-update-radio-target-regexp))
20398 (statistics-cookie
20399 (call-interactively 'org-update-statistics-cookies))
20400 ((table table-cell table-row)
20401 ;; At a table, recalculate every field and align it. Also
20402 ;; send the table if necessary. If the table has
20403 ;; a `table.el' type, just give up. At a table row or
20404 ;; cell, maybe recalculate line but always align table.
20405 (if (eq (org-element-property :type context) 'table.el)
20406 (message "Use C-c ' to edit table.el tables")
20407 (let ((org-enable-table-editor t))
20408 (if (or (eq type 'table)
20409 ;; Check if point is at a TBLFM line.
20410 (and (eq type 'table-row)
20411 (= (point) (org-element-property :end context))))
20412 (save-excursion
20413 (if (org-at-TBLFM-p)
20414 (progn (require 'org-table)
20415 (org-table-calc-current-TBLFM))
20416 (goto-char (org-element-property :contents-begin context))
20417 (org-call-with-arg 'org-table-recalculate (or arg t))
20418 (orgtbl-send-table 'maybe)))
20419 (org-table-maybe-eval-formula)
20420 (cond (arg (call-interactively 'org-table-recalculate))
20421 ((org-table-maybe-recalculate-line))
20422 (t (org-table-align)))))))
20423 (timestamp (org-timestamp-change 0 'day))
20424 (otherwise
20425 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20426 (user-error
20427 "C-c C-c can do nothing useful at this location")))))))))
20428
20429 (defun org-mode-restart ()
20430 (interactive)
20431 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20432 (funcall major-mode)
20433 (hack-local-variables)
20434 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20435 (org-indent-mode -1)))
20436 (message "%s restarted" major-mode))
20437
20438 (defun org-kill-note-or-show-branches ()
20439 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20440 (interactive)
20441 (if (not org-finish-function)
20442 (progn
20443 (hide-subtree)
20444 (call-interactively 'show-branches))
20445 (let ((org-note-abort t))
20446 (funcall org-finish-function))))
20447
20448 (defun org-open-line (n)
20449 "Insert a new row in tables, call `open-line' elsewhere.
20450 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20451 (interactive "*p")
20452 (cond
20453 ((not org-special-ctrl-o)
20454 (open-line n))
20455 ((org-at-table-p)
20456 (org-table-insert-row))
20457 (t
20458 (open-line n))))
20459
20460 (defun org-return (&optional indent)
20461 "Goto next table row or insert a newline.
20462 Calls `org-table-next-row' or `newline', depending on context.
20463 See the individual commands for more information."
20464 (interactive)
20465 (let (org-ts-what)
20466 (cond
20467 ((or (bobp) (org-in-src-block-p))
20468 (if indent (newline-and-indent) (newline)))
20469 ((org-at-table-p)
20470 (org-table-justify-field-maybe)
20471 (call-interactively 'org-table-next-row))
20472 ;; when `newline-and-indent' is called within a list, make sure
20473 ;; text moved stays inside the item.
20474 ((and (org-in-item-p) indent)
20475 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20476 (progn
20477 (save-match-data (newline))
20478 (org-indent-line-to (length (match-string 0))))
20479 (let ((ind (org-get-indentation)))
20480 (newline)
20481 (if (org-looking-back org-list-end-re)
20482 (org-indent-line)
20483 (org-indent-line-to ind)))))
20484 ((and org-return-follows-link
20485 (org-at-timestamp-p t)
20486 (not (eq org-ts-what 'after)))
20487 (org-follow-timestamp-link))
20488 ((and org-return-follows-link
20489 (let ((tprop (get-text-property (point) 'face)))
20490 (or (eq tprop 'org-link)
20491 (and (listp tprop) (memq 'org-link tprop)))))
20492 (call-interactively 'org-open-at-point))
20493 ((and (org-at-heading-p)
20494 (looking-at
20495 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20496 (org-show-entry)
20497 (end-of-line 1)
20498 (newline))
20499 (t (if indent (newline-and-indent) (newline))))))
20500
20501 (defun org-return-indent ()
20502 "Goto next table row or insert a newline and indent.
20503 Calls `org-table-next-row' or `newline-and-indent', depending on
20504 context. See the individual commands for more information."
20505 (interactive)
20506 (org-return t))
20507
20508 (defun org-ctrl-c-star ()
20509 "Compute table, or change heading status of lines.
20510 Calls `org-table-recalculate' or `org-toggle-heading',
20511 depending on context."
20512 (interactive)
20513 (cond
20514 ((org-at-table-p)
20515 (call-interactively 'org-table-recalculate))
20516 (t
20517 ;; Convert all lines in region to list items
20518 (call-interactively 'org-toggle-heading))))
20519
20520 (defun org-ctrl-c-minus ()
20521 "Insert separator line in table or modify bullet status of line.
20522 Also turns a plain line or a region of lines into list items.
20523 Calls `org-table-insert-hline', `org-toggle-item', or
20524 `org-cycle-list-bullet', depending on context."
20525 (interactive)
20526 (cond
20527 ((org-at-table-p)
20528 (call-interactively 'org-table-insert-hline))
20529 ((org-region-active-p)
20530 (call-interactively 'org-toggle-item))
20531 ((org-in-item-p)
20532 (call-interactively 'org-cycle-list-bullet))
20533 (t
20534 (call-interactively 'org-toggle-item))))
20535
20536 (defun org-toggle-item (arg)
20537 "Convert headings or normal lines to items, items to normal lines.
20538 If there is no active region, only the current line is considered.
20539
20540 If the first non blank line in the region is a headline, convert
20541 all headlines to items, shifting text accordingly.
20542
20543 If it is an item, convert all items to normal lines.
20544
20545 If it is normal text, change region into a list of items.
20546 With a prefix argument ARG, change the region in a single item."
20547 (interactive "P")
20548 (let ((shift-text
20549 (function
20550 ;; Shift text in current section to IND, from point to END.
20551 ;; The function leaves point to END line.
20552 (lambda (ind end)
20553 (let ((min-i 1000) (end (copy-marker end)))
20554 ;; First determine the minimum indentation (MIN-I) of
20555 ;; the text.
20556 (save-excursion
20557 (catch 'exit
20558 (while (< (point) end)
20559 (let ((i (org-get-indentation)))
20560 (cond
20561 ;; Skip blank lines and inline tasks.
20562 ((looking-at "^[ \t]*$"))
20563 ((looking-at org-outline-regexp-bol))
20564 ;; We can't find less than 0 indentation.
20565 ((zerop i) (throw 'exit (setq min-i 0)))
20566 ((< i min-i) (setq min-i i))))
20567 (forward-line))))
20568 ;; Then indent each line so that a line indented to
20569 ;; MIN-I becomes indented to IND. Ignore blank lines
20570 ;; and inline tasks in the process.
20571 (let ((delta (- ind min-i)))
20572 (while (< (point) end)
20573 (unless (or (looking-at "^[ \t]*$")
20574 (looking-at org-outline-regexp-bol))
20575 (org-indent-line-to (+ (org-get-indentation) delta)))
20576 (forward-line)))))))
20577 (skip-blanks
20578 (function
20579 ;; Return beginning of first non-blank line, starting from
20580 ;; line at POS.
20581 (lambda (pos)
20582 (save-excursion
20583 (goto-char pos)
20584 (skip-chars-forward " \r\t\n")
20585 (point-at-bol)))))
20586 beg end)
20587 ;; Determine boundaries of changes.
20588 (if (org-region-active-p)
20589 (setq beg (funcall skip-blanks (region-beginning))
20590 end (copy-marker (region-end)))
20591 (setq beg (funcall skip-blanks (point-at-bol))
20592 end (copy-marker (point-at-eol))))
20593 ;; Depending on the starting line, choose an action on the text
20594 ;; between BEG and END.
20595 (org-with-limited-levels
20596 (save-excursion
20597 (goto-char beg)
20598 (cond
20599 ;; Case 1. Start at an item: de-itemize. Note that it only
20600 ;; happens when a region is active: `org-ctrl-c-minus'
20601 ;; would call `org-cycle-list-bullet' otherwise.
20602 ((org-at-item-p)
20603 (while (< (point) end)
20604 (when (org-at-item-p)
20605 (skip-chars-forward " \t")
20606 (delete-region (point) (match-end 0)))
20607 (forward-line)))
20608 ;; Case 2. Start at an heading: convert to items.
20609 ((org-at-heading-p)
20610 (let* ((bul (org-list-bullet-string "-"))
20611 (bul-len (length bul))
20612 ;; Indentation of the first heading. It should be
20613 ;; relative to the indentation of its parent, if any.
20614 (start-ind (save-excursion
20615 (cond
20616 ((not org-adapt-indentation) 0)
20617 ((not (outline-previous-heading)) 0)
20618 (t (length (match-string 0))))))
20619 ;; Level of first heading. Further headings will be
20620 ;; compared to it to determine hierarchy in the list.
20621 (ref-level (org-reduced-level (org-outline-level))))
20622 (while (< (point) end)
20623 (let* ((level (org-reduced-level (org-outline-level)))
20624 (delta (max 0 (- level ref-level))))
20625 ;; If current headline is less indented than the first
20626 ;; one, set it as reference, in order to preserve
20627 ;; subtrees.
20628 (when (< level ref-level) (setq ref-level level))
20629 (replace-match bul t t)
20630 (org-indent-line-to (+ start-ind (* delta bul-len)))
20631 ;; Ensure all text down to END (or SECTION-END) belongs
20632 ;; to the newly created item.
20633 (let ((section-end (save-excursion
20634 (or (outline-next-heading) (point)))))
20635 (forward-line)
20636 (funcall shift-text
20637 (+ start-ind (* (1+ delta) bul-len))
20638 (min end section-end)))))))
20639 ;; Case 3. Normal line with ARG: make the first line of region
20640 ;; an item, and shift indentation of others lines to
20641 ;; set them as item's body.
20642 (arg (let* ((bul (org-list-bullet-string "-"))
20643 (bul-len (length bul))
20644 (ref-ind (org-get-indentation)))
20645 (skip-chars-forward " \t")
20646 (insert bul)
20647 (forward-line)
20648 (while (< (point) end)
20649 ;; Ensure that lines less indented than first one
20650 ;; still get included in item body.
20651 (funcall shift-text
20652 (+ ref-ind bul-len)
20653 (min end (save-excursion (or (outline-next-heading)
20654 (point)))))
20655 (forward-line))))
20656 ;; Case 4. Normal line without ARG: turn each non-item line
20657 ;; into an item.
20658 (t
20659 (while (< (point) end)
20660 (unless (or (org-at-heading-p) (org-at-item-p))
20661 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20662 (replace-match
20663 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20664 (forward-line))))))))
20665
20666 (defun org-toggle-heading (&optional nstars)
20667 "Convert headings to normal text, or items or text to headings.
20668 If there is no active region, only convert the current line.
20669
20670 With a \\[universal-argument] prefix, convert the whole list at
20671 point into heading.
20672
20673 In a region:
20674
20675 - If the first non blank line is a headline, remove the stars
20676 from all headlines in the region.
20677
20678 - If it is a normal line, turn each and every normal line (i.e.,
20679 not an heading or an item) in the region into headings. If you
20680 want to convert only the first line of this region, use one
20681 universal prefix argument.
20682
20683 - If it is a plain list item, turn all plain list items into headings.
20684
20685 When converting a line into a heading, the number of stars is chosen
20686 such that the lines become children of the current entry. However,
20687 when a numeric prefix argument is given, its value determines the
20688 number of stars to add."
20689 (interactive "P")
20690 (let ((skip-blanks
20691 (function
20692 ;; Return beginning of first non-blank line, starting from
20693 ;; line at POS.
20694 (lambda (pos)
20695 (save-excursion
20696 (goto-char pos)
20697 (while (org-at-comment-p) (forward-line))
20698 (skip-chars-forward " \r\t\n")
20699 (point-at-bol)))))
20700 beg end toggled)
20701 ;; Determine boundaries of changes. If a universal prefix has
20702 ;; been given, put the list in a region. If region ends at a bol,
20703 ;; do not consider the last line to be in the region.
20704
20705 (when (and current-prefix-arg (org-at-item-p))
20706 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20707 (org-mark-element))
20708
20709 (if (org-region-active-p)
20710 (setq beg (funcall skip-blanks (region-beginning))
20711 end (copy-marker (save-excursion
20712 (goto-char (region-end))
20713 (if (bolp) (point) (point-at-eol)))))
20714 (setq beg (funcall skip-blanks (point-at-bol))
20715 end (copy-marker (point-at-eol))))
20716 ;; Ensure inline tasks don't count as headings.
20717 (org-with-limited-levels
20718 (save-excursion
20719 (goto-char beg)
20720 (cond
20721 ;; Case 1. Started at an heading: de-star headings.
20722 ((org-at-heading-p)
20723 (while (< (point) end)
20724 (when (org-at-heading-p t)
20725 (looking-at org-outline-regexp) (replace-match "")
20726 (setq toggled t))
20727 (forward-line)))
20728 ;; Case 2. Started at an item: change items into headlines.
20729 ;; One star will be added by `org-list-to-subtree'.
20730 ((org-at-item-p)
20731 (let* ((stars (make-string
20732 ;; subtract the star that will be added again by
20733 ;; `org-list-to-subtree'
20734 (if (numberp nstars) (1- nstars)
20735 (or (org-current-level) 0))
20736 ?*))
20737 (add-stars
20738 (cond (nstars "") ; stars from prefix only
20739 ((equal stars "") "") ; before first heading
20740 (org-odd-levels-only "*") ; inside heading, odd
20741 (t "")))) ; inside heading, oddeven
20742 (while (< (point) end)
20743 (when (org-at-item-p)
20744 ;; Pay attention to cases when region ends before list.
20745 (let* ((struct (org-list-struct))
20746 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20747 (save-restriction
20748 (narrow-to-region (point) list-end)
20749 (insert
20750 (org-list-to-subtree
20751 (org-list-parse-list t)
20752 '(:istart (concat stars add-stars (funcall get-stars depth))
20753 :icount (concat stars add-stars (funcall get-stars depth)))))))
20754 (setq toggled t))
20755 (forward-line))))
20756 ;; Case 3. Started at normal text: make every line an heading,
20757 ;; skipping headlines and items.
20758 (t (let* ((stars
20759 (make-string
20760 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20761 (add-stars
20762 (cond (nstars "") ; stars from prefix only
20763 ((equal stars "") "*") ; before first heading
20764 (org-odd-levels-only "**") ; inside heading, odd
20765 (t "*"))) ; inside heading, oddeven
20766 (rpl (concat stars add-stars " "))
20767 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20768 (while (< (point) (if (equal nstars '(4)) lend end))
20769 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20770 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20771 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20772 (forward-line)))))))
20773 (unless toggled (message "Cannot toggle heading from here"))))
20774
20775 (defun org-meta-return (&optional arg)
20776 "Insert a new heading or wrap a region in a table.
20777 Calls `org-insert-heading' or `org-table-wrap-region', depending
20778 on context. See the individual commands for more information."
20779 (interactive "P")
20780 (org-check-before-invisible-edit 'insert)
20781 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20782 (let* ((element (org-element-at-point))
20783 (type (org-element-type element)))
20784 (when (eq type 'table-row)
20785 (setq element (org-element-property :parent element))
20786 (setq type 'table))
20787 (if (and (eq type 'table)
20788 (eq (org-element-property :type element) 'org)
20789 (>= (point) (org-element-property :contents-begin element))
20790 (< (point) (org-element-property :contents-end element)))
20791 (call-interactively 'org-table-wrap-region)
20792 (call-interactively 'org-insert-heading)))))
20793
20794 ;;; Menu entries
20795
20796 (defsubst org-in-subtree-not-table-p ()
20797 "Are we in a subtree and not in a table?"
20798 (and (not (org-before-first-heading-p))
20799 (not (org-at-table-p))))
20800
20801 ;; Define the Org-mode menus
20802 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20803 '("Tbl"
20804 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20805 ["Next Field" org-cycle (org-at-table-p)]
20806 ["Previous Field" org-shifttab (org-at-table-p)]
20807 ["Next Row" org-return (org-at-table-p)]
20808 "--"
20809 ["Blank Field" org-table-blank-field (org-at-table-p)]
20810 ["Edit Field" org-table-edit-field (org-at-table-p)]
20811 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20812 "--"
20813 ("Column"
20814 ["Move Column Left" org-metaleft (org-at-table-p)]
20815 ["Move Column Right" org-metaright (org-at-table-p)]
20816 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20817 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20818 ("Row"
20819 ["Move Row Up" org-metaup (org-at-table-p)]
20820 ["Move Row Down" org-metadown (org-at-table-p)]
20821 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20822 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20823 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20824 "--"
20825 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20826 ("Rectangle"
20827 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20828 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20829 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20830 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20831 "--"
20832 ("Calculate"
20833 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20834 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20835 ["Edit Formulas" org-edit-special (org-at-table-p)]
20836 "--"
20837 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20838 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20839 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20840 "--"
20841 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20842 "--"
20843 ["Sum Column/Rectangle" org-table-sum
20844 (or (org-at-table-p) (org-region-active-p))]
20845 ["Which Column?" org-table-current-column (org-at-table-p)])
20846 ["Debug Formulas"
20847 org-table-toggle-formula-debugger
20848 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20849 ["Show Col/Row Numbers"
20850 org-table-toggle-coordinate-overlays
20851 :style toggle
20852 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20853 "--"
20854 ["Create" org-table-create (and (not (org-at-table-p))
20855 org-enable-table-editor)]
20856 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20857 ["Import from File" org-table-import (not (org-at-table-p))]
20858 ["Export to File" org-table-export (org-at-table-p)]
20859 "--"
20860 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20861
20862 (easy-menu-define org-org-menu org-mode-map "Org menu"
20863 '("Org"
20864 ("Show/Hide"
20865 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20866 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20867 ["Sparse Tree..." org-sparse-tree t]
20868 ["Reveal Context" org-reveal t]
20869 ["Show All" show-all t]
20870 "--"
20871 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20872 "--"
20873 ["New Heading" org-insert-heading t]
20874 ("Navigate Headings"
20875 ["Up" outline-up-heading t]
20876 ["Next" outline-next-visible-heading t]
20877 ["Previous" outline-previous-visible-heading t]
20878 ["Next Same Level" outline-forward-same-level t]
20879 ["Previous Same Level" outline-backward-same-level t]
20880 "--"
20881 ["Jump" org-goto t])
20882 ("Edit Structure"
20883 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20884 "--"
20885 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20886 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20887 "--"
20888 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20889 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20890 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20891 "--"
20892 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20893 "--"
20894 ["Copy visible text" org-copy-visible t]
20895 "--"
20896 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20897 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20898 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20899 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20900 "--"
20901 ["Sort Region/Children" org-sort t]
20902 "--"
20903 ["Convert to odd levels" org-convert-to-odd-levels t]
20904 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20905 ("Editing"
20906 ["Emphasis..." org-emphasize t]
20907 ["Edit Source Example" org-edit-special t]
20908 "--"
20909 ["Footnote new/jump" org-footnote-action t]
20910 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20911 ("Archive"
20912 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20913 "--"
20914 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20915 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20916 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20917 )
20918 "--"
20919 ("Hyperlinks"
20920 ["Store Link (Global)" org-store-link t]
20921 ["Find existing link to here" org-occur-link-in-agenda-files t]
20922 ["Insert Link" org-insert-link t]
20923 ["Follow Link" org-open-at-point t]
20924 "--"
20925 ["Next link" org-next-link t]
20926 ["Previous link" org-previous-link t]
20927 "--"
20928 ["Descriptive Links"
20929 org-toggle-link-display
20930 :style radio
20931 :selected org-descriptive-links
20932 ]
20933 ["Literal Links"
20934 org-toggle-link-display
20935 :style radio
20936 :selected (not org-descriptive-links)])
20937 "--"
20938 ("TODO Lists"
20939 ["TODO/DONE/-" org-todo t]
20940 ("Select keyword"
20941 ["Next keyword" org-shiftright (org-at-heading-p)]
20942 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20943 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20944 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20945 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20946 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20947 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20948 "--"
20949 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20950 :selected org-enforce-todo-dependencies :style toggle :active t]
20951 "Settings for tree at point"
20952 ["Do Children sequentially" org-toggle-ordered-property :style radio
20953 :selected (org-entry-get nil "ORDERED")
20954 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20955 ["Do Children parallel" org-toggle-ordered-property :style radio
20956 :selected (not (org-entry-get nil "ORDERED"))
20957 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20958 "--"
20959 ["Set Priority" org-priority t]
20960 ["Priority Up" org-shiftup t]
20961 ["Priority Down" org-shiftdown t]
20962 "--"
20963 ["Get news from all feeds" org-feed-update-all t]
20964 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20965 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20966 ("TAGS and Properties"
20967 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20968 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20969 "--"
20970 ["Set property" org-set-property (not (org-before-first-heading-p))]
20971 ["Column view of properties" org-columns t]
20972 ["Insert Column View DBlock" org-insert-columns-dblock t])
20973 ("Dates and Scheduling"
20974 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20975 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20976 ("Change Date"
20977 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20978 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20979 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20980 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20981 ["Compute Time Range" org-evaluate-time-range t]
20982 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20983 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20984 "--"
20985 ["Custom time format" org-toggle-time-stamp-overlays
20986 :style radio :selected org-display-custom-times]
20987 "--"
20988 ["Goto Calendar" org-goto-calendar t]
20989 ["Date from Calendar" org-date-from-calendar t]
20990 "--"
20991 ["Start/Restart Timer" org-timer-start t]
20992 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20993 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20994 ["Insert Timer String" org-timer t]
20995 ["Insert Timer Item" org-timer-item t])
20996 ("Logging work"
20997 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20998 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20999 ["Clock out" org-clock-out t]
21000 ["Clock cancel" org-clock-cancel t]
21001 "--"
21002 ["Mark as default task" org-clock-mark-default-task t]
21003 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21004 ["Goto running clock" org-clock-goto t]
21005 "--"
21006 ["Display times" org-clock-display t]
21007 ["Create clock table" org-clock-report t]
21008 "--"
21009 ["Record DONE time"
21010 (progn (setq org-log-done (not org-log-done))
21011 (message "Switching to %s will %s record a timestamp"
21012 (car org-done-keywords)
21013 (if org-log-done "automatically" "not")))
21014 :style toggle :selected org-log-done])
21015 "--"
21016 ["Agenda Command..." org-agenda t]
21017 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21018 ("File List for Agenda")
21019 ("Special views current file"
21020 ["TODO Tree" org-show-todo-tree t]
21021 ["Check Deadlines" org-check-deadlines t]
21022 ["Timeline" org-timeline t]
21023 ["Tags/Property tree" org-match-sparse-tree t])
21024 "--"
21025 ["Export/Publish..." org-export-dispatch t]
21026 ("LaTeX"
21027 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21028 :selected org-cdlatex-mode]
21029 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21030 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21031 ["Modify math symbol" org-cdlatex-math-modify
21032 (org-inside-LaTeX-fragment-p)]
21033 ["Insert citation" org-reftex-citation t]
21034 "--"
21035 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21036 "--"
21037 ("MobileOrg"
21038 ["Push Files and Views" org-mobile-push t]
21039 ["Get Captured and Flagged" org-mobile-pull t]
21040 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21041 "--"
21042 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21043 "--"
21044 ("Documentation"
21045 ["Show Version" org-version t]
21046 ["Info Documentation" org-info t])
21047 ("Customize"
21048 ["Browse Org Group" org-customize t]
21049 "--"
21050 ["Expand This Menu" org-create-customize-menu
21051 (fboundp 'customize-menu-create)])
21052 ["Send bug report" org-submit-bug-report t]
21053 "--"
21054 ("Refresh/Reload"
21055 ["Refresh setup current buffer" org-mode-restart t]
21056 ["Reload Org (after update)" org-reload t]
21057 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21058 ))
21059
21060 (defun org-info (&optional node)
21061 "Read documentation for Org-mode in the info system.
21062 With optional NODE, go directly to that node."
21063 (interactive)
21064 (info (format "(org)%s" (or node ""))))
21065
21066 ;;;###autoload
21067 (defun org-submit-bug-report ()
21068 "Submit a bug report on Org-mode via mail.
21069
21070 Don't hesitate to report any problems or inaccurate documentation.
21071
21072 If you don't have setup sending mail from (X)Emacs, please copy the
21073 output buffer into your mail program, as it gives us important
21074 information about your Org-mode version and configuration."
21075 (interactive)
21076 (require 'reporter)
21077 (org-load-modules-maybe)
21078 (org-require-autoloaded-modules)
21079 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21080 (reporter-submit-bug-report
21081 "emacs-orgmode@gnu.org"
21082 (org-version nil 'full)
21083 (let (list)
21084 (save-window-excursion
21085 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21086 (delete-other-windows)
21087 (erase-buffer)
21088 (insert "You are about to submit a bug report to the Org-mode mailing list.
21089
21090 We would like to add your full Org-mode and Outline configuration to the
21091 bug report. This greatly simplifies the work of the maintainer and
21092 other experts on the mailing list.
21093
21094 HOWEVER, some variables you have customized may contain private
21095 information. The names of customers, colleagues, or friends, might
21096 appear in the form of file names, tags, todo states, or search strings.
21097 If you answer yes to the prompt, you might want to check and remove
21098 such private information before sending the email.")
21099 (add-text-properties (point-min) (point-max) '(face org-warning))
21100 (when (yes-or-no-p "Include your Org-mode configuration ")
21101 (mapatoms
21102 (lambda (v)
21103 (and (boundp v)
21104 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21105 (or (and (symbol-value v)
21106 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21107 (and
21108 (get v 'custom-type) (get v 'standard-value)
21109 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21110 (push v list)))))
21111 (kill-buffer (get-buffer "*Warn about privacy*"))
21112 list))
21113 nil nil
21114 "Remember to cover the basics, that is, what you expected to happen and
21115 what in fact did happen. You don't know how to make a good report? See
21116
21117 http://orgmode.org/manual/Feedback.html#Feedback
21118
21119 Your bug report will be posted to the Org-mode mailing list.
21120 ------------------------------------------------------------------------")
21121 (save-excursion
21122 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21123 (replace-match "\\1Bug: \\3 [\\2]")))))
21124
21125
21126 (defun org-install-agenda-files-menu ()
21127 (let ((bl (buffer-list)))
21128 (save-excursion
21129 (while bl
21130 (set-buffer (pop bl))
21131 (if (derived-mode-p 'org-mode) (setq bl nil)))
21132 (when (derived-mode-p 'org-mode)
21133 (easy-menu-change
21134 '("Org") "File List for Agenda"
21135 (append
21136 (list
21137 ["Edit File List" (org-edit-agenda-file-list) t]
21138 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21139 ["Remove Current File from List" org-remove-file t]
21140 ["Cycle through agenda files" org-cycle-agenda-files t]
21141 ["Occur in all agenda files" org-occur-in-agenda-files t]
21142 "--")
21143 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21144
21145 ;;;; Documentation
21146
21147 (defun org-require-autoloaded-modules ()
21148 (interactive)
21149 (mapc 'require
21150 '(org-agenda org-archive org-attach org-clock org-colview org-id
21151 org-table org-timer)))
21152
21153 ;;;###autoload
21154 (defun org-reload (&optional uncompiled)
21155 "Reload all org lisp files.
21156 With prefix arg UNCOMPILED, load the uncompiled versions."
21157 (interactive "P")
21158 (require 'loadhist)
21159 (let* ((org-dir (org-find-library-dir "org"))
21160 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21161 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21162 (remove-re (mapconcat 'identity
21163 (mapcar (lambda (f) (concat "^" f "$"))
21164 (list (if (featurep 'xemacs)
21165 "org-colview"
21166 "org-colview-xemacs")
21167 "org" "org-loaddefs" "org-version"))
21168 "\\|"))
21169 (feats (delete-dups
21170 (mapcar 'file-name-sans-extension
21171 (mapcar 'file-name-nondirectory
21172 (delq nil
21173 (mapcar 'feature-file
21174 features))))))
21175 (lfeat (append
21176 (sort
21177 (setq feats
21178 (delq nil (mapcar
21179 (lambda (f)
21180 (if (and (string-match feature-re f)
21181 (not (string-match remove-re f)))
21182 f nil))
21183 feats)))
21184 'string-lessp)
21185 (list "org-version" "org")))
21186 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21187 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21188 load-uncore load-misses)
21189 (setq load-misses
21190 (delq 't
21191 (mapcar (lambda (f)
21192 (or (org-load-noerror-mustsuffix (concat org-dir f))
21193 (and (string= org-dir contrib-dir)
21194 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21195 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21196 (add-to-list 'load-uncore f 'append)
21197 't)
21198 f))
21199 lfeat)))
21200 (if load-uncore
21201 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21202 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21203 (if load-misses
21204 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21205 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21206 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21207
21208 ;;;###autoload
21209 (defun org-customize ()
21210 "Call the customize function with org as argument."
21211 (interactive)
21212 (org-load-modules-maybe)
21213 (org-require-autoloaded-modules)
21214 (customize-browse 'org))
21215
21216 (defun org-create-customize-menu ()
21217 "Create a full customization menu for Org-mode, insert it into the menu."
21218 (interactive)
21219 (org-load-modules-maybe)
21220 (org-require-autoloaded-modules)
21221 (if (fboundp 'customize-menu-create)
21222 (progn
21223 (easy-menu-change
21224 '("Org") "Customize"
21225 `(["Browse Org group" org-customize t]
21226 "--"
21227 ,(customize-menu-create 'org)
21228 ["Set" Custom-set t]
21229 ["Save" Custom-save t]
21230 ["Reset to Current" Custom-reset-current t]
21231 ["Reset to Saved" Custom-reset-saved t]
21232 ["Reset to Standard Settings" Custom-reset-standard t]))
21233 (message "\"Org\"-menu now contains full customization menu"))
21234 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21235
21236 ;;;; Miscellaneous stuff
21237
21238 ;;; Generally useful functions
21239
21240 (defun org-get-at-bol (property)
21241 "Get text property PROPERTY at beginning of line."
21242 (get-text-property (point-at-bol) property))
21243
21244 (defun org-find-text-property-in-string (prop s)
21245 "Return the first non-nil value of property PROP in string S."
21246 (or (get-text-property 0 prop s)
21247 (get-text-property (or (next-single-property-change 0 prop s) 0)
21248 prop s)))
21249
21250 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21251 "Display the given MESSAGE as a warning."
21252 (if (fboundp 'display-warning)
21253 (display-warning 'org message
21254 (if (featurep 'xemacs) 'warning :warning))
21255 (let ((buf (get-buffer-create "*Org warnings*")))
21256 (with-current-buffer buf
21257 (goto-char (point-max))
21258 (insert "Warning (Org): " message)
21259 (unless (bolp)
21260 (newline)))
21261 (display-buffer buf)
21262 (sit-for 0))))
21263
21264 (defun org-eval (form)
21265 "Eval FORM and return result."
21266 (condition-case error
21267 (eval form)
21268 (error (format "%%![Error: %s]" error))))
21269
21270 (defun org-in-clocktable-p ()
21271 "Check if the cursor is in a clocktable."
21272 (let ((pos (point)) start)
21273 (save-excursion
21274 (end-of-line 1)
21275 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21276 (setq start (match-beginning 0))
21277 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21278 (>= (match-end 0) pos)
21279 start))))
21280
21281 (defun org-in-commented-line ()
21282 "Is point in a line starting with `#'?"
21283 (equal (char-after (point-at-bol)) ?#))
21284
21285 (defun org-in-indented-comment-line ()
21286 "Is point in a line starting with `#' after some white space?"
21287 (save-excursion
21288 (save-match-data
21289 (goto-char (point-at-bol))
21290 (looking-at "[ \t]*#"))))
21291
21292 (defun org-in-verbatim-emphasis ()
21293 (save-match-data
21294 (and (org-in-regexp org-emph-re 2)
21295 (>= (point) (match-beginning 3))
21296 (<= (point) (match-end 4))
21297 (member (match-string 3) '("=" "~")))))
21298
21299 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21300 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21301 (if (and marker (marker-buffer marker)
21302 (buffer-live-p (marker-buffer marker)))
21303 (progn
21304 (org-pop-to-buffer-same-window (marker-buffer marker))
21305 (if (or (> marker (point-max)) (< marker (point-min)))
21306 (widen))
21307 (goto-char marker)
21308 (org-show-context 'org-goto))
21309 (if bookmark
21310 (bookmark-jump bookmark)
21311 (error "Cannot find location"))))
21312
21313 (defun org-quote-csv-field (s)
21314 "Quote field for inclusion in CSV material."
21315 (if (string-match "[\",]" s)
21316 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21317 s))
21318
21319 (defun org-force-self-insert (N)
21320 "Needed to enforce self-insert under remapping."
21321 (interactive "p")
21322 (self-insert-command N))
21323
21324 (defun org-string-width (s)
21325 "Compute width of string, ignoring invisible characters.
21326 This ignores character with invisibility property `org-link', and also
21327 characters with property `org-cwidth', because these will become invisible
21328 upon the next fontification round."
21329 (let (b l)
21330 (when (or (eq t buffer-invisibility-spec)
21331 (assq 'org-link buffer-invisibility-spec))
21332 (while (setq b (text-property-any 0 (length s)
21333 'invisible 'org-link s))
21334 (setq s (concat (substring s 0 b)
21335 (substring s (or (next-single-property-change
21336 b 'invisible s) (length s)))))))
21337 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21338 (setq s (concat (substring s 0 b)
21339 (substring s (or (next-single-property-change
21340 b 'org-cwidth s) (length s))))))
21341 (setq l (string-width s) b -1)
21342 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21343 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21344 l))
21345
21346 (defun org-shorten-string (s maxlength)
21347 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21348 If the string is shorter or has length MAXLENGTH, just return the
21349 original string. If it is longer, the functions finds a space in the
21350 string, breaks this string off at that locations and adds three dots
21351 as ellipsis. Including the ellipsis, the string will not be longer
21352 than MAXLENGTH. If finding a good breaking point in the string does
21353 not work, the string is just chopped off in the middle of a word
21354 if necessary."
21355 (if (<= (length s) maxlength)
21356 s
21357 (let* ((n (max (- maxlength 4) 1))
21358 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21359 (if (string-match re s)
21360 (concat (match-string 1 s) "...")
21361 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21362
21363 (defun org-get-indentation (&optional line)
21364 "Get the indentation of the current line, interpreting tabs.
21365 When LINE is given, assume it represents a line and compute its indentation."
21366 (if line
21367 (if (string-match "^ *" (org-remove-tabs line))
21368 (match-end 0))
21369 (save-excursion
21370 (beginning-of-line 1)
21371 (skip-chars-forward " \t")
21372 (current-column))))
21373
21374 (defun org-get-string-indentation (s)
21375 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21376 (let ((n -1) (i 0) (w tab-width) c)
21377 (catch 'exit
21378 (while (< (setq n (1+ n)) (length s))
21379 (setq c (aref s n))
21380 (cond ((= c ?\ ) (setq i (1+ i)))
21381 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21382 (t (throw 'exit t)))))
21383 i))
21384
21385 (defun org-remove-tabs (s &optional width)
21386 "Replace tabulators in S with spaces.
21387 Assumes that s is a single line, starting in column 0."
21388 (setq width (or width tab-width))
21389 (while (string-match "\t" s)
21390 (setq s (replace-match
21391 (make-string
21392 (- (* width (/ (+ (match-beginning 0) width) width))
21393 (match-beginning 0)) ?\ )
21394 t t s)))
21395 s)
21396
21397 (defun org-fix-indentation (line ind)
21398 "Fix indentation in LINE.
21399 IND is a cons cell with target and minimum indentation.
21400 If the current indentation in LINE is smaller than the minimum,
21401 leave it alone. If it is larger than ind, set it to the target."
21402 (let* ((l (org-remove-tabs line))
21403 (i (org-get-indentation l))
21404 (i1 (car ind)) (i2 (cdr ind)))
21405 (if (>= i i2) (setq l (substring line i2)))
21406 (if (> i1 0)
21407 (concat (make-string i1 ?\ ) l)
21408 l)))
21409
21410 (defun org-remove-indentation (code &optional n)
21411 "Remove the maximum common indentation from the lines in CODE.
21412 N may optionally be the number of spaces to remove."
21413 (with-temp-buffer
21414 (insert code)
21415 (org-do-remove-indentation n)
21416 (buffer-string)))
21417
21418 (defun org-do-remove-indentation (&optional n)
21419 "Remove the maximum common indentation from the buffer."
21420 (untabify (point-min) (point-max))
21421 (let ((min 10000) re)
21422 (if n
21423 (setq min n)
21424 (goto-char (point-min))
21425 (while (re-search-forward "^ *[^ \n]" nil t)
21426 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21427 (unless (or (= min 0) (= min 10000))
21428 (setq re (format "^ \\{%d\\}" min))
21429 (goto-char (point-min))
21430 (while (re-search-forward re nil t)
21431 (replace-match "")
21432 (end-of-line 1))
21433 min)))
21434
21435 (defun org-fill-template (template alist)
21436 "Find each %key of ALIST in TEMPLATE and replace it."
21437 (let ((case-fold-search nil)
21438 entry key value)
21439 (setq alist (sort (copy-sequence alist)
21440 (lambda (a b) (< (length (car a)) (length (car b))))))
21441 (while (setq entry (pop alist))
21442 (setq template
21443 (replace-regexp-in-string
21444 (concat "%" (regexp-quote (car entry)))
21445 (or (cdr entry) "") template t t)))
21446 template))
21447
21448 (defun org-base-buffer (buffer)
21449 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21450 (if (not buffer)
21451 buffer
21452 (or (buffer-base-buffer buffer)
21453 buffer)))
21454
21455 (defun org-trim (s)
21456 "Remove whitespace at beginning and end of string."
21457 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21458 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21459 s)
21460
21461 (defun org-wrap (string &optional width lines)
21462 "Wrap string to either a number of lines, or a width in characters.
21463 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21464 that costs. If there is a word longer than WIDTH, the text is actually
21465 wrapped to the length of that word.
21466 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21467 many lines, whatever width that takes.
21468 The return value is a list of lines, without newlines at the end."
21469 (let* ((words (org-split-string string "[ \t\n]+"))
21470 (maxword (apply 'max (mapcar 'org-string-width words)))
21471 w ll)
21472 (cond (width
21473 (org-do-wrap words (max maxword width)))
21474 (lines
21475 (setq w maxword)
21476 (setq ll (org-do-wrap words maxword))
21477 (if (<= (length ll) lines)
21478 ll
21479 (setq ll words)
21480 (while (> (length ll) lines)
21481 (setq w (1+ w))
21482 (setq ll (org-do-wrap words w)))
21483 ll))
21484 (t (error "Cannot wrap this")))))
21485
21486 (defun org-do-wrap (words width)
21487 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21488 (let (lines line)
21489 (while words
21490 (setq line (pop words))
21491 (while (and words (< (+ (length line) (length (car words))) width))
21492 (setq line (concat line " " (pop words))))
21493 (setq lines (push line lines)))
21494 (nreverse lines)))
21495
21496 (defun org-split-string (string &optional separators)
21497 "Splits STRING into substrings at SEPARATORS.
21498 No empty strings are returned if there are matches at the beginning
21499 and end of string."
21500 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21501 (start 0)
21502 notfirst
21503 (list nil))
21504 (while (and (string-match rexp string
21505 (if (and notfirst
21506 (= start (match-beginning 0))
21507 (< start (length string)))
21508 (1+ start) start))
21509 (< (match-beginning 0) (length string)))
21510 (setq notfirst t)
21511 (or (eq (match-beginning 0) 0)
21512 (and (eq (match-beginning 0) (match-end 0))
21513 (eq (match-beginning 0) start))
21514 (setq list
21515 (cons (substring string start (match-beginning 0))
21516 list)))
21517 (setq start (match-end 0)))
21518 (or (eq start (length string))
21519 (setq list
21520 (cons (substring string start)
21521 list)))
21522 (nreverse list)))
21523
21524 (defun org-quote-vert (s)
21525 "Replace \"|\" with \"\\vert\"."
21526 (while (string-match "|" s)
21527 (setq s (replace-match "\\vert" t t s)))
21528 s)
21529
21530 (defun org-uuidgen-p (s)
21531 "Is S an ID created by UUIDGEN?"
21532 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21533
21534 (defun org-in-src-block-p (&optional inside)
21535 "Whether point is in a code source block.
21536 When INSIDE is non-nil, don't consider we are within a src block
21537 when point is at #+BEGIN_SRC or #+END_SRC."
21538 (let ((case-fold-search t) ov)
21539 (or (and (setq ov (overlays-at (point)))
21540 (memq 'org-block-background
21541 (overlay-properties (car ov))))
21542 (and (not inside)
21543 (save-match-data
21544 (save-excursion
21545 (beginning-of-line)
21546 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21547
21548 (defun org-context ()
21549 "Return a list of contexts of the current cursor position.
21550 If several contexts apply, all are returned.
21551 Each context entry is a list with a symbol naming the context, and
21552 two positions indicating start and end of the context. Possible
21553 contexts are:
21554
21555 :headline anywhere in a headline
21556 :headline-stars on the leading stars in a headline
21557 :todo-keyword on a TODO keyword (including DONE) in a headline
21558 :tags on the TAGS in a headline
21559 :priority on the priority cookie in a headline
21560 :item on the first line of a plain list item
21561 :item-bullet on the bullet/number of a plain list item
21562 :checkbox on the checkbox in a plain list item
21563 :table in an org-mode table
21564 :table-special on a special filed in a table
21565 :table-table in a table.el table
21566 :clocktable in a clocktable
21567 :src-block in a source block
21568 :link on a hyperlink
21569 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21570 :target on a <<target>>
21571 :radio-target on a <<<radio-target>>>
21572 :latex-fragment on a LaTeX fragment
21573 :latex-preview on a LaTeX fragment with overlaid preview image
21574
21575 This function expects the position to be visible because it uses font-lock
21576 faces as a help to recognize the following contexts: :table-special, :link,
21577 and :keyword."
21578 (let* ((f (get-text-property (point) 'face))
21579 (faces (if (listp f) f (list f)))
21580 (case-fold-search t)
21581 (p (point)) clist o)
21582 ;; First the large context
21583 (cond
21584 ((org-at-heading-p t)
21585 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21586 (when (progn
21587 (beginning-of-line 1)
21588 (looking-at org-todo-line-tags-regexp))
21589 (push (org-point-in-group p 1 :headline-stars) clist)
21590 (push (org-point-in-group p 2 :todo-keyword) clist)
21591 (push (org-point-in-group p 4 :tags) clist))
21592 (goto-char p)
21593 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21594 (if (looking-at "\\[#[A-Z0-9]\\]")
21595 (push (org-point-in-group p 0 :priority) clist)))
21596
21597 ((org-at-item-p)
21598 (push (org-point-in-group p 2 :item-bullet) clist)
21599 (push (list :item (point-at-bol)
21600 (save-excursion (org-end-of-item) (point)))
21601 clist)
21602 (and (org-at-item-checkbox-p)
21603 (push (org-point-in-group p 0 :checkbox) clist)))
21604
21605 ((org-at-table-p)
21606 (push (list :table (org-table-begin) (org-table-end)) clist)
21607 (if (memq 'org-formula faces)
21608 (push (list :table-special
21609 (previous-single-property-change p 'face)
21610 (next-single-property-change p 'face)) clist)))
21611 ((org-at-table-p 'any)
21612 (push (list :table-table) clist)))
21613 (goto-char p)
21614
21615 (let ((case-fold-search t))
21616 ;; New the "medium" contexts: clocktables, source blocks
21617 (cond ((org-in-clocktable-p)
21618 (push (list :clocktable
21619 (and (or (looking-at "#\\+BEGIN: clocktable")
21620 (search-backward "#+BEGIN: clocktable" nil t))
21621 (match-beginning 0))
21622 (and (re-search-forward "#\\+END:?" nil t)
21623 (match-end 0))) clist))
21624 ((org-in-src-block-p)
21625 (push (list :src-block
21626 (and (or (looking-at "#\\+BEGIN_SRC")
21627 (search-backward "#+BEGIN_SRC" nil t))
21628 (match-beginning 0))
21629 (and (search-forward "#+END_SRC" nil t)
21630 (match-beginning 0))) clist))))
21631 (goto-char p)
21632
21633 ;; Now the small context
21634 (cond
21635 ((org-at-timestamp-p)
21636 (push (org-point-in-group p 0 :timestamp) clist))
21637 ((memq 'org-link faces)
21638 (push (list :link
21639 (previous-single-property-change p 'face)
21640 (next-single-property-change p 'face)) clist))
21641 ((memq 'org-special-keyword faces)
21642 (push (list :keyword
21643 (previous-single-property-change p 'face)
21644 (next-single-property-change p 'face)) clist))
21645 ((org-at-target-p)
21646 (push (org-point-in-group p 0 :target) clist)
21647 (goto-char (1- (match-beginning 0)))
21648 (if (looking-at org-radio-target-regexp)
21649 (push (org-point-in-group p 0 :radio-target) clist))
21650 (goto-char p))
21651 ((setq o (car (delq nil
21652 (mapcar
21653 (lambda (x)
21654 (if (memq x org-latex-fragment-image-overlays) x))
21655 (overlays-at (point))))))
21656 (push (list :latex-fragment
21657 (overlay-start o) (overlay-end o)) clist)
21658 (push (list :latex-preview
21659 (overlay-start o) (overlay-end o)) clist))
21660 ((org-inside-LaTeX-fragment-p)
21661 ;; FIXME: positions wrong.
21662 (push (list :latex-fragment (point) (point)) clist)))
21663
21664 (setq clist (nreverse (delq nil clist)))
21665 clist))
21666
21667 ;; FIXME: Compare with at-regexp-p Do we need both?
21668 (defun org-in-regexp (re &optional nlines visually)
21669 "Check if point is inside a match of regexp.
21670 Normally only the current line is checked, but you can include NLINES extra
21671 lines both before and after point into the search.
21672 If VISUALLY is set, require that the cursor is not after the match but
21673 really on, so that the block visually is on the match."
21674 (catch 'exit
21675 (let ((pos (point))
21676 (eol (point-at-eol (+ 1 (or nlines 0))))
21677 (inc (if visually 1 0)))
21678 (save-excursion
21679 (beginning-of-line (- 1 (or nlines 0)))
21680 (while (re-search-forward re eol t)
21681 (if (and (<= (match-beginning 0) pos)
21682 (>= (+ inc (match-end 0)) pos))
21683 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21684
21685 (defun org-at-regexp-p (regexp)
21686 "Is point inside a match of REGEXP in the current line?"
21687 (catch 'exit
21688 (save-excursion
21689 (let ((pos (point)) (end (point-at-eol)))
21690 (beginning-of-line 1)
21691 (while (re-search-forward regexp end t)
21692 (if (and (<= (match-beginning 0) pos)
21693 (>= (match-end 0) pos))
21694 (throw 'exit t)))
21695 nil))))
21696
21697 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21698 "Non-nil when point is between matches of START-RE and END-RE.
21699
21700 Also return a non-nil value when point is on one of the matches.
21701
21702 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21703 buffer positions. Default values are the positions of headlines
21704 surrounding the point.
21705
21706 The functions returns a cons cell whose car (resp. cdr) is the
21707 position before START-RE (resp. after END-RE)."
21708 (save-match-data
21709 (let ((pos (point))
21710 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21711 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21712 beg end)
21713 (save-excursion
21714 ;; Point is on a block when on START-RE or if START-RE can be
21715 ;; found before it...
21716 (and (or (org-at-regexp-p start-re)
21717 (re-search-backward start-re limit-up t))
21718 (setq beg (match-beginning 0))
21719 ;; ... and END-RE after it...
21720 (goto-char (match-end 0))
21721 (re-search-forward end-re limit-down t)
21722 (> (setq end (match-end 0)) pos)
21723 ;; ... without another START-RE in-between.
21724 (goto-char (match-beginning 0))
21725 (not (re-search-backward start-re (1+ beg) t))
21726 ;; Return value.
21727 (cons beg end))))))
21728
21729 (defun org-in-block-p (names)
21730 "Non-nil when point belongs to a block whose name belongs to NAMES.
21731
21732 NAMES is a list of strings containing names of blocks.
21733
21734 Return first block name matched, or nil. Beware that in case of
21735 nested blocks, the returned name may not belong to the closest
21736 block from point."
21737 (save-match-data
21738 (catch 'exit
21739 (let ((case-fold-search t)
21740 (lim-up (save-excursion (outline-previous-heading)))
21741 (lim-down (save-excursion (outline-next-heading))))
21742 (mapc (lambda (name)
21743 (let ((n (regexp-quote name)))
21744 (when (org-between-regexps-p
21745 (concat "^[ \t]*#\\+begin_" n)
21746 (concat "^[ \t]*#\\+end_" n)
21747 lim-up lim-down)
21748 (throw 'exit n))))
21749 names))
21750 nil)))
21751
21752 (defun org-in-drawer-p ()
21753 "Is point within a drawer?"
21754 (save-match-data
21755 (let ((case-fold-search t)
21756 (lim-up (save-excursion (outline-previous-heading)))
21757 (lim-down (save-excursion (outline-next-heading))))
21758 (org-between-regexps-p
21759 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21760 "^[ \t]*:end:.*$"
21761 lim-up lim-down))))
21762
21763 (defun org-occur-in-agenda-files (regexp &optional nlines)
21764 "Call `multi-occur' with buffers for all agenda files."
21765 (interactive "sOrg-files matching: \np")
21766 (let* ((files (org-agenda-files))
21767 (tnames (mapcar 'file-truename files))
21768 (extra org-agenda-text-search-extra-files)
21769 f)
21770 (when (eq (car extra) 'agenda-archives)
21771 (setq extra (cdr extra))
21772 (setq files (org-add-archive-files files)))
21773 (while (setq f (pop extra))
21774 (unless (member (file-truename f) tnames)
21775 (add-to-list 'files f 'append)
21776 (add-to-list 'tnames (file-truename f) 'append)))
21777 (multi-occur
21778 (mapcar (lambda (x)
21779 (with-current-buffer
21780 (or (get-file-buffer x) (find-file-noselect x))
21781 (widen)
21782 (current-buffer)))
21783 files)
21784 regexp)))
21785
21786 (if (boundp 'occur-mode-find-occurrence-hook)
21787 ;; Emacs 23
21788 (add-hook 'occur-mode-find-occurrence-hook
21789 (lambda ()
21790 (when (derived-mode-p 'org-mode)
21791 (org-reveal))))
21792 ;; Emacs 22
21793 (defadvice occur-mode-goto-occurrence
21794 (after org-occur-reveal activate)
21795 (and (derived-mode-p 'org-mode) (org-reveal)))
21796 (defadvice occur-mode-goto-occurrence-other-window
21797 (after org-occur-reveal activate)
21798 (and (derived-mode-p 'org-mode) (org-reveal)))
21799 (defadvice occur-mode-display-occurrence
21800 (after org-occur-reveal activate)
21801 (when (derived-mode-p 'org-mode)
21802 (let ((pos (occur-mode-find-occurrence)))
21803 (with-current-buffer (marker-buffer pos)
21804 (save-excursion
21805 (goto-char pos)
21806 (org-reveal)))))))
21807
21808 (defun org-occur-link-in-agenda-files ()
21809 "Create a link and search for it in the agendas.
21810 The link is not stored in `org-stored-links', it is just created
21811 for the search purpose."
21812 (interactive)
21813 (let ((link (condition-case nil
21814 (org-store-link nil)
21815 (error "Unable to create a link to here"))))
21816 (org-occur-in-agenda-files (regexp-quote link))))
21817
21818 (defun org-reverse-string (string)
21819 "Return the reverse of STRING."
21820 (apply 'string (reverse (string-to-list string))))
21821
21822 (defsubst org-uniquify (list)
21823 "Non-destructively remove duplicate elements from LIST."
21824 (let ((res (copy-sequence list))) (delete-dups res)))
21825
21826 (defun org-uniquify-alist (alist)
21827 "Merge elements of ALIST with the same key.
21828
21829 For example, in this alist:
21830
21831 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21832 => '((a 1 3) (b 2))
21833
21834 merge (a 1) and (a 3) into (a 1 3).
21835
21836 The function returns the new ALIST."
21837 (let (rtn)
21838 (mapc
21839 (lambda (e)
21840 (let (n)
21841 (if (not (assoc (car e) rtn))
21842 (push e rtn)
21843 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21844 (setq rtn (assq-delete-all (car e) rtn))
21845 (push n rtn))))
21846 alist)
21847 rtn))
21848
21849 (defun org-delete-all (elts list)
21850 "Remove all elements in ELTS from LIST."
21851 (while elts
21852 (setq list (delete (pop elts) list)))
21853 list)
21854
21855 (defun org-count (cl-item cl-seq)
21856 "Count the number of occurrences of ITEM in SEQ.
21857 Taken from `count' in cl-seq.el with all keyword arguments removed."
21858 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21859 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21860 (while (< cl-start cl-end)
21861 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21862 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21863 (setq cl-start (1+ cl-start)))
21864 cl-count))
21865
21866 (defun org-remove-if (predicate seq)
21867 "Remove everything from SEQ that fulfills PREDICATE."
21868 (let (res e)
21869 (while seq
21870 (setq e (pop seq))
21871 (if (not (funcall predicate e)) (push e res)))
21872 (nreverse res)))
21873
21874 (defun org-remove-if-not (predicate seq)
21875 "Remove everything from SEQ that does not fulfill PREDICATE."
21876 (let (res e)
21877 (while seq
21878 (setq e (pop seq))
21879 (if (funcall predicate e) (push e res)))
21880 (nreverse res)))
21881
21882 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21883 "Reduce two-argument FUNCTION across SEQ.
21884 Taken from `reduce' in cl-seq.el with all keyword arguments but
21885 \":initial-value\" removed."
21886 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21887 (cadr (memq :initial-value cl-keys)))
21888 (cl-seq (pop cl-seq))
21889 (t (funcall cl-func)))))
21890 (while cl-seq
21891 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21892 cl-accum))
21893
21894 (defun org-every (pred seq)
21895 "Return true if PREDICATE is true of every element of SEQ.
21896 Adapted from `every' in cl.el."
21897 (catch 'org-every
21898 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21899 t))
21900
21901 (defun org-some (pred seq)
21902 "Return true if PREDICATE is true of any element of SEQ.
21903 Adapted from `some' in cl.el."
21904 (catch 'org-some
21905 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21906 nil))
21907
21908 (defun org-back-over-empty-lines ()
21909 "Move backwards over whitespace, to the beginning of the first empty line.
21910 Returns the number of empty lines passed."
21911 (let ((pos (point)))
21912 (if (cdr (assoc 'heading org-blank-before-new-entry))
21913 (skip-chars-backward " \t\n\r")
21914 (unless (eobp)
21915 (forward-line -1)))
21916 (beginning-of-line 2)
21917 (goto-char (min (point) pos))
21918 (count-lines (point) pos)))
21919
21920 (defun org-skip-whitespace ()
21921 (skip-chars-forward " \t\n\r"))
21922
21923 (defun org-point-in-group (point group &optional context)
21924 "Check if POINT is in match-group GROUP.
21925 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21926 match. If the match group does not exist or point is not inside it,
21927 return nil."
21928 (and (match-beginning group)
21929 (>= point (match-beginning group))
21930 (<= point (match-end group))
21931 (if context
21932 (list context (match-beginning group) (match-end group))
21933 t)))
21934
21935 (defun org-switch-to-buffer-other-window (&rest args)
21936 "Switch to buffer in a second window on the current frame.
21937 In particular, do not allow pop-up frames.
21938 Returns the newly created buffer."
21939 (org-no-popups
21940 (apply 'switch-to-buffer-other-window args)))
21941
21942 (defun org-combine-plists (&rest plists)
21943 "Create a single property list from all plists in PLISTS.
21944 The process starts by copying the first list, and then setting properties
21945 from the other lists. Settings in the last list are the most significant
21946 ones and overrule settings in the other lists."
21947 (let ((rtn (copy-sequence (pop plists)))
21948 p v ls)
21949 (while plists
21950 (setq ls (pop plists))
21951 (while ls
21952 (setq p (pop ls) v (pop ls))
21953 (setq rtn (plist-put rtn p v))))
21954 rtn))
21955
21956 (defun org-replace-escapes (string table)
21957 "Replace %-escapes in STRING with values in TABLE.
21958 TABLE is an association list with keys like \"%a\" and string values.
21959 The sequences in STRING may contain normal field width and padding information,
21960 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21961 so values can contain further %-escapes if they are define later in TABLE."
21962 (let ((tbl (copy-alist table))
21963 (case-fold-search nil)
21964 (pchg 0)
21965 e re rpl)
21966 (while (setq e (pop tbl))
21967 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21968 (when (and (cdr e) (string-match re (cdr e)))
21969 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21970 (safe "SREF"))
21971 (add-text-properties 0 3 (list 'sref sref) safe)
21972 (setcdr e (replace-match safe t t (cdr e)))))
21973 (while (string-match re string)
21974 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21975 (cdr e)))
21976 (setq string (replace-match rpl t t string))))
21977 (while (setq pchg (next-property-change pchg string))
21978 (let ((sref (get-text-property pchg 'sref string)))
21979 (when (and sref (string-match "SREF" string pchg))
21980 (setq string (replace-match sref t t string)))))
21981 string))
21982
21983 (defun org-sublist (list start end)
21984 "Return a section of LIST, from START to END.
21985 Counting starts at 1."
21986 (let (rtn (c start))
21987 (setq list (nthcdr (1- start) list))
21988 (while (and list (<= c end))
21989 (push (pop list) rtn)
21990 (setq c (1+ c)))
21991 (nreverse rtn)))
21992
21993 (defun org-find-base-buffer-visiting (file)
21994 "Like `find-buffer-visiting' but always return the base buffer and
21995 not an indirect buffer."
21996 (let ((buf (or (get-file-buffer file)
21997 (find-buffer-visiting file))))
21998 (if buf
21999 (or (buffer-base-buffer buf) buf)
22000 nil)))
22001
22002 (defun org-image-file-name-regexp (&optional extensions)
22003 "Return regexp matching the file names of images.
22004 If EXTENSIONS is given, only match these."
22005 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22006 (image-file-name-regexp)
22007 (let ((image-file-name-extensions
22008 (or extensions
22009 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22010 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22011 (concat "\\."
22012 (regexp-opt (nconc (mapcar 'upcase
22013 image-file-name-extensions)
22014 image-file-name-extensions)
22015 t)
22016 "\\'"))))
22017
22018 (defun org-file-image-p (file &optional extensions)
22019 "Return non-nil if FILE is an image."
22020 (save-match-data
22021 (string-match (org-image-file-name-regexp extensions) file)))
22022
22023 (defun org-get-cursor-date (&optional with-time)
22024 "Return the date at cursor in as a time.
22025 This works in the calendar and in the agenda, anywhere else it just
22026 returns the current time.
22027 If WITH-TIME is non-nil, returns the time of the event at point (in
22028 the agenda) or the current time of the day."
22029 (let (date day defd tp tm hod mod)
22030 (when with-time
22031 (setq tp (get-text-property (point) 'time))
22032 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22033 (setq hod (string-to-number (match-string 1 tp))
22034 mod (string-to-number (match-string 2 tp))))
22035 (or tp (setq hod (nth 2 (decode-time (current-time)))
22036 mod (nth 1 (decode-time (current-time))))))
22037 (cond
22038 ((eq major-mode 'calendar-mode)
22039 (setq date (calendar-cursor-to-date)
22040 defd (encode-time 0 (or mod 0) (or hod 0)
22041 (nth 1 date) (nth 0 date) (nth 2 date))))
22042 ((eq major-mode 'org-agenda-mode)
22043 (setq day (get-text-property (point) 'day))
22044 (if day
22045 (setq date (calendar-gregorian-from-absolute day)
22046 defd (encode-time 0 (or mod 0) (or hod 0)
22047 (nth 1 date) (nth 0 date) (nth 2 date))))))
22048 (or defd (current-time))))
22049
22050 (defun org-mark-subtree (&optional up)
22051 "Mark the current subtree.
22052 This puts point at the start of the current subtree, and mark at
22053 the end. If a numeric prefix UP is given, move up into the
22054 hierarchy of headlines by UP levels before marking the subtree."
22055 (interactive "P")
22056 (org-with-limited-levels
22057 (cond ((org-at-heading-p) (beginning-of-line))
22058 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22059 (t (outline-previous-visible-heading 1))))
22060 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22061 (if (org-called-interactively-p 'any)
22062 (call-interactively 'org-mark-element)
22063 (org-mark-element)))
22064
22065
22066 ;;; Indentation
22067
22068 (defun org-indent-line ()
22069 "Indent line depending on context."
22070 (interactive)
22071 (let* ((pos (point))
22072 (itemp (org-at-item-p))
22073 (case-fold-search t)
22074 (org-drawer-regexp (or org-drawer-regexp "\000"))
22075 (inline-task-p (and (featurep 'org-inlinetask)
22076 (org-inlinetask-in-task-p)))
22077 (inline-re (and inline-task-p
22078 (org-inlinetask-outline-regexp)))
22079 column)
22080 (if (and orgstruct-is-++ (eq pos (point)))
22081 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22082 (indent-according-to-mode))
22083 (beginning-of-line 1)
22084 (cond
22085 ;; Headings
22086 ((looking-at org-outline-regexp) (setq column 0))
22087 ;; Footnote definition
22088 ((looking-at org-footnote-definition-re) (setq column 0))
22089 ;; Literal examples
22090 ((looking-at "[ \t]*:\\( \\|$\\)")
22091 (setq column (org-get-indentation))) ; do nothing
22092 ;; Lists
22093 ((ignore-errors (goto-char (org-in-item-p)))
22094 (setq column (if itemp
22095 (org-get-indentation)
22096 (org-list-item-body-column (point))))
22097 (goto-char pos))
22098 ;; Drawers
22099 ((and (looking-at "[ \t]*:END:")
22100 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22101 (save-excursion
22102 (goto-char (1- (match-beginning 1)))
22103 (setq column (current-column))))
22104 ;; Special blocks
22105 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22106 (save-excursion
22107 (re-search-backward
22108 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22109 (setq column (org-get-indentation (match-string 0))))
22110 ((and (not (looking-at "[ \t]*#\\+begin_"))
22111 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22112 (save-excursion
22113 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22114 (setq column
22115 (cond ((equal (downcase (match-string 1)) "src")
22116 ;; src blocks: let `org-edit-src-exit' handle them
22117 (org-get-indentation))
22118 ((equal (downcase (match-string 1)) "example")
22119 (max (org-get-indentation)
22120 (org-get-indentation (match-string 0))))
22121 (t
22122 (org-get-indentation (match-string 0))))))
22123 ;; This line has nothing special, look at the previous relevant
22124 ;; line to compute indentation
22125 (t
22126 (beginning-of-line 0)
22127 (while (and (not (bobp))
22128 (not (looking-at org-table-line-regexp))
22129 (not (looking-at org-drawer-regexp))
22130 ;; When point started in an inline task, do not move
22131 ;; above task starting line.
22132 (not (and inline-task-p (looking-at inline-re)))
22133 ;; Skip drawers, blocks, empty lines, verbatim,
22134 ;; comments, tables, footnotes definitions, lists,
22135 ;; inline tasks.
22136 (or (and (looking-at "[ \t]*:END:")
22137 (re-search-backward org-drawer-regexp nil t))
22138 (and (looking-at "[ \t]*#\\+end_")
22139 (re-search-backward "[ \t]*#\\+begin_"nil t))
22140 (looking-at "[ \t]*[\n:#|]")
22141 (looking-at org-footnote-definition-re)
22142 (and (not inline-task-p)
22143 (featurep 'org-inlinetask)
22144 (org-inlinetask-in-task-p)
22145 (or (org-inlinetask-goto-beginning) t))))
22146 (beginning-of-line 0))
22147 (cond
22148 ;; There was a list item above.
22149 ((ignore-errors (goto-char (org-in-item-p)))
22150 (goto-char (org-list-get-top-point (org-list-struct)))
22151 (setq column (org-get-indentation)))
22152 ;; There was an heading above.
22153 ((looking-at "\\*+[ \t]+")
22154 (if (not org-adapt-indentation)
22155 (setq column 0)
22156 (goto-char (match-end 0))
22157 (setq column (current-column))))
22158 ;; A drawer had started and is unfinished
22159 ((looking-at org-drawer-regexp)
22160 (goto-char (1- (match-beginning 1)))
22161 (setq column (current-column)))
22162 ;; Else, nothing noticeable found: get indentation and go on.
22163 (t (setq column (org-get-indentation))))))
22164 ;; Now apply indentation and move cursor accordingly
22165 (goto-char pos)
22166 (if (<= (current-column) (current-indentation))
22167 (org-indent-line-to column)
22168 (save-excursion (org-indent-line-to column)))
22169 ;; Special polishing for properties, see `org-property-format'
22170 (setq column (current-column))
22171 (beginning-of-line 1)
22172 (if (looking-at org-property-re)
22173 (replace-match (concat (match-string 4)
22174 (format org-property-format
22175 (match-string 1) (match-string 3)))
22176 t t))
22177 (org-move-to-column column))))
22178
22179 (defun org-indent-drawer ()
22180 "Indent the drawer at point."
22181 (interactive)
22182 (let ((p (point))
22183 (e (and (save-excursion (re-search-forward ":END:" nil t))
22184 (match-end 0)))
22185 (folded
22186 (save-excursion
22187 (end-of-line)
22188 (when (overlays-at (point))
22189 (member 'invisible (overlay-properties
22190 (car (overlays-at (point)))))))))
22191 (when folded (org-cycle))
22192 (indent-for-tab-command)
22193 (while (and (move-beginning-of-line 2) (< (point) e))
22194 (indent-for-tab-command))
22195 (goto-char p)
22196 (when folded (org-cycle)))
22197 (message "Drawer at point indented"))
22198
22199 (defun org-indent-block ()
22200 "Indent the block at point."
22201 (interactive)
22202 (let ((p (point))
22203 (case-fold-search t)
22204 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22205 (match-end 0)))
22206 (folded
22207 (save-excursion
22208 (end-of-line)
22209 (when (overlays-at (point))
22210 (member 'invisible (overlay-properties
22211 (car (overlays-at (point)))))))))
22212 (when folded (org-cycle))
22213 (indent-for-tab-command)
22214 (while (and (move-beginning-of-line 2) (< (point) e))
22215 (indent-for-tab-command))
22216 (goto-char p)
22217 (when folded (org-cycle)))
22218 (message "Block at point indented"))
22219
22220 (defun org-indent-region (start end)
22221 "Indent region."
22222 (interactive "r")
22223 (save-excursion
22224 (let ((line-end (org-current-line end)))
22225 (goto-char start)
22226 (while (< (org-current-line) line-end)
22227 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22228 (t (call-interactively 'org-indent-line)))
22229 (move-beginning-of-line 2)))))
22230
22231
22232 ;;; Filling
22233
22234 ;; We use our own fill-paragraph and auto-fill functions.
22235
22236 ;; `org-fill-paragraph' relies on adaptive filling and context
22237 ;; checking. Appropriate `fill-prefix' is computed with
22238 ;; `org-adaptive-fill-function'.
22239
22240 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22241 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22242 ;; `org-adaptive-fill-function' value. Internally,
22243 ;; `org-comment-line-break-function' breaks the line.
22244
22245 ;; `org-setup-filling' installs filling and auto-filling related
22246 ;; variables during `org-mode' initialization.
22247
22248 (defvar org-element-paragraph-separate) ; org-element.el
22249 (defun org-setup-filling ()
22250 (require 'org-element)
22251 ;; Prevent auto-fill from inserting unwanted new items.
22252 (when (boundp 'fill-nobreak-predicate)
22253 (org-set-local
22254 'fill-nobreak-predicate
22255 (org-uniquify
22256 (append fill-nobreak-predicate
22257 '(org-fill-line-break-nobreak-p
22258 org-fill-paragraph-with-timestamp-nobreak-p)))))
22259 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22260 (org-set-local 'paragraph-start paragraph-ending)
22261 (org-set-local 'paragraph-separate paragraph-ending))
22262 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22263 (org-set-local 'auto-fill-inhibit-regexp nil)
22264 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22265 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22266 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22267
22268 (defun org-fill-line-break-nobreak-p ()
22269 "Non-nil when a new line at point would create an Org line break."
22270 (save-excursion
22271 (skip-chars-backward "[ \t]")
22272 (skip-chars-backward "\\\\")
22273 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22274
22275 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22276 "Non-nil when a new line at point would split a timestamp."
22277 (and (org-at-timestamp-p t)
22278 (not (looking-at org-ts-regexp-both))))
22279
22280 (declare-function message-in-body-p "message" ())
22281 (defvar orgtbl-line-start-regexp) ; From org-table.el
22282 (defun org-adaptive-fill-function ()
22283 "Compute a fill prefix for the current line.
22284 Return fill prefix, as a string, or nil if current line isn't
22285 meant to be filled. For convenience, if `adaptive-fill-regexp'
22286 matches in paragraphs or comments, use it."
22287 (catch 'exit
22288 (when (derived-mode-p 'message-mode)
22289 (save-excursion
22290 (beginning-of-line)
22291 (cond ((or (not (message-in-body-p))
22292 (looking-at orgtbl-line-start-regexp))
22293 (throw 'exit nil))
22294 ((looking-at message-cite-prefix-regexp)
22295 (throw 'exit (match-string-no-properties 0)))
22296 ((looking-at org-outline-regexp)
22297 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22298 (org-with-wide-buffer
22299 (let* ((p (line-beginning-position))
22300 (element (save-excursion
22301 (beginning-of-line)
22302 (or (ignore-errors (org-element-at-point))
22303 (user-error "An element cannot be parsed line %d"
22304 (line-number-at-pos (point))))))
22305 (type (org-element-type element))
22306 (post-affiliated (org-element-property :post-affiliated element)))
22307 (unless (and post-affiliated (< p post-affiliated))
22308 (case type
22309 (comment
22310 (save-excursion
22311 (beginning-of-line)
22312 (looking-at "[ \t]*")
22313 (concat (match-string 0) "# ")))
22314 (footnote-definition "")
22315 ((item plain-list)
22316 (make-string (org-list-item-body-column
22317 (or post-affiliated
22318 (org-element-property :begin element)))
22319 ? ))
22320 (paragraph
22321 ;; Fill prefix is usually the same as the current line,
22322 ;; unless the paragraph is at the beginning of an item.
22323 (let ((parent (org-element-property :parent element)))
22324 (save-excursion
22325 (beginning-of-line)
22326 (cond ((eq (org-element-type parent) 'item)
22327 (make-string (org-list-item-body-column
22328 (org-element-property :begin parent))
22329 ? ))
22330 ((and adaptive-fill-regexp
22331 ;; Locally disable
22332 ;; `adaptive-fill-function' to let
22333 ;; `fill-context-prefix' handle
22334 ;; `adaptive-fill-regexp' variable.
22335 (let (adaptive-fill-function)
22336 (fill-context-prefix
22337 post-affiliated
22338 (org-element-property :end element)))))
22339 ((looking-at "[ \t]+") (match-string 0))
22340 (t "")))))
22341 (comment-block
22342 ;; Only fill contents if P is within block boundaries.
22343 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22344 (forward-line)
22345 (point)))
22346 (cend (save-excursion
22347 (goto-char (org-element-property :end element))
22348 (skip-chars-backward " \r\t\n")
22349 (line-beginning-position))))
22350 (when (and (>= p cbeg) (< p cend))
22351 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22352 (match-string 0)
22353 ""))))))))))
22354
22355 (declare-function message-goto-body "message" ())
22356 (defvar message-cite-prefix-regexp) ; From message.el
22357 (defun org-fill-paragraph (&optional justify)
22358 "Fill element at point, when applicable.
22359
22360 This function only applies to comment blocks, comments, example
22361 blocks and paragraphs. Also, as a special case, re-align table
22362 when point is at one.
22363
22364 If JUSTIFY is non-nil (interactively, with prefix argument),
22365 justify as well. If `sentence-end-double-space' is non-nil, then
22366 period followed by one space does not end a sentence, so don't
22367 break a line there. The variable `fill-column' controls the
22368 width for filling.
22369
22370 For convenience, when point is at a plain list, an item or
22371 a footnote definition, try to fill the first paragraph within."
22372 (interactive)
22373 (if (and (derived-mode-p 'message-mode)
22374 (or (not (message-in-body-p))
22375 (save-excursion (move-beginning-of-line 1)
22376 (looking-at message-cite-prefix-regexp))))
22377 ;; First ensure filling is correct in message-mode.
22378 (let ((fill-paragraph-function
22379 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22380 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22381 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22382 (paragraph-separate
22383 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22384 (fill-paragraph nil))
22385 (with-syntax-table org-mode-transpose-word-syntax-table
22386 ;; Move to end of line in order to get the first paragraph
22387 ;; within a plain list or a footnote definition.
22388 (let ((element (save-excursion
22389 (end-of-line)
22390 (or (ignore-errors (org-element-at-point))
22391 (user-error "An element cannot be parsed line %d"
22392 (line-number-at-pos (point)))))))
22393 ;; First check if point is in a blank line at the beginning of
22394 ;; the buffer. In that case, ignore filling.
22395 (case (org-element-type element)
22396 ;; Use major mode filling function is src blocks.
22397 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22398 ;; Align Org tables, leave table.el tables as-is.
22399 (table-row (org-table-align) t)
22400 (table
22401 (when (eq (org-element-property :type element) 'org)
22402 (save-excursion
22403 (goto-char (org-element-property :post-affiliated element))
22404 (org-table-align)))
22405 t)
22406 (paragraph
22407 ;; Paragraphs may contain `line-break' type objects.
22408 (let ((beg (max (point-min)
22409 (org-element-property :contents-begin element)))
22410 (end (min (point-max)
22411 (org-element-property :contents-end element))))
22412 ;; Do nothing if point is at an affiliated keyword.
22413 (if (< (line-end-position) beg) t
22414 (when (derived-mode-p 'message-mode)
22415 ;; In `message-mode', do not fill following citation
22416 ;; in current paragraph nor text before message body.
22417 (let ((body-start (save-excursion (message-goto-body))))
22418 (when body-start (setq beg (max body-start beg))))
22419 (when (save-excursion
22420 (re-search-forward
22421 (concat "^" message-cite-prefix-regexp) end t))
22422 (setq end (match-beginning 0))))
22423 ;; Fill paragraph, taking line breaks into account.
22424 ;; For that, slice the paragraph using line breaks as
22425 ;; separators, and fill the parts in reverse order to
22426 ;; avoid messing with markers.
22427 (save-excursion
22428 (goto-char end)
22429 (mapc
22430 (lambda (pos)
22431 (fill-region-as-paragraph pos (point) justify)
22432 (goto-char pos))
22433 ;; Find the list of ending positions for line breaks
22434 ;; in the current paragraph. Add paragraph
22435 ;; beginning to include first slice.
22436 (nreverse
22437 (cons beg
22438 (org-element-map
22439 (org-element--parse-objects
22440 beg end nil (org-element-restriction 'paragraph))
22441 'line-break
22442 (lambda (lb) (org-element-property :end lb)))))))
22443 t)))
22444 ;; Contents of `comment-block' type elements should be
22445 ;; filled as plain text, but only if point is within block
22446 ;; markers.
22447 (comment-block
22448 (let* ((case-fold-search t)
22449 (beg (save-excursion
22450 (goto-char (org-element-property :begin element))
22451 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22452 (forward-line)
22453 (point)))
22454 (end (save-excursion
22455 (goto-char (org-element-property :end element))
22456 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22457 (line-beginning-position))))
22458 (if (or (< (point) beg) (> (point) end)) t
22459 (fill-region-as-paragraph
22460 (save-excursion (end-of-line)
22461 (re-search-backward "^[ \t]*$" beg 'move)
22462 (line-beginning-position))
22463 (save-excursion (beginning-of-line)
22464 (re-search-forward "^[ \t]*$" end 'move)
22465 (line-beginning-position))
22466 justify))))
22467 ;; Fill comments.
22468 (comment
22469 (let ((begin (org-element-property :post-affiliated element))
22470 (end (org-element-property :end element)))
22471 (when (and (>= (point) begin) (<= (point) end))
22472 (let ((begin (save-excursion
22473 (end-of-line)
22474 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22475 (progn (forward-line) (point))
22476 begin)))
22477 (end (save-excursion
22478 (end-of-line)
22479 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22480 (1- (line-beginning-position))
22481 (skip-chars-backward " \r\t\n")
22482 (line-end-position)))))
22483 ;; Do not fill comments when at a blank line.
22484 (when (> end begin)
22485 (let ((fill-prefix
22486 (save-excursion
22487 (beginning-of-line)
22488 (looking-at "[ \t]*#")
22489 (let ((comment-prefix (match-string 0)))
22490 (goto-char (match-end 0))
22491 (if (looking-at adaptive-fill-regexp)
22492 (concat comment-prefix (match-string 0))
22493 (concat comment-prefix " "))))))
22494 (save-excursion
22495 (fill-region-as-paragraph begin end justify))))))
22496 t))
22497 ;; Ignore every other element.
22498 (otherwise t))))))
22499
22500 (defun org-auto-fill-function ()
22501 "Auto-fill function."
22502 ;; Check if auto-filling is meaningful.
22503 (let ((fc (current-fill-column)))
22504 (when (and fc (> (current-column) fc))
22505 (let* ((fill-prefix (org-adaptive-fill-function))
22506 ;; Enforce empty fill prefix, if required. Otherwise, it
22507 ;; will be computed again.
22508 (adaptive-fill-mode (not (equal fill-prefix ""))))
22509 (when fill-prefix (do-auto-fill))))))
22510
22511 (defun org-comment-line-break-function (&optional soft)
22512 "Break line at point and indent, continuing comment if within one.
22513 The inserted newline is marked hard if variable
22514 `use-hard-newlines' is true, unless optional argument SOFT is
22515 non-nil."
22516 (if soft (insert-and-inherit ?\n) (newline 1))
22517 (save-excursion (forward-char -1) (delete-horizontal-space))
22518 (delete-horizontal-space)
22519 (indent-to-left-margin)
22520 (insert-before-markers-and-inherit fill-prefix))
22521
22522
22523 ;;; Comments
22524
22525 ;; Org comments syntax is quite complex. It requires the entire line
22526 ;; to be just a comment. Also, even with the right syntax at the
22527 ;; beginning of line, some some elements (i.e. verse-block or
22528 ;; example-block) don't accept comments. Usual Emacs comment commands
22529 ;; cannot cope with those requirements. Therefore, Org replaces them.
22530
22531 ;; Org still relies on `comment-dwim', but cannot trust
22532 ;; `comment-only-p'. So, `comment-region-function' and
22533 ;; `uncomment-region-function' both point
22534 ;; to`org-comment-or-uncomment-region'. Eventually,
22535 ;; `org-insert-comment' takes care of insertion of comments at the
22536 ;; beginning of line.
22537
22538 ;; `org-setup-comments-handling' install comments related variables
22539 ;; during `org-mode' initialization.
22540
22541 (defun org-setup-comments-handling ()
22542 (interactive)
22543 (org-set-local 'comment-use-syntax nil)
22544 (org-set-local 'comment-start "# ")
22545 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22546 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22547 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22548 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22549
22550 (defun org-insert-comment ()
22551 "Insert an empty comment above current line.
22552 If the line is empty, insert comment at its beginning."
22553 (beginning-of-line)
22554 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22555 (org-indent-line)
22556 (insert "# "))
22557
22558 (defvar comment-empty-lines) ; From newcomment.el.
22559 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22560 "Comment or uncomment each non-blank line in the region.
22561 Uncomment each non-blank line between BEG and END if it only
22562 contains commented lines. Otherwise, comment them."
22563 (save-restriction
22564 ;; Restrict region
22565 (narrow-to-region (save-excursion (goto-char beg)
22566 (skip-chars-forward " \r\t\n" end)
22567 (line-beginning-position))
22568 (save-excursion (goto-char end)
22569 (skip-chars-backward " \r\t\n" beg)
22570 (line-end-position)))
22571 (let ((uncommentp
22572 ;; UNCOMMENTP is non-nil when every non blank line between
22573 ;; BEG and END is a comment.
22574 (save-excursion
22575 (goto-char (point-min))
22576 (while (and (not (eobp))
22577 (let ((element (org-element-at-point)))
22578 (and (eq (org-element-type element) 'comment)
22579 (goto-char (min (point-max)
22580 (org-element-property
22581 :end element)))))))
22582 (eobp))))
22583 (if uncommentp
22584 ;; Only blank lines and comments in region: uncomment it.
22585 (save-excursion
22586 (goto-char (point-min))
22587 (while (not (eobp))
22588 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22589 (replace-match "" nil nil nil 1))
22590 (forward-line)))
22591 ;; Comment each line in region.
22592 (let ((min-indent (point-max)))
22593 ;; First find the minimum indentation across all lines.
22594 (save-excursion
22595 (goto-char (point-min))
22596 (while (and (not (eobp)) (not (zerop min-indent)))
22597 (unless (looking-at "[ \t]*$")
22598 (setq min-indent (min min-indent (current-indentation))))
22599 (forward-line)))
22600 ;; Then loop over all lines.
22601 (save-excursion
22602 (goto-char (point-min))
22603 (while (not (eobp))
22604 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22605 ;; Don't get fooled by invisible text (e.g. link path)
22606 ;; when moving to column MIN-INDENT.
22607 (let ((buffer-invisibility-spec nil))
22608 (org-move-to-column min-indent t))
22609 (insert comment-start))
22610 (forward-line))))))))
22611
22612
22613 ;;; Planning
22614
22615 ;; This section contains tools to operate on timestamp objects, as
22616 ;; returned by, e.g. `org-element-context'.
22617
22618 (defun org-timestamp-has-time-p (timestamp)
22619 "Non-nil when TIMESTAMP has a time specified."
22620 (org-element-property :hour-start timestamp))
22621
22622 (defun org-timestamp-format (timestamp format &optional end utc)
22623 "Format a TIMESTAMP element into a string.
22624
22625 FORMAT is a format specifier to be passed to
22626 `format-time-string'.
22627
22628 When optional argument END is non-nil, use end of date-range or
22629 time-range, if possible.
22630
22631 When optional argument UTC is non-nil, time will be expressed as
22632 Universal Time."
22633 (format-time-string
22634 format
22635 (apply 'encode-time
22636 (cons 0
22637 (mapcar
22638 (lambda (prop) (or (org-element-property prop timestamp) 0))
22639 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22640 '(:minute-start :hour-start :day-start :month-start
22641 :year-start)))))
22642 utc))
22643
22644 (defun org-timestamp-split-range (timestamp &optional end)
22645 "Extract a timestamp object from a date or time range.
22646
22647 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22648 the end of the range. Otherwise, extract its start.
22649
22650 Return a new timestamp object sharing the same parent as
22651 TIMESTAMP."
22652 (let ((type (org-element-property :type timestamp)))
22653 (if (memq type '(active inactive diary)) timestamp
22654 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22655 ;; Set new type.
22656 (org-element-put-property
22657 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22658 ;; Copy start properties over end properties if END is
22659 ;; non-nil. Otherwise, copy end properties over `start' ones.
22660 (let ((p-alist '((:minute-start . :minute-end)
22661 (:hour-start . :hour-end)
22662 (:day-start . :day-end)
22663 (:month-start . :month-end)
22664 (:year-start . :year-end))))
22665 (dolist (p-cell p-alist)
22666 (org-element-put-property
22667 split-ts
22668 (funcall (if end 'car 'cdr) p-cell)
22669 (org-element-property
22670 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22671 ;; Eventually refresh `:raw-value'.
22672 (org-element-put-property split-ts :raw-value nil)
22673 (org-element-put-property
22674 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22675
22676 (defun org-timestamp-translate (timestamp &optional boundary)
22677 "Apply `org-translate-time' on a TIMESTAMP object.
22678 When optional argument BOUNDARY is non-nil, it is either the
22679 symbol `start' or `end'. In this case, only translate the
22680 starting or ending part of TIMESTAMP if it is a date or time
22681 range. Otherwise, translate both parts."
22682 (if (and (not boundary)
22683 (memq (org-element-property :type timestamp)
22684 '(active-range inactive-range)))
22685 (concat
22686 (org-translate-time
22687 (org-element-property :raw-value
22688 (org-timestamp-split-range timestamp)))
22689 "--"
22690 (org-translate-time
22691 (org-element-property :raw-value
22692 (org-timestamp-split-range timestamp t))))
22693 (org-translate-time
22694 (org-element-property
22695 :raw-value
22696 (if (not boundary) timestamp
22697 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22698
22699
22700
22701 ;;; Other stuff.
22702
22703 (defun org-toggle-fixed-width-section (arg)
22704 "Toggle the fixed-width export.
22705 If there is no active region, the QUOTE keyword at the current headline is
22706 inserted or removed. When present, it causes the text between this headline
22707 and the next to be exported as fixed-width text, and unmodified.
22708 If there is an active region, this command adds or removes a colon as the
22709 first character of this line. If the first character of a line is a colon,
22710 this line is also exported in fixed-width font."
22711 (interactive "P")
22712 (let* ((cc 0)
22713 (regionp (org-region-active-p))
22714 (beg (if regionp (region-beginning) (point)))
22715 (end (if regionp (region-end)))
22716 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22717 (case-fold-search nil)
22718 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22719 off)
22720 (if regionp
22721 (save-excursion
22722 (goto-char beg)
22723 (setq cc (current-column))
22724 (beginning-of-line 1)
22725 (setq off (looking-at re))
22726 (while (> nlines 0)
22727 (setq nlines (1- nlines))
22728 (beginning-of-line 1)
22729 (cond
22730 (arg
22731 (org-move-to-column cc t)
22732 (insert ": \n")
22733 (forward-line -1))
22734 ((and off (looking-at re))
22735 (replace-match "" t t nil 1))
22736 ((not off) (org-move-to-column cc t) (insert ": ")))
22737 (forward-line 1)))
22738 (save-excursion
22739 (org-back-to-heading)
22740 (cond
22741 ((looking-at (format org-heading-keyword-regexp-format
22742 org-quote-string))
22743 (goto-char (match-end 1))
22744 (looking-at (concat " +" org-quote-string))
22745 (replace-match "" t t)
22746 (when (eolp) (insert " ")))
22747 ((looking-at org-outline-regexp)
22748 (goto-char (match-end 0))
22749 (insert org-quote-string " ")))))))
22750
22751 (defun org-reftex-citation ()
22752 "Use reftex-citation to insert a citation into the buffer.
22753 This looks for a line like
22754
22755 #+BIBLIOGRAPHY: foo plain option:-d
22756
22757 and derives from it that foo.bib is the bibliography file relevant
22758 for this document. It then installs the necessary environment for RefTeX
22759 to work in this buffer and calls `reftex-citation' to insert a citation
22760 into the buffer.
22761
22762 Export of such citations to both LaTeX and HTML is handled by the contributed
22763 package ox-bibtex by Taru Karttunen."
22764 (interactive)
22765 (let ((reftex-docstruct-symbol 'rds)
22766 (reftex-cite-format "\\cite{%l}")
22767 rds bib)
22768 (save-excursion
22769 (save-restriction
22770 (widen)
22771 (let ((case-fold-search t)
22772 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22773 (if (not (save-excursion
22774 (or (re-search-forward re nil t)
22775 (re-search-backward re nil t))))
22776 (error "No bibliography defined in file")
22777 (setq bib (concat (match-string 1) ".bib")
22778 rds (list (list 'bib bib)))))))
22779 (call-interactively 'reftex-citation)))
22780
22781 ;;;; Functions extending outline functionality
22782
22783 (defun org-beginning-of-line (&optional arg)
22784 "Go to the beginning of the current line. If that is invisible, continue
22785 to a visible line beginning. This makes the function of C-a more intuitive.
22786 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22787 first attempt, and only move to after the tags when the cursor is already
22788 beyond the end of the headline."
22789 (interactive "P")
22790 (let ((pos (point))
22791 (special (if (consp org-special-ctrl-a/e)
22792 (car org-special-ctrl-a/e)
22793 org-special-ctrl-a/e))
22794 deactivate-mark refpos)
22795 (if (org-bound-and-true-p visual-line-mode)
22796 (beginning-of-visual-line 1)
22797 (beginning-of-line 1))
22798 (if (and arg (fboundp 'move-beginning-of-line))
22799 (call-interactively 'move-beginning-of-line)
22800 (if (bobp)
22801 nil
22802 (backward-char 1)
22803 (if (org-truely-invisible-p)
22804 (while (and (not (bobp)) (org-truely-invisible-p))
22805 (backward-char 1)
22806 (beginning-of-line 1))
22807 (forward-char 1))))
22808 (when special
22809 (cond
22810 ((and (looking-at org-complex-heading-regexp)
22811 (= (char-after (match-end 1)) ?\ ))
22812 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22813 (point-at-eol)))
22814 (goto-char
22815 (if (eq special t)
22816 (cond ((> pos refpos) refpos)
22817 ((= pos (point)) refpos)
22818 (t (point)))
22819 (cond ((> pos (point)) (point))
22820 ((not (eq last-command this-command)) (point))
22821 (t refpos)))))
22822 ((org-at-item-p)
22823 ;; Being at an item and not looking at an the item means point
22824 ;; was previously moved to beginning of a visual line, which
22825 ;; doesn't contain the item. Therefore, do nothing special,
22826 ;; just stay here.
22827 (when (looking-at org-list-full-item-re)
22828 ;; Set special position at first white space character after
22829 ;; bullet, and check-box, if any.
22830 (let ((after-bullet
22831 (let ((box (match-end 3)))
22832 (if (not box) (match-end 1)
22833 (let ((after (char-after box)))
22834 (if (and after (= after ? )) (1+ box) box))))))
22835 ;; Special case: Move point to special position when
22836 ;; currently after it or at beginning of line.
22837 (if (eq special t)
22838 (when (or (> pos after-bullet) (= (point) pos))
22839 (goto-char after-bullet))
22840 ;; Reversed case: Move point to special position when
22841 ;; point was already at beginning of line and command is
22842 ;; repeated.
22843 (when (and (= (point) pos) (eq last-command this-command))
22844 (goto-char after-bullet))))))))
22845 (org-no-warnings
22846 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22847 (setq disable-point-adjustment
22848 (or (not (invisible-p (point)))
22849 (not (invisible-p (max (point-min) (1- (point))))))))
22850
22851 (defun org-end-of-line (&optional arg)
22852 "Go to the end of the line.
22853 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22854 tags on the first attempt, and only move to after the tags when
22855 the cursor is already beyond the end of the headline."
22856 (interactive "P")
22857 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22858 org-special-ctrl-a/e))
22859 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22860 'end-of-visual-line)
22861 ((fboundp 'move-end-of-line) 'move-end-of-line)
22862 (t 'end-of-line)))
22863 deactivate-mark)
22864 (if (or (not special) arg) (call-interactively move-fun)
22865 (let* ((element (save-excursion (beginning-of-line)
22866 (org-element-at-point)))
22867 (type (org-element-type element)))
22868 (cond
22869 ((memq type '(headline inlinetask))
22870 (let ((pos (point)))
22871 (beginning-of-line 1)
22872 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22873 (if (eq special t)
22874 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22875 (goto-char (match-beginning 1))
22876 (goto-char (match-end 0)))
22877 (if (or (< pos (match-end 0))
22878 (not (eq this-command last-command)))
22879 (goto-char (match-end 0))
22880 (goto-char (match-beginning 1))))
22881 (call-interactively move-fun))))
22882 ((org-element-property :hiddenp element)
22883 ;; If element is hidden, `move-end-of-line' would put point
22884 ;; after it. Use `end-of-line' to stay on current line.
22885 (call-interactively 'end-of-line))
22886 (t (call-interactively move-fun)))))
22887 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22888 (setq disable-point-adjustment
22889 (or (not (invisible-p (point)))
22890 (not (invisible-p (max (point-min) (1- (point))))))))
22891
22892 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22893 (define-key org-mode-map "\C-e" 'org-end-of-line)
22894
22895 (defun org-backward-sentence (&optional arg)
22896 "Go to beginning of sentence, or beginning of table field.
22897 This will call `backward-sentence' or `org-table-beginning-of-field',
22898 depending on context."
22899 (interactive "P")
22900 (cond
22901 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22902 (t (call-interactively 'backward-sentence))))
22903
22904 (defun org-forward-sentence (&optional arg)
22905 "Go to end of sentence, or end of table field.
22906 This will call `forward-sentence' or `org-table-end-of-field',
22907 depending on context."
22908 (interactive "P")
22909 (cond
22910 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22911 (t (call-interactively 'forward-sentence))))
22912
22913 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22914 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22915
22916 (defun org-kill-line (&optional arg)
22917 "Kill line, to tags or end of line."
22918 (interactive "P")
22919 (cond
22920 ((or (not org-special-ctrl-k)
22921 (bolp)
22922 (not (org-at-heading-p)))
22923 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22924 org-ctrl-k-protect-subtree)
22925 (if (or (eq org-ctrl-k-protect-subtree 'error)
22926 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22927 (user-error "C-k aborted as it would kill a hidden subtree")))
22928 (call-interactively
22929 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22930 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22931 (kill-region (point) (match-beginning 1))
22932 (org-set-tags nil t))
22933 (t (kill-region (point) (point-at-eol)))))
22934
22935 (define-key org-mode-map "\C-k" 'org-kill-line)
22936
22937 (defun org-yank (&optional arg)
22938 "Yank. If the kill is a subtree, treat it specially.
22939 This command will look at the current kill and check if is a single
22940 subtree, or a series of subtrees[1]. If it passes the test, and if the
22941 cursor is at the beginning of a line or after the stars of a currently
22942 empty headline, then the yank is handled specially. How exactly depends
22943 on the value of the following variables, both set by default.
22944
22945 org-yank-folded-subtrees
22946 When set, the subtree(s) will be folded after insertion, but only
22947 if doing so would now swallow text after the yanked text.
22948
22949 org-yank-adjusted-subtrees
22950 When set, the subtree will be promoted or demoted in order to
22951 fit into the local outline tree structure, which means that the level
22952 will be adjusted so that it becomes the smaller one of the two
22953 *visible* surrounding headings.
22954
22955 Any prefix to this command will cause `yank' to be called directly with
22956 no special treatment. In particular, a simple \\[universal-argument] prefix \
22957 will just
22958 plainly yank the text as it is.
22959
22960 \[1] The test checks if the first non-white line is a heading
22961 and if there are no other headings with fewer stars."
22962 (interactive "P")
22963 (org-yank-generic 'yank arg))
22964
22965 (defun org-yank-generic (command arg)
22966 "Perform some yank-like command.
22967
22968 This function implements the behavior described in the `org-yank'
22969 documentation. However, it has been generalized to work for any
22970 interactive command with similar behavior."
22971
22972 ;; pretend to be command COMMAND
22973 (setq this-command command)
22974
22975 (if arg
22976 (call-interactively command)
22977
22978 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22979 (and (org-kill-is-subtree-p)
22980 (or (bolp)
22981 (and (looking-at "[ \t]*$")
22982 (string-match
22983 "\\`\\*+\\'"
22984 (buffer-substring (point-at-bol) (point)))))))
22985 swallowp)
22986 (cond
22987 ((and subtreep org-yank-folded-subtrees)
22988 (let ((beg (point))
22989 end)
22990 (if (and subtreep org-yank-adjusted-subtrees)
22991 (org-paste-subtree nil nil 'for-yank)
22992 (call-interactively command))
22993
22994 (setq end (point))
22995 (goto-char beg)
22996 (when (and (bolp) subtreep
22997 (not (setq swallowp
22998 (org-yank-folding-would-swallow-text beg end))))
22999 (org-with-limited-levels
23000 (or (looking-at org-outline-regexp)
23001 (re-search-forward org-outline-regexp-bol end t))
23002 (while (and (< (point) end) (looking-at org-outline-regexp))
23003 (hide-subtree)
23004 (org-cycle-show-empty-lines 'folded)
23005 (condition-case nil
23006 (outline-forward-same-level 1)
23007 (error (goto-char end))))))
23008 (when swallowp
23009 (message
23010 "Inserted text not folded because that would swallow text"))
23011
23012 (goto-char end)
23013 (skip-chars-forward " \t\n\r")
23014 (beginning-of-line 1)
23015 (push-mark beg 'nomsg)))
23016 ((and subtreep org-yank-adjusted-subtrees)
23017 (let ((beg (point-at-bol)))
23018 (org-paste-subtree nil nil 'for-yank)
23019 (push-mark beg 'nomsg)))
23020 (t
23021 (call-interactively command))))))
23022
23023 (defun org-yank-folding-would-swallow-text (beg end)
23024 "Would hide-subtree at BEG swallow any text after END?"
23025 (let (level)
23026 (org-with-limited-levels
23027 (save-excursion
23028 (goto-char beg)
23029 (when (or (looking-at org-outline-regexp)
23030 (re-search-forward org-outline-regexp-bol end t))
23031 (setq level (org-outline-level)))
23032 (goto-char end)
23033 (skip-chars-forward " \t\r\n\v\f")
23034 (if (or (eobp)
23035 (and (bolp) (looking-at org-outline-regexp)
23036 (<= (org-outline-level) level)))
23037 nil ; Nothing would be swallowed
23038 t))))) ; something would swallow
23039
23040 (define-key org-mode-map "\C-y" 'org-yank)
23041
23042 (defun org-truely-invisible-p ()
23043 "Check if point is at a character currently not visible.
23044 This version does not only check the character property, but also
23045 `visible-mode'."
23046 ;; Early versions of noutline don't have `outline-invisible-p'.
23047 (if (org-bound-and-true-p visible-mode)
23048 nil
23049 (outline-invisible-p)))
23050
23051 (defun org-invisible-p2 ()
23052 "Check if point is at a character currently not visible."
23053 (save-excursion
23054 (if (and (eolp) (not (bobp))) (backward-char 1))
23055 ;; Early versions of noutline don't have `outline-invisible-p'.
23056 (outline-invisible-p)))
23057
23058 (defun org-back-to-heading (&optional invisible-ok)
23059 "Call `outline-back-to-heading', but provide a better error message."
23060 (condition-case nil
23061 (outline-back-to-heading invisible-ok)
23062 (error (error "Before first headline at position %d in buffer %s"
23063 (point) (current-buffer)))))
23064
23065 (defun org-before-first-heading-p ()
23066 "Before first heading?"
23067 (save-excursion
23068 (end-of-line)
23069 (null (re-search-backward org-outline-regexp-bol nil t))))
23070
23071 (defun org-at-heading-p (&optional ignored)
23072 (outline-on-heading-p t))
23073 ;; Compatibility alias with Org versions < 7.8.03
23074 (defalias 'org-on-heading-p 'org-at-heading-p)
23075
23076 (defun org-at-comment-p nil
23077 "Is cursor in a line starting with a # character?"
23078 (save-excursion
23079 (beginning-of-line)
23080 (looking-at "^#")))
23081
23082 (defun org-at-drawer-p nil
23083 "Is cursor at a drawer keyword?"
23084 (save-excursion
23085 (move-beginning-of-line 1)
23086 (looking-at org-drawer-regexp)))
23087
23088 (defun org-at-block-p nil
23089 "Is cursor at a block keyword?"
23090 (save-excursion
23091 (move-beginning-of-line 1)
23092 (looking-at org-block-regexp)))
23093
23094 (defun org-point-at-end-of-empty-headline ()
23095 "If point is at the end of an empty headline, return t, else nil.
23096 If the heading only contains a TODO keyword, it is still still considered
23097 empty."
23098 (and (looking-at "[ \t]*$")
23099 (when org-todo-line-regexp
23100 (save-excursion
23101 (beginning-of-line 1)
23102 (let ((case-fold-search nil))
23103 (looking-at org-todo-line-regexp)
23104 (string= (match-string 3) ""))))))
23105
23106 (defun org-at-heading-or-item-p ()
23107 (or (org-at-heading-p) (org-at-item-p)))
23108
23109 (defun org-at-target-p ()
23110 (or (org-in-regexp org-radio-target-regexp)
23111 (org-in-regexp org-target-regexp)))
23112 ;; Compatibility alias with Org versions < 7.8.03
23113 (defalias 'org-on-target-p 'org-at-target-p)
23114
23115 (defun org-up-heading-all (arg)
23116 "Move to the heading line of which the present line is a subheading.
23117 This function considers both visible and invisible heading lines.
23118 With argument, move up ARG levels."
23119 (if (fboundp 'outline-up-heading-all)
23120 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23121 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23122
23123 (defun org-up-heading-safe ()
23124 "Move to the heading line of which the present line is a subheading.
23125 This version will not throw an error. It will return the level of the
23126 headline found, or nil if no higher level is found.
23127
23128 Also, this function will be a lot faster than `outline-up-heading',
23129 because it relies on stars being the outline starters. This can really
23130 make a significant difference in outlines with very many siblings."
23131 (let (start-level re)
23132 (org-back-to-heading t)
23133 (setq start-level (funcall outline-level))
23134 (if (equal start-level 1)
23135 nil
23136 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23137 (if (re-search-backward re nil t)
23138 (funcall outline-level)))))
23139
23140 (defun org-first-sibling-p ()
23141 "Is this heading the first child of its parents?"
23142 (interactive)
23143 (let ((re org-outline-regexp-bol)
23144 level l)
23145 (unless (org-at-heading-p t)
23146 (user-error "Not at a heading"))
23147 (setq level (funcall outline-level))
23148 (save-excursion
23149 (if (not (re-search-backward re nil t))
23150 t
23151 (setq l (funcall outline-level))
23152 (< l level)))))
23153
23154 (defun org-goto-sibling (&optional previous)
23155 "Goto the next sibling, even if it is invisible.
23156 When PREVIOUS is set, go to the previous sibling instead. Returns t
23157 when a sibling was found. When none is found, return nil and don't
23158 move point."
23159 (let ((fun (if previous 're-search-backward 're-search-forward))
23160 (pos (point))
23161 (re org-outline-regexp-bol)
23162 level l)
23163 (when (condition-case nil (org-back-to-heading t) (error nil))
23164 (setq level (funcall outline-level))
23165 (catch 'exit
23166 (or previous (forward-char 1))
23167 (while (funcall fun re nil t)
23168 (setq l (funcall outline-level))
23169 (when (< l level) (goto-char pos) (throw 'exit nil))
23170 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23171 (goto-char pos)
23172 nil))))
23173
23174 (defun org-show-siblings ()
23175 "Show all siblings of the current headline."
23176 (save-excursion
23177 (while (org-goto-sibling) (org-flag-heading nil)))
23178 (save-excursion
23179 (while (org-goto-sibling 'previous)
23180 (org-flag-heading nil))))
23181
23182 (defun org-goto-first-child ()
23183 "Goto the first child, even if it is invisible.
23184 Return t when a child was found. Otherwise don't move point and
23185 return nil."
23186 (let (level (pos (point)) (re org-outline-regexp-bol))
23187 (when (condition-case nil (org-back-to-heading t) (error nil))
23188 (setq level (outline-level))
23189 (forward-char 1)
23190 (if (and (re-search-forward re nil t) (> (outline-level) level))
23191 (progn (goto-char (match-beginning 0)) t)
23192 (goto-char pos) nil))))
23193
23194 (defun org-show-hidden-entry ()
23195 "Show an entry where even the heading is hidden."
23196 (save-excursion
23197 (org-show-entry)))
23198
23199 (defun org-flag-heading (flag &optional entry)
23200 "Flag the current heading. FLAG non-nil means make invisible.
23201 When ENTRY is non-nil, show the entire entry."
23202 (save-excursion
23203 (org-back-to-heading t)
23204 ;; Check if we should show the entire entry
23205 (if entry
23206 (progn
23207 (org-show-entry)
23208 (save-excursion
23209 (and (outline-next-heading)
23210 (org-flag-heading nil))))
23211 (outline-flag-region (max (point-min) (1- (point)))
23212 (save-excursion (outline-end-of-heading) (point))
23213 flag))))
23214
23215 (defun org-get-next-sibling ()
23216 "Move to next heading of the same level, and return point.
23217 If there is no such heading, return nil.
23218 This is like outline-next-sibling, but invisible headings are ok."
23219 (let ((level (funcall outline-level)))
23220 (outline-next-heading)
23221 (while (and (not (eobp)) (> (funcall outline-level) level))
23222 (outline-next-heading))
23223 (if (or (eobp) (< (funcall outline-level) level))
23224 nil
23225 (point))))
23226
23227 (defun org-get-last-sibling ()
23228 "Move to previous heading of the same level, and return point.
23229 If there is no such heading, return nil."
23230 (let ((opoint (point))
23231 (level (funcall outline-level)))
23232 (outline-previous-heading)
23233 (when (and (/= (point) opoint) (outline-on-heading-p t))
23234 (while (and (> (funcall outline-level) level)
23235 (not (bobp)))
23236 (outline-previous-heading))
23237 (if (< (funcall outline-level) level)
23238 nil
23239 (point)))))
23240
23241 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23242 "Goto to the end of a subtree."
23243 ;; This contains an exact copy of the original function, but it uses
23244 ;; `org-back-to-heading', to make it work also in invisible
23245 ;; trees. And is uses an invisible-ok argument.
23246 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23247 ;; Furthermore, when used inside Org, finding the end of a large subtree
23248 ;; with many children and grandchildren etc, this can be much faster
23249 ;; than the outline version.
23250 (org-back-to-heading invisible-ok)
23251 (let ((first t)
23252 (level (funcall outline-level)))
23253 (if (and (derived-mode-p 'org-mode) (< level 1000))
23254 ;; A true heading (not a plain list item), in Org-mode
23255 ;; This means we can easily find the end by looking
23256 ;; only for the right number of stars. Using a regexp to do
23257 ;; this is so much faster than using a Lisp loop.
23258 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23259 (forward-char 1)
23260 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23261 ;; something else, do it the slow way
23262 (while (and (not (eobp))
23263 (or first (> (funcall outline-level) level)))
23264 (setq first nil)
23265 (outline-next-heading)))
23266 (unless to-heading
23267 (if (memq (preceding-char) '(?\n ?\^M))
23268 (progn
23269 ;; Go to end of line before heading
23270 (forward-char -1)
23271 (if (memq (preceding-char) '(?\n ?\^M))
23272 ;; leave blank line before heading
23273 (forward-char -1))))))
23274 (point))
23275
23276 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23277 "Use Org version in org-mode, for dramatic speed-up."
23278 (if (derived-mode-p 'org-mode)
23279 (progn
23280 (org-end-of-subtree nil t)
23281 (unless (eobp) (backward-char 1)))
23282 ad-do-it))
23283
23284 (defun org-end-of-meta-data-and-drawers ()
23285 "Jump to the first text after meta data and drawers in the current entry.
23286 This will move over empty lines, lines with planning time stamps,
23287 clocking lines, and drawers."
23288 (org-back-to-heading t)
23289 (let ((end (save-excursion (outline-next-heading) (point)))
23290 (re (concat "\\(" org-drawer-regexp "\\)"
23291 "\\|" "[ \t]*" org-keyword-time-regexp)))
23292 (forward-line 1)
23293 (while (re-search-forward re end t)
23294 (if (not (match-end 1))
23295 ;; empty or planning line
23296 (forward-line 1)
23297 ;; a drawer, find the end
23298 (re-search-forward "^[ \t]*:END:" end 'move)
23299 (forward-line 1)))
23300 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23301 (point)))
23302
23303 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23304 "Move forward to the ARG'th subheading at same level as this one.
23305 Stop at the first and last subheadings of a superior heading.
23306 Normally this only looks at visible headings, but when INVISIBLE-OK is
23307 non-nil it will also look at invisible ones."
23308 (interactive "p")
23309 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23310 (if (and arg (< arg 0))
23311 (goto-char (point-min))
23312 (outline-next-heading))
23313 (org-at-heading-p)
23314 (let ((level (- (match-end 0) (match-beginning 0) 1))
23315 (f (if (and arg (< arg 0))
23316 're-search-backward
23317 're-search-forward))
23318 (count (if arg (abs arg) 1))
23319 (result (point)))
23320 (while (and (prog1 (> count 0)
23321 (forward-char (if (and arg (< arg 0)) -1 1)))
23322 (funcall f org-outline-regexp-bol nil 'move))
23323 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23324 (cond ((< l level) (setq count 0))
23325 ((and (= l level)
23326 (or invisible-ok
23327 (progn
23328 (goto-char (line-beginning-position))
23329 (not (outline-invisible-p)))))
23330 (setq count (1- count))
23331 (when (eq l level)
23332 (setq result (point)))))))
23333 (goto-char result))
23334 (beginning-of-line 1)))
23335
23336 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23337 "Move backward to the ARG'th subheading at same level as this one.
23338 Stop at the first and last subheadings of a superior heading."
23339 (interactive "p")
23340 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23341
23342 (defun org-next-block (arg &optional backward block-regexp)
23343 "Jump to the next block.
23344 With a prefix argument ARG, jump forward ARG many source blocks.
23345 When BACKWARD is non-nil, jump to the previous block.
23346 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23347 (interactive "p")
23348 (let ((re (or block-regexp org-block-regexp))
23349 (re-search-fn (or (and backward 're-search-backward)
23350 're-search-forward)))
23351 (if (looking-at re) (forward-char 1))
23352 (condition-case nil
23353 (funcall re-search-fn re nil nil arg)
23354 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23355 (goto-char (match-beginning 0)) (org-show-context)))
23356
23357 (defun org-previous-block (arg &optional block-regexp)
23358 "Jump to the previous block.
23359 With a prefix argument ARG, jump backward ARG many source blocks.
23360 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23361 (interactive "p")
23362 (org-next-block arg t block-regexp))
23363
23364 (defun org-forward-paragraph ()
23365 "Move forward to beginning of next paragraph or equivalent.
23366
23367 The function moves point to the beginning of the next visible
23368 structural element, which can be a paragraph, a table, a list
23369 item, etc. It also provides some special moves for convenience:
23370
23371 - On an affiliated keyword, jump to the beginning of the
23372 relative element.
23373 - On an item or a footnote definition, move to the second
23374 element inside, if any.
23375 - On a table or a property drawer, jump after it.
23376 - On a verse or source block, stop after blank lines."
23377 (interactive)
23378 (when (eobp) (user-error "Cannot move further down"))
23379 (let* ((deactivate-mark nil)
23380 (element (org-element-at-point))
23381 (type (org-element-type element))
23382 (post-affiliated (org-element-property :post-affiliated element))
23383 (contents-begin (org-element-property :contents-begin element))
23384 (contents-end (org-element-property :contents-end element))
23385 (end (let ((end (org-element-property :end element)) (parent element))
23386 (while (and (setq parent (org-element-property :parent parent))
23387 (= (org-element-property :contents-end parent) end))
23388 (setq end (org-element-property :end parent)))
23389 end)))
23390 (cond ((not element)
23391 (skip-chars-forward " \r\t\n")
23392 (or (eobp) (beginning-of-line)))
23393 ;; On affiliated keywords, move to element's beginning.
23394 ((and post-affiliated (< (point) post-affiliated))
23395 (goto-char post-affiliated))
23396 ;; At a table row, move to the end of the table. Similarly,
23397 ;; at a node property, move to the end of the property
23398 ;; drawer.
23399 ((memq type '(node-property table-row))
23400 (goto-char (org-element-property
23401 :end (org-element-property :parent element))))
23402 ((memq type '(property-drawer table)) (goto-char end))
23403 ;; Consider blank lines as separators in verse and source
23404 ;; blocks to ease editing.
23405 ((memq type '(src-block verse-block))
23406 (when (eq type 'src-block)
23407 (setq contents-end
23408 (save-excursion (goto-char end)
23409 (skip-chars-backward " \r\t\n")
23410 (line-beginning-position))))
23411 (beginning-of-line)
23412 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23413 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23414 (goto-char end)
23415 (skip-chars-forward " \r\t\n")
23416 (if (= (point) contents-end) (goto-char end)
23417 (beginning-of-line))))
23418 ;; With no contents, just skip element.
23419 ((not contents-begin) (goto-char end))
23420 ;; If contents are invisible, skip the element altogether.
23421 ((outline-invisible-p (line-end-position))
23422 (case type
23423 (headline
23424 (org-with-limited-levels (outline-next-visible-heading 1)))
23425 ;; At a plain list, make sure we move to the next item
23426 ;; instead of skipping the whole list.
23427 (plain-list (forward-char)
23428 (org-forward-paragraph))
23429 (otherwise (goto-char end))))
23430 ((>= (point) contents-end) (goto-char end))
23431 ((>= (point) contents-begin)
23432 ;; This can only happen on paragraphs and plain lists.
23433 (case type
23434 (paragraph (goto-char end))
23435 ;; At a plain list, try to move to second element in
23436 ;; first item, if possible.
23437 (plain-list (end-of-line)
23438 (org-forward-paragraph))))
23439 ;; When contents start on the middle of a line (e.g. in
23440 ;; items and footnote definitions), try to reach first
23441 ;; element starting after current line.
23442 ((> (line-end-position) contents-begin)
23443 (end-of-line)
23444 (org-forward-paragraph))
23445 (t (goto-char contents-begin)))))
23446
23447 (defun org-backward-paragraph ()
23448 "Move backward to start of previous paragraph or equivalent.
23449
23450 The function moves point to the beginning of the current
23451 structural element, which can be a paragraph, a table, a list
23452 item, etc., or to the beginning of the previous visible one if
23453 point is already there. It also provides some special moves for
23454 convenience:
23455
23456 - On an affiliated keyword, jump to the first one.
23457 - On a table or a property drawer, move to its beginning.
23458 - On a verse or source block, stop before blank lines."
23459 (interactive)
23460 (when (bobp) (user-error "Cannot move further up"))
23461 (let* ((deactivate-mark nil)
23462 (element (org-element-at-point))
23463 (type (org-element-type element))
23464 (contents-begin (org-element-property :contents-begin element))
23465 (contents-end (org-element-property :contents-end element))
23466 (post-affiliated (org-element-property :post-affiliated element))
23467 (begin (org-element-property :begin element)))
23468 (cond
23469 ((not element) (goto-char (point-min)))
23470 ((= (point) begin)
23471 (backward-char)
23472 (org-backward-paragraph))
23473 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23474 ((memq type '(node-property table-row))
23475 (goto-char (org-element-property
23476 :post-affiliated (org-element-property :parent element))))
23477 ((memq type '(property-drawer table)) (goto-char begin))
23478 ((memq type '(src-block verse-block))
23479 (when (eq type 'src-block)
23480 (setq contents-begin
23481 (save-excursion (goto-char begin) (forward-line) (point))))
23482 (if (= (point) contents-begin) (goto-char post-affiliated)
23483 ;; Inside a verse block, see blank lines as paragraph
23484 ;; separators.
23485 (let ((origin (point)))
23486 (skip-chars-backward " \r\t\n" contents-begin)
23487 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23488 (skip-chars-forward " \r\t\n" origin)
23489 (if (= (point) origin) (goto-char contents-begin)
23490 (beginning-of-line))))))
23491 ((not contents-begin) (goto-char (or post-affiliated begin)))
23492 ((eq type 'paragraph)
23493 (goto-char contents-begin)
23494 ;; When at first paragraph in an item or a footnote definition,
23495 ;; move directly to beginning of line.
23496 (let ((parent-contents
23497 (org-element-property
23498 :contents-begin (org-element-property :parent element))))
23499 (when (and parent-contents (= parent-contents contents-begin))
23500 (beginning-of-line))))
23501 ;; At the end of a greater element, move to the beginning of the
23502 ;; last element within.
23503 ((>= (point) contents-end)
23504 (goto-char (1- contents-end))
23505 (org-backward-paragraph))
23506 (t (goto-char (or post-affiliated begin))))
23507 ;; Ensure we never leave point invisible.
23508 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23509
23510 (defun org-forward-element ()
23511 "Move forward by one element.
23512 Move to the next element at the same level, when possible."
23513 (interactive)
23514 (cond ((eobp) (user-error "Cannot move further down"))
23515 ((org-with-limited-levels (org-at-heading-p))
23516 (let ((origin (point)))
23517 (goto-char (org-end-of-subtree nil t))
23518 (unless (org-with-limited-levels (org-at-heading-p))
23519 (goto-char origin)
23520 (user-error "Cannot move further down"))))
23521 (t
23522 (let* ((elem (org-element-at-point))
23523 (end (org-element-property :end elem))
23524 (parent (org-element-property :parent elem)))
23525 (cond ((and parent (= (org-element-property :contents-end parent) end))
23526 (goto-char (org-element-property :end parent)))
23527 ((integer-or-marker-p end) (goto-char end))
23528 (t (message "No element at point")))))))
23529
23530 (defun org-backward-element ()
23531 "Move backward by one element.
23532 Move to the previous element at the same level, when possible."
23533 (interactive)
23534 (cond ((bobp) (user-error "Cannot move further up"))
23535 ((org-with-limited-levels (org-at-heading-p))
23536 ;; At a headline, move to the previous one, if any, or stay
23537 ;; here.
23538 (let ((origin (point)))
23539 (org-with-limited-levels (org-backward-heading-same-level 1))
23540 ;; When current headline has no sibling above, move to its
23541 ;; parent.
23542 (when (= (point) origin)
23543 (or (org-with-limited-levels (org-up-heading-safe))
23544 (progn (goto-char origin)
23545 (user-error "Cannot move further up"))))))
23546 (t
23547 (let* ((trail (org-element-at-point 'keep-trail))
23548 (elem (car trail))
23549 (prev-elem (nth 1 trail))
23550 (beg (org-element-property :begin elem)))
23551 (cond
23552 ;; Move to beginning of current element if point isn't
23553 ;; there already.
23554 ((null beg) (message "No element at point"))
23555 ((/= (point) beg) (goto-char beg))
23556 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23557 ((org-before-first-heading-p) (goto-char (point-min)))
23558 (t (org-back-to-heading)))))))
23559
23560 (defun org-up-element ()
23561 "Move to upper element."
23562 (interactive)
23563 (if (org-with-limited-levels (org-at-heading-p))
23564 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23565 (let* ((elem (org-element-at-point))
23566 (parent (org-element-property :parent elem)))
23567 (if parent (goto-char (org-element-property :begin parent))
23568 (if (org-with-limited-levels (org-before-first-heading-p))
23569 (user-error "No surrounding element")
23570 (org-with-limited-levels (org-back-to-heading)))))))
23571
23572 (defvar org-element-greater-elements)
23573 (defun org-down-element ()
23574 "Move to inner element."
23575 (interactive)
23576 (let ((element (org-element-at-point)))
23577 (cond
23578 ((memq (org-element-type element) '(plain-list table))
23579 (goto-char (org-element-property :contents-begin element))
23580 (forward-char))
23581 ((memq (org-element-type element) org-element-greater-elements)
23582 ;; If contents are hidden, first disclose them.
23583 (when (org-element-property :hiddenp element) (org-cycle))
23584 (goto-char (or (org-element-property :contents-begin element)
23585 (user-error "No content for this element"))))
23586 (t (user-error "No inner element")))))
23587
23588 (defun org-drag-element-backward ()
23589 "Move backward element at point."
23590 (interactive)
23591 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23592 (let* ((trail (org-element-at-point 'keep-trail))
23593 (elem (car trail))
23594 (prev-elem (nth 1 trail)))
23595 ;; Error out if no previous element or previous element is
23596 ;; a parent of the current one.
23597 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23598 (user-error "Cannot drag element backward")
23599 (let ((pos (point)))
23600 (org-element-swap-A-B prev-elem elem)
23601 (goto-char (+ (org-element-property :begin prev-elem)
23602 (- pos (org-element-property :begin elem)))))))))
23603
23604 (defun org-drag-element-forward ()
23605 "Move forward element at point."
23606 (interactive)
23607 (let* ((pos (point))
23608 (elem (org-element-at-point)))
23609 (when (= (point-max) (org-element-property :end elem))
23610 (user-error "Cannot drag element forward"))
23611 (goto-char (org-element-property :end elem))
23612 (let ((next-elem (org-element-at-point)))
23613 (when (or (org-element-nested-p elem next-elem)
23614 (and (eq (org-element-type next-elem) 'headline)
23615 (not (eq (org-element-type elem) 'headline))))
23616 (goto-char pos)
23617 (user-error "Cannot drag element forward"))
23618 ;; Compute new position of point: it's shifted by NEXT-ELEM
23619 ;; body's length (without final blanks) and by the length of
23620 ;; blanks between ELEM and NEXT-ELEM.
23621 (let ((size-next (- (save-excursion
23622 (goto-char (org-element-property :end next-elem))
23623 (skip-chars-backward " \r\t\n")
23624 (forward-line)
23625 ;; Small correction if buffer doesn't end
23626 ;; with a newline character.
23627 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23628 (org-element-property :begin next-elem)))
23629 (size-blank (- (org-element-property :end elem)
23630 (save-excursion
23631 (goto-char (org-element-property :end elem))
23632 (skip-chars-backward " \r\t\n")
23633 (forward-line)
23634 (point)))))
23635 (org-element-swap-A-B elem next-elem)
23636 (goto-char (+ pos size-next size-blank))))))
23637
23638 (defun org-drag-line-forward (arg)
23639 "Drag the line at point ARG lines forward."
23640 (interactive "p")
23641 (dotimes (n (abs arg))
23642 (let ((c (current-column)))
23643 (if (< 0 arg)
23644 (progn
23645 (beginning-of-line 2)
23646 (transpose-lines 1)
23647 (beginning-of-line 0))
23648 (transpose-lines 1)
23649 (beginning-of-line -1))
23650 (org-move-to-column c))))
23651
23652 (defun org-drag-line-backward (arg)
23653 "Drag the line at point ARG lines backward."
23654 (interactive "p")
23655 (org-drag-line-forward (- arg)))
23656
23657 (defun org-mark-element ()
23658 "Put point at beginning of this element, mark at end.
23659
23660 Interactively, if this command is repeated or (in Transient Mark
23661 mode) if the mark is active, it marks the next element after the
23662 ones already marked."
23663 (interactive)
23664 (let (deactivate-mark)
23665 (if (and (org-called-interactively-p 'any)
23666 (or (and (eq last-command this-command) (mark t))
23667 (and transient-mark-mode mark-active)))
23668 (set-mark
23669 (save-excursion
23670 (goto-char (mark))
23671 (goto-char (org-element-property :end (org-element-at-point)))))
23672 (let ((element (org-element-at-point)))
23673 (end-of-line)
23674 (push-mark (org-element-property :end element) t t)
23675 (goto-char (org-element-property :begin element))))))
23676
23677 (defun org-narrow-to-element ()
23678 "Narrow buffer to current element."
23679 (interactive)
23680 (let ((elem (org-element-at-point)))
23681 (cond
23682 ((eq (car elem) 'headline)
23683 (narrow-to-region
23684 (org-element-property :begin elem)
23685 (org-element-property :end elem)))
23686 ((memq (car elem) org-element-greater-elements)
23687 (narrow-to-region
23688 (org-element-property :contents-begin elem)
23689 (org-element-property :contents-end elem)))
23690 (t
23691 (narrow-to-region
23692 (org-element-property :begin elem)
23693 (org-element-property :end elem))))))
23694
23695 (defun org-transpose-element ()
23696 "Transpose current and previous elements, keeping blank lines between.
23697 Point is moved after both elements."
23698 (interactive)
23699 (org-skip-whitespace)
23700 (let ((end (org-element-property :end (org-element-at-point))))
23701 (org-drag-element-backward)
23702 (goto-char end)))
23703
23704 (defun org-unindent-buffer ()
23705 "Un-indent the visible part of the buffer.
23706 Relative indentation (between items, inside blocks, etc.) isn't
23707 modified."
23708 (interactive)
23709 (unless (eq major-mode 'org-mode)
23710 (user-error "Cannot un-indent a buffer not in Org mode"))
23711 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23712 unindent-tree ; For byte-compiler.
23713 (unindent-tree
23714 (function
23715 (lambda (contents)
23716 (mapc
23717 (lambda (element)
23718 (if (memq (org-element-type element) '(headline section))
23719 (funcall unindent-tree (org-element-contents element))
23720 (save-excursion
23721 (save-restriction
23722 (narrow-to-region
23723 (org-element-property :begin element)
23724 (org-element-property :end element))
23725 (org-do-remove-indentation)))))
23726 (reverse contents))))))
23727 (funcall unindent-tree (org-element-contents parse-tree))))
23728
23729 (defun org-show-subtree ()
23730 "Show everything after this heading at deeper levels."
23731 (interactive)
23732 (outline-flag-region
23733 (point)
23734 (save-excursion
23735 (org-end-of-subtree t t))
23736 nil))
23737
23738 (defun org-show-entry ()
23739 "Show the body directly following this heading.
23740 Show the heading too, if it is currently invisible."
23741 (interactive)
23742 (save-excursion
23743 (condition-case nil
23744 (progn
23745 (org-back-to-heading t)
23746 (outline-flag-region
23747 (max (point-min) (1- (point)))
23748 (save-excursion
23749 (if (re-search-forward
23750 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23751 (match-beginning 1)
23752 (point-max)))
23753 nil)
23754 (org-cycle-hide-drawers 'children))
23755 (error nil))))
23756
23757 (defun org-make-options-regexp (kwds &optional extra)
23758 "Make a regular expression for keyword lines."
23759 (concat
23760 "^#\\+\\("
23761 (mapconcat 'regexp-quote kwds "\\|")
23762 (if extra (concat "\\|" extra))
23763 "\\):[ \t]*\\(.*\\)"))
23764
23765 ;; Make isearch reveal the necessary context
23766 (defun org-isearch-end ()
23767 "Reveal context after isearch exits."
23768 (when isearch-success ; only if search was successful
23769 (if (featurep 'xemacs)
23770 ;; Under XEmacs, the hook is run in the correct place,
23771 ;; we directly show the context.
23772 (org-show-context 'isearch)
23773 ;; In Emacs the hook runs *before* restoring the overlays.
23774 ;; So we have to use a one-time post-command-hook to do this.
23775 ;; (Emacs 22 has a special variable, see function `org-mode')
23776 (unless (and (boundp 'isearch-mode-end-hook-quit)
23777 isearch-mode-end-hook-quit)
23778 ;; Only when the isearch was not quitted.
23779 (org-add-hook 'post-command-hook 'org-isearch-post-command
23780 'append 'local)))
23781 (org-fix-ellipsis-at-bol)))
23782
23783 (defun org-isearch-post-command ()
23784 "Remove self from hook, and show context."
23785 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23786 (org-show-context 'isearch))
23787
23788
23789 ;;;; Integration with and fixes for other packages
23790
23791 ;;; Imenu support
23792
23793 (defvar org-imenu-markers nil
23794 "All markers currently used by Imenu.")
23795 (make-variable-buffer-local 'org-imenu-markers)
23796
23797 (defun org-imenu-new-marker (&optional pos)
23798 "Return a new marker for use by Imenu, and remember the marker."
23799 (let ((m (make-marker)))
23800 (move-marker m (or pos (point)))
23801 (push m org-imenu-markers)
23802 m))
23803
23804 (defun org-imenu-get-tree ()
23805 "Produce the index for Imenu."
23806 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23807 (setq org-imenu-markers nil)
23808 (let* ((n org-imenu-depth)
23809 (re (concat "^" (org-get-limited-outline-regexp)))
23810 (subs (make-vector (1+ n) nil))
23811 (last-level 0)
23812 m level head0 head)
23813 (save-excursion
23814 (save-restriction
23815 (widen)
23816 (goto-char (point-max))
23817 (while (re-search-backward re nil t)
23818 (setq level (org-reduced-level (funcall outline-level)))
23819 (when (and (<= level n)
23820 (looking-at org-complex-heading-regexp)
23821 (setq head0 (org-match-string-no-properties 4)))
23822 (setq head (org-link-display-format head0)
23823 m (org-imenu-new-marker))
23824 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23825 (if (>= level last-level)
23826 (push (cons head m) (aref subs level))
23827 (push (cons head (aref subs (1+ level))) (aref subs level))
23828 (loop for i from (1+ level) to n do (aset subs i nil)))
23829 (setq last-level level)))))
23830 (aref subs 1)))
23831
23832 (eval-after-load "imenu"
23833 '(progn
23834 (add-hook 'imenu-after-jump-hook
23835 (lambda ()
23836 (if (derived-mode-p 'org-mode)
23837 (org-show-context 'org-goto))))))
23838
23839 (defun org-link-display-format (link)
23840 "Replace a link with its the description.
23841 If there is no description, use the link target."
23842 (save-match-data
23843 (if (string-match org-bracket-link-analytic-regexp link)
23844 (replace-match (if (match-end 5)
23845 (match-string 5 link)
23846 (concat (match-string 1 link)
23847 (match-string 3 link)))
23848 nil t link)
23849 link)))
23850
23851 (defun org-toggle-link-display ()
23852 "Toggle the literal or descriptive display of links."
23853 (interactive)
23854 (if org-descriptive-links
23855 (progn (org-remove-from-invisibility-spec '(org-link))
23856 (org-restart-font-lock)
23857 (setq org-descriptive-links nil))
23858 (progn (add-to-invisibility-spec '(org-link))
23859 (org-restart-font-lock)
23860 (setq org-descriptive-links t))))
23861
23862 ;; Speedbar support
23863
23864 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23865 "Overlay marking the agenda restriction line in speedbar.")
23866 (overlay-put org-speedbar-restriction-lock-overlay
23867 'face 'org-agenda-restriction-lock)
23868 (overlay-put org-speedbar-restriction-lock-overlay
23869 'help-echo "Agendas are currently limited to this item.")
23870 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23871
23872 (defun org-speedbar-set-agenda-restriction ()
23873 "Restrict future agenda commands to the location at point in speedbar.
23874 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23875 (interactive)
23876 (require 'org-agenda)
23877 (let (p m tp np dir txt)
23878 (cond
23879 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23880 'org-imenu t))
23881 (setq m (get-text-property p 'org-imenu-marker))
23882 (with-current-buffer (marker-buffer m)
23883 (goto-char m)
23884 (org-agenda-set-restriction-lock 'subtree)))
23885 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23886 'speedbar-function 'speedbar-find-file))
23887 (setq tp (previous-single-property-change
23888 (1+ p) 'speedbar-function)
23889 np (next-single-property-change
23890 tp 'speedbar-function)
23891 dir (speedbar-line-directory)
23892 txt (buffer-substring-no-properties (or tp (point-min))
23893 (or np (point-max))))
23894 (with-current-buffer (find-file-noselect
23895 (let ((default-directory dir))
23896 (expand-file-name txt)))
23897 (unless (derived-mode-p 'org-mode)
23898 (user-error "Cannot restrict to non-Org-mode file"))
23899 (org-agenda-set-restriction-lock 'file)))
23900 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23901 (move-overlay org-speedbar-restriction-lock-overlay
23902 (point-at-bol) (point-at-eol))
23903 (setq current-prefix-arg nil)
23904 (org-agenda-maybe-redo)))
23905
23906 (defvar speedbar-file-key-map)
23907 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23908 (eval-after-load "speedbar"
23909 '(progn
23910 (speedbar-add-supported-extension ".org")
23911 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23912 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23913 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23914 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23915 (add-hook 'speedbar-visiting-tag-hook
23916 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23917
23918 ;;; Fixes and Hacks for problems with other packages
23919
23920 ;; Make flyspell not check words in links, to not mess up our keymap
23921 (defvar org-element-affiliated-keywords) ; From org-element.el
23922 (defvar org-element-block-name-alist) ; From org-element.el
23923 (defun org-mode-flyspell-verify ()
23924 "Don't let flyspell put overlays at active buttons, or on
23925 {todo,all-time,additional-option-like}-keywords."
23926 (require 'org-element) ; For `org-element-affiliated-keywords'
23927 (let ((pos (max (1- (point)) (point-min)))
23928 (word (thing-at-point 'word)))
23929 (and (not (get-text-property pos 'keymap))
23930 (not (get-text-property pos 'org-no-flyspell))
23931 (not (member word org-todo-keywords-1))
23932 (not (member word org-all-time-keywords))
23933 (not (member word org-options-keywords))
23934 (not (member word (mapcar 'car org-startup-options)))
23935 (not (member-ignore-case word org-element-affiliated-keywords))
23936 (not (member-ignore-case word (org-get-export-keywords)))
23937 (not (member-ignore-case
23938 word (mapcar 'car org-element-block-name-alist)))
23939 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23940 (not (org-in-src-block-p)))))
23941
23942 (defun org-remove-flyspell-overlays-in (beg end)
23943 "Remove flyspell overlays in region."
23944 (and (org-bound-and-true-p flyspell-mode)
23945 (fboundp 'flyspell-delete-region-overlays)
23946 (flyspell-delete-region-overlays beg end))
23947 (add-text-properties beg end '(org-no-flyspell t)))
23948
23949 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23950 (eval-after-load "bookmark"
23951 '(if (boundp 'bookmark-after-jump-hook)
23952 ;; We can use the hook
23953 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23954 ;; Hook not available, use advice
23955 (defadvice bookmark-jump (after org-make-visible activate)
23956 "Make the position visible."
23957 (org-bookmark-jump-unhide))))
23958
23959 ;; Make sure saveplace shows the location if it was hidden
23960 (eval-after-load "saveplace"
23961 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23962 "Make the position visible."
23963 (org-bookmark-jump-unhide)))
23964
23965 ;; Make sure ecb shows the location if it was hidden
23966 (eval-after-load "ecb"
23967 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23968 "Make hierarchy visible when jumping into location from ECB tree buffer."
23969 (if (derived-mode-p 'org-mode)
23970 (org-show-context))))
23971
23972 (defun org-bookmark-jump-unhide ()
23973 "Unhide the current position, to show the bookmark location."
23974 (and (derived-mode-p 'org-mode)
23975 (or (outline-invisible-p)
23976 (save-excursion (goto-char (max (point-min) (1- (point))))
23977 (outline-invisible-p)))
23978 (org-show-context 'bookmark-jump)))
23979
23980 ;; Make session.el ignore our circular variable
23981 (defvar session-globals-exclude)
23982 (eval-after-load "session"
23983 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23984
23985 ;;;; Finish up
23986
23987 (provide 'org)
23988
23989 (run-hooks 'org-load-hook)
23990
23991 ;;; org.el ends here