]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
Fix byte-compiler warnings about looking-back.
[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-2015 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-add-archive-files "org-archive" (files))
115
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-update-time-maybe "org-clock" ())
126 (declare-function org-clocktable-shift "org-clock" (dir n))
127
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-edit-field "org-table" (arg))
132 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
133 (declare-function org-table-set-constants "org-table" ())
134 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
135 (declare-function org-id-get-create "org-id" (&optional force))
136 (declare-function org-id-find-id-file "org-id" (id))
137 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
138 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
139 (declare-function org-agenda-redo "org-agenda" (&optional all))
140 (declare-function org-table-align "org-table" ())
141 (declare-function org-table-begin "org-table" (&optional table-type))
142 (declare-function org-table-blank-field "org-table" ())
143 (declare-function org-table-end "org-table" (&optional table-type))
144 (declare-function org-table-insert-row "org-table" (&optional arg))
145 (declare-function org-table-paste-rectangle "org-table" ())
146 (declare-function org-table-maybe-eval-formula "org-table" ())
147 (declare-function org-table-maybe-recalculate-line "org-table" ())
148
149 (declare-function org-element--parse-objects "org-element"
150 (beg end acc restriction))
151 (declare-function org-element-at-point "org-element" (&optional keep-trail))
152 (declare-function org-element-contents "org-element" (element))
153 (declare-function org-element-context "org-element" (&optional element))
154 (declare-function org-element-interpret-data "org-element"
155 (data &optional parent))
156 (declare-function org-element-map "org-element"
157 (data types fun &optional info first-match no-recursion))
158 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
159 (declare-function org-element-parse-buffer "org-element"
160 (&optional granularity visible-only))
161 (declare-function org-element-property "org-element" (property element))
162 (declare-function org-element-put-property "org-element"
163 (element property value))
164 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
165 (declare-function org-element--parse-objects "org-element"
166 (beg end acc restriction))
167 (declare-function org-element-parse-buffer "org-element"
168 (&optional granularity visible-only))
169 (declare-function org-element-restriction "org-element" (element))
170 (declare-function org-element-type "org-element" (element))
171
172 ;; load languages based on value of `org-babel-load-languages'
173 (defvar org-babel-load-languages)
174
175 ;;;###autoload
176 (defun org-babel-do-load-languages (sym value)
177 "Load the languages defined in `org-babel-load-languages'."
178 (set-default sym value)
179 (mapc (lambda (pair)
180 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
181 (if active
182 (progn
183 (require (intern (concat "ob-" lang))))
184 (progn
185 (funcall 'fmakunbound
186 (intern (concat "org-babel-execute:" lang)))
187 (funcall 'fmakunbound
188 (intern (concat "org-babel-expand-body:" lang)))))))
189 org-babel-load-languages))
190
191 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
192 ;;;###autoload
193 (defun org-babel-load-file (file &optional compile)
194 "Load Emacs Lisp source code blocks in the Org-mode FILE.
195 This function exports the source code using `org-babel-tangle'
196 and then loads the resulting file using `load-file'. With prefix
197 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
198 file to byte-code before it is loaded."
199 (interactive "fFile to load: \nP")
200 (require 'ob-core)
201 (let* ((age (lambda (file)
202 (float-time
203 (time-subtract (current-time)
204 (nth 5 (or (file-attributes (file-truename file))
205 (file-attributes file)))))))
206 (base-name (file-name-sans-extension file))
207 (exported-file (concat base-name ".el")))
208 ;; tangle if the org-mode file is newer than the elisp file
209 (unless (and (file-exists-p exported-file)
210 (> (funcall age file) (funcall age exported-file)))
211 (setq exported-file
212 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
213 (message "%s %s"
214 (if compile
215 (progn (byte-compile-file exported-file 'load)
216 "Compiled and loaded")
217 (progn (load-file exported-file) "Loaded"))
218 exported-file)))
219
220 (defcustom org-babel-load-languages '((emacs-lisp . t))
221 "Languages which can be evaluated in Org-mode buffers.
222 This list can be used to load support for any of the languages
223 below, note that each language will depend on a different set of
224 system executables and/or Emacs modes. When a language is
225 \"loaded\", then code blocks in that language can be evaluated
226 with `org-babel-execute-src-block' bound by default to C-c
227 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
228 be set to remove code block evaluation from the C-c C-c
229 keybinding. By default only Emacs Lisp (which has no
230 requirements) is loaded."
231 :group 'org-babel
232 :set 'org-babel-do-load-languages
233 :version "24.1"
234 :type '(alist :tag "Babel Languages"
235 :key-type
236 (choice
237 (const :tag "Awk" awk)
238 (const :tag "C" C)
239 (const :tag "R" R)
240 (const :tag "Asymptote" asymptote)
241 (const :tag "Calc" calc)
242 (const :tag "Clojure" clojure)
243 (const :tag "CSS" css)
244 (const :tag "Ditaa" ditaa)
245 (const :tag "Dot" dot)
246 (const :tag "Emacs Lisp" emacs-lisp)
247 (const :tag "Fortran" fortran)
248 (const :tag "Gnuplot" gnuplot)
249 (const :tag "Haskell" haskell)
250 (const :tag "IO" io)
251 (const :tag "Java" java)
252 (const :tag "Javascript" js)
253 (const :tag "LaTeX" latex)
254 (const :tag "Ledger" ledger)
255 (const :tag "Lilypond" lilypond)
256 (const :tag "Lisp" lisp)
257 (const :tag "Makefile" makefile)
258 (const :tag "Maxima" maxima)
259 (const :tag "Matlab" matlab)
260 (const :tag "Mscgen" mscgen)
261 (const :tag "Ocaml" ocaml)
262 (const :tag "Octave" octave)
263 (const :tag "Org" org)
264 (const :tag "Perl" perl)
265 (const :tag "Pico Lisp" picolisp)
266 (const :tag "PlantUML" plantuml)
267 (const :tag "Python" python)
268 (const :tag "Ruby" ruby)
269 (const :tag "Sass" sass)
270 (const :tag "Scala" scala)
271 (const :tag "Scheme" scheme)
272 (const :tag "Screen" screen)
273 (const :tag "Shell Script" sh)
274 (const :tag "Shen" shen)
275 (const :tag "Sql" sql)
276 (const :tag "Sqlite" sqlite))
277 :value-type (boolean :tag "Activate" :value t)))
278
279 ;;;; Customization variables
280 (defcustom org-clone-delete-id nil
281 "Remove ID property of clones of a subtree.
282 When non-nil, clones of a subtree don't inherit the ID property.
283 Otherwise they inherit the ID property with a new unique
284 identifier."
285 :type 'boolean
286 :version "24.1"
287 :group 'org-id)
288
289 ;;; Version
290 (org-check-version)
291
292 ;;;###autoload
293 (defun org-version (&optional here full message)
294 "Show the org-mode version in the echo area.
295 With prefix argument HERE, insert it at point.
296 When FULL is non-nil, use a verbose version string.
297 When MESSAGE is non-nil, display a message with the version."
298 (interactive "P")
299 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
300 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
301 (load-suffixes (list ".el"))
302 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
303 (org-trash (or
304 (and (fboundp 'org-release) (fboundp 'org-git-version))
305 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
306 (load-suffixes save-load-suffixes)
307 (org-version (org-release))
308 (git-version (org-git-version))
309 (version (format "Org-mode version %s (%s @ %s)"
310 org-version
311 git-version
312 (if org-install-dir
313 (if (string= org-dir org-install-dir)
314 org-install-dir
315 (concat "mixed installation! " org-install-dir " and " org-dir))
316 "org-loaddefs.el can not be found!")))
317 (version1 (if full version org-version)))
318 (if (org-called-interactively-p 'interactive)
319 (if here
320 (insert version)
321 (message version))
322 (if message (message version1))
323 version1)))
324
325 (defconst org-version (org-version))
326
327 ;;; Compatibility constants
328
329 ;;; The custom variables
330
331 (defgroup org nil
332 "Outline-based notes management and organizer."
333 :tag "Org"
334 :group 'outlines
335 :group 'calendar)
336
337 (defcustom org-mode-hook nil
338 "Mode hook for Org-mode, run after the mode was turned on."
339 :group 'org
340 :type 'hook)
341
342 (defcustom org-load-hook nil
343 "Hook that is run after org.el has been loaded."
344 :group 'org
345 :type 'hook)
346
347 (defcustom org-log-buffer-setup-hook nil
348 "Hook that is run after an Org log buffer is created."
349 :group 'org
350 :version "24.1"
351 :type 'hook)
352
353 (defvar org-modules) ; defined below
354 (defvar org-modules-loaded nil
355 "Have the modules been loaded already?")
356
357 (defun org-load-modules-maybe (&optional force)
358 "Load all extensions listed in `org-modules'."
359 (when (or force (not org-modules-loaded))
360 (mapc (lambda (ext)
361 (condition-case nil (require ext)
362 (error (message "Problems while trying to load feature `%s'" ext))))
363 org-modules)
364 (setq org-modules-loaded t)))
365
366 (defun org-set-modules (var value)
367 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
368 (set var value)
369 (when (featurep 'org)
370 (org-load-modules-maybe 'force)))
371
372 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
373 "Modules that should always be loaded together with org.el.
374
375 If a description starts with <C>, the file is not part of Emacs
376 and loading it will require that you have downloaded and properly
377 installed the Org mode distribution.
378
379 You can also use this system to load external packages (i.e. neither Org
380 core modules, nor modules from the CONTRIB directory). Just add symbols
381 to the end of the list. If the package is called org-xyz.el, then you need
382 to add the symbol `xyz', and the package must have a call to:
383
384 \(provide 'org-xyz)
385
386 For export specific modules, see also `org-export-backends'."
387 :group 'org
388 :set 'org-set-modules
389 :version "24.4"
390 :package-version '(Org . "8.0")
391 :type
392 '(set :greedy t
393 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
394 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
395 (const :tag " crypt: Encryption of subtrees" org-crypt)
396 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
397 (const :tag " docview: Links to doc-view buffers" org-docview)
398 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
399 (const :tag " habit: Track your consistency with habits" org-habit)
400 (const :tag " id: Global IDs for identifying entries" org-id)
401 (const :tag " info: Links to Info nodes" org-info)
402 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
403 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
404 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
405 (const :tag " mouse: Additional mouse support" org-mouse)
406 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
407 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
408 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
409
410 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
411 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
412 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
413 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
414 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
415 (const :tag "C collector: Collect properties into tables" org-collector)
416 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
417 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
418 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
419 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
420 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
421 (const :tag "C eval: Include command output as text" org-eval)
422 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
423 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
424 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
425 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
426 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
427 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
428 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
429 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
430 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
431 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
432 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
433 (const :tag "C mew: Links to Mew folders/messages" org-mew)
434 (const :tag "C mtags: Support for muse-like tags" org-mtags)
435 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
436 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
437 (const :tag "C registry: A registry for Org-mode links" org-registry)
438 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
439 (const :tag "C secretary: Team management with org-mode" org-secretary)
440 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
441 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
442 (const :tag "C track: Keep up with Org-mode development" org-track)
443 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
444 (const :tag "C vm: Links to VM folders/messages" org-vm)
445 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
446 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
447 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
448
449 (defvar org-export--registered-backends) ; From ox.el.
450 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
451 (declare-function org-export-backend-name "ox" (backend))
452 (defcustom org-export-backends '(ascii html icalendar latex)
453 "List of export back-ends that should be always available.
454
455 If a description starts with <C>, the file is not part of Emacs
456 and loading it will require that you have downloaded and properly
457 installed the Org mode distribution.
458
459 Unlike to `org-modules', libraries in this list will not be
460 loaded along with Org, but only once the export framework is
461 needed.
462
463 This variable needs to be set before org.el is loaded. If you
464 need to make a change while Emacs is running, use the customize
465 interface or run the following code, where VAL stands for the new
466 value of the variable, after updating it:
467
468 \(progn
469 \(setq org-export--registered-backends
470 \(org-remove-if-not
471 \(lambda (backend)
472 \(let ((name (org-export-backend-name backend)))
473 \(or (memq name val)
474 \(catch 'parentp
475 \(dolist (b val)
476 \(and (org-export-derived-backend-p b name)
477 \(throw 'parentp t)))))))
478 org-export--registered-backends))
479 \(let ((new-list (mapcar 'org-export-backend-name
480 org-export--registered-backends)))
481 \(dolist (backend val)
482 \(cond
483 \((not (load (format \"ox-%s\" backend) t t))
484 \(message \"Problems while trying to load export back-end `%s'\"
485 backend))
486 \((not (memq backend new-list)) (push backend new-list))))
487 \(set-default 'org-export-backends new-list)))
488
489 Adding a back-end to this list will also pull the back-end it
490 depends on, if any."
491 :group 'org
492 :group 'org-export
493 :version "24.4"
494 :package-version '(Org . "8.0")
495 :initialize 'custom-initialize-set
496 :set (lambda (var val)
497 (if (not (featurep 'ox)) (set-default var val)
498 ;; Any back-end not required anymore (not present in VAL and not
499 ;; a parent of any back-end in the new value) is removed from the
500 ;; list of registered back-ends.
501 (setq org-export--registered-backends
502 (org-remove-if-not
503 (lambda (backend)
504 (let ((name (org-export-backend-name backend)))
505 (or (memq name val)
506 (catch 'parentp
507 (dolist (b val)
508 (and (org-export-derived-backend-p b name)
509 (throw 'parentp t)))))))
510 org-export--registered-backends))
511 ;; Now build NEW-LIST of both new back-ends and required
512 ;; parents.
513 (let ((new-list (mapcar 'org-export-backend-name
514 org-export--registered-backends)))
515 (dolist (backend val)
516 (cond
517 ((not (load (format "ox-%s" backend) t t))
518 (message "Problems while trying to load export back-end `%s'"
519 backend))
520 ((not (memq backend new-list)) (push backend new-list))))
521 ;; Set VAR to that list with fixed dependencies.
522 (set-default var new-list))))
523 :type '(set :greedy t
524 (const :tag " ascii Export buffer to ASCII format" ascii)
525 (const :tag " beamer Export buffer to Beamer presentation" beamer)
526 (const :tag " html Export buffer to HTML format" html)
527 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
528 (const :tag " latex Export buffer to LaTeX format" latex)
529 (const :tag " man Export buffer to MAN format" man)
530 (const :tag " md Export buffer to Markdown format" md)
531 (const :tag " odt Export buffer to ODT format" odt)
532 (const :tag " org Export buffer to Org format" org)
533 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
534 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
535 (const :tag "C deck Export buffer to deck.js presentations" deck)
536 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
537 (const :tag "C groff Export buffer to Groff format" groff)
538 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
539 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
540 (const :tag "C s5 Export buffer to s5 presentations" s5)
541 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
542
543 (eval-after-load 'ox
544 '(mapc
545 (lambda (backend)
546 (condition-case nil (require (intern (format "ox-%s" backend)))
547 (error (message "Problems while trying to load export back-end `%s'"
548 backend))))
549 org-export-backends))
550
551 (defcustom org-support-shift-select nil
552 "Non-nil means make shift-cursor commands select text when possible.
553
554 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
555 start selecting a region, or enlarge regions started in this way.
556 In Org-mode, in special contexts, these same keys are used for
557 other purposes, important enough to compete with shift selection.
558 Org tries to balance these needs by supporting `shift-select-mode'
559 outside these special contexts, under control of this variable.
560
561 The default of this variable is nil, to avoid confusing behavior. Shifted
562 cursor keys will then execute Org commands in the following contexts:
563 - on a headline, changing TODO state (left/right) and priority (up/down)
564 - on a time stamp, changing the time
565 - in a plain list item, changing the bullet type
566 - in a property definition line, switching between allowed values
567 - in the BEGIN line of a clock table (changing the time block).
568 Outside these contexts, the commands will throw an error.
569
570 When this variable is t and the cursor is not in a special
571 context, Org-mode will support shift-selection for making and
572 enlarging regions. To make this more effective, the bullet
573 cycling will no longer happen anywhere in an item line, but only
574 if the cursor is exactly on the bullet.
575
576 If you set this variable to the symbol `always', then the keys
577 will not be special in headlines, property lines, and item lines,
578 to make shift selection work there as well. If this is what you
579 want, you can use the following alternative commands: `C-c C-t'
580 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
581 can be used to switch TODO sets, `C-c -' to cycle item bullet
582 types, and properties can be edited by hand or in column view.
583
584 However, when the cursor is on a timestamp, shift-cursor commands
585 will still edit the time stamp - this is just too good to give up.
586
587 XEmacs user should have this variable set to nil, because
588 `shift-select-mode' is in Emacs 23 or later only."
589 :group 'org
590 :type '(choice
591 (const :tag "Never" nil)
592 (const :tag "When outside special context" t)
593 (const :tag "Everywhere except timestamps" always)))
594
595 (defcustom org-loop-over-headlines-in-active-region nil
596 "Shall some commands act upon headlines in the active region?
597
598 When set to `t', some commands will be performed in all headlines
599 within the active region.
600
601 When set to `start-level', some commands will be performed in all
602 headlines within the active region, provided that these headlines
603 are of the same level than the first one.
604
605 When set to a string, those commands will be performed on the
606 matching headlines within the active region. Such string must be
607 a tags/property/todo match as it is used in the agenda tags view.
608
609 The list of commands is: `org-schedule', `org-deadline',
610 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
611 `org-archive-to-archive-sibling'. The archiving commands skip
612 already archived entries."
613 :type '(choice (const :tag "Don't loop" nil)
614 (const :tag "All headlines in active region" t)
615 (const :tag "In active region, headlines at the same level than the first one" start-level)
616 (string :tag "Tags/Property/Todo matcher"))
617 :version "24.1"
618 :group 'org-todo
619 :group 'org-archive)
620
621 (defgroup org-startup nil
622 "Options concerning startup of Org-mode."
623 :tag "Org Startup"
624 :group 'org)
625
626 (defcustom org-startup-folded t
627 "Non-nil means entering Org-mode will switch to OVERVIEW.
628 This can also be configured on a per-file basis by adding one of
629 the following lines anywhere in the buffer:
630
631 #+STARTUP: fold (or `overview', this is equivalent)
632 #+STARTUP: nofold (or `showall', this is equivalent)
633 #+STARTUP: content
634 #+STARTUP: showeverything
635
636 By default, this option is ignored when Org opens agenda files
637 for the first time. If you want the agenda to honor the startup
638 option, set `org-agenda-inhibit-startup' to nil."
639 :group 'org-startup
640 :type '(choice
641 (const :tag "nofold: show all" nil)
642 (const :tag "fold: overview" t)
643 (const :tag "content: all headlines" content)
644 (const :tag "show everything, even drawers" showeverything)))
645
646 (defcustom org-startup-truncated t
647 "Non-nil means entering Org-mode will set `truncate-lines'.
648 This is useful since some lines containing links can be very long and
649 uninteresting. Also tables look terrible when wrapped."
650 :group 'org-startup
651 :type 'boolean)
652
653 (defcustom org-startup-indented nil
654 "Non-nil means turn on `org-indent-mode' on startup.
655 This can also be configured on a per-file basis by adding one of
656 the following lines anywhere in the buffer:
657
658 #+STARTUP: indent
659 #+STARTUP: noindent"
660 :group 'org-structure
661 :type '(choice
662 (const :tag "Not" nil)
663 (const :tag "Globally (slow on startup in large files)" t)))
664
665 (defcustom org-use-sub-superscripts t
666 "Non-nil means interpret \"_\" and \"^\" for display.
667
668 If you want to control how Org exports those characters, see
669 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
670 used to be an alias for `org-export-with-sub-superscripts' in
671 Org <8.0, it is not anymore.
672
673 When this option is turned on, you can use TeX-like syntax for
674 sub- and superscripts within the buffer. Several characters after
675 \"_\" or \"^\" will be considered as a single item - so grouping
676 with {} is normally not needed. For example, the following things
677 will be parsed as single sub- or superscripts:
678
679 10^24 or 10^tau several digits will be considered 1 item.
680 10^-12 or 10^-tau a leading sign with digits or a word
681 x^2-y^3 will be read as x^2 - y^3, because items are
682 terminated by almost any nonword/nondigit char.
683 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
684
685 Still, ambiguity is possible. So when in doubt, use {} to enclose
686 the sub/superscript. If you set this variable to the symbol `{}',
687 the braces are *required* in order to trigger interpretations as
688 sub/superscript. This can be helpful in documents that need \"_\"
689 frequently in plain text."
690 :group 'org-startup
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type '(choice
694 (const :tag "Always interpret" t)
695 (const :tag "Only with braces" {})
696 (const :tag "Never interpret" nil)))
697
698 (defcustom org-startup-with-beamer-mode nil
699 "Non-nil means turn on `org-beamer-mode' on startup.
700 This can also be configured on a per-file basis by adding one of
701 the following lines anywhere in the buffer:
702
703 #+STARTUP: beamer"
704 :group 'org-startup
705 :version "24.1"
706 :type 'boolean)
707
708 (defcustom org-startup-align-all-tables nil
709 "Non-nil means align all tables when visiting a file.
710 This is useful when the column width in tables is forced with <N> cookies
711 in table fields. Such tables will look correct only after the first re-align.
712 This can also be configured on a per-file basis by adding one of
713 the following lines anywhere in the buffer:
714 #+STARTUP: align
715 #+STARTUP: noalign"
716 :group 'org-startup
717 :type 'boolean)
718
719 (defcustom org-startup-with-inline-images nil
720 "Non-nil means show inline images when loading a new Org file.
721 This can also be configured on a per-file basis by adding one of
722 the following lines anywhere in the buffer:
723 #+STARTUP: inlineimages
724 #+STARTUP: noinlineimages"
725 :group 'org-startup
726 :version "24.1"
727 :type 'boolean)
728
729 (defcustom org-startup-with-latex-preview nil
730 "Non-nil means preview LaTeX fragments when loading a new Org file.
731
732 This can also be configured on a per-file basis by adding one of
733 the following lines anywhere in the buffer:
734 #+STARTUP: latexpreview
735 #+STARTUP: nolatexpreview"
736 :group 'org-startup
737 :version "24.4"
738 :package-version '(Org . "8.0")
739 :type 'boolean)
740
741 (defcustom org-insert-mode-line-in-empty-file nil
742 "Non-nil means insert the first line setting Org-mode in empty files.
743 When the function `org-mode' is called interactively in an empty file, this
744 normally means that the file name does not automatically trigger Org-mode.
745 To ensure that the file will always be in Org-mode in the future, a
746 line enforcing Org-mode will be inserted into the buffer, if this option
747 has been set."
748 :group 'org-startup
749 :type 'boolean)
750
751 (defcustom org-replace-disputed-keys nil
752 "Non-nil means use alternative key bindings for some keys.
753 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
754 These keys are also used by other packages like shift-selection-mode'
755 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
756 If you want to use Org-mode together with one of these other modes,
757 or more generally if you would like to move some Org-mode commands to
758 other keys, set this variable and configure the keys with the variable
759 `org-disputed-keys'.
760
761 This option is only relevant at load-time of Org-mode, and must be set
762 *before* org.el is loaded. Changing it requires a restart of Emacs to
763 become effective."
764 :group 'org-startup
765 :type 'boolean)
766
767 (defcustom org-use-extra-keys nil
768 "Non-nil means use extra key sequence definitions for certain commands.
769 This happens automatically if you run XEmacs or if `window-system'
770 is nil. This variable lets you do the same manually. You must
771 set it before loading org.
772
773 Example: on Carbon Emacs 22 running graphically, with an external
774 keyboard on a Powerbook, the default way of setting M-left might
775 not work for either Alt or ESC. Setting this variable will make
776 it work for ESC."
777 :group 'org-startup
778 :type 'boolean)
779
780 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
781
782 (defcustom org-disputed-keys
783 '(([(shift up)] . [(meta p)])
784 ([(shift down)] . [(meta n)])
785 ([(shift left)] . [(meta -)])
786 ([(shift right)] . [(meta +)])
787 ([(control shift right)] . [(meta shift +)])
788 ([(control shift left)] . [(meta shift -)]))
789 "Keys for which Org-mode and other modes compete.
790 This is an alist, cars are the default keys, second element specifies
791 the alternative to use when `org-replace-disputed-keys' is t.
792
793 Keys can be specified in any syntax supported by `define-key'.
794 The value of this option takes effect only at Org-mode's startup,
795 therefore you'll have to restart Emacs to apply it after changing."
796 :group 'org-startup
797 :type 'alist)
798
799 (defun org-key (key)
800 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
801 Or return the original if not disputed.
802 Also apply the translations defined in `org-xemacs-key-equivalents'."
803 (when org-replace-disputed-keys
804 (let* ((nkey (key-description key))
805 (x (org-find-if (lambda (x)
806 (equal (key-description (car x)) nkey))
807 org-disputed-keys)))
808 (setq key (if x (cdr x) key))))
809 (when (featurep 'xemacs)
810 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
811 key)
812
813 (defun org-find-if (predicate seq)
814 (catch 'exit
815 (while seq
816 (if (funcall predicate (car seq))
817 (throw 'exit (car seq))
818 (pop seq)))))
819
820 (defun org-defkey (keymap key def)
821 "Define a key, possibly translated, as returned by `org-key'."
822 (define-key keymap (org-key key) def))
823
824 (defcustom org-ellipsis nil
825 "The ellipsis to use in the Org-mode outline.
826 When nil, just use the standard three dots.
827 When a string, use that string instead.
828 When a face, use the standard 3 dots, but with the specified face.
829 The change affects only Org-mode (which will then use its own display table).
830 Changing this requires executing `M-x org-mode RET' in a buffer to become
831 effective."
832 :group 'org-startup
833 :type '(choice (const :tag "Default" nil)
834 (face :tag "Face" :value org-warning)
835 (string :tag "String" :value "...#")))
836
837 (defvar org-display-table nil
838 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
839
840 (defgroup org-keywords nil
841 "Keywords in Org-mode."
842 :tag "Org Keywords"
843 :group 'org)
844
845 (defcustom org-deadline-string "DEADLINE:"
846 "String to mark deadline entries.
847 A deadline is this string, followed by a time stamp. Should be a word,
848 terminated by a colon. You can insert a schedule keyword and
849 a timestamp with \\[org-deadline].
850 Changes become only effective after restarting Emacs."
851 :group 'org-keywords
852 :type 'string)
853
854 (defcustom org-scheduled-string "SCHEDULED:"
855 "String to mark scheduled TODO entries.
856 A schedule is this string, followed by a time stamp. Should be a word,
857 terminated by a colon. You can insert a schedule keyword and
858 a timestamp with \\[org-schedule].
859 Changes become only effective after restarting Emacs."
860 :group 'org-keywords
861 :type 'string)
862
863 (defcustom org-closed-string "CLOSED:"
864 "String used as the prefix for timestamps logging closing a TODO entry."
865 :group 'org-keywords
866 :type 'string)
867
868 (defcustom org-clock-string "CLOCK:"
869 "String used as prefix for timestamps clocking work hours on an item."
870 :group 'org-keywords
871 :type 'string)
872
873 (defcustom org-closed-keep-when-no-todo nil
874 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
875 :group 'org-todo
876 :group 'org-keywords
877 :version "24.4"
878 :package-version '(Org . "8.0")
879 :type 'boolean)
880
881 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
882 org-scheduled-string "\\|"
883 org-deadline-string "\\|"
884 org-closed-string "\\|"
885 org-clock-string "\\)")
886 "Matches a line with planning or clock info.")
887
888 (defcustom org-comment-string "COMMENT"
889 "Entries starting with this keyword will never be exported.
890 An entry can be toggled between COMMENT and normal with
891 \\[org-toggle-comment].
892 Changes become only effective after restarting Emacs."
893 :group 'org-keywords
894 :type 'string)
895
896 (defcustom org-quote-string "QUOTE"
897 "Entries starting with this keyword will be exported in fixed-width font.
898 Quoting applies only to the text in the entry following the headline, and does
899 not extend beyond the next headline, even if that is lower level.
900 An entry can be toggled between QUOTE and normal with
901 \\[org-toggle-fixed-width-section]."
902 :group 'org-keywords
903 :type 'string)
904
905 (defconst org-repeat-re
906 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
907 "Regular expression for specifying repeated events.
908 After a match, group 1 contains the repeat expression.")
909
910 (defgroup org-structure nil
911 "Options concerning the general structure of Org-mode files."
912 :tag "Org Structure"
913 :group 'org)
914
915 (defgroup org-reveal-location nil
916 "Options about how to make context of a location visible."
917 :tag "Org Reveal Location"
918 :group 'org-structure)
919
920 (defconst org-context-choice
921 '(choice
922 (const :tag "Always" t)
923 (const :tag "Never" nil)
924 (repeat :greedy t :tag "Individual contexts"
925 (cons
926 (choice :tag "Context"
927 (const agenda)
928 (const org-goto)
929 (const occur-tree)
930 (const tags-tree)
931 (const link-search)
932 (const mark-goto)
933 (const bookmark-jump)
934 (const isearch)
935 (const default))
936 (boolean))))
937 "Contexts for the reveal options.")
938
939 (defcustom org-show-hierarchy-above '((default . t))
940 "Non-nil means show full hierarchy when revealing a location.
941 Org-mode often shows locations in an org-mode file which might have
942 been invisible before. When this is set, the hierarchy of headings
943 above the exposed location is shown.
944 Turning this off for example for sparse trees makes them very compact.
945 Instead of t, this can also be an alist specifying this option for different
946 contexts. Valid contexts are
947 agenda when exposing an entry from the agenda
948 org-goto when using the command `org-goto' on key C-c C-j
949 occur-tree when using the command `org-occur' on key C-c /
950 tags-tree when constructing a sparse tree based on tags matches
951 link-search when exposing search matches associated with a link
952 mark-goto when exposing the jump goal of a mark
953 bookmark-jump when exposing a bookmark location
954 isearch when exiting from an incremental search
955 default default for all contexts not set explicitly"
956 :group 'org-reveal-location
957 :type org-context-choice)
958
959 (defcustom org-show-following-heading '((default . nil))
960 "Non-nil means show following heading when revealing a location.
961 Org-mode often shows locations in an org-mode file which might have
962 been invisible before. When this is set, the heading following the
963 match is shown.
964 Turning this off for example for sparse trees makes them very compact,
965 but makes it harder to edit the location of the match. In such a case,
966 use the command \\[org-reveal] to show more context.
967 Instead of t, this can also be an alist specifying this option for different
968 contexts. See `org-show-hierarchy-above' for valid contexts."
969 :group 'org-reveal-location
970 :type org-context-choice)
971
972 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
973 "Non-nil means show all sibling heading when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the sibling of the current entry
976 heading are all made visible. If `org-show-hierarchy-above' is t,
977 the same happens on each level of the hierarchy above the current entry.
978
979 By default this is on for the isearch context, off for all other contexts.
980 Turning this off for example for sparse trees makes them very compact,
981 but makes it harder to edit the location of the match. In such a case,
982 use the command \\[org-reveal] to show more context.
983 Instead of t, this can also be an alist specifying this option for different
984 contexts. See `org-show-hierarchy-above' for valid contexts."
985 :group 'org-reveal-location
986 :type org-context-choice
987 :version "24.4"
988 :package-version '(Org . "8.0"))
989
990 (defcustom org-show-entry-below '((default . nil))
991 "Non-nil means show the entry below a headline when revealing a location.
992 Org-mode often shows locations in an org-mode file which might have
993 been invisible before. When this is set, the text below the headline that is
994 exposed is also shown.
995
996 By default this is off for all contexts.
997 Instead of t, this can also be an alist specifying this option for different
998 contexts. See `org-show-hierarchy-above' for valid contexts."
999 :group 'org-reveal-location
1000 :type org-context-choice)
1001
1002 (defcustom org-indirect-buffer-display 'other-window
1003 "How should indirect tree buffers be displayed?
1004 This applies to indirect buffers created with the commands
1005 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1006 Valid values are:
1007 current-window Display in the current window
1008 other-window Just display in another window.
1009 dedicated-frame Create one new frame, and re-use it each time.
1010 new-frame Make a new frame each time. Note that in this case
1011 previously-made indirect buffers are kept, and you need to
1012 kill these buffers yourself."
1013 :group 'org-structure
1014 :group 'org-agenda-windows
1015 :type '(choice
1016 (const :tag "In current window" current-window)
1017 (const :tag "In current frame, other window" other-window)
1018 (const :tag "Each time a new frame" new-frame)
1019 (const :tag "One dedicated frame" dedicated-frame)))
1020
1021 (defcustom org-use-speed-commands nil
1022 "Non-nil means activate single letter commands at beginning of a headline.
1023 This may also be a function to test for appropriate locations where speed
1024 commands should be active."
1025 :group 'org-structure
1026 :type '(choice
1027 (const :tag "Never" nil)
1028 (const :tag "At beginning of headline stars" t)
1029 (function)))
1030
1031 (defcustom org-speed-commands-user nil
1032 "Alist of additional speed commands.
1033 This list will be checked before `org-speed-commands-default'
1034 when the variable `org-use-speed-commands' is non-nil
1035 and when the cursor is at the beginning of a headline.
1036 The car if each entry is a string with a single letter, which must
1037 be assigned to `self-insert-command' in the global map.
1038 The cdr is either a command to be called interactively, a function
1039 to be called, or a form to be evaluated.
1040 An entry that is just a list with a single string will be interpreted
1041 as a descriptive headline that will be added when listing the speed
1042 commands in the Help buffer using the `?' speed command."
1043 :group 'org-structure
1044 :type '(repeat :value ("k" . ignore)
1045 (choice :value ("k" . ignore)
1046 (list :tag "Descriptive Headline" (string :tag "Headline"))
1047 (cons :tag "Letter and Command"
1048 (string :tag "Command letter")
1049 (choice
1050 (function)
1051 (sexp))))))
1052
1053 (defcustom org-bookmark-names-plist
1054 '(:last-capture "org-capture-last-stored"
1055 :last-refile "org-refile-last-stored"
1056 :last-capture-marker "org-capture-last-stored-marker")
1057 "Names for bookmarks automatically set by some Org commands.
1058 This can provide strings as names for a number of bookmarks Org sets
1059 automatically. The following keys are currently implemented:
1060 :last-capture
1061 :last-capture-marker
1062 :last-refile
1063 When a key does not show up in the property list, the corresponding bookmark
1064 is not set."
1065 :group 'org-structure
1066 :type 'plist)
1067
1068 (defgroup org-cycle nil
1069 "Options concerning visibility cycling in Org-mode."
1070 :tag "Org Cycle"
1071 :group 'org-structure)
1072
1073 (defcustom org-cycle-skip-children-state-if-no-children t
1074 "Non-nil means skip CHILDREN state in entries that don't have any."
1075 :group 'org-cycle
1076 :type 'boolean)
1077
1078 (defcustom org-cycle-max-level nil
1079 "Maximum level which should still be subject to visibility cycling.
1080 Levels higher than this will, for cycling, be treated as text, not a headline.
1081 When `org-odd-levels-only' is set, a value of N in this variable actually
1082 means 2N-1 stars as the limiting headline.
1083 When nil, cycle all levels.
1084 Note that the limiting level of cycling is also influenced by
1085 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1086 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1087 than its value."
1088 :group 'org-cycle
1089 :type '(choice
1090 (const :tag "No limit" nil)
1091 (integer :tag "Maximum level")))
1092
1093 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1094 "Names of drawers. Drawers are not opened by cycling on the headline above.
1095 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1096 this:
1097 :DRAWERNAME:
1098 .....
1099 :END:
1100 The drawer \"PROPERTIES\" is special for capturing properties through
1101 the property API.
1102
1103 Drawers can be defined on the per-file basis with a line like:
1104
1105 #+DRAWERS: HIDDEN STATE PROPERTIES"
1106 :group 'org-structure
1107 :group 'org-cycle
1108 :type '(repeat (string :tag "Drawer Name")))
1109
1110 (defcustom org-hide-block-startup nil
1111 "Non-nil means entering Org-mode will fold all blocks.
1112 This can also be set in on a per-file basis with
1113
1114 #+STARTUP: hideblocks
1115 #+STARTUP: showblocks"
1116 :group 'org-startup
1117 :group 'org-cycle
1118 :type 'boolean)
1119
1120 (defcustom org-cycle-global-at-bob nil
1121 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1122 This makes it possible to do global cycling without having to use S-TAB or
1123 \\[universal-argument] TAB. For this special case to work, the first line
1124 of the buffer must not be a headline -- it may be empty or some other text.
1125 When used in this way, `org-cycle-hook' is disabled temporarily to make
1126 sure the cursor stays at the beginning of the buffer. When this option is
1127 nil, don't do anything special at the beginning of the buffer."
1128 :group 'org-cycle
1129 :type 'boolean)
1130
1131 (defcustom org-cycle-level-after-item/entry-creation t
1132 "Non-nil means cycle entry level or item indentation in new empty entries.
1133
1134 When the cursor is at the end of an empty headline, i.e., with only stars
1135 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1136 and then all possible ancestor states, before returning to the original state.
1137 This makes data entry extremely fast: M-RET to create a new headline,
1138 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1139
1140 When the cursor is at the end of an empty plain list item, one TAB will
1141 make it a subitem, two or more tabs will back up to make this an item
1142 higher up in the item hierarchy."
1143 :group 'org-cycle
1144 :type 'boolean)
1145
1146 (defcustom org-cycle-emulate-tab t
1147 "Where should `org-cycle' emulate TAB.
1148 nil Never
1149 white Only in completely white lines
1150 whitestart Only at the beginning of lines, before the first non-white char
1151 t Everywhere except in headlines
1152 exc-hl-bol Everywhere except at the start of a headline
1153 If TAB is used in a place where it does not emulate TAB, the current subtree
1154 visibility is cycled."
1155 :group 'org-cycle
1156 :type '(choice (const :tag "Never" nil)
1157 (const :tag "Only in completely white lines" white)
1158 (const :tag "Before first char in a line" whitestart)
1159 (const :tag "Everywhere except in headlines" t)
1160 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1161
1162 (defcustom org-cycle-separator-lines 2
1163 "Number of empty lines needed to keep an empty line between collapsed trees.
1164 If you leave an empty line between the end of a subtree and the following
1165 headline, this empty line is hidden when the subtree is folded.
1166 Org-mode will leave (exactly) one empty line visible if the number of
1167 empty lines is equal or larger to the number given in this variable.
1168 So the default 2 means at least 2 empty lines after the end of a subtree
1169 are needed to produce free space between a collapsed subtree and the
1170 following headline.
1171
1172 If the number is negative, and the number of empty lines is at least -N,
1173 all empty lines are shown.
1174
1175 Special case: when 0, never leave empty lines in collapsed view."
1176 :group 'org-cycle
1177 :type 'integer)
1178 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1179
1180 (defcustom org-pre-cycle-hook nil
1181 "Hook that is run before visibility cycling is happening.
1182 The function(s) in this hook must accept a single argument which indicates
1183 the new state that will be set right after running this hook. The
1184 argument is a symbol. Before a global state change, it can have the values
1185 `overview', `content', or `all'. Before a local state change, it can have
1186 the values `folded', `children', or `subtree'."
1187 :group 'org-cycle
1188 :type 'hook)
1189
1190 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1191 org-cycle-hide-drawers
1192 org-cycle-hide-inline-tasks
1193 org-cycle-show-empty-lines
1194 org-optimize-window-after-visibility-change)
1195 "Hook that is run after `org-cycle' has changed the buffer visibility.
1196 The function(s) in this hook must accept a single argument which indicates
1197 the new state that was set by the most recent `org-cycle' command. The
1198 argument is a symbol. After a global state change, it can have the values
1199 `overview', `contents', or `all'. After a local state change, it can have
1200 the values `folded', `children', or `subtree'."
1201 :group 'org-cycle
1202 :type 'hook)
1203
1204 (defgroup org-edit-structure nil
1205 "Options concerning structure editing in Org-mode."
1206 :tag "Org Edit Structure"
1207 :group 'org-structure)
1208
1209 (defcustom org-odd-levels-only nil
1210 "Non-nil means skip even levels and only use odd levels for the outline.
1211 This has the effect that two stars are being added/taken away in
1212 promotion/demotion commands. It also influences how levels are
1213 handled by the exporters.
1214 Changing it requires restart of `font-lock-mode' to become effective
1215 for fontification also in regions already fontified.
1216 You may also set this on a per-file basis by adding one of the following
1217 lines to the buffer:
1218
1219 #+STARTUP: odd
1220 #+STARTUP: oddeven"
1221 :group 'org-edit-structure
1222 :group 'org-appearance
1223 :type 'boolean)
1224
1225 (defcustom org-adapt-indentation t
1226 "Non-nil means adapt indentation to outline node level.
1227
1228 When this variable is set, Org assumes that you write outlines by
1229 indenting text in each node to align with the headline (after the stars).
1230 The following issues are influenced by this variable:
1231
1232 - When this is set and the *entire* text in an entry is indented, the
1233 indentation is increased by one space in a demotion command, and
1234 decreased by one in a promotion command. If any line in the entry
1235 body starts with text at column 0, indentation is not changed at all.
1236
1237 - Property drawers and planning information is inserted indented when
1238 this variable s set. When nil, they will not be indented.
1239
1240 - TAB indents a line relative to context. The lines below a headline
1241 will be indented when this variable is set.
1242
1243 Note that this is all about true indentation, by adding and removing
1244 space characters. See also `org-indent.el' which does level-dependent
1245 indentation in a virtual way, i.e. at display time in Emacs."
1246 :group 'org-edit-structure
1247 :type 'boolean)
1248
1249 (defcustom org-special-ctrl-a/e nil
1250 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1251
1252 When t, `C-a' will bring back the cursor to the beginning of the
1253 headline text, i.e. after the stars and after a possible TODO
1254 keyword. In an item, this will be the position after bullet and
1255 check-box, if any. When the cursor is already at that position,
1256 another `C-a' will bring it to the beginning of the line.
1257
1258 `C-e' will jump to the end of the headline, ignoring the presence
1259 of tags in the headline. A second `C-e' will then jump to the
1260 true end of the line, after any tags. This also means that, when
1261 this variable is non-nil, `C-e' also will never jump beyond the
1262 end of the heading of a folded section, i.e. not after the
1263 ellipses.
1264
1265 When set to the symbol `reversed', the first `C-a' or `C-e' works
1266 normally, going to the true line boundary first. Only a directly
1267 following, identical keypress will bring the cursor to the
1268 special positions.
1269
1270 This may also be a cons cell where the behavior for `C-a' and
1271 `C-e' is set separately."
1272 :group 'org-edit-structure
1273 :type '(choice
1274 (const :tag "off" nil)
1275 (const :tag "on: after stars/bullet and before tags first" t)
1276 (const :tag "reversed: true line boundary first" reversed)
1277 (cons :tag "Set C-a and C-e separately"
1278 (choice :tag "Special C-a"
1279 (const :tag "off" nil)
1280 (const :tag "on: after stars/bullet first" t)
1281 (const :tag "reversed: before stars/bullet first" reversed))
1282 (choice :tag "Special C-e"
1283 (const :tag "off" nil)
1284 (const :tag "on: before tags first" t)
1285 (const :tag "reversed: after tags first" reversed)))))
1286 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1287
1288 (defcustom org-special-ctrl-k nil
1289 "Non-nil means `C-k' will behave specially in headlines.
1290 When nil, `C-k' will call the default `kill-line' command.
1291 When t, the following will happen while the cursor is in the headline:
1292
1293 - When the cursor is at the beginning of a headline, kill the entire
1294 line and possible the folded subtree below the line.
1295 - When in the middle of the headline text, kill the headline up to the tags.
1296 - When after the headline text, kill the tags."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1299
1300 (defcustom org-ctrl-k-protect-subtree nil
1301 "Non-nil means, do not delete a hidden subtree with C-k.
1302 When set to the symbol `error', simply throw an error when C-k is
1303 used to kill (part-of) a headline that has hidden text behind it.
1304 Any other non-nil value will result in a query to the user, if it is
1305 OK to kill that hidden subtree. When nil, kill without remorse."
1306 :group 'org-edit-structure
1307 :version "24.1"
1308 :type '(choice
1309 (const :tag "Do not protect hidden subtrees" nil)
1310 (const :tag "Protect hidden subtrees with a security query" t)
1311 (const :tag "Never kill a hidden subtree with C-k" error)))
1312
1313 (defcustom org-special-ctrl-o t
1314 "Non-nil means, make `C-o' insert a row in tables."
1315 :group 'org-edit-structure
1316 :type 'boolean)
1317
1318 (defcustom org-catch-invisible-edits nil
1319 "Check if in invisible region before inserting or deleting a character.
1320 Valid values are:
1321
1322 nil Do not check, so just do invisible edits.
1323 error Throw an error and do nothing.
1324 show Make point visible, and do the requested edit.
1325 show-and-error Make point visible, then throw an error and abort the edit.
1326 smart Make point visible, and do insertion/deletion if it is
1327 adjacent to visible text and the change feels predictable.
1328 Never delete a previously invisible character or add in the
1329 middle or right after an invisible region. Basically, this
1330 allows insertion and backward-delete right before ellipses.
1331 FIXME: maybe in this case we should not even show?"
1332 :group 'org-edit-structure
1333 :version "24.1"
1334 :type '(choice
1335 (const :tag "Do not check" nil)
1336 (const :tag "Throw error when trying to edit" error)
1337 (const :tag "Unhide, but do not do the edit" show-and-error)
1338 (const :tag "Show invisible part and do the edit" show)
1339 (const :tag "Be smart and do the right thing" smart)))
1340
1341 (defcustom org-yank-folded-subtrees t
1342 "Non-nil means when yanking subtrees, fold them.
1343 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1344 it starts with a heading and all other headings in it are either children
1345 or siblings, then fold all the subtrees. However, do this only if no
1346 text after the yank would be swallowed into a folded tree by this action."
1347 :group 'org-edit-structure
1348 :type 'boolean)
1349
1350 (defcustom org-yank-adjusted-subtrees nil
1351 "Non-nil means when yanking subtrees, adjust the level.
1352 With this setting, `org-paste-subtree' is used to insert the subtree, see
1353 this function for details."
1354 :group 'org-edit-structure
1355 :type 'boolean)
1356
1357 (defcustom org-M-RET-may-split-line '((default . t))
1358 "Non-nil means M-RET will split the line at the cursor position.
1359 When nil, it will go to the end of the line before making a
1360 new line.
1361 You may also set this option in a different way for different
1362 contexts. Valid contexts are:
1363
1364 headline when creating a new headline
1365 item when creating a new item
1366 table in a table field
1367 default the value to be used for all contexts not explicitly
1368 customized"
1369 :group 'org-structure
1370 :group 'org-table
1371 :type '(choice
1372 (const :tag "Always" t)
1373 (const :tag "Never" nil)
1374 (repeat :greedy t :tag "Individual contexts"
1375 (cons
1376 (choice :tag "Context"
1377 (const headline)
1378 (const item)
1379 (const table)
1380 (const default))
1381 (boolean)))))
1382
1383
1384 (defcustom org-insert-heading-respect-content nil
1385 "Non-nil means insert new headings after the current subtree.
1386 When nil, the new heading is created directly after the current line.
1387 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1388 this variable on for the duration of the command."
1389 :group 'org-structure
1390 :type 'boolean)
1391
1392 (defcustom org-blank-before-new-entry '((heading . auto)
1393 (plain-list-item . auto))
1394 "Should `org-insert-heading' leave a blank line before new heading/item?
1395 The value is an alist, with `heading' and `plain-list-item' as CAR,
1396 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1397 which case Org will look at the surrounding headings/items and try to
1398 make an intelligent decision whether to insert a blank line or not.
1399
1400 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1401 the setting here is ignored and no empty line is inserted to avoid breaking
1402 the list structure."
1403 :group 'org-edit-structure
1404 :type '(list
1405 (cons (const heading)
1406 (choice (const :tag "Never" nil)
1407 (const :tag "Always" t)
1408 (const :tag "Auto" auto)))
1409 (cons (const plain-list-item)
1410 (choice (const :tag "Never" nil)
1411 (const :tag "Always" t)
1412 (const :tag "Auto" auto)))))
1413
1414 (defcustom org-insert-heading-hook nil
1415 "Hook being run after inserting a new heading."
1416 :group 'org-edit-structure
1417 :type 'hook)
1418
1419 (defcustom org-enable-fixed-width-editor t
1420 "Non-nil means lines starting with \":\" are treated as fixed-width.
1421 This currently only means they are never auto-wrapped.
1422 When nil, such lines will be treated like ordinary lines.
1423 See also the QUOTE keyword."
1424 :group 'org-edit-structure
1425 :type 'boolean)
1426
1427 (defcustom org-goto-auto-isearch t
1428 "Non-nil means typing characters in `org-goto' starts incremental search.
1429 When nil, you can use these keybindings to navigate the buffer:
1430
1431 q Quit the org-goto interface
1432 n Go to the next visible heading
1433 p Go to the previous visible heading
1434 f Go one heading forward on same level
1435 b Go one heading backward on same level
1436 u Go one heading up"
1437 :group 'org-edit-structure
1438 :type 'boolean)
1439
1440 (defgroup org-sparse-trees nil
1441 "Options concerning sparse trees in Org-mode."
1442 :tag "Org Sparse Trees"
1443 :group 'org-structure)
1444
1445 (defcustom org-highlight-sparse-tree-matches t
1446 "Non-nil means highlight all matches that define a sparse tree.
1447 The highlights will automatically disappear the next time the buffer is
1448 changed by an edit command."
1449 :group 'org-sparse-trees
1450 :type 'boolean)
1451
1452 (defcustom org-remove-highlights-with-change t
1453 "Non-nil means any change to the buffer will remove temporary highlights.
1454 Such highlights are created by `org-occur' and `org-clock-display'.
1455 When nil, `C-c C-c needs to be used to get rid of the highlights.
1456 The highlights created by `org-preview-latex-fragment' always need
1457 `C-c C-c' to be removed."
1458 :group 'org-sparse-trees
1459 :group 'org-time
1460 :type 'boolean)
1461
1462
1463 (defcustom org-occur-hook '(org-first-headline-recenter)
1464 "Hook that is run after `org-occur' has constructed a sparse tree.
1465 This can be used to recenter the window to show as much of the structure
1466 as possible."
1467 :group 'org-sparse-trees
1468 :type 'hook)
1469
1470 (defgroup org-imenu-and-speedbar nil
1471 "Options concerning imenu and speedbar in Org-mode."
1472 :tag "Org Imenu and Speedbar"
1473 :group 'org-structure)
1474
1475 (defcustom org-imenu-depth 2
1476 "The maximum level for Imenu access to Org-mode headlines.
1477 This also applied for speedbar access."
1478 :group 'org-imenu-and-speedbar
1479 :type 'integer)
1480
1481 (defgroup org-table nil
1482 "Options concerning tables in Org-mode."
1483 :tag "Org Table"
1484 :group 'org)
1485
1486 (defcustom org-enable-table-editor 'optimized
1487 "Non-nil means lines starting with \"|\" are handled by the table editor.
1488 When nil, such lines will be treated like ordinary lines.
1489
1490 When equal to the symbol `optimized', the table editor will be optimized to
1491 do the following:
1492 - Automatic overwrite mode in front of whitespace in table fields.
1493 This makes the structure of the table stay in tact as long as the edited
1494 field does not exceed the column width.
1495 - Minimize the number of realigns. Normally, the table is aligned each time
1496 TAB or RET are pressed to move to another field. With optimization this
1497 happens only if changes to a field might have changed the column width.
1498 Optimization requires replacing the functions `self-insert-command',
1499 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1500 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1501 very good at guessing when a re-align will be necessary, but you can always
1502 force one with \\[org-ctrl-c-ctrl-c].
1503
1504 If you would like to use the optimized version in Org-mode, but the
1505 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1506
1507 This variable can be used to turn on and off the table editor during a session,
1508 but in order to toggle optimization, a restart is required.
1509
1510 See also the variable `org-table-auto-blank-field'."
1511 :group 'org-table
1512 :type '(choice
1513 (const :tag "off" nil)
1514 (const :tag "on" t)
1515 (const :tag "on, optimized" optimized)))
1516
1517 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1518 (version<= emacs-version "24.1"))
1519 "Non-nil means cluster self-insert commands for undo when possible.
1520 If this is set, then, like in the Emacs command loop, 20 consecutive
1521 characters will be undone together.
1522 This is configurable, because there is some impact on typing performance."
1523 :group 'org-table
1524 :type 'boolean)
1525
1526 (defcustom org-table-tab-recognizes-table.el t
1527 "Non-nil means TAB will automatically notice a table.el table.
1528 When it sees such a table, it moves point into it and - if necessary -
1529 calls `table-recognize-table'."
1530 :group 'org-table-editing
1531 :type 'boolean)
1532
1533 (defgroup org-link nil
1534 "Options concerning links in Org-mode."
1535 :tag "Org Link"
1536 :group 'org)
1537
1538 (defvar org-link-abbrev-alist-local nil
1539 "Buffer-local version of `org-link-abbrev-alist', which see.
1540 The value of this is taken from the #+LINK lines.")
1541 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1542
1543 (defcustom org-link-abbrev-alist nil
1544 "Alist of link abbreviations.
1545 The car of each element is a string, to be replaced at the start of a link.
1546 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1547 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1548
1549 [[linkkey:tag][description]]
1550
1551 The 'linkkey' must be a word word, starting with a letter, followed
1552 by letters, numbers, '-' or '_'.
1553
1554 If REPLACE is a string, the tag will simply be appended to create the link.
1555 If the string contains \"%s\", the tag will be inserted there. If the string
1556 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1557 at that point (see the function `url-hexify-string'). If the string contains
1558 the specifier \"%(my-function)\", then the custom function `my-function' will
1559 be invoked: this function takes the tag as its only argument and must return
1560 a string.
1561
1562 REPLACE may also be a function that will be called with the tag as the
1563 only argument to create the link, which should be returned as a string.
1564
1565 See the manual for examples."
1566 :group 'org-link
1567 :type '(repeat
1568 (cons
1569 (string :tag "Protocol")
1570 (choice
1571 (string :tag "Format")
1572 (function)))))
1573
1574 (defcustom org-descriptive-links t
1575 "Non-nil means Org will display descriptive links.
1576 E.g. [[http://orgmode.org][Org website]] will be displayed as
1577 \"Org Website\", hiding the link itself and just displaying its
1578 description. When set to `nil', Org will display the full links
1579 literally.
1580
1581 You can interactively set the value of this variable by calling
1582 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1583 :group 'org-link
1584 :type 'boolean)
1585
1586 (defcustom org-link-file-path-type 'adaptive
1587 "How the path name in file links should be stored.
1588 Valid values are:
1589
1590 relative Relative to the current directory, i.e. the directory of the file
1591 into which the link is being inserted.
1592 absolute Absolute path, if possible with ~ for home directory.
1593 noabbrev Absolute path, no abbreviation of home directory.
1594 adaptive Use relative path for files in the current directory and sub-
1595 directories of it. For other files, use an absolute path."
1596 :group 'org-link
1597 :type '(choice
1598 (const relative)
1599 (const absolute)
1600 (const noabbrev)
1601 (const adaptive)))
1602
1603 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1604 "Types of links that should be activated in Org-mode files.
1605 This is a list of symbols, each leading to the activation of a certain link
1606 type. In principle, it does not hurt to turn on most link types - there may
1607 be a small gain when turning off unused link types. The types are:
1608
1609 bracket The recommended [[link][description]] or [[link]] links with hiding.
1610 angle Links in angular brackets that may contain whitespace like
1611 <bbdb:Carsten Dominik>.
1612 plain Plain links in normal text, no whitespace, like http://google.com.
1613 radio Text that is matched by a radio target, see manual for details.
1614 tag Tag settings in a headline (link to tag search).
1615 date Time stamps (link to calendar).
1616 footnote Footnote labels.
1617
1618 Changing this variable requires a restart of Emacs to become effective."
1619 :group 'org-link
1620 :type '(set :greedy t
1621 (const :tag "Double bracket links" bracket)
1622 (const :tag "Angular bracket links" angle)
1623 (const :tag "Plain text links" plain)
1624 (const :tag "Radio target matches" radio)
1625 (const :tag "Tags" tag)
1626 (const :tag "Timestamps" date)
1627 (const :tag "Footnotes" footnote)))
1628
1629 (defcustom org-make-link-description-function nil
1630 "Function to use for generating link descriptions from links.
1631 When nil, the link location will be used. This function must take
1632 two parameters: the first one is the link, the second one is the
1633 description generated by `org-insert-link'. The function should
1634 return the description to use."
1635 :group 'org-link
1636 :type '(choice (const nil) (function)))
1637
1638 (defgroup org-link-store nil
1639 "Options concerning storing links in Org-mode."
1640 :tag "Org Store Link"
1641 :group 'org-link)
1642
1643 (defcustom org-url-hexify-p t
1644 "When non-nil, hexify URL when creating a link."
1645 :type 'boolean
1646 :version "24.3"
1647 :group 'org-link-store)
1648
1649 (defcustom org-email-link-description-format "Email %c: %.30s"
1650 "Format of the description part of a link to an email or usenet message.
1651 The following %-escapes will be replaced by corresponding information:
1652
1653 %F full \"From\" field
1654 %f name, taken from \"From\" field, address if no name
1655 %T full \"To\" field
1656 %t first name in \"To\" field, address if no name
1657 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1658 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1659 %s subject
1660 %d date
1661 %m message-id.
1662
1663 You may use normal field width specification between the % and the letter.
1664 This is for example useful to limit the length of the subject.
1665
1666 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1667 :group 'org-link-store
1668 :type 'string)
1669
1670 (defcustom org-from-is-user-regexp
1671 (let (r1 r2)
1672 (when (and user-mail-address (not (string= user-mail-address "")))
1673 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1674 (when (and user-full-name (not (string= user-full-name "")))
1675 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1676 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1677 "Regexp matched against the \"From:\" header of an email or usenet message.
1678 It should match if the message is from the user him/herself."
1679 :group 'org-link-store
1680 :type 'regexp)
1681
1682 (defcustom org-context-in-file-links t
1683 "Non-nil means file links from `org-store-link' contain context.
1684 A search string will be added to the file name with :: as separator and
1685 used to find the context when the link is activated by the command
1686 `org-open-at-point'. When this option is t, the entire active region
1687 will be placed in the search string of the file link. If set to a
1688 positive integer, only the first n lines of context will be stored.
1689
1690 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1691 negates this setting for the duration of the command."
1692 :group 'org-link-store
1693 :type '(choice boolean integer))
1694
1695 (defcustom org-keep-stored-link-after-insertion nil
1696 "Non-nil means keep link in list for entire session.
1697
1698 The command `org-store-link' adds a link pointing to the current
1699 location to an internal list. These links accumulate during a session.
1700 The command `org-insert-link' can be used to insert links into any
1701 Org-mode file (offering completion for all stored links). When this
1702 option is nil, every link which has been inserted once using \\[org-insert-link]
1703 will be removed from the list, to make completing the unused links
1704 more efficient."
1705 :group 'org-link-store
1706 :type 'boolean)
1707
1708 (defgroup org-link-follow nil
1709 "Options concerning following links in Org-mode."
1710 :tag "Org Follow Link"
1711 :group 'org-link)
1712
1713 (defcustom org-link-translation-function nil
1714 "Function to translate links with different syntax to Org syntax.
1715 This can be used to translate links created for example by the Planner
1716 or emacs-wiki packages to Org syntax.
1717 The function must accept two parameters, a TYPE containing the link
1718 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1719 which is everything after the link protocol. It should return a cons
1720 with possibly modified values of type and path.
1721 Org contains a function for this, so if you set this variable to
1722 `org-translate-link-from-planner', you should be able follow many
1723 links created by planner."
1724 :group 'org-link-follow
1725 :type '(choice (const nil) (function)))
1726
1727 (defcustom org-follow-link-hook nil
1728 "Hook that is run after a link has been followed."
1729 :group 'org-link-follow
1730 :type 'hook)
1731
1732 (defcustom org-tab-follows-link nil
1733 "Non-nil means on links TAB will follow the link.
1734 Needs to be set before org.el is loaded.
1735 This really should not be used, it does not make sense, and the
1736 implementation is bad."
1737 :group 'org-link-follow
1738 :type 'boolean)
1739
1740 (defcustom org-return-follows-link nil
1741 "Non-nil means on links RET will follow the link.
1742 In tables, the special behavior of RET has precedence."
1743 :group 'org-link-follow
1744 :type 'boolean)
1745
1746 (defcustom org-mouse-1-follows-link
1747 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1748 "Non-nil means mouse-1 on a link will follow the link.
1749 A longer mouse click will still set point. Does not work on XEmacs.
1750 Needs to be set before org.el is loaded."
1751 :group 'org-link-follow
1752 :version "24.4"
1753 :package-version '(Org . "8.3")
1754 :type '(choice
1755 (const :tag "A double click follows the link" double)
1756 (const :tag "Unconditionally follow the link with mouse-1" t)
1757 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1758
1759 (defcustom org-mark-ring-length 4
1760 "Number of different positions to be recorded in the ring.
1761 Changing this requires a restart of Emacs to work correctly."
1762 :group 'org-link-follow
1763 :type 'integer)
1764
1765 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1766 "Non-nil means internal links in Org files must exactly match a headline.
1767 When nil, the link search tries to match a phrase with all words
1768 in the search text."
1769 :group 'org-link-follow
1770 :version "24.1"
1771 :type '(choice
1772 (const :tag "Use fuzzy text search" nil)
1773 (const :tag "Match only exact headline" t)
1774 (const :tag "Match exact headline or query to create it"
1775 query-to-create)))
1776
1777 (defcustom org-link-frame-setup
1778 '((vm . vm-visit-folder-other-frame)
1779 (vm-imap . vm-visit-imap-folder-other-frame)
1780 (gnus . org-gnus-no-new-news)
1781 (file . find-file-other-window)
1782 (wl . wl-other-frame))
1783 "Setup the frame configuration for following links.
1784 When following a link with Emacs, it may often be useful to display
1785 this link in another window or frame. This variable can be used to
1786 set this up for the different types of links.
1787 For VM, use any of
1788 `vm-visit-folder'
1789 `vm-visit-folder-other-window'
1790 `vm-visit-folder-other-frame'
1791 For Gnus, use any of
1792 `gnus'
1793 `gnus-other-frame'
1794 `org-gnus-no-new-news'
1795 For FILE, use any of
1796 `find-file'
1797 `find-file-other-window'
1798 `find-file-other-frame'
1799 For Wanderlust use any of
1800 `wl'
1801 `wl-other-frame'
1802 For the calendar, use the variable `calendar-setup'.
1803 For BBDB, it is currently only possible to display the matches in
1804 another window."
1805 :group 'org-link-follow
1806 :type '(list
1807 (cons (const vm)
1808 (choice
1809 (const vm-visit-folder)
1810 (const vm-visit-folder-other-window)
1811 (const vm-visit-folder-other-frame)))
1812 (cons (const vm-imap)
1813 (choice
1814 (const vm-visit-imap-folder)
1815 (const vm-visit-imap-folder-other-window)
1816 (const vm-visit-imap-folder-other-frame)))
1817 (cons (const gnus)
1818 (choice
1819 (const gnus)
1820 (const gnus-other-frame)
1821 (const org-gnus-no-new-news)))
1822 (cons (const file)
1823 (choice
1824 (const find-file)
1825 (const find-file-other-window)
1826 (const find-file-other-frame)))
1827 (cons (const wl)
1828 (choice
1829 (const wl)
1830 (const wl-other-frame)))))
1831
1832 (defcustom org-display-internal-link-with-indirect-buffer nil
1833 "Non-nil means use indirect buffer to display infile links.
1834 Activating internal links (from one location in a file to another location
1835 in the same file) normally just jumps to the location. When the link is
1836 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1837 is displayed in
1838 another window. When this option is set, the other window actually displays
1839 an indirect buffer clone of the current buffer, to avoid any visibility
1840 changes to the current buffer."
1841 :group 'org-link-follow
1842 :type 'boolean)
1843
1844 (defcustom org-open-non-existing-files nil
1845 "Non-nil means `org-open-file' will open non-existing files.
1846 When nil, an error will be generated.
1847 This variable applies only to external applications because they
1848 might choke on non-existing files. If the link is to a file that
1849 will be opened in Emacs, the variable is ignored."
1850 :group 'org-link-follow
1851 :type 'boolean)
1852
1853 (defcustom org-open-directory-means-index-dot-org nil
1854 "Non-nil means a link to a directory really means to index.org.
1855 When nil, following a directory link will run dired or open a finder/explorer
1856 window on that directory."
1857 :group 'org-link-follow
1858 :type 'boolean)
1859
1860 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1861 "Function and arguments to call for following mailto links.
1862 This is a list with the first element being a Lisp function, and the
1863 remaining elements being arguments to the function. In string arguments,
1864 %a will be replaced by the address, and %s will be replaced by the subject
1865 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1866 :group 'org-link-follow
1867 :type '(choice
1868 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1869 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1870 (const :tag "message-mail" (message-mail "%a" "%s"))
1871 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1872
1873 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1874 "Non-nil means ask for confirmation before executing shell links.
1875 Shell links can be dangerous: just think about a link
1876
1877 [[shell:rm -rf ~/*][Google Search]]
1878
1879 This link would show up in your Org-mode document as \"Google Search\",
1880 but really it would remove your entire home directory.
1881 Therefore we advise against setting this variable to nil.
1882 Just change it to `y-or-n-p' if you want to confirm with a
1883 single keystroke rather than having to type \"yes\"."
1884 :group 'org-link-follow
1885 :type '(choice
1886 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1887 (const :tag "with y-or-n (faster)" y-or-n-p)
1888 (const :tag "no confirmation (dangerous)" nil)))
1889 (put 'org-confirm-shell-link-function
1890 'safe-local-variable
1891 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1892
1893 (defcustom org-confirm-shell-link-not-regexp ""
1894 "A regexp to skip confirmation for shell links."
1895 :group 'org-link-follow
1896 :version "24.1"
1897 :type 'regexp)
1898
1899 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1900 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1901 Elisp links can be dangerous: just think about a link
1902
1903 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1904
1905 This link would show up in your Org-mode document as \"Google Search\",
1906 but really it would remove your entire home directory.
1907 Therefore we advise against setting this variable to nil.
1908 Just change it to `y-or-n-p' if you want to confirm with a
1909 single keystroke rather than having to type \"yes\"."
1910 :group 'org-link-follow
1911 :type '(choice
1912 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1913 (const :tag "with y-or-n (faster)" y-or-n-p)
1914 (const :tag "no confirmation (dangerous)" nil)))
1915 (put 'org-confirm-shell-link-function
1916 'safe-local-variable
1917 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1918
1919 (defcustom org-confirm-elisp-link-not-regexp ""
1920 "A regexp to skip confirmation for Elisp links."
1921 :group 'org-link-follow
1922 :version "24.1"
1923 :type 'regexp)
1924
1925 (defconst org-file-apps-defaults-gnu
1926 '((remote . emacs)
1927 (system . mailcap)
1928 (t . mailcap))
1929 "Default file applications on a UNIX or GNU/Linux system.
1930 See `org-file-apps'.")
1931
1932 (defconst org-file-apps-defaults-macosx
1933 '((remote . emacs)
1934 (t . "open %s")
1935 (system . "open %s")
1936 ("ps.gz" . "gv %s")
1937 ("eps.gz" . "gv %s")
1938 ("dvi" . "xdvi %s")
1939 ("fig" . "xfig %s"))
1940 "Default file applications on a MacOS X system.
1941 The system \"open\" is known as a default, but we use X11 applications
1942 for some files for which the OS does not have a good default.
1943 See `org-file-apps'.")
1944
1945 (defconst org-file-apps-defaults-windowsnt
1946 (list
1947 '(remote . emacs)
1948 (cons t
1949 (list (if (featurep 'xemacs)
1950 'mswindows-shell-execute
1951 'w32-shell-execute)
1952 "open" 'file))
1953 (cons 'system
1954 (list (if (featurep 'xemacs)
1955 'mswindows-shell-execute
1956 'w32-shell-execute)
1957 "open" 'file)))
1958 "Default file applications on a Windows NT system.
1959 The system \"open\" is used for most files.
1960 See `org-file-apps'.")
1961
1962 (defcustom org-file-apps
1963 '((auto-mode . emacs)
1964 ("\\.mm\\'" . default)
1965 ("\\.x?html?\\'" . default)
1966 ("\\.pdf\\'" . default))
1967 "External applications for opening `file:path' items in a document.
1968 Org-mode uses system defaults for different file types, but
1969 you can use this variable to set the application for a given file
1970 extension. The entries in this list are cons cells where the car identifies
1971 files and the cdr the corresponding command. Possible values for the
1972 file identifier are
1973 \"string\" A string as a file identifier can be interpreted in different
1974 ways, depending on its contents:
1975
1976 - Alphanumeric characters only:
1977 Match links with this file extension.
1978 Example: (\"pdf\" . \"evince %s\")
1979 to open PDFs with evince.
1980
1981 - Regular expression: Match links where the
1982 filename matches the regexp. If you want to
1983 use groups here, use shy groups.
1984
1985 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1986 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1987 to open *.html and *.xhtml with firefox.
1988
1989 - Regular expression which contains (non-shy) groups:
1990 Match links where the whole link, including \"::\", and
1991 anything after that, matches the regexp.
1992 In a custom command string, %1, %2, etc. are replaced with
1993 the parts of the link that were matched by the groups.
1994 For backwards compatibility, if a command string is given
1995 that does not use any of the group matches, this case is
1996 handled identically to the second one (i.e. match against
1997 file name only).
1998 In a custom lisp form, you can access the group matches with
1999 (match-string n link).
2000
2001 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2002 to open [[file:document.pdf::5]] with evince at page 5.
2003
2004 `directory' Matches a directory
2005 `remote' Matches a remote file, accessible through tramp or efs.
2006 Remote files most likely should be visited through Emacs
2007 because external applications cannot handle such paths.
2008 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2009 so all files Emacs knows how to handle. Using this with
2010 command `emacs' will open most files in Emacs. Beware that this
2011 will also open html files inside Emacs, unless you add
2012 (\"html\" . default) to the list as well.
2013 t Default for files not matched by any of the other options.
2014 `system' The system command to open files, like `open' on Windows
2015 and Mac OS X, and mailcap under GNU/Linux. This is the command
2016 that will be selected if you call `C-c C-o' with a double
2017 \\[universal-argument] \\[universal-argument] prefix.
2018
2019 Possible values for the command are:
2020 `emacs' The file will be visited by the current Emacs process.
2021 `default' Use the default application for this file type, which is the
2022 association for t in the list, most likely in the system-specific
2023 part.
2024 This can be used to overrule an unwanted setting in the
2025 system-specific variable.
2026 `system' Use the system command for opening files, like \"open\".
2027 This command is specified by the entry whose car is `system'.
2028 Most likely, the system-specific version of this variable
2029 does define this command, but you can overrule/replace it
2030 here.
2031 string A command to be executed by a shell; %s will be replaced
2032 by the path to the file.
2033 sexp A Lisp form which will be evaluated. The file path will
2034 be available in the Lisp variable `file'.
2035 For more examples, see the system specific constants
2036 `org-file-apps-defaults-macosx'
2037 `org-file-apps-defaults-windowsnt'
2038 `org-file-apps-defaults-gnu'."
2039 :group 'org-link-follow
2040 :type '(repeat
2041 (cons (choice :value ""
2042 (string :tag "Extension")
2043 (const :tag "System command to open files" system)
2044 (const :tag "Default for unrecognized files" t)
2045 (const :tag "Remote file" remote)
2046 (const :tag "Links to a directory" directory)
2047 (const :tag "Any files that have Emacs modes"
2048 auto-mode))
2049 (choice :value ""
2050 (const :tag "Visit with Emacs" emacs)
2051 (const :tag "Use default" default)
2052 (const :tag "Use the system command" system)
2053 (string :tag "Command")
2054 (sexp :tag "Lisp form")))))
2055
2056 (defcustom org-doi-server-url "http://dx.doi.org/"
2057 "The URL of the DOI server."
2058 :type 'string
2059 :version "24.3"
2060 :group 'org-link-follow)
2061
2062 (defgroup org-refile nil
2063 "Options concerning refiling entries in Org-mode."
2064 :tag "Org Refile"
2065 :group 'org)
2066
2067 (defcustom org-directory "~/org"
2068 "Directory with org files.
2069 This is just a default location to look for Org files. There is no need
2070 at all to put your files into this directory. It is only used in the
2071 following situations:
2072
2073 1. When a capture template specifies a target file that is not an
2074 absolute path. The path will then be interpreted relative to
2075 `org-directory'
2076 2. When a capture note is filed away in an interactive way (when exiting the
2077 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2078 with `org-directory' as the default path."
2079 :group 'org-refile
2080 :group 'org-capture
2081 :type 'directory)
2082
2083 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2084 "Default target for storing notes.
2085 Used as a fall back file for org-capture.el, for templates that
2086 do not specify a target file."
2087 :group 'org-refile
2088 :group 'org-capture
2089 :type '(choice
2090 (const :tag "Default from remember-data-file" nil)
2091 file))
2092
2093 (defcustom org-goto-interface 'outline
2094 "The default interface to be used for `org-goto'.
2095 Allowed values are:
2096 outline The interface shows an outline of the relevant file
2097 and the correct heading is found by moving through
2098 the outline or by searching with incremental search.
2099 outline-path-completion Headlines in the current buffer are offered via
2100 completion. This is the interface also used by
2101 the refile command."
2102 :group 'org-refile
2103 :type '(choice
2104 (const :tag "Outline" outline)
2105 (const :tag "Outline-path-completion" outline-path-completion)))
2106
2107 (defcustom org-goto-max-level 5
2108 "Maximum target level when running `org-goto' with refile interface."
2109 :group 'org-refile
2110 :type 'integer)
2111
2112 (defcustom org-reverse-note-order nil
2113 "Non-nil means store new notes at the beginning of a file or entry.
2114 When nil, new notes will be filed to the end of a file or entry.
2115 This can also be a list with cons cells of regular expressions that
2116 are matched against file names, and values."
2117 :group 'org-capture
2118 :group 'org-refile
2119 :type '(choice
2120 (const :tag "Reverse always" t)
2121 (const :tag "Reverse never" nil)
2122 (repeat :tag "By file name regexp"
2123 (cons regexp boolean))))
2124
2125 (defcustom org-log-refile nil
2126 "Information to record when a task is refiled.
2127
2128 Possible values are:
2129
2130 nil Don't add anything
2131 time Add a time stamp to the task
2132 note Prompt for a note and add it with template `org-log-note-headings'
2133
2134 This option can also be set with on a per-file-basis with
2135
2136 #+STARTUP: nologrefile
2137 #+STARTUP: logrefile
2138 #+STARTUP: lognoterefile
2139
2140 You can have local logging settings for a subtree by setting the LOGGING
2141 property to one or more of these keywords.
2142
2143 When bulk-refiling from the agenda, the value `note' is forbidden and
2144 will temporarily be changed to `time'."
2145 :group 'org-refile
2146 :group 'org-progress
2147 :version "24.1"
2148 :type '(choice
2149 (const :tag "No logging" nil)
2150 (const :tag "Record timestamp" time)
2151 (const :tag "Record timestamp with note." note)))
2152
2153 (defcustom org-refile-targets nil
2154 "Targets for refiling entries with \\[org-refile].
2155 This is a list of cons cells. Each cell contains:
2156 - a specification of the files to be considered, either a list of files,
2157 or a symbol whose function or variable value will be used to retrieve
2158 a file name or a list of file names. If you use `org-agenda-files' for
2159 that, all agenda files will be scanned for targets. Nil means consider
2160 headings in the current buffer.
2161 - A specification of how to find candidate refile targets. This may be
2162 any of:
2163 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2164 This tag has to be present in all target headlines, inheritance will
2165 not be considered.
2166 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2167 todo keyword.
2168 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2169 headlines that are refiling targets.
2170 - a cons cell (:level . N). Any headline of level N is considered a target.
2171 Note that, when `org-odd-levels-only' is set, level corresponds to
2172 order in hierarchy, not to the number of stars.
2173 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2174 Note that, when `org-odd-levels-only' is set, level corresponds to
2175 order in hierarchy, not to the number of stars.
2176
2177 Each element of this list generates a set of possible targets.
2178 The union of these sets is presented (with completion) to
2179 the user by `org-refile'.
2180
2181 You can set the variable `org-refile-target-verify-function' to a function
2182 to verify each headline found by the simple criteria above.
2183
2184 When this variable is nil, all top-level headlines in the current buffer
2185 are used, equivalent to the value `((nil . (:level . 1))'."
2186 :group 'org-refile
2187 :type '(repeat
2188 (cons
2189 (choice :value org-agenda-files
2190 (const :tag "All agenda files" org-agenda-files)
2191 (const :tag "Current buffer" nil)
2192 (function) (variable) (file))
2193 (choice :tag "Identify target headline by"
2194 (cons :tag "Specific tag" (const :value :tag) (string))
2195 (cons :tag "TODO keyword" (const :value :todo) (string))
2196 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2197 (cons :tag "Level number" (const :value :level) (integer))
2198 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2199
2200 (defcustom org-refile-target-verify-function nil
2201 "Function to verify if the headline at point should be a refile target.
2202 The function will be called without arguments, with point at the
2203 beginning of the headline. It should return t and leave point
2204 where it is if the headline is a valid target for refiling.
2205
2206 If the target should not be selected, the function must return nil.
2207 In addition to this, it may move point to a place from where the search
2208 should be continued. For example, the function may decide that the entire
2209 subtree of the current entry should be excluded and move point to the end
2210 of the subtree."
2211 :group 'org-refile
2212 :type '(choice
2213 (const nil)
2214 (function)))
2215
2216 (defcustom org-refile-use-cache nil
2217 "Non-nil means cache refile targets to speed up the process.
2218 The cache for a particular file will be updated automatically when
2219 the buffer has been killed, or when any of the marker used for flagging
2220 refile targets no longer points at a live buffer.
2221 If you have added new entries to a buffer that might themselves be targets,
2222 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2223 find that easier, `C-u C-u C-u C-c C-w'."
2224 :group 'org-refile
2225 :version "24.1"
2226 :type 'boolean)
2227
2228 (defcustom org-refile-use-outline-path nil
2229 "Non-nil means provide refile targets as paths.
2230 So a level 3 headline will be available as level1/level2/level3.
2231
2232 When the value is `file', also include the file name (without directory)
2233 into the path. In this case, you can also stop the completion after
2234 the file name, to get entries inserted as top level in the file.
2235
2236 When `full-file-path', include the full file path."
2237 :group 'org-refile
2238 :type '(choice
2239 (const :tag "Not" nil)
2240 (const :tag "Yes" t)
2241 (const :tag "Start with file name" file)
2242 (const :tag "Start with full file path" full-file-path)))
2243
2244 (defcustom org-outline-path-complete-in-steps t
2245 "Non-nil means complete the outline path in hierarchical steps.
2246 When Org-mode uses the refile interface to select an outline path
2247 \(see variable `org-refile-use-outline-path'), the completion of
2248 the path can be done is a single go, or if can be done in steps down
2249 the headline hierarchy. Going in steps is probably the best if you
2250 do not use a special completion package like `ido' or `icicles'.
2251 However, when using these packages, going in one step can be very
2252 fast, while still showing the whole path to the entry."
2253 :group 'org-refile
2254 :type 'boolean)
2255
2256 (defcustom org-refile-allow-creating-parent-nodes nil
2257 "Non-nil means allow to create new nodes as refile targets.
2258 New nodes are then created by adding \"/new node name\" to the completion
2259 of an existing node. When the value of this variable is `confirm',
2260 new node creation must be confirmed by the user (recommended).
2261 When nil, the completion must match an existing entry.
2262
2263 Note that, if the new heading is not seen by the criteria
2264 listed in `org-refile-targets', multiple instances of the same
2265 heading would be created by trying again to file under the new
2266 heading."
2267 :group 'org-refile
2268 :type '(choice
2269 (const :tag "Never" nil)
2270 (const :tag "Always" t)
2271 (const :tag "Prompt for confirmation" confirm)))
2272
2273 (defcustom org-refile-active-region-within-subtree nil
2274 "Non-nil means also refile active region within a subtree.
2275
2276 By default `org-refile' doesn't allow refiling regions if they
2277 don't contain a set of subtrees, but it might be convenient to
2278 do so sometimes: in that case, the first line of the region is
2279 converted to a headline before refiling."
2280 :group 'org-refile
2281 :version "24.1"
2282 :type 'boolean)
2283
2284 (defgroup org-todo nil
2285 "Options concerning TODO items in Org-mode."
2286 :tag "Org TODO"
2287 :group 'org)
2288
2289 (defgroup org-progress nil
2290 "Options concerning Progress logging in Org-mode."
2291 :tag "Org Progress"
2292 :group 'org-time)
2293
2294 (defvar org-todo-interpretation-widgets
2295 '((:tag "Sequence (cycling hits every state)" sequence)
2296 (:tag "Type (cycling directly to DONE)" type))
2297 "The available interpretation symbols for customizing `org-todo-keywords'.
2298 Interested libraries should add to this list.")
2299
2300 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2301 "List of TODO entry keyword sequences and their interpretation.
2302 \\<org-mode-map>This is a list of sequences.
2303
2304 Each sequence starts with a symbol, either `sequence' or `type',
2305 indicating if the keywords should be interpreted as a sequence of
2306 action steps, or as different types of TODO items. The first
2307 keywords are states requiring action - these states will select a headline
2308 for inclusion into the global TODO list Org-mode produces. If one of
2309 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2310 signify that no further action is necessary. If \"|\" is not found,
2311 the last keyword is treated as the only DONE state of the sequence.
2312
2313 The command \\[org-todo] cycles an entry through these states, and one
2314 additional state where no keyword is present. For details about this
2315 cycling, see the manual.
2316
2317 TODO keywords and interpretation can also be set on a per-file basis with
2318 the special #+SEQ_TODO and #+TYP_TODO lines.
2319
2320 Each keyword can optionally specify a character for fast state selection
2321 \(in combination with the variable `org-use-fast-todo-selection')
2322 and specifiers for state change logging, using the same syntax that
2323 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2324 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2325 indicates to record a time stamp each time this state is selected.
2326
2327 Each keyword may also specify if a timestamp or a note should be
2328 recorded when entering or leaving the state, by adding additional
2329 characters in the parenthesis after the keyword. This looks like this:
2330 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2331 record only the time of the state change. With X and Y being either
2332 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2333 Y when leaving the state if and only if the *target* state does not
2334 define X. You may omit any of the fast-selection key or X or /Y,
2335 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2336
2337 For backward compatibility, this variable may also be just a list
2338 of keywords. In this case the interpretation (sequence or type) will be
2339 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2340 :group 'org-todo
2341 :group 'org-keywords
2342 :type '(choice
2343 (repeat :tag "Old syntax, just keywords"
2344 (string :tag "Keyword"))
2345 (repeat :tag "New syntax"
2346 (cons
2347 (choice
2348 :tag "Interpretation"
2349 ;;Quick and dirty way to see
2350 ;;`org-todo-interpretations'. This takes the
2351 ;;place of item arguments
2352 :convert-widget
2353 (lambda (widget)
2354 (widget-put widget
2355 :args (mapcar
2356 #'(lambda (x)
2357 (widget-convert
2358 (cons 'const x)))
2359 org-todo-interpretation-widgets))
2360 widget))
2361 (repeat
2362 (string :tag "Keyword"))))))
2363
2364 (defvar org-todo-keywords-1 nil
2365 "All TODO and DONE keywords active in a buffer.")
2366 (make-variable-buffer-local 'org-todo-keywords-1)
2367 (defvar org-todo-keywords-for-agenda nil)
2368 (defvar org-done-keywords-for-agenda nil)
2369 (defvar org-drawers-for-agenda nil)
2370 (defvar org-todo-keyword-alist-for-agenda nil)
2371 (defvar org-tag-alist-for-agenda nil
2372 "Alist of all tags from all agenda files.")
2373 (defvar org-tag-groups-alist-for-agenda nil
2374 "Alist of all groups tags from all current agenda files.")
2375 (defvar org-tag-groups-alist nil)
2376 (make-variable-buffer-local 'org-tag-groups-alist)
2377 (defvar org-agenda-contributing-files nil)
2378 (defvar org-not-done-keywords nil)
2379 (make-variable-buffer-local 'org-not-done-keywords)
2380 (defvar org-done-keywords nil)
2381 (make-variable-buffer-local 'org-done-keywords)
2382 (defvar org-todo-heads nil)
2383 (make-variable-buffer-local 'org-todo-heads)
2384 (defvar org-todo-sets nil)
2385 (make-variable-buffer-local 'org-todo-sets)
2386 (defvar org-todo-log-states nil)
2387 (make-variable-buffer-local 'org-todo-log-states)
2388 (defvar org-todo-kwd-alist nil)
2389 (make-variable-buffer-local 'org-todo-kwd-alist)
2390 (defvar org-todo-key-alist nil)
2391 (make-variable-buffer-local 'org-todo-key-alist)
2392 (defvar org-todo-key-trigger nil)
2393 (make-variable-buffer-local 'org-todo-key-trigger)
2394
2395 (defcustom org-todo-interpretation 'sequence
2396 "Controls how TODO keywords are interpreted.
2397 This variable is in principle obsolete and is only used for
2398 backward compatibility, if the interpretation of todo keywords is
2399 not given already in `org-todo-keywords'. See that variable for
2400 more information."
2401 :group 'org-todo
2402 :group 'org-keywords
2403 :type '(choice (const sequence)
2404 (const type)))
2405
2406 (defcustom org-use-fast-todo-selection t
2407 "Non-nil means use the fast todo selection scheme with C-c C-t.
2408 This variable describes if and under what circumstances the cycling
2409 mechanism for TODO keywords will be replaced by a single-key, direct
2410 selection scheme.
2411
2412 When nil, fast selection is never used.
2413
2414 When the symbol `prefix', it will be used when `org-todo' is called
2415 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2416 `C-u t' in an agenda buffer.
2417
2418 When t, fast selection is used by default. In this case, the prefix
2419 argument forces cycling instead.
2420
2421 In all cases, the special interface is only used if access keys have
2422 actually been assigned by the user, i.e. if keywords in the configuration
2423 are followed by a letter in parenthesis, like TODO(t)."
2424 :group 'org-todo
2425 :type '(choice
2426 (const :tag "Never" nil)
2427 (const :tag "By default" t)
2428 (const :tag "Only with C-u C-c C-t" prefix)))
2429
2430 (defcustom org-provide-todo-statistics t
2431 "Non-nil means update todo statistics after insert and toggle.
2432 ALL-HEADLINES means update todo statistics by including headlines
2433 with no TODO keyword as well, counting them as not done.
2434 A list of TODO keywords means the same, but skip keywords that are
2435 not in this list.
2436
2437 When this is set, todo statistics is updated in the parent of the
2438 current entry each time a todo state is changed."
2439 :group 'org-todo
2440 :type '(choice
2441 (const :tag "Yes, only for TODO entries" t)
2442 (const :tag "Yes, including all entries" all-headlines)
2443 (repeat :tag "Yes, for TODOs in this list"
2444 (string :tag "TODO keyword"))
2445 (other :tag "No TODO statistics" nil)))
2446
2447 (defcustom org-hierarchical-todo-statistics t
2448 "Non-nil means TODO statistics covers just direct children.
2449 When nil, all entries in the subtree are considered.
2450 This has only an effect if `org-provide-todo-statistics' is set.
2451 To set this to nil for only a single subtree, use a COOKIE_DATA
2452 property and include the word \"recursive\" into the value."
2453 :group 'org-todo
2454 :type 'boolean)
2455
2456 (defcustom org-after-todo-state-change-hook nil
2457 "Hook which is run after the state of a TODO item was changed.
2458 The new state (a string with a TODO keyword, or nil) is available in the
2459 Lisp variable `org-state'."
2460 :group 'org-todo
2461 :type 'hook)
2462
2463 (defvar org-blocker-hook nil
2464 "Hook for functions that are allowed to block a state change.
2465
2466 Functions in this hook should not modify the buffer.
2467 Each function gets as its single argument a property list,
2468 see `org-trigger-hook' for more information about this list.
2469
2470 If any of the functions in this hook returns nil, the state change
2471 is blocked.")
2472
2473 (defvar org-trigger-hook nil
2474 "Hook for functions that are triggered by a state change.
2475
2476 Each function gets as its single argument a property list with at
2477 least the following elements:
2478
2479 (:type type-of-change :position pos-at-entry-start
2480 :from old-state :to new-state)
2481
2482 Depending on the type, more properties may be present.
2483
2484 This mechanism is currently implemented for:
2485
2486 TODO state changes
2487 ------------------
2488 :type todo-state-change
2489 :from previous state (keyword as a string), or nil, or a symbol
2490 'todo' or 'done', to indicate the general type of state.
2491 :to new state, like in :from")
2492
2493 (defcustom org-enforce-todo-dependencies nil
2494 "Non-nil means undone TODO entries will block switching the parent to DONE.
2495 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2496 be blocked if any prior sibling is not yet done.
2497 Finally, if the parent is blocked because of ordered siblings of its own,
2498 the child will also be blocked."
2499 :set (lambda (var val)
2500 (set var val)
2501 (if val
2502 (add-hook 'org-blocker-hook
2503 'org-block-todo-from-children-or-siblings-or-parent)
2504 (remove-hook 'org-blocker-hook
2505 'org-block-todo-from-children-or-siblings-or-parent)))
2506 :group 'org-todo
2507 :type 'boolean)
2508
2509 (defcustom org-enforce-todo-checkbox-dependencies nil
2510 "Non-nil means unchecked boxes will block switching the parent to DONE.
2511 When this is nil, checkboxes have no influence on switching TODO states.
2512 When non-nil, you first need to check off all check boxes before the TODO
2513 entry can be switched to DONE.
2514 This variable needs to be set before org.el is loaded, and you need to
2515 restart Emacs after a change to make the change effective. The only way
2516 to change is while Emacs is running is through the customize interface."
2517 :set (lambda (var val)
2518 (set var val)
2519 (if val
2520 (add-hook 'org-blocker-hook
2521 'org-block-todo-from-checkboxes)
2522 (remove-hook 'org-blocker-hook
2523 'org-block-todo-from-checkboxes)))
2524 :group 'org-todo
2525 :type 'boolean)
2526
2527 (defcustom org-treat-insert-todo-heading-as-state-change nil
2528 "Non-nil means inserting a TODO heading is treated as state change.
2529 So when the command \\[org-insert-todo-heading] is used, state change
2530 logging will apply if appropriate. When nil, the new TODO item will
2531 be inserted directly, and no logging will take place."
2532 :group 'org-todo
2533 :type 'boolean)
2534
2535 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2536 "Non-nil means switching TODO states with S-cursor counts as state change.
2537 This is the default behavior. However, setting this to nil allows a
2538 convenient way to select a TODO state and bypass any logging associated
2539 with that."
2540 :group 'org-todo
2541 :type 'boolean)
2542
2543 (defcustom org-todo-state-tags-triggers nil
2544 "Tag changes that should be triggered by TODO state changes.
2545 This is a list. Each entry is
2546
2547 (state-change (tag . flag) .......)
2548
2549 State-change can be a string with a state, and empty string to indicate the
2550 state that has no TODO keyword, or it can be one of the symbols `todo'
2551 or `done', meaning any not-done or done state, respectively."
2552 :group 'org-todo
2553 :group 'org-tags
2554 :type '(repeat
2555 (cons (choice :tag "When changing to"
2556 (const :tag "Not-done state" todo)
2557 (const :tag "Done state" done)
2558 (string :tag "State"))
2559 (repeat
2560 (cons :tag "Tag action"
2561 (string :tag "Tag")
2562 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2563
2564 (defcustom org-log-done nil
2565 "Information to record when a task moves to the DONE state.
2566
2567 Possible values are:
2568
2569 nil Don't add anything, just change the keyword
2570 time Add a time stamp to the task
2571 note Prompt for a note and add it with template `org-log-note-headings'
2572
2573 This option can also be set with on a per-file-basis with
2574
2575 #+STARTUP: nologdone
2576 #+STARTUP: logdone
2577 #+STARTUP: lognotedone
2578
2579 You can have local logging settings for a subtree by setting the LOGGING
2580 property to one or more of these keywords."
2581 :group 'org-todo
2582 :group 'org-progress
2583 :type '(choice
2584 (const :tag "No logging" nil)
2585 (const :tag "Record CLOSED timestamp" time)
2586 (const :tag "Record CLOSED timestamp with note." note)))
2587
2588 ;; Normalize old uses of org-log-done.
2589 (cond
2590 ((eq org-log-done t) (setq org-log-done 'time))
2591 ((and (listp org-log-done) (memq 'done org-log-done))
2592 (setq org-log-done 'note)))
2593
2594 (defcustom org-log-reschedule nil
2595 "Information to record when the scheduling date of a tasks is modified.
2596
2597 Possible values are:
2598
2599 nil Don't add anything, just change the date
2600 time Add a time stamp to the task
2601 note Prompt for a note and add it with template `org-log-note-headings'
2602
2603 This option can also be set with on a per-file-basis with
2604
2605 #+STARTUP: nologreschedule
2606 #+STARTUP: logreschedule
2607 #+STARTUP: lognotereschedule"
2608 :group 'org-todo
2609 :group 'org-progress
2610 :type '(choice
2611 (const :tag "No logging" nil)
2612 (const :tag "Record timestamp" time)
2613 (const :tag "Record timestamp with note." note)))
2614
2615 (defcustom org-log-redeadline nil
2616 "Information to record when the deadline date of a tasks is modified.
2617
2618 Possible values are:
2619
2620 nil Don't add anything, just change the date
2621 time Add a time stamp to the task
2622 note Prompt for a note and add it with template `org-log-note-headings'
2623
2624 This option can also be set with on a per-file-basis with
2625
2626 #+STARTUP: nologredeadline
2627 #+STARTUP: logredeadline
2628 #+STARTUP: lognoteredeadline
2629
2630 You can have local logging settings for a subtree by setting the LOGGING
2631 property to one or more of these keywords."
2632 :group 'org-todo
2633 :group 'org-progress
2634 :type '(choice
2635 (const :tag "No logging" nil)
2636 (const :tag "Record timestamp" time)
2637 (const :tag "Record timestamp with note." note)))
2638
2639 (defcustom org-log-note-clock-out nil
2640 "Non-nil means record a note when clocking out of an item.
2641 This can also be configured on a per-file basis by adding one of
2642 the following lines anywhere in the buffer:
2643
2644 #+STARTUP: lognoteclock-out
2645 #+STARTUP: nolognoteclock-out"
2646 :group 'org-todo
2647 :group 'org-progress
2648 :type 'boolean)
2649
2650 (defcustom org-log-done-with-time t
2651 "Non-nil means the CLOSED time stamp will contain date and time.
2652 When nil, only the date will be recorded."
2653 :group 'org-progress
2654 :type 'boolean)
2655
2656 (defcustom org-log-note-headings
2657 '((done . "CLOSING NOTE %t")
2658 (state . "State %-12s from %-12S %t")
2659 (note . "Note taken on %t")
2660 (reschedule . "Rescheduled from %S on %t")
2661 (delschedule . "Not scheduled, was %S on %t")
2662 (redeadline . "New deadline from %S on %t")
2663 (deldeadline . "Removed deadline, was %S on %t")
2664 (refile . "Refiled on %t")
2665 (clock-out . ""))
2666 "Headings for notes added to entries.
2667 The value is an alist, with the car being a symbol indicating the note
2668 context, and the cdr is the heading to be used. The heading may also be the
2669 empty string.
2670 %t in the heading will be replaced by a time stamp.
2671 %T will be an active time stamp instead the default inactive one
2672 %d will be replaced by a short-format time stamp.
2673 %D will be replaced by an active short-format time stamp.
2674 %s will be replaced by the new TODO state, in double quotes.
2675 %S will be replaced by the old TODO state, in double quotes.
2676 %u will be replaced by the user name.
2677 %U will be replaced by the full user name.
2678
2679 In fact, it is not a good idea to change the `state' entry, because
2680 agenda log mode depends on the format of these entries."
2681 :group 'org-todo
2682 :group 'org-progress
2683 :type '(list :greedy t
2684 (cons (const :tag "Heading when closing an item" done) string)
2685 (cons (const :tag
2686 "Heading when changing todo state (todo sequence only)"
2687 state) string)
2688 (cons (const :tag "Heading when just taking a note" note) string)
2689 (cons (const :tag "Heading when rescheduling" reschedule) string)
2690 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2691 (cons (const :tag "Heading when changing deadline" redeadline) string)
2692 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2693 (cons (const :tag "Heading when refiling" refile) string)
2694 (cons (const :tag "Heading when clocking out" clock-out) string)))
2695
2696 (unless (assq 'note org-log-note-headings)
2697 (push '(note . "%t") org-log-note-headings))
2698
2699 (defcustom org-log-into-drawer nil
2700 "Non-nil means insert state change notes and time stamps into a drawer.
2701 When nil, state changes notes will be inserted after the headline and
2702 any scheduling and clock lines, but not inside a drawer.
2703
2704 The value of this variable should be the name of the drawer to use.
2705 LOGBOOK is proposed as the default drawer for this purpose, you can
2706 also set this to a string to define the drawer of your choice.
2707
2708 A value of t is also allowed, representing \"LOGBOOK\".
2709
2710 A value of t or nil can also be set with on a per-file-basis with
2711
2712 #+STARTUP: logdrawer
2713 #+STARTUP: nologdrawer
2714
2715 If this variable is set, `org-log-state-notes-insert-after-drawers'
2716 will be ignored.
2717
2718 You can set the property LOG_INTO_DRAWER to overrule this setting for
2719 a subtree."
2720 :group 'org-todo
2721 :group 'org-progress
2722 :type '(choice
2723 (const :tag "Not into a drawer" nil)
2724 (const :tag "LOGBOOK" t)
2725 (string :tag "Other")))
2726
2727 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2728
2729 (defun org-log-into-drawer ()
2730 "Return the value of `org-log-into-drawer', but let properties overrule.
2731 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2732 used instead of the default value."
2733 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2734 (cond
2735 ((not p) org-log-into-drawer)
2736 ((equal p "nil") nil)
2737 ((equal p "t") "LOGBOOK")
2738 (t p))))
2739
2740 (defcustom org-log-state-notes-insert-after-drawers nil
2741 "Non-nil means insert state change notes after any drawers in entry.
2742 Only the drawers that *immediately* follow the headline and the
2743 deadline/scheduled line are skipped.
2744 When nil, insert notes right after the heading and perhaps the line
2745 with deadline/scheduling if present.
2746
2747 This variable will have no effect if `org-log-into-drawer' is
2748 set."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type 'boolean)
2752
2753 (defcustom org-log-states-order-reversed t
2754 "Non-nil means the latest state note will be directly after heading.
2755 When nil, the state change notes will be ordered according to time.
2756
2757 This option can also be set with on a per-file-basis with
2758
2759 #+STARTUP: logstatesreversed
2760 #+STARTUP: nologstatesreversed"
2761 :group 'org-todo
2762 :group 'org-progress
2763 :type 'boolean)
2764
2765 (defcustom org-todo-repeat-to-state nil
2766 "The TODO state to which a repeater should return the repeating task.
2767 By default this is the first task in a TODO sequence, or the previous state
2768 in a TODO_TYP set. But you can specify another task here.
2769 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2770 :group 'org-todo
2771 :version "24.1"
2772 :type '(choice (const :tag "Head of sequence" nil)
2773 (string :tag "Specific state")))
2774
2775 (defcustom org-log-repeat 'time
2776 "Non-nil means record moving through the DONE state when triggering repeat.
2777 An auto-repeating task is immediately switched back to TODO when
2778 marked DONE. If you are not logging state changes (by adding \"@\"
2779 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2780 record a closing note, there will be no record of the task moving
2781 through DONE. This variable forces taking a note anyway.
2782
2783 nil Don't force a record
2784 time Record a time stamp
2785 note Prompt for a note and add it with template `org-log-note-headings'
2786
2787 This option can also be set with on a per-file-basis with
2788
2789 #+STARTUP: nologrepeat
2790 #+STARTUP: logrepeat
2791 #+STARTUP: lognoterepeat
2792
2793 You can have local logging settings for a subtree by setting the LOGGING
2794 property to one or more of these keywords."
2795 :group 'org-todo
2796 :group 'org-progress
2797 :type '(choice
2798 (const :tag "Don't force a record" nil)
2799 (const :tag "Force recording the DONE state" time)
2800 (const :tag "Force recording a note with the DONE state" note)))
2801
2802
2803 (defgroup org-priorities nil
2804 "Priorities in Org-mode."
2805 :tag "Org Priorities"
2806 :group 'org-todo)
2807
2808 (defcustom org-enable-priority-commands t
2809 "Non-nil means priority commands are active.
2810 When nil, these commands will be disabled, so that you never accidentally
2811 set a priority."
2812 :group 'org-priorities
2813 :type 'boolean)
2814
2815 (defcustom org-highest-priority ?A
2816 "The highest priority of TODO items. A character like ?A, ?B etc.
2817 Must have a smaller ASCII number than `org-lowest-priority'."
2818 :group 'org-priorities
2819 :type 'character)
2820
2821 (defcustom org-lowest-priority ?C
2822 "The lowest priority of TODO items. A character like ?A, ?B etc.
2823 Must have a larger ASCII number than `org-highest-priority'."
2824 :group 'org-priorities
2825 :type 'character)
2826
2827 (defcustom org-default-priority ?B
2828 "The default priority of TODO items.
2829 This is the priority an item gets if no explicit priority is given.
2830 When starting to cycle on an empty priority the first step in the cycle
2831 depends on `org-priority-start-cycle-with-default'. The resulting first
2832 step priority must not exceed the range from `org-highest-priority' to
2833 `org-lowest-priority' which means that `org-default-priority' has to be
2834 in this range exclusive or inclusive the range boundaries. Else the
2835 first step refuses to set the default and the second will fall back
2836 to (depending on the command used) the highest or lowest priority."
2837 :group 'org-priorities
2838 :type 'character)
2839
2840 (defcustom org-priority-start-cycle-with-default t
2841 "Non-nil means start with default priority when starting to cycle.
2842 When this is nil, the first step in the cycle will be (depending on the
2843 command used) one higher or lower than the default priority.
2844 See also `org-default-priority'."
2845 :group 'org-priorities
2846 :type 'boolean)
2847
2848 (defcustom org-get-priority-function nil
2849 "Function to extract the priority from a string.
2850 The string is normally the headline. If this is nil Org computes the
2851 priority from the priority cookie like [#A] in the headline. It returns
2852 an integer, increasing by 1000 for each priority level.
2853 The user can set a different function here, which should take a string
2854 as an argument and return the numeric priority."
2855 :group 'org-priorities
2856 :version "24.1"
2857 :type '(choice
2858 (const nil)
2859 (function)))
2860
2861 (defgroup org-time nil
2862 "Options concerning time stamps and deadlines in Org-mode."
2863 :tag "Org Time"
2864 :group 'org)
2865
2866 (defcustom org-insert-labeled-timestamps-at-point nil
2867 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2868 When nil, these labeled time stamps are forces into the second line of an
2869 entry, just after the headline. When scheduling from the global TODO list,
2870 the time stamp will always be forced into the second line."
2871 :group 'org-time
2872 :type 'boolean)
2873
2874 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2875 "Formats for `format-time-string' which are used for time stamps.
2876 It is not recommended to change this constant.")
2877
2878 (defcustom org-time-stamp-rounding-minutes '(0 5)
2879 "Number of minutes to round time stamps to.
2880 These are two values, the first applies when first creating a time stamp.
2881 The second applies when changing it with the commands `S-up' and `S-down'.
2882 When changing the time stamp, this means that it will change in steps
2883 of N minutes, as given by the second value.
2884
2885 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2886 numbers should be factors of 60, so for example 5, 10, 15.
2887
2888 When this is larger than 1, you can still force an exact time stamp by using
2889 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2890 and by using a prefix arg to `S-up/down' to specify the exact number
2891 of minutes to shift."
2892 :group 'org-time
2893 :get #'(lambda (var) ; Make sure both elements are there
2894 (if (integerp (default-value var))
2895 (list (default-value var) 5)
2896 (default-value var)))
2897 :type '(list
2898 (integer :tag "when inserting times")
2899 (integer :tag "when modifying times")))
2900
2901 ;; Normalize old customizations of this variable.
2902 (when (integerp org-time-stamp-rounding-minutes)
2903 (setq org-time-stamp-rounding-minutes
2904 (list org-time-stamp-rounding-minutes
2905 org-time-stamp-rounding-minutes)))
2906
2907 (defcustom org-display-custom-times nil
2908 "Non-nil means overlay custom formats over all time stamps.
2909 The formats are defined through the variable `org-time-stamp-custom-formats'.
2910 To turn this on on a per-file basis, insert anywhere in the file:
2911 #+STARTUP: customtime"
2912 :group 'org-time
2913 :set 'set-default
2914 :type 'sexp)
2915 (make-variable-buffer-local 'org-display-custom-times)
2916
2917 (defcustom org-time-stamp-custom-formats
2918 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2919 "Custom formats for time stamps. See `format-time-string' for the syntax.
2920 These are overlaid over the default ISO format if the variable
2921 `org-display-custom-times' is set. Time like %H:%M should be at the
2922 end of the second format. The custom formats are also honored by export
2923 commands, if custom time display is turned on at the time of export."
2924 :group 'org-time
2925 :type 'sexp)
2926
2927 (defun org-time-stamp-format (&optional long inactive)
2928 "Get the right format for a time string."
2929 (let ((f (if long (cdr org-time-stamp-formats)
2930 (car org-time-stamp-formats))))
2931 (if inactive
2932 (concat "[" (substring f 1 -1) "]")
2933 f)))
2934
2935 (defcustom org-time-clocksum-format
2936 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2937 "The format string used when creating CLOCKSUM lines.
2938 This is also used when Org mode generates a time duration.
2939
2940 The value can be a single format string containing two
2941 %-sequences, which will be filled with the number of hours and
2942 minutes in that order.
2943
2944 Alternatively, the value can be a plist associating any of the
2945 keys :years, :months, :weeks, :days, :hours or :minutes with
2946 format strings. The time duration is formatted using only the
2947 time components that are needed and concatenating the results.
2948 If a time unit in absent, it falls back to the next smallest
2949 unit.
2950
2951 The keys :require-years, :require-months, :require-days,
2952 :require-weeks, :require-hours, :require-minutes are also
2953 meaningful. A non-nil value for these keys indicates that the
2954 corresponding time component should always be included, even if
2955 its value is 0.
2956
2957
2958 For example,
2959
2960 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2961 :require-minutes t)
2962
2963 means durations longer than a day will be expressed in days,
2964 hours and minutes, and durations less than a day will always be
2965 expressed in hours and minutes (even for durations less than an
2966 hour).
2967
2968 The value
2969
2970 \(:days \"%dd\" :minutes \"%dm\")
2971
2972 means durations longer than a day will be expressed in days and
2973 minutes, and durations less than a day will be expressed entirely
2974 in minutes (even for durations longer than an hour)."
2975 :group 'org-time
2976 :group 'org-clock
2977 :version "24.4"
2978 :package-version '(Org . "8.0")
2979 :type '(choice (string :tag "Format string")
2980 (set :tag "Plist"
2981 (group :inline t (const :tag "Years" :years)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show years" :require-years)
2985 (const t))
2986 (group :inline t (const :tag "Months" :months)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show months" :require-months)
2990 (const t))
2991 (group :inline t (const :tag "Weeks" :weeks)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show weeks" :require-weeks)
2995 (const t))
2996 (group :inline t (const :tag "Days" :days)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show days" :require-days)
3000 (const t))
3001 (group :inline t (const :tag "Hours" :hours)
3002 (string :tag "Format string"))
3003 (group :inline t
3004 (const :tag "Always show hours" :require-hours)
3005 (const t))
3006 (group :inline t (const :tag "Minutes" :minutes)
3007 (string :tag "Format string"))
3008 (group :inline t
3009 (const :tag "Always show minutes" :require-minutes)
3010 (const t)))))
3011
3012 (defcustom org-time-clocksum-use-fractional nil
3013 "When non-nil, \\[org-clock-display] uses fractional times.
3014 See `org-time-clocksum-format' for more on time clock formats."
3015 :group 'org-time
3016 :group 'org-clock
3017 :version "24.3"
3018 :type 'boolean)
3019
3020 (defcustom org-time-clocksum-use-effort-durations nil
3021 "When non-nil, \\[org-clock-display] uses effort durations.
3022 E.g. by default, one day is considered to be a 8 hours effort,
3023 so a task that has been clocked for 16 hours will be displayed
3024 as during 2 days in the clock display or in the clocktable.
3025
3026 See `org-effort-durations' on how to set effort durations
3027 and `org-time-clocksum-format' for more on time clock formats."
3028 :group 'org-time
3029 :group 'org-clock
3030 :version "24.4"
3031 :package-version '(Org . "8.0")
3032 :type 'boolean)
3033
3034 (defcustom org-time-clocksum-fractional-format "%.2f"
3035 "The format string used when creating CLOCKSUM lines,
3036 or when Org mode generates a time duration, if
3037 `org-time-clocksum-use-fractional' is enabled.
3038
3039 The value can be a single format string containing one
3040 %-sequence, which will be filled with the number of hours as
3041 a float.
3042
3043 Alternatively, the value can be a plist associating any of the
3044 keys :years, :months, :weeks, :days, :hours or :minutes with
3045 a format string. The time duration is formatted using the
3046 largest time unit which gives a non-zero integer part. If all
3047 specified formats have zero integer part, the smallest time unit
3048 is used."
3049 :group 'org-time
3050 :type '(choice (string :tag "Format string")
3051 (set (group :inline t (const :tag "Years" :years)
3052 (string :tag "Format string"))
3053 (group :inline t (const :tag "Months" :months)
3054 (string :tag "Format string"))
3055 (group :inline t (const :tag "Weeks" :weeks)
3056 (string :tag "Format string"))
3057 (group :inline t (const :tag "Days" :days)
3058 (string :tag "Format string"))
3059 (group :inline t (const :tag "Hours" :hours)
3060 (string :tag "Format string"))
3061 (group :inline t (const :tag "Minutes" :minutes)
3062 (string :tag "Format string")))))
3063
3064 (defcustom org-deadline-warning-days 14
3065 "Number of days before expiration during which a deadline becomes active.
3066 This variable governs the display in sparse trees and in the agenda.
3067 When 0 or negative, it means use this number (the absolute value of it)
3068 even if a deadline has a different individual lead time specified.
3069
3070 Custom commands can set this variable in the options section."
3071 :group 'org-time
3072 :group 'org-agenda-daily/weekly
3073 :type 'integer)
3074
3075 (defcustom org-scheduled-delay-days 0
3076 "Number of days before a scheduled item becomes active.
3077 This variable governs the display in sparse trees and in the agenda.
3078 The default value (i.e. 0) means: don't delay scheduled item.
3079 When negative, it means use this number (the absolute value of it)
3080 even if a scheduled item has a different individual delay time
3081 specified.
3082
3083 Custom commands can set this variable in the options section."
3084 :group 'org-time
3085 :group 'org-agenda-daily/weekly
3086 :version "24.4"
3087 :package-version '(Org . "8.0")
3088 :type 'integer)
3089
3090 (defcustom org-read-date-prefer-future t
3091 "Non-nil means assume future for incomplete date input from user.
3092 This affects the following situations:
3093 1. The user gives a month but not a year.
3094 For example, if it is April and you enter \"feb 2\", this will be read
3095 as Feb 2, *next* year. \"May 5\", however, will be this year.
3096 2. The user gives a day, but no month.
3097 For example, if today is the 15th, and you enter \"3\", Org-mode will
3098 read this as the third of *next* month. However, if you enter \"17\",
3099 it will be considered as *this* month.
3100
3101 If you set this variable to the symbol `time', then also the following
3102 will work:
3103
3104 3. If the user gives a time.
3105 If the time is before now, it will be interpreted as tomorrow.
3106
3107 Currently none of this works for ISO week specifications.
3108
3109 When this option is nil, the current day, month and year will always be
3110 used as defaults.
3111
3112 See also `org-agenda-jump-prefer-future'."
3113 :group 'org-time
3114 :type '(choice
3115 (const :tag "Never" nil)
3116 (const :tag "Check month and day" t)
3117 (const :tag "Check month, day, and time" time)))
3118
3119 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3120 "Should the agenda jump command prefer the future for incomplete dates?
3121 The default is to do the same as configured in `org-read-date-prefer-future'.
3122 But you can also set a deviating value here.
3123 This may t or nil, or the symbol `org-read-date-prefer-future'."
3124 :group 'org-agenda
3125 :group 'org-time
3126 :version "24.1"
3127 :type '(choice
3128 (const :tag "Use org-read-date-prefer-future"
3129 org-read-date-prefer-future)
3130 (const :tag "Never" nil)
3131 (const :tag "Always" t)))
3132
3133 (defcustom org-read-date-force-compatible-dates t
3134 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3135
3136 Depending on the system Emacs is running on, certain dates cannot
3137 be represented with the type used internally to represent time.
3138 Dates between 1970-1-1 and 2038-1-1 can always be represented
3139 correctly. Some systems allow for earlier dates, some for later,
3140 some for both. One way to find out it to insert any date into an
3141 Org buffer, putting the cursor on the year and hitting S-up and
3142 S-down to test the range.
3143
3144 When this variable is set to t, the date/time prompt will not let
3145 you specify dates outside the 1970-2037 range, so it is certain that
3146 these dates will work in whatever version of Emacs you are
3147 running, and also that you can move a file from one Emacs implementation
3148 to another. WHenever Org is forcing the year for you, it will display
3149 a message and beep.
3150
3151 When this variable is nil, Org will check if the date is
3152 representable in the specific Emacs implementation you are using.
3153 If not, it will force a year, usually the current year, and beep
3154 to remind you. Currently this setting is not recommended because
3155 the likelihood that you will open your Org files in an Emacs that
3156 has limited date range is not negligible.
3157
3158 A workaround for this problem is to use diary sexp dates for time
3159 stamps outside of this range."
3160 :group 'org-time
3161 :version "24.1"
3162 :type 'boolean)
3163
3164 (defcustom org-read-date-display-live t
3165 "Non-nil means display current interpretation of date prompt live.
3166 This display will be in an overlay, in the minibuffer."
3167 :group 'org-time
3168 :type 'boolean)
3169
3170 (defcustom org-read-date-popup-calendar t
3171 "Non-nil means pop up a calendar when prompting for a date.
3172 In the calendar, the date can be selected with mouse-1. However, the
3173 minibuffer will also be active, and you can simply enter the date as well.
3174 When nil, only the minibuffer will be available."
3175 :group 'org-time
3176 :type 'boolean)
3177 (org-defvaralias 'org-popup-calendar-for-date-prompt
3178 'org-read-date-popup-calendar)
3179
3180 (make-obsolete-variable
3181 'org-read-date-minibuffer-setup-hook
3182 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3183 (defcustom org-read-date-minibuffer-setup-hook nil
3184 "Hook to be used to set up keys for the date/time interface.
3185 Add key definitions to `minibuffer-local-map', which will be a
3186 temporary copy.
3187
3188 WARNING: This option is obsolete, you should use
3189 `org-read-date-minibuffer-local-map' to set up keys."
3190 :group 'org-time
3191 :type 'hook)
3192
3193 (defcustom org-extend-today-until 0
3194 "The hour when your day really ends. Must be an integer.
3195 This has influence for the following applications:
3196 - When switching the agenda to \"today\". It it is still earlier than
3197 the time given here, the day recognized as TODAY is actually yesterday.
3198 - When a date is read from the user and it is still before the time given
3199 here, the current date and time will be assumed to be yesterday, 23:59.
3200 Also, timestamps inserted in capture templates follow this rule.
3201
3202 IMPORTANT: This is a feature whose implementation is and likely will
3203 remain incomplete. Really, it is only here because past midnight seems to
3204 be the favorite working time of John Wiegley :-)"
3205 :group 'org-time
3206 :type 'integer)
3207
3208 (defcustom org-use-effective-time nil
3209 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3210 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3211 \"effective time\" of any timestamps between midnight and 8am will be
3212 23:59 of the previous day."
3213 :group 'org-time
3214 :version "24.1"
3215 :type 'boolean)
3216
3217 (defcustom org-use-last-clock-out-time-as-effective-time nil
3218 "When non-nil, use the last clock out time for `org-todo'.
3219 Note that this option has precedence over the combined use of
3220 `org-use-effective-time' and `org-extend-today-until'."
3221 :group 'org-time
3222 :version "24.4"
3223 :package-version '(Org . "8.0")
3224 :type 'boolean)
3225
3226 (defcustom org-edit-timestamp-down-means-later nil
3227 "Non-nil means S-down will increase the time in a time stamp.
3228 When nil, S-up will increase."
3229 :group 'org-time
3230 :type 'boolean)
3231
3232 (defcustom org-calendar-follow-timestamp-change t
3233 "Non-nil means make the calendar window follow timestamp changes.
3234 When a timestamp is modified and the calendar window is visible, it will be
3235 moved to the new date."
3236 :group 'org-time
3237 :type 'boolean)
3238
3239 (defgroup org-tags nil
3240 "Options concerning tags in Org-mode."
3241 :tag "Org Tags"
3242 :group 'org)
3243
3244 (defcustom org-tag-alist nil
3245 "List of tags allowed in Org-mode files.
3246 When this list is nil, Org-mode will base TAG input on what is already in the
3247 buffer.
3248 The value of this variable is an alist, the car of each entry must be a
3249 keyword as a string, the cdr may be a character that is used to select
3250 that tag through the fast-tag-selection interface.
3251 See the manual for details."
3252 :group 'org-tags
3253 :type '(repeat
3254 (choice
3255 (cons (string :tag "Tag name")
3256 (character :tag "Access char"))
3257 (list :tag "Start radio group"
3258 (const :startgroup)
3259 (option (string :tag "Group description")))
3260 (list :tag "Group tags delimiter"
3261 (const :grouptags))
3262 (list :tag "End radio group"
3263 (const :endgroup)
3264 (option (string :tag "Group description")))
3265 (const :tag "New line" (:newline)))))
3266
3267 (defcustom org-tag-persistent-alist nil
3268 "List of tags that will always appear in all Org-mode files.
3269 This is in addition to any in buffer settings or customizations
3270 of `org-tag-alist'.
3271 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3272 The value of this variable is an alist, the car of each entry must be a
3273 keyword as a string, the cdr may be a character that is used to select
3274 that tag through the fast-tag-selection interface.
3275 See the manual for details.
3276 To disable these tags on a per-file basis, insert anywhere in the file:
3277 #+STARTUP: noptag"
3278 :group 'org-tags
3279 :type '(repeat
3280 (choice
3281 (cons (string :tag "Tag name")
3282 (character :tag "Access char"))
3283 (const :tag "Start radio group" (:startgroup))
3284 (const :tag "Group tags delimiter" (:grouptags))
3285 (const :tag "End radio group" (:endgroup))
3286 (const :tag "New line" (:newline)))))
3287
3288 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3289 "If non-nil, always offer completion for all tags of all agenda files.
3290 Instead of customizing this variable directly, you might want to
3291 set it locally for capture buffers, because there no list of
3292 tags in that file can be created dynamically (there are none).
3293
3294 (add-hook 'org-capture-mode-hook
3295 (lambda ()
3296 (set (make-local-variable
3297 'org-complete-tags-always-offer-all-agenda-tags)
3298 t)))"
3299 :group 'org-tags
3300 :version "24.1"
3301 :type 'boolean)
3302
3303 (defvar org-file-tags nil
3304 "List of tags that can be inherited by all entries in the file.
3305 The tags will be inherited if the variable `org-use-tag-inheritance'
3306 says they should be.
3307 This variable is populated from #+FILETAGS lines.")
3308
3309 (defcustom org-use-fast-tag-selection 'auto
3310 "Non-nil means use fast tag selection scheme.
3311 This is a special interface to select and deselect tags with single keys.
3312 When nil, fast selection is never used.
3313 When the symbol `auto', fast selection is used if and only if selection
3314 characters for tags have been configured, either through the variable
3315 `org-tag-alist' or through a #+TAGS line in the buffer.
3316 When t, fast selection is always used and selection keys are assigned
3317 automatically if necessary."
3318 :group 'org-tags
3319 :type '(choice
3320 (const :tag "Always" t)
3321 (const :tag "Never" nil)
3322 (const :tag "When selection characters are configured" auto)))
3323
3324 (defcustom org-fast-tag-selection-single-key nil
3325 "Non-nil means fast tag selection exits after first change.
3326 When nil, you have to press RET to exit it.
3327 During fast tag selection, you can toggle this flag with `C-c'.
3328 This variable can also have the value `expert'. In this case, the window
3329 displaying the tags menu is not even shown, until you press C-c again."
3330 :group 'org-tags
3331 :type '(choice
3332 (const :tag "No" nil)
3333 (const :tag "Yes" t)
3334 (const :tag "Expert" expert)))
3335
3336 (defvar org-fast-tag-selection-include-todo nil
3337 "Non-nil means fast tags selection interface will also offer TODO states.
3338 This is an undocumented feature, you should not rely on it.")
3339
3340 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3341 "The column to which tags should be indented in a headline.
3342 If this number is positive, it specifies the column. If it is negative,
3343 it means that the tags should be flushright to that column. For example,
3344 -80 works well for a normal 80 character screen.
3345 When 0, place tags directly after headline text, with only one space in
3346 between."
3347 :group 'org-tags
3348 :type 'integer)
3349
3350 (defcustom org-auto-align-tags t
3351 "Non-nil keeps tags aligned when modifying headlines.
3352 Some operations (i.e. demoting) change the length of a headline and
3353 therefore shift the tags around. With this option turned on, after
3354 each such operation the tags are again aligned to `org-tags-column'."
3355 :group 'org-tags
3356 :type 'boolean)
3357
3358 (defcustom org-use-tag-inheritance t
3359 "Non-nil means tags in levels apply also for sublevels.
3360 When nil, only the tags directly given in a specific line apply there.
3361 This may also be a list of tags that should be inherited, or a regexp that
3362 matches tags that should be inherited. Additional control is possible
3363 with the variable `org-tags-exclude-from-inheritance' which gives an
3364 explicit list of tags to be excluded from inheritance, even if the value of
3365 `org-use-tag-inheritance' would select it for inheritance.
3366
3367 If this option is t, a match early-on in a tree can lead to a large
3368 number of matches in the subtree when constructing the agenda or creating
3369 a sparse tree. If you only want to see the first match in a tree during
3370 a search, check out the variable `org-tags-match-list-sublevels'."
3371 :group 'org-tags
3372 :type '(choice
3373 (const :tag "Not" nil)
3374 (const :tag "Always" t)
3375 (repeat :tag "Specific tags" (string :tag "Tag"))
3376 (regexp :tag "Tags matched by regexp")))
3377
3378 (defcustom org-tags-exclude-from-inheritance nil
3379 "List of tags that should never be inherited.
3380 This is a way to exclude a few tags from inheritance. For way to do
3381 the opposite, to actively allow inheritance for selected tags,
3382 see the variable `org-use-tag-inheritance'."
3383 :group 'org-tags
3384 :type '(repeat (string :tag "Tag")))
3385
3386 (defun org-tag-inherit-p (tag)
3387 "Check if TAG is one that should be inherited."
3388 (cond
3389 ((member tag org-tags-exclude-from-inheritance) nil)
3390 ((eq org-use-tag-inheritance t) t)
3391 ((not org-use-tag-inheritance) nil)
3392 ((stringp org-use-tag-inheritance)
3393 (string-match org-use-tag-inheritance tag))
3394 ((listp org-use-tag-inheritance)
3395 (member tag org-use-tag-inheritance))
3396 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3397
3398 (defcustom org-tags-match-list-sublevels t
3399 "Non-nil means list also sublevels of headlines matching a search.
3400 This variable applies to tags/property searches, and also to stuck
3401 projects because this search is based on a tags match as well.
3402
3403 When set to the symbol `indented', sublevels are indented with
3404 leading dots.
3405
3406 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3407 the sublevels of a headline matching a tag search often also match
3408 the same search. Listing all of them can create very long lists.
3409 Setting this variable to nil causes subtrees of a match to be skipped.
3410
3411 This variable is semi-obsolete and probably should always be true. It
3412 is better to limit inheritance to certain tags using the variables
3413 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3414 :group 'org-tags
3415 :type '(choice
3416 (const :tag "No, don't list them" nil)
3417 (const :tag "Yes, do list them" t)
3418 (const :tag "List them, indented with leading dots" indented)))
3419
3420 (defcustom org-tags-sort-function nil
3421 "When set, tags are sorted using this function as a comparator."
3422 :group 'org-tags
3423 :type '(choice
3424 (const :tag "No sorting" nil)
3425 (const :tag "Alphabetical" string<)
3426 (const :tag "Reverse alphabetical" string>)
3427 (function :tag "Custom function" nil)))
3428
3429 (defvar org-tags-history nil
3430 "History of minibuffer reads for tags.")
3431 (defvar org-last-tags-completion-table nil
3432 "The last used completion table for tags.")
3433 (defvar org-after-tags-change-hook nil
3434 "Hook that is run after the tags in a line have changed.")
3435
3436 (defgroup org-properties nil
3437 "Options concerning properties in Org-mode."
3438 :tag "Org Properties"
3439 :group 'org)
3440
3441 (defcustom org-property-format "%-10s %s"
3442 "How property key/value pairs should be formatted by `indent-line'.
3443 When `indent-line' hits a property definition, it will format the line
3444 according to this format, mainly to make sure that the values are
3445 lined-up with respect to each other."
3446 :group 'org-properties
3447 :type 'string)
3448
3449 (defcustom org-properties-postprocess-alist nil
3450 "Alist of properties and functions to adjust inserted values.
3451 Elements of this alist must be of the form
3452
3453 ([string] [function])
3454
3455 where [string] must be a property name and [function] must be a
3456 lambda expression: this lambda expression must take one argument,
3457 the value to adjust, and return the new value as a string.
3458
3459 For example, this element will allow the property \"Remaining\"
3460 to be updated wrt the relation between the \"Effort\" property
3461 and the clock summary:
3462
3463 ((\"Remaining\" (lambda(value)
3464 (let ((clocksum (org-clock-sum-current-item))
3465 (effort (org-duration-string-to-minutes
3466 (org-entry-get (point) \"Effort\"))))
3467 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3468 :group 'org-properties
3469 :version "24.1"
3470 :type '(alist :key-type (string :tag "Property")
3471 :value-type (function :tag "Function")))
3472
3473 (defcustom org-use-property-inheritance nil
3474 "Non-nil means properties apply also for sublevels.
3475
3476 This setting is chiefly used during property searches. Turning it on can
3477 cause significant overhead when doing a search, which is why it is not
3478 on by default.
3479
3480 When nil, only the properties directly given in the current entry count.
3481 When t, every property is inherited. The value may also be a list of
3482 properties that should have inheritance, or a regular expression matching
3483 properties that should be inherited.
3484
3485 However, note that some special properties use inheritance under special
3486 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3487 and the properties ending in \"_ALL\" when they are used as descriptor
3488 for valid values of a property.
3489
3490 Note for programmers:
3491 When querying an entry with `org-entry-get', you can control if inheritance
3492 should be used. By default, `org-entry-get' looks only at the local
3493 properties. You can request inheritance by setting the inherit argument
3494 to t (to force inheritance) or to `selective' (to respect the setting
3495 in this variable)."
3496 :group 'org-properties
3497 :type '(choice
3498 (const :tag "Not" nil)
3499 (const :tag "Always" t)
3500 (repeat :tag "Specific properties" (string :tag "Property"))
3501 (regexp :tag "Properties matched by regexp")))
3502
3503 (defun org-property-inherit-p (property)
3504 "Check if PROPERTY is one that should be inherited."
3505 (cond
3506 ((eq org-use-property-inheritance t) t)
3507 ((not org-use-property-inheritance) nil)
3508 ((stringp org-use-property-inheritance)
3509 (string-match org-use-property-inheritance property))
3510 ((listp org-use-property-inheritance)
3511 (member property org-use-property-inheritance))
3512 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3513
3514 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3515 "The default column format, if no other format has been defined.
3516 This variable can be set on the per-file basis by inserting a line
3517
3518 #+COLUMNS: %25ITEM ....."
3519 :group 'org-properties
3520 :type 'string)
3521
3522 (defcustom org-columns-ellipses ".."
3523 "The ellipses to be used when a field in column view is truncated.
3524 When this is the empty string, as many characters as possible are shown,
3525 but then there will be no visual indication that the field has been truncated.
3526 When this is a string of length N, the last N characters of a truncated
3527 field are replaced by this string. If the column is narrower than the
3528 ellipses string, only part of the ellipses string will be shown."
3529 :group 'org-properties
3530 :type 'string)
3531
3532 (defcustom org-columns-modify-value-for-display-function nil
3533 "Function that modifies values for display in column view.
3534 For example, it can be used to cut out a certain part from a time stamp.
3535 The function must take 2 arguments:
3536
3537 column-title The title of the column (*not* the property name)
3538 value The value that should be modified.
3539
3540 The function should return the value that should be displayed,
3541 or nil if the normal value should be used."
3542 :group 'org-properties
3543 :type '(choice (const nil) (function)))
3544
3545 (defcustom org-effort-property "Effort"
3546 "The property that is being used to keep track of effort estimates.
3547 Effort estimates given in this property need to have the format H:MM."
3548 :group 'org-properties
3549 :group 'org-progress
3550 :type '(string :tag "Property"))
3551
3552 (defconst org-global-properties-fixed
3553 '(("VISIBILITY_ALL" . "folded children content all")
3554 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3555 "List of property/value pairs that can be inherited by any entry.
3556
3557 These are fixed values, for the preset properties. The user variable
3558 that can be used to add to this list is `org-global-properties'.
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. If the value represents
3562 multiple items like an \"_ALL\" property, separate the items by
3563 spaces.")
3564
3565 (defcustom org-global-properties nil
3566 "List of property/value pairs that can be inherited by any entry.
3567
3568 This list will be combined with the constant `org-global-properties-fixed'.
3569
3570 The entries in this list are cons cells where the car is a property
3571 name and cdr is a string with the value.
3572
3573 You can set buffer-local values for the same purpose in the variable
3574 `org-file-properties' this by adding lines like
3575
3576 #+PROPERTY: NAME VALUE"
3577 :group 'org-properties
3578 :type '(repeat
3579 (cons (string :tag "Property")
3580 (string :tag "Value"))))
3581
3582 (defvar org-file-properties nil
3583 "List of property/value pairs that can be inherited by any entry.
3584 Valid for the current buffer.
3585 This variable is populated from #+PROPERTY lines.")
3586 (make-variable-buffer-local 'org-file-properties)
3587
3588 (defgroup org-agenda nil
3589 "Options concerning agenda views in Org-mode."
3590 :tag "Org Agenda"
3591 :group 'org)
3592
3593 (defvar org-category nil
3594 "Variable used by org files to set a category for agenda display.
3595 Such files should use a file variable to set it, for example
3596
3597 # -*- mode: org; org-category: \"ELisp\"
3598
3599 or contain a special line
3600
3601 #+CATEGORY: ELisp
3602
3603 If the file does not specify a category, then file's base name
3604 is used instead.")
3605 (make-variable-buffer-local 'org-category)
3606 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3607
3608 (defcustom org-agenda-files nil
3609 "The files to be used for agenda display.
3610 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3611 \\[org-remove-file]. You can also use customize to edit the list.
3612
3613 If an entry is a directory, all files in that directory that are matched by
3614 `org-agenda-file-regexp' will be part of the file list.
3615
3616 If the value of the variable is not a list but a single file name, then
3617 the list of agenda files is actually stored and maintained in that file, one
3618 agenda file per line. In this file paths can be given relative to
3619 `org-directory'. Tilde expansion and environment variable substitution
3620 are also made."
3621 :group 'org-agenda
3622 :type '(choice
3623 (repeat :tag "List of files and directories" file)
3624 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3625
3626 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3627 "Regular expression to match files for `org-agenda-files'.
3628 If any element in the list in that variable contains a directory instead
3629 of a normal file, all files in that directory that are matched by this
3630 regular expression will be included."
3631 :group 'org-agenda
3632 :type 'regexp)
3633
3634 (defcustom org-agenda-text-search-extra-files nil
3635 "List of extra files to be searched by text search commands.
3636 These files will be searched in addition to the agenda files by the
3637 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3638 Note that these files will only be searched for text search commands,
3639 not for the other agenda views like todo lists, tag searches or the weekly
3640 agenda. This variable is intended to list notes and possibly archive files
3641 that should also be searched by these two commands.
3642 In fact, if the first element in the list is the symbol `agenda-archives',
3643 then all archive files of all agenda files will be added to the search
3644 scope."
3645 :group 'org-agenda
3646 :type '(set :greedy t
3647 (const :tag "Agenda Archives" agenda-archives)
3648 (repeat :inline t (file))))
3649
3650 (org-defvaralias 'org-agenda-multi-occur-extra-files
3651 'org-agenda-text-search-extra-files)
3652
3653 (defcustom org-agenda-skip-unavailable-files nil
3654 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3655 A nil value means to remove them, after a query, from the list."
3656 :group 'org-agenda
3657 :type 'boolean)
3658
3659 (defcustom org-calendar-to-agenda-key [?c]
3660 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3661 The command `org-calendar-goto-agenda' will be bound to this key. The
3662 default is the character `c' because then `c' can be used to switch back and
3663 forth between agenda and calendar."
3664 :group 'org-agenda
3665 :type 'sexp)
3666
3667 (defcustom org-calendar-insert-diary-entry-key [?i]
3668 "The key to be installed in `calendar-mode-map' for adding diary entries.
3669 This option is irrelevant until `org-agenda-diary-file' has been configured
3670 to point to an Org-mode file. When that is the case, the command
3671 `org-agenda-diary-entry' will be bound to the key given here, by default
3672 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3673 if you want to continue doing this, you need to change this to a different
3674 key."
3675 :group 'org-agenda
3676 :type 'sexp)
3677
3678 (defcustom org-agenda-diary-file 'diary-file
3679 "File to which to add new entries with the `i' key in agenda and calendar.
3680 When this is the symbol `diary-file', the functionality in the Emacs
3681 calendar will be used to add entries to the `diary-file'. But when this
3682 points to a file, `org-agenda-diary-entry' will be used instead."
3683 :group 'org-agenda
3684 :type '(choice
3685 (const :tag "The standard Emacs diary file" diary-file)
3686 (file :tag "Special Org file diary entries")))
3687
3688 (eval-after-load "calendar"
3689 '(progn
3690 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3691 'org-calendar-goto-agenda)
3692 (add-hook 'calendar-mode-hook
3693 (lambda ()
3694 (unless (eq org-agenda-diary-file 'diary-file)
3695 (define-key calendar-mode-map
3696 org-calendar-insert-diary-entry-key
3697 'org-agenda-diary-entry))))))
3698
3699 (defgroup org-latex nil
3700 "Options for embedding LaTeX code into Org-mode."
3701 :tag "Org LaTeX"
3702 :group 'org)
3703
3704 (defcustom org-format-latex-options
3705 '(:foreground default :background default :scale 1.0
3706 :html-foreground "Black" :html-background "Transparent"
3707 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3708 "Options for creating images from LaTeX fragments.
3709 This is a property list with the following properties:
3710 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3711 `default' means use the foreground of the default face.
3712 `auto' means use the foreground from the text face.
3713 :background the background color, or \"Transparent\".
3714 `default' means use the background of the default face.
3715 `auto' means use the background from the text face.
3716 :scale a scaling factor for the size of the images, to get more pixels
3717 :html-foreground, :html-background, :html-scale
3718 the same numbers for HTML export.
3719 :matchers a list indicating which matchers should be used to
3720 find LaTeX fragments. Valid members of this list are:
3721 \"begin\" find environments
3722 \"$1\" find single characters surrounded by $.$
3723 \"$\" find math expressions surrounded by $...$
3724 \"$$\" find math expressions surrounded by $$....$$
3725 \"\\(\" find math expressions surrounded by \\(...\\)
3726 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3727 :group 'org-latex
3728 :type 'plist)
3729
3730 (defcustom org-format-latex-signal-error t
3731 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3732 When nil, just push out a message."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type 'boolean)
3736
3737 (defcustom org-latex-to-mathml-jar-file nil
3738 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3739 Use this to specify additional executable file say a jar file.
3740
3741 When using MathToWeb as the converter, specify the full-path to
3742 your mathtoweb.jar file."
3743 :group 'org-latex
3744 :version "24.1"
3745 :type '(choice
3746 (const :tag "None" nil)
3747 (file :tag "JAR file" :must-match t)))
3748
3749 (defcustom org-latex-to-mathml-convert-command nil
3750 "Command to convert LaTeX fragments to MathML.
3751 Replace format-specifiers in the command as noted below and use
3752 `shell-command' to convert LaTeX to MathML.
3753 %j: Executable file in fully expanded form as specified by
3754 `org-latex-to-mathml-jar-file'.
3755 %I: Input LaTeX file in fully expanded form
3756 %o: Output MathML file
3757 This command is used by `org-create-math-formula'.
3758
3759 When using MathToWeb as the converter, set this to
3760 \"java -jar %j -unicode -force -df %o %I\"."
3761 :group 'org-latex
3762 :version "24.1"
3763 :type '(choice
3764 (const :tag "None" nil)
3765 (string :tag "\nShell command")))
3766
3767 (defcustom org-latex-create-formula-image-program 'dvipng
3768 "Program to convert LaTeX fragments with.
3769
3770 dvipng Process the LaTeX fragments to dvi file, then convert
3771 dvi files to png files using dvipng.
3772 This will also include processing of non-math environments.
3773 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3774 to convert pdf files to png files"
3775 :group 'org-latex
3776 :version "24.1"
3777 :type '(choice
3778 (const :tag "dvipng" dvipng)
3779 (const :tag "imagemagick" imagemagick)))
3780
3781 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3782 "Path to store latex preview images.
3783 A relative path here creates many directories relative to the
3784 processed org files paths. An absolute path puts all preview
3785 images at the same place."
3786 :group 'org-latex
3787 :version "24.3"
3788 :type 'string)
3789
3790 (defun org-format-latex-mathml-available-p ()
3791 "Return t if `org-latex-to-mathml-convert-command' is usable."
3792 (save-match-data
3793 (when (and (boundp 'org-latex-to-mathml-convert-command)
3794 org-latex-to-mathml-convert-command)
3795 (let ((executable (car (split-string
3796 org-latex-to-mathml-convert-command))))
3797 (when (executable-find executable)
3798 (if (string-match
3799 "%j" org-latex-to-mathml-convert-command)
3800 (file-readable-p org-latex-to-mathml-jar-file)
3801 t))))))
3802
3803 (defcustom org-format-latex-header "\\documentclass{article}
3804 \\usepackage[usenames]{color}
3805 \[PACKAGES]
3806 \[DEFAULT-PACKAGES]
3807 \\pagestyle{empty} % do not remove
3808 % The settings below are copied from fullpage.sty
3809 \\setlength{\\textwidth}{\\paperwidth}
3810 \\addtolength{\\textwidth}{-3cm}
3811 \\setlength{\\oddsidemargin}{1.5cm}
3812 \\addtolength{\\oddsidemargin}{-2.54cm}
3813 \\setlength{\\evensidemargin}{\\oddsidemargin}
3814 \\setlength{\\textheight}{\\paperheight}
3815 \\addtolength{\\textheight}{-\\headheight}
3816 \\addtolength{\\textheight}{-\\headsep}
3817 \\addtolength{\\textheight}{-\\footskip}
3818 \\addtolength{\\textheight}{-3cm}
3819 \\setlength{\\topmargin}{1.5cm}
3820 \\addtolength{\\topmargin}{-2.54cm}"
3821 "The document header used for processing LaTeX fragments.
3822 It is imperative that this header make sure that no page number
3823 appears on the page. The package defined in the variables
3824 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3825 will either replace the placeholder \"[PACKAGES]\" in this
3826 header, or they will be appended."
3827 :group 'org-latex
3828 :type 'string)
3829
3830 (defun org-set-packages-alist (var val)
3831 "Set the packages alist and make sure it has 3 elements per entry."
3832 (set var (mapcar (lambda (x)
3833 (if (and (consp x) (= (length x) 2))
3834 (list (car x) (nth 1 x) t)
3835 x))
3836 val)))
3837
3838 (defun org-get-packages-alist (var)
3839 "Get the packages alist and make sure it has 3 elements per entry."
3840 (mapcar (lambda (x)
3841 (if (and (consp x) (= (length x) 2))
3842 (list (car x) (nth 1 x) t)
3843 x))
3844 (default-value var)))
3845
3846 (defcustom org-latex-default-packages-alist
3847 '(("AUTO" "inputenc" t)
3848 ("T1" "fontenc" t)
3849 ("" "fixltx2e" nil)
3850 ("" "graphicx" t)
3851 ("" "longtable" nil)
3852 ("" "float" nil)
3853 ("" "wrapfig" nil)
3854 ("" "rotating" nil)
3855 ("normalem" "ulem" t)
3856 ("" "amsmath" t)
3857 ("" "textcomp" t)
3858 ("" "marvosym" t)
3859 ("" "wasysym" t)
3860 ("" "amssymb" t)
3861 ("" "hyperref" nil)
3862 "\\tolerance=1000")
3863 "Alist of default packages to be inserted in the header.
3864
3865 Change this only if one of the packages here causes an
3866 incompatibility with another package you are using.
3867
3868 The packages in this list are needed by one part or another of
3869 Org mode to function properly:
3870
3871 - inputenc, fontenc: for basic font and character selection
3872 - fixltx2e: Important patches of LaTeX itself
3873 - graphicx: for including images
3874 - longtable: For multipage tables
3875 - float, wrapfig: for figure placement
3876 - rotating: for sideways figures and tables
3877 - ulem: for underline and strike-through
3878 - amsmath: for subscript and superscript and math environments
3879 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3880 for interpreting the entities in `org-entities'. You can skip
3881 some of these packages if you don't use any of their symbols.
3882 - hyperref: for cross references
3883
3884 Therefore you should not modify this variable unless you know
3885 what you are doing. The one reason to change it anyway is that
3886 you might be loading some other package that conflicts with one
3887 of the default packages. Each element is either a cell or
3888 a string.
3889
3890 A cell is of the format:
3891
3892 \( \"options\" \"package\" SNIPPET-FLAG).
3893
3894 If SNIPPET-FLAG is non-nil, the package also needs to be included
3895 when compiling LaTeX snippets into images for inclusion into
3896 non-LaTeX output.
3897
3898 A string will be inserted as-is in the header of the document."
3899 :group 'org-latex
3900 :group 'org-export-latex
3901 :set 'org-set-packages-alist
3902 :get 'org-get-packages-alist
3903 :version "24.1"
3904 :type '(repeat
3905 (choice
3906 (list :tag "options/package pair"
3907 (string :tag "options")
3908 (string :tag "package")
3909 (boolean :tag "Snippet"))
3910 (string :tag "A line of LaTeX"))))
3911
3912 (defcustom org-latex-packages-alist nil
3913 "Alist of packages to be inserted in every LaTeX header.
3914
3915 These will be inserted after `org-latex-default-packages-alist'.
3916 Each element is either a cell or a string.
3917
3918 A cell is of the format:
3919
3920 \(\"options\" \"package\" SNIPPET-FLAG)
3921
3922 SNIPPET-FLAG, when non-nil, indicates that this package is also
3923 needed when turning LaTeX snippets into images for inclusion into
3924 non-LaTeX output.
3925
3926 A string will be inserted as-is in the header of the document.
3927
3928 Make sure that you only list packages here which:
3929
3930 - you want in every file;
3931 - do not conflict with the setup in `org-format-latex-header';
3932 - do not conflict with the default packages in
3933 `org-latex-default-packages-alist'."
3934 :group 'org-latex
3935 :group 'org-export-latex
3936 :set 'org-set-packages-alist
3937 :get 'org-get-packages-alist
3938 :type '(repeat
3939 (choice
3940 (list :tag "options/package pair"
3941 (string :tag "options")
3942 (string :tag "package")
3943 (boolean :tag "Snippet"))
3944 (string :tag "A line of LaTeX"))))
3945
3946 (defgroup org-appearance nil
3947 "Settings for Org-mode appearance."
3948 :tag "Org Appearance"
3949 :group 'org)
3950
3951 (defcustom org-level-color-stars-only nil
3952 "Non-nil means fontify only the stars in each headline.
3953 When nil, the entire headline is fontified.
3954 Changing it requires restart of `font-lock-mode' to become effective
3955 also in regions already fontified."
3956 :group 'org-appearance
3957 :type 'boolean)
3958
3959 (defcustom org-hide-leading-stars nil
3960 "Non-nil means hide the first N-1 stars in a headline.
3961 This works by using the face `org-hide' for these stars. This
3962 face is white for a light background, and black for a dark
3963 background. You may have to customize the face `org-hide' to
3964 make this work.
3965 Changing it requires restart of `font-lock-mode' to become effective
3966 also in regions already fontified.
3967 You may also set this on a per-file basis by adding one of the following
3968 lines to the buffer:
3969
3970 #+STARTUP: hidestars
3971 #+STARTUP: showstars"
3972 :group 'org-appearance
3973 :type 'boolean)
3974
3975 (defcustom org-hidden-keywords nil
3976 "List of symbols corresponding to keywords to be hidden the org buffer.
3977 For example, a value '(title) for this list will make the document's title
3978 appear in the buffer without the initial #+TITLE: keyword."
3979 :group 'org-appearance
3980 :version "24.1"
3981 :type '(set (const :tag "#+AUTHOR" author)
3982 (const :tag "#+DATE" date)
3983 (const :tag "#+EMAIL" email)
3984 (const :tag "#+TITLE" title)))
3985
3986 (defcustom org-custom-properties nil
3987 "List of properties (as strings) with a special meaning.
3988 The default use of these custom properties is to let the user
3989 hide them with `org-toggle-custom-properties-visibility'."
3990 :group 'org-properties
3991 :group 'org-appearance
3992 :version "24.3"
3993 :type '(repeat (string :tag "Property Name")))
3994
3995 (defcustom org-fontify-done-headline nil
3996 "Non-nil means change the face of a headline if it is marked DONE.
3997 Normally, only the TODO/DONE keyword indicates the state of a headline.
3998 When this is non-nil, the headline after the keyword is set to the
3999 `org-headline-done' as an additional indication."
4000 :group 'org-appearance
4001 :type 'boolean)
4002
4003 (defcustom org-fontify-emphasized-text t
4004 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4005 Changing this variable requires a restart of Emacs to take effect."
4006 :group 'org-appearance
4007 :type 'boolean)
4008
4009 (defcustom org-fontify-whole-heading-line nil
4010 "Non-nil means fontify the whole line for headings.
4011 This is useful when setting a background color for the
4012 org-level-* faces."
4013 :group 'org-appearance
4014 :type 'boolean)
4015
4016 (defcustom org-highlight-latex-and-related nil
4017 "Non-nil means highlight LaTeX related syntax in the buffer.
4018 When non nil, the value should be a list containing any of the
4019 following symbols:
4020 `latex' Highlight LaTeX snippets and environments.
4021 `script' Highlight subscript and superscript.
4022 `entities' Highlight entities."
4023 :group 'org-appearance
4024 :version "24.4"
4025 :package-version '(Org . "8.0")
4026 :type '(choice
4027 (const :tag "No highlighting" nil)
4028 (set :greedy t :tag "Highlight"
4029 (const :tag "LaTeX snippets and environments" latex)
4030 (const :tag "Subscript and superscript" script)
4031 (const :tag "Entities" entities))))
4032
4033 (defcustom org-hide-emphasis-markers nil
4034 "Non-nil mean font-lock should hide the emphasis marker characters."
4035 :group 'org-appearance
4036 :type 'boolean)
4037
4038 (defcustom org-pretty-entities nil
4039 "Non-nil means show entities as UTF8 characters.
4040 When nil, the \\name form remains in the buffer."
4041 :group 'org-appearance
4042 :version "24.1"
4043 :type 'boolean)
4044
4045 (defcustom org-pretty-entities-include-sub-superscripts t
4046 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4047 :group 'org-appearance
4048 :version "24.1"
4049 :type 'boolean)
4050
4051 (defvar org-emph-re nil
4052 "Regular expression for matching emphasis.
4053 After a match, the match groups contain these elements:
4054 0 The match of the full regular expression, including the characters
4055 before and after the proper match
4056 1 The character before the proper match, or empty at beginning of line
4057 2 The proper match, including the leading and trailing markers
4058 3 The leading marker like * or /, indicating the type of highlighting
4059 4 The text between the emphasis markers, not including the markers
4060 5 The character after the match, empty at the end of a line")
4061 (defvar org-verbatim-re nil
4062 "Regular expression for matching verbatim text.")
4063 (defvar org-emphasis-regexp-components) ; defined just below
4064 (defvar org-emphasis-alist) ; defined just below
4065 (defun org-set-emph-re (var val)
4066 "Set variable and compute the emphasis regular expression."
4067 (set var val)
4068 (when (and (boundp 'org-emphasis-alist)
4069 (boundp 'org-emphasis-regexp-components)
4070 org-emphasis-alist org-emphasis-regexp-components)
4071 (let* ((e org-emphasis-regexp-components)
4072 (pre (car e))
4073 (post (nth 1 e))
4074 (border (nth 2 e))
4075 (body (nth 3 e))
4076 (nl (nth 4 e))
4077 (body1 (concat body "*?"))
4078 (markers (mapconcat 'car org-emphasis-alist ""))
4079 (vmarkers (mapconcat
4080 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4081 org-emphasis-alist "")))
4082 ;; make sure special characters appear at the right position in the class
4083 (if (string-match "\\^" markers)
4084 (setq markers (concat (replace-match "" t t markers) "^")))
4085 (if (string-match "-" markers)
4086 (setq markers (concat (replace-match "" t t markers) "-")))
4087 (if (string-match "\\^" vmarkers)
4088 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4089 (if (string-match "-" vmarkers)
4090 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4091 (if (> nl 0)
4092 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4093 (int-to-string nl) "\\}")))
4094 ;; Make the regexp
4095 (setq org-emph-re
4096 (concat "\\([" pre "]\\|^\\)"
4097 "\\("
4098 "\\([" markers "]\\)"
4099 "\\("
4100 "[^" border "]\\|"
4101 "[^" border "]"
4102 body1
4103 "[^" border "]"
4104 "\\)"
4105 "\\3\\)"
4106 "\\([" post "]\\|$\\)"))
4107 (setq org-verbatim-re
4108 (concat "\\([" pre "]\\|^\\)"
4109 "\\("
4110 "\\([" vmarkers "]\\)"
4111 "\\("
4112 "[^" border "]\\|"
4113 "[^" border "]"
4114 body1
4115 "[^" border "]"
4116 "\\)"
4117 "\\3\\)"
4118 "\\([" post "]\\|$\\)")))))
4119
4120 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4121 ;; set this option proved cumbersome. See this message/thread:
4122 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4123 (defvar org-emphasis-regexp-components
4124 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4125 "Components used to build the regular expression for emphasis.
4126 This is a list with five entries. Terminology: In an emphasis string
4127 like \" *strong word* \", we call the initial space PREMATCH, the final
4128 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4129 and \"trong wor\" is the body. The different components in this variable
4130 specify what is allowed/forbidden in each part:
4131
4132 pre Chars allowed as prematch. Beginning of line will be allowed too.
4133 post Chars allowed as postmatch. End of line will be allowed too.
4134 border The chars *forbidden* as border characters.
4135 body-regexp A regexp like \".\" to match a body character. Don't use
4136 non-shy groups here, and don't allow newline here.
4137 newline The maximum number of newlines allowed in an emphasis exp.
4138
4139 You need to reload Org or to restart Emacs after customizing this.")
4140
4141 (defcustom org-emphasis-alist
4142 `(("*" bold)
4143 ("/" italic)
4144 ("_" underline)
4145 ("=" org-verbatim verbatim)
4146 ("~" org-code verbatim)
4147 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4148 "Alist of characters and faces to emphasize text.
4149 Text starting and ending with a special character will be emphasized,
4150 for example *bold*, _underlined_ and /italic/. This variable sets the
4151 marker characters and the face to be used by font-lock for highlighting
4152 in Org-mode Emacs buffers.
4153
4154 You need to reload Org or to restart Emacs after customizing this."
4155 :group 'org-appearance
4156 :set 'org-set-emph-re
4157 :version "24.4"
4158 :package-version '(Org . "8.0")
4159 :type '(repeat
4160 (list
4161 (string :tag "Marker character")
4162 (choice
4163 (face :tag "Font-lock-face")
4164 (plist :tag "Face property list"))
4165 (option (const verbatim)))))
4166
4167 (defvar org-protecting-blocks
4168 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4169 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4170 This is needed for font-lock setup.")
4171
4172 ;;; Miscellaneous options
4173
4174 (defgroup org-completion nil
4175 "Completion in Org-mode."
4176 :tag "Org Completion"
4177 :group 'org)
4178
4179 (defcustom org-completion-use-ido nil
4180 "Non-nil means use ido completion wherever possible.
4181 Note that `ido-mode' must be active for this variable to be relevant.
4182 If you decide to turn this variable on, you might well want to turn off
4183 `org-outline-path-complete-in-steps'.
4184 See also `org-completion-use-iswitchb'."
4185 :group 'org-completion
4186 :type 'boolean)
4187
4188 (defcustom org-completion-use-iswitchb nil
4189 "Non-nil means use iswitchb completion wherever possible.
4190 Note that `iswitchb-mode' must be active for this variable to be relevant.
4191 If you decide to turn this variable on, you might well want to turn off
4192 `org-outline-path-complete-in-steps'.
4193 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4194 :group 'org-completion
4195 :type 'boolean)
4196
4197 (defcustom org-completion-fallback-command 'hippie-expand
4198 "The expansion command called by \\[pcomplete] in normal context.
4199 Normal means, no org-mode-specific context."
4200 :group 'org-completion
4201 :type 'function)
4202
4203 ;;; Functions and variables from their packages
4204 ;; Declared here to avoid compiler warnings
4205
4206 ;; XEmacs only
4207 (defvar outline-mode-menu-heading)
4208 (defvar outline-mode-menu-show)
4209 (defvar outline-mode-menu-hide)
4210 (defvar zmacs-regions) ; XEmacs regions
4211
4212 ;; Emacs only
4213 (defvar mark-active)
4214
4215 ;; Various packages
4216 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4217 (declare-function calendar-forward-day "cal-move" (arg))
4218 (declare-function calendar-goto-date "cal-move" (date))
4219 (declare-function calendar-goto-today "cal-move" ())
4220 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4221 (defvar calc-embedded-close-formula)
4222 (defvar calc-embedded-open-formula)
4223 (declare-function cdlatex-tab "ext:cdlatex" ())
4224 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4225 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4226 (defvar font-lock-unfontify-region-function)
4227 (declare-function iswitchb-read-buffer "iswitchb"
4228 (prompt &optional default require-match start matches-set))
4229 (defvar iswitchb-temp-buflist)
4230 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4231 (defvar org-agenda-tags-todo-honor-ignore-options)
4232 (declare-function org-agenda-skip "org-agenda" ())
4233 (declare-function
4234 org-agenda-format-item "org-agenda"
4235 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4236 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4237 (declare-function org-agenda-change-all-lines "org-agenda"
4238 (newhead hdmarker &optional fixface just-this))
4239 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4240 (declare-function org-agenda-maybe-redo "org-agenda" ())
4241 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4242 (beg end))
4243 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4244 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4245 "org-agenda" (&optional end))
4246 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4247 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4248 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4249 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4250 (declare-function org-indent-mode "org-indent" (&optional arg))
4251 (declare-function parse-time-string "parse-time" (string))
4252 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4253 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4254 (defvar remember-data-file)
4255 (defvar texmathp-why)
4256 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4257 (declare-function table--at-cell-p "table" (position &optional object at-column))
4258
4259 (defvar org-latex-regexps)
4260
4261 ;;; Autoload and prepare some org modules
4262
4263 ;; Some table stuff that needs to be defined here, because it is used
4264 ;; by the functions setting up org-mode or checking for table context.
4265
4266 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4267 "Detect an org-type or table-type table.")
4268 (defconst org-table-line-regexp "^[ \t]*|"
4269 "Detect an org-type table line.")
4270 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4271 "Detect an org-type table line.")
4272 (defconst org-table-hline-regexp "^[ \t]*|-"
4273 "Detect an org-type table hline.")
4274 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4275 "Detect a table-type table hline.")
4276 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4277 "Detect the first line outside a table when searching from within it.
4278 This works for both table types.")
4279
4280 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4281 "Detect a #+TBLFM line.")
4282
4283 ;;;###autoload
4284 (defun turn-on-orgtbl ()
4285 "Unconditionally turn on `orgtbl-mode'."
4286 (require 'org-table)
4287 (orgtbl-mode 1))
4288
4289 (defun org-at-table-p (&optional table-type)
4290 "Return t if the cursor is inside an org-type table.
4291 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4292 (if org-enable-table-editor
4293 (save-excursion
4294 (beginning-of-line 1)
4295 (looking-at (if table-type org-table-any-line-regexp
4296 org-table-line-regexp)))
4297 nil))
4298 (defsubst org-table-p () (org-at-table-p))
4299
4300 (defun org-at-table.el-p ()
4301 "Return t if and only if we are at a table.el table."
4302 (and (org-at-table-p 'any)
4303 (save-excursion
4304 (goto-char (org-table-begin 'any))
4305 (looking-at org-table1-hline-regexp))))
4306
4307 (defun org-table-recognize-table.el ()
4308 "If there is a table.el table nearby, recognize it and move into it."
4309 (if org-table-tab-recognizes-table.el
4310 (if (org-at-table.el-p)
4311 (progn
4312 (beginning-of-line 1)
4313 (if (looking-at org-table-dataline-regexp)
4314 nil
4315 (if (looking-at org-table1-hline-regexp)
4316 (progn
4317 (beginning-of-line 2)
4318 (if (looking-at org-table-any-border-regexp)
4319 (beginning-of-line -1)))))
4320 (if (re-search-forward "|" (org-table-end t) t)
4321 (progn
4322 (require 'table)
4323 (if (table--at-cell-p (point))
4324 t
4325 (message "recognizing table.el table...")
4326 (table-recognize-table)
4327 (message "recognizing table.el table...done")))
4328 (error "This should not happen"))
4329 t)
4330 nil)
4331 nil))
4332
4333 (defun org-at-table-hline-p ()
4334 "Return t if the cursor is inside a hline in a table."
4335 (if org-enable-table-editor
4336 (save-excursion
4337 (beginning-of-line 1)
4338 (looking-at org-table-hline-regexp))
4339 nil))
4340
4341 (defun org-table-map-tables (function &optional quietly)
4342 "Apply FUNCTION to the start of all tables in the buffer."
4343 (save-excursion
4344 (save-restriction
4345 (widen)
4346 (goto-char (point-min))
4347 (while (re-search-forward org-table-any-line-regexp nil t)
4348 (unless quietly
4349 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4350 (beginning-of-line 1)
4351 (when (and (looking-at org-table-line-regexp)
4352 ;; Exclude tables in src/example/verbatim/clocktable blocks
4353 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4354 (save-excursion (funcall function))
4355 (or (looking-at org-table-line-regexp)
4356 (forward-char 1)))
4357 (re-search-forward org-table-any-border-regexp nil 1))))
4358 (unless quietly (message "Mapping tables: done")))
4359
4360 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4361 (declare-function org-clock-update-mode-line "org-clock" ())
4362 (declare-function org-resolve-clocks "org-clock"
4363 (&optional also-non-dangling-p prompt last-valid))
4364
4365 (defun org-at-TBLFM-p (&optional pos)
4366 "Return t when point (or POS) is in #+TBLFM line."
4367 (save-excursion
4368 (let ((pos pos)))
4369 (goto-char (or pos (point)))
4370 (beginning-of-line 1)
4371 (looking-at org-TBLFM-regexp)))
4372
4373 (defvar org-clock-start-time)
4374 (defvar org-clock-marker (make-marker)
4375 "Marker recording the last clock-in.")
4376 (defvar org-clock-hd-marker (make-marker)
4377 "Marker recording the last clock-in, but the headline position.")
4378 (defvar org-clock-heading ""
4379 "The heading of the current clock entry.")
4380 (defun org-clock-is-active ()
4381 "Return the buffer where the clock is currently running.
4382 Return nil if no clock is running."
4383 (marker-buffer org-clock-marker))
4384
4385 (defun org-check-running-clock ()
4386 "Check if the current buffer contains the running clock.
4387 If yes, offer to stop it and to save the buffer with the changes."
4388 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4389 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4390 (buffer-name))))
4391 (org-clock-out)
4392 (when (y-or-n-p "Save changed buffer?")
4393 (save-buffer))))
4394
4395 (defun org-clocktable-try-shift (dir n)
4396 "Check if this line starts a clock table, if yes, shift the time block."
4397 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4398 (org-clocktable-shift dir n)))
4399
4400 ;;;###autoload
4401 (defun org-clock-persistence-insinuate ()
4402 "Set up hooks for clock persistence."
4403 (require 'org-clock)
4404 (add-hook 'org-mode-hook 'org-clock-load)
4405 (add-hook 'kill-emacs-hook 'org-clock-save))
4406
4407 (defgroup org-archive nil
4408 "Options concerning archiving in Org-mode."
4409 :tag "Org Archive"
4410 :group 'org-structure)
4411
4412 (defcustom org-archive-location "%s_archive::"
4413 "The location where subtrees should be archived.
4414
4415 The value of this variable is a string, consisting of two parts,
4416 separated by a double-colon. The first part is a filename and
4417 the second part is a headline.
4418
4419 When the filename is omitted, archiving happens in the same file.
4420 %s in the filename will be replaced by the current file
4421 name (without the directory part). Archiving to a different file
4422 is useful to keep archived entries from contributing to the
4423 Org-mode Agenda.
4424
4425 The archived entries will be filed as subtrees of the specified
4426 headline. When the headline is omitted, the subtrees are simply
4427 filed away at the end of the file, as top-level entries. Also in
4428 the heading you can use %s to represent the file name, this can be
4429 useful when using the same archive for a number of different files.
4430
4431 Here are a few examples:
4432 \"%s_archive::\"
4433 If the current file is Projects.org, archive in file
4434 Projects.org_archive, as top-level trees. This is the default.
4435
4436 \"::* Archived Tasks\"
4437 Archive in the current file, under the top-level headline
4438 \"* Archived Tasks\".
4439
4440 \"~/org/archive.org::\"
4441 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4442
4443 \"~/org/archive.org::* From %s\"
4444 Archive in file ~/org/archive.org (absolute path), under headlines
4445 \"From FILENAME\" where file name is the current file name.
4446
4447 \"~/org/datetree.org::datetree/* Finished Tasks\"
4448 The \"datetree/\" string is special, signifying to archive
4449 items to the datetree. Items are placed in either the CLOSED
4450 date of the item, or the current date if there is no CLOSED date.
4451 The heading will be a subentry to the current date. There doesn't
4452 need to be a heading, but there always needs to be a slash after
4453 datetree. For example, to store archived items directly in the
4454 datetree, use \"~/org/datetree.org::datetree/\".
4455
4456 \"basement::** Finished Tasks\"
4457 Archive in file ./basement (relative path), as level 3 trees
4458 below the level 2 heading \"** Finished Tasks\".
4459
4460 You may set this option on a per-file basis by adding to the buffer a
4461 line like
4462
4463 #+ARCHIVE: basement::** Finished Tasks
4464
4465 You may also define it locally for a subtree by setting an ARCHIVE property
4466 in the entry. If such a property is found in an entry, or anywhere up
4467 the hierarchy, it will be used."
4468 :group 'org-archive
4469 :type 'string)
4470
4471 (defcustom org-archive-tag "ARCHIVE"
4472 "The tag that marks a subtree as archived.
4473 An archived subtree does not open during visibility cycling, and does
4474 not contribute to the agenda listings.
4475 After changing this, font-lock must be restarted in the relevant buffers to
4476 get the proper fontification."
4477 :group 'org-archive
4478 :group 'org-keywords
4479 :type 'string)
4480
4481 (defcustom org-agenda-skip-archived-trees t
4482 "Non-nil means the agenda will skip any items located in archived trees.
4483 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4484 variable is no longer recommended, you should leave it at the value t.
4485 Instead, use the key `v' to cycle the archives-mode in the agenda."
4486 :group 'org-archive
4487 :group 'org-agenda-skip
4488 :type 'boolean)
4489
4490 (defcustom org-columns-skip-archived-trees t
4491 "Non-nil means ignore archived trees when creating column view."
4492 :group 'org-archive
4493 :group 'org-properties
4494 :type 'boolean)
4495
4496 (defcustom org-cycle-open-archived-trees nil
4497 "Non-nil means `org-cycle' will open archived trees.
4498 An archived tree is a tree marked with the tag ARCHIVE.
4499 When nil, archived trees will stay folded. You can still open them with
4500 normal outline commands like `show-all', but not with the cycling commands."
4501 :group 'org-archive
4502 :group 'org-cycle
4503 :type 'boolean)
4504
4505 (defcustom org-sparse-tree-open-archived-trees nil
4506 "Non-nil means sparse tree construction shows matches in archived trees.
4507 When nil, matches in these trees are highlighted, but the trees are kept in
4508 collapsed state."
4509 :group 'org-archive
4510 :group 'org-sparse-trees
4511 :type 'boolean)
4512
4513 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4514 "The default date type when building a sparse tree.
4515 When this is nil, a date is a scheduled or a deadline timestamp.
4516 Otherwise, these types are allowed:
4517
4518 all: all timestamps
4519 active: only active timestamps (<...>)
4520 inactive: only inactive timestamps (<...)
4521 scheduled: only scheduled timestamps
4522 deadline: only deadline timestamps"
4523 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4524 (const :tag "All timestamps" all)
4525 (const :tag "Only active timestamps" active)
4526 (const :tag "Only inactive timestamps" inactive)
4527 (const :tag "Only scheduled timestamps" scheduled)
4528 (const :tag "Only deadline timestamps" deadline)
4529 (const :tag "Only closed timestamps" closed))
4530 :version "24.3"
4531 :group 'org-sparse-trees)
4532
4533 (defun org-cycle-hide-archived-subtrees (state)
4534 "Re-hide all archived subtrees after a visibility state change."
4535 (when (and (not org-cycle-open-archived-trees)
4536 (not (memq state '(overview folded))))
4537 (save-excursion
4538 (let* ((globalp (memq state '(contents all)))
4539 (beg (if globalp (point-min) (point)))
4540 (end (if globalp (point-max) (org-end-of-subtree t))))
4541 (org-hide-archived-subtrees beg end)
4542 (goto-char beg)
4543 (if (looking-at (concat ".*:" org-archive-tag ":"))
4544 (message "%s" (substitute-command-keys
4545 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4546
4547 (defun org-force-cycle-archived ()
4548 "Cycle subtree even if it is archived."
4549 (interactive)
4550 (setq this-command 'org-cycle)
4551 (let ((org-cycle-open-archived-trees t))
4552 (call-interactively 'org-cycle)))
4553
4554 (defun org-hide-archived-subtrees (beg end)
4555 "Re-hide all archived subtrees after a visibility state change."
4556 (save-excursion
4557 (let* ((re (concat ":" org-archive-tag ":")))
4558 (goto-char beg)
4559 (while (re-search-forward re end t)
4560 (when (org-at-heading-p)
4561 (org-flag-subtree t)
4562 (org-end-of-subtree t))))))
4563
4564 (declare-function outline-end-of-heading "outline" ())
4565 (declare-function outline-flag-region "outline" (from to flag))
4566 (defun org-flag-subtree (flag)
4567 (save-excursion
4568 (org-back-to-heading t)
4569 (outline-end-of-heading)
4570 (outline-flag-region (point)
4571 (progn (org-end-of-subtree t) (point))
4572 flag)))
4573
4574 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4575
4576 ;; Declare Column View Code
4577
4578 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4579 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4580 (declare-function org-columns-compute "org-colview" (property))
4581
4582 ;; Declare ID code
4583
4584 (declare-function org-id-store-link "org-id")
4585 (declare-function org-id-locations-load "org-id")
4586 (declare-function org-id-locations-save "org-id")
4587 (defvar org-id-track-globally)
4588
4589 ;;; Variables for pre-computed regular expressions, all buffer local
4590
4591 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4592 "Matches first line of a hidden block.")
4593 (make-variable-buffer-local 'org-drawer-regexp)
4594 (defvar org-todo-regexp nil
4595 "Matches any of the TODO state keywords.")
4596 (make-variable-buffer-local 'org-todo-regexp)
4597 (defvar org-not-done-regexp nil
4598 "Matches any of the TODO state keywords except the last one.")
4599 (make-variable-buffer-local 'org-not-done-regexp)
4600 (defvar org-not-done-heading-regexp nil
4601 "Matches a TODO headline that is not done.")
4602 (make-variable-buffer-local 'org-not-done-regexp)
4603 (defvar org-todo-line-regexp nil
4604 "Matches a headline and puts TODO state into group 2 if present.")
4605 (make-variable-buffer-local 'org-todo-line-regexp)
4606 (defvar org-complex-heading-regexp nil
4607 "Matches a headline and puts everything into groups:
4608 group 1: the stars
4609 group 2: The todo keyword, maybe
4610 group 3: Priority cookie
4611 group 4: True headline
4612 group 5: Tags")
4613 (make-variable-buffer-local 'org-complex-heading-regexp)
4614 (defvar org-complex-heading-regexp-format nil
4615 "Printf format to make regexp to match an exact headline.
4616 This regexp will match the headline of any node which has the
4617 exact headline text that is put into the format, but may have any
4618 TODO state, priority and tags.")
4619 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4620 (defvar org-todo-line-tags-regexp nil
4621 "Matches a headline and puts TODO state into group 2 if present.
4622 Also put tags into group 4 if tags are present.")
4623 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4624 (defvar org-ds-keyword-length 12
4625 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4626 (make-variable-buffer-local 'org-ds-keyword-length)
4627 (defvar org-deadline-regexp nil
4628 "Matches the DEADLINE keyword.")
4629 (make-variable-buffer-local 'org-deadline-regexp)
4630 (defvar org-deadline-time-regexp nil
4631 "Matches the DEADLINE keyword together with a time stamp.")
4632 (make-variable-buffer-local 'org-deadline-time-regexp)
4633 (defvar org-deadline-time-hour-regexp nil
4634 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4635 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4636 (defvar org-deadline-line-regexp nil
4637 "Matches the DEADLINE keyword and the rest of the line.")
4638 (make-variable-buffer-local 'org-deadline-line-regexp)
4639 (defvar org-scheduled-regexp nil
4640 "Matches the SCHEDULED keyword.")
4641 (make-variable-buffer-local 'org-scheduled-regexp)
4642 (defvar org-scheduled-time-regexp nil
4643 "Matches the SCHEDULED keyword together with a time stamp.")
4644 (make-variable-buffer-local 'org-scheduled-time-regexp)
4645 (defvar org-scheduled-time-hour-regexp nil
4646 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4647 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4648 (defvar org-closed-time-regexp nil
4649 "Matches the CLOSED keyword together with a time stamp.")
4650 (make-variable-buffer-local 'org-closed-time-regexp)
4651
4652 (defvar org-keyword-time-regexp nil
4653 "Matches any of the 4 keywords, together with the time stamp.")
4654 (make-variable-buffer-local 'org-keyword-time-regexp)
4655 (defvar org-keyword-time-not-clock-regexp nil
4656 "Matches any of the 3 keywords, together with the time stamp.")
4657 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4658 (defvar org-maybe-keyword-time-regexp nil
4659 "Matches a timestamp, possibly preceded by a keyword.")
4660 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4661 (defvar org-all-time-keywords nil
4662 "List of time keywords.")
4663 (make-variable-buffer-local 'org-all-time-keywords)
4664
4665 (defconst org-plain-time-of-day-regexp
4666 (concat
4667 "\\(\\<[012]?[0-9]"
4668 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4669 "\\(--?"
4670 "\\(\\<[012]?[0-9]"
4671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4672 "\\)?")
4673 "Regular expression to match a plain time or time range.
4674 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4675 groups carry important information:
4676 0 the full match
4677 1 the first time, range or not
4678 8 the second time, if it is a range.")
4679
4680 (defconst org-plain-time-extension-regexp
4681 (concat
4682 "\\(\\<[012]?[0-9]"
4683 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4684 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4685 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4686 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4687 groups carry important information:
4688 0 the full match
4689 7 hours of duration
4690 9 minutes of duration")
4691
4692 (defconst org-stamp-time-of-day-regexp
4693 (concat
4694 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4695 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4696 "\\(--?"
4697 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4698 "Regular expression to match a timestamp time or time range.
4699 After a match, the following groups carry important information:
4700 0 the full match
4701 1 date plus weekday, for back referencing to make sure both times are on the same day
4702 2 the first time, range or not
4703 4 the second time, if it is a range.")
4704
4705 (defconst org-startup-options
4706 '(("fold" org-startup-folded t)
4707 ("overview" org-startup-folded t)
4708 ("nofold" org-startup-folded nil)
4709 ("showall" org-startup-folded nil)
4710 ("showeverything" org-startup-folded showeverything)
4711 ("content" org-startup-folded content)
4712 ("indent" org-startup-indented t)
4713 ("noindent" org-startup-indented nil)
4714 ("hidestars" org-hide-leading-stars t)
4715 ("showstars" org-hide-leading-stars nil)
4716 ("odd" org-odd-levels-only t)
4717 ("oddeven" org-odd-levels-only nil)
4718 ("align" org-startup-align-all-tables t)
4719 ("noalign" org-startup-align-all-tables nil)
4720 ("inlineimages" org-startup-with-inline-images t)
4721 ("noinlineimages" org-startup-with-inline-images nil)
4722 ("latexpreview" org-startup-with-latex-preview t)
4723 ("nolatexpreview" org-startup-with-latex-preview nil)
4724 ("customtime" org-display-custom-times t)
4725 ("logdone" org-log-done time)
4726 ("lognotedone" org-log-done note)
4727 ("nologdone" org-log-done nil)
4728 ("lognoteclock-out" org-log-note-clock-out t)
4729 ("nolognoteclock-out" org-log-note-clock-out nil)
4730 ("logrepeat" org-log-repeat state)
4731 ("lognoterepeat" org-log-repeat note)
4732 ("logdrawer" org-log-into-drawer t)
4733 ("nologdrawer" org-log-into-drawer nil)
4734 ("logstatesreversed" org-log-states-order-reversed t)
4735 ("nologstatesreversed" org-log-states-order-reversed nil)
4736 ("nologrepeat" org-log-repeat nil)
4737 ("logreschedule" org-log-reschedule time)
4738 ("lognotereschedule" org-log-reschedule note)
4739 ("nologreschedule" org-log-reschedule nil)
4740 ("logredeadline" org-log-redeadline time)
4741 ("lognoteredeadline" org-log-redeadline note)
4742 ("nologredeadline" org-log-redeadline nil)
4743 ("logrefile" org-log-refile time)
4744 ("lognoterefile" org-log-refile note)
4745 ("nologrefile" org-log-refile nil)
4746 ("fninline" org-footnote-define-inline t)
4747 ("nofninline" org-footnote-define-inline nil)
4748 ("fnlocal" org-footnote-section nil)
4749 ("fnauto" org-footnote-auto-label t)
4750 ("fnprompt" org-footnote-auto-label nil)
4751 ("fnconfirm" org-footnote-auto-label confirm)
4752 ("fnplain" org-footnote-auto-label plain)
4753 ("fnadjust" org-footnote-auto-adjust t)
4754 ("nofnadjust" org-footnote-auto-adjust nil)
4755 ("constcgs" constants-unit-system cgs)
4756 ("constSI" constants-unit-system SI)
4757 ("noptag" org-tag-persistent-alist nil)
4758 ("hideblocks" org-hide-block-startup t)
4759 ("nohideblocks" org-hide-block-startup nil)
4760 ("beamer" org-startup-with-beamer-mode t)
4761 ("entitiespretty" org-pretty-entities t)
4762 ("entitiesplain" org-pretty-entities nil))
4763 "Variable associated with STARTUP options for org-mode.
4764 Each element is a list of three items: the startup options (as written
4765 in the #+STARTUP line), the corresponding variable, and the value to set
4766 this variable to if the option is found. An optional forth element PUSH
4767 means to push this value onto the list in the variable.")
4768
4769 (defun org-update-property-plist (key val props)
4770 "Update PROPS with KEY and VAL."
4771 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4772 (key (if appending (substring key 0 (- (length key) 1)) key))
4773 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4774 (previous (cdr (assoc key props))))
4775 (if appending
4776 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4777 (cons (cons key val) remainder))))
4778
4779 (defconst org-block-regexp
4780 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4781 "Regular expression for hiding blocks.")
4782 (defconst org-heading-keyword-regexp-format
4783 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4784 "Printf format for a regexp matching a headline with some keyword.
4785 This regexp will match the headline of any node which has the
4786 exact keyword that is put into the format. The keyword isn't in
4787 any group by default, but the stars and the body are.")
4788 (defconst org-heading-keyword-maybe-regexp-format
4789 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4790 "Printf format for a regexp matching a headline, possibly with some keyword.
4791 This regexp can match any headline with the specified keyword, or
4792 without a keyword. The keyword isn't in any group by default,
4793 but the stars and the body are.")
4794
4795 (defcustom org-group-tags t
4796 "When non-nil (the default), use group tags.
4797 This can be turned on/off through `org-toggle-tags-groups'."
4798 :group 'org-tags
4799 :group 'org-startup
4800 :type 'boolean)
4801
4802 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4803
4804 (defun org-toggle-tags-groups ()
4805 "Toggle support for group tags.
4806 Support for group tags is controlled by the option
4807 `org-group-tags', which is non-nil by default."
4808 (interactive)
4809 (setq org-group-tags (not org-group-tags))
4810 (cond ((and (derived-mode-p 'org-agenda-mode)
4811 org-group-tags)
4812 (org-agenda-redo))
4813 ((derived-mode-p 'org-mode)
4814 (let ((org-inhibit-startup t)) (org-mode))))
4815 (message "Groups tags support has been turned %s"
4816 (if org-group-tags "on" "off")))
4817
4818 (defun org-set-regexps-and-options-for-tags ()
4819 "Precompute variables used for tags."
4820 (when (derived-mode-p 'org-mode)
4821 (org-set-local 'org-file-tags nil)
4822 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4823 (splitre "[ \t]+")
4824 (start 0)
4825 tags ftags key value)
4826 (save-excursion
4827 (save-restriction
4828 (widen)
4829 (goto-char (point-min))
4830 (while (re-search-forward re nil t)
4831 (setq key (upcase (org-match-string-no-properties 1))
4832 value (org-match-string-no-properties 2))
4833 (if (stringp value) (setq value (org-trim value)))
4834 (cond
4835 ((equal key "TAGS")
4836 (setq tags (append tags (if tags '("\\n") nil)
4837 (org-split-string value splitre))))
4838 ((equal key "FILETAGS")
4839 (when (string-match "\\S-" value)
4840 (setq ftags
4841 (append
4842 ftags
4843 (apply 'append
4844 (mapcar (lambda (x) (org-split-string x ":"))
4845 (org-split-string value)))))))))))
4846 ;; Process the file tags.
4847 (and ftags (org-set-local 'org-file-tags
4848 (mapcar 'org-add-prop-inherited ftags)))
4849 (org-set-local 'org-tag-groups-alist nil)
4850 ;; Process the tags.
4851 (when (and (not tags) org-tag-alist)
4852 (setq tags
4853 (mapcar
4854 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4855 ((eq (car tg) :endgroup) "}")
4856 ((eq (car tg) :grouptags) ":")
4857 ((eq (car tg) :newline) "\n")
4858 (t (concat (car tg)
4859 (if (characterp (cdr tg))
4860 (format "(%s)" (char-to-string (cdr tg))) "")))))
4861 org-tag-alist)))
4862 (let (e tgs g)
4863 (while (setq e (pop tags))
4864 (cond
4865 ((equal e "{")
4866 (progn (push '(:startgroup) tgs)
4867 (when (equal (nth 1 tags) ":")
4868 (push (list (replace-regexp-in-string
4869 "(.+)$" "" (nth 0 tags)))
4870 org-tag-groups-alist)
4871 (setq g 0))))
4872 ((equal e ":") (push '(:grouptags) tgs))
4873 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4874 ((equal e "\\n") (push '(:newline) tgs))
4875 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4876 (push (cons (match-string 1 e)
4877 (string-to-char (match-string 2 e))) tgs)
4878 (if (and g (> g 0))
4879 (setcar org-tag-groups-alist
4880 (append (car org-tag-groups-alist)
4881 (list (match-string 1 e)))))
4882 (if g (setq g (1+ g))))
4883 (t (push (list e) tgs)
4884 (if (and g (> g 0))
4885 (setcar org-tag-groups-alist
4886 (append (car org-tag-groups-alist) (list e))))
4887 (if g (setq g (1+ g))))))
4888 (org-set-local 'org-tag-alist nil)
4889 (while (setq e (pop tgs))
4890 (or (and (stringp (car e))
4891 (assoc (car e) org-tag-alist))
4892 (push e org-tag-alist)))
4893 ;; Return a list with tag variables
4894 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4895
4896 (defvar org-ota nil)
4897 (defun org-set-regexps-and-options ()
4898 "Precompute regular expressions used in the current buffer."
4899 (when (derived-mode-p 'org-mode)
4900 (org-set-local 'org-todo-kwd-alist nil)
4901 (org-set-local 'org-todo-key-alist nil)
4902 (org-set-local 'org-todo-key-trigger nil)
4903 (org-set-local 'org-todo-keywords-1 nil)
4904 (org-set-local 'org-done-keywords nil)
4905 (org-set-local 'org-todo-heads nil)
4906 (org-set-local 'org-todo-sets nil)
4907 (org-set-local 'org-todo-log-states nil)
4908 (org-set-local 'org-file-properties nil)
4909 (let ((re (org-make-options-regexp
4910 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4911 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4912 "SETUPFILE" "OPTIONS")
4913 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4914 (splitre "[ \t]+")
4915 (scripts org-use-sub-superscripts)
4916 kwds kws0 kwsa key log value cat arch const links hw dws
4917 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4918 (start 0))
4919 (save-excursion
4920 (save-restriction
4921 (widen)
4922 (goto-char (point-min))
4923 (while
4924 (or (and
4925 ext-setup-or-nil
4926 (not org-ota)
4927 (let (ret)
4928 (with-temp-buffer
4929 (insert ext-setup-or-nil)
4930 (let ((major-mode 'org-mode) org-ota)
4931 (setq ret (save-match-data
4932 (org-set-regexps-and-options-for-tags)))))
4933 ;; Append setupfile tags to existing tags
4934 (setq org-ota t)
4935 (setq org-file-tags
4936 (delq nil (append org-file-tags (nth 0 ret)))
4937 org-tag-alist
4938 (delq nil (append org-tag-alist (nth 1 ret)))
4939 org-tag-groups-alist
4940 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4941 (and ext-setup-or-nil
4942 (string-match re ext-setup-or-nil start)
4943 (setq start (match-end 0)))
4944 (and (setq ext-setup-or-nil nil start 0)
4945 (re-search-forward re nil t)))
4946 (setq key (upcase (match-string 1 ext-setup-or-nil))
4947 value (org-match-string-no-properties 2 ext-setup-or-nil))
4948 (if (stringp value) (setq value (org-trim value)))
4949 (cond
4950 ((equal key "CATEGORY")
4951 (setq cat value))
4952 ((member key '("SEQ_TODO" "TODO"))
4953 (push (cons 'sequence (org-split-string value splitre)) kwds))
4954 ((equal key "TYP_TODO")
4955 (push (cons 'type (org-split-string value splitre)) kwds))
4956 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4957 ;; general TODO-like setup
4958 (push (cons (intern (downcase (match-string 1 key)))
4959 (org-split-string value splitre)) kwds))
4960 ((equal key "COLUMNS")
4961 (org-set-local 'org-columns-default-format value))
4962 ((equal key "LINK")
4963 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4964 (push (cons (match-string 1 value)
4965 (org-trim (match-string 2 value)))
4966 links)))
4967 ((equal key "PRIORITIES")
4968 (setq prio (org-split-string value " +")))
4969 ((equal key "PROPERTY")
4970 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4971 (setq props (org-update-property-plist (match-string 1 value)
4972 (match-string 2 value)
4973 props))))
4974 ((equal key "DRAWERS")
4975 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4976 ((equal key "CONSTANTS")
4977 (org-table-set-constants))
4978 ((equal key "STARTUP")
4979 (let ((opts (org-split-string value splitre))
4980 l var val)
4981 (while (setq l (pop opts))
4982 (when (setq l (assoc l org-startup-options))
4983 (setq var (nth 1 l) val (nth 2 l))
4984 (if (not (nth 3 l))
4985 (set (make-local-variable var) val)
4986 (if (not (listp (symbol-value var)))
4987 (set (make-local-variable var) nil))
4988 (set (make-local-variable var) (symbol-value var))
4989 (add-to-list var val))))))
4990 ((equal key "ARCHIVE")
4991 (setq arch value)
4992 (remove-text-properties 0 (length arch)
4993 '(face t fontified t) arch))
4994 ((equal key "OPTIONS")
4995 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4996 (setq scripts (read (match-string 2 value)))))
4997 ((and (equal key "SETUPFILE")
4998 ;; Prevent checking in Gnus messages
4999 (not buffer-read-only))
5000 (setq setup-contents (org-file-contents
5001 (expand-file-name
5002 (org-remove-double-quotes value))
5003 'noerror))
5004 (if (not ext-setup-or-nil)
5005 (setq ext-setup-or-nil setup-contents start 0)
5006 (setq ext-setup-or-nil
5007 (concat (substring ext-setup-or-nil 0 start)
5008 "\n" setup-contents "\n"
5009 (substring ext-setup-or-nil start)))))))
5010 ;; search for property blocks
5011 (goto-char (point-min))
5012 (while (re-search-forward org-block-regexp nil t)
5013 (when (equal "PROPERTY" (upcase (match-string 1)))
5014 (setq value (replace-regexp-in-string
5015 "[\n\r]" " " (match-string 4)))
5016 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5017 (setq props (org-update-property-plist (match-string 1 value)
5018 (match-string 2 value)
5019 props)))))))
5020 (org-set-local 'org-use-sub-superscripts scripts)
5021 (when cat
5022 (org-set-local 'org-category (intern cat))
5023 (push (cons "CATEGORY" cat) props))
5024 (when prio
5025 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5026 (setq prio (mapcar 'string-to-char prio))
5027 (org-set-local 'org-highest-priority (nth 0 prio))
5028 (org-set-local 'org-lowest-priority (nth 1 prio))
5029 (org-set-local 'org-default-priority (nth 2 prio)))
5030 (and props (org-set-local 'org-file-properties (nreverse props)))
5031 (and drawers (org-set-local 'org-drawers drawers))
5032 (and arch (org-set-local 'org-archive-location arch))
5033 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5034 ;; Process the TODO keywords
5035 (unless kwds
5036 ;; Use the global values as if they had been given locally.
5037 (setq kwds (default-value 'org-todo-keywords))
5038 (if (stringp (car kwds))
5039 (setq kwds (list (cons org-todo-interpretation
5040 (default-value 'org-todo-keywords)))))
5041 (setq kwds (reverse kwds)))
5042 (setq kwds (nreverse kwds))
5043 (let (inter kws kw)
5044 (while (setq kws (pop kwds))
5045 (let ((kws (or
5046 (run-hook-with-args-until-success
5047 'org-todo-setup-filter-hook kws)
5048 kws)))
5049 (setq inter (pop kws) sep (member "|" kws)
5050 kws0 (delete "|" (copy-sequence kws))
5051 kwsa nil
5052 kws1 (mapcar
5053 (lambda (x)
5054 ;; 1 2
5055 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5056 (progn
5057 (setq kw (match-string 1 x)
5058 key (and (match-end 2) (match-string 2 x))
5059 log (org-extract-log-state-settings x))
5060 (push (cons kw (and key (string-to-char key))) kwsa)
5061 (and log (push log org-todo-log-states))
5062 kw)
5063 (error "Invalid TODO keyword %s" x)))
5064 kws0)
5065 kwsa (if kwsa (append '((:startgroup))
5066 (nreverse kwsa)
5067 '((:endgroup))))
5068 hw (car kws1)
5069 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5070 tail (list inter hw (car dws) (org-last dws))))
5071 (add-to-list 'org-todo-heads hw 'append)
5072 (push kws1 org-todo-sets)
5073 (setq org-done-keywords (append org-done-keywords dws nil))
5074 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5075 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5076 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5077 (setq org-todo-sets (nreverse org-todo-sets)
5078 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5079 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5080 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5081 ;; Compute the regular expressions and other local variables.
5082 ;; Using `org-outline-regexp-bol' would complicate them much,
5083 ;; because of the fixed white space at the end of that string.
5084 (if (not org-done-keywords)
5085 (setq org-done-keywords (and org-todo-keywords-1
5086 (list (org-last org-todo-keywords-1)))))
5087 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5088 (length org-scheduled-string)
5089 (length org-clock-string)
5090 (length org-closed-string)))
5091 org-drawer-regexp
5092 (concat "^[ \t]*:\\("
5093 (mapconcat 'regexp-quote org-drawers "\\|")
5094 "\\):[ \t]*$")
5095 org-not-done-keywords
5096 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5097 org-todo-regexp
5098 (concat "\\("
5099 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5100 "\\)")
5101 org-not-done-regexp
5102 (concat "\\("
5103 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5104 "\\)")
5105 org-not-done-heading-regexp
5106 (format org-heading-keyword-regexp-format org-not-done-regexp)
5107 org-todo-line-regexp
5108 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5109 org-complex-heading-regexp
5110 (concat "^\\(\\*+\\)"
5111 "\\(?: +" org-todo-regexp "\\)?"
5112 "\\(?: +\\(\\[#.\\]\\)\\)?"
5113 "\\(?: +\\(.*?\\)\\)??"
5114 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5115 "[ \t]*$")
5116 org-complex-heading-regexp-format
5117 (concat "^\\(\\*+\\)"
5118 "\\(?: +" org-todo-regexp "\\)?"
5119 "\\(?: +\\(\\[#.\\]\\)\\)?"
5120 "\\(?: +"
5121 ;; Stats cookies can be stuck to body.
5122 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5123 "\\(%s\\)"
5124 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5125 "\\)"
5126 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5127 "[ \t]*$")
5128 org-todo-line-tags-regexp
5129 (concat "^\\(\\*+\\)"
5130 "\\(?: +" org-todo-regexp "\\)?"
5131 "\\(?: +\\(.*?\\)\\)??"
5132 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5133 "[ \t]*$")
5134 org-deadline-regexp (concat "\\<" org-deadline-string)
5135 org-deadline-time-regexp
5136 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5137 org-deadline-time-hour-regexp
5138 (concat "\\<" org-deadline-string
5139 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5140 org-deadline-line-regexp
5141 (concat "\\<\\(" org-deadline-string "\\).*")
5142 org-scheduled-regexp
5143 (concat "\\<" org-scheduled-string)
5144 org-scheduled-time-regexp
5145 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5146 org-scheduled-time-hour-regexp
5147 (concat "\\<" org-scheduled-string
5148 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5149 org-closed-time-regexp
5150 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5151 org-keyword-time-regexp
5152 (concat "\\<\\(" org-scheduled-string
5153 "\\|" org-deadline-string
5154 "\\|" org-closed-string
5155 "\\|" org-clock-string "\\)"
5156 " *[[<]\\([^]>]+\\)[]>]")
5157 org-keyword-time-not-clock-regexp
5158 (concat "\\<\\(" org-scheduled-string
5159 "\\|" org-deadline-string
5160 "\\|" org-closed-string
5161 "\\)"
5162 " *[[<]\\([^]>]+\\)[]>]")
5163 org-maybe-keyword-time-regexp
5164 (concat "\\(\\<\\(" org-scheduled-string
5165 "\\|" org-deadline-string
5166 "\\|" org-closed-string
5167 "\\|" org-clock-string "\\)\\)?"
5168 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5169 org-all-time-keywords
5170 (mapcar (lambda (w) (substring w 0 -1))
5171 (list org-scheduled-string org-deadline-string
5172 org-clock-string org-closed-string)))
5173 (setq org-ota nil)
5174 (org-compute-latex-and-related-regexp))))
5175
5176 (defun org-file-contents (file &optional noerror)
5177 "Return the contents of FILE, as a string."
5178 (if (or (not file) (not (file-readable-p file)))
5179 (if (not noerror)
5180 (error "Cannot read file \"%s\"" file)
5181 (message "Cannot read file \"%s\"" file)
5182 "")
5183 (with-temp-buffer
5184 (insert-file-contents file)
5185 (buffer-string))))
5186
5187 (defun org-extract-log-state-settings (x)
5188 "Extract the log state setting from a TODO keyword string.
5189 This will extract info from a string like \"WAIT(w@/!)\"."
5190 (let (kw key log1 log2)
5191 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5192 (setq kw (match-string 1 x)
5193 key (and (match-end 2) (match-string 2 x))
5194 log1 (and (match-end 3) (match-string 3 x))
5195 log2 (and (match-end 4) (match-string 4 x)))
5196 (and (or log1 log2)
5197 (list kw
5198 (and log1 (if (equal log1 "!") 'time 'note))
5199 (and log2 (if (equal log2 "!") 'time 'note)))))))
5200
5201 (defun org-remove-keyword-keys (list)
5202 "Remove a pair of parenthesis at the end of each string in LIST."
5203 (mapcar (lambda (x)
5204 (if (string-match "(.*)$" x)
5205 (substring x 0 (match-beginning 0))
5206 x))
5207 list))
5208
5209 (defun org-assign-fast-keys (alist)
5210 "Assign fast keys to a keyword-key alist.
5211 Respect keys that are already there."
5212 (let (new e (alt ?0))
5213 (while (setq e (pop alist))
5214 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5215 (cdr e)) ;; Key already assigned.
5216 (push e new)
5217 (let ((clist (string-to-list (downcase (car e))))
5218 (used (append new alist)))
5219 (when (= (car clist) ?@)
5220 (pop clist))
5221 (while (and clist (rassoc (car clist) used))
5222 (pop clist))
5223 (unless clist
5224 (while (rassoc alt used)
5225 (incf alt)))
5226 (push (cons (car e) (or (car clist) alt)) new))))
5227 (nreverse new)))
5228
5229 ;;; Some variables used in various places
5230
5231 (defvar org-window-configuration nil
5232 "Used in various places to store a window configuration.")
5233 (defvar org-selected-window nil
5234 "Used in various places to store a window configuration.")
5235 (defvar org-finish-function nil
5236 "Function to be called when `C-c C-c' is used.
5237 This is for getting out of special buffers like capture.")
5238
5239
5240 ;; FIXME: Occasionally check by commenting these, to make sure
5241 ;; no other functions uses these, forgetting to let-bind them.
5242 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5243 (defvar org-last-state)
5244 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5245
5246 ;; Defined somewhere in this file, but used before definition.
5247 (defvar org-entities) ;; defined in org-entities.el
5248 (defvar org-struct-menu)
5249 (defvar org-org-menu)
5250 (defvar org-tbl-menu)
5251
5252 ;;;; Define the Org-mode
5253
5254 ;; We use a before-change function to check if a table might need
5255 ;; an update.
5256 (defvar org-table-may-need-update t
5257 "Indicates that a table might need an update.
5258 This variable is set by `org-before-change-function'.
5259 `org-table-align' sets it back to nil.")
5260 (defun org-before-change-function (beg end)
5261 "Every change indicates that a table might need an update."
5262 (setq org-table-may-need-update t))
5263 (defvar org-mode-map)
5264 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5265 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5266 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5267 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5268 (defvar org-table-buffer-is-an nil)
5269
5270 (defvar bidi-paragraph-direction)
5271 (defvar buffer-face-mode-face)
5272
5273 (require 'outline)
5274 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5275 (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"))
5276 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5277
5278 ;; Other stuff we need.
5279 (require 'time-date)
5280 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5281 (require 'easymenu)
5282 (require 'overlay)
5283
5284 ;; (require 'org-macs) moved higher up in the file before it is first used
5285 (require 'org-entities)
5286 ;; (require 'org-compat) moved higher up in the file before it is first used
5287 (require 'org-faces)
5288 (require 'org-list)
5289 (require 'org-pcomplete)
5290 (require 'org-src)
5291 (require 'org-footnote)
5292 (require 'org-macro)
5293
5294 ;; babel
5295 (require 'ob)
5296
5297 ;;;###autoload
5298 (define-derived-mode org-mode outline-mode "Org"
5299 "Outline-based notes management and organizer, alias
5300 \"Carsten's outline-mode for keeping track of everything.\"
5301
5302 Org-mode develops organizational tasks around a NOTES file which
5303 contains information about projects as plain text. Org-mode is
5304 implemented on top of outline-mode, which is ideal to keep the content
5305 of large files well structured. It supports ToDo items, deadlines and
5306 time stamps, which magically appear in the diary listing of the Emacs
5307 calendar. Tables are easily created with a built-in table editor.
5308 Plain text URL-like links connect to websites, emails (VM), Usenet
5309 messages (Gnus), BBDB entries, and any files related to the project.
5310 For printing and sharing of notes, an Org-mode file (or a part of it)
5311 can be exported as a structured ASCII or HTML file.
5312
5313 The following commands are available:
5314
5315 \\{org-mode-map}"
5316
5317 ;; Get rid of Outline menus, they are not needed
5318 ;; Need to do this here because define-derived-mode sets up
5319 ;; the keymap so late. Still, it is a waste to call this each time
5320 ;; we switch another buffer into org-mode.
5321 (if (featurep 'xemacs)
5322 (when (boundp 'outline-mode-menu-heading)
5323 ;; Assume this is Greg's port, it uses easymenu
5324 (easy-menu-remove outline-mode-menu-heading)
5325 (easy-menu-remove outline-mode-menu-show)
5326 (easy-menu-remove outline-mode-menu-hide))
5327 (define-key org-mode-map [menu-bar headings] 'undefined)
5328 (define-key org-mode-map [menu-bar hide] 'undefined)
5329 (define-key org-mode-map [menu-bar show] 'undefined))
5330
5331 (org-load-modules-maybe)
5332 (easy-menu-add org-org-menu)
5333 (easy-menu-add org-tbl-menu)
5334 (org-install-agenda-files-menu)
5335 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5336 (add-to-invisibility-spec '(org-cwidth))
5337 (add-to-invisibility-spec '(org-hide-block . t))
5338 (when (featurep 'xemacs)
5339 (org-set-local 'line-move-ignore-invisible t))
5340 (org-set-local 'outline-regexp org-outline-regexp)
5341 (org-set-local 'outline-level 'org-outline-level)
5342 (setq bidi-paragraph-direction 'left-to-right)
5343 (when (and org-ellipsis
5344 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5345 (fboundp 'make-glyph-code))
5346 (unless org-display-table
5347 (setq org-display-table (make-display-table)))
5348 (set-display-table-slot
5349 org-display-table 4
5350 (vconcat (mapcar
5351 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5352 org-ellipsis)))
5353 (if (stringp org-ellipsis) org-ellipsis "..."))))
5354 (setq buffer-display-table org-display-table))
5355 (org-set-regexps-and-options-for-tags)
5356 (org-set-regexps-and-options)
5357 (org-set-font-lock-defaults)
5358 (when (and org-tag-faces (not org-tags-special-faces-re))
5359 ;; tag faces set outside customize.... force initialization.
5360 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5361 ;; Calc embedded
5362 (org-set-local 'calc-embedded-open-mode "# ")
5363 ;; Modify a few syntax entries
5364 (modify-syntax-entry ?@ "w")
5365 (modify-syntax-entry ?\" "\"")
5366 (modify-syntax-entry ?\\ "_")
5367 (modify-syntax-entry ?~ "_")
5368 (if org-startup-truncated (setq truncate-lines t))
5369 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5370 (org-set-local 'font-lock-unfontify-region-function
5371 'org-unfontify-region)
5372 ;; Activate before-change-function
5373 (org-set-local 'org-table-may-need-update t)
5374 (org-add-hook 'before-change-functions 'org-before-change-function nil
5375 'local)
5376 ;; Check for running clock before killing a buffer
5377 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5378 ;; Initialize macros templates.
5379 (org-macro-initialize-templates)
5380 ;; Initialize radio targets.
5381 (org-update-radio-target-regexp)
5382 ;; Indentation.
5383 (org-set-local 'indent-line-function 'org-indent-line)
5384 (org-set-local 'indent-region-function 'org-indent-region)
5385 ;; Filling and auto-filling.
5386 (org-setup-filling)
5387 ;; Comments.
5388 (org-setup-comments-handling)
5389 ;; Beginning/end of defun
5390 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5391 (org-set-local 'end-of-defun-function
5392 (lambda ()
5393 (if (not (org-at-heading-p))
5394 (org-forward-element)
5395 (org-forward-element)
5396 (forward-char -1))))
5397 ;; Next error for sparse trees
5398 (org-set-local 'next-error-function 'org-occur-next-match)
5399 ;; Make sure dependence stuff works reliably, even for users who set it
5400 ;; too late :-(
5401 (if org-enforce-todo-dependencies
5402 (add-hook 'org-blocker-hook
5403 'org-block-todo-from-children-or-siblings-or-parent)
5404 (remove-hook 'org-blocker-hook
5405 'org-block-todo-from-children-or-siblings-or-parent))
5406 (if org-enforce-todo-checkbox-dependencies
5407 (add-hook 'org-blocker-hook
5408 'org-block-todo-from-checkboxes)
5409 (remove-hook 'org-blocker-hook
5410 'org-block-todo-from-checkboxes))
5411
5412 ;; Align options lines
5413 (org-set-local
5414 'align-mode-rules-list
5415 '((org-in-buffer-settings
5416 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5417 (modes . '(org-mode)))))
5418
5419 ;; Imenu
5420 (org-set-local 'imenu-create-index-function
5421 'org-imenu-get-tree)
5422
5423 ;; Make isearch reveal context
5424 (if (or (featurep 'xemacs)
5425 (not (boundp 'outline-isearch-open-invisible-function)))
5426 ;; Emacs 21 and XEmacs make use of the hook
5427 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5428 ;; Emacs 22 deals with this through a special variable
5429 (org-set-local 'outline-isearch-open-invisible-function
5430 (lambda (&rest ignore) (org-show-context 'isearch))))
5431
5432 ;; Setup the pcomplete hooks
5433 (set (make-local-variable 'pcomplete-command-completion-function)
5434 'org-pcomplete-initial)
5435 (set (make-local-variable 'pcomplete-command-name-function)
5436 'org-command-at-point)
5437 (set (make-local-variable 'pcomplete-default-completion-function)
5438 'ignore)
5439 (set (make-local-variable 'pcomplete-parse-arguments-function)
5440 'org-parse-arguments)
5441 (set (make-local-variable 'pcomplete-termination-string) "")
5442 (when (>= emacs-major-version 23)
5443 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5444
5445 ;; If empty file that did not turn on org-mode automatically, make it to.
5446 (if (and org-insert-mode-line-in-empty-file
5447 (org-called-interactively-p 'any)
5448 (= (point-min) (point-max)))
5449 (insert "# -*- mode: org -*-\n\n"))
5450 (unless org-inhibit-startup
5451 (org-unmodified
5452 (and org-startup-with-beamer-mode (org-beamer-mode))
5453 (when org-startup-align-all-tables
5454 (org-table-map-tables 'org-table-align 'quietly))
5455 (when org-startup-with-inline-images
5456 (org-display-inline-images))
5457 (when org-startup-with-latex-preview
5458 (org-preview-latex-fragment))
5459 (unless org-inhibit-startup-visibility-stuff
5460 (org-set-startup-visibility))))
5461 ;; Try to set org-hide correctly
5462 (let ((foreground (org-find-invisible-foreground)))
5463 (if foreground
5464 (set-face-foreground 'org-hide foreground))))
5465
5466 ;; Update `customize-package-emacs-version-alist'
5467 (add-to-list 'customize-package-emacs-version-alist
5468 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5469 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5470 ("8.2.6" . "24.4")))
5471
5472 (defvar org-mode-transpose-word-syntax-table
5473 (let ((st (make-syntax-table)))
5474 (mapc (lambda(c) (modify-syntax-entry
5475 (string-to-char (car c)) "w p" st))
5476 org-emphasis-alist)
5477 st))
5478
5479 (when (fboundp 'abbrev-table-put)
5480 (abbrev-table-put org-mode-abbrev-table
5481 :parents (list text-mode-abbrev-table)))
5482
5483 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5484
5485 (defun org-find-invisible-foreground ()
5486 (let ((candidates (remove
5487 "unspecified-bg"
5488 (nconc
5489 (list (face-background 'default)
5490 (face-background 'org-default))
5491 (mapcar
5492 (lambda (alist)
5493 (when (boundp alist)
5494 (cdr (assoc 'background-color (symbol-value alist)))))
5495 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5496 (list (face-foreground 'org-hide))))))
5497 (car (remove nil candidates))))
5498
5499 (defun org-current-time (&optional rounding-minutes past)
5500 "Current time, possibly rounded to ROUNDING-MINUTES.
5501 When ROUNDING-MINUTES is not an integer, fall back on the car of
5502 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5503 the rounding returns a past time."
5504 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5505 (car org-time-stamp-rounding-minutes)))
5506 (time (decode-time)) res)
5507 (if (< r 1)
5508 (current-time)
5509 (setq res
5510 (apply 'encode-time
5511 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5512 (nthcdr 2 time))))
5513 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5514 (seconds-to-time (- (org-float-time res) (* r 60)))
5515 res))))
5516
5517 (defun org-today ()
5518 "Return today date, considering `org-extend-today-until'."
5519 (time-to-days
5520 (time-subtract (current-time)
5521 (list 0 (* 3600 org-extend-today-until) 0))))
5522
5523 ;;;; Font-Lock stuff, including the activators
5524
5525 (defvar org-mouse-map (make-sparse-keymap))
5526 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5527 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5528 (when org-mouse-1-follows-link
5529 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5530 (when org-tab-follows-link
5531 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5532 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5533
5534 (require 'font-lock)
5535
5536 (defconst org-non-link-chars "]\t\n\r<>")
5537 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5538 "shell" "elisp" "doi" "message"))
5539 (defvar org-link-types-re nil
5540 "Matches a link that has a url-like prefix like \"http:\"")
5541 (defvar org-link-re-with-space nil
5542 "Matches a link with spaces, optional angular brackets around it.")
5543 (defvar org-link-re-with-space2 nil
5544 "Matches a link with spaces, optional angular brackets around it.")
5545 (defvar org-link-re-with-space3 nil
5546 "Matches a link with spaces, only for internal part in bracket links.")
5547 (defvar org-angle-link-re nil
5548 "Matches link with angular brackets, spaces are allowed.")
5549 (defvar org-plain-link-re nil
5550 "Matches plain link, without spaces.")
5551 (defvar org-bracket-link-regexp nil
5552 "Matches a link in double brackets.")
5553 (defvar org-bracket-link-analytic-regexp nil
5554 "Regular expression used to analyze links.
5555 Here is what the match groups contain after a match:
5556 1: http:
5557 2: http
5558 3: path
5559 4: [desc]
5560 5: desc")
5561 (defvar org-bracket-link-analytic-regexp++ nil
5562 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5563 (defvar org-any-link-re nil
5564 "Regular expression matching any link.")
5565
5566 (defconst org-match-sexp-depth 3
5567 "Number of stacked braces for sub/superscript matching.")
5568
5569 (defun org-create-multibrace-regexp (left right n)
5570 "Create a regular expression which will match a balanced sexp.
5571 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5572 as single character strings.
5573 The regexp returned will match the entire expression including the
5574 delimiters. It will also define a single group which contains the
5575 match except for the outermost delimiters. The maximum depth of
5576 stacked delimiters is N. Escaping delimiters is not possible."
5577 (let* ((nothing (concat "[^" left right "]*?"))
5578 (or "\\|")
5579 (re nothing)
5580 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5581 (while (> n 1)
5582 (setq n (1- n)
5583 re (concat re or next)
5584 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5585 (concat left "\\(" re "\\)" right)))
5586
5587 (defvar org-match-substring-regexp
5588 (concat
5589 "\\(\\S-\\)\\([_^]\\)\\("
5590 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5591 "\\|"
5592 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5593 "\\|"
5594 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5595 "The regular expression matching a sub- or superscript.")
5596
5597 (defvar org-match-substring-with-braces-regexp
5598 (concat
5599 "\\(\\S-\\)\\([_^]\\)\\("
5600 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5601 "\\)")
5602 "The regular expression matching a sub- or superscript, forcing braces.")
5603
5604 (defun org-make-link-regexps ()
5605 "Update the link regular expressions.
5606 This should be called after the variable `org-link-types' has changed."
5607 (let ((types-re (regexp-opt org-link-types t)))
5608 (setq org-link-types-re
5609 (concat "\\`" types-re ":")
5610 org-link-re-with-space
5611 (concat "<?" types-re ":"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "[^" org-non-link-chars " ]\\)>?")
5615 org-link-re-with-space2
5616 (concat "<?" types-re ":"
5617 "\\([^" org-non-link-chars " ]"
5618 "[^\t\n\r]*"
5619 "[^" org-non-link-chars " ]\\)>?")
5620 org-link-re-with-space3
5621 (concat "<?" types-re ":"
5622 "\\([^" org-non-link-chars " ]"
5623 "[^\t\n\r]*\\)")
5624 org-angle-link-re
5625 (concat "<" types-re ":"
5626 "\\([^" org-non-link-chars " ]"
5627 "[^" org-non-link-chars "]*"
5628 "\\)>")
5629 org-plain-link-re
5630 (concat
5631 "\\<" types-re ":"
5632 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5633 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5634 org-bracket-link-regexp
5635 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5636 org-bracket-link-analytic-regexp
5637 (concat
5638 "\\[\\["
5639 "\\(" types-re ":\\)?"
5640 "\\([^]]+\\)"
5641 "\\]"
5642 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5643 "\\]")
5644 org-bracket-link-analytic-regexp++
5645 (concat
5646 "\\[\\["
5647 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5648 "\\([^]]+\\)"
5649 "\\]"
5650 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5651 "\\]")
5652 org-any-link-re
5653 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5654 org-angle-link-re "\\)\\|\\("
5655 org-plain-link-re "\\)"))))
5656
5657 (org-make-link-regexps)
5658
5659 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5660 "Regular expression for fast time stamp matching.")
5661 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5662 "Regular expression for fast time stamp matching.")
5663 (defconst org-ts-regexp0
5664 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5665 "Regular expression matching time strings for analysis.
5666 This one does not require the space after the date, so it can be used
5667 on a string that terminates immediately after the date.")
5668 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5669 "Regular expression matching time strings for analysis.")
5670 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5671 "Regular expression matching time stamps, with groups.")
5672 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5673 "Regular expression matching time stamps (also [..]), with groups.")
5674 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5675 "Regular expression matching a time stamp range.")
5676 (defconst org-tr-regexp-both
5677 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5678 "Regular expression matching a time stamp range.")
5679 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5680 org-ts-regexp "\\)?")
5681 "Regular expression matching a time stamp or time stamp range.")
5682 (defconst org-tsr-regexp-both
5683 (concat org-ts-regexp-both "\\(--?-?"
5684 org-ts-regexp-both "\\)?")
5685 "Regular expression matching a time stamp or time stamp range.
5686 The time stamps may be either active or inactive.")
5687
5688 (defvar org-emph-face nil)
5689
5690 (defun org-do-emphasis-faces (limit)
5691 "Run through the buffer and add overlays to emphasized strings."
5692 (let (rtn a)
5693 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5694 (let* ((border (char-after (match-beginning 3)))
5695 (bre (regexp-quote (char-to-string border))))
5696 (if (and (not (= border (char-after (match-beginning 4))))
5697 (not (save-match-data
5698 (string-match (concat bre ".*" bre)
5699 (replace-regexp-in-string
5700 "\n" " "
5701 (substring (match-string 2) 1 -1))))))
5702 (progn
5703 (setq rtn t)
5704 (setq a (assoc (match-string 3) org-emphasis-alist))
5705 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5706 'face
5707 (nth 1 a))
5708 (and (nth 2 a)
5709 (org-remove-flyspell-overlays-in
5710 (match-beginning 0) (match-end 0)))
5711 (add-text-properties (match-beginning 2) (match-end 2)
5712 '(font-lock-multiline t org-emphasis t))
5713 (when org-hide-emphasis-markers
5714 (add-text-properties (match-end 4) (match-beginning 5)
5715 '(invisible org-link))
5716 (add-text-properties (match-beginning 3) (match-end 3)
5717 '(invisible org-link))))))
5718 (goto-char (1+ (match-beginning 0))))
5719 rtn))
5720
5721 (defun org-emphasize (&optional char)
5722 "Insert or change an emphasis, i.e. a font like bold or italic.
5723 If there is an active region, change that region to a new emphasis.
5724 If there is no region, just insert the marker characters and position
5725 the cursor between them.
5726 CHAR should be the marker character. If it is a space, it means to
5727 remove the emphasis of the selected region.
5728 If CHAR is not given (for example in an interactive call) it will be
5729 prompted for."
5730 (interactive)
5731 (let ((erc org-emphasis-regexp-components)
5732 (prompt "")
5733 (string "") beg end move c s)
5734 (if (org-region-active-p)
5735 (setq beg (region-beginning) end (region-end)
5736 string (buffer-substring beg end))
5737 (setq move t))
5738
5739 (unless char
5740 (message "Emphasis marker or tag: [%s]"
5741 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5742 (setq char (read-char-exclusive)))
5743 (if (equal char ?\ )
5744 (setq s "" move nil)
5745 (unless (assoc (char-to-string char) org-emphasis-alist)
5746 (user-error "No such emphasis marker: \"%c\"" char))
5747 (setq s (char-to-string char)))
5748 (while (and (> (length string) 1)
5749 (equal (substring string 0 1) (substring string -1))
5750 (assoc (substring string 0 1) org-emphasis-alist))
5751 (setq string (substring string 1 -1)))
5752 (setq string (concat s string s))
5753 (if beg (delete-region beg end))
5754 (unless (or (bolp)
5755 (string-match (concat "[" (nth 0 erc) "\n]")
5756 (char-to-string (char-before (point)))))
5757 (insert " "))
5758 (unless (or (eobp)
5759 (string-match (concat "[" (nth 1 erc) "\n]")
5760 (char-to-string (char-after (point)))))
5761 (insert " ") (backward-char 1))
5762 (insert string)
5763 (and move (backward-char 1))))
5764
5765 (defconst org-nonsticky-props
5766 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5767
5768 (defsubst org-rear-nonsticky-at (pos)
5769 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5770
5771 (defun org-activate-plain-links (limit)
5772 "Run through the buffer and add overlays to links."
5773 (let (f hl)
5774 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5775 (not (org-in-src-block-p)))
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (setq f (get-text-property (match-beginning 0) 'face))
5778 (setq hl (org-match-string-no-properties 0))
5779 (if (or (eq f 'org-tag)
5780 (and (listp f) (memq 'org-tag f)))
5781 nil
5782 (add-text-properties (match-beginning 0) (match-end 0)
5783 (list 'mouse-face 'highlight
5784 'face 'org-link
5785 'htmlize-link `(:uri ,hl)
5786 'keymap org-mouse-map))
5787 (org-rear-nonsticky-at (match-end 0)))
5788 t)))
5789
5790 (defun org-activate-code (limit)
5791 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5792 (progn
5793 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5794 (remove-text-properties (match-beginning 0) (match-end 0)
5795 '(display t invisible t intangible t))
5796 t)))
5797
5798 (defcustom org-src-fontify-natively nil
5799 "When non-nil, fontify code in code blocks."
5800 :type 'boolean
5801 :version "24.1"
5802 :group 'org-appearance
5803 :group 'org-babel)
5804
5805 (defcustom org-allow-promoting-top-level-subtree nil
5806 "When non-nil, allow promoting a top level subtree.
5807 The leading star of the top level headline will be replaced
5808 by a #."
5809 :type 'boolean
5810 :version "24.1"
5811 :group 'org-appearance)
5812
5813 (defun org-fontify-meta-lines-and-blocks (limit)
5814 (condition-case nil
5815 (org-fontify-meta-lines-and-blocks-1 limit)
5816 (error (message "org-mode fontification error"))))
5817
5818 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5819 "Fontify #+ lines and blocks."
5820 (let ((case-fold-search t))
5821 (if (re-search-forward
5822 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5823 limit t)
5824 (let ((beg (match-beginning 0))
5825 (block-start (match-end 0))
5826 (block-end nil)
5827 (lang (match-string 7))
5828 (beg1 (line-beginning-position 2))
5829 (dc1 (downcase (match-string 2)))
5830 (dc3 (downcase (match-string 3)))
5831 end end1 quoting block-type ovl)
5832 (cond
5833 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5834 ;; a single line of backend-specific content
5835 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5836 (remove-text-properties (match-beginning 0) (match-end 0)
5837 '(display t invisible t intangible t))
5838 (add-text-properties (match-beginning 1) (match-end 3)
5839 '(font-lock-fontified t face org-meta-line))
5840 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5841 '(font-lock-fontified t face org-block))
5842 ; for backend-specific code
5843 t)
5844 ((and (match-end 4) (equal dc3 "+begin"))
5845 ;; Truly a block
5846 (setq block-type (downcase (match-string 5))
5847 quoting (member block-type org-protecting-blocks))
5848 (when (re-search-forward
5849 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5850 nil t) ;; on purpose, we look further than LIMIT
5851 (setq end (min (point-max) (match-end 0))
5852 end1 (min (point-max) (1- (match-beginning 0))))
5853 (setq block-end (match-beginning 0))
5854 (when quoting
5855 (remove-text-properties beg end
5856 '(display t invisible t intangible t)))
5857 (add-text-properties
5858 beg end
5859 '(font-lock-fontified t font-lock-multiline t))
5860 (add-text-properties beg beg1 '(face org-meta-line))
5861 (add-text-properties end1 (min (point-max) (1+ end))
5862 '(face org-meta-line)) ; for end_src
5863 (cond
5864 ((and lang (not (string= lang "")) org-src-fontify-natively)
5865 (org-src-font-lock-fontify-block lang block-start block-end)
5866 ;; remove old background overlays
5867 (mapc (lambda (ov)
5868 (if (eq (overlay-get ov 'face) 'org-block-background)
5869 (delete-overlay ov)))
5870 (overlays-at (/ (+ beg1 block-end) 2)))
5871 ;; add a background overlay
5872 (setq ovl (make-overlay beg1 block-end))
5873 (overlay-put ovl 'face 'org-block-background)
5874 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5875 (quoting
5876 (add-text-properties beg1 (min (point-max) (1+ end1))
5877 '(face org-block))) ; end of source block
5878 ((not org-fontify-quote-and-verse-blocks))
5879 ((string= block-type "quote")
5880 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5881 ((string= block-type "verse")
5882 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5883 (add-text-properties beg beg1 '(face org-block-begin-line))
5884 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5885 '(face org-block-end-line))
5886 t))
5887 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5888 (add-text-properties
5889 beg (match-end 3)
5890 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5891 '(font-lock-fontified t invisible t)
5892 '(font-lock-fontified t face org-document-info-keyword)))
5893 (add-text-properties
5894 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5895 (if (string-equal dc1 "+title:")
5896 '(font-lock-fontified t face org-document-title)
5897 '(font-lock-fontified t face org-document-info))))
5898 ((or (equal dc1 "+results")
5899 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5900 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5901 "+call:" "+header:" "+headers:" "+name:"))
5902 (and (match-end 4) (equal dc3 "+attr")))
5903 (add-text-properties
5904 beg (match-end 0)
5905 '(font-lock-fontified t face org-meta-line))
5906 t)
5907 ((member dc3 '(" " ""))
5908 (add-text-properties
5909 beg (match-end 0)
5910 '(font-lock-fontified t face font-lock-comment-face)))
5911 ((not (member (char-after beg) '(?\ ?\t)))
5912 ;; just any other in-buffer setting, but not indented
5913 (add-text-properties
5914 beg (match-end 0)
5915 '(font-lock-fontified t face org-meta-line))
5916 t)
5917 (t nil))))))
5918
5919 (defun org-activate-angle-links (limit)
5920 "Run through the buffer and add overlays to links."
5921 (if (and (re-search-forward org-angle-link-re limit t)
5922 (not (org-in-src-block-p)))
5923 (progn
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (add-text-properties (match-beginning 0) (match-end 0)
5926 (list 'mouse-face 'highlight
5927 'keymap org-mouse-map))
5928 (org-rear-nonsticky-at (match-end 0))
5929 t)))
5930
5931 (defun org-activate-footnote-links (limit)
5932 "Run through the buffer and add overlays to footnotes."
5933 (let ((fn (org-footnote-next-reference-or-definition limit)))
5934 (when fn
5935 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5936 (org-remove-flyspell-overlays-in beg end)
5937 (add-text-properties beg end
5938 (list 'mouse-face 'highlight
5939 'keymap org-mouse-map
5940 'help-echo
5941 (if (= (point-at-bol) beg)
5942 "Footnote definition"
5943 "Footnote reference")
5944 'font-lock-fontified t
5945 'font-lock-multiline t
5946 'face 'org-footnote))))))
5947
5948 (defun org-activate-bracket-links (limit)
5949 "Run through the buffer and add overlays to bracketed links."
5950 (if (and (re-search-forward org-bracket-link-regexp limit t)
5951 (not (org-in-src-block-p)))
5952 (let* ((hl (org-match-string-no-properties 1))
5953 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5954 (ip (org-maybe-intangible
5955 (list 'invisible 'org-link
5956 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5960 'font-lock-multiline t 'help-echo help
5961 'htmlize-link `(:uri ,hl))))
5962 ;; We need to remove the invisible property here. Table narrowing
5963 ;; may have made some of this invisible.
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (remove-text-properties (match-beginning 0) (match-end 0)
5966 '(invisible nil))
5967 (if (match-end 3)
5968 (progn
5969 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5970 (org-rear-nonsticky-at (match-beginning 3))
5971 (add-text-properties (match-beginning 3) (match-end 3) vp)
5972 (org-rear-nonsticky-at (match-end 3))
5973 (add-text-properties (match-end 3) (match-end 0) ip)
5974 (org-rear-nonsticky-at (match-end 0)))
5975 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5976 (org-rear-nonsticky-at (match-beginning 1))
5977 (add-text-properties (match-beginning 1) (match-end 1) vp)
5978 (org-rear-nonsticky-at (match-end 1))
5979 (add-text-properties (match-end 1) (match-end 0) ip)
5980 (org-rear-nonsticky-at (match-end 0)))
5981 t)))
5982
5983 (defun org-activate-dates (limit)
5984 "Run through the buffer and add overlays to dates."
5985 (if (and (re-search-forward org-tsr-regexp-both limit t)
5986 (not (equal (char-before (match-beginning 0)) 91)))
5987 (progn
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties (match-beginning 0) (match-end 0)
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map))
5992 (org-rear-nonsticky-at (match-end 0))
5993 (when org-display-custom-times
5994 (if (match-end 3)
5995 (org-display-custom-time (match-beginning 3) (match-end 3)))
5996 (org-display-custom-time (match-beginning 1) (match-end 1)))
5997 t)))
5998
5999 (defvar org-target-link-regexp nil
6000 "Regular expression matching radio targets in plain text.")
6001 (make-variable-buffer-local 'org-target-link-regexp)
6002 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6003 "Regular expression matching a link target.")
6004 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6005 "Regular expression matching a radio target.")
6006 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6007 "Regular expression matching any target.")
6008
6009 (defun org-activate-target-links (limit)
6010 "Run through the buffer and add overlays to target matches."
6011 (when org-target-link-regexp
6012 (let ((case-fold-search t))
6013 (if (re-search-forward org-target-link-regexp limit t)
6014 (progn
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (add-text-properties (match-beginning 0) (match-end 0)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 0))
6022 t)))))
6023
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression."
6026 (interactive)
6027 (when (memq 'radio org-activate-links)
6028 (setq org-target-link-regexp
6029 (org-make-target-link-regexp (org-all-targets 'radio)))
6030 (org-restart-font-lock)))
6031
6032 (defun org-hide-wide-columns (limit)
6033 (let (s e)
6034 (setq s (text-property-any (point) (or limit (point-max))
6035 'org-cwidth t))
6036 (when s
6037 (setq e (next-single-property-change s 'org-cwidth))
6038 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6039 (goto-char e)
6040 t)))
6041
6042 (defvar org-latex-and-related-regexp nil
6043 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6044 (defvar org-match-substring-regexp)
6045 (defvar org-match-substring-with-braces-regexp)
6046
6047 (defun org-compute-latex-and-related-regexp ()
6048 "Compute regular expression for LaTeX, entities and sub/superscript.
6049 Result depends on variable `org-highlight-latex-and-related'."
6050 (org-set-local
6051 'org-latex-and-related-regexp
6052 (let* ((re-sub
6053 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6054 ((eq org-use-sub-superscripts '{})
6055 (list org-match-substring-with-braces-regexp))
6056 (org-use-sub-superscripts (list org-match-substring-regexp))))
6057 (re-latex
6058 (when (memq 'latex org-highlight-latex-and-related)
6059 (let ((matchers (plist-get org-format-latex-options :matchers)))
6060 (delq nil
6061 (mapcar (lambda (x)
6062 (and (member (car x) matchers) (nth 1 x)))
6063 org-latex-regexps)))))
6064 (re-entities
6065 (when (memq 'entities org-highlight-latex-and-related)
6066 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6067 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6068
6069 (defun org-do-latex-and-related (limit)
6070 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6071 LIMIT bounds the search for syntax to highlight. Stop at first
6072 highlighted object, if any. Return t if some highlighting was
6073 done, nil otherwise."
6074 (when (org-string-nw-p org-latex-and-related-regexp)
6075 (catch 'found
6076 (while (re-search-forward org-latex-and-related-regexp limit t)
6077 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6078 'face))
6079 '(org-code org-verbatim underline))
6080 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6081 '(?_ ?^))
6082 1
6083 0)))
6084 (font-lock-prepend-text-property
6085 (+ offset (match-beginning 0)) (match-end 0)
6086 'face 'org-latex-and-related)
6087 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6088 '(font-lock-multiline t)))
6089 (throw 'found t)))
6090 nil)))
6091
6092 (defun org-restart-font-lock ()
6093 "Restart `font-lock-mode', to force refontification."
6094 (when (and (boundp 'font-lock-mode) font-lock-mode)
6095 (font-lock-mode -1)
6096 (font-lock-mode 1)))
6097
6098 (defun org-all-targets (&optional radio)
6099 "Return a list of all targets in this file.
6100 When optional argument RADIO is non-nil, only find radio
6101 targets."
6102 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6103 (save-excursion
6104 (goto-char (point-min))
6105 (while (re-search-forward re nil t)
6106 ;; Make sure point is really within the object.
6107 (backward-char)
6108 (let ((obj (org-element-context)))
6109 (when (memq (org-element-type obj) '(radio-target target))
6110 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6111 rtn)))
6112
6113 (defun org-make-target-link-regexp (targets)
6114 "Make regular expression matching all strings in TARGETS.
6115 The regular expression finds the targets also if there is a line break
6116 between words."
6117 (and targets
6118 (concat
6119 "\\_<\\("
6120 (mapconcat
6121 (lambda (x)
6122 (setq x (regexp-quote x))
6123 (while (string-match " +" x)
6124 (setq x (replace-match "\\s-+" t t x)))
6125 x)
6126 targets
6127 "\\|")
6128 "\\)\\_>")))
6129
6130 (defun org-activate-tags (limit)
6131 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6132 (progn
6133 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6134 (add-text-properties (match-beginning 1) (match-end 1)
6135 (list 'mouse-face 'highlight
6136 'keymap org-mouse-map))
6137 (org-rear-nonsticky-at (match-end 1))
6138 t)))
6139
6140 (defun org-outline-level ()
6141 "Compute the outline level of the heading at point.
6142 If this is called at a normal headline, the level is the number of stars.
6143 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6144 (save-excursion
6145 (if (not (condition-case nil
6146 (org-back-to-heading t)
6147 (error nil)))
6148 0
6149 (looking-at org-outline-regexp)
6150 (1- (- (match-end 0) (match-beginning 0))))))
6151
6152 (defvar org-font-lock-keywords nil)
6153
6154 (defsubst org-re-property (property &optional literal allow-null)
6155 "Return a regexp matching a PROPERTY line.
6156
6157 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6158 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6159 non-nil, match properties even without a value.
6160
6161 Match group 3 is set to the value when it exists. If there is no
6162 value and ALLOW-NULL is non-nil, it is set to the empty string."
6163 (concat
6164 "^\\(?4:[ \t]*\\)"
6165 (format "\\(?1::\\(?2:%s\\):\\)"
6166 (if literal property (regexp-quote property)))
6167 (if allow-null
6168 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6169 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6170
6171 (defconst org-property-re
6172 (org-re-property ".*?" 'literal t)
6173 "Regular expression matching a property line.
6174 There are four matching groups:
6175 1: :PROPKEY: including the leading and trailing colon,
6176 2: PROPKEY without the leading and trailing colon,
6177 3: PROPVAL without leading or trailing spaces,
6178 4: the indentation of the current line,
6179 5: trailing whitespace.")
6180
6181 (defvar org-font-lock-hook nil
6182 "Functions to be called for special font lock stuff.")
6183
6184 (defvar org-font-lock-set-keywords-hook nil
6185 "Functions that can manipulate `org-font-lock-extra-keywords'.
6186 This is called after `org-font-lock-extra-keywords' is defined, but before
6187 it is installed to be used by font lock. This can be useful if something
6188 needs to be inserted at a specific position in the font-lock sequence.")
6189
6190 (defun org-font-lock-hook (limit)
6191 "Run `org-font-lock-hook' within LIMIT."
6192 (run-hook-with-args 'org-font-lock-hook limit))
6193
6194 (defun org-set-font-lock-defaults ()
6195 "Set font lock defaults for the current buffer."
6196 (let* ((em org-fontify-emphasized-text)
6197 (lk org-activate-links)
6198 (org-font-lock-extra-keywords
6199 (list
6200 ;; Call the hook
6201 '(org-font-lock-hook)
6202 ;; Headlines
6203 `(,(if org-fontify-whole-heading-line
6204 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6205 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6206 (1 (org-get-level-face 1))
6207 (2 (org-get-level-face 2))
6208 (3 (org-get-level-face 3)))
6209 ;; Table lines
6210 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6211 (1 'org-table t))
6212 ;; Table internals
6213 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6214 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6215 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6216 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6217 ;; Drawers
6218 (list org-drawer-regexp '(0 'org-special-keyword t))
6219 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6220 ;; Properties
6221 (list org-property-re
6222 '(1 'org-special-keyword t)
6223 '(3 'org-property-value t))
6224 ;; Links
6225 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6226 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6227 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6228 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6229 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6230 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6231 (if (memq 'footnote lk) '(org-activate-footnote-links))
6232 ;; Targets.
6233 (list org-any-target-regexp '(0 'org-target t))
6234 ;; Diary sexps.
6235 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6236 ;; Macro
6237 '("{{{.+}}}" (0 'org-macro t))
6238 '(org-hide-wide-columns (0 nil append))
6239 ;; TODO keyword
6240 (list (format org-heading-keyword-regexp-format
6241 org-todo-regexp)
6242 '(2 (org-get-todo-face 2) t))
6243 ;; DONE
6244 (if org-fontify-done-headline
6245 (list (format org-heading-keyword-regexp-format
6246 (concat
6247 "\\(?:"
6248 (mapconcat 'regexp-quote org-done-keywords "\\|")
6249 "\\)"))
6250 '(2 'org-headline-done t))
6251 nil)
6252 ;; Priorities
6253 '(org-font-lock-add-priority-faces)
6254 ;; Tags
6255 '(org-font-lock-add-tag-faces)
6256 ;; Tags groups
6257 (if (and org-group-tags org-tag-groups-alist)
6258 (list (concat org-outline-regexp-bol ".+\\(:"
6259 (regexp-opt (mapcar 'car org-tag-groups-alist))
6260 ":\\).*$")
6261 '(1 'org-tag-group prepend)))
6262 ;; Special keywords
6263 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6264 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6265 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6266 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6267 ;; Emphasis
6268 (if em
6269 (if (featurep 'xemacs)
6270 '(org-do-emphasis-faces (0 nil append))
6271 '(org-do-emphasis-faces)))
6272 ;; Checkboxes
6273 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6274 1 'org-checkbox prepend)
6275 (if (cdr (assq 'checkbox org-list-automatic-rules))
6276 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6277 (0 (org-get-checkbox-statistics-face) t)))
6278 ;; Description list items
6279 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6280 1 'org-list-dt prepend)
6281 ;; ARCHIVEd headings
6282 (list (concat
6283 org-outline-regexp-bol
6284 "\\(.*:" org-archive-tag ":.*\\)")
6285 '(1 'org-archived prepend))
6286 ;; Specials
6287 '(org-do-latex-and-related)
6288 '(org-fontify-entities)
6289 '(org-raise-scripts)
6290 ;; Code
6291 '(org-activate-code (1 'org-code t))
6292 ;; COMMENT
6293 (list (format org-heading-keyword-regexp-format
6294 (concat "\\("
6295 org-comment-string "\\|" org-quote-string
6296 "\\)"))
6297 '(2 'org-special-keyword t))
6298 ;; Blocks and meta lines
6299 '(org-fontify-meta-lines-and-blocks))))
6300 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6301 (run-hooks 'org-font-lock-set-keywords-hook)
6302 ;; Now set the full font-lock-keywords
6303 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6304 (org-set-local 'font-lock-defaults
6305 '(org-font-lock-keywords t nil nil backward-paragraph))
6306 (kill-local-variable 'font-lock-keywords) nil))
6307
6308 (defun org-toggle-pretty-entities ()
6309 "Toggle the composition display of entities as UTF8 characters."
6310 (interactive)
6311 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6312 (org-restart-font-lock)
6313 (if org-pretty-entities
6314 (message "Entities are now displayed as UTF8 characters")
6315 (save-restriction
6316 (widen)
6317 (org-decompose-region (point-min) (point-max))
6318 (message "Entities are now displayed as plain text"))))
6319
6320 (defvar org-custom-properties-overlays nil
6321 "List of overlays used for custom properties.")
6322 (make-variable-buffer-local 'org-custom-properties-overlays)
6323
6324 (defun org-toggle-custom-properties-visibility ()
6325 "Display or hide properties in `org-custom-properties'."
6326 (interactive)
6327 (if org-custom-properties-overlays
6328 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6329 (setq org-custom-properties-overlays nil))
6330 (unless (not org-custom-properties)
6331 (save-excursion
6332 (save-restriction
6333 (widen)
6334 (goto-char (point-min))
6335 (while (re-search-forward org-property-re nil t)
6336 (mapc (lambda(p)
6337 (when (equal p (substring (match-string 1) 1 -1))
6338 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6339 (overlay-put o 'invisible t)
6340 (overlay-put o 'org-custom-property t)
6341 (push o org-custom-properties-overlays))))
6342 org-custom-properties)))))))
6343
6344 (defun org-fontify-entities (limit)
6345 "Find an entity to fontify."
6346 (let (ee)
6347 (when org-pretty-entities
6348 (catch 'match
6349 (while (re-search-forward
6350 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6351 limit t)
6352 (if (and (not (org-in-indented-comment-line))
6353 (setq ee (org-entity-get (match-string 1)))
6354 (= (length (nth 6 ee)) 1))
6355 (let*
6356 ((end (if (equal (match-string 2) "{}")
6357 (match-end 2)
6358 (match-end 1))))
6359 (add-text-properties
6360 (match-beginning 0) end
6361 (list 'font-lock-fontified t))
6362 (compose-region (match-beginning 0) end
6363 (nth 6 ee) nil)
6364 (backward-char 1)
6365 (throw 'match t))))
6366 nil))))
6367
6368 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6369 "Fontify string S like in Org-mode."
6370 (with-temp-buffer
6371 (insert s)
6372 (let ((org-odd-levels-only odd-levels))
6373 (org-mode)
6374 (org-font-lock-ensure)
6375 (buffer-string))))
6376
6377 (defvar org-m nil)
6378 (defvar org-l nil)
6379 (defvar org-f nil)
6380 (defun org-get-level-face (n)
6381 "Get the right face for match N in font-lock matching of headlines."
6382 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6383 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6384 (if org-cycle-level-faces
6385 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6386 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6387 (cond
6388 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6389 ((eq n 2) org-f)
6390 (t (if org-level-color-stars-only nil org-f))))
6391
6392
6393 (defun org-get-todo-face (kwd)
6394 "Get the right face for a TODO keyword KWD.
6395 If KWD is a number, get the corresponding match group."
6396 (if (numberp kwd) (setq kwd (match-string kwd)))
6397 (or (org-face-from-face-or-color
6398 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6399 (and (member kwd org-done-keywords) 'org-done)
6400 'org-todo))
6401
6402 (defun org-face-from-face-or-color (context inherit face-or-color)
6403 "Create a face list that inherits INHERIT, but sets the foreground color.
6404 When FACE-OR-COLOR is not a string, just return it."
6405 (if (stringp face-or-color)
6406 (list :inherit inherit
6407 (cdr (assoc context org-faces-easy-properties))
6408 face-or-color)
6409 face-or-color))
6410
6411 (defun org-font-lock-add-tag-faces (limit)
6412 "Add the special tag faces."
6413 (when (and org-tag-faces org-tags-special-faces-re)
6414 (while (re-search-forward org-tags-special-faces-re limit t)
6415 (add-text-properties (match-beginning 1) (match-end 1)
6416 (list 'face (org-get-tag-face 1)
6417 'font-lock-fontified t))
6418 (backward-char 1))))
6419
6420 (defun org-font-lock-add-priority-faces (limit)
6421 "Add the special priority faces."
6422 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6423 (when (save-match-data (org-at-heading-p))
6424 (add-text-properties
6425 (match-beginning 0) (match-end 0)
6426 (list 'face (or (org-face-from-face-or-color
6427 'priority 'org-priority
6428 (cdr (assoc (char-after (match-beginning 1))
6429 org-priority-faces)))
6430 'org-priority)
6431 'font-lock-fontified t)))))
6432
6433 (defun org-get-tag-face (kwd)
6434 "Get the right face for a TODO keyword KWD.
6435 If KWD is a number, get the corresponding match group."
6436 (if (numberp kwd) (setq kwd (match-string kwd)))
6437 (or (org-face-from-face-or-color
6438 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6439 'org-tag))
6440
6441 (defun org-unfontify-region (beg end &optional maybe_loudly)
6442 "Remove fontification and activation overlays from links."
6443 (font-lock-default-unfontify-region beg end)
6444 (let* ((buffer-undo-list t)
6445 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6446 (inhibit-modification-hooks t)
6447 deactivate-mark buffer-file-name buffer-file-truename)
6448 (org-decompose-region beg end)
6449 (remove-text-properties beg end
6450 '(mouse-face t keymap t org-linked-text t
6451 invisible t intangible t
6452 org-no-flyspell t org-emphasis t))
6453 (org-remove-font-lock-display-properties beg end)))
6454
6455 (defconst org-script-display '(((raise -0.3) (height 0.7))
6456 ((raise 0.3) (height 0.7))
6457 ((raise -0.5))
6458 ((raise 0.5)))
6459 "Display properties for showing superscripts and subscripts.")
6460
6461 (defun org-remove-font-lock-display-properties (beg end)
6462 "Remove specific display properties that have been added by font lock.
6463 The will remove the raise properties that are used to show superscripts
6464 and subscripts."
6465 (let (next prop)
6466 (while (< beg end)
6467 (setq next (next-single-property-change beg 'display nil end)
6468 prop (get-text-property beg 'display))
6469 (if (member prop org-script-display)
6470 (put-text-property beg next 'display nil))
6471 (setq beg next))))
6472
6473 (defun org-raise-scripts (limit)
6474 "Add raise properties to sub/superscripts."
6475 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6476 (if (re-search-forward
6477 (if (eq org-use-sub-superscripts t)
6478 org-match-substring-regexp
6479 org-match-substring-with-braces-regexp)
6480 limit t)
6481 (let* ((pos (point)) table-p comment-p
6482 (mpos (match-beginning 3))
6483 (emph-p (get-text-property mpos 'org-emphasis))
6484 (link-p (get-text-property mpos 'mouse-face))
6485 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6486 (goto-char (point-at-bol))
6487 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6488 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6489 (goto-char pos)
6490 ;; Handle a_b^c
6491 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6492 (if (or comment-p emph-p link-p keyw-p)
6493 t
6494 (put-text-property (match-beginning 3) (match-end 0)
6495 'display
6496 (if (equal (char-after (match-beginning 2)) ?^)
6497 (nth (if table-p 3 1) org-script-display)
6498 (nth (if table-p 2 0) org-script-display)))
6499 (add-text-properties (match-beginning 2) (match-end 2)
6500 (list 'invisible t
6501 'org-dwidth t 'org-dwidth-n 1))
6502 (if (and (eq (char-after (match-beginning 3)) ?{)
6503 (eq (char-before (match-end 3)) ?}))
6504 (progn
6505 (add-text-properties
6506 (match-beginning 3) (1+ (match-beginning 3))
6507 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6508 (add-text-properties
6509 (1- (match-end 3)) (match-end 3)
6510 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6511 t)))))
6512
6513 ;;;; Visibility cycling, including org-goto and indirect buffer
6514
6515 ;;; Cycling
6516
6517 (defvar org-cycle-global-status nil)
6518 (make-variable-buffer-local 'org-cycle-global-status)
6519 (put 'org-cycle-global-status 'org-state t)
6520 (defvar org-cycle-subtree-status nil)
6521 (make-variable-buffer-local 'org-cycle-subtree-status)
6522 (put 'org-cycle-subtree-status 'org-state t)
6523
6524 (defvar org-inlinetask-min-level)
6525
6526 (defun org-unlogged-message (&rest args)
6527 "Display a message, but avoid logging it in the *Messages* buffer."
6528 (let ((message-log-max nil))
6529 (apply 'message args)))
6530
6531 ;;;###autoload
6532 (defun org-cycle (&optional arg)
6533 "TAB-action and visibility cycling for Org-mode.
6534
6535 This is the command invoked in Org-mode by the TAB key. Its main purpose
6536 is outline visibility cycling, but it also invokes other actions
6537 in special contexts.
6538
6539 - When this function is called with a prefix argument, rotate the entire
6540 buffer through 3 states (global cycling)
6541 1. OVERVIEW: Show only top-level headlines.
6542 2. CONTENTS: Show all headlines of all levels, but no body text.
6543 3. SHOW ALL: Show everything.
6544 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6545 determined by the variable `org-startup-folded', and by any VISIBILITY
6546 properties in the buffer.
6547 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6548 including any drawers.
6549
6550 - When inside a table, re-align the table and move to the next field.
6551
6552 - When point is at the beginning of a headline, rotate the subtree started
6553 by this line through 3 different states (local cycling)
6554 1. FOLDED: Only the main headline is shown.
6555 2. CHILDREN: The main headline and the direct children are shown.
6556 From this state, you can move to one of the children
6557 and zoom in further.
6558 3. SUBTREE: Show the entire subtree, including body text.
6559 If there is no subtree, switch directly from CHILDREN to FOLDED.
6560
6561 - When point is at the beginning of an empty headline and the variable
6562 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6563 of the headline by demoting and promoting it to likely levels. This
6564 speeds up creation document structure by pressing TAB once or several
6565 times right after creating a new headline.
6566
6567 - When there is a numeric prefix, go up to a heading with level ARG, do
6568 a `show-subtree' and return to the previous cursor position. If ARG
6569 is negative, go up that many levels.
6570
6571 - When point is not at the beginning of a headline, execute the global
6572 binding for TAB, which is re-indenting the line. See the option
6573 `org-cycle-emulate-tab' for details.
6574
6575 - Special case: if point is at the beginning of the buffer and there is
6576 no headline in line 1, this function will act as if called with prefix arg
6577 (C-u TAB, same as S-TAB) also when called without prefix arg.
6578 But only if also the variable `org-cycle-global-at-bob' is t."
6579 (interactive "P")
6580 (org-load-modules-maybe)
6581 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6582 (and org-cycle-level-after-item/entry-creation
6583 (or (org-cycle-level)
6584 (org-cycle-item-indentation))))
6585 (let* ((limit-level
6586 (or org-cycle-max-level
6587 (and (boundp 'org-inlinetask-min-level)
6588 org-inlinetask-min-level
6589 (1- org-inlinetask-min-level))))
6590 (nstars (and limit-level
6591 (if org-odd-levels-only
6592 (and limit-level (1- (* limit-level 2)))
6593 limit-level)))
6594 (org-outline-regexp
6595 (if (not (derived-mode-p 'org-mode))
6596 outline-regexp
6597 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6598 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6599 (not (looking-at org-outline-regexp))))
6600 (org-cycle-hook
6601 (if bob-special
6602 (delq 'org-optimize-window-after-visibility-change
6603 (copy-sequence org-cycle-hook))
6604 org-cycle-hook))
6605 (pos (point)))
6606
6607 (if (or bob-special (equal arg '(4)))
6608 ;; special case: use global cycling
6609 (setq arg t))
6610
6611 (cond
6612
6613 ((equal arg '(16))
6614 (setq last-command 'dummy)
6615 (org-set-startup-visibility)
6616 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6617
6618 ((equal arg '(64))
6619 (show-all)
6620 (org-unlogged-message "Entire buffer visible, including drawers"))
6621
6622 ;; Try cdlatex TAB completion
6623 ((org-try-cdlatex-tab))
6624
6625 ;; Table: enter it or move to the next field.
6626 ((org-at-table-p 'any)
6627 (if (org-at-table.el-p)
6628 (message "Use C-c ' to edit table.el tables")
6629 (if arg (org-table-edit-field t)
6630 (org-table-justify-field-maybe)
6631 (call-interactively 'org-table-next-field))))
6632
6633 ((run-hook-with-args-until-success
6634 'org-tab-after-check-for-table-hook))
6635
6636 ;; Global cycling: delegate to `org-cycle-internal-global'.
6637 ((eq arg t) (org-cycle-internal-global))
6638
6639 ;; Drawers: delegate to `org-flag-drawer'.
6640 ((and org-drawers org-drawer-regexp
6641 (save-excursion
6642 (beginning-of-line 1)
6643 (looking-at org-drawer-regexp)))
6644 (org-flag-drawer ; toggle block visibility
6645 (not (get-char-property (match-end 0) 'invisible))))
6646
6647 ;; Show-subtree, ARG levels up from here.
6648 ((integerp arg)
6649 (save-excursion
6650 (org-back-to-heading)
6651 (outline-up-heading (if (< arg 0) (- arg)
6652 (- (funcall outline-level) arg)))
6653 (org-show-subtree)))
6654
6655 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6656 ((and (featurep 'org-inlinetask)
6657 (org-inlinetask-at-task-p)
6658 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6659 (org-inlinetask-toggle-visibility))
6660
6661 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6662 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6663 (save-excursion (beginning-of-line 1)
6664 (looking-at org-outline-regexp)))
6665 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6666 (org-cycle-internal-local))
6667
6668 ;; From there: TAB emulation and template completion.
6669 (buffer-read-only (org-back-to-heading))
6670
6671 ((run-hook-with-args-until-success
6672 'org-tab-after-check-for-cycling-hook))
6673
6674 ((org-try-structure-completion))
6675
6676 ((run-hook-with-args-until-success
6677 'org-tab-before-tab-emulation-hook))
6678
6679 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6680 (or (not (bolp))
6681 (not (looking-at org-outline-regexp))))
6682 (call-interactively (global-key-binding "\t")))
6683
6684 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6685 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6686 (or (and (eq org-cycle-emulate-tab 'white)
6687 (= (match-end 0) (point-at-eol)))
6688 (and (eq org-cycle-emulate-tab 'whitestart)
6689 (>= (match-end 0) pos))))
6690 t
6691 (eq org-cycle-emulate-tab t))
6692 (call-interactively (global-key-binding "\t")))
6693
6694 (t (save-excursion
6695 (org-back-to-heading)
6696 (org-cycle)))))))
6697
6698 (defun org-cycle-internal-global ()
6699 "Do the global cycling action."
6700 ;; Hack to avoid display of messages for .org attachments in Gnus
6701 (let ((ga (string-match "\\*fontification" (buffer-name))))
6702 (cond
6703 ((and (eq last-command this-command)
6704 (eq org-cycle-global-status 'overview))
6705 ;; We just created the overview - now do table of contents
6706 ;; This can be slow in very large buffers, so indicate action
6707 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6708 (unless ga (org-unlogged-message "CONTENTS..."))
6709 (org-content)
6710 (unless ga (org-unlogged-message "CONTENTS...done"))
6711 (setq org-cycle-global-status 'contents)
6712 (run-hook-with-args 'org-cycle-hook 'contents))
6713
6714 ((and (eq last-command this-command)
6715 (eq org-cycle-global-status 'contents))
6716 ;; We just showed the table of contents - now show everything
6717 (run-hook-with-args 'org-pre-cycle-hook 'all)
6718 (show-all)
6719 (unless ga (org-unlogged-message "SHOW ALL"))
6720 (setq org-cycle-global-status 'all)
6721 (run-hook-with-args 'org-cycle-hook 'all))
6722
6723 (t
6724 ;; Default action: go to overview
6725 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6726 (org-overview)
6727 (unless ga (org-unlogged-message "OVERVIEW"))
6728 (setq org-cycle-global-status 'overview)
6729 (run-hook-with-args 'org-cycle-hook 'overview)))))
6730
6731 (defvar org-called-with-limited-levels nil
6732 "Non-nil when `org-with-limited-levels' is currently active.")
6733
6734 (defun org-cycle-internal-local ()
6735 "Do the local cycling action."
6736 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6737 ;; First, determine end of headline (EOH), end of subtree or item
6738 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6739 (save-excursion
6740 (if (org-at-item-p)
6741 (progn
6742 (beginning-of-line)
6743 (setq struct (org-list-struct))
6744 (setq eoh (point-at-eol))
6745 (setq eos (org-list-get-item-end-before-blank (point) struct))
6746 (setq has-children (org-list-has-child-p (point) struct)))
6747 (org-back-to-heading)
6748 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6749 (setq eos (save-excursion (org-end-of-subtree t t)
6750 (when (bolp) (backward-char)) (point)))
6751 (setq has-children
6752 (or (save-excursion
6753 (let ((level (funcall outline-level)))
6754 (outline-next-heading)
6755 (and (org-at-heading-p t)
6756 (> (funcall outline-level) level))))
6757 (save-excursion
6758 (org-list-search-forward (org-item-beginning-re) eos t)))))
6759 ;; Determine end invisible part of buffer (EOL)
6760 (beginning-of-line 2)
6761 ;; XEmacs doesn't have `next-single-char-property-change'
6762 (if (featurep 'xemacs)
6763 (while (and (not (eobp)) ;; this is like `next-line'
6764 (get-char-property (1- (point)) 'invisible))
6765 (beginning-of-line 2))
6766 (while (and (not (eobp)) ;; this is like `next-line'
6767 (get-char-property (1- (point)) 'invisible))
6768 (goto-char (next-single-char-property-change (point) 'invisible))
6769 (and (eolp) (beginning-of-line 2))))
6770 (setq eol (point)))
6771 ;; Find out what to do next and set `this-command'
6772 (cond
6773 ((= eos eoh)
6774 ;; Nothing is hidden behind this heading
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6777 (org-unlogged-message "EMPTY ENTRY")
6778 (setq org-cycle-subtree-status nil)
6779 (save-excursion
6780 (goto-char eos)
6781 (outline-next-heading)
6782 (if (outline-invisible-p) (org-flag-heading nil))))
6783 ((and (or (>= eol eos)
6784 (not (string-match "\\S-" (buffer-substring eol eos))))
6785 (or has-children
6786 (not (setq children-skipped
6787 org-cycle-skip-children-state-if-no-children))))
6788 ;; Entire subtree is hidden in one line: children view
6789 (unless (org-before-first-heading-p)
6790 (run-hook-with-args 'org-pre-cycle-hook 'children))
6791 (if (org-at-item-p)
6792 (org-list-set-item-visibility (point-at-bol) struct 'children)
6793 (org-show-entry)
6794 (org-with-limited-levels (show-children))
6795 ;; FIXME: This slows down the func way too much.
6796 ;; How keep drawers hidden in subtree anyway?
6797 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6798 ;; (org-cycle-hide-drawers 'subtree))
6799
6800 ;; Fold every list in subtree to top-level items.
6801 (when (eq org-cycle-include-plain-lists 'integrate)
6802 (save-excursion
6803 (org-back-to-heading)
6804 (while (org-list-search-forward (org-item-beginning-re) eos t)
6805 (beginning-of-line 1)
6806 (let* ((struct (org-list-struct))
6807 (prevs (org-list-prevs-alist struct))
6808 (end (org-list-get-bottom-point struct)))
6809 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6810 (org-list-get-all-items (point) struct prevs))
6811 (goto-char (if (< end eos) end eos)))))))
6812 (org-unlogged-message "CHILDREN")
6813 (save-excursion
6814 (goto-char eos)
6815 (outline-next-heading)
6816 (if (outline-invisible-p) (org-flag-heading nil)))
6817 (setq org-cycle-subtree-status 'children)
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-cycle-hook 'children)))
6820 ((or children-skipped
6821 (and (eq last-command this-command)
6822 (eq org-cycle-subtree-status 'children)))
6823 ;; We just showed the children, or no children are there,
6824 ;; now show everything.
6825 (unless (org-before-first-heading-p)
6826 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6827 (outline-flag-region eoh eos nil)
6828 (org-unlogged-message
6829 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6830 (setq org-cycle-subtree-status 'subtree)
6831 (unless (org-before-first-heading-p)
6832 (run-hook-with-args 'org-cycle-hook 'subtree)))
6833 (t
6834 ;; Default action: hide the subtree.
6835 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6836 (outline-flag-region eoh eos t)
6837 (org-unlogged-message "FOLDED")
6838 (setq org-cycle-subtree-status 'folded)
6839 (unless (org-before-first-heading-p)
6840 (run-hook-with-args 'org-cycle-hook 'folded))))))
6841
6842 ;;;###autoload
6843 (defun org-global-cycle (&optional arg)
6844 "Cycle the global visibility. For details see `org-cycle'.
6845 With \\[universal-argument] prefix arg, switch to startup visibility.
6846 With a numeric prefix, show all headlines up to that level."
6847 (interactive "P")
6848 (let ((org-cycle-include-plain-lists
6849 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6850 (cond
6851 ((integerp arg)
6852 (show-all)
6853 (hide-sublevels arg)
6854 (setq org-cycle-global-status 'contents))
6855 ((equal arg '(4))
6856 (org-set-startup-visibility)
6857 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6858 (t
6859 (org-cycle '(4))))))
6860
6861 (defun org-set-startup-visibility ()
6862 "Set the visibility required by startup options and properties."
6863 (cond
6864 ((eq org-startup-folded t)
6865 (org-overview))
6866 ((eq org-startup-folded 'content)
6867 (org-content))
6868 ((or (eq org-startup-folded 'showeverything)
6869 (eq org-startup-folded nil))
6870 (show-all)))
6871 (unless (eq org-startup-folded 'showeverything)
6872 (if org-hide-block-startup (org-hide-block-all))
6873 (org-set-visibility-according-to-property 'no-cleanup)
6874 (org-cycle-hide-archived-subtrees 'all)
6875 (org-cycle-hide-drawers 'all)
6876 (org-cycle-show-empty-lines t)))
6877
6878 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6879 "Switch subtree visibilities according to :VISIBILITY: property."
6880 (interactive)
6881 (let (org-show-entry-below state)
6882 (save-excursion
6883 (goto-char (point-min))
6884 (while (re-search-forward
6885 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6886 nil t)
6887 (setq state (match-string 1))
6888 (save-excursion
6889 (org-back-to-heading t)
6890 (hide-subtree)
6891 (org-reveal)
6892 (cond
6893 ((equal state '("fold" "folded"))
6894 (hide-subtree))
6895 ((equal state "children")
6896 (org-show-hidden-entry)
6897 (show-children))
6898 ((equal state "content")
6899 (save-excursion
6900 (save-restriction
6901 (org-narrow-to-subtree)
6902 (org-content))))
6903 ((member state '("all" "showall"))
6904 (show-subtree)))))
6905 (unless no-cleanup
6906 (org-cycle-hide-archived-subtrees 'all)
6907 (org-cycle-hide-drawers 'all)
6908 (org-cycle-show-empty-lines 'all)))))
6909
6910 ;; This function uses outline-regexp instead of the more fundamental
6911 ;; org-outline-regexp so that org-cycle-global works outside of Org
6912 ;; buffers, where outline-regexp is needed.
6913 (defun org-overview ()
6914 "Switch to overview mode, showing only top-level headlines.
6915 This shows all headlines with a level equal or greater than the level
6916 of the first headline in the buffer. This is important, because if the
6917 first headline is not level one, then (hide-sublevels 1) gives confusing
6918 results."
6919 (interactive)
6920 (save-excursion
6921 (let ((level
6922 (save-excursion
6923 (goto-char (point-min))
6924 (if (re-search-forward (concat "^" outline-regexp) nil t)
6925 (progn
6926 (goto-char (match-beginning 0))
6927 (funcall outline-level))))))
6928 (and level (hide-sublevels level)))))
6929
6930 (defun org-content (&optional arg)
6931 "Show all headlines in the buffer, like a table of contents.
6932 With numerical argument N, show content up to level N."
6933 (interactive "P")
6934 (org-overview)
6935 (save-excursion
6936 ;; Visit all headings and show their offspring
6937 (and (integerp arg) (org-overview))
6938 (goto-char (point-max))
6939 (catch 'exit
6940 (while (and (progn (condition-case nil
6941 (outline-previous-visible-heading 1)
6942 (error (goto-char (point-min))))
6943 t)
6944 (looking-at org-outline-regexp))
6945 (if (integerp arg)
6946 (show-children (1- arg))
6947 (show-branches))
6948 (if (bobp) (throw 'exit nil))))))
6949
6950 (defun org-optimize-window-after-visibility-change (state)
6951 "Adjust the window after a change in outline visibility.
6952 This function is the default value of the hook `org-cycle-hook'."
6953 (when (get-buffer-window (current-buffer))
6954 (cond
6955 ((eq state 'content) nil)
6956 ((eq state 'all) nil)
6957 ((eq state 'folded) nil)
6958 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6959 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6960
6961 (defun org-remove-empty-overlays-at (pos)
6962 "Remove outline overlays that do not contain non-white stuff."
6963 (mapc
6964 (lambda (o)
6965 (and (eq 'outline (overlay-get o 'invisible))
6966 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6967 (overlay-end o))))
6968 (delete-overlay o)))
6969 (overlays-at pos)))
6970
6971 (defun org-clean-visibility-after-subtree-move ()
6972 "Fix visibility issues after moving a subtree."
6973 ;; First, find a reasonable region to look at:
6974 ;; Start two siblings above, end three below
6975 (let* ((beg (save-excursion
6976 (and (org-get-last-sibling)
6977 (org-get-last-sibling))
6978 (point)))
6979 (end (save-excursion
6980 (and (org-get-next-sibling)
6981 (org-get-next-sibling)
6982 (org-get-next-sibling))
6983 (if (org-at-heading-p)
6984 (point-at-eol)
6985 (point))))
6986 (level (looking-at "\\*+"))
6987 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6988 (save-excursion
6989 (save-restriction
6990 (narrow-to-region beg end)
6991 (when re
6992 ;; Properly fold already folded siblings
6993 (goto-char (point-min))
6994 (while (re-search-forward re nil t)
6995 (if (and (not (outline-invisible-p))
6996 (save-excursion
6997 (goto-char (point-at-eol)) (outline-invisible-p)))
6998 (hide-entry))))
6999 (org-cycle-show-empty-lines 'overview)
7000 (org-cycle-hide-drawers 'overview)))))
7001
7002 (defun org-cycle-show-empty-lines (state)
7003 "Show empty lines above all visible headlines.
7004 The region to be covered depends on STATE when called through
7005 `org-cycle-hook'. Lisp program can use t for STATE to get the
7006 entire buffer covered. Note that an empty line is only shown if there
7007 are at least `org-cycle-separator-lines' empty lines before the headline."
7008 (when (not (= org-cycle-separator-lines 0))
7009 (save-excursion
7010 (let* ((n (abs org-cycle-separator-lines))
7011 (re (cond
7012 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7013 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7014 (t (let ((ns (number-to-string (- n 2))))
7015 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7016 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7017 beg end b e)
7018 (cond
7019 ((memq state '(overview contents t))
7020 (setq beg (point-min) end (point-max)))
7021 ((memq state '(children folded))
7022 (setq beg (point) end (progn (org-end-of-subtree t t)
7023 (beginning-of-line 2)
7024 (point)))))
7025 (when beg
7026 (goto-char beg)
7027 (while (re-search-forward re end t)
7028 (unless (get-char-property (match-end 1) 'invisible)
7029 (setq e (match-end 1))
7030 (if (< org-cycle-separator-lines 0)
7031 (setq b (save-excursion
7032 (goto-char (match-beginning 0))
7033 (org-back-over-empty-lines)
7034 (if (save-excursion
7035 (goto-char (max (point-min) (1- (point))))
7036 (org-at-heading-p))
7037 (1- (point))
7038 (point))))
7039 (setq b (match-beginning 1)))
7040 (outline-flag-region b e nil)))))))
7041 ;; Never hide empty lines at the end of the file.
7042 (save-excursion
7043 (goto-char (point-max))
7044 (outline-previous-heading)
7045 (outline-end-of-heading)
7046 (if (and (looking-at "[ \t\n]+")
7047 (= (match-end 0) (point-max)))
7048 (outline-flag-region (point) (match-end 0) nil))))
7049
7050 (defun org-show-empty-lines-in-parent ()
7051 "Move to the parent and re-show empty lines before visible headlines."
7052 (save-excursion
7053 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7054 (org-cycle-show-empty-lines context))))
7055
7056 (defun org-files-list ()
7057 "Return `org-agenda-files' list, plus all open org-mode files.
7058 This is useful for operations that need to scan all of a user's
7059 open and agenda-wise Org files."
7060 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7061 (dolist (buf (buffer-list))
7062 (with-current-buffer buf
7063 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7064 (let ((file (expand-file-name (buffer-file-name))))
7065 (unless (member file files)
7066 (push file files))))))
7067 files))
7068
7069 (defsubst org-entry-beginning-position ()
7070 "Return the beginning position of the current entry."
7071 (save-excursion (outline-back-to-heading t) (point)))
7072
7073 (defsubst org-entry-end-position ()
7074 "Return the end position of the current entry."
7075 (save-excursion (outline-next-heading) (point)))
7076
7077 (defun org-cycle-hide-drawers (state)
7078 "Re-hide all drawers after a visibility state change."
7079 (when (and (derived-mode-p 'org-mode)
7080 (not (memq state '(overview folded contents))))
7081 (save-excursion
7082 (let* ((globalp (memq state '(contents all)))
7083 (beg (if globalp (point-min) (point)))
7084 (end (if globalp (point-max)
7085 (if (eq state 'children)
7086 (save-excursion (outline-next-heading) (point))
7087 (org-end-of-subtree t)))))
7088 (goto-char beg)
7089 (while (re-search-forward org-drawer-regexp end t)
7090 (org-flag-drawer t))))))
7091
7092 (defun org-cycle-hide-inline-tasks (state)
7093 "Re-hide inline tasks when switching to 'contents or 'children
7094 visibility state."
7095 (case state
7096 (contents
7097 (when (org-bound-and-true-p org-inlinetask-min-level)
7098 (hide-sublevels (1- org-inlinetask-min-level))))
7099 (children
7100 (when (featurep 'org-inlinetask)
7101 (save-excursion
7102 (while (and (outline-next-heading)
7103 (org-inlinetask-at-task-p))
7104 (org-inlinetask-toggle-visibility)
7105 (org-inlinetask-goto-end)))))))
7106
7107 (defun org-flag-drawer (flag)
7108 "When FLAG is non-nil, hide the drawer we are within.
7109 Otherwise make it visible."
7110 (save-excursion
7111 (beginning-of-line 1)
7112 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7113 (let ((b (match-end 0)))
7114 (if (re-search-forward
7115 "^[ \t]*:END:"
7116 (save-excursion (outline-next-heading) (point)) t)
7117 (outline-flag-region b (point-at-eol) flag)
7118 (user-error ":END: line missing at position %s" b))))))
7119
7120 (defun org-subtree-end-visible-p ()
7121 "Is the end of the current subtree visible?"
7122 (pos-visible-in-window-p
7123 (save-excursion (org-end-of-subtree t) (point))))
7124
7125 (defun org-first-headline-recenter ()
7126 "Move cursor to the first headline and recenter the headline."
7127 (goto-char (point-min))
7128 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7129 (set-window-start (selected-window) (point-at-bol))))
7130
7131 ;;; Saving and restoring visibility
7132
7133 (defun org-outline-overlay-data (&optional use-markers)
7134 "Return a list of the locations of all outline overlays.
7135 These are overlays with the `invisible' property value `outline'.
7136 The return value is a list of cons cells, with start and stop
7137 positions for each overlay.
7138 If USE-MARKERS is set, return the positions as markers."
7139 (let (beg end)
7140 (save-excursion
7141 (save-restriction
7142 (widen)
7143 (delq nil
7144 (mapcar (lambda (o)
7145 (when (eq (overlay-get o 'invisible) 'outline)
7146 (setq beg (overlay-start o)
7147 end (overlay-end o))
7148 (and beg end (> end beg)
7149 (if use-markers
7150 (cons (move-marker (make-marker) beg)
7151 (move-marker (make-marker) end))
7152 (cons beg end)))))
7153 (overlays-in (point-min) (point-max))))))))
7154
7155 (defun org-set-outline-overlay-data (data)
7156 "Create visibility overlays for all positions in DATA.
7157 DATA should have been made by `org-outline-overlay-data'."
7158 (let (o)
7159 (save-excursion
7160 (save-restriction
7161 (widen)
7162 (show-all)
7163 (mapc (lambda (c)
7164 (outline-flag-region (car c) (cdr c) t))
7165 data)))))
7166
7167 ;;; Folding of blocks
7168
7169 (defvar org-hide-block-overlays nil
7170 "Overlays hiding blocks.")
7171 (make-variable-buffer-local 'org-hide-block-overlays)
7172
7173 (defun org-block-map (function &optional start end)
7174 "Call FUNCTION at the head of all source blocks in the current buffer.
7175 Optional arguments START and END can be used to limit the range."
7176 (let ((start (or start (point-min)))
7177 (end (or end (point-max))))
7178 (save-excursion
7179 (goto-char start)
7180 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7181 (save-excursion
7182 (save-match-data
7183 (goto-char (match-beginning 0))
7184 (funcall function)))))))
7185
7186 (defun org-hide-block-toggle-all ()
7187 "Toggle the visibility of all blocks in the current buffer."
7188 (org-block-map #'org-hide-block-toggle))
7189
7190 (defun org-hide-block-all ()
7191 "Fold all blocks in the current buffer."
7192 (interactive)
7193 (org-show-block-all)
7194 (org-block-map #'org-hide-block-toggle-maybe))
7195
7196 (defun org-show-block-all ()
7197 "Unfold all blocks in the current buffer."
7198 (interactive)
7199 (mapc 'delete-overlay org-hide-block-overlays)
7200 (setq org-hide-block-overlays nil))
7201
7202 (defun org-hide-block-toggle-maybe ()
7203 "Toggle visibility of block at point."
7204 (interactive)
7205 (let ((case-fold-search t))
7206 (if (save-excursion
7207 (beginning-of-line 1)
7208 (looking-at org-block-regexp))
7209 (progn (org-hide-block-toggle)
7210 t) ;; to signal that we took action
7211 nil))) ;; to signal that we did not
7212
7213 (defun org-hide-block-toggle (&optional force)
7214 "Toggle the visibility of the current block."
7215 (interactive)
7216 (save-excursion
7217 (beginning-of-line)
7218 (if (re-search-forward org-block-regexp nil t)
7219 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7220 (end (match-end 0)) ;; end of entire body
7221 ov)
7222 (if (memq t (mapcar (lambda (overlay)
7223 (eq (overlay-get overlay 'invisible)
7224 'org-hide-block))
7225 (overlays-at start)))
7226 (if (or (not force) (eq force 'off))
7227 (mapc (lambda (ov)
7228 (when (member ov org-hide-block-overlays)
7229 (setq org-hide-block-overlays
7230 (delq ov org-hide-block-overlays)))
7231 (when (eq (overlay-get ov 'invisible)
7232 'org-hide-block)
7233 (delete-overlay ov)))
7234 (overlays-at start)))
7235 (setq ov (make-overlay start end))
7236 (overlay-put ov 'invisible 'org-hide-block)
7237 ;; make the block accessible to isearch
7238 (overlay-put
7239 ov 'isearch-open-invisible
7240 (lambda (ov)
7241 (when (member ov org-hide-block-overlays)
7242 (setq org-hide-block-overlays
7243 (delq ov org-hide-block-overlays)))
7244 (when (eq (overlay-get ov 'invisible)
7245 'org-hide-block)
7246 (delete-overlay ov))))
7247 (push ov org-hide-block-overlays)))
7248 (user-error "Not looking at a source block"))))
7249
7250 ;; org-tab-after-check-for-cycling-hook
7251 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7252 ;; Remove overlays when changing major mode
7253 (add-hook 'org-mode-hook
7254 (lambda () (org-add-hook 'change-major-mode-hook
7255 'org-show-block-all 'append 'local)))
7256
7257 ;;; Org-goto
7258
7259 (defvar org-goto-window-configuration nil)
7260 (defvar org-goto-marker nil)
7261 (defvar org-goto-map)
7262 (defun org-goto-map ()
7263 "Set the keymap `org-goto'."
7264 (setq org-goto-map
7265 (let ((map (make-sparse-keymap)))
7266 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7267 mouse-drag-region universal-argument org-occur))
7268 cmd)
7269 (while (setq cmd (pop cmds))
7270 (substitute-key-definition cmd cmd map global-map)))
7271 (suppress-keymap map)
7272 (org-defkey map "\C-m" 'org-goto-ret)
7273 (org-defkey map [(return)] 'org-goto-ret)
7274 (org-defkey map [(left)] 'org-goto-left)
7275 (org-defkey map [(right)] 'org-goto-right)
7276 (org-defkey map [(control ?g)] 'org-goto-quit)
7277 (org-defkey map "\C-i" 'org-cycle)
7278 (org-defkey map [(tab)] 'org-cycle)
7279 (org-defkey map [(down)] 'outline-next-visible-heading)
7280 (org-defkey map [(up)] 'outline-previous-visible-heading)
7281 (if org-goto-auto-isearch
7282 (if (fboundp 'define-key-after)
7283 (define-key-after map [t] 'org-goto-local-auto-isearch)
7284 nil)
7285 (org-defkey map "q" 'org-goto-quit)
7286 (org-defkey map "n" 'outline-next-visible-heading)
7287 (org-defkey map "p" 'outline-previous-visible-heading)
7288 (org-defkey map "f" 'outline-forward-same-level)
7289 (org-defkey map "b" 'outline-backward-same-level)
7290 (org-defkey map "u" 'outline-up-heading))
7291 (org-defkey map "/" 'org-occur)
7292 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7293 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7294 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7295 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7296 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7297 map)))
7298
7299 (defconst org-goto-help
7300 "Browse buffer copy, to find location or copy text.%s
7301 RET=jump to location C-g=quit and return to previous location
7302 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7303
7304 (defvar org-goto-start-pos) ; dynamically scoped parameter
7305
7306 (defun org-goto (&optional alternative-interface)
7307 "Look up a different location in the current file, keeping current visibility.
7308
7309 When you want look-up or go to a different location in a
7310 document, the fastest way is often to fold the entire buffer and
7311 then dive into the tree. This method has the disadvantage, that
7312 the previous location will be folded, which may not be what you
7313 want.
7314
7315 This command works around this by showing a copy of the current
7316 buffer in an indirect buffer, in overview mode. You can dive
7317 into the tree in that copy, use org-occur and incremental search
7318 to find a location. When pressing RET or `Q', the command
7319 returns to the original buffer in which the visibility is still
7320 unchanged. After RET it will also jump to the location selected
7321 in the indirect buffer and expose the headline hierarchy above.
7322
7323 With a prefix argument, use the alternative interface: e.g. if
7324 `org-goto-interface' is 'outline use 'outline-path-completion."
7325 (interactive "P")
7326 (org-goto-map)
7327 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7328 (org-refile-use-outline-path t)
7329 (org-refile-target-verify-function nil)
7330 (interface
7331 (if (not alternative-interface)
7332 org-goto-interface
7333 (if (eq org-goto-interface 'outline)
7334 'outline-path-completion
7335 'outline)))
7336 (org-goto-start-pos (point))
7337 (selected-point
7338 (if (eq interface 'outline)
7339 (car (org-get-location (current-buffer) org-goto-help))
7340 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7341 (org-refile-check-position pa)
7342 (nth 3 pa)))))
7343 (if selected-point
7344 (progn
7345 (org-mark-ring-push org-goto-start-pos)
7346 (goto-char selected-point)
7347 (if (or (outline-invisible-p) (org-invisible-p2))
7348 (org-show-context 'org-goto)))
7349 (message "Quit"))))
7350
7351 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7352 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7353 (defvar org-goto-local-auto-isearch-map) ; defined below
7354
7355 (defun org-get-location (buf help)
7356 "Let the user select a location in the Org-mode buffer BUF.
7357 This function uses a recursive edit. It returns the selected position
7358 or nil."
7359 (org-no-popups
7360 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7361 (isearch-hide-immediately nil)
7362 (isearch-search-fun-function
7363 (lambda () 'org-goto-local-search-headings))
7364 (org-goto-selected-point org-goto-exit-command))
7365 (save-excursion
7366 (save-window-excursion
7367 (delete-other-windows)
7368 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7369 (org-pop-to-buffer-same-window
7370 (condition-case nil
7371 (make-indirect-buffer (current-buffer) "*org-goto*")
7372 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7373 (with-output-to-temp-buffer "*Org Help*"
7374 (princ (format help (if org-goto-auto-isearch
7375 " Just type for auto-isearch."
7376 " n/p/f/b/u to navigate, q to quit."))))
7377 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7378 (setq buffer-read-only nil)
7379 (let ((org-startup-truncated t)
7380 (org-startup-folded nil)
7381 (org-startup-align-all-tables nil))
7382 (org-mode)
7383 (org-overview))
7384 (setq buffer-read-only t)
7385 (if (and (boundp 'org-goto-start-pos)
7386 (integer-or-marker-p org-goto-start-pos))
7387 (let ((org-show-hierarchy-above t)
7388 (org-show-siblings t)
7389 (org-show-following-heading t))
7390 (goto-char org-goto-start-pos)
7391 (and (outline-invisible-p) (org-show-context)))
7392 (goto-char (point-min)))
7393 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7394 (message "Select location and press RET")
7395 (use-local-map org-goto-map)
7396 (recursive-edit)))
7397 (kill-buffer "*org-goto*")
7398 (cons org-goto-selected-point org-goto-exit-command))))
7399
7400 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7401 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7402 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7403 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7404
7405 (defun org-goto-local-search-headings (string bound noerror)
7406 "Search and make sure that any matches are in headlines."
7407 (catch 'return
7408 (while (if isearch-forward
7409 (search-forward string bound noerror)
7410 (search-backward string bound noerror))
7411 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7412 (and (member :headline context)
7413 (not (member :tags context))))
7414 (throw 'return (point))))))
7415
7416 (defun org-goto-local-auto-isearch ()
7417 "Start isearch."
7418 (interactive)
7419 (goto-char (point-min))
7420 (let ((keys (this-command-keys)))
7421 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7422 (isearch-mode t)
7423 (isearch-process-search-char (string-to-char keys)))))
7424
7425 (defun org-goto-ret (&optional arg)
7426 "Finish `org-goto' by going to the new location."
7427 (interactive "P")
7428 (setq org-goto-selected-point (point)
7429 org-goto-exit-command 'return)
7430 (throw 'exit nil))
7431
7432 (defun org-goto-left ()
7433 "Finish `org-goto' by going to the new location."
7434 (interactive)
7435 (if (org-at-heading-p)
7436 (progn
7437 (beginning-of-line 1)
7438 (setq org-goto-selected-point (point)
7439 org-goto-exit-command 'left)
7440 (throw 'exit nil))
7441 (user-error "Not on a heading")))
7442
7443 (defun org-goto-right ()
7444 "Finish `org-goto' by going to the new location."
7445 (interactive)
7446 (if (org-at-heading-p)
7447 (progn
7448 (setq org-goto-selected-point (point)
7449 org-goto-exit-command 'right)
7450 (throw 'exit nil))
7451 (user-error "Not on a heading")))
7452
7453 (defun org-goto-quit ()
7454 "Finish `org-goto' without cursor motion."
7455 (interactive)
7456 (setq org-goto-selected-point nil)
7457 (setq org-goto-exit-command 'quit)
7458 (throw 'exit nil))
7459
7460 ;;; Indirect buffer display of subtrees
7461
7462 (defvar org-indirect-dedicated-frame nil
7463 "This is the frame being used for indirect tree display.")
7464 (defvar org-last-indirect-buffer nil)
7465
7466 (defun org-tree-to-indirect-buffer (&optional arg)
7467 "Create indirect buffer and narrow it to current subtree.
7468 With a numerical prefix ARG, go up to this level and then take that tree.
7469 If ARG is negative, go up that many levels.
7470
7471 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7472 indirect buffer previously made with this command, to avoid proliferation of
7473 indirect buffers. However, when you call the command with a \
7474 \\[universal-argument] prefix, or
7475 when `org-indirect-buffer-display' is `new-frame', the last buffer
7476 is kept so that you can work with several indirect buffers at the same time.
7477 If `org-indirect-buffer-display' is `dedicated-frame', the \
7478 \\[universal-argument] prefix also
7479 requests that a new frame be made for the new buffer, so that the dedicated
7480 frame is not changed."
7481 (interactive "P")
7482 (let ((cbuf (current-buffer))
7483 (cwin (selected-window))
7484 (pos (point))
7485 beg end level heading ibuf)
7486 (save-excursion
7487 (org-back-to-heading t)
7488 (when (numberp arg)
7489 (setq level (org-outline-level))
7490 (if (< arg 0) (setq arg (+ level arg)))
7491 (while (> (setq level (org-outline-level)) arg)
7492 (org-up-heading-safe)))
7493 (setq beg (point)
7494 heading (org-get-heading))
7495 (org-end-of-subtree t t)
7496 (if (org-at-heading-p) (backward-char 1))
7497 (setq end (point)))
7498 (if (and (buffer-live-p org-last-indirect-buffer)
7499 (not (eq org-indirect-buffer-display 'new-frame))
7500 (not arg))
7501 (kill-buffer org-last-indirect-buffer))
7502 (setq ibuf (org-get-indirect-buffer cbuf)
7503 org-last-indirect-buffer ibuf)
7504 (cond
7505 ((or (eq org-indirect-buffer-display 'new-frame)
7506 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7507 (select-frame (make-frame))
7508 (delete-other-windows)
7509 (org-pop-to-buffer-same-window ibuf)
7510 (org-set-frame-title heading))
7511 ((eq org-indirect-buffer-display 'dedicated-frame)
7512 (raise-frame
7513 (select-frame (or (and org-indirect-dedicated-frame
7514 (frame-live-p org-indirect-dedicated-frame)
7515 org-indirect-dedicated-frame)
7516 (setq org-indirect-dedicated-frame (make-frame)))))
7517 (delete-other-windows)
7518 (org-pop-to-buffer-same-window ibuf)
7519 (org-set-frame-title (concat "Indirect: " heading)))
7520 ((eq org-indirect-buffer-display 'current-window)
7521 (org-pop-to-buffer-same-window ibuf))
7522 ((eq org-indirect-buffer-display 'other-window)
7523 (pop-to-buffer ibuf))
7524 (t (error "Invalid value")))
7525 (if (featurep 'xemacs)
7526 (save-excursion (org-mode) (turn-on-font-lock)))
7527 (narrow-to-region beg end)
7528 (show-all)
7529 (goto-char pos)
7530 (run-hook-with-args 'org-cycle-hook 'all)
7531 (and (window-live-p cwin) (select-window cwin))))
7532
7533 (defun org-get-indirect-buffer (&optional buffer)
7534 (setq buffer (or buffer (current-buffer)))
7535 (let ((n 1) (base (buffer-name buffer)) bname)
7536 (while (buffer-live-p
7537 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7538 (setq n (1+ n)))
7539 (condition-case nil
7540 (make-indirect-buffer buffer bname 'clone)
7541 (error (make-indirect-buffer buffer bname)))))
7542
7543 (defun org-set-frame-title (title)
7544 "Set the title of the current frame to the string TITLE."
7545 ;; FIXME: how to name a single frame in XEmacs???
7546 (unless (featurep 'xemacs)
7547 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7548
7549 ;;;; Structure editing
7550
7551 ;;; Inserting headlines
7552
7553 (defun org-previous-line-empty-p (&optional next)
7554 "Is the previous line a blank line?
7555 When NEXT is non-nil, check the next line instead."
7556 (save-excursion
7557 (and (not (bobp))
7558 (or (beginning-of-line (if next 2 0)) t)
7559 (save-match-data
7560 (looking-at "[ \t]*$")))))
7561
7562 (defun org-insert-heading (&optional arg invisible-ok)
7563 "Insert a new heading or an item with the same depth at point.
7564
7565 If point is at the beginning of a heading or a list item, insert
7566 a new heading or a new item above the current one. If point is
7567 at the beginning of a normal line, turn the line into a heading.
7568
7569 If point is in the middle of a headline or a list item, split the
7570 headline or the item and create a new headline/item with the text
7571 in the current line after point \(see `org-M-RET-may-split-line'
7572 on how to modify this behavior).
7573
7574 With one universal prefix argument, set the user option
7575 `org-insert-heading-respect-content' to t for the duration of
7576 the command. This modifies the behavior described above in this
7577 ways: on list items and at the beginning of normal lines, force
7578 the insertion of a heading after the current subtree.
7579
7580 With two universal prefix arguments, insert the heading at the
7581 end of the grandparent subtree. For example, if point is within
7582 a 2nd-level heading, then it will insert a 2nd-level heading at
7583 the end of the 1st-level parent heading.
7584
7585 When INVISIBLE-OK is set, stop at invisible headlines when going
7586 back. This is important for non-interactive uses of the
7587 command."
7588 (interactive "P")
7589 (if (org-called-interactively-p 'any) (org-reveal))
7590 (let ((itemp (org-in-item-p))
7591 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7592 (respect-content (or org-insert-heading-respect-content
7593 (equal arg '(4))))
7594 (initial-content "")
7595 (adjust-empty-lines t))
7596
7597 (cond
7598
7599 ((or (= (buffer-size) 0)
7600 (and (not (save-excursion
7601 (and (ignore-errors (org-back-to-heading invisible-ok))
7602 (org-at-heading-p))))
7603 (or arg (not itemp))))
7604 ;; At beginning of buffer or so high up that only a heading
7605 ;; makes sense.
7606 (cond ((and (bolp) (not respect-content)) (insert "* "))
7607 ((not respect-content)
7608 (unless may-split (end-of-line))
7609 (insert "\n* "))
7610 ((re-search-forward org-outline-regexp-bol nil t)
7611 (beginning-of-line)
7612 (insert "* \n")
7613 (backward-char))
7614 (t (goto-char (point-max))
7615 (insert "\n* ")))
7616 (run-hooks 'org-insert-heading-hook))
7617
7618 ((and itemp (not (member arg '((4) (16)))))
7619 ;; Insert an item
7620 (org-insert-item))
7621
7622 (t
7623 ;; Maybe move at the end of the subtree
7624 (when (equal arg '(16))
7625 (org-up-heading-safe)
7626 (org-end-of-subtree t))
7627 ;; Insert a heading
7628 (save-restriction
7629 (widen)
7630 (let* ((level nil)
7631 (on-heading (org-at-heading-p))
7632 (empty-line-p (if on-heading
7633 (org-previous-line-empty-p)
7634 ;; We will decide later
7635 nil))
7636 ;; Get a level string to fall back on
7637 (fix-level
7638 (if (org-before-first-heading-p) "*"
7639 (save-excursion
7640 (org-back-to-heading t)
7641 (if (org-previous-line-empty-p) (setq empty-line-p t))
7642 (looking-at org-outline-regexp)
7643 (make-string (1- (length (match-string 0))) ?*))))
7644 (stars
7645 (save-excursion
7646 (condition-case nil
7647 (progn
7648 (org-back-to-heading invisible-ok)
7649 (when (and (not on-heading)
7650 (featurep 'org-inlinetask)
7651 (integerp org-inlinetask-min-level)
7652 (>= (length (match-string 0))
7653 org-inlinetask-min-level))
7654 ;; Find a heading level before the inline task
7655 (while (and (setq level (org-up-heading-safe))
7656 (>= level org-inlinetask-min-level)))
7657 (if (org-at-heading-p)
7658 (org-back-to-heading invisible-ok)
7659 (error "This should not happen")))
7660 (unless (and (save-excursion
7661 (save-match-data
7662 (org-backward-heading-same-level
7663 1 invisible-ok))
7664 (= (point) (match-beginning 0)))
7665 (not (org-previous-line-empty-p t)))
7666 (setq empty-line-p (or empty-line-p
7667 (org-previous-line-empty-p))))
7668 (match-string 0))
7669 (error (or fix-level "* ")))))
7670 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7671 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7672 pos hide-previous previous-pos)
7673
7674 ;; If we insert after content, move there and clean up whitespace
7675 (when (and respect-content
7676 (not (org-looking-at-p org-outline-regexp-bol)))
7677 (if (not (org-before-first-heading-p))
7678 (org-end-of-subtree nil t)
7679 (re-search-forward org-outline-regexp-bol)
7680 (beginning-of-line 0))
7681 (skip-chars-backward " \r\n")
7682 (and (not (looking-back "^\*+" (line-beginning-position)))
7683 (looking-at "[ \t]+") (replace-match ""))
7684 (unless (eobp) (forward-char 1))
7685 (when (looking-at "^\\*")
7686 (unless (bobp) (backward-char 1))
7687 (insert "\n")))
7688
7689 ;; If we are splitting, grab the text that should be moved to the new headline
7690 (when may-split
7691 (if (org-on-heading-p)
7692 ;; This is a heading, we split intelligently (keeping tags)
7693 (let ((pos (point)))
7694 (goto-char (point-at-bol))
7695 (unless (looking-at org-complex-heading-regexp)
7696 (error "This should not happen"))
7697 (when (and (match-beginning 4)
7698 (> pos (match-beginning 4))
7699 (< pos (match-end 4)))
7700 (setq initial-content (buffer-substring pos (match-end 4)))
7701 (goto-char pos)
7702 (delete-region (point) (match-end 4))
7703 (if (looking-at "[ \t]*$")
7704 (replace-match "")
7705 (insert (make-string (length initial-content) ?\ )))
7706 (setq initial-content (org-trim initial-content)))
7707 (goto-char pos))
7708 ;; a normal line
7709 (setq initial-content
7710 (org-trim (buffer-substring (point) (point-at-eol))))
7711 (delete-region (point) (point-at-eol))))
7712
7713 ;; If we are at the beginning of the line, insert before it. Else after
7714 (cond
7715 ((and (bolp) (looking-at "[ \t]*$")))
7716 ((and (bolp) (not (looking-at "[ \t]*$")))
7717 (open-line 1))
7718 (t
7719 (goto-char (point-at-eol))
7720 (insert "\n")))
7721
7722 ;; Insert the new heading
7723 (insert stars)
7724 (just-one-space)
7725 (insert initial-content)
7726 (when adjust-empty-lines
7727 (if (or (not blank)
7728 (and blank (not (org-previous-line-empty-p))))
7729 (org-N-empty-lines-before-current (if blank 1 0))))
7730 (run-hooks 'org-insert-heading-hook)))))))
7731
7732 (defun org-N-empty-lines-before-current (N)
7733 "Make the number of empty lines before current exactly N.
7734 So this will delete or add empty lines."
7735 (save-excursion
7736 (beginning-of-line)
7737 (let ((p (point)))
7738 (skip-chars-backward " \r\t\n")
7739 (unless (bolp) (forward-line))
7740 (delete-region (point) p))
7741 (when (> N 0) (insert (make-string N ?\n)))))
7742
7743 (defun org-get-heading (&optional no-tags no-todo)
7744 "Return the heading of the current entry, without the stars.
7745 When NO-TAGS is non-nil, don't include tags.
7746 When NO-TODO is non-nil, don't include TODO keywords."
7747 (save-excursion
7748 (org-back-to-heading t)
7749 (cond
7750 ((and no-tags no-todo)
7751 (looking-at org-complex-heading-regexp)
7752 (match-string 4))
7753 (no-tags
7754 (looking-at (concat org-outline-regexp
7755 "\\(.*?\\)"
7756 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7757 (match-string 1))
7758 (no-todo
7759 (looking-at org-todo-line-regexp)
7760 (match-string 3))
7761 (t (looking-at org-heading-regexp)
7762 (match-string 2)))))
7763
7764 (defvar orgstruct-mode) ; defined below
7765
7766 (defun org-heading-components ()
7767 "Return the components of the current heading.
7768 This is a list with the following elements:
7769 - the level as an integer
7770 - the reduced level, different if `org-odd-levels-only' is set.
7771 - the TODO keyword, or nil
7772 - the priority character, like ?A, or nil if no priority is given
7773 - the headline text itself, or the tags string if no headline text
7774 - the tags string, or nil."
7775 (save-excursion
7776 (org-back-to-heading t)
7777 (if (let (case-fold-search)
7778 (looking-at
7779 (if orgstruct-mode
7780 org-heading-regexp
7781 org-complex-heading-regexp)))
7782 (if orgstruct-mode
7783 (list (length (match-string 1))
7784 (org-reduced-level (length (match-string 1)))
7785 nil
7786 nil
7787 (match-string 2)
7788 nil)
7789 (list (length (match-string 1))
7790 (org-reduced-level (length (match-string 1)))
7791 (org-match-string-no-properties 2)
7792 (and (match-end 3) (aref (match-string 3) 2))
7793 (org-match-string-no-properties 4)
7794 (org-match-string-no-properties 5))))))
7795
7796 (defun org-get-entry ()
7797 "Get the entry text, after heading, entire subtree."
7798 (save-excursion
7799 (org-back-to-heading t)
7800 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7801
7802 (defun org-insert-heading-after-current ()
7803 "Insert a new heading with same level as current, after current subtree."
7804 (interactive)
7805 (org-back-to-heading)
7806 (org-insert-heading)
7807 (org-move-subtree-down)
7808 (end-of-line 1))
7809
7810 (defun org-insert-heading-respect-content (&optional invisible-ok)
7811 "Insert heading with `org-insert-heading-respect-content' set to t."
7812 (interactive)
7813 (org-insert-heading '(4) invisible-ok))
7814
7815 (defun org-insert-todo-heading-respect-content (&optional force-state)
7816 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7817 (interactive)
7818 (org-insert-todo-heading force-state '(4)))
7819
7820 (defun org-insert-todo-heading (arg &optional force-heading)
7821 "Insert a new heading with the same level and TODO state as current heading.
7822 If the heading has no TODO state, or if the state is DONE, use the first
7823 state (TODO by default). Also with one prefix arg, force first state. With
7824 two prefix args, force inserting at the end of the parent subtree."
7825 (interactive "P")
7826 (when (or force-heading (not (org-insert-item 'checkbox)))
7827 (org-insert-heading (or (and (equal arg '(16)) '(16))
7828 force-heading))
7829 (save-excursion
7830 (org-back-to-heading)
7831 (outline-previous-heading)
7832 (looking-at org-todo-line-regexp))
7833 (let*
7834 ((new-mark-x
7835 (if (or (equal arg '(4))
7836 (not (match-beginning 2))
7837 (member (match-string 2) org-done-keywords))
7838 (car org-todo-keywords-1)
7839 (match-string 2)))
7840 (new-mark
7841 (or
7842 (run-hook-with-args-until-success
7843 'org-todo-get-default-hook new-mark-x nil)
7844 new-mark-x)))
7845 (beginning-of-line 1)
7846 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7847 (if org-treat-insert-todo-heading-as-state-change
7848 (org-todo new-mark)
7849 (insert new-mark " "))))
7850 (when org-provide-todo-statistics
7851 (org-update-parent-todo-statistics))))
7852
7853 (defun org-insert-subheading (arg)
7854 "Insert a new subheading and demote it.
7855 Works for outline headings and for plain lists alike."
7856 (interactive "P")
7857 (org-insert-heading arg)
7858 (cond
7859 ((org-at-heading-p) (org-do-demote))
7860 ((org-at-item-p) (org-indent-item))))
7861
7862 (defun org-insert-todo-subheading (arg)
7863 "Insert a new subheading with TODO keyword or checkbox and demote it.
7864 Works for outline headings and for plain lists alike."
7865 (interactive "P")
7866 (org-insert-todo-heading arg)
7867 (cond
7868 ((org-at-heading-p) (org-do-demote))
7869 ((org-at-item-p) (org-indent-item))))
7870
7871 ;;; Promotion and Demotion
7872
7873 (defvar org-after-demote-entry-hook nil
7874 "Hook run after an entry has been demoted.
7875 The cursor will be at the beginning of the entry.
7876 When a subtree is being demoted, the hook will be called for each node.")
7877
7878 (defvar org-after-promote-entry-hook nil
7879 "Hook run after an entry has been promoted.
7880 The cursor will be at the beginning of the entry.
7881 When a subtree is being promoted, the hook will be called for each node.")
7882
7883 (defun org-promote-subtree ()
7884 "Promote the entire subtree.
7885 See also `org-promote'."
7886 (interactive)
7887 (save-excursion
7888 (org-with-limited-levels (org-map-tree 'org-promote)))
7889 (org-fix-position-after-promote))
7890
7891 (defun org-demote-subtree ()
7892 "Demote the entire subtree. See `org-demote'.
7893 See also `org-promote'."
7894 (interactive)
7895 (save-excursion
7896 (org-with-limited-levels (org-map-tree 'org-demote)))
7897 (org-fix-position-after-promote))
7898
7899
7900 (defun org-do-promote ()
7901 "Promote the current heading higher up the tree.
7902 If the region is active in `transient-mark-mode', promote all headings
7903 in the region."
7904 (interactive)
7905 (save-excursion
7906 (if (org-region-active-p)
7907 (org-map-region 'org-promote (region-beginning) (region-end))
7908 (org-promote)))
7909 (org-fix-position-after-promote))
7910
7911 (defun org-do-demote ()
7912 "Demote the current heading lower down the tree.
7913 If the region is active in `transient-mark-mode', demote all headings
7914 in the region."
7915 (interactive)
7916 (save-excursion
7917 (if (org-region-active-p)
7918 (org-map-region 'org-demote (region-beginning) (region-end))
7919 (org-demote)))
7920 (org-fix-position-after-promote))
7921
7922 (defun org-fix-position-after-promote ()
7923 "Make sure that after pro/demotion cursor position is right."
7924 (let ((pos (point)))
7925 (when (save-excursion
7926 (beginning-of-line 1)
7927 (looking-at org-todo-line-regexp)
7928 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7929 (cond ((eobp) (insert " "))
7930 ((eolp) (insert " "))
7931 ((equal (char-after) ?\ ) (forward-char 1))))))
7932
7933 (defun org-current-level ()
7934 "Return the level of the current entry, or nil if before the first headline.
7935 The level is the number of stars at the beginning of the headline."
7936 (save-excursion
7937 (org-with-limited-levels
7938 (if (ignore-errors (org-back-to-heading t))
7939 (funcall outline-level)))))
7940
7941 (defun org-get-previous-line-level ()
7942 "Return the outline depth of the last headline before the current line.
7943 Returns 0 for the first headline in the buffer, and nil if before the
7944 first headline."
7945 (and (org-current-level)
7946 (or (and (/= (line-beginning-position) (point-min))
7947 (save-excursion (beginning-of-line 0) (org-current-level)))
7948 0)))
7949
7950 (defun org-reduced-level (l)
7951 "Compute the effective level of a heading.
7952 This takes into account the setting of `org-odd-levels-only'."
7953 (cond
7954 ((zerop l) 0)
7955 (org-odd-levels-only (1+ (floor (/ l 2))))
7956 (t l)))
7957
7958 (defun org-level-increment ()
7959 "Return the number of stars that will be added or removed at a
7960 time to headlines when structure editing, based on the value of
7961 `org-odd-levels-only'."
7962 (if org-odd-levels-only 2 1))
7963
7964 (defun org-get-valid-level (level &optional change)
7965 "Rectify a level change under the influence of `org-odd-levels-only'
7966 LEVEL is a current level, CHANGE is by how much the level should be
7967 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7968 even level numbers will become the next higher odd number."
7969 (if org-odd-levels-only
7970 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7971 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7972 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7973 (max 1 (+ level (or change 0)))))
7974
7975 (if (boundp 'define-obsolete-function-alias)
7976 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7977 (define-obsolete-function-alias 'org-get-legal-level
7978 'org-get-valid-level)
7979 (define-obsolete-function-alias 'org-get-legal-level
7980 'org-get-valid-level "23.1")))
7981
7982 (defun org-promote ()
7983 "Promote the current heading higher up the tree.
7984 If the region is active in `transient-mark-mode', promote 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 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7991 (diff (abs (- level (length up-head) -1))))
7992 (cond ((and (= level 1) org-called-with-limited-levels
7993 org-allow-promoting-top-level-subtree)
7994 (replace-match "# " nil t))
7995 ((= level 1)
7996 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7997 (t (replace-match up-head nil t)))
7998 ;; Fixup tag positioning
7999 (unless (= level 1)
8000 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8001 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8002 (run-hooks 'org-after-promote-entry-hook)))
8003
8004 (defun org-demote ()
8005 "Demote the current heading lower down the tree.
8006 If the region is active in `transient-mark-mode', demote all headings
8007 in the region."
8008 (org-back-to-heading t)
8009 (let* ((level (save-match-data (funcall outline-level)))
8010 (after-change-functions (remove 'flyspell-after-change-function
8011 after-change-functions))
8012 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8013 (diff (abs (- level (length down-head) -1))))
8014 (replace-match down-head nil t)
8015 ;; Fixup tag positioning
8016 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8017 (if org-adapt-indentation (org-fixup-indentation diff))
8018 (run-hooks 'org-after-demote-entry-hook)))
8019
8020 (defun org-cycle-level ()
8021 "Cycle the level of an empty headline through possible states.
8022 This goes first to child, then to parent, level, then up the hierarchy.
8023 After top level, it switches back to sibling level."
8024 (interactive)
8025 (let ((org-adapt-indentation nil))
8026 (when (org-point-at-end-of-empty-headline)
8027 (setq this-command 'org-cycle-level) ; Only needed for caching
8028 (let ((cur-level (org-current-level))
8029 (prev-level (org-get-previous-line-level)))
8030 (cond
8031 ;; If first headline in file, promote to top-level.
8032 ((= prev-level 0)
8033 (loop repeat (/ (- cur-level 1) (org-level-increment))
8034 do (org-do-promote)))
8035 ;; If same level as prev, demote one.
8036 ((= prev-level cur-level)
8037 (org-do-demote))
8038 ;; If parent is top-level, promote to top level if not already.
8039 ((= prev-level 1)
8040 (loop repeat (/ (- cur-level 1) (org-level-increment))
8041 do (org-do-promote)))
8042 ;; If top-level, return to prev-level.
8043 ((= cur-level 1)
8044 (loop repeat (/ (- prev-level 1) (org-level-increment))
8045 do (org-do-demote)))
8046 ;; If less than prev-level, promote one.
8047 ((< cur-level prev-level)
8048 (org-do-promote))
8049 ;; If deeper than prev-level, promote until higher than
8050 ;; prev-level.
8051 ((> cur-level prev-level)
8052 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8053 do (org-do-promote))))
8054 t))))
8055
8056 (defun org-map-tree (fun)
8057 "Call FUN for every heading underneath the current one."
8058 (org-back-to-heading)
8059 (let ((level (funcall outline-level)))
8060 (save-excursion
8061 (funcall fun)
8062 (while (and (progn
8063 (outline-next-heading)
8064 (> (funcall outline-level) level))
8065 (not (eobp)))
8066 (funcall fun)))))
8067
8068 (defun org-map-region (fun beg end)
8069 "Call FUN for every heading between BEG and END."
8070 (let ((org-ignore-region t))
8071 (save-excursion
8072 (setq end (copy-marker end))
8073 (goto-char beg)
8074 (if (and (re-search-forward org-outline-regexp-bol nil t)
8075 (< (point) end))
8076 (funcall fun))
8077 (while (and (progn
8078 (outline-next-heading)
8079 (< (point) end))
8080 (not (eobp)))
8081 (funcall fun)))))
8082
8083 (defvar org-property-end-re) ; silence byte-compiler
8084 (defun org-fixup-indentation (diff)
8085 "Change the indentation in the current entry by DIFF.
8086 However, if any line in the current entry has no indentation, or if it
8087 would end up with no indentation after the change, nothing at all is done."
8088 (save-excursion
8089 (let ((end (save-excursion (outline-next-heading)
8090 (point-marker)))
8091 (prohibit (if (> diff 0)
8092 "^\\S-"
8093 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8094 col)
8095 (unless (save-excursion (end-of-line 1)
8096 (re-search-forward prohibit end t))
8097 (while (and (< (point) end)
8098 (re-search-forward "^[ \t]+" end t))
8099 (goto-char (match-end 0))
8100 (setq col (current-column))
8101 (if (< diff 0) (replace-match ""))
8102 (org-indent-to-column (+ diff col))))
8103 (move-marker end nil))))
8104
8105 (defun org-convert-to-odd-levels ()
8106 "Convert an org-mode file with all levels allowed to one with odd levels.
8107 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8108 level 5 etc."
8109 (interactive)
8110 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8111 (let ((outline-level 'org-outline-level)
8112 (org-odd-levels-only nil) n)
8113 (save-excursion
8114 (goto-char (point-min))
8115 (while (re-search-forward "^\\*\\*+ " nil t)
8116 (setq n (- (length (match-string 0)) 2))
8117 (while (>= (setq n (1- n)) 0)
8118 (org-demote))
8119 (end-of-line 1))))))
8120
8121 (defun org-convert-to-oddeven-levels ()
8122 "Convert an org-mode file with only odd levels to one with odd/even levels.
8123 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8124 file contains a section with an even level, conversion would
8125 destroy the structure of the file. An error is signaled in this
8126 case."
8127 (interactive)
8128 (goto-char (point-min))
8129 ;; First check if there are no even levels
8130 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8131 (org-show-context t)
8132 (error "Not all levels are odd in this file. Conversion not possible"))
8133 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8134 (let ((outline-regexp org-outline-regexp)
8135 (outline-level 'org-outline-level)
8136 (org-odd-levels-only nil) n)
8137 (save-excursion
8138 (goto-char (point-min))
8139 (while (re-search-forward "^\\*\\*+ " nil t)
8140 (setq n (/ (1- (length (match-string 0))) 2))
8141 (while (>= (setq n (1- n)) 0)
8142 (org-promote))
8143 (end-of-line 1))))))
8144
8145 (defun org-tr-level (n)
8146 "Make N odd if required."
8147 (if org-odd-levels-only (1+ (/ n 2)) n))
8148
8149 ;;; Vertical tree motion, cutting and pasting of subtrees
8150
8151 (defun org-move-subtree-up (&optional arg)
8152 "Move the current subtree up past ARG headlines of the same level."
8153 (interactive "p")
8154 (org-move-subtree-down (- (prefix-numeric-value arg))))
8155
8156 (defun org-move-subtree-down (&optional arg)
8157 "Move the current subtree down past ARG headlines of the same level."
8158 (interactive "p")
8159 (setq arg (prefix-numeric-value arg))
8160 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8161 'org-get-last-sibling))
8162 (ins-point (make-marker))
8163 (cnt (abs arg))
8164 (col (current-column))
8165 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8166 ;; Select the tree
8167 (org-back-to-heading)
8168 (setq beg0 (point))
8169 (save-excursion
8170 (setq ne-beg (org-back-over-empty-lines))
8171 (setq beg (point)))
8172 (save-match-data
8173 (save-excursion (outline-end-of-heading)
8174 (setq folded (outline-invisible-p)))
8175 (progn (org-end-of-subtree nil t)
8176 (unless (eobp) (backward-char))))
8177 (outline-next-heading)
8178 (setq ne-end (org-back-over-empty-lines))
8179 (setq end (point))
8180 (goto-char beg0)
8181 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8182 ;; include less whitespace
8183 (save-excursion
8184 (goto-char beg)
8185 (forward-line (- ne-beg ne-end))
8186 (setq beg (point))))
8187 ;; Find insertion point, with error handling
8188 (while (> cnt 0)
8189 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8190 (progn (goto-char beg0)
8191 (user-error "Cannot move past superior level or buffer limit")))
8192 (setq cnt (1- cnt)))
8193 (if (> arg 0)
8194 ;; Moving forward - still need to move over subtree
8195 (progn (org-end-of-subtree t t)
8196 (save-excursion
8197 (org-back-over-empty-lines)
8198 (or (bolp) (newline)))))
8199 (setq ne-ins (org-back-over-empty-lines))
8200 (move-marker ins-point (point))
8201 (setq txt (buffer-substring beg end))
8202 (org-save-markers-in-region beg end)
8203 (delete-region beg end)
8204 (org-remove-empty-overlays-at beg)
8205 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8206 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8207 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8208 (let ((bbb (point)))
8209 (insert-before-markers txt)
8210 (org-reinstall-markers-in-region bbb)
8211 (move-marker ins-point bbb))
8212 (or (bolp) (insert "\n"))
8213 (setq ins-end (point))
8214 (goto-char ins-point)
8215 (org-skip-whitespace)
8216 (when (and (< arg 0)
8217 (org-first-sibling-p)
8218 (> ne-ins ne-beg))
8219 ;; Move whitespace back to beginning
8220 (save-excursion
8221 (goto-char ins-end)
8222 (let ((kill-whole-line t))
8223 (kill-line (- ne-ins ne-beg)) (point)))
8224 (insert (make-string (- ne-ins ne-beg) ?\n)))
8225 (move-marker ins-point nil)
8226 (if folded
8227 (hide-subtree)
8228 (org-show-entry)
8229 (show-children)
8230 (org-cycle-hide-drawers 'children))
8231 (org-clean-visibility-after-subtree-move)
8232 ;; move back to the initial column we were at
8233 (move-to-column col)))
8234
8235 (defvar org-subtree-clip ""
8236 "Clipboard for cut and paste of subtrees.
8237 This is actually only a copy of the kill, because we use the normal kill
8238 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8239
8240 (defvar org-subtree-clip-folded nil
8241 "Was the last copied subtree folded?
8242 This is used to fold the tree back after pasting.")
8243
8244 (defun org-cut-subtree (&optional n)
8245 "Cut the current subtree into the clipboard.
8246 With prefix arg N, cut this many sequential subtrees.
8247 This is a short-hand for marking the subtree and then cutting it."
8248 (interactive "p")
8249 (org-copy-subtree n 'cut))
8250
8251 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8252 "Copy the current subtree it in the clipboard.
8253 With prefix arg N, copy this many sequential subtrees.
8254 This is a short-hand for marking the subtree and then copying it.
8255 If CUT is non-nil, actually cut the subtree.
8256 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8257 of some markers in the region, even if CUT is non-nil. This is
8258 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8259 (interactive "p")
8260 (let (beg end folded (beg0 (point)))
8261 (if (org-called-interactively-p 'any)
8262 (org-back-to-heading nil) ; take what looks like a subtree
8263 (org-back-to-heading t)) ; take what is really there
8264 (setq beg (point))
8265 (skip-chars-forward " \t\r\n")
8266 (save-match-data
8267 (if nosubtrees
8268 (outline-next-heading)
8269 (save-excursion (outline-end-of-heading)
8270 (setq folded (outline-invisible-p)))
8271 (condition-case nil
8272 (org-forward-heading-same-level (1- n) t)
8273 (error nil))
8274 (org-end-of-subtree t t)))
8275 (setq end (point))
8276 (goto-char beg0)
8277 (when (> end beg)
8278 (setq org-subtree-clip-folded folded)
8279 (when (or cut force-store-markers)
8280 (org-save-markers-in-region beg end))
8281 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8282 (setq org-subtree-clip (current-kill 0))
8283 (message "%s: Subtree(s) with %d characters"
8284 (if cut "Cut" "Copied")
8285 (length org-subtree-clip)))))
8286
8287 (defun org-paste-subtree (&optional level tree for-yank)
8288 "Paste the clipboard as a subtree, with modification of headline level.
8289 The entire subtree is promoted or demoted in order to match a new headline
8290 level.
8291
8292 If the cursor is at the beginning of a headline, the same level as
8293 that headline is used to paste the tree.
8294
8295 If not, the new level is derived from the *visible* headings
8296 before and after the insertion point, and taken to be the inferior headline
8297 level of the two. So if the previous visible heading is level 3 and the
8298 next is level 4 (or vice versa), level 4 will be used for insertion.
8299 This makes sure that the subtree remains an independent subtree and does
8300 not swallow low level entries.
8301
8302 You can also force a different level, either by using a numeric prefix
8303 argument, or by inserting the heading marker by hand. For example, if the
8304 cursor is after \"*****\", then the tree will be shifted to level 5.
8305
8306 If optional TREE is given, use this text instead of the kill ring.
8307
8308 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8309 move back over whitespace before inserting, and move point to the end of
8310 the inserted text when done."
8311 (interactive "P")
8312 (setq tree (or tree (and kill-ring (current-kill 0))))
8313 (unless (org-kill-is-subtree-p tree)
8314 (user-error "%s"
8315 (substitute-command-keys
8316 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8317 (org-with-limited-levels
8318 (let* ((visp (not (outline-invisible-p)))
8319 (txt tree)
8320 (^re_ "\\(\\*+\\)[ \t]*")
8321 (old-level (if (string-match org-outline-regexp-bol txt)
8322 (- (match-end 0) (match-beginning 0) 1)
8323 -1))
8324 (force-level (cond (level (prefix-numeric-value level))
8325 ((and (looking-at "[ \t]*$")
8326 (string-match
8327 "^\\*+$" (buffer-substring
8328 (point-at-bol) (point))))
8329 (- (match-end 0) (match-beginning 0)))
8330 ((and (bolp)
8331 (looking-at org-outline-regexp))
8332 (- (match-end 0) (point) 1))))
8333 (previous-level (save-excursion
8334 (condition-case nil
8335 (progn
8336 (outline-previous-visible-heading 1)
8337 (if (looking-at ^re_)
8338 (- (match-end 0) (match-beginning 0) 1)
8339 1))
8340 (error 1))))
8341 (next-level (save-excursion
8342 (condition-case nil
8343 (progn
8344 (or (looking-at org-outline-regexp)
8345 (outline-next-visible-heading 1))
8346 (if (looking-at ^re_)
8347 (- (match-end 0) (match-beginning 0) 1)
8348 1))
8349 (error 1))))
8350 (new-level (or force-level (max previous-level next-level)))
8351 (shift (if (or (= old-level -1)
8352 (= new-level -1)
8353 (= old-level new-level))
8354 0
8355 (- new-level old-level)))
8356 (delta (if (> shift 0) -1 1))
8357 (func (if (> shift 0) 'org-demote 'org-promote))
8358 (org-odd-levels-only nil)
8359 beg end newend)
8360 ;; Remove the forced level indicator
8361 (if force-level
8362 (delete-region (point-at-bol) (point)))
8363 ;; Paste
8364 (beginning-of-line (if (bolp) 1 2))
8365 (setq beg (point))
8366 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8367 (insert-before-markers txt)
8368 (unless (string-match "\n\\'" txt) (insert "\n"))
8369 (setq newend (point))
8370 (org-reinstall-markers-in-region beg)
8371 (setq end (point))
8372 (goto-char beg)
8373 (skip-chars-forward " \t\n\r")
8374 (setq beg (point))
8375 (if (and (outline-invisible-p) visp)
8376 (save-excursion (outline-show-heading)))
8377 ;; Shift if necessary
8378 (unless (= shift 0)
8379 (save-restriction
8380 (narrow-to-region beg end)
8381 (while (not (= shift 0))
8382 (org-map-region func (point-min) (point-max))
8383 (setq shift (+ delta shift)))
8384 (goto-char (point-min))
8385 (setq newend (point-max))))
8386 (when (or (org-called-interactively-p 'interactive) for-yank)
8387 (message "Clipboard pasted as level %d subtree" new-level))
8388 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8389 kill-ring
8390 (eq org-subtree-clip (current-kill 0))
8391 org-subtree-clip-folded)
8392 ;; The tree was folded before it was killed/copied
8393 (hide-subtree))
8394 (and for-yank (goto-char newend)))))
8395
8396 (defun org-kill-is-subtree-p (&optional txt)
8397 "Check if the current kill is an outline subtree, or a set of trees.
8398 Returns nil if kill does not start with a headline, or if the first
8399 headline level is not the largest headline level in the tree.
8400 So this will actually accept several entries of equal levels as well,
8401 which is OK for `org-paste-subtree'.
8402 If optional TXT is given, check this string instead of the current kill."
8403 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8404 (re (org-get-limited-outline-regexp))
8405 (^re (concat "^" re))
8406 (start-level (and kill
8407 (string-match
8408 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8409 kill)
8410 (- (match-end 2) (match-beginning 2) 1)))
8411 (start (1+ (or (match-beginning 2) -1))))
8412 (if (not start-level)
8413 (progn
8414 nil) ;; does not even start with a heading
8415 (catch 'exit
8416 (while (setq start (string-match ^re kill (1+ start)))
8417 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8418 (throw 'exit nil)))
8419 t))))
8420
8421 (defvar org-markers-to-move nil
8422 "Markers that should be moved with a cut-and-paste operation.
8423 Those markers are stored together with their positions relative to
8424 the start of the region.")
8425
8426 (defun org-save-markers-in-region (beg end)
8427 "Check markers in region.
8428 If these markers are between BEG and END, record their position relative
8429 to BEG, so that after moving the block of text, we can put the markers back
8430 into place.
8431 This function gets called just before an entry or tree gets cut from the
8432 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8433 called immediately, to move the markers with the entries."
8434 (setq org-markers-to-move nil)
8435 (when (featurep 'org-clock)
8436 (org-clock-save-markers-for-cut-and-paste beg end))
8437 (when (featurep 'org-agenda)
8438 (org-agenda-save-markers-for-cut-and-paste beg end)))
8439
8440 (defun org-check-and-save-marker (marker beg end)
8441 "Check if MARKER is between BEG and END.
8442 If yes, remember the marker and the distance to BEG."
8443 (when (and (marker-buffer marker)
8444 (equal (marker-buffer marker) (current-buffer)))
8445 (if (and (>= marker beg) (< marker end))
8446 (push (cons marker (- marker beg)) org-markers-to-move))))
8447
8448 (defun org-reinstall-markers-in-region (beg)
8449 "Move all remembered markers to their position relative to BEG."
8450 (mapc (lambda (x)
8451 (move-marker (car x) (+ beg (cdr x))))
8452 org-markers-to-move)
8453 (setq org-markers-to-move nil))
8454
8455 (defun org-narrow-to-subtree ()
8456 "Narrow buffer to the current subtree."
8457 (interactive)
8458 (save-excursion
8459 (save-match-data
8460 (org-with-limited-levels
8461 (narrow-to-region
8462 (progn (org-back-to-heading t) (point))
8463 (progn (org-end-of-subtree t t)
8464 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8465 (point)))))))
8466
8467 (defun org-narrow-to-block ()
8468 "Narrow buffer to the current block."
8469 (interactive)
8470 (let* ((case-fold-search t)
8471 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8472 "^[ \t]*#\\+end_.*")))
8473 (if blockp
8474 (narrow-to-region (car blockp) (cdr blockp))
8475 (user-error "Not in a block"))))
8476
8477 (eval-when-compile
8478 (defvar org-property-drawer-re))
8479
8480 (defvar org-property-start-re) ;; defined below
8481 (defun org-clone-subtree-with-time-shift (n &optional shift)
8482 "Clone the task (subtree) at point N times.
8483 The clones will be inserted as siblings.
8484
8485 In interactive use, the user will be prompted for the number of
8486 clones to be produced. If the entry has a timestamp, the user
8487 will also be prompted for a time shift, which may be a repeater
8488 as used in time stamps, for example `+3d'. To disable this,
8489 you can call the function with a universal prefix argument.
8490
8491 When a valid repeater is given and the entry contains any time
8492 stamps, the clones will become a sequence in time, with time
8493 stamps in the subtree shifted for each clone produced. If SHIFT
8494 is nil or the empty string, time stamps will be left alone. The
8495 ID property of the original subtree is removed.
8496
8497 If the original subtree did contain time stamps with a repeater,
8498 the following will happen:
8499 - the repeater will be removed in each clone
8500 - an additional clone will be produced, with the current, unshifted
8501 date(s) in the entry.
8502 - the original entry will be placed *after* all the clones, with
8503 repeater intact.
8504 - the start days in the repeater in the original entry will be shifted
8505 to past the last clone.
8506 In this way you can spell out a number of instances of a repeating task,
8507 and still retain the repeater to cover future instances of the task."
8508 (interactive "nNumber of clones to produce: ")
8509 (let ((shift
8510 (or shift
8511 (if (and (not (equal current-prefix-arg '(4)))
8512 (save-excursion
8513 (re-search-forward org-ts-regexp-both
8514 (save-excursion
8515 (org-end-of-subtree t)
8516 (point)) t)))
8517 (read-from-minibuffer
8518 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8519 ""))) ;; No time shift
8520 (n-no-remove -1)
8521 (drawer-re org-drawer-regexp)
8522 beg end template task idprop
8523 shift-n shift-what doshift nmin nmax)
8524 (if (not (and (integerp n) (> n 0)))
8525 (error "Invalid number of replications %s" n))
8526 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8527 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8528 shift)))
8529 (error "Invalid shift specification %s" shift))
8530 (when doshift
8531 (setq shift-n (string-to-number (match-string 1 shift))
8532 shift-what (cdr (assoc (match-string 2 shift)
8533 '(("d" . day) ("w" . week)
8534 ("m" . month) ("y" . year))))))
8535 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8536 (setq nmin 1 nmax n)
8537 (org-back-to-heading t)
8538 (setq beg (point))
8539 (setq idprop (org-entry-get nil "ID"))
8540 (org-end-of-subtree t t)
8541 (or (bolp) (insert "\n"))
8542 (setq end (point))
8543 (setq template (buffer-substring beg end))
8544 (when (and doshift
8545 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8546 (delete-region beg end)
8547 (setq end beg)
8548 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8549 (goto-char end)
8550 (loop for n from nmin to nmax do
8551 ;; prepare clone
8552 (with-temp-buffer
8553 (insert template)
8554 (org-mode)
8555 (goto-char (point-min))
8556 (org-show-subtree)
8557 (and idprop (if org-clone-delete-id
8558 (org-entry-delete nil "ID")
8559 (org-id-get-create t)))
8560 (unless (= n 0)
8561 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8562 (kill-whole-line))
8563 (goto-char (point-min))
8564 (while (re-search-forward drawer-re nil t)
8565 (mapc (lambda (d)
8566 (org-remove-empty-drawer-at d (point))) org-drawers)))
8567 (goto-char (point-min))
8568 (when doshift
8569 (while (re-search-forward org-ts-regexp-both nil t)
8570 (org-timestamp-change (* n shift-n) shift-what))
8571 (unless (= n n-no-remove)
8572 (goto-char (point-min))
8573 (while (re-search-forward org-ts-regexp nil t)
8574 (save-excursion
8575 (goto-char (match-beginning 0))
8576 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8577 (delete-region (match-beginning 1) (match-end 1)))))))
8578 (setq task (buffer-string)))
8579 (insert task))
8580 (goto-char beg)))
8581
8582 ;;; Outline Sorting
8583
8584 (defun org-sort (with-case)
8585 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8586 Optional argument WITH-CASE means sort case-sensitively."
8587 (interactive "P")
8588 (cond
8589 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8590 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8591 (t
8592 (org-call-with-arg 'org-sort-entries with-case))))
8593
8594 (defun org-sort-remove-invisible (s)
8595 "Remove invisible links from string S."
8596 (remove-text-properties 0 (length s) org-rm-props s)
8597 (while (string-match org-bracket-link-regexp s)
8598 (setq s (replace-match (if (match-end 2)
8599 (match-string 3 s)
8600 (match-string 1 s)) t t s)))
8601 (let ((st (format " %s " s)))
8602 (while (string-match org-emph-re st)
8603 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8604 (setq s (substring st 1 -1)))
8605 s)
8606
8607 (defvar org-priority-regexp) ; defined later in the file
8608
8609 (defvar org-after-sorting-entries-or-items-hook nil
8610 "Hook that is run after a bunch of entries or items have been sorted.
8611 When children are sorted, the cursor is in the parent line when this
8612 hook gets called. When a region or a plain list is sorted, the cursor
8613 will be in the first entry of the sorted region/list.")
8614
8615 (defun org-sort-entries
8616 (&optional with-case sorting-type getkey-func compare-func property)
8617 "Sort entries on a certain level of an outline tree.
8618 If there is an active region, the entries in the region are sorted.
8619 Else, if the cursor is before the first entry, sort the top-level items.
8620 Else, the children of the entry at point are sorted.
8621
8622 Sorting can be alphabetically, numerically, by date/time as given by
8623 a time stamp, by a property, by priority order, or by a custom function.
8624
8625 The command prompts for the sorting type unless it has been given to the
8626 function through the SORTING-TYPE argument, which needs to be a character,
8627 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8628 precise meaning of each character:
8629
8630 n Numerically, by converting the beginning of the entry/item to a number.
8631 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8632 o By order of TODO keywords.
8633 t By date/time, either the first active time stamp in the entry, or, if
8634 none exist, by the first inactive one.
8635 s By the scheduled date/time.
8636 d By deadline date/time.
8637 c By creation time, which is assumed to be the first inactive time stamp
8638 at the beginning of a line.
8639 p By priority according to the cookie.
8640 r By the value of a property.
8641
8642 Capital letters will reverse the sort order.
8643
8644 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8645 called with point at the beginning of the record. It must return either
8646 a string or a number that should serve as the sorting key for that record.
8647
8648 Comparing entries ignores case by default. However, with an optional argument
8649 WITH-CASE, the sorting considers case as well.
8650
8651 Sorting is done against the visible part of the headlines, it ignores hidden
8652 links."
8653 (interactive "P")
8654 (let ((case-func (if with-case 'identity 'downcase))
8655 (cmstr
8656 ;; The clock marker is lost when using `sort-subr', let's
8657 ;; store the clocking string.
8658 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8659 (save-excursion
8660 (goto-char org-clock-marker)
8661 (buffer-substring-no-properties (line-beginning-position)
8662 (point)))))
8663 start beg end stars re re2
8664 txt what tmp)
8665 ;; Find beginning and end of region to sort
8666 (cond
8667 ((org-region-active-p)
8668 ;; we will sort the region
8669 (setq end (region-end)
8670 what "region")
8671 (goto-char (region-beginning))
8672 (if (not (org-at-heading-p)) (outline-next-heading))
8673 (setq start (point)))
8674 ((or (org-at-heading-p)
8675 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8676 ;; we will sort the children of the current headline
8677 (org-back-to-heading)
8678 (setq start (point)
8679 end (progn (org-end-of-subtree t t)
8680 (or (bolp) (insert "\n"))
8681 (when (>= (org-back-over-empty-lines) 1)
8682 (forward-line 1))
8683 (point))
8684 what "children")
8685 (goto-char start)
8686 (show-subtree)
8687 (outline-next-heading))
8688 (t
8689 ;; we will sort the top-level entries in this file
8690 (goto-char (point-min))
8691 (or (org-at-heading-p) (outline-next-heading))
8692 (setq start (point))
8693 (goto-char (point-max))
8694 (beginning-of-line 1)
8695 (when (looking-at ".*?\\S-")
8696 ;; File ends in a non-white line
8697 (end-of-line 1)
8698 (insert "\n"))
8699 (setq end (point-max))
8700 (setq what "top-level")
8701 (goto-char start)
8702 (show-all)))
8703
8704 (setq beg (point))
8705 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8706
8707 (looking-at "\\(\\*+\\)")
8708 (setq stars (match-string 1)
8709 re (concat "^" (regexp-quote stars) " +")
8710 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8711 txt (buffer-substring beg end))
8712 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8713 (if (and (not (equal stars "*")) (string-match re2 txt))
8714 (user-error "Region to sort contains a level above the first entry"))
8715
8716 (unless sorting-type
8717 (message
8718 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8719 [t]ime [s]cheduled [d]eadline [c]reated
8720 A/N/P/R/O/F/T/S/D/C means reversed:"
8721 what)
8722 (setq sorting-type (read-char-exclusive))
8723
8724 (unless getkey-func
8725 (and (= (downcase sorting-type) ?f)
8726 (setq getkey-func
8727 (org-icompleting-read "Sort using function: "
8728 obarray 'fboundp t nil nil))
8729 (setq getkey-func (intern getkey-func))))
8730
8731 (and (= (downcase sorting-type) ?r)
8732 (not property)
8733 (setq property
8734 (org-icompleting-read "Property: "
8735 (mapcar 'list (org-buffer-property-keys t))
8736 nil t))))
8737
8738 (message "Sorting entries...")
8739
8740 (save-restriction
8741 (narrow-to-region start end)
8742 (let ((dcst (downcase sorting-type))
8743 (case-fold-search nil)
8744 (now (current-time)))
8745 (sort-subr
8746 (/= dcst sorting-type)
8747 ;; This function moves to the beginning character of the "record" to
8748 ;; be sorted.
8749 (lambda nil
8750 (if (re-search-forward re nil t)
8751 (goto-char (match-beginning 0))
8752 (goto-char (point-max))))
8753 ;; This function moves to the last character of the "record" being
8754 ;; sorted.
8755 (lambda nil
8756 (save-match-data
8757 (condition-case nil
8758 (outline-forward-same-level 1)
8759 (error
8760 (goto-char (point-max))))))
8761 ;; This function returns the value that gets sorted against.
8762 (lambda nil
8763 (cond
8764 ((= dcst ?n)
8765 (if (looking-at org-complex-heading-regexp)
8766 (string-to-number (org-sort-remove-invisible (match-string 4)))
8767 nil))
8768 ((= dcst ?a)
8769 (if (looking-at org-complex-heading-regexp)
8770 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8771 nil))
8772 ((= dcst ?t)
8773 (let ((end (save-excursion (outline-next-heading) (point))))
8774 (if (or (re-search-forward org-ts-regexp end t)
8775 (re-search-forward org-ts-regexp-both end t))
8776 (org-time-string-to-seconds (match-string 0))
8777 (org-float-time now))))
8778 ((= dcst ?c)
8779 (let ((end (save-excursion (outline-next-heading) (point))))
8780 (if (re-search-forward
8781 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8782 end t)
8783 (org-time-string-to-seconds (match-string 0))
8784 (org-float-time now))))
8785 ((= dcst ?s)
8786 (let ((end (save-excursion (outline-next-heading) (point))))
8787 (if (re-search-forward org-scheduled-time-regexp end t)
8788 (org-time-string-to-seconds (match-string 1))
8789 (org-float-time now))))
8790 ((= dcst ?d)
8791 (let ((end (save-excursion (outline-next-heading) (point))))
8792 (if (re-search-forward org-deadline-time-regexp end t)
8793 (org-time-string-to-seconds (match-string 1))
8794 (org-float-time now))))
8795 ((= dcst ?p)
8796 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8797 (string-to-char (match-string 2))
8798 org-default-priority))
8799 ((= dcst ?r)
8800 (or (org-entry-get nil property) ""))
8801 ((= dcst ?o)
8802 (if (looking-at org-complex-heading-regexp)
8803 (- 9999 (length (member (match-string 2)
8804 org-todo-keywords-1)))))
8805 ((= dcst ?f)
8806 (if getkey-func
8807 (progn
8808 (setq tmp (funcall getkey-func))
8809 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8810 tmp)
8811 (error "Invalid key function `%s'" getkey-func)))
8812 (t (error "Invalid sorting type `%c'" sorting-type))))
8813 nil
8814 (cond
8815 ((= dcst ?a) 'string<)
8816 ((= dcst ?f) compare-func)
8817 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8818 (run-hooks 'org-after-sorting-entries-or-items-hook)
8819 ;; Reset the clock marker if needed
8820 (when cmstr
8821 (save-excursion
8822 (goto-char start)
8823 (search-forward cmstr nil t)
8824 (move-marker org-clock-marker (point))))
8825 (message "Sorting entries...done")))
8826
8827 (defun org-do-sort (table what &optional with-case sorting-type)
8828 "Sort TABLE of WHAT according to SORTING-TYPE.
8829 The user will be prompted for the SORTING-TYPE if the call to this
8830 function does not specify it. WHAT is only for the prompt, to indicate
8831 what is being sorted. The sorting key will be extracted from
8832 the car of the elements of the table.
8833 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8834 (unless sorting-type
8835 (message
8836 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8837 what)
8838 (setq sorting-type (read-char-exclusive)))
8839 (let ((dcst (downcase sorting-type))
8840 extractfun comparefun)
8841 ;; Define the appropriate functions
8842 (cond
8843 ((= dcst ?n)
8844 (setq extractfun 'string-to-number
8845 comparefun (if (= dcst sorting-type) '< '>)))
8846 ((= dcst ?a)
8847 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8848 (lambda(x) (downcase (org-sort-remove-invisible x))))
8849 comparefun (if (= dcst sorting-type)
8850 'string<
8851 (lambda (a b) (and (not (string< a b))
8852 (not (string= a b)))))))
8853 ((= dcst ?t)
8854 (setq extractfun
8855 (lambda (x)
8856 (if (or (string-match org-ts-regexp x)
8857 (string-match org-ts-regexp-both x))
8858 (org-float-time
8859 (org-time-string-to-time (match-string 0 x)))
8860 0))
8861 comparefun (if (= dcst sorting-type) '< '>)))
8862 (t (error "Invalid sorting type `%c'" sorting-type)))
8863
8864 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8865 table)
8866 (lambda (a b) (funcall comparefun (car a) (car b))))))
8867
8868
8869 ;;; The orgstruct minor mode
8870
8871 ;; Define a minor mode which can be used in other modes in order to
8872 ;; integrate the org-mode structure editing commands.
8873
8874 ;; This is really a hack, because the org-mode structure commands use
8875 ;; keys which normally belong to the major mode. Here is how it
8876 ;; works: The minor mode defines all the keys necessary to operate the
8877 ;; structure commands, but wraps the commands into a function which
8878 ;; tests if the cursor is currently at a headline or a plain list
8879 ;; item. If that is the case, the structure command is used,
8880 ;; temporarily setting many Org-mode variables like regular
8881 ;; expressions for filling etc. However, when any of those keys is
8882 ;; used at a different location, function uses `key-binding' to look
8883 ;; up if the key has an associated command in another currently active
8884 ;; keymap (minor modes, major mode, global), and executes that
8885 ;; command. There might be problems if any of the keys is otherwise
8886 ;; used as a prefix key.
8887
8888 (defcustom orgstruct-heading-prefix-regexp ""
8889 "Regexp that matches the custom prefix of Org headlines in
8890 orgstruct(++)-mode."
8891 :group 'org
8892 :version "24.4"
8893 :package-version '(Org . "8.3")
8894 :type 'regexp)
8895 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8896
8897 (defcustom orgstruct-setup-hook nil
8898 "Hook run after orgstruct-mode-map is filled."
8899 :group 'org
8900 :version "24.4"
8901 :package-version '(Org . "8.0")
8902 :type 'hook)
8903
8904 (defvar orgstruct-initialized nil)
8905
8906 (defvar org-local-vars nil
8907 "List of local variables, for use by `orgstruct-mode'.")
8908
8909 ;;;###autoload
8910 (define-minor-mode orgstruct-mode
8911 "Toggle the minor mode `orgstruct-mode'.
8912 This mode is for using Org-mode structure commands in other
8913 modes. The following keys behave as if Org-mode were active, if
8914 the cursor is on a headline, or on a plain list item (both as
8915 defined by Org-mode)."
8916 nil " OrgStruct" (make-sparse-keymap)
8917 (funcall (if orgstruct-mode
8918 'add-to-invisibility-spec
8919 'remove-from-invisibility-spec)
8920 '(outline . t))
8921 (when orgstruct-mode
8922 (org-load-modules-maybe)
8923 (unless orgstruct-initialized
8924 (orgstruct-setup)
8925 (setq orgstruct-initialized t))))
8926
8927 ;;;###autoload
8928 (defun turn-on-orgstruct ()
8929 "Unconditionally turn on `orgstruct-mode'."
8930 (orgstruct-mode 1))
8931
8932 (defvar org-fb-vars nil)
8933 (make-variable-buffer-local 'org-fb-vars)
8934 (defun orgstruct++-mode (&optional arg)
8935 "Toggle `orgstruct-mode', the enhanced version of it.
8936 In addition to setting orgstruct-mode, this also exports all
8937 indentation and autofilling variables from org-mode into the
8938 buffer. It will also recognize item context in multiline items."
8939 (interactive "P")
8940 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8941 (if (< arg 1)
8942 (progn (orgstruct-mode -1)
8943 (mapc (lambda(v)
8944 (org-set-local (car v)
8945 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8946 org-fb-vars))
8947 (orgstruct-mode 1)
8948 (setq org-fb-vars nil)
8949 (unless org-local-vars
8950 (setq org-local-vars (org-get-local-variables)))
8951 (let (var val)
8952 (mapc
8953 (lambda (x)
8954 (when (string-match
8955 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8956 (symbol-name (car x)))
8957 (setq var (car x) val (nth 1 x))
8958 (push (list var `(quote ,(eval var))) org-fb-vars)
8959 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8960 org-local-vars)
8961 (org-set-local 'orgstruct-is-++ t))))
8962
8963 (defvar orgstruct-is-++ nil
8964 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8965 (make-variable-buffer-local 'orgstruct-is-++)
8966
8967 ;;;###autoload
8968 (defun turn-on-orgstruct++ ()
8969 "Unconditionally turn on `orgstruct++-mode'."
8970 (orgstruct++-mode 1))
8971
8972 (defun orgstruct-error ()
8973 "Error when there is no default binding for a structure key."
8974 (interactive)
8975 (funcall (if (fboundp 'user-error)
8976 'user-error
8977 'error)
8978 "This key has no function outside structure elements"))
8979
8980 (defun orgstruct-setup ()
8981 "Setup orgstruct keymap."
8982 (dolist (cell '((org-demote . t)
8983 (org-metaleft . t)
8984 (org-metaright . t)
8985 (org-promote . t)
8986 (org-shiftmetaleft . t)
8987 (org-shiftmetaright . t)
8988 org-backward-element
8989 org-backward-heading-same-level
8990 org-ctrl-c-ret
8991 org-ctrl-c-minus
8992 org-ctrl-c-star
8993 org-cycle
8994 org-forward-heading-same-level
8995 org-insert-heading
8996 org-insert-heading-respect-content
8997 org-kill-note-or-show-branches
8998 org-mark-subtree
8999 org-meta-return
9000 org-metadown
9001 org-metaup
9002 org-narrow-to-subtree
9003 org-promote-subtree
9004 org-reveal
9005 org-shiftdown
9006 org-shiftleft
9007 org-shiftmetadown
9008 org-shiftmetaup
9009 org-shiftright
9010 org-shifttab
9011 org-shifttab
9012 org-shiftup
9013 org-show-subtree
9014 org-sort
9015 org-up-element
9016 outline-demote
9017 outline-next-visible-heading
9018 outline-previous-visible-heading
9019 outline-promote
9020 outline-up-heading
9021 show-children))
9022 (let ((f (or (car-safe cell) cell))
9023 (disable-when-heading-prefix (cdr-safe cell)))
9024 (when (fboundp f)
9025 (let ((new-bindings))
9026 (dolist (binding (nconc (where-is-internal f org-mode-map)
9027 (where-is-internal f outline-mode-map)))
9028 (push binding new-bindings)
9029 ;; TODO use local-function-key-map
9030 (dolist (rep '(("<tab>" . "TAB")
9031 ("<return>" . "RET")
9032 ("<escape>" . "ESC")
9033 ("<delete>" . "DEL")))
9034 (setq binding (read-kbd-macro
9035 (let ((case-fold-search))
9036 (replace-regexp-in-string
9037 (regexp-quote (cdr rep))
9038 (car rep)
9039 (key-description binding)))))
9040 (pushnew binding new-bindings :test 'equal)))
9041 (dolist (binding new-bindings)
9042 (let ((key (lookup-key orgstruct-mode-map binding)))
9043 (when (or (not key) (numberp key))
9044 (condition-case nil
9045 (org-defkey orgstruct-mode-map
9046 binding
9047 (orgstruct-make-binding f binding disable-when-heading-prefix))
9048 (error nil)))))))))
9049 (run-hooks 'orgstruct-setup-hook))
9050
9051 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9052 "Create a function for binding in the structure minor mode.
9053 FUN is the command to call inside a table. KEY is the key that
9054 should be checked in for a command to execute outside of tables.
9055 Non-nil `disable-when-heading-prefix' means to disable the command
9056 if `orgstruct-heading-prefix-regexp' is not empty."
9057 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9058 (let ((nname name)
9059 (i 0))
9060 (while (fboundp (intern nname))
9061 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9062 (setq name (intern nname)))
9063 (eval
9064 (let ((bindings '((org-heading-regexp
9065 (concat "^"
9066 orgstruct-heading-prefix-regexp
9067 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9068 (org-outline-regexp
9069 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9070 (org-outline-regexp-bol
9071 (concat "^" org-outline-regexp))
9072 (outline-regexp org-outline-regexp)
9073 (outline-heading-end-regexp "\n")
9074 (outline-level 'org-outline-level)
9075 (outline-heading-alist))))
9076 `(defun ,name (arg)
9077 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9078 "Outside of structure, run the binding of `"
9079 (key-description key) "'."
9080 (when disable-when-heading-prefix
9081 (concat
9082 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9083 "back to the default binding due to limitations of Org's implementation of\n"
9084 "`" (symbol-name fun) "'.")))
9085 (interactive "p")
9086 (let* ((disable
9087 ,(and disable-when-heading-prefix
9088 '(not (string= orgstruct-heading-prefix-regexp ""))))
9089 (fallback
9090 (or disable
9091 (not
9092 (let* ,bindings
9093 (org-context-p 'headline 'item
9094 ,(when (memq fun
9095 '(org-insert-heading
9096 org-insert-heading-respect-content
9097 org-meta-return))
9098 '(when orgstruct-is-++
9099 'item-body))))))))
9100 (if fallback
9101 (let* ((orgstruct-mode)
9102 (binding
9103 (let ((key ,key))
9104 (catch 'exit
9105 (dolist
9106 (rep
9107 '(nil
9108 ("<\\([^>]*\\)tab>" . "\\1TAB")
9109 ("<\\([^>]*\\)return>" . "\\1RET")
9110 ("<\\([^>]*\\)escape>" . "\\1ESC")
9111 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9112 nil)
9113 (when rep
9114 (setq key (read-kbd-macro
9115 (let ((case-fold-search))
9116 (replace-regexp-in-string
9117 (car rep)
9118 (cdr rep)
9119 (key-description key))))))
9120 (when (key-binding key)
9121 (throw 'exit (key-binding key))))))))
9122 (if (keymapp binding)
9123 (org-set-transient-map binding)
9124 (let ((func (or binding
9125 (unless disable
9126 'orgstruct-error))))
9127 (when func
9128 (call-interactively func)))))
9129 (org-run-like-in-org-mode
9130 (lambda ()
9131 (interactive)
9132 (let* ,bindings
9133 (call-interactively ',fun)))))))))
9134 name))
9135
9136 (defun org-contextualize-keys (alist contexts)
9137 "Return valid elements in ALIST depending on CONTEXTS.
9138
9139 `org-agenda-custom-commands' or `org-capture-templates' are the
9140 values used for ALIST, and `org-agenda-custom-commands-contexts'
9141 or `org-capture-templates-contexts' are the associated contexts
9142 definitions."
9143 (let ((contexts
9144 ;; normalize contexts
9145 (mapcar
9146 (lambda(c) (cond ((listp (cadr c))
9147 (list (car c) (car c) (cadr c)))
9148 ((string= "" (cadr c))
9149 (list (car c) (car c) (caddr c)))
9150 (t c))) contexts))
9151 (a alist) c r s)
9152 ;; loop over all commands or templates
9153 (while (setq c (pop a))
9154 (let (vrules repl)
9155 (cond
9156 ((not (assoc (car c) contexts))
9157 (push c r))
9158 ((and (assoc (car c) contexts)
9159 (setq vrules (org-contextualize-validate-key
9160 (car c) contexts)))
9161 (mapc (lambda (vr)
9162 (when (not (equal (car vr) (cadr vr)))
9163 (setq repl vr))) vrules)
9164 (if (not repl) (push c r)
9165 (push (cadr repl) s)
9166 (push
9167 (cons (car c)
9168 (cdr (or (assoc (cadr repl) alist)
9169 (error "Undefined key `%s' as contextual replacement for `%s'"
9170 (cadr repl) (car c)))))
9171 r))))))
9172 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9173 (delq
9174 nil
9175 (delete-dups
9176 (mapcar (lambda (x)
9177 (let ((tpl (car x)))
9178 (when (not (delq
9179 nil
9180 (mapcar (lambda(y)
9181 (equal y tpl)) s))) x)))
9182 (reverse r))))))
9183
9184 (defun org-contextualize-validate-key (key contexts)
9185 "Check CONTEXTS for agenda or capture KEY."
9186 (let (r rr res)
9187 (while (setq r (pop contexts))
9188 (mapc
9189 (lambda (rr)
9190 (when
9191 (and (equal key (car r))
9192 (if (functionp rr) (funcall rr)
9193 (or (and (eq (car rr) 'in-file)
9194 (buffer-file-name)
9195 (string-match (cdr rr) (buffer-file-name)))
9196 (and (eq (car rr) 'in-mode)
9197 (string-match (cdr rr) (symbol-name major-mode)))
9198 (and (eq (car rr) 'in-buffer)
9199 (string-match (cdr rr) (buffer-name)))
9200 (when (and (eq (car rr) 'not-in-file)
9201 (buffer-file-name))
9202 (not (string-match (cdr rr) (buffer-file-name))))
9203 (when (eq (car rr) 'not-in-mode)
9204 (not (string-match (cdr rr) (symbol-name major-mode))))
9205 (when (eq (car rr) 'not-in-buffer)
9206 (not (string-match (cdr rr) (buffer-name)))))))
9207 (push r res)))
9208 (car (last r))))
9209 (delete-dups (delq nil res))))
9210
9211 (defun org-context-p (&rest contexts)
9212 "Check if local context is any of CONTEXTS.
9213 Possible values in the list of contexts are `table', `headline', and `item'."
9214 (let ((pos (point)))
9215 (goto-char (point-at-bol))
9216 (prog1 (or (and (memq 'table contexts)
9217 (looking-at "[ \t]*|"))
9218 (and (memq 'headline contexts)
9219 (looking-at org-outline-regexp))
9220 (and (memq 'item contexts)
9221 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9222 (and (memq 'item-body contexts)
9223 (org-in-item-p)))
9224 (goto-char pos))))
9225
9226 (defun org-get-local-variables ()
9227 "Return a list of all local variables in an Org mode buffer."
9228 (let (varlist)
9229 (with-current-buffer (get-buffer-create "*Org tmp*")
9230 (erase-buffer)
9231 (org-mode)
9232 (setq varlist (buffer-local-variables)))
9233 (kill-buffer "*Org tmp*")
9234 (delq nil
9235 (mapcar
9236 (lambda (x)
9237 (setq x
9238 (if (symbolp x)
9239 (list x)
9240 (list (car x) (cdr x))))
9241 (if (and (not (get (car x) 'org-state))
9242 (string-match
9243 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9244 (symbol-name (car x))))
9245 x nil))
9246 varlist))))
9247
9248 (defun org-clone-local-variables (from-buffer &optional regexp)
9249 "Clone local variables from FROM-BUFFER.
9250 Optional argument REGEXP selects variables to clone."
9251 (mapc
9252 (lambda (pair)
9253 (and (symbolp (car pair))
9254 (or (null regexp)
9255 (string-match regexp (symbol-name (car pair))))
9256 (set (make-local-variable (car pair))
9257 (cdr pair))))
9258 (buffer-local-variables from-buffer)))
9259
9260 ;;;###autoload
9261 (defun org-run-like-in-org-mode (cmd)
9262 "Run a command, pretending that the current buffer is in Org-mode.
9263 This will temporarily bind local variables that are typically bound in
9264 Org-mode to the values they have in Org-mode, and then interactively
9265 call CMD."
9266 (org-load-modules-maybe)
9267 (unless org-local-vars
9268 (setq org-local-vars (org-get-local-variables)))
9269 (let (binds)
9270 (dolist (var org-local-vars)
9271 (when (or (not (boundp (car var)))
9272 (eq (symbol-value (car var))
9273 (default-value (car var))))
9274 (push (list (car var) `(quote ,(cadr var))) binds)))
9275 (eval `(let ,binds
9276 (call-interactively (quote ,cmd))))))
9277
9278 ;;;; Archiving
9279
9280 (defun org-get-category (&optional pos force-refresh)
9281 "Get the category applying to position POS."
9282 (save-match-data
9283 (if force-refresh (org-refresh-category-properties))
9284 (let ((pos (or pos (point))))
9285 (or (get-text-property pos 'org-category)
9286 (progn (org-refresh-category-properties)
9287 (get-text-property pos 'org-category))))))
9288
9289 (defun org-refresh-category-properties ()
9290 "Refresh category text properties in the buffer."
9291 (let ((case-fold-search t)
9292 (inhibit-read-only t)
9293 (def-cat (cond
9294 ((null org-category)
9295 (if buffer-file-name
9296 (file-name-sans-extension
9297 (file-name-nondirectory buffer-file-name))
9298 "???"))
9299 ((symbolp org-category) (symbol-name org-category))
9300 (t org-category)))
9301 beg end cat pos optionp)
9302 (org-with-silent-modifications
9303 (save-excursion
9304 (save-restriction
9305 (widen)
9306 (goto-char (point-min))
9307 (put-text-property (point) (point-max) 'org-category def-cat)
9308 (while (re-search-forward
9309 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9310 (setq pos (match-end 0)
9311 optionp (equal (char-after (match-beginning 0)) ?#)
9312 cat (org-trim (match-string 2)))
9313 (if optionp
9314 (setq beg (point-at-bol) end (point-max))
9315 (org-back-to-heading t)
9316 (setq beg (point) end (org-end-of-subtree t t)))
9317 (put-text-property beg end 'org-category cat)
9318 (put-text-property beg end 'org-category-position beg)
9319 (goto-char pos)))))))
9320
9321 (defun org-refresh-properties (dprop tprop)
9322 "Refresh buffer text properties.
9323 DPROP is the drawer property and TPROP is the corresponding text
9324 property to set."
9325 (let ((case-fold-search t)
9326 (inhibit-read-only t) p)
9327 (org-with-silent-modifications
9328 (save-excursion
9329 (save-restriction
9330 (widen)
9331 (goto-char (point-min))
9332 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9333 (setq p (org-match-string-no-properties 1))
9334 (save-excursion
9335 (org-back-to-heading t)
9336 (put-text-property
9337 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9338
9339
9340 ;;;; Link Stuff
9341
9342 ;;; Link abbreviations
9343
9344 (defun org-link-expand-abbrev (link)
9345 "Apply replacements as defined in `org-link-abbrev-alist'."
9346 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9347 (let* ((key (match-string 1 link))
9348 (as (or (assoc key org-link-abbrev-alist-local)
9349 (assoc key org-link-abbrev-alist)))
9350 (tag (and (match-end 2) (match-string 3 link)))
9351 rpl)
9352 (if (not as)
9353 link
9354 (setq rpl (cdr as))
9355 (cond
9356 ((symbolp rpl) (funcall rpl tag))
9357 ((string-match "%(\\([^)]+\\))" rpl)
9358 (replace-match
9359 (save-match-data
9360 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9361 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9362 ((string-match "%h" rpl)
9363 (replace-match (url-hexify-string (or tag "")) t t rpl))
9364 (t (concat rpl tag)))))
9365 link))
9366
9367 ;;; Storing and inserting links
9368
9369 (defvar org-insert-link-history nil
9370 "Minibuffer history for links inserted with `org-insert-link'.")
9371
9372 (defvar org-stored-links nil
9373 "Contains the links stored with `org-store-link'.")
9374
9375 (defvar org-store-link-plist nil
9376 "Plist with info about the most recently link created with `org-store-link'.")
9377
9378 (defvar org-link-protocols nil
9379 "Link protocols added to Org-mode using `org-add-link-type'.")
9380
9381 (defvar org-store-link-functions nil
9382 "List of functions that are called to create and store a link.
9383 Each function will be called in turn until one returns a non-nil
9384 value. Each function should check if it is responsible for creating
9385 this link (for example by looking at the major mode).
9386 If not, it must exit and return nil.
9387 If yes, it should return a non-nil value after a calling
9388 `org-store-link-props' with a list of properties and values.
9389 Special properties are:
9390
9391 :type The link prefix, like \"http\". This must be given.
9392 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9393 This is obligatory as well.
9394 :description Optional default description for the second pair
9395 of brackets in an Org-mode link. The user can still change
9396 this when inserting this link into an Org-mode buffer.
9397
9398 In addition to these, any additional properties can be specified
9399 and then used in capture templates.")
9400
9401 (defun org-add-link-type (type &optional follow export)
9402 "Add TYPE to the list of `org-link-types'.
9403 Re-compute all regular expressions depending on `org-link-types'
9404
9405 FOLLOW and EXPORT are two functions.
9406
9407 FOLLOW should take the link path as the single argument and do whatever
9408 is necessary to follow the link, for example find a file or display
9409 a mail message.
9410
9411 EXPORT should format the link path for export to one of the export formats.
9412 It should be a function accepting three arguments:
9413
9414 path the path of the link, the text after the prefix (like \"http:\")
9415 desc the description of the link, if any, or a description added by
9416 org-export-normalize-links if there is none
9417 format the export format, a symbol like `html' or `latex' or `ascii'..
9418
9419 The function may use the FORMAT information to return different values
9420 depending on the format. The return value will be put literally into
9421 the exported file. If the return value is nil, this means Org should
9422 do what it normally does with links which do not have EXPORT defined.
9423
9424 Org-mode has a built-in default for exporting links. If you are happy with
9425 this default, there is no need to define an export function for the link
9426 type. For a simple example of an export function, see `org-bbdb.el'."
9427 (add-to-list 'org-link-types type t)
9428 (org-make-link-regexps)
9429 (if (assoc type org-link-protocols)
9430 (setcdr (assoc type org-link-protocols) (list follow export))
9431 (push (list type follow export) org-link-protocols)))
9432
9433 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9434 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9435
9436 ;;;###autoload
9437 (defun org-store-link (arg)
9438 "\\<org-mode-map>Store an org-link to the current location.
9439 This link is added to `org-stored-links' and can later be inserted
9440 into an org-buffer with \\[org-insert-link].
9441
9442 For some link types, a prefix arg is interpreted.
9443 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9444 For file links, arg negates `org-context-in-file-links'.
9445
9446 A double prefix arg force skipping storing functions that are not
9447 part of Org's core.
9448
9449 A triple prefix arg force storing a link for each line in the
9450 active region."
9451 (interactive "P")
9452 (org-load-modules-maybe)
9453 (if (and (equal arg '(64)) (org-region-active-p))
9454 (save-excursion
9455 (let ((end (region-end)))
9456 (goto-char (region-beginning))
9457 (set-mark (point))
9458 (while (< (point-at-eol) end)
9459 (move-end-of-line 1) (activate-mark)
9460 (let (current-prefix-arg)
9461 (call-interactively 'org-store-link))
9462 (move-beginning-of-line 2)
9463 (set-mark (point)))))
9464 (org-with-limited-levels
9465 (setq org-store-link-plist nil)
9466 (let (link cpltxt desc description search
9467 txt custom-id agenda-link sfuns sfunsn)
9468 (cond
9469
9470 ;; Store a link using an external link type
9471 ((and (not (equal arg '(16)))
9472 (setq sfuns
9473 (delq
9474 nil (mapcar (lambda (f)
9475 (let (fs) (if (funcall f) (push f fs))))
9476 org-store-link-functions))
9477 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9478 (or (and (cdr sfuns)
9479 (funcall (intern
9480 (completing-read
9481 "Which function for creating the link? "
9482 sfunsn nil t (car sfunsn)))))
9483 (funcall (caar sfuns)))
9484 (setq link (plist-get org-store-link-plist :link)
9485 desc (or (plist-get org-store-link-plist
9486 :description) link))))
9487
9488 ;; Store a link from a source code buffer
9489 ((org-src-edit-buffer-p)
9490 (let (label gc)
9491 (while (or (not label)
9492 (save-excursion
9493 (save-restriction
9494 (widen)
9495 (goto-char (point-min))
9496 (re-search-forward
9497 (regexp-quote (format org-coderef-label-format label))
9498 nil t))))
9499 (when label (message "Label exists already") (sit-for 2))
9500 (setq label (read-string "Code line label: " label)))
9501 (end-of-line 1)
9502 (setq link (format org-coderef-label-format label))
9503 (setq gc (- 79 (length link)))
9504 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9505 (insert link)
9506 (setq link (concat "(" label ")") desc nil)))
9507
9508 ;; We are in the agenda, link to referenced location
9509 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9510 (let ((m (or (get-text-property (point) 'org-hd-marker)
9511 (get-text-property (point) 'org-marker))))
9512 (when m
9513 (org-with-point-at m
9514 (setq agenda-link
9515 (if (org-called-interactively-p 'any)
9516 (call-interactively 'org-store-link)
9517 (org-store-link nil)))))))
9518
9519 ((eq major-mode 'calendar-mode)
9520 (let ((cd (calendar-cursor-to-date)))
9521 (setq link
9522 (format-time-string
9523 (car org-time-stamp-formats)
9524 (apply 'encode-time
9525 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9526 nil nil nil))))
9527 (org-store-link-props :type "calendar" :date cd)))
9528
9529 ((eq major-mode 'help-mode)
9530 (setq link (concat "help:" (save-excursion
9531 (goto-char (point-min))
9532 (looking-at "^[^ ]+")
9533 (match-string 0))))
9534 (org-store-link-props :type "help"))
9535
9536 ((eq major-mode 'w3-mode)
9537 (setq cpltxt (if (and (buffer-name)
9538 (not (string-match "Untitled" (buffer-name))))
9539 (buffer-name)
9540 (url-view-url t))
9541 link (url-view-url t))
9542 (org-store-link-props :type "w3" :url (url-view-url t)))
9543
9544 ((eq major-mode 'image-mode)
9545 (setq cpltxt (concat "file:"
9546 (abbreviate-file-name buffer-file-name))
9547 link cpltxt)
9548 (org-store-link-props :type "image" :file buffer-file-name))
9549
9550 ;; In dired, store a link to the file of the current line
9551 ((eq major-mode 'dired-mode)
9552 (let ((file (dired-get-filename nil t)))
9553 (setq file (if file
9554 (abbreviate-file-name
9555 (expand-file-name (dired-get-filename nil t)))
9556 ;; otherwise, no file so use current directory.
9557 default-directory))
9558 (setq cpltxt (concat "file:" file)
9559 link cpltxt)))
9560
9561 ((setq search (run-hook-with-args-until-success
9562 'org-create-file-search-functions))
9563 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9564 "::" search))
9565 (setq cpltxt (or description link)))
9566
9567 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9568 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9569 (cond
9570 ;; Store a link using the target at point
9571 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9572 (setq cpltxt
9573 (concat "file:"
9574 (abbreviate-file-name
9575 (buffer-file-name (buffer-base-buffer)))
9576 "::" (match-string 1))
9577 link cpltxt))
9578 ((and (featurep 'org-id)
9579 (or (eq org-id-link-to-org-use-id t)
9580 (and (org-called-interactively-p 'any)
9581 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9582 (and (eq org-id-link-to-org-use-id
9583 'create-if-interactive-and-no-custom-id)
9584 (not custom-id))))
9585 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9586 ;; Store a link using the ID at point
9587 (setq link (condition-case nil
9588 (prog1 (org-id-store-link)
9589 (setq desc (or (plist-get org-store-link-plist
9590 :description)
9591 "")))
9592 (error
9593 ;; Probably before first headline, link only to file
9594 (concat "file:"
9595 (abbreviate-file-name
9596 (buffer-file-name (buffer-base-buffer))))))))
9597 (t
9598 ;; Just link to current headline
9599 (setq cpltxt (concat "file:"
9600 (abbreviate-file-name
9601 (buffer-file-name (buffer-base-buffer)))))
9602 ;; Add a context search string
9603 (when (org-xor org-context-in-file-links arg)
9604 (let* ((ee (org-element-at-point))
9605 (et (org-element-type ee))
9606 (ev (plist-get (cadr ee) :value))
9607 (ek (plist-get (cadr ee) :key))
9608 (eok (and (stringp ek) (string-match "name" ek))))
9609 (setq txt (cond
9610 ((org-at-heading-p) nil)
9611 ((and (eq et 'keyword) eok) ev)
9612 ((org-region-active-p)
9613 (buffer-substring (region-beginning) (region-end)))))
9614 (when (or (null txt) (string-match "\\S-" txt))
9615 (setq cpltxt
9616 (concat cpltxt "::"
9617 (condition-case nil
9618 (org-make-org-heading-search-string txt)
9619 (error "")))
9620 desc (or (and (eq et 'keyword) eok ev)
9621 (nth 4 (ignore-errors (org-heading-components)))
9622 "NONE")))))
9623 (if (string-match "::\\'" cpltxt)
9624 (setq cpltxt (substring cpltxt 0 -2)))
9625 (setq link cpltxt))))
9626
9627 ((buffer-file-name (buffer-base-buffer))
9628 ;; Just link to this file here.
9629 (setq cpltxt (concat "file:"
9630 (abbreviate-file-name
9631 (buffer-file-name (buffer-base-buffer)))))
9632 ;; Add a context string.
9633 (when (org-xor org-context-in-file-links arg)
9634 (setq txt (if (org-region-active-p)
9635 (buffer-substring (region-beginning) (region-end))
9636 (buffer-substring (point-at-bol) (point-at-eol))))
9637 ;; Only use search option if there is some text.
9638 (when (string-match "\\S-" txt)
9639 (setq cpltxt
9640 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9641 desc "NONE")))
9642 (setq link cpltxt))
9643
9644 ((org-called-interactively-p 'interactive)
9645 (user-error "No method for storing a link from this buffer"))
9646
9647 (t (setq link nil)))
9648
9649 ;; We're done setting link and desc, clean up
9650 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9651 (setq link (or link cpltxt)
9652 desc (or desc cpltxt))
9653 (cond ((equal desc "NONE") (setq desc nil))
9654 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9655 (let ((d0 (match-string 3 desc))
9656 (p0 (match-string 5 desc)))
9657 (setq desc
9658 (replace-regexp-in-string
9659 org-bracket-link-regexp
9660 (concat (or p0 d0)
9661 (if (equal (length (match-string 0 desc))
9662 (length desc)) "*" "")) desc)))))
9663
9664 ;; Return the link
9665 (if (not (and (or (org-called-interactively-p 'any)
9666 executing-kbd-macro) link))
9667 (or agenda-link (and link (org-make-link-string link desc)))
9668 (push (list link desc) org-stored-links)
9669 (message "Stored: %s" (or desc link))
9670 (when custom-id
9671 (setq link (concat "file:" (abbreviate-file-name
9672 (buffer-file-name)) "::#" custom-id))
9673 (push (list link desc) org-stored-links))
9674 (car org-stored-links))))))
9675
9676 (defun org-store-link-props (&rest plist)
9677 "Store link properties, extract names and addresses."
9678 (let (x adr)
9679 (when (setq x (plist-get plist :from))
9680 (setq adr (mail-extract-address-components x))
9681 (setq plist (plist-put plist :fromname (car adr)))
9682 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9683 (when (setq x (plist-get plist :to))
9684 (setq adr (mail-extract-address-components x))
9685 (setq plist (plist-put plist :toname (car adr)))
9686 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9687 (let ((from (plist-get plist :from))
9688 (to (plist-get plist :to)))
9689 (when (and from to org-from-is-user-regexp)
9690 (setq plist
9691 (plist-put plist :fromto
9692 (if (string-match org-from-is-user-regexp from)
9693 (concat "to %t")
9694 (concat "from %f"))))))
9695 (setq org-store-link-plist plist))
9696
9697 (defun org-add-link-props (&rest plist)
9698 "Add these properties to the link property list."
9699 (let (key value)
9700 (while plist
9701 (setq key (pop plist) value (pop plist))
9702 (setq org-store-link-plist
9703 (plist-put org-store-link-plist key value)))))
9704
9705 (defun org-email-link-description (&optional fmt)
9706 "Return the description part of an email link.
9707 This takes information from `org-store-link-plist' and formats it
9708 according to FMT (default from `org-email-link-description-format')."
9709 (setq fmt (or fmt org-email-link-description-format))
9710 (let* ((p org-store-link-plist)
9711 (to (plist-get p :toaddress))
9712 (from (plist-get p :fromaddress))
9713 (table
9714 (list
9715 (cons "%c" (plist-get p :fromto))
9716 (cons "%F" (plist-get p :from))
9717 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9718 (cons "%T" (plist-get p :to))
9719 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9720 (cons "%s" (plist-get p :subject))
9721 (cons "%d" (plist-get p :date))
9722 (cons "%m" (plist-get p :message-id)))))
9723 (when (string-match "%c" fmt)
9724 ;; Check if the user wrote this message
9725 (if (and org-from-is-user-regexp from to
9726 (save-match-data (string-match org-from-is-user-regexp from)))
9727 (setq fmt (replace-match "to %t" t t fmt))
9728 (setq fmt (replace-match "from %f" t t fmt))))
9729 (org-replace-escapes fmt table)))
9730
9731 (defun org-make-org-heading-search-string (&optional string)
9732 "Make search string for the current headline or STRING."
9733 (let ((s (or string
9734 (and (derived-mode-p 'org-mode)
9735 (save-excursion
9736 (org-back-to-heading t)
9737 (org-element-property :raw-value (org-element-at-point))))))
9738 (lines org-context-in-file-links))
9739 (or string (setq s (concat "*" s))) ; Add * for headlines
9740 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9741 (when (and string (integerp lines) (> lines 0))
9742 (let ((slines (org-split-string s "\n")))
9743 (when (< lines (length slines))
9744 (setq s (mapconcat
9745 'identity
9746 (reverse (nthcdr (- (length slines) lines)
9747 (reverse slines))) "\n")))))
9748 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9749
9750 (defun org-make-link-string (link &optional description)
9751 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9752 (unless (string-match "\\S-" link)
9753 (error "Empty link"))
9754 (when (and description
9755 (stringp description)
9756 (not (string-match "\\S-" description)))
9757 (setq description nil))
9758 (when (stringp description)
9759 ;; Remove brackets from the description, they are fatal.
9760 (while (string-match "\\[" description)
9761 (setq description (replace-match "{" t t description)))
9762 (while (string-match "\\]" description)
9763 (setq description (replace-match "}" t t description))))
9764 (when (equal link description)
9765 ;; No description needed, it is identical
9766 (setq description nil))
9767 (when (and (not description)
9768 (not (string-match (org-image-file-name-regexp) link))
9769 (not (equal link (org-link-escape link))))
9770 (setq description (org-extract-attributes link)))
9771 (setq link
9772 (cond ((string-match (org-image-file-name-regexp) link) link)
9773 ((string-match org-link-types-re link)
9774 (concat (match-string 1 link)
9775 (org-link-escape (substring link (match-end 1)))))
9776 (t (org-link-escape link))))
9777 (concat "[[" link "]"
9778 (if description (concat "[" description "]") "")
9779 "]"))
9780
9781 (defconst org-link-escape-chars
9782 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9783 "List of characters that should be escaped in link.
9784 This is the list that is used for internal purposes.")
9785
9786 (defconst org-link-escape-chars-browser
9787 '(?\ ?\")
9788 "List of escapes for characters that are problematic in links.
9789 This is the list that is used before handing over to the browser.")
9790
9791 (defun org-link-escape (text &optional table merge)
9792 "Return percent escaped representation of TEXT.
9793 TEXT is a string with the text to escape.
9794 Optional argument TABLE is a list with characters that should be
9795 escaped. When nil, `org-link-escape-chars' is used.
9796 If optional argument MERGE is set, merge TABLE into
9797 `org-link-escape-chars'."
9798 (cond
9799 ((and table merge)
9800 (mapc (lambda (defchr)
9801 (unless (member defchr table)
9802 (setq table (cons defchr table)))) org-link-escape-chars))
9803 ((null table)
9804 (setq table org-link-escape-chars)))
9805 (mapconcat
9806 (lambda (char)
9807 (if (or (member char table)
9808 (and (or (< char 32) (= char 37) (> char 126))
9809 org-url-hexify-p))
9810 (mapconcat (lambda (sequence-element)
9811 (format "%%%.2X" sequence-element))
9812 (or (encode-coding-char char 'utf-8)
9813 (error "Unable to percent escape character: %s"
9814 (char-to-string char))) "")
9815 (char-to-string char))) text ""))
9816
9817 (defun org-link-unescape (str)
9818 "Unhex hexified Unicode strings as returned from the JavaScript function
9819 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9820 (unless (and (null str) (string= "" str))
9821 (let ((pos 0) (case-fold-search t) unhexed)
9822 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9823 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9824 (setq str (replace-match unhexed t t str))
9825 (setq pos (+ pos (length unhexed))))))
9826 str)
9827
9828 (defun org-link-unescape-compound (hex)
9829 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9830 Note: this function also decodes single byte encodings like
9831 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9832 (save-match-data
9833 (let* ((bytes (cdr (split-string hex "%")))
9834 (ret "")
9835 (eat 0)
9836 (sum 0))
9837 (while bytes
9838 (let* ((val (string-to-number (pop bytes) 16))
9839 (shift-xor
9840 (if (= 0 eat)
9841 (cond
9842 ((>= val 252) (cons 6 252))
9843 ((>= val 248) (cons 5 248))
9844 ((>= val 240) (cons 4 240))
9845 ((>= val 224) (cons 3 224))
9846 ((>= val 192) (cons 2 192))
9847 (t (cons 0 0)))
9848 (cons 6 128))))
9849 (if (>= val 192) (setq eat (car shift-xor)))
9850 (setq val (logxor val (cdr shift-xor)))
9851 (setq sum (+ (lsh sum (car shift-xor)) val))
9852 (if (> eat 0) (setq eat (- eat 1)))
9853 (cond
9854 ((= 0 eat) ;multi byte
9855 (setq ret (concat ret (org-char-to-string sum)))
9856 (setq sum 0))
9857 ((not bytes) ; single byte(s)
9858 (setq ret (org-link-unescape-single-byte-sequence hex))))
9859 )) ;; end (while bytes
9860 ret )))
9861
9862 (defun org-link-unescape-single-byte-sequence (hex)
9863 "Unhexify hex-encoded single byte character sequences."
9864 (mapconcat (lambda (byte)
9865 (char-to-string (string-to-number byte 16)))
9866 (cdr (split-string hex "%")) ""))
9867
9868 (defun org-xor (a b)
9869 "Exclusive or."
9870 (if a (not b) b))
9871
9872 (defun org-fixup-message-id-for-http (s)
9873 "Replace special characters in a message id, so it can be used in an http query."
9874 (when (string-match "%" s)
9875 (setq s (mapconcat (lambda (c)
9876 (if (eq c ?%)
9877 "%25"
9878 (char-to-string c)))
9879 s "")))
9880 (while (string-match "<" s)
9881 (setq s (replace-match "%3C" t t s)))
9882 (while (string-match ">" s)
9883 (setq s (replace-match "%3E" t t s)))
9884 (while (string-match "@" s)
9885 (setq s (replace-match "%40" t t s)))
9886 s)
9887
9888 (defun org-link-prettify (link)
9889 "Return a human-readable representation of LINK.
9890 The car of LINK must be a raw link the cdr of LINK must be either
9891 a link description or nil."
9892 (let ((desc (or (cadr link) "<no description>")))
9893 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9894 "<" (car link) ">")))
9895
9896 ;;;###autoload
9897 (defun org-insert-link-global ()
9898 "Insert a link like Org-mode does.
9899 This command can be called in any mode to insert a link in Org-mode syntax."
9900 (interactive)
9901 (org-load-modules-maybe)
9902 (org-run-like-in-org-mode 'org-insert-link))
9903
9904 (defun org-insert-all-links (&optional keep)
9905 "Insert all links in `org-stored-links'."
9906 (interactive "P")
9907 (let ((links (copy-sequence org-stored-links)) l)
9908 (while (setq l (if keep (pop links) (pop org-stored-links)))
9909 (insert "- ")
9910 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9911 (insert "\n"))))
9912
9913 (defun org-link-fontify-links-to-this-file ()
9914 "Fontify links to the current file in `org-stored-links'."
9915 (let ((f (buffer-file-name)) a b)
9916 (setq a (mapcar (lambda(l)
9917 (let ((ll (car l)))
9918 (when (and (string-match "^file:\\(.+\\)::" ll)
9919 (equal f (expand-file-name (match-string 1 ll))))
9920 ll)))
9921 org-stored-links))
9922 (when (featurep 'org-id)
9923 (setq b (mapcar (lambda(l)
9924 (let ((ll (car l)))
9925 (when (and (string-match "^id:\\(.+\\)$" ll)
9926 (equal f (expand-file-name
9927 (or (org-id-find-id-file
9928 (match-string 1 ll)) ""))))
9929 ll)))
9930 org-stored-links)))
9931 (mapcar (lambda(l)
9932 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9933 (delq nil (append a b)))))
9934
9935 (defvar org-link-links-in-this-file nil)
9936 (defun org-insert-link (&optional complete-file link-location default-description)
9937 "Insert a link. At the prompt, enter the link.
9938
9939 Completion can be used to insert any of the link protocol prefixes like
9940 http or ftp in use.
9941
9942 The history can be used to select a link previously stored with
9943 `org-store-link'. When the empty string is entered (i.e. if you just
9944 press RET at the prompt), the link defaults to the most recently
9945 stored link. As SPC triggers completion in the minibuffer, you need to
9946 use M-SPC or C-q SPC to force the insertion of a space character.
9947
9948 You will also be prompted for a description, and if one is given, it will
9949 be displayed in the buffer instead of the link.
9950
9951 If there is already a link at point, this command will allow you to edit link
9952 and description parts.
9953
9954 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9955 be selected using completion. The path to the file will be relative to the
9956 current directory if the file is in the current directory or a subdirectory.
9957 Otherwise, the link will be the absolute path as completed in the minibuffer
9958 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9959 option `org-link-file-path-type'.
9960
9961 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9962 the current directory or below.
9963
9964 With three \\[universal-argument] prefixes, negate the meaning of
9965 `org-keep-stored-link-after-insertion'.
9966
9967 If `org-make-link-description-function' is non-nil, this function will be
9968 called with the link target, and the result will be the default
9969 link description.
9970
9971 If the LINK-LOCATION parameter is non-nil, this value will be
9972 used as the link location instead of reading one interactively.
9973
9974 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9975 be used as the default description."
9976 (interactive "P")
9977 (let* ((wcf (current-window-configuration))
9978 (origbuf (current-buffer))
9979 (region (if (org-region-active-p)
9980 (buffer-substring (region-beginning) (region-end))))
9981 (remove (and region (list (region-beginning) (region-end))))
9982 (desc region)
9983 tmphist ; byte-compile incorrectly complains about this
9984 (link link-location)
9985 (abbrevs org-link-abbrev-alist-local)
9986 entry file all-prefixes auto-desc)
9987 (cond
9988 (link-location) ; specified by arg, just use it.
9989 ((org-in-regexp org-bracket-link-regexp 1)
9990 ;; We do have a link at point, and we are going to edit it.
9991 (setq remove (list (match-beginning 0) (match-end 0)))
9992 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9993 (setq link (read-string "Link: "
9994 (org-link-unescape
9995 (org-match-string-no-properties 1)))))
9996 ((or (org-in-regexp org-angle-link-re)
9997 (org-in-regexp org-plain-link-re))
9998 ;; Convert to bracket link
9999 (setq remove (list (match-beginning 0) (match-end 0))
10000 link (read-string "Link: "
10001 (org-remove-angle-brackets (match-string 0)))))
10002 ((member complete-file '((4) (16)))
10003 ;; Completing read for file names.
10004 (setq link (org-file-complete-link complete-file)))
10005 (t
10006 ;; Read link, with completion for stored links.
10007 (org-link-fontify-links-to-this-file)
10008 (org-switch-to-buffer-other-window "*Org Links*")
10009 (with-current-buffer "*Org Links*"
10010 (erase-buffer)
10011 (insert "Insert a link.
10012 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10013 (when org-stored-links
10014 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10015 (insert (mapconcat 'org-link-prettify
10016 (reverse org-stored-links) "\n")))
10017 (goto-char (point-min)))
10018 (let ((cw (selected-window)))
10019 (select-window (get-buffer-window "*Org Links*" 'visible))
10020 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10021 (unless (pos-visible-in-window-p (point-max))
10022 (org-fit-window-to-buffer))
10023 (and (window-live-p cw) (select-window cw)))
10024 ;; Fake a link history, containing the stored links.
10025 (setq tmphist (append (mapcar 'car org-stored-links)
10026 org-insert-link-history))
10027 (setq all-prefixes (append (mapcar 'car abbrevs)
10028 (mapcar 'car org-link-abbrev-alist)
10029 org-link-types))
10030 (unwind-protect
10031 (progn
10032 (setq link
10033 (org-completing-read
10034 "Link: "
10035 (append
10036 (mapcar (lambda (x) (concat x ":"))
10037 all-prefixes)
10038 (mapcar 'car org-stored-links))
10039 nil nil nil
10040 'tmphist
10041 (caar org-stored-links)))
10042 (if (not (string-match "\\S-" link))
10043 (user-error "No link selected"))
10044 (mapc (lambda(l)
10045 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10046 org-stored-links)
10047 (if (or (member link all-prefixes)
10048 (and (equal ":" (substring link -1))
10049 (member (substring link 0 -1) all-prefixes)
10050 (setq link (substring link 0 -1))))
10051 (setq link (with-current-buffer origbuf
10052 (org-link-try-special-completion link)))))
10053 (set-window-configuration wcf)
10054 (kill-buffer "*Org Links*"))
10055 (setq entry (assoc link org-stored-links))
10056 (or entry (push link org-insert-link-history))
10057 (setq desc (or desc (nth 1 entry)))))
10058
10059 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10060 (not org-keep-stored-link-after-insertion))
10061 (setq org-stored-links (delq (assoc link org-stored-links)
10062 org-stored-links)))
10063
10064 (if (and (string-match org-plain-link-re link)
10065 (not (string-match org-ts-regexp link)))
10066 ;; URL-like link, normalize the use of angular brackets.
10067 (setq link (org-remove-angle-brackets link)))
10068
10069 ;; Check if we are linking to the current file with a search
10070 ;; option If yes, simplify the link by using only the search
10071 ;; option.
10072 (when (and buffer-file-name
10073 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10074 (let* ((path (match-string 1 link))
10075 (case-fold-search nil)
10076 (search (match-string 2 link)))
10077 (save-match-data
10078 (if (equal (file-truename buffer-file-name) (file-truename path))
10079 ;; We are linking to this same file, with a search option
10080 (setq link search)))))
10081
10082 ;; Check if we can/should use a relative path. If yes, simplify the link
10083 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10084 (let* ((type (match-string 1 link))
10085 (path (match-string 2 link))
10086 (origpath path)
10087 (case-fold-search nil))
10088 (cond
10089 ((or (eq org-link-file-path-type 'absolute)
10090 (equal complete-file '(16)))
10091 (setq path (abbreviate-file-name (expand-file-name path))))
10092 ((eq org-link-file-path-type 'noabbrev)
10093 (setq path (expand-file-name path)))
10094 ((eq org-link-file-path-type 'relative)
10095 (setq path (file-relative-name path)))
10096 (t
10097 (save-match-data
10098 (if (string-match (concat "^" (regexp-quote
10099 (expand-file-name
10100 (file-name-as-directory
10101 default-directory))))
10102 (expand-file-name path))
10103 ;; We are linking a file with relative path name.
10104 (setq path (substring (expand-file-name path)
10105 (match-end 0)))
10106 (setq path (abbreviate-file-name (expand-file-name path)))))))
10107 (setq link (concat type path))
10108 (if (equal desc origpath)
10109 (setq desc path))))
10110
10111 (if org-make-link-description-function
10112 (setq desc
10113 (or (condition-case nil
10114 (funcall org-make-link-description-function link desc)
10115 (error (progn (message "Can't get link description from `%s'"
10116 (symbol-name org-make-link-description-function))
10117 (sit-for 2) nil)))
10118 (read-string "Description: " default-description)))
10119 (if default-description (setq desc default-description)
10120 (setq desc (or (and auto-desc desc)
10121 (read-string "Description: " desc)))))
10122
10123 (unless (string-match "\\S-" desc) (setq desc nil))
10124 (if remove (apply 'delete-region remove))
10125 (insert (org-make-link-string link desc))))
10126
10127 (defun org-link-try-special-completion (type)
10128 "If there is completion support for link type TYPE, offer it."
10129 (let ((fun (intern (concat "org-" type "-complete-link"))))
10130 (if (functionp fun)
10131 (funcall fun)
10132 (read-string "Link (no completion support): " (concat type ":")))))
10133
10134 (defun org-file-complete-link (&optional arg)
10135 "Create a file link using completion."
10136 (let (file link)
10137 (setq file (org-iread-file-name "File: "))
10138 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10139 (pwd1 (file-name-as-directory (abbreviate-file-name
10140 (expand-file-name ".")))))
10141 (cond
10142 ((equal arg '(16))
10143 (setq link (concat
10144 "file:"
10145 (abbreviate-file-name (expand-file-name file)))))
10146 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10147 (setq link (concat "file:" (match-string 1 file))))
10148 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10149 (expand-file-name file))
10150 (setq link (concat
10151 "file:" (match-string 1 (expand-file-name file)))))
10152 (t (setq link (concat "file:" file)))))
10153 link))
10154
10155 (defun org-iread-file-name (&rest args)
10156 "Read-file-name using `ido-mode' speedup if available.
10157 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10158 See `read-file-name' for a description of parameters."
10159 (org-without-partial-completion
10160 (if (and org-completion-use-ido
10161 (fboundp 'ido-read-file-name)
10162 (boundp 'ido-mode) ido-mode
10163 (listp (second args)))
10164 (let ((ido-enter-matching-directory nil))
10165 (apply 'ido-read-file-name args))
10166 (apply 'read-file-name args))))
10167
10168 (defun org-completing-read (&rest args)
10169 "Completing-read with SPACE being a normal character."
10170 (let ((enable-recursive-minibuffers t)
10171 (minibuffer-local-completion-map
10172 (copy-keymap minibuffer-local-completion-map)))
10173 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10174 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10175 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10176 (apply 'org-icompleting-read args)))
10177
10178 (defun org-completing-read-no-i (&rest args)
10179 (let (org-completion-use-ido org-completion-use-iswitchb)
10180 (apply 'org-completing-read args)))
10181
10182 (defun org-iswitchb-completing-read (prompt choices &rest args)
10183 "Use iswitch as a completing-read replacement to choose from choices.
10184 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10185 from."
10186 (let* ((iswitchb-use-virtual-buffers nil)
10187 (iswitchb-make-buflist-hook
10188 (lambda ()
10189 (setq iswitchb-temp-buflist choices))))
10190 (iswitchb-read-buffer prompt)))
10191
10192 (defun org-icompleting-read (&rest args)
10193 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10194 (org-without-partial-completion
10195 (if (and org-completion-use-ido
10196 (fboundp 'ido-completing-read)
10197 (boundp 'ido-mode) ido-mode
10198 (listp (second args)))
10199 (let ((ido-enter-matching-directory nil))
10200 (apply 'ido-completing-read (concat (car args))
10201 (if (consp (car (nth 1 args)))
10202 (mapcar 'car (nth 1 args))
10203 (nth 1 args))
10204 (cddr args)))
10205 (if (and org-completion-use-iswitchb
10206 (boundp 'iswitchb-mode) iswitchb-mode
10207 (listp (second args)))
10208 (apply 'org-iswitchb-completing-read (concat (car args))
10209 (if (consp (car (nth 1 args)))
10210 (mapcar 'car (nth 1 args))
10211 (nth 1 args))
10212 (cddr args))
10213 (apply 'completing-read args)))))
10214
10215 (defun org-extract-attributes (s)
10216 "Extract the attributes cookie from a string and set as text property."
10217 (let (a attr (start 0) key value)
10218 (save-match-data
10219 (when (string-match "{{\\([^}]+\\)}}$" s)
10220 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10221 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10222 (setq key (match-string 1 a) value (match-string 2 a)
10223 start (match-end 0)
10224 attr (plist-put attr (intern key) value))))
10225 (org-add-props s nil 'org-attr attr))
10226 s))
10227
10228 ;;; Opening/following a link
10229
10230 (defvar org-link-search-failed nil)
10231
10232 (defvar org-open-link-functions nil
10233 "Hook for functions finding a plain text link.
10234 These functions must take a single argument, the link content.
10235 They will be called for links that look like [[link text][description]]
10236 when LINK TEXT does not have a protocol like \"http:\" and does not look
10237 like a filename (e.g. \"./blue.png\").
10238
10239 These functions will be called *before* Org attempts to resolve the
10240 link by doing text searches in the current buffer - so if you want a
10241 link \"[[target]]\" to still find \"<<target>>\", your function should
10242 handle this as a special case.
10243
10244 When the function does handle the link, it must return a non-nil value.
10245 If it decides that it is not responsible for this link, it must return
10246 nil to indicate that that Org-mode can continue with other options
10247 like exact and fuzzy text search.")
10248
10249 (defun org-next-link (&optional search-backward)
10250 "Move forward to the next link.
10251 If the link is in hidden text, expose it."
10252 (interactive "P")
10253 (when (and org-link-search-failed (eq this-command last-command))
10254 (goto-char (point-min))
10255 (message "Link search wrapped back to beginning of buffer"))
10256 (setq org-link-search-failed nil)
10257 (let* ((pos (point))
10258 (ct (org-context))
10259 (a (assoc :link ct))
10260 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10261 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10262 ((looking-at org-any-link-re)
10263 ;; Don't stay stuck at link without an org-link face
10264 (forward-char (if search-backward -1 1))))
10265 (if (funcall srch-fun org-any-link-re nil t)
10266 (progn
10267 (goto-char (match-beginning 0))
10268 (if (outline-invisible-p) (org-show-context)))
10269 (goto-char pos)
10270 (setq org-link-search-failed t)
10271 (message "No further link found"))))
10272
10273 (defun org-previous-link ()
10274 "Move backward to the previous link.
10275 If the link is in hidden text, expose it."
10276 (interactive)
10277 (funcall 'org-next-link t))
10278
10279 (defun org-translate-link (s)
10280 "Translate a link string if a translation function has been defined."
10281 (if (and org-link-translation-function
10282 (fboundp org-link-translation-function)
10283 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10284 (progn
10285 (setq s (funcall org-link-translation-function
10286 (match-string 1 s) (match-string 2 s)))
10287 (concat (car s) ":" (cdr s)))
10288 s))
10289
10290 (defun org-translate-link-from-planner (type path)
10291 "Translate a link from Emacs Planner syntax so that Org can follow it.
10292 This is still an experimental function, your mileage may vary."
10293 (cond
10294 ((member type '("http" "https" "news" "ftp"))
10295 ;; standard Internet links are the same.
10296 nil)
10297 ((and (equal type "irc") (string-match "^//" path))
10298 ;; Planner has two / at the beginning of an irc link, we have 1.
10299 ;; We should have zero, actually....
10300 (setq path (substring path 1)))
10301 ((and (equal type "lisp") (string-match "^/" path))
10302 ;; Planner has a slash, we do not.
10303 (setq type "elisp" path (substring path 1)))
10304 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10305 ;; A typical message link. Planner has the id after the final slash,
10306 ;; we separate it with a hash mark
10307 (setq path (concat (match-string 1 path) "#"
10308 (org-remove-angle-brackets (match-string 2 path))))))
10309 (cons type path))
10310
10311 (defun org-find-file-at-mouse (ev)
10312 "Open file link or URL at mouse."
10313 (interactive "e")
10314 (mouse-set-point ev)
10315 (org-open-at-point 'in-emacs))
10316
10317 (defun org-open-at-mouse (ev)
10318 "Open file link or URL at mouse.
10319 See the docstring of `org-open-file' for details."
10320 (interactive "e")
10321 (mouse-set-point ev)
10322 (if (eq major-mode 'org-agenda-mode)
10323 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10324 (org-open-at-point))
10325
10326 (defvar org-window-config-before-follow-link nil
10327 "The window configuration before following a link.
10328 This is saved in case the need arises to restore it.")
10329
10330 (defvar org-open-link-marker (make-marker)
10331 "Marker pointing to the location where `org-open-at-point' was called.")
10332
10333 ;;;###autoload
10334 (defun org-open-at-point-global ()
10335 "Follow a link like Org-mode does.
10336 This command can be called in any mode to follow a link that has
10337 Org-mode syntax."
10338 (interactive)
10339 (org-run-like-in-org-mode 'org-open-at-point))
10340
10341 ;;;###autoload
10342 (defun org-open-link-from-string (s &optional arg reference-buffer)
10343 "Open a link in the string S, as if it was in Org-mode."
10344 (interactive "sLink: \nP")
10345 (let ((reference-buffer (or reference-buffer (current-buffer))))
10346 (with-temp-buffer
10347 (let ((org-inhibit-startup (not reference-buffer)))
10348 (org-mode)
10349 (insert s)
10350 (goto-char (point-min))
10351 (when reference-buffer
10352 (setq org-link-abbrev-alist-local
10353 (with-current-buffer reference-buffer
10354 org-link-abbrev-alist-local)))
10355 (org-open-at-point arg reference-buffer)))))
10356
10357 (defvar org-open-at-point-functions nil
10358 "Hook that is run when following a link at point.
10359
10360 Functions in this hook must return t if they identify and follow
10361 a link at point. If they don't find anything interesting at point,
10362 they must return nil.")
10363
10364 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10365 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10366 (defun org-open-at-point (&optional arg reference-buffer)
10367 "Open link at or after point.
10368 If there is no link at point, this function will search forward up to
10369 the end of the current line.
10370 Normally, files will be opened by an appropriate application. If the
10371 optional prefix argument ARG is non-nil, Emacs will visit the file.
10372 With a double prefix argument, try to open outside of Emacs, in the
10373 application the system uses for this file type."
10374 (interactive "P")
10375 ;; if in a code block, then open the block's results
10376 (unless (call-interactively #'org-babel-open-src-block-result)
10377 (org-load-modules-maybe)
10378 (move-marker org-open-link-marker (point))
10379 (setq org-window-config-before-follow-link (current-window-configuration))
10380 (org-remove-occur-highlights nil nil t)
10381 (cond
10382 ((and (org-at-heading-p)
10383 (not (org-at-timestamp-p t))
10384 (not (org-in-regexp
10385 (concat org-plain-link-re "\\|"
10386 org-bracket-link-regexp "\\|"
10387 org-angle-link-re "\\|"
10388 "[ \t]:[^ \t\n]+:[ \t]*$")))
10389 (not (get-text-property (point) 'org-linked-text)))
10390 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10391 (lk0 (car lkall))
10392 (lk (if (stringp lk0) (list lk0) lk0))
10393 (lkend (cdr lkall)))
10394 (mapcar (lambda(l)
10395 (search-forward l nil lkend)
10396 (goto-char (match-beginning 0))
10397 (org-open-at-point))
10398 lk))
10399 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10400 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10401 ((and (org-at-timestamp-p t)
10402 (not (org-in-regexp org-bracket-link-regexp)))
10403 (org-follow-timestamp-link))
10404 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10405 (not (org-in-regexp org-any-link-re)))
10406 (org-footnote-action))
10407 (t
10408 (let (type path link line search (pos (point)))
10409 (catch 'match
10410 (save-excursion
10411 (or (org-in-regexp org-plain-link-re)
10412 (skip-chars-forward "^]\n\r"))
10413 (when (org-in-regexp org-bracket-link-regexp 1)
10414 (setq link (org-extract-attributes
10415 (org-link-unescape (org-match-string-no-properties 1))))
10416 (while (string-match " *\n *" link)
10417 (setq link (replace-match " " t t link)))
10418 (setq link (org-link-expand-abbrev link))
10419 (cond
10420 ((or (file-name-absolute-p link)
10421 (string-match "^\\.\\.?/" link))
10422 (setq type "file" path link))
10423 ((string-match org-link-re-with-space3 link)
10424 (setq type (match-string 1 link) path (match-string 2 link)))
10425 ((string-match "^help:+\\(.+\\)" link)
10426 (setq type "help" path (match-string 1 link)))
10427 (t (setq type "thisfile" path link)))
10428 (throw 'match t)))
10429
10430 (when (get-text-property (point) 'org-linked-text)
10431 (setq type "thisfile"
10432 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10433 (1+ (point)) (point))
10434 path (buffer-substring
10435 (or (previous-single-property-change pos 'org-linked-text)
10436 (point-min))
10437 (or (next-single-property-change pos 'org-linked-text)
10438 (point-max)))
10439 ;; Ensure we will search for a <<<radio>>> link, not
10440 ;; a simple reference like <<ref>>
10441 path (concat "<" path))
10442 (throw 'match t))
10443
10444 (save-excursion
10445 (when (or (org-in-regexp org-angle-link-re)
10446 (let ((match (org-in-regexp org-plain-link-re)))
10447 ;; Check a plain link is not within a bracket link
10448 (and match
10449 (save-excursion
10450 (save-match-data
10451 (progn
10452 (goto-char (car match))
10453 (not (org-in-regexp org-bracket-link-regexp)))))))
10454 (let ((line_ending (save-excursion (end-of-line) (point))))
10455 ;; We are in a line before a plain or bracket link
10456 (or (re-search-forward org-plain-link-re line_ending t)
10457 (re-search-forward org-bracket-link-regexp line_ending t))))
10458 (setq type (match-string 1)
10459 path (org-link-unescape (match-string 2)))
10460 (throw 'match t)))
10461 (save-excursion
10462 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10463 (setq type "tags"
10464 path (match-string 1))
10465 (while (string-match ":" path)
10466 (setq path (replace-match "+" t t path)))
10467 (throw 'match t)))
10468 (when (org-in-regexp "<\\([^><\n]+\\)>")
10469 (setq type "tree-match"
10470 path (match-string 1))
10471 (throw 'match t)))
10472 (unless path
10473 (user-error "No link found"))
10474
10475 ;; switch back to reference buffer
10476 ;; needed when if called in a temporary buffer through
10477 ;; org-open-link-from-string
10478 (with-current-buffer (or reference-buffer (current-buffer))
10479
10480 ;; Remove any trailing spaces in path
10481 (if (string-match " +\\'" path)
10482 (setq path (replace-match "" t t path)))
10483 (if (and org-link-translation-function
10484 (fboundp org-link-translation-function))
10485 ;; Check if we need to translate the link
10486 (let ((tmp (funcall org-link-translation-function type path)))
10487 (setq type (car tmp) path (cdr tmp))))
10488
10489 (cond
10490
10491 ((assoc type org-link-protocols)
10492 (funcall (nth 1 (assoc type org-link-protocols)) path))
10493
10494 ((equal type "help")
10495 (let ((f-or-v (intern path)))
10496 (cond ((fboundp f-or-v)
10497 (describe-function f-or-v))
10498 ((boundp f-or-v)
10499 (describe-variable f-or-v))
10500 (t (error "Not a known function or variable")))))
10501
10502 ((equal type "mailto")
10503 (let ((cmd (car org-link-mailto-program))
10504 (args (cdr org-link-mailto-program)) args1
10505 (address path) (subject "") a)
10506 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10507 (setq address (match-string 1 path)
10508 subject (org-link-escape (match-string 2 path))))
10509 (while args
10510 (cond
10511 ((not (stringp (car args))) (push (pop args) args1))
10512 (t (setq a (pop args))
10513 (if (string-match "%a" a)
10514 (setq a (replace-match address t t a)))
10515 (if (string-match "%s" a)
10516 (setq a (replace-match subject t t a)))
10517 (push a args1))))
10518 (apply cmd (nreverse args1))))
10519
10520 ((member type '("http" "https" "ftp" "news"))
10521 (browse-url
10522 (concat type ":"
10523 (if (org-string-match-p
10524 (concat "[[:nonascii:]"
10525 org-link-escape-chars-browser "]")
10526 path)
10527 (org-link-escape path org-link-escape-chars-browser)
10528 path))))
10529
10530 ((string= type "doi")
10531 (browse-url
10532 (concat org-doi-server-url
10533 (if (org-string-match-p
10534 (concat "[[:nonascii:]"
10535 org-link-escape-chars-browser "]")
10536 path)
10537 (org-link-escape path org-link-escape-chars-browser)
10538 path))))
10539
10540 ((member type '("message"))
10541 (browse-url (concat type ":" path)))
10542
10543 ((string= type "tags")
10544 (org-tags-view arg path))
10545
10546 ((string= type "tree-match")
10547 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10548
10549 ((string= type "file")
10550 (if (string-match "::\\([0-9]+\\)\\'" path)
10551 (setq line (string-to-number (match-string 1 path))
10552 path (substring path 0 (match-beginning 0)))
10553 (if (string-match "::\\(.+\\)\\'" path)
10554 (setq search (match-string 1 path)
10555 path (substring path 0 (match-beginning 0)))))
10556 (if (string-match "[*?{]" (file-name-nondirectory path))
10557 (dired path)
10558 (org-open-file path arg line search)))
10559
10560 ((string= type "shell")
10561 (let ((buf (generate-new-buffer "*Org Shell Output"))
10562 (cmd path))
10563 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10564 (string-match org-confirm-shell-link-not-regexp cmd))
10565 (not org-confirm-shell-link-function)
10566 (funcall org-confirm-shell-link-function
10567 (format "Execute \"%s\" in shell? "
10568 (org-add-props cmd nil
10569 'face 'org-warning))))
10570 (progn
10571 (message "Executing %s" cmd)
10572 (shell-command cmd buf)
10573 (if (featurep 'midnight)
10574 (setq clean-buffer-list-kill-buffer-names
10575 (cons buf clean-buffer-list-kill-buffer-names))))
10576 (error "Abort"))))
10577
10578 ((string= type "elisp")
10579 (let ((cmd path))
10580 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10581 (string-match org-confirm-elisp-link-not-regexp cmd))
10582 (not org-confirm-elisp-link-function)
10583 (funcall org-confirm-elisp-link-function
10584 (format "Execute \"%s\" as elisp? "
10585 (org-add-props cmd nil
10586 'face 'org-warning))))
10587 (message "%s => %s" cmd
10588 (if (equal (string-to-char cmd) ?\()
10589 (eval (read cmd))
10590 (call-interactively (read cmd))))
10591 (error "Abort"))))
10592
10593 ((and (string= type "thisfile")
10594 (or (run-hook-with-args-until-success
10595 'org-open-link-functions path)
10596 (and link
10597 (string-match "^id:" link)
10598 (or (featurep 'org-id) (require 'org-id))
10599 (progn
10600 (funcall (nth 1 (assoc "id" org-link-protocols))
10601 (substring path 3))
10602 t)))))
10603
10604 ((string= type "thisfile")
10605 (if arg
10606 (switch-to-buffer-other-window
10607 (org-get-buffer-for-internal-link (current-buffer)))
10608 (org-mark-ring-push))
10609 (let ((cmd `(org-link-search
10610 ,path
10611 ,(cond ((equal arg '(4)) ''occur)
10612 ((equal arg '(16)) ''org-occur))
10613 ,pos)))
10614 (condition-case nil (let ((org-link-search-inhibit-query t))
10615 (eval cmd))
10616 (error (progn (widen) (eval cmd))))))
10617
10618 (t (browse-url-at-point)))))))
10619 (move-marker org-open-link-marker nil)
10620 (run-hook-with-args 'org-follow-link-hook)))
10621
10622 (defsubst org-uniquify (list)
10623 "Non-destructively remove duplicate elements from LIST."
10624 (let ((res (copy-sequence list))) (delete-dups res)))
10625
10626 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10627 "Offer links in the current entry and return the selected link.
10628 If there is only one link, return it.
10629 If NTH is an integer, return the NTH link found.
10630 If ZERO is a string, check also this string for a link, and if
10631 there is one, return it."
10632 (with-current-buffer buffer
10633 (save-excursion
10634 (save-restriction
10635 (widen)
10636 (goto-char marker)
10637 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10638 "\\(" org-angle-link-re "\\)\\|"
10639 "\\(" org-plain-link-re "\\)"))
10640 (cnt ?0)
10641 (in-emacs (if (integerp nth) nil nth))
10642 have-zero end links link c)
10643 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10644 (push (match-string 0 zero) links)
10645 (setq cnt (1- cnt) have-zero t))
10646 (save-excursion
10647 (org-back-to-heading t)
10648 (setq end (save-excursion (outline-next-heading) (point)))
10649 (while (re-search-forward re end t)
10650 (push (match-string 0) links))
10651 (setq links (org-uniquify (reverse links))))
10652 (cond
10653 ((null links)
10654 (message "No links"))
10655 ((equal (length links) 1)
10656 (setq link (car links)))
10657 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10658 (setq link (nth (if have-zero nth (1- nth)) links)))
10659 (t ; we have to select a link
10660 (save-excursion
10661 (save-window-excursion
10662 (delete-other-windows)
10663 (with-output-to-temp-buffer "*Select Link*"
10664 (mapc (lambda (l)
10665 (if (not (string-match org-bracket-link-regexp l))
10666 (princ (format "[%c] %s\n" (incf cnt)
10667 (org-remove-angle-brackets l)))
10668 (if (match-end 3)
10669 (princ (format "[%c] %s (%s)\n" (incf cnt)
10670 (match-string 3 l) (match-string 1 l)))
10671 (princ (format "[%c] %s\n" (incf cnt)
10672 (match-string 1 l))))))
10673 links))
10674 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10675 (message "Select link to open, RET to open all:")
10676 (setq c (read-char-exclusive))
10677 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10678 (when (equal c ?q) (error "Abort"))
10679 (if (equal c ?\C-m)
10680 (setq link links)
10681 (setq nth (- c ?0))
10682 (if have-zero (setq nth (1+ nth)))
10683 (unless (and (integerp nth) (>= (length links) nth))
10684 (user-error "Invalid link selection"))
10685 (setq link (nth (1- nth) links)))))
10686 (cons link end))))))
10687
10688 ;; Add special file links that specify the way of opening
10689
10690 (org-add-link-type "file+sys" 'org-open-file-with-system)
10691 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10692 (defun org-open-file-with-system (path)
10693 "Open file at PATH using the system way of opening it."
10694 (org-open-file path 'system))
10695 (defun org-open-file-with-emacs (path)
10696 "Open file at PATH in Emacs."
10697 (org-open-file path 'emacs))
10698
10699
10700 ;;; File search
10701
10702 (defvar org-create-file-search-functions nil
10703 "List of functions to construct the right search string for a file link.
10704 These functions are called in turn with point at the location to
10705 which the link should point.
10706
10707 A function in the hook should first test if it would like to
10708 handle this file type, for example by checking the `major-mode'
10709 or the file extension. If it decides not to handle this file, it
10710 should just return nil to give other functions a chance. If it
10711 does handle the file, it must return the search string to be used
10712 when following the link. The search string will be part of the
10713 file link, given after a double colon, and `org-open-at-point'
10714 will automatically search for it. If special measures must be
10715 taken to make the search successful, another function should be
10716 added to the companion hook `org-execute-file-search-functions',
10717 which see.
10718
10719 A function in this hook may also use `setq' to set the variable
10720 `description' to provide a suggestion for the descriptive text to
10721 be used for this link when it gets inserted into an Org-mode
10722 buffer with \\[org-insert-link].")
10723
10724 (defvar org-execute-file-search-functions nil
10725 "List of functions to execute a file search triggered by a link.
10726
10727 Functions added to this hook must accept a single argument, the
10728 search string that was part of the file link, the part after the
10729 double colon. The function must first check if it would like to
10730 handle this search, for example by checking the `major-mode' or
10731 the file extension. If it decides not to handle this search, it
10732 should just return nil to give other functions a chance. If it
10733 does handle the search, it must return a non-nil value to keep
10734 other functions from trying.
10735
10736 Each function can access the current prefix argument through the
10737 variable `current-prefix-arg'. Note that a single prefix is used
10738 to force opening a link in Emacs, so it may be good to only use a
10739 numeric or double prefix to guide the search function.
10740
10741 In case this is needed, a function in this hook can also restore
10742 the window configuration before `org-open-at-point' was called using:
10743
10744 (set-window-configuration org-window-config-before-follow-link)")
10745
10746 (defun org-link-search (s &optional type avoid-pos stealth)
10747 "Search for a link search option.
10748 If S is surrounded by forward slashes, it is interpreted as a
10749 regular expression. In org-mode files, this will create an `org-occur'
10750 sparse tree. In ordinary files, `occur' will be used to list matches.
10751 If the current buffer is in `dired-mode', grep will be used to search
10752 in all files. If AVOID-POS is given, ignore matches near that position.
10753
10754 When optional argument STEALTH is non-nil, do not modify
10755 visibility around point, thus ignoring
10756 `org-show-hierarchy-above', `org-show-following-heading' and
10757 `org-show-siblings' variables."
10758 (let ((case-fold-search t)
10759 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10760 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10761 (append '(("") (" ") ("\t") ("\n"))
10762 org-emphasis-alist)
10763 "\\|") "\\)"))
10764 (pos (point))
10765 (pre nil) (post nil)
10766 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10767 (cond
10768 ;; First check if there are any special search functions
10769 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10770 ;; Now try the builtin stuff
10771 ((and (equal (string-to-char s0) ?#)
10772 (> (length s0) 1)
10773 (save-excursion
10774 (goto-char (point-min))
10775 (and
10776 (re-search-forward
10777 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10778 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10779 (setq type 'dedicated
10780 pos (match-beginning 0))))
10781 ;; There is an exact target for this
10782 (goto-char pos)
10783 (org-back-to-heading t)))
10784 ((save-excursion
10785 (goto-char (point-min))
10786 (and
10787 (re-search-forward
10788 (concat "<<" (regexp-quote s0) ">>") nil t)
10789 (setq type 'dedicated
10790 pos (match-beginning 0))))
10791 ;; There is an exact target for this
10792 (goto-char pos))
10793 ((save-excursion
10794 (goto-char (point-min))
10795 (and
10796 (re-search-forward
10797 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10798 (setq type 'dedicated pos (match-beginning 0))))
10799 ;; Found an element with a matching #+name affiliated keyword.
10800 (goto-char pos))
10801 ((and (string-match "^(\\(.*\\))$" s0)
10802 (save-excursion
10803 (goto-char (point-min))
10804 (and
10805 (re-search-forward
10806 (concat "[^[]" (regexp-quote
10807 (format org-coderef-label-format
10808 (match-string 1 s0))))
10809 nil t)
10810 (setq type 'dedicated
10811 pos (1+ (match-beginning 0))))))
10812 ;; There is a coderef target for this
10813 (goto-char pos))
10814 ((string-match "^/\\(.*\\)/$" s)
10815 ;; A regular expression
10816 (cond
10817 ((derived-mode-p 'org-mode)
10818 (org-occur (match-string 1 s)))
10819 (t (org-do-occur (match-string 1 s)))))
10820 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10821 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10822 (goto-char (point-min))
10823 (cond
10824 ((let (case-fold-search)
10825 (re-search-forward (format org-complex-heading-regexp-format
10826 (regexp-quote s))
10827 nil t))
10828 ;; OK, found a match
10829 (setq type 'dedicated)
10830 (goto-char (match-beginning 0)))
10831 ((and (not org-link-search-inhibit-query)
10832 (eq org-link-search-must-match-exact-headline 'query-to-create)
10833 (y-or-n-p "No match - create this as a new heading? "))
10834 (goto-char (point-max))
10835 (or (bolp) (newline))
10836 (insert "* " s "\n")
10837 (beginning-of-line 0))
10838 (t
10839 (goto-char pos)
10840 (error "No match"))))
10841 (t
10842 ;; A normal search string
10843 (when (equal (string-to-char s) ?*)
10844 ;; Anchor on headlines, post may include tags.
10845 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10846 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10847 s (substring s 1)))
10848 (remove-text-properties
10849 0 (length s)
10850 '(face nil mouse-face nil keymap nil fontified nil) s)
10851 ;; Make a series of regular expressions to find a match
10852 (setq words (org-split-string s "[ \n\r\t]+")
10853
10854 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10855 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10856 "\\)" markers)
10857 re2a_ (concat "\\(" (mapconcat 'downcase words
10858 "[ \t\r\n]+") "\\)[ \t\r\n]")
10859 re2a (concat "[ \t\r\n]" re2a_)
10860 re4_ (concat "\\(" (mapconcat 'downcase words
10861 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10862 re4 (concat "[^a-zA-Z_]" re4_)
10863
10864 re1 (concat pre re2 post)
10865 re3 (concat pre (if pre re4_ re4) post)
10866 re5 (concat pre ".*" re4)
10867 re2 (concat pre re2)
10868 re2a (concat pre (if pre re2a_ re2a))
10869 re4 (concat pre (if pre re4_ re4))
10870 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10871 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10872 re5 "\\)"))
10873 (cond
10874 ((eq type 'org-occur) (org-occur reall))
10875 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10876 (t (goto-char (point-min))
10877 (setq type 'fuzzy)
10878 (if (or (and (org-search-not-self 1 re0 nil t)
10879 (setq type 'dedicated))
10880 (org-search-not-self 1 re1 nil t)
10881 (org-search-not-self 1 re2 nil t)
10882 (org-search-not-self 1 re2a nil t)
10883 (org-search-not-self 1 re3 nil t)
10884 (org-search-not-self 1 re4 nil t)
10885 (org-search-not-self 1 re5 nil t))
10886 (goto-char (match-beginning 1))
10887 (goto-char pos)
10888 (error "No match"))))))
10889 (and (derived-mode-p 'org-mode)
10890 (not stealth)
10891 (org-show-context 'link-search))
10892 type))
10893
10894 (defun org-search-not-self (group &rest args)
10895 "Execute `re-search-forward', but only accept matches that do not
10896 enclose the position of `org-open-link-marker'."
10897 (let ((m org-open-link-marker))
10898 (catch 'exit
10899 (while (apply 're-search-forward args)
10900 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10901 (goto-char (match-end group))
10902 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10903 (> (match-beginning 0) (marker-position m))
10904 (< (match-end 0) (marker-position m)))
10905 (save-match-data
10906 (or (not (org-in-regexp
10907 org-bracket-link-analytic-regexp 1))
10908 (not (match-end 4)) ; no description
10909 (and (<= (match-beginning 4) (point))
10910 (>= (match-end 4) (point))))))
10911 (throw 'exit (point))))))))
10912
10913 (defun org-get-buffer-for-internal-link (buffer)
10914 "Return a buffer to be used for displaying the link target of internal links."
10915 (cond
10916 ((not org-display-internal-link-with-indirect-buffer)
10917 buffer)
10918 ((string-match "(Clone)$" (buffer-name buffer))
10919 (message "Buffer is already a clone, not making another one")
10920 ;; we also do not modify visibility in this case
10921 buffer)
10922 (t ; make a new indirect buffer for displaying the link
10923 (let* ((bn (buffer-name buffer))
10924 (ibn (concat bn "(Clone)"))
10925 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10926 (with-current-buffer ib (org-overview))
10927 ib))))
10928
10929 (defun org-do-occur (regexp &optional cleanup)
10930 "Call the Emacs command `occur'.
10931 If CLEANUP is non-nil, remove the printout of the regular expression
10932 in the *Occur* buffer. This is useful if the regex is long and not useful
10933 to read."
10934 (occur regexp)
10935 (when cleanup
10936 (let ((cwin (selected-window)) win beg end)
10937 (when (setq win (get-buffer-window "*Occur*"))
10938 (select-window win))
10939 (goto-char (point-min))
10940 (when (re-search-forward "match[a-z]+" nil t)
10941 (setq beg (match-end 0))
10942 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10943 (setq end (1- (match-beginning 0)))))
10944 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10945 (goto-char (point-min))
10946 (select-window cwin))))
10947
10948 ;;; The mark ring for links jumps
10949
10950 (defvar org-mark-ring nil
10951 "Mark ring for positions before jumps in Org-mode.")
10952 (defvar org-mark-ring-last-goto nil
10953 "Last position in the mark ring used to go back.")
10954 ;; Fill and close the ring
10955 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10956 (loop for i from 1 to org-mark-ring-length do
10957 (push (make-marker) org-mark-ring))
10958 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10959 org-mark-ring)
10960
10961 (defun org-mark-ring-push (&optional pos buffer)
10962 "Put the current position or POS into the mark ring and rotate it."
10963 (interactive)
10964 (setq pos (or pos (point)))
10965 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10966 (move-marker (car org-mark-ring)
10967 (or pos (point))
10968 (or buffer (current-buffer)))
10969 (message "%s"
10970 (substitute-command-keys
10971 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10972
10973 (defun org-mark-ring-goto (&optional n)
10974 "Jump to the previous position in the mark ring.
10975 With prefix arg N, jump back that many stored positions. When
10976 called several times in succession, walk through the entire ring.
10977 Org-mode commands jumping to a different position in the current file,
10978 or to another Org-mode file, automatically push the old position
10979 onto the ring."
10980 (interactive "p")
10981 (let (p m)
10982 (if (eq last-command this-command)
10983 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10984 (setq p org-mark-ring))
10985 (setq org-mark-ring-last-goto p)
10986 (setq m (car p))
10987 (org-pop-to-buffer-same-window (marker-buffer m))
10988 (goto-char m)
10989 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10990
10991 (defun org-remove-angle-brackets (s)
10992 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10993 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10994 s)
10995 (defun org-add-angle-brackets (s)
10996 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10997 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10998 s)
10999 (defun org-remove-double-quotes (s)
11000 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11001 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11002 s)
11003
11004 ;;; Following specific links
11005
11006 (defun org-follow-timestamp-link ()
11007 "Open an agenda view for the time-stamp date/range at point."
11008 (cond
11009 ((org-at-date-range-p t)
11010 (let ((org-agenda-start-on-weekday)
11011 (t1 (match-string 1))
11012 (t2 (match-string 2)) tt1 tt2)
11013 (setq tt1 (time-to-days (org-time-string-to-time t1))
11014 tt2 (time-to-days (org-time-string-to-time t2)))
11015 (let ((org-agenda-buffer-tmp-name
11016 (format "*Org Agenda(a:%s)"
11017 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11018 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11019 ((org-at-timestamp-p t)
11020 (let ((org-agenda-buffer-tmp-name
11021 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11022 (org-agenda-list nil (time-to-days (org-time-string-to-time
11023 (substring (match-string 1) 0 10)))
11024 1)))
11025 (t (error "This should not happen"))))
11026
11027
11028 ;;; Following file links
11029 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11030 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11031 (declare-function mailcap-mime-info
11032 "mailcap" (string &optional request no-decode))
11033 (defvar org-wait nil)
11034 (defun org-open-file (path &optional in-emacs line search)
11035 "Open the file at PATH.
11036 First, this expands any special file name abbreviations. Then the
11037 configuration variable `org-file-apps' is checked if it contains an
11038 entry for this file type, and if yes, the corresponding command is launched.
11039
11040 If no application is found, Emacs simply visits the file.
11041
11042 With optional prefix argument IN-EMACS, Emacs will visit the file.
11043 With a double \\[universal-argument] \\[universal-argument] \
11044 prefix arg, Org tries to avoid opening in Emacs
11045 and to use an external application to visit the file.
11046
11047 Optional LINE specifies a line to go to, optional SEARCH a string
11048 to search for. If LINE or SEARCH is given, the file will be
11049 opened in Emacs, unless an entry from org-file-apps that makes
11050 use of groups in a regexp matches.
11051
11052 If you want to change the way frames are used when following a
11053 link, please customize `org-link-frame-setup'.
11054
11055 If the file does not exist, an error is thrown."
11056 (let* ((file (if (equal path "")
11057 buffer-file-name
11058 (substitute-in-file-name (expand-file-name path))))
11059 (file-apps (append org-file-apps (org-default-apps)))
11060 (apps (org-remove-if
11061 'org-file-apps-entry-match-against-dlink-p file-apps))
11062 (apps-dlink (org-remove-if-not
11063 'org-file-apps-entry-match-against-dlink-p file-apps))
11064 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11065 (dirp (if remp nil (file-directory-p file)))
11066 (file (if (and dirp org-open-directory-means-index-dot-org)
11067 (concat (file-name-as-directory file) "index.org")
11068 file))
11069 (a-m-a-p (assq 'auto-mode apps))
11070 (dfile (downcase file))
11071 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11072 (link (cond ((and (eq line nil)
11073 (eq search nil))
11074 file)
11075 (line
11076 (concat file "::" (number-to-string line)))
11077 (search
11078 (concat file "::" search))))
11079 (dlink (downcase link))
11080 (old-buffer (current-buffer))
11081 (old-pos (point))
11082 (old-mode major-mode)
11083 ext cmd link-match-data)
11084 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11085 (setq ext (match-string 1 dfile))
11086 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11087 (setq ext (match-string 1 dfile))))
11088 (cond
11089 ((member in-emacs '((16) system))
11090 (setq cmd (cdr (assoc 'system apps))))
11091 (in-emacs (setq cmd 'emacs))
11092 (t
11093 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11094 (and dirp (cdr (assoc 'directory apps)))
11095 ; first, try matching against apps-dlink
11096 ; if we get a match here, store the match data for later
11097 (let ((match (assoc-default dlink apps-dlink
11098 'string-match)))
11099 (if match
11100 (progn (setq link-match-data (match-data))
11101 match)
11102 (progn (setq in-emacs (or in-emacs line search))
11103 nil))) ; if we have no match in apps-dlink,
11104 ; always open the file in emacs if line or search
11105 ; is given (for backwards compatibility)
11106 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11107 'string-match)
11108 (cdr (assoc ext apps))
11109 (cdr (assoc t apps))))))
11110 (when (eq cmd 'system)
11111 (setq cmd (cdr (assoc 'system apps))))
11112 (when (eq cmd 'default)
11113 (setq cmd (cdr (assoc t apps))))
11114 (when (eq cmd 'mailcap)
11115 (require 'mailcap)
11116 (mailcap-parse-mailcaps)
11117 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11118 (command (mailcap-mime-info mime-type)))
11119 (if (stringp command)
11120 (setq cmd command)
11121 (setq cmd 'emacs))))
11122 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11123 (not (file-exists-p file))
11124 (not org-open-non-existing-files))
11125 (user-error "No such file: %s" file))
11126 (cond
11127 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11128 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11129 (while (string-match "['\"]%s['\"]" cmd)
11130 (setq cmd (replace-match "%s" t t cmd)))
11131 (while (string-match "%s" cmd)
11132 (setq cmd (replace-match
11133 (save-match-data
11134 (shell-quote-argument
11135 (convert-standard-filename file)))
11136 t t cmd)))
11137
11138 ;; Replace "%1", "%2" etc. in command with group matches from regex
11139 (save-match-data
11140 (let ((match-index 1)
11141 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11142 (set-match-data link-match-data)
11143 (while (<= match-index number-of-groups)
11144 (let ((regex (concat "%" (number-to-string match-index)))
11145 (replace-with (match-string match-index dlink)))
11146 (while (string-match regex cmd)
11147 (setq cmd (replace-match replace-with t t cmd))))
11148 (setq match-index (+ match-index 1)))))
11149
11150 (save-window-excursion
11151 (message "Running %s...done" cmd)
11152 (start-process-shell-command cmd nil cmd)
11153 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11154 ((or (stringp cmd)
11155 (eq cmd 'emacs))
11156 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11157 (widen)
11158 (if line (org-goto-line line)
11159 (if search (org-link-search search))))
11160 ((consp cmd)
11161 (let ((file (convert-standard-filename file)))
11162 (save-match-data
11163 (set-match-data link-match-data)
11164 (eval cmd))))
11165 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11166 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11167 (or (not (equal old-buffer (current-buffer)))
11168 (not (equal old-pos (point))))
11169 (org-mark-ring-push old-pos old-buffer))))
11170
11171 (defun org-file-apps-entry-match-against-dlink-p (entry)
11172 "This function returns non-nil if `entry' uses a regular
11173 expression which should be matched against the whole link by
11174 org-open-file.
11175
11176 It assumes that is the case when the entry uses a regular
11177 expression which has at least one grouping construct and the
11178 action is either a lisp form or a command string containing
11179 '%1', i.e. using at least one subexpression match as a
11180 parameter."
11181 (let ((selector (car entry))
11182 (action (cdr entry)))
11183 (if (stringp selector)
11184 (and (> (regexp-opt-depth selector) 0)
11185 (or (and (stringp action)
11186 (string-match "%[0-9]" action))
11187 (consp action)))
11188 nil)))
11189
11190 (defun org-default-apps ()
11191 "Return the default applications for this operating system."
11192 (cond
11193 ((eq system-type 'darwin)
11194 org-file-apps-defaults-macosx)
11195 ((eq system-type 'windows-nt)
11196 org-file-apps-defaults-windowsnt)
11197 (t org-file-apps-defaults-gnu)))
11198
11199 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11200 "Convert extensions to regular expressions in the cars of LIST.
11201 Also, weed out any non-string entries, because the return value is used
11202 only for regexp matching.
11203 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11204 point to the symbol `emacs', indicating that the file should
11205 be opened in Emacs."
11206 (append
11207 (delq nil
11208 (mapcar (lambda (x)
11209 (if (not (stringp (car x)))
11210 nil
11211 (if (string-match "\\W" (car x))
11212 x
11213 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11214 list))
11215 (if add-auto-mode
11216 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11217
11218 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11219 (defun org-file-remote-p (file)
11220 "Test whether FILE specifies a location on a remote system.
11221 Return non-nil if the location is indeed remote.
11222
11223 For example, the filename \"/user@host:/foo\" specifies a location
11224 on the system \"/user@host:\"."
11225 (cond ((fboundp 'file-remote-p)
11226 (file-remote-p file))
11227 ((fboundp 'tramp-handle-file-remote-p)
11228 (tramp-handle-file-remote-p file))
11229 ((and (boundp 'ange-ftp-name-format)
11230 (string-match (car ange-ftp-name-format) file))
11231 t)))
11232
11233
11234 ;;;; Refiling
11235
11236 (defun org-get-org-file ()
11237 "Read a filename, with default directory `org-directory'."
11238 (let ((default (or org-default-notes-file remember-data-file)))
11239 (read-file-name (format "File name [%s]: " default)
11240 (file-name-as-directory org-directory)
11241 default)))
11242
11243 (defun org-notes-order-reversed-p ()
11244 "Check if the current file should receive notes in reversed order."
11245 (cond
11246 ((not org-reverse-note-order) nil)
11247 ((eq t org-reverse-note-order) t)
11248 ((not (listp org-reverse-note-order)) nil)
11249 (t (catch 'exit
11250 (let ((all org-reverse-note-order)
11251 entry)
11252 (while (setq entry (pop all))
11253 (if (string-match (car entry) buffer-file-name)
11254 (throw 'exit (cdr entry))))
11255 nil)))))
11256
11257 (defvar org-refile-target-table nil
11258 "The list of refile targets, created by `org-refile'.")
11259
11260 (defvar org-agenda-new-buffers nil
11261 "Buffers created to visit agenda files.")
11262
11263 (defvar org-refile-cache nil
11264 "Cache for refile targets.")
11265
11266 (defvar org-refile-markers nil
11267 "All the markers used for caching refile locations.")
11268
11269 (defun org-refile-marker (pos)
11270 "Get a new refile marker, but only if caching is in use."
11271 (if (not org-refile-use-cache)
11272 pos
11273 (let ((m (make-marker)))
11274 (move-marker m pos)
11275 (push m org-refile-markers)
11276 m)))
11277
11278 (defun org-refile-cache-clear ()
11279 "Clear the refile cache and disable all the markers."
11280 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11281 (setq org-refile-markers nil)
11282 (setq org-refile-cache nil)
11283 (message "Refile cache has been cleared"))
11284
11285 (defun org-refile-cache-check-set (set)
11286 "Check if all the markers in the cache still have live buffers."
11287 (let (marker)
11288 (catch 'exit
11289 (while (and set (setq marker (nth 3 (pop set))))
11290 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11291 (when (and marker (null (marker-buffer marker)))
11292 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11293 (sit-for 3)
11294 (throw 'exit nil)))
11295 t)))
11296
11297 (defun org-refile-cache-put (set &rest identifiers)
11298 "Push the refile targets SET into the cache, under IDENTIFIERS."
11299 (let* ((key (sha1 (prin1-to-string identifiers)))
11300 (entry (assoc key org-refile-cache)))
11301 (if entry
11302 (setcdr entry set)
11303 (push (cons key set) org-refile-cache))))
11304
11305 (defun org-refile-cache-get (&rest identifiers)
11306 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11307 (cond
11308 ((not org-refile-cache) nil)
11309 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11310 (t
11311 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11312 org-refile-cache))))
11313 (and set (org-refile-cache-check-set set) set)))))
11314
11315 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11316 "Produce a table with refile targets."
11317 (let ((case-fold-search nil)
11318 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11319 (entries (or org-refile-targets '((nil . (:level . 1)))))
11320 targets tgs txt re files f desc descre fast-path-p level pos0)
11321 (message "Getting targets...")
11322 (with-current-buffer (or default-buffer (current-buffer))
11323 (while (setq entry (pop entries))
11324 (setq files (car entry) desc (cdr entry))
11325 (setq fast-path-p nil)
11326 (cond
11327 ((null files) (setq files (list (current-buffer))))
11328 ((eq files 'org-agenda-files)
11329 (setq files (org-agenda-files 'unrestricted)))
11330 ((and (symbolp files) (fboundp files))
11331 (setq files (funcall files)))
11332 ((and (symbolp files) (boundp files))
11333 (setq files (symbol-value files))))
11334 (if (stringp files) (setq files (list files)))
11335 (cond
11336 ((eq (car desc) :tag)
11337 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11338 ((eq (car desc) :todo)
11339 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11340 ((eq (car desc) :regexp)
11341 (setq descre (cdr desc)))
11342 ((eq (car desc) :level)
11343 (setq descre (concat "^\\*\\{" (number-to-string
11344 (if org-odd-levels-only
11345 (1- (* 2 (cdr desc)))
11346 (cdr desc)))
11347 "\\}[ \t]")))
11348 ((eq (car desc) :maxlevel)
11349 (setq fast-path-p t)
11350 (setq descre (concat "^\\*\\{1," (number-to-string
11351 (if org-odd-levels-only
11352 (1- (* 2 (cdr desc)))
11353 (cdr desc)))
11354 "\\}[ \t]")))
11355 (t (error "Bad refiling target description %s" desc)))
11356 (while (setq f (pop files))
11357 (with-current-buffer
11358 (if (bufferp f) f (org-get-agenda-file-buffer f))
11359 (or
11360 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11361 (progn
11362 (if (bufferp f) (setq f (buffer-file-name
11363 (buffer-base-buffer f))))
11364 (setq f (and f (expand-file-name f)))
11365 (if (eq org-refile-use-outline-path 'file)
11366 (push (list (file-name-nondirectory f) f nil nil) tgs))
11367 (save-excursion
11368 (save-restriction
11369 (widen)
11370 (goto-char (point-min))
11371 (while (re-search-forward descre nil t)
11372 (goto-char (setq pos0 (point-at-bol)))
11373 (catch 'next
11374 (when org-refile-target-verify-function
11375 (save-match-data
11376 (or (funcall org-refile-target-verify-function)
11377 (throw 'next t))))
11378 (when (and (looking-at org-complex-heading-regexp)
11379 (not (member (match-string 4) excluded-entries))
11380 (match-string 4))
11381 (setq level (org-reduced-level
11382 (- (match-end 1) (match-beginning 1)))
11383 txt (org-link-display-format (match-string 4))
11384 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11385 re (format org-complex-heading-regexp-format
11386 (regexp-quote (match-string 4))))
11387 (when org-refile-use-outline-path
11388 (setq txt (mapconcat
11389 'org-protect-slash
11390 (append
11391 (if (eq org-refile-use-outline-path
11392 'file)
11393 (list (file-name-nondirectory
11394 (buffer-file-name
11395 (buffer-base-buffer))))
11396 (if (eq org-refile-use-outline-path
11397 'full-file-path)
11398 (list (buffer-file-name
11399 (buffer-base-buffer)))))
11400 (org-get-outline-path fast-path-p
11401 level txt)
11402 (list txt))
11403 "/")))
11404 (push (list txt f re (org-refile-marker (point)))
11405 tgs)))
11406 (when (= (point) pos0)
11407 ;; verification function has not moved point
11408 (goto-char (point-at-eol))))))))
11409 (when org-refile-use-cache
11410 (org-refile-cache-put tgs (buffer-file-name) descre))
11411 (setq targets (append tgs targets))))))
11412 (message "Getting targets...done")
11413 (nreverse targets)))
11414
11415 (defun org-protect-slash (s)
11416 (while (string-match "/" s)
11417 (setq s (replace-match "\\" t t s)))
11418 s)
11419
11420 (defvar org-olpa (make-vector 20 nil))
11421
11422 (defun org-get-outline-path (&optional fastp level heading)
11423 "Return the outline path to the current entry, as a list.
11424
11425 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11426 routine which makes outline path derivations for an entire file,
11427 avoiding backtracing. Refile target collection makes use of that."
11428 (if fastp
11429 (progn
11430 (if (> level 19)
11431 (error "Outline path failure, more than 19 levels"))
11432 (loop for i from level upto 19 do
11433 (aset org-olpa i nil))
11434 (prog1
11435 (delq nil (append org-olpa nil))
11436 (aset org-olpa level heading)))
11437 (let (rtn case-fold-search)
11438 (save-excursion
11439 (save-restriction
11440 (widen)
11441 (while (org-up-heading-safe)
11442 (when (looking-at org-complex-heading-regexp)
11443 (push (org-trim
11444 (replace-regexp-in-string
11445 ;; Remove statistical/checkboxes cookies
11446 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11447 (org-match-string-no-properties 4)))
11448 rtn)))
11449 rtn)))))
11450
11451 (defun org-format-outline-path (path &optional width prefix separator)
11452 "Format the outline path PATH for display.
11453 WIDTH is the maximum number of characters that is available.
11454 PREFIX is a prefix to be included in the returned string,
11455 such as the file name.
11456 SEPARATOR is inserted between the different parts of the path,
11457 the default is \"/\"."
11458 (setq width (or width 79))
11459 (if prefix (setq width (- width (length prefix))))
11460 (if (not path)
11461 (or prefix "")
11462 (let* ((nsteps (length path))
11463 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11464 (maxwidth (if (<= total-width width)
11465 10000 ;; everything fits
11466 ;; we need to shorten the level headings
11467 (/ (- width nsteps) nsteps)))
11468 (org-odd-levels-only nil)
11469 (n 0)
11470 (total (1+ (length prefix))))
11471 (setq maxwidth (max maxwidth 10))
11472 (concat prefix
11473 (if prefix (or separator "/"))
11474 (mapconcat
11475 (lambda (h)
11476 (setq n (1+ n))
11477 (if (and (= n nsteps) (< maxwidth 10000))
11478 (setq maxwidth (- total-width total)))
11479 (if (< (length h) maxwidth)
11480 (progn (setq total (+ total (length h) 1)) h)
11481 (setq h (substring h 0 (- maxwidth 2))
11482 total (+ total maxwidth 1))
11483 (if (string-match "[ \t]+\\'" h)
11484 (setq h (substring h 0 (match-beginning 0))))
11485 (setq h (concat h "..")))
11486 (org-add-props h nil 'face
11487 (nth (% (1- n) org-n-level-faces)
11488 org-level-faces))
11489 h)
11490 path (or separator "/"))))))
11491
11492 (defun org-display-outline-path (&optional file current separator just-return-string)
11493 "Display the current outline path in the echo area.
11494
11495 If FILE is non-nil, prepend the output with the file name.
11496 If CURRENT is non-nil, append the current heading to the output.
11497 SEPARATOR is passed through to `org-format-outline-path'. It separates
11498 the different parts of the path and defaults to \"/\".
11499 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11500 (interactive "P")
11501 (let* (case-fold-search
11502 (bfn (buffer-file-name (buffer-base-buffer)))
11503 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11504 res)
11505 (if current (setq path (append path
11506 (save-excursion
11507 (org-back-to-heading t)
11508 (if (looking-at org-complex-heading-regexp)
11509 (list (match-string 4)))))))
11510 (setq res
11511 (org-format-outline-path
11512 path
11513 (1- (frame-width))
11514 (and file bfn (concat (file-name-nondirectory bfn) separator))
11515 separator))
11516 (if just-return-string
11517 (org-no-properties res)
11518 (org-unlogged-message "%s" res))))
11519
11520 (defvar org-refile-history nil
11521 "History for refiling operations.")
11522
11523 (defvar org-after-refile-insert-hook nil
11524 "Hook run after `org-refile' has inserted its stuff at the new location.
11525 Note that this is still *before* the stuff will be removed from
11526 the *old* location.")
11527
11528 (defvar org-capture-last-stored-marker)
11529 (defvar org-refile-keep nil
11530 "Non-nil means `org-refile' will copy instead of refile.")
11531
11532 (defun org-copy ()
11533 "Like `org-refile', but copy."
11534 (interactive)
11535 (let ((org-refile-keep t))
11536 (funcall 'org-refile nil nil nil "Copy")))
11537
11538 (defun org-refile (&optional goto default-buffer rfloc msg)
11539 "Move the entry or entries at point to another heading.
11540 The list of target headings is compiled using the information in
11541 `org-refile-targets', which see.
11542
11543 At the target location, the entry is filed as a subitem of the target
11544 heading. Depending on `org-reverse-note-order', the new subitem will
11545 either be the first or the last subitem.
11546
11547 If there is an active region, all entries in that region will be moved.
11548 However, the region must fulfill the requirement that the first heading
11549 is the first one sets the top-level of the moved text - at most siblings
11550 below it are allowed.
11551
11552 With prefix arg GOTO, the command will only visit the target location
11553 and not actually move anything.
11554
11555 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11556 go to the location where the last refiling operation has put the subtree.
11557
11558 With a numeric prefix argument of `2', refile to the running clock.
11559
11560 With a numeric prefix argument of `3', emulate `org-refile-keep'
11561 being set to `t' and copy to the target location, don't move it.
11562 Beware that keeping refiled entries may result in duplicated ID
11563 properties.
11564
11565 RFLOC can be a refile location obtained in a different way.
11566
11567 MSG is a string to replace \"Refile\" in the default prompt with
11568 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11569
11570 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11571
11572 If you are using target caching (see `org-refile-use-cache'),
11573 you have to clear the target cache in order to find new targets.
11574 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11575 prefix argument (`C-u C-u C-u C-c C-w')."
11576
11577 (interactive "P")
11578 (if (member goto '(0 (64)))
11579 (org-refile-cache-clear)
11580 (let* ((actionmsg (cond (msg msg)
11581 ((equal goto 3) "Refile (and keep)")
11582 (t "Refile")))
11583 (cbuf (current-buffer))
11584 (regionp (org-region-active-p))
11585 (region-start (and regionp (region-beginning)))
11586 (region-end (and regionp (region-end)))
11587 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11588 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11589 pos it nbuf file re level reversed)
11590 (setq last-command nil)
11591 (when regionp
11592 (goto-char region-start)
11593 (or (bolp) (goto-char (point-at-bol)))
11594 (setq region-start (point))
11595 (unless (or (org-kill-is-subtree-p
11596 (buffer-substring region-start region-end))
11597 (prog1 org-refile-active-region-within-subtree
11598 (let ((s (point-at-eol)))
11599 (org-toggle-heading)
11600 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11601 (user-error "The region is not a (sequence of) subtree(s)")))
11602 (if (equal goto '(16))
11603 (org-refile-goto-last-stored)
11604 (when (or
11605 (and (equal goto 2)
11606 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11607 (prog1
11608 (setq it (list (or org-clock-heading "running clock")
11609 (buffer-file-name
11610 (marker-buffer org-clock-hd-marker))
11611 ""
11612 (marker-position org-clock-hd-marker)))
11613 (setq goto nil)))
11614 (setq it (or rfloc
11615 (let (heading-text)
11616 (save-excursion
11617 (unless (and goto (listp goto))
11618 (org-back-to-heading t)
11619 (setq heading-text
11620 (nth 4 (org-heading-components))))
11621
11622 (org-refile-get-location
11623 (cond ((and goto (listp goto)) "Goto")
11624 (regionp (concat actionmsg " region to"))
11625 (t (concat actionmsg " subtree \""
11626 heading-text "\" to")))
11627 default-buffer
11628 (and (not (equal '(4) goto))
11629 org-refile-allow-creating-parent-nodes)
11630 goto))))))
11631 (setq file (nth 1 it)
11632 re (nth 2 it)
11633 pos (nth 3 it))
11634 (if (and (not goto)
11635 pos
11636 (equal (buffer-file-name) file)
11637 (if regionp
11638 (and (>= pos region-start)
11639 (<= pos region-end))
11640 (and (>= pos (point))
11641 (< pos (save-excursion
11642 (org-end-of-subtree t t))))))
11643 (error "Cannot refile to position inside the tree or region"))
11644
11645 (setq nbuf (or (find-buffer-visiting file)
11646 (find-file-noselect file)))
11647 (if (and goto (not (equal goto 3)))
11648 (progn
11649 (org-pop-to-buffer-same-window nbuf)
11650 (goto-char pos)
11651 (org-show-context 'org-goto))
11652 (if regionp
11653 (progn
11654 (org-kill-new (buffer-substring region-start region-end))
11655 (org-save-markers-in-region region-start region-end))
11656 (org-copy-subtree 1 nil t))
11657 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11658 (find-file-noselect file)))
11659 (setq reversed (org-notes-order-reversed-p))
11660 (save-excursion
11661 (save-restriction
11662 (widen)
11663 (if pos
11664 (progn
11665 (goto-char pos)
11666 (looking-at org-outline-regexp)
11667 (setq level (org-get-valid-level (funcall outline-level) 1))
11668 (goto-char
11669 (if reversed
11670 (or (outline-next-heading) (point-max))
11671 (or (save-excursion (org-get-next-sibling))
11672 (org-end-of-subtree t t)
11673 (point-max)))))
11674 (setq level 1)
11675 (if (not reversed)
11676 (goto-char (point-max))
11677 (goto-char (point-min))
11678 (or (outline-next-heading) (goto-char (point-max)))))
11679 (if (not (bolp)) (newline))
11680 (org-paste-subtree level)
11681 (when org-log-refile
11682 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11683 (unless (eq org-log-refile 'note)
11684 (save-excursion (org-add-log-note))))
11685 (and org-auto-align-tags
11686 (let ((org-loop-over-headlines-in-active-region nil))
11687 (org-set-tags nil t)))
11688 (let ((bookmark-name (plist-get org-bookmark-names-plist
11689 :last-refile)))
11690 (when bookmark-name
11691 (with-demoted-errors
11692 (bookmark-set bookmark-name))))
11693 ;; If we are refiling for capture, make sure that the
11694 ;; last-capture pointers point here
11695 (when (org-bound-and-true-p org-refile-for-capture)
11696 (let ((bookmark-name (plist-get org-bookmark-names-plist
11697 :last-capture-marker)))
11698 (when bookmark-name
11699 (with-demoted-errors
11700 (bookmark-set bookmark-name))))
11701 (move-marker org-capture-last-stored-marker (point)))
11702 (if (fboundp 'deactivate-mark) (deactivate-mark))
11703 (run-hooks 'org-after-refile-insert-hook))))
11704 (unless org-refile-keep
11705 (if regionp
11706 (delete-region (point) (+ (point) (- region-end region-start)))
11707 (delete-region
11708 (and (org-back-to-heading t) (point))
11709 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11710 (when (featurep 'org-inlinetask)
11711 (org-inlinetask-remove-END-maybe))
11712 (setq org-markers-to-move nil)
11713 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11714
11715 (defun org-refile-goto-last-stored ()
11716 "Go to the location where the last refile was stored."
11717 (interactive)
11718 (bookmark-jump "org-refile-last-stored")
11719 (message "This is the location of the last refile"))
11720
11721 (defun org-refile--get-location (refloc tbl)
11722 "When user refile to REFLOC, find the associated target in TBL.
11723 Also check `org-refile-target-table'."
11724 (car (delq
11725 nil
11726 (mapcar
11727 (lambda (r) (or (assoc r tbl)
11728 (assoc r org-refile-target-table)))
11729 (list (replace-regexp-in-string "/$" "" refloc)
11730 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11731
11732 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11733 no-exclude)
11734 "Prompt the user for a refile location, using PROMPT.
11735 PROMPT should not be suffixed with a colon and a space, because
11736 this function appends the default value from
11737 `org-refile-history' automatically, if that is not empty.
11738 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11739 this is used for the GOTO interface."
11740 (let ((org-refile-targets org-refile-targets)
11741 (org-refile-use-outline-path org-refile-use-outline-path)
11742 excluded-entries)
11743 (when (and (derived-mode-p 'org-mode)
11744 (not org-refile-use-cache)
11745 (not no-exclude))
11746 (org-map-tree
11747 (lambda()
11748 (setq excluded-entries
11749 (append excluded-entries (list (org-get-heading t t)))))))
11750 (setq org-refile-target-table
11751 (org-refile-get-targets default-buffer excluded-entries)))
11752 (unless org-refile-target-table
11753 (user-error "No refile targets"))
11754 (let* ((cbuf (current-buffer))
11755 (partial-completion-mode nil)
11756 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11757 (cfunc (if (and org-refile-use-outline-path
11758 org-outline-path-complete-in-steps)
11759 'org-olpath-completing-read
11760 'org-icompleting-read))
11761 (extra (if org-refile-use-outline-path "/" ""))
11762 (cbnex (concat (buffer-name) extra))
11763 (filename (and cfn (expand-file-name cfn)))
11764 (tbl (mapcar
11765 (lambda (x)
11766 (if (and (not (member org-refile-use-outline-path
11767 '(file full-file-path)))
11768 (not (equal filename (nth 1 x))))
11769 (cons (concat (car x) extra " ("
11770 (file-name-nondirectory (nth 1 x)) ")")
11771 (cdr x))
11772 (cons (concat (car x) extra) (cdr x))))
11773 org-refile-target-table))
11774 (completion-ignore-case t)
11775 cdef
11776 (prompt (concat prompt
11777 (or (and (car org-refile-history)
11778 (concat " (default " (car org-refile-history) ")"))
11779 (and (assoc cbnex tbl) (setq cdef cbnex)
11780 (concat " (default " cbnex ")"))) ": "))
11781 pa answ parent-target child parent old-hist)
11782 (setq old-hist org-refile-history)
11783 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11784 nil 'org-refile-history (or cdef (car org-refile-history))))
11785 (if (setq pa (org-refile--get-location answ tbl))
11786 (progn
11787 (org-refile-check-position pa)
11788 (when (or (not org-refile-history)
11789 (not (eq old-hist org-refile-history))
11790 (not (equal (car pa) (car org-refile-history))))
11791 (setq org-refile-history
11792 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11793 org-refile-history
11794 (cdr org-refile-history))))
11795 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11796 (pop org-refile-history)))
11797 pa)
11798 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11799 (progn
11800 (setq parent (match-string 1 answ)
11801 child (match-string 2 answ))
11802 (setq parent-target (org-refile--get-location parent tbl))
11803 (when (and parent-target
11804 (or (eq new-nodes t)
11805 (and (eq new-nodes 'confirm)
11806 (y-or-n-p (format "Create new node \"%s\"? "
11807 child)))))
11808 (org-refile-new-child parent-target child)))
11809 (user-error "Invalid target location")))))
11810
11811 (declare-function org-string-nw-p "org-macs" (s))
11812 (defun org-refile-check-position (refile-pointer)
11813 "Check if the refile pointer matches the headline to which it points."
11814 (let* ((file (nth 1 refile-pointer))
11815 (re (nth 2 refile-pointer))
11816 (pos (nth 3 refile-pointer))
11817 buffer)
11818 (if (and (not (markerp pos)) (not file))
11819 (user-error "Please save the buffer to a file before refiling")
11820 (when (org-string-nw-p re)
11821 (setq buffer (if (markerp pos)
11822 (marker-buffer pos)
11823 (or (find-buffer-visiting file)
11824 (find-file-noselect file))))
11825 (with-current-buffer buffer
11826 (save-excursion
11827 (save-restriction
11828 (widen)
11829 (goto-char pos)
11830 (beginning-of-line 1)
11831 (unless (org-looking-at-p re)
11832 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11833
11834 (defun org-refile-new-child (parent-target child)
11835 "Use refile target PARENT-TARGET to add new CHILD below it."
11836 (unless parent-target
11837 (error "Cannot find parent for new node"))
11838 (let ((file (nth 1 parent-target))
11839 (pos (nth 3 parent-target))
11840 level)
11841 (with-current-buffer (or (find-buffer-visiting file)
11842 (find-file-noselect file))
11843 (save-excursion
11844 (save-restriction
11845 (widen)
11846 (if pos
11847 (goto-char pos)
11848 (goto-char (point-max))
11849 (if (not (bolp)) (newline)))
11850 (when (looking-at org-outline-regexp)
11851 (setq level (funcall outline-level))
11852 (org-end-of-subtree t t))
11853 (org-back-over-empty-lines)
11854 (insert "\n" (make-string
11855 (if pos (org-get-valid-level level 1) 1) ?*)
11856 " " child "\n")
11857 (beginning-of-line 0)
11858 (list (concat (car parent-target) "/" child) file "" (point)))))))
11859
11860 (defun org-olpath-completing-read (prompt collection &rest args)
11861 "Read an outline path like a file name."
11862 (let ((thetable collection)
11863 (org-completion-use-ido nil) ; does not work with ido.
11864 (org-completion-use-iswitchb nil)) ; or iswitchb
11865 (apply
11866 'org-icompleting-read prompt
11867 (lambda (string predicate &optional flag)
11868 (let (rtn r f (l (length string)))
11869 (cond
11870 ((eq flag nil)
11871 ;; try completion
11872 (try-completion string thetable))
11873 ((eq flag t)
11874 ;; all-completions
11875 (setq rtn (all-completions string thetable predicate))
11876 (mapcar
11877 (lambda (x)
11878 (setq r (substring x l))
11879 (if (string-match " ([^)]*)$" x)
11880 (setq f (match-string 0 x))
11881 (setq f ""))
11882 (if (string-match "/" r)
11883 (concat string (substring r 0 (match-end 0)) f)
11884 x))
11885 rtn))
11886 ((eq flag 'lambda)
11887 ;; exact match?
11888 (assoc string thetable)))))
11889 args)))
11890
11891 ;;;; Dynamic blocks
11892
11893 (defun org-find-dblock (name)
11894 "Find the first dynamic block with name NAME in the buffer.
11895 If not found, stay at current position and return nil."
11896 (let ((case-fold-search t) pos)
11897 (save-excursion
11898 (goto-char (point-min))
11899 (setq pos (and (re-search-forward
11900 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11901 (match-beginning 0))))
11902 (if pos (goto-char pos))
11903 pos))
11904
11905 (defconst org-dblock-start-re
11906 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11907 "Matches the start line of a dynamic block, with parameters.")
11908
11909 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11910 "Matches the end of a dynamic block.")
11911
11912 (defun org-create-dblock (plist)
11913 "Create a dynamic block section, with parameters taken from PLIST.
11914 PLIST must contain a :name entry which is used as name of the block."
11915 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11916 (end-of-line 1)
11917 (newline))
11918 (let ((col (current-column))
11919 (name (plist-get plist :name)))
11920 (insert "#+BEGIN: " name)
11921 (while plist
11922 (if (eq (car plist) :name)
11923 (setq plist (cddr plist))
11924 (insert " " (prin1-to-string (pop plist)))))
11925 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11926 (beginning-of-line -2)))
11927
11928 (defun org-prepare-dblock ()
11929 "Prepare dynamic block for refresh.
11930 This empties the block, puts the cursor at the insert position and returns
11931 the property list including an extra property :name with the block name."
11932 (unless (looking-at org-dblock-start-re)
11933 (user-error "Not at a dynamic block"))
11934 (let* ((begdel (1+ (match-end 0)))
11935 (name (org-no-properties (match-string 1)))
11936 (params (append (list :name name)
11937 (read (concat "(" (match-string 3) ")")))))
11938 (save-excursion
11939 (beginning-of-line 1)
11940 (skip-chars-forward " \t")
11941 (setq params (plist-put params :indentation-column (current-column))))
11942 (unless (re-search-forward org-dblock-end-re nil t)
11943 (error "Dynamic block not terminated"))
11944 (setq params
11945 (append params
11946 (list :content (buffer-substring
11947 begdel (match-beginning 0)))))
11948 (delete-region begdel (match-beginning 0))
11949 (goto-char begdel)
11950 (open-line 1)
11951 params))
11952
11953 (defun org-map-dblocks (&optional command)
11954 "Apply COMMAND to all dynamic blocks in the current buffer.
11955 If COMMAND is not given, use `org-update-dblock'."
11956 (let ((cmd (or command 'org-update-dblock)))
11957 (save-excursion
11958 (goto-char (point-min))
11959 (while (re-search-forward org-dblock-start-re nil t)
11960 (goto-char (match-beginning 0))
11961 (save-excursion
11962 (condition-case nil
11963 (funcall cmd)
11964 (error (message "Error during update of dynamic block"))))
11965 (unless (re-search-forward org-dblock-end-re nil t)
11966 (error "Dynamic block not terminated"))))))
11967
11968 (defun org-dblock-update (&optional arg)
11969 "User command for updating dynamic blocks.
11970 Update the dynamic block at point. With prefix ARG, update all dynamic
11971 blocks in the buffer."
11972 (interactive "P")
11973 (if arg
11974 (org-update-all-dblocks)
11975 (or (looking-at org-dblock-start-re)
11976 (org-beginning-of-dblock))
11977 (org-update-dblock)))
11978
11979 (defun org-update-dblock ()
11980 "Update the dynamic block at point.
11981 This means to empty the block, parse for parameters and then call
11982 the correct writing function."
11983 (interactive)
11984 (save-excursion
11985 (let* ((win (selected-window))
11986 (pos (point))
11987 (line (org-current-line))
11988 (params (org-prepare-dblock))
11989 (name (plist-get params :name))
11990 (indent (plist-get params :indentation-column))
11991 (cmd (intern (concat "org-dblock-write:" name))))
11992 (message "Updating dynamic block `%s' at line %d..." name line)
11993 (funcall cmd params)
11994 (message "Updating dynamic block `%s' at line %d...done" name line)
11995 (goto-char pos)
11996 (when (and indent (> indent 0))
11997 (setq indent (make-string indent ?\ ))
11998 (save-excursion
11999 (select-window win)
12000 (org-beginning-of-dblock)
12001 (forward-line 1)
12002 (while (not (looking-at org-dblock-end-re))
12003 (insert indent)
12004 (beginning-of-line 2))
12005 (when (looking-at org-dblock-end-re)
12006 (and (looking-at "[ \t]+")
12007 (replace-match ""))
12008 (insert indent)))))))
12009
12010 (defun org-beginning-of-dblock ()
12011 "Find the beginning of the dynamic block at point.
12012 Error if there is no such block at point."
12013 (let ((pos (point))
12014 beg)
12015 (end-of-line 1)
12016 (if (and (re-search-backward org-dblock-start-re nil t)
12017 (setq beg (match-beginning 0))
12018 (re-search-forward org-dblock-end-re nil t)
12019 (> (match-end 0) pos))
12020 (goto-char beg)
12021 (goto-char pos)
12022 (error "Not in a dynamic block"))))
12023
12024 (defun org-update-all-dblocks ()
12025 "Update all dynamic blocks in the buffer.
12026 This function can be used in a hook."
12027 (interactive)
12028 (when (derived-mode-p 'org-mode)
12029 (org-map-dblocks 'org-update-dblock)))
12030
12031
12032 ;;;; Completion
12033
12034 (declare-function org-export-backend-name "org-export" (cl-x))
12035 (declare-function org-export-backend-options "org-export" (cl-x))
12036 (defun org-get-export-keywords ()
12037 "Return a list of all currently understood export keywords.
12038 Export keywords include options, block names, attributes and
12039 keywords relative to each registered export back-end."
12040 (let (keywords)
12041 (dolist (backend
12042 (org-bound-and-true-p org-export--registered-backends)
12043 (delq nil keywords))
12044 ;; Back-end name (for keywords, like #+LATEX:)
12045 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12046 (dolist (option-entry (org-export-backend-options backend))
12047 ;; Back-end options.
12048 (push (nth 1 option-entry) keywords)))))
12049
12050 (defconst org-options-keywords
12051 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12052 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12053 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12054 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12055 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12056
12057 (defcustom org-structure-template-alist
12058 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12059 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12060 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12061 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12062 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12063 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12064 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12065 "<literal style=\"latex\">\n?\n</literal>")
12066 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12067 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12068 "<literal style=\"html\">\n?\n</literal>")
12069 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12070 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12071 ("A" "#+ASCII: " "")
12072 ("i" "#+INDEX: ?" "#+INDEX: ?")
12073 ("I" "#+INCLUDE: %file ?"
12074 "<include file=%file markup=\"?\">"))
12075 "Structure completion elements.
12076 This is a list of abbreviation keys and values. The value gets inserted
12077 if you type `<' followed by the key and then press the completion key,
12078 usually `M-TAB'. %file will be replaced by a file name after prompting
12079 for the file using completion. The cursor will be placed at the position
12080 of the `?` in the template.
12081 There are two templates for each key, the first uses the original Org syntax,
12082 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12083 the default when the /org-mtags.el/ module has been loaded. See also the
12084 variable `org-mtags-prefer-muse-templates'."
12085 :group 'org-completion
12086 :type '(repeat
12087 (list
12088 (string :tag "Key")
12089 (string :tag "Template")
12090 (string :tag "Muse Template"))))
12091
12092 (defun org-try-structure-completion ()
12093 "Try to complete a structure template before point.
12094 This looks for strings like \"<e\" on an otherwise empty line and
12095 expands them."
12096 (let ((l (buffer-substring (point-at-bol) (point)))
12097 a)
12098 (when (and (looking-at "[ \t]*$")
12099 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12100 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12101 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12102 (match-beginning 1)) a)
12103 t)))
12104
12105 (defun org-complete-expand-structure-template (start cell)
12106 "Expand a structure template."
12107 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12108 (rpl (nth (if musep 2 1) cell))
12109 (ind ""))
12110 (delete-region start (point))
12111 (when (string-match "\\`#\\+" rpl)
12112 (cond
12113 ((bolp))
12114 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12115 (setq ind (buffer-substring (point-at-bol) (point))))
12116 (t (newline))))
12117 (setq start (point))
12118 (if (string-match "%file" rpl)
12119 (setq rpl (replace-match
12120 (concat
12121 "\""
12122 (save-match-data
12123 (abbreviate-file-name (read-file-name "Include file: ")))
12124 "\"")
12125 t t rpl)))
12126 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12127 (concat "\n" ind)))
12128 (insert rpl)
12129 (if (re-search-backward "\\?" start t) (delete-char 1))))
12130
12131 ;;;; TODO, DEADLINE, Comments
12132
12133 (defun org-toggle-comment ()
12134 "Change the COMMENT state of an entry."
12135 (interactive)
12136 (save-excursion
12137 (org-back-to-heading)
12138 (let (case-fold-search)
12139 (cond
12140 ((looking-at (format org-heading-keyword-regexp-format
12141 org-comment-string))
12142 (goto-char (match-end 1))
12143 (looking-at (concat " +" org-comment-string))
12144 (replace-match "" t t)
12145 (when (eolp) (insert " ")))
12146 ((looking-at org-outline-regexp)
12147 (goto-char (match-end 0))
12148 (insert org-comment-string " "))))))
12149
12150 (defvar org-last-todo-state-is-todo nil
12151 "This is non-nil when the last TODO state change led to a TODO state.
12152 If the last change removed the TODO tag or switched to DONE, then
12153 this is nil.")
12154
12155 (defvar org-setting-tags nil) ; dynamically skipped
12156
12157 (defvar org-todo-setup-filter-hook nil
12158 "Hook for functions that pre-filter todo specs.
12159 Each function takes a todo spec and returns either nil or the spec
12160 transformed into canonical form." )
12161
12162 (defvar org-todo-get-default-hook nil
12163 "Hook for functions that get a default item for todo.
12164 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12165 nil or a string to be used for the todo mark." )
12166
12167 (defvar org-agenda-headline-snapshot-before-repeat)
12168
12169 (defun org-current-effective-time ()
12170 "Return current time adjusted for `org-extend-today-until' variable."
12171 (let* ((ct (org-current-time))
12172 (dct (decode-time ct))
12173 (ct1
12174 (cond
12175 (org-use-last-clock-out-time-as-effective-time
12176 (or (org-clock-get-last-clock-out-time) ct))
12177 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12178 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12179 (t ct))))
12180 ct1))
12181
12182 (defun org-todo-yesterday (&optional arg)
12183 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12184 (interactive "P")
12185 (if (eq major-mode 'org-agenda-mode)
12186 (apply 'org-agenda-todo-yesterday arg)
12187 (let* ((hour (third (decode-time
12188 (org-current-time))))
12189 (org-extend-today-until (1+ hour)))
12190 (org-todo arg))))
12191
12192 (defvar org-block-entry-blocking ""
12193 "First entry preventing the TODO state change.")
12194
12195 (defun org-todo (&optional arg)
12196 "Change the TODO state of an item.
12197 The state of an item is given by a keyword at the start of the heading,
12198 like
12199 *** TODO Write paper
12200 *** DONE Call mom
12201
12202 The different keywords are specified in the variable `org-todo-keywords'.
12203 By default the available states are \"TODO\" and \"DONE\".
12204 So for this example: when the item starts with TODO, it is changed to DONE.
12205 When it starts with DONE, the DONE is removed. And when neither TODO nor
12206 DONE are present, add TODO at the beginning of the heading.
12207
12208 With \\[universal-argument] prefix arg, use completion to determine the new \
12209 state.
12210 With numeric prefix arg, switch to that state.
12211 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12212 keywords (nextset).
12213 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12214 With a numeric prefix arg of 0, inhibit note taking for the change.
12215
12216 For calling through lisp, arg is also interpreted in the following way:
12217 'none -> empty state
12218 \"\"(empty string) -> switch to empty state
12219 'done -> switch to DONE
12220 'nextset -> switch to the next set of keywords
12221 'previousset -> switch to the previous set of keywords
12222 \"WAITING\" -> switch to the specified keyword, but only if it
12223 really is a member of `org-todo-keywords'."
12224 (interactive "P")
12225 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12226 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12227 'region-start-level 'region))
12228 org-loop-over-headlines-in-active-region)
12229 (org-map-entries
12230 `(org-todo ,arg)
12231 org-loop-over-headlines-in-active-region
12232 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12233 (if (equal arg '(16)) (setq arg 'nextset))
12234 (let ((org-blocker-hook org-blocker-hook)
12235 commentp
12236 case-fold-search)
12237 (when (equal arg '(64))
12238 (setq arg nil org-blocker-hook nil))
12239 (when (and org-blocker-hook
12240 (or org-inhibit-blocking
12241 (org-entry-get nil "NOBLOCKING")))
12242 (setq org-blocker-hook nil))
12243 (save-excursion
12244 (catch 'exit
12245 (org-back-to-heading t)
12246 (when (looking-at (concat "^\\*+ " org-comment-string))
12247 (org-toggle-comment)
12248 (setq commentp t))
12249 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12250 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12251 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12252 (let* ((match-data (match-data))
12253 (startpos (point-at-bol))
12254 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12255 (org-log-done org-log-done)
12256 (org-log-repeat org-log-repeat)
12257 (org-todo-log-states org-todo-log-states)
12258 (org-inhibit-logging
12259 (if (equal arg 0)
12260 (progn (setq arg nil) 'note) org-inhibit-logging))
12261 (this (match-string 1))
12262 (hl-pos (match-beginning 0))
12263 (head (org-get-todo-sequence-head this))
12264 (ass (assoc head org-todo-kwd-alist))
12265 (interpret (nth 1 ass))
12266 (done-word (nth 3 ass))
12267 (final-done-word (nth 4 ass))
12268 (org-last-state (or this ""))
12269 (completion-ignore-case t)
12270 (member (member this org-todo-keywords-1))
12271 (tail (cdr member))
12272 (org-state (cond
12273 ((and org-todo-key-trigger
12274 (or (and (equal arg '(4))
12275 (eq org-use-fast-todo-selection 'prefix))
12276 (and (not arg) org-use-fast-todo-selection
12277 (not (eq org-use-fast-todo-selection
12278 'prefix)))))
12279 ;; Use fast selection
12280 (org-fast-todo-selection))
12281 ((and (equal arg '(4))
12282 (or (not org-use-fast-todo-selection)
12283 (not org-todo-key-trigger)))
12284 ;; Read a state with completion
12285 (org-icompleting-read
12286 "State: " (mapcar 'list org-todo-keywords-1)
12287 nil t))
12288 ((eq arg 'right)
12289 (if this
12290 (if tail (car tail) nil)
12291 (car org-todo-keywords-1)))
12292 ((eq arg 'left)
12293 (if (equal member org-todo-keywords-1)
12294 nil
12295 (if this
12296 (nth (- (length org-todo-keywords-1)
12297 (length tail) 2)
12298 org-todo-keywords-1)
12299 (org-last org-todo-keywords-1))))
12300 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12301 (setq arg nil))) ; hack to fall back to cycling
12302 (arg
12303 ;; user or caller requests a specific state
12304 (cond
12305 ((equal arg "") nil)
12306 ((eq arg 'none) nil)
12307 ((eq arg 'done) (or done-word (car org-done-keywords)))
12308 ((eq arg 'nextset)
12309 (or (car (cdr (member head org-todo-heads)))
12310 (car org-todo-heads)))
12311 ((eq arg 'previousset)
12312 (let ((org-todo-heads (reverse org-todo-heads)))
12313 (or (car (cdr (member head org-todo-heads)))
12314 (car org-todo-heads))))
12315 ((car (member arg org-todo-keywords-1)))
12316 ((stringp arg)
12317 (user-error "State `%s' not valid in this file" arg))
12318 ((nth (1- (prefix-numeric-value arg))
12319 org-todo-keywords-1))))
12320 ((null member) (or head (car org-todo-keywords-1)))
12321 ((equal this final-done-word) nil) ;; -> make empty
12322 ((null tail) nil) ;; -> first entry
12323 ((memq interpret '(type priority))
12324 (if (eq this-command last-command)
12325 (car tail)
12326 (if (> (length tail) 0)
12327 (or done-word (car org-done-keywords))
12328 nil)))
12329 (t
12330 (car tail))))
12331 (org-state (or
12332 (run-hook-with-args-until-success
12333 'org-todo-get-default-hook org-state org-last-state)
12334 org-state))
12335 (next (if org-state (concat " " org-state " ") " "))
12336 (change-plist (list :type 'todo-state-change :from this :to org-state
12337 :position startpos))
12338 dolog now-done-p)
12339 (when org-blocker-hook
12340 (setq org-last-todo-state-is-todo
12341 (not (member this org-done-keywords)))
12342 (unless (save-excursion
12343 (save-match-data
12344 (org-with-wide-buffer
12345 (run-hook-with-args-until-failure
12346 'org-blocker-hook change-plist))))
12347 (if (org-called-interactively-p 'interactive)
12348 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12349 this org-state org-block-entry-blocking)
12350 ;; fail silently
12351 (message "TODO state change from %s to %s blocked (by \"%s\")"
12352 this org-state org-block-entry-blocking)
12353 (throw 'exit nil))))
12354 (store-match-data match-data)
12355 (replace-match next t t)
12356 (unless (pos-visible-in-window-p hl-pos)
12357 (message "TODO state changed to %s" (org-trim next)))
12358 (unless head
12359 (setq head (org-get-todo-sequence-head org-state)
12360 ass (assoc head org-todo-kwd-alist)
12361 interpret (nth 1 ass)
12362 done-word (nth 3 ass)
12363 final-done-word (nth 4 ass)))
12364 (when (memq arg '(nextset previousset))
12365 (message "Keyword-Set %d/%d: %s"
12366 (- (length org-todo-sets) -1
12367 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12368 (length org-todo-sets)
12369 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12370 (setq org-last-todo-state-is-todo
12371 (not (member org-state org-done-keywords)))
12372 (setq now-done-p (and (member org-state org-done-keywords)
12373 (not (member this org-done-keywords))))
12374 (and logging (org-local-logging logging))
12375 (when (and (or org-todo-log-states org-log-done)
12376 (not (eq org-inhibit-logging t))
12377 (not (memq arg '(nextset previousset))))
12378 ;; we need to look at recording a time and note
12379 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12380 (nth 2 (assoc this org-todo-log-states))))
12381 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12382 (setq dolog 'time))
12383 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12384 (and org-state
12385 (member org-state org-not-done-keywords)
12386 (not (member this org-not-done-keywords))))
12387 ;; This is now a todo state and was not one before
12388 ;; If there was a CLOSED time stamp, get rid of it.
12389 (org-add-planning-info nil nil 'closed))
12390 (when (and now-done-p org-log-done)
12391 ;; It is now done, and it was not done before
12392 (org-add-planning-info 'closed (org-current-effective-time))
12393 (if (and (not dolog) (eq 'note org-log-done))
12394 (org-add-log-setup 'done org-state this 'findpos 'note)))
12395 (when (and org-state dolog)
12396 ;; This is a non-nil state, and we need to log it
12397 (org-add-log-setup 'state org-state this 'findpos dolog)))
12398 ;; Fixup tag positioning
12399 (org-todo-trigger-tag-changes org-state)
12400 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12401 (when org-provide-todo-statistics
12402 (org-update-parent-todo-statistics))
12403 (run-hooks 'org-after-todo-state-change-hook)
12404 (if (and arg (not (member org-state org-done-keywords)))
12405 (setq head (org-get-todo-sequence-head org-state)))
12406 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12407 ;; Do we need to trigger a repeat?
12408 (when now-done-p
12409 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12410 ;; This is for the agenda, take a snapshot of the headline.
12411 (save-match-data
12412 (setq org-agenda-headline-snapshot-before-repeat
12413 (org-get-heading))))
12414 (org-auto-repeat-maybe org-state))
12415 ;; Fixup cursor location if close to the keyword
12416 (if (and (outline-on-heading-p)
12417 (not (bolp))
12418 (save-excursion (beginning-of-line 1)
12419 (looking-at org-todo-line-regexp))
12420 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12421 (progn
12422 (goto-char (or (match-end 2) (match-end 1)))
12423 (and (looking-at " ") (just-one-space))))
12424 (when org-trigger-hook
12425 (save-excursion
12426 (run-hook-with-args 'org-trigger-hook change-plist)))
12427 (when commentp (org-toggle-comment))))))))
12428
12429 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12430 "Block turning an entry into a TODO, using the hierarchy.
12431 This checks whether the current task should be blocked from state
12432 changes. Such blocking occurs when:
12433
12434 1. The task has children which are not all in a completed state.
12435
12436 2. A task has a parent with the property :ORDERED:, and there
12437 are siblings prior to the current task with incomplete
12438 status.
12439
12440 3. The parent of the task is blocked because it has siblings that should
12441 be done first, or is child of a block grandparent TODO entry."
12442
12443 (if (not org-enforce-todo-dependencies)
12444 t ; if locally turned off don't block
12445 (catch 'dont-block
12446 ;; If this is not a todo state change, or if this entry is already DONE,
12447 ;; do not block
12448 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12449 (member (plist-get change-plist :from)
12450 (cons 'done org-done-keywords))
12451 (member (plist-get change-plist :to)
12452 (cons 'todo org-not-done-keywords))
12453 (not (plist-get change-plist :to)))
12454 (throw 'dont-block t))
12455 ;; If this task has children, and any are undone, it's blocked
12456 (save-excursion
12457 (org-back-to-heading t)
12458 (let ((this-level (funcall outline-level)))
12459 (outline-next-heading)
12460 (let ((child-level (funcall outline-level)))
12461 (while (and (not (eobp))
12462 (> child-level this-level))
12463 ;; this todo has children, check whether they are all
12464 ;; completed
12465 (if (and (not (org-entry-is-done-p))
12466 (org-entry-is-todo-p))
12467 (progn (setq org-block-entry-blocking (org-get-heading))
12468 (throw 'dont-block nil)))
12469 (outline-next-heading)
12470 (setq child-level (funcall outline-level))))))
12471 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12472 ;; any previous siblings are undone, it's blocked
12473 (save-excursion
12474 (org-back-to-heading t)
12475 (let* ((pos (point))
12476 (parent-pos (and (org-up-heading-safe) (point))))
12477 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12478 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12479 (forward-line 1)
12480 (re-search-forward org-not-done-heading-regexp pos t))
12481 (setq org-block-entry-blocking (match-string 0))
12482 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12483 ;; Search further up the hierarchy, to see if an ancestor is blocked
12484 (while t
12485 (goto-char parent-pos)
12486 (if (not (looking-at org-not-done-heading-regexp))
12487 (throw 'dont-block t)) ; do not block, parent is not a TODO
12488 (setq pos (point))
12489 (setq parent-pos (and (org-up-heading-safe) (point)))
12490 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12491 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12492 (forward-line 1)
12493 (re-search-forward org-not-done-heading-regexp pos t)
12494 (setq org-block-entry-blocking (org-get-heading)))
12495 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12496
12497 (defcustom org-track-ordered-property-with-tag nil
12498 "Should the ORDERED property also be shown as a tag?
12499 The ORDERED property decides if an entry should require subtasks to be
12500 completed in sequence. Since a property is not very visible, setting
12501 this option means that toggling the ORDERED property with the command
12502 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12503 not relevant for the behavior, but it makes things more visible.
12504
12505 Note that toggling the tag with tags commands will not change the property
12506 and therefore not influence behavior!
12507
12508 This can be t, meaning the tag ORDERED should be used, It can also be a
12509 string to select a different tag for this task."
12510 :group 'org-todo
12511 :type '(choice
12512 (const :tag "No tracking" nil)
12513 (const :tag "Track with ORDERED tag" t)
12514 (string :tag "Use other tag")))
12515
12516 (defun org-toggle-ordered-property ()
12517 "Toggle the ORDERED property of the current entry.
12518 For better visibility, you can track the value of this property with a tag.
12519 See variable `org-track-ordered-property-with-tag'."
12520 (interactive)
12521 (let* ((t1 org-track-ordered-property-with-tag)
12522 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12523 (save-excursion
12524 (org-back-to-heading)
12525 (if (org-entry-get nil "ORDERED")
12526 (progn
12527 (org-delete-property "ORDERED" "PROPERTIES")
12528 (and tag (org-toggle-tag tag 'off))
12529 (message "Subtasks can be completed in arbitrary order"))
12530 (org-entry-put nil "ORDERED" "t")
12531 (and tag (org-toggle-tag tag 'on))
12532 (message "Subtasks must be completed in sequence")))))
12533
12534 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12535 (defun org-block-todo-from-checkboxes (change-plist)
12536 "Block turning an entry into a TODO, using checkboxes.
12537 This checks whether the current task should be blocked from state
12538 changes because there are unchecked boxes in this entry."
12539 (if (not org-enforce-todo-checkbox-dependencies)
12540 t ; if locally turned off don't block
12541 (catch 'dont-block
12542 ;; If this is not a todo state change, or if this entry is already DONE,
12543 ;; do not block
12544 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12545 (member (plist-get change-plist :from)
12546 (cons 'done org-done-keywords))
12547 (member (plist-get change-plist :to)
12548 (cons 'todo org-not-done-keywords))
12549 (not (plist-get change-plist :to)))
12550 (throw 'dont-block t))
12551 ;; If this task has checkboxes that are not checked, it's blocked
12552 (save-excursion
12553 (org-back-to-heading t)
12554 (let ((beg (point)) end)
12555 (outline-next-heading)
12556 (setq end (point))
12557 (goto-char beg)
12558 (if (org-list-search-forward
12559 (concat (org-item-beginning-re)
12560 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12561 "\\[[- ]\\]")
12562 end t)
12563 (progn
12564 (if (boundp 'org-blocked-by-checkboxes)
12565 (setq org-blocked-by-checkboxes t))
12566 (throw 'dont-block nil)))))
12567 t))) ; do not block
12568
12569 (defun org-entry-blocked-p ()
12570 "Is the current entry blocked?"
12571 (org-with-silent-modifications
12572 (if (org-entry-get nil "NOBLOCKING")
12573 nil ;; Never block this entry
12574 (not (run-hook-with-args-until-failure
12575 'org-blocker-hook
12576 (list :type 'todo-state-change
12577 :position (point)
12578 :from 'todo
12579 :to 'done))))))
12580
12581 (defun org-update-statistics-cookies (all)
12582 "Update the statistics cookie, either from TODO or from checkboxes.
12583 This should be called with the cursor in a line with a statistics cookie."
12584 (interactive "P")
12585 (if all
12586 (progn
12587 (org-update-checkbox-count 'all)
12588 (org-map-entries 'org-update-parent-todo-statistics))
12589 (if (not (org-at-heading-p))
12590 (org-update-checkbox-count)
12591 (let ((pos (point-marker))
12592 end l1 l2)
12593 (ignore-errors (org-back-to-heading t))
12594 (if (not (org-at-heading-p))
12595 (org-update-checkbox-count)
12596 (setq l1 (org-outline-level))
12597 (setq end (save-excursion
12598 (outline-next-heading)
12599 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12600 (point)))
12601 (if (and (save-excursion
12602 (re-search-forward
12603 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12604 (not (save-excursion (re-search-forward
12605 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12606 (org-update-checkbox-count)
12607 (if (and l2 (> l2 l1))
12608 (progn
12609 (goto-char end)
12610 (org-update-parent-todo-statistics))
12611 (goto-char pos)
12612 (beginning-of-line 1)
12613 (while (re-search-forward
12614 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12615 (point-at-eol) t)
12616 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12617 (goto-char pos)
12618 (move-marker pos nil)))))
12619
12620 (defvar org-entry-property-inherited-from) ;; defined below
12621 (defun org-update-parent-todo-statistics ()
12622 "Update any statistics cookie in the parent of the current headline.
12623 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12624 the entire subtree and this will travel up the hierarchy and update
12625 statistics everywhere."
12626 (let* ((prop (save-excursion (org-up-heading-safe)
12627 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12628 (recursive (or (not org-hierarchical-todo-statistics)
12629 (and prop (string-match "\\<recursive\\>" prop))))
12630 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12631 0))
12632 (first t)
12633 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12634 level ltoggle l1 new ndel
12635 (cnt-all 0) (cnt-done 0) is-percent kwd
12636 checkbox-beg ov ovs ove cookie-present)
12637 (catch 'exit
12638 (save-excursion
12639 (beginning-of-line 1)
12640 (setq ltoggle (funcall outline-level))
12641 ;; Three situations are to consider:
12642
12643 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12644 ;; to the top-level ancestor on the headline;
12645
12646 ;; 2. If parent has "recursive" property, repeat up to the
12647 ;; headline setting that property, taking inheritance into
12648 ;; account;
12649
12650 ;; 3. Else, move up to direct parent and proceed only once.
12651 (while (and (setq level (org-up-heading-safe))
12652 (or recursive first)
12653 (>= (point) lim))
12654 (setq first nil cookie-present nil)
12655 (unless (and level
12656 (not (string-match
12657 "\\<checkbox\\>"
12658 (downcase (or (org-entry-get nil "COOKIE_DATA")
12659 "")))))
12660 (throw 'exit nil))
12661 (while (re-search-forward box-re (point-at-eol) t)
12662 (setq cnt-all 0 cnt-done 0 cookie-present t)
12663 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12664 (save-match-data
12665 (unless (outline-next-heading) (throw 'exit nil))
12666 (while (and (looking-at org-complex-heading-regexp)
12667 (> (setq l1 (length (match-string 1))) level))
12668 (setq kwd (and (or recursive (= l1 ltoggle))
12669 (match-string 2)))
12670 (if (or (eq org-provide-todo-statistics 'all-headlines)
12671 (and (listp org-provide-todo-statistics)
12672 (or (member kwd org-provide-todo-statistics)
12673 (member kwd org-done-keywords))))
12674 (setq cnt-all (1+ cnt-all))
12675 (if (eq org-provide-todo-statistics t)
12676 (and kwd (setq cnt-all (1+ cnt-all)))))
12677 (and (member kwd org-done-keywords)
12678 (setq cnt-done (1+ cnt-done)))
12679 (outline-next-heading)))
12680 (setq new
12681 (if is-percent
12682 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12683 (format "[%d/%d]" cnt-done cnt-all))
12684 ndel (- (match-end 0) checkbox-beg))
12685 ;; handle overlays when updating cookie from column view
12686 (when (setq ov (car (overlays-at checkbox-beg)))
12687 (setq ovs (overlay-start ov) ove (overlay-end ov))
12688 (delete-overlay ov))
12689 (goto-char checkbox-beg)
12690 (insert new)
12691 (delete-region (point) (+ (point) ndel))
12692 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12693 (when ov (move-overlay ov ovs ove)))
12694 (when cookie-present
12695 (run-hook-with-args 'org-after-todo-statistics-hook
12696 cnt-done (- cnt-all cnt-done))))))
12697 (run-hooks 'org-todo-statistics-hook)))
12698
12699 (defvar org-after-todo-statistics-hook nil
12700 "Hook that is called after a TODO statistics cookie has been updated.
12701 Each function is called with two arguments: the number of not-done entries
12702 and the number of done entries.
12703
12704 For example, the following function, when added to this hook, will switch
12705 an entry to DONE when all children are done, and back to TODO when new
12706 entries are set to a TODO status. Note that this hook is only called
12707 when there is a statistics cookie in the headline!
12708
12709 (defun org-summary-todo (n-done n-not-done)
12710 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12711 (let (org-log-done org-log-states) ; turn off logging
12712 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12713 ")
12714
12715 (defvar org-todo-statistics-hook nil
12716 "Hook that is run whenever Org thinks TODO statistics should be updated.
12717 This hook runs even if there is no statistics cookie present, in which case
12718 `org-after-todo-statistics-hook' would not run.")
12719
12720 (defun org-todo-trigger-tag-changes (state)
12721 "Apply the changes defined in `org-todo-state-tags-triggers'."
12722 (let ((l org-todo-state-tags-triggers)
12723 changes)
12724 (when (or (not state) (equal state ""))
12725 (setq changes (append changes (cdr (assoc "" l)))))
12726 (when (and (stringp state) (> (length state) 0))
12727 (setq changes (append changes (cdr (assoc state l)))))
12728 (when (member state org-not-done-keywords)
12729 (setq changes (append changes (cdr (assoc 'todo l)))))
12730 (when (member state org-done-keywords)
12731 (setq changes (append changes (cdr (assoc 'done l)))))
12732 (dolist (c changes)
12733 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12734
12735 (defun org-local-logging (value)
12736 "Get logging settings from a property VALUE."
12737 (let* (words w a)
12738 ;; directly set the variables, they are already local.
12739 (setq org-log-done nil
12740 org-log-repeat nil
12741 org-todo-log-states nil)
12742 (setq words (org-split-string value))
12743 (while (setq w (pop words))
12744 (cond
12745 ((setq a (assoc w org-startup-options))
12746 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12747 (set (nth 1 a) (nth 2 a))))
12748 ((setq a (org-extract-log-state-settings w))
12749 (and (member (car a) org-todo-keywords-1)
12750 (push a org-todo-log-states)))))))
12751
12752 (defun org-get-todo-sequence-head (kwd)
12753 "Return the head of the TODO sequence to which KWD belongs.
12754 If KWD is not set, check if there is a text property remembering the
12755 right sequence."
12756 (let (p)
12757 (cond
12758 ((not kwd)
12759 (or (get-text-property (point-at-bol) 'org-todo-head)
12760 (progn
12761 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12762 nil (point-at-eol)))
12763 (get-text-property p 'org-todo-head))))
12764 ((not (member kwd org-todo-keywords-1))
12765 (car org-todo-keywords-1))
12766 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12767
12768 (defun org-fast-todo-selection ()
12769 "Fast TODO keyword selection with single keys.
12770 Returns the new TODO keyword, or nil if no state change should occur."
12771 (let* ((fulltable org-todo-key-alist)
12772 (done-keywords org-done-keywords) ;; needed for the faces.
12773 (maxlen (apply 'max (mapcar
12774 (lambda (x)
12775 (if (stringp (car x)) (string-width (car x)) 0))
12776 fulltable)))
12777 (expert nil)
12778 (fwidth (+ maxlen 3 1 3))
12779 (ncol (/ (- (window-width) 4) fwidth))
12780 tg cnt e c tbl
12781 groups ingroup)
12782 (save-excursion
12783 (save-window-excursion
12784 (if expert
12785 (set-buffer (get-buffer-create " *Org todo*"))
12786 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12787 (erase-buffer)
12788 (org-set-local 'org-done-keywords done-keywords)
12789 (setq tbl fulltable cnt 0)
12790 (while (setq e (pop tbl))
12791 (cond
12792 ((equal e '(:startgroup))
12793 (push '() groups) (setq ingroup t)
12794 (when (not (= cnt 0))
12795 (setq cnt 0)
12796 (insert "\n"))
12797 (insert "{ "))
12798 ((equal e '(:endgroup))
12799 (setq ingroup nil cnt 0)
12800 (insert "}\n"))
12801 ((equal e '(:newline))
12802 (when (not (= cnt 0))
12803 (setq cnt 0)
12804 (insert "\n")
12805 (setq e (car tbl))
12806 (while (equal (car tbl) '(:newline))
12807 (insert "\n")
12808 (setq tbl (cdr tbl)))))
12809 (t
12810 (setq tg (car e) c (cdr e))
12811 (if ingroup (push tg (car groups)))
12812 (setq tg (org-add-props tg nil 'face
12813 (org-get-todo-face tg)))
12814 (if (and (= cnt 0) (not ingroup)) (insert " "))
12815 (insert "[" c "] " tg (make-string
12816 (- fwidth 4 (length tg)) ?\ ))
12817 (when (= (setq cnt (1+ cnt)) ncol)
12818 (insert "\n")
12819 (if ingroup (insert " "))
12820 (setq cnt 0)))))
12821 (insert "\n")
12822 (goto-char (point-min))
12823 (if (not expert) (org-fit-window-to-buffer))
12824 (message "[a-z..]:Set [SPC]:clear")
12825 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12826 (cond
12827 ((or (= c ?\C-g)
12828 (and (= c ?q) (not (rassoc c fulltable))))
12829 (setq quit-flag t))
12830 ((= c ?\ ) nil)
12831 ((setq e (rassoc c fulltable) tg (car e))
12832 tg)
12833 (t (setq quit-flag t)))))))
12834
12835 (defun org-entry-is-todo-p ()
12836 (member (org-get-todo-state) org-not-done-keywords))
12837
12838 (defun org-entry-is-done-p ()
12839 (member (org-get-todo-state) org-done-keywords))
12840
12841 (defun org-get-todo-state ()
12842 "Return the TODO keyword of the current subtree."
12843 (save-excursion
12844 (org-back-to-heading t)
12845 (and (looking-at org-todo-line-regexp)
12846 (match-end 2)
12847 (match-string 2))))
12848
12849 (defun org-at-date-range-p (&optional inactive-ok)
12850 "Is the cursor inside a date range?"
12851 (interactive)
12852 (save-excursion
12853 (catch 'exit
12854 (let ((pos (point)))
12855 (skip-chars-backward "^[<\r\n")
12856 (skip-chars-backward "<[")
12857 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12858 (>= (match-end 0) pos)
12859 (throw 'exit t))
12860 (skip-chars-backward "^<[\r\n")
12861 (skip-chars-backward "<[")
12862 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12863 (>= (match-end 0) pos)
12864 (throw 'exit t)))
12865 nil)))
12866
12867 (defun org-get-repeat (&optional tagline)
12868 "Check if there is a deadline/schedule with repeater in this entry."
12869 (save-match-data
12870 (save-excursion
12871 (org-back-to-heading t)
12872 (and (re-search-forward (if tagline
12873 (concat tagline "\\s-*" org-repeat-re)
12874 org-repeat-re)
12875 (org-entry-end-position) t)
12876 (match-string-no-properties 1)))))
12877
12878 (defvar org-last-changed-timestamp)
12879 (defvar org-last-inserted-timestamp)
12880 (defvar org-log-post-message)
12881 (defvar org-log-note-purpose)
12882 (defvar org-log-note-how)
12883 (defvar org-log-note-extra)
12884 (defun org-auto-repeat-maybe (done-word)
12885 "Check if the current headline contains a repeated deadline/schedule.
12886 If yes, set TODO state back to what it was and change the base date
12887 of repeating deadline/scheduled time stamps to new date.
12888 This function is run automatically after each state change to a DONE state."
12889 ;; last-state is dynamically scoped into this function
12890 (let* ((repeat (org-get-repeat))
12891 (aa (assoc org-last-state org-todo-kwd-alist))
12892 (interpret (nth 1 aa))
12893 (head (nth 2 aa))
12894 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12895 (msg "Entry repeats: ")
12896 (org-log-done nil)
12897 (org-todo-log-states nil)
12898 re type n what ts time to-state)
12899 (when repeat
12900 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12901 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12902 org-todo-repeat-to-state))
12903 (unless (and to-state (member to-state org-todo-keywords-1))
12904 (setq to-state (if (eq interpret 'type) org-last-state head)))
12905 (org-todo to-state)
12906 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12907 (org-entry-put nil "LAST_REPEAT" (format-time-string
12908 (org-time-stamp-format t t))))
12909 (when org-log-repeat
12910 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12911 (memq 'org-add-log-note post-command-hook))
12912 ;; OK, we are already setup for some record
12913 (if (eq org-log-repeat 'note)
12914 ;; make sure we take a note, not only a time stamp
12915 (setq org-log-note-how 'note))
12916 ;; Set up for taking a record
12917 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12918 org-last-state
12919 'findpos org-log-repeat)))
12920 (org-back-to-heading t)
12921 (org-add-planning-info nil nil 'closed)
12922 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12923 org-deadline-time-regexp "\\)\\|\\("
12924 org-ts-regexp "\\)"))
12925 (while (re-search-forward
12926 re (save-excursion (outline-next-heading) (point)) t)
12927 (setq type (if (match-end 1) org-scheduled-string
12928 (if (match-end 3) org-deadline-string "Plain:"))
12929 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12930 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12931 (setq n (string-to-number (match-string 2 ts))
12932 what (match-string 3 ts))
12933 (if (equal what "w") (setq n (* n 7) what "d"))
12934 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12935 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12936 ;; Preparation, see if we need to modify the start date for the change
12937 (when (match-end 1)
12938 (setq time (save-match-data (org-time-string-to-time ts)))
12939 (cond
12940 ((equal (match-string 1 ts) ".")
12941 ;; Shift starting date to today
12942 (org-timestamp-change
12943 (- (org-today) (time-to-days time))
12944 'day))
12945 ((equal (match-string 1 ts) "+")
12946 (let ((nshiftmax 10) (nshift 0))
12947 (while (or (= nshift 0)
12948 (<= (time-to-days time)
12949 (time-to-days (current-time))))
12950 (when (= (incf nshift) nshiftmax)
12951 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12952 (error "Abort")))
12953 (org-timestamp-change n (cdr (assoc what whata)))
12954 (org-at-timestamp-p t)
12955 (setq ts (match-string 1))
12956 (setq time (save-match-data (org-time-string-to-time ts)))))
12957 (org-timestamp-change (- n) (cdr (assoc what whata)))
12958 ;; rematch, so that we have everything in place for the real shift
12959 (org-at-timestamp-p t)
12960 (setq ts (match-string 1))
12961 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12962 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12963 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12964 (setq org-log-post-message msg)
12965 (message "%s" msg))))
12966
12967 (defun org-show-todo-tree (arg)
12968 "Make a compact tree which shows all headlines marked with TODO.
12969 The tree will show the lines where the regexp matches, and all higher
12970 headlines above the match.
12971 With a \\[universal-argument] prefix, prompt for a regexp to match.
12972 With a numeric prefix N, construct a sparse tree for the Nth element
12973 of `org-todo-keywords-1'."
12974 (interactive "P")
12975 (let ((case-fold-search nil)
12976 (kwd-re
12977 (cond ((null arg) org-not-done-regexp)
12978 ((equal arg '(4))
12979 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12980 (mapcar 'list org-todo-keywords-1))))
12981 (concat "\\("
12982 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12983 "\\)\\>")))
12984 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12985 (regexp-quote (nth (1- (prefix-numeric-value arg))
12986 org-todo-keywords-1)))
12987 (t (user-error "Invalid prefix argument: %s" arg)))))
12988 (message "%d TODO entries found"
12989 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12990
12991 (defun org-deadline (arg &optional time)
12992 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12993 With one universal prefix argument, remove any deadline from the item.
12994 With two universal prefix arguments, prompt for a warning delay.
12995 With argument TIME, set the deadline at the corresponding date. TIME
12996 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12997 (interactive "P")
12998 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12999 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13000 'region-start-level 'region))
13001 org-loop-over-headlines-in-active-region)
13002 (org-map-entries
13003 `(org-deadline ',arg ,time)
13004 org-loop-over-headlines-in-active-region
13005 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13006 (let* ((old-date (org-entry-get nil "DEADLINE"))
13007 (old-date-time (if old-date (org-time-string-to-time old-date)))
13008 (repeater (and old-date
13009 (string-match
13010 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13011 old-date)
13012 (match-string 1 old-date))))
13013 (cond
13014 ((equal arg '(4))
13015 (when (and old-date org-log-redeadline)
13016 (org-add-log-setup 'deldeadline nil old-date 'findpos
13017 org-log-redeadline))
13018 (org-remove-timestamp-with-keyword org-deadline-string)
13019 (message "Item no longer has a deadline."))
13020 ((equal arg '(16))
13021 (save-excursion
13022 (org-back-to-heading t)
13023 (if (re-search-forward
13024 org-deadline-time-regexp
13025 (save-excursion (outline-next-heading) (point)) t)
13026 (let* ((rpl0 (match-string 1))
13027 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13028 (replace-match
13029 (concat org-deadline-string
13030 " <" rpl
13031 (format " -%dd"
13032 (abs
13033 (- (time-to-days
13034 (save-match-data
13035 (org-read-date nil t nil "Warn starting from" old-date-time)))
13036 (time-to-days old-date-time))))
13037 ">") t t))
13038 (user-error "No deadline information to update"))))
13039 (t
13040 (org-add-planning-info 'deadline time 'closed)
13041 (when (and old-date org-log-redeadline
13042 (not (equal old-date
13043 (substring org-last-inserted-timestamp 1 -1))))
13044 (org-add-log-setup 'redeadline nil old-date 'findpos
13045 org-log-redeadline))
13046 (when repeater
13047 (save-excursion
13048 (org-back-to-heading t)
13049 (when (re-search-forward (concat org-deadline-string " "
13050 org-last-inserted-timestamp)
13051 (save-excursion
13052 (outline-next-heading) (point)) t)
13053 (goto-char (1- (match-end 0)))
13054 (insert " " repeater)
13055 (setq org-last-inserted-timestamp
13056 (concat (substring org-last-inserted-timestamp 0 -1)
13057 " " repeater
13058 (substring org-last-inserted-timestamp -1))))))
13059 (message "Deadline on %s" org-last-inserted-timestamp))))))
13060
13061 (defun org-schedule (arg &optional time)
13062 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13063 With one universal prefix argument, remove any scheduling date from the item.
13064 With two universal prefix arguments, prompt for a delay cookie.
13065 With argument TIME, scheduled at the corresponding date. TIME can
13066 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13067 (interactive "P")
13068 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13069 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13070 'region-start-level 'region))
13071 org-loop-over-headlines-in-active-region)
13072 (org-map-entries
13073 `(org-schedule ',arg ,time)
13074 org-loop-over-headlines-in-active-region
13075 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13076 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13077 (old-date-time (if old-date (org-time-string-to-time old-date)))
13078 (repeater (and old-date
13079 (string-match
13080 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13081 old-date)
13082 (match-string 1 old-date))))
13083 (cond
13084 ((equal arg '(4))
13085 (progn
13086 (when (and old-date org-log-reschedule)
13087 (org-add-log-setup 'delschedule nil old-date 'findpos
13088 org-log-reschedule))
13089 (org-remove-timestamp-with-keyword org-scheduled-string)
13090 (message "Item is no longer scheduled.")))
13091 ((equal arg '(16))
13092 (save-excursion
13093 (org-back-to-heading t)
13094 (if (re-search-forward
13095 org-scheduled-time-regexp
13096 (save-excursion (outline-next-heading) (point)) t)
13097 (let* ((rpl0 (match-string 1))
13098 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13099 (replace-match
13100 (concat org-scheduled-string
13101 " <" rpl
13102 (format " -%dd"
13103 (abs
13104 (- (time-to-days
13105 (save-match-data
13106 (org-read-date nil t nil "Delay until" old-date-time)))
13107 (time-to-days old-date-time))))
13108 ">") t t))
13109 (user-error "No scheduled information to update"))))
13110 (t
13111 (org-add-planning-info 'scheduled time 'closed)
13112 (when (and old-date org-log-reschedule
13113 (not (equal old-date
13114 (substring org-last-inserted-timestamp 1 -1))))
13115 (org-add-log-setup 'reschedule nil old-date 'findpos
13116 org-log-reschedule))
13117 (when repeater
13118 (save-excursion
13119 (org-back-to-heading t)
13120 (when (re-search-forward (concat org-scheduled-string " "
13121 org-last-inserted-timestamp)
13122 (save-excursion
13123 (outline-next-heading) (point)) t)
13124 (goto-char (1- (match-end 0)))
13125 (insert " " repeater)
13126 (setq org-last-inserted-timestamp
13127 (concat (substring org-last-inserted-timestamp 0 -1)
13128 " " repeater
13129 (substring org-last-inserted-timestamp -1))))))
13130 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13131
13132 (defun org-get-scheduled-time (pom &optional inherit)
13133 "Get the scheduled time as a time tuple, of a format suitable
13134 for calling org-schedule with, or if there is no scheduling,
13135 returns nil."
13136 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13137 (when time
13138 (apply 'encode-time (org-parse-time-string time)))))
13139
13140 (defun org-get-deadline-time (pom &optional inherit)
13141 "Get the deadline as a time tuple, of a format suitable for
13142 calling org-deadline with, or if there is no scheduling, returns
13143 nil."
13144 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13145 (when time
13146 (apply 'encode-time (org-parse-time-string time)))))
13147
13148 (defun org-remove-timestamp-with-keyword (keyword)
13149 "Remove all time stamps with KEYWORD in the current entry."
13150 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13151 beg)
13152 (save-excursion
13153 (org-back-to-heading t)
13154 (setq beg (point))
13155 (outline-next-heading)
13156 (while (re-search-backward re beg t)
13157 (replace-match "")
13158 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13159 (equal (char-before) ?\ ))
13160 (backward-delete-char 1)
13161 (if (string-match "^[ \t]*$" (buffer-substring
13162 (point-at-bol) (point-at-eol)))
13163 (delete-region (point-at-bol)
13164 (min (point-max) (1+ (point-at-eol))))))))))
13165
13166 (defvar org-time-was-given) ; dynamically scoped parameter
13167 (defvar org-end-time-was-given) ; dynamically scoped parameter
13168
13169 (defun org-add-planning-info (what &optional time &rest remove)
13170 "Insert new timestamp with keyword in the line directly after the headline.
13171 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13172 If non is given, the user is prompted for a date.
13173 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13174 be removed."
13175 (interactive)
13176 (let (org-time-was-given org-end-time-was-given ts
13177 end default-time default-input)
13178
13179 (catch 'exit
13180 (when (and (memq what '(scheduled deadline))
13181 (or (not time)
13182 (and (stringp time)
13183 (string-match "^[-+]+[0-9]" time))))
13184 ;; Try to get a default date/time from existing timestamp
13185 (save-excursion
13186 (org-back-to-heading t)
13187 (setq end (save-excursion (outline-next-heading) (point)))
13188 (when (re-search-forward (if (eq what 'scheduled)
13189 org-scheduled-time-regexp
13190 org-deadline-time-regexp)
13191 end t)
13192 (setq ts (match-string 1)
13193 default-time
13194 (apply 'encode-time (org-parse-time-string ts))
13195 default-input (and ts (org-get-compact-tod ts))))))
13196 (when what
13197 (setq time
13198 (if (stringp time)
13199 ;; This is a string (relative or absolute), set proper date
13200 (apply 'encode-time
13201 (org-read-date-analyze
13202 time default-time (decode-time default-time)))
13203 ;; If necessary, get the time from the user
13204 (or time (org-read-date nil 'to-time nil nil
13205 default-time default-input)))))
13206
13207 (when (and org-insert-labeled-timestamps-at-point
13208 (member what '(scheduled deadline)))
13209 (insert
13210 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13211 (org-insert-time-stamp time org-time-was-given
13212 nil nil nil (list org-end-time-was-given))
13213 (setq what nil))
13214 (save-excursion
13215 (save-restriction
13216 (let (col list elt ts buffer-invisibility-spec)
13217 (org-back-to-heading t)
13218 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13219 (goto-char (match-end 1))
13220 (setq col (current-column))
13221 (goto-char (match-end 0))
13222 (if (eobp) (insert "\n") (forward-char 1))
13223 (when (and (not what)
13224 (not (looking-at
13225 (concat "[ \t]*"
13226 org-keyword-time-not-clock-regexp))))
13227 ;; Nothing to add, nothing to remove...... :-)
13228 (throw 'exit nil))
13229 (if (and (not (looking-at org-outline-regexp))
13230 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13231 "[^\r\n]*"))
13232 (not (equal (match-string 1) org-clock-string)))
13233 (narrow-to-region (match-beginning 0) (match-end 0))
13234 (insert-before-markers "\n")
13235 (backward-char 1)
13236 (narrow-to-region (point) (point))
13237 (and org-adapt-indentation (org-indent-to-column col)))
13238 ;; Check if we have to remove something.
13239 (setq list (cons what remove))
13240 (while list
13241 (setq elt (pop list))
13242 (when (or (and (eq elt 'scheduled)
13243 (re-search-forward org-scheduled-time-regexp nil t))
13244 (and (eq elt 'deadline)
13245 (re-search-forward org-deadline-time-regexp nil t))
13246 (and (eq elt 'closed)
13247 (re-search-forward org-closed-time-regexp nil t)))
13248 (replace-match "")
13249 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13250 (and (looking-at "[ \t]+") (replace-match ""))
13251 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13252 (when what
13253 (insert
13254 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13255 (cond ((eq what 'scheduled) org-scheduled-string)
13256 ((eq what 'deadline) org-deadline-string)
13257 ((eq what 'closed) org-closed-string))
13258 " ")
13259 (setq ts (org-insert-time-stamp
13260 time
13261 (or org-time-was-given
13262 (and (eq what 'closed) org-log-done-with-time))
13263 (eq what 'closed)
13264 nil nil (list org-end-time-was-given)))
13265 (insert
13266 (if (not (or (bolp) (eq (char-before) ?\ )
13267 (memq (char-after) '(32 10))
13268 (eobp))) " " ""))
13269 (end-of-line 1))
13270 (goto-char (point-min))
13271 (widen)
13272 (if (and (looking-at "[ \t]*\n")
13273 (equal (char-before) ?\n))
13274 (delete-region (1- (point)) (point-at-eol)))
13275 ts))))))
13276
13277 (defvar org-log-note-marker (make-marker))
13278 (defvar org-log-note-purpose nil)
13279 (defvar org-log-note-state nil)
13280 (defvar org-log-note-previous-state nil)
13281 (defvar org-log-note-how nil)
13282 (defvar org-log-note-extra nil)
13283 (defvar org-log-note-window-configuration nil)
13284 (defvar org-log-note-return-to (make-marker))
13285 (defvar org-log-note-effective-time nil
13286 "Remembered current time so that dynamically scoped
13287 `org-extend-today-until' affects tha timestamps in state change
13288 log")
13289
13290 (defvar org-log-post-message nil
13291 "Message to be displayed after a log note has been stored.
13292 The auto-repeater uses this.")
13293
13294 (defun org-add-note ()
13295 "Add a note to the current entry.
13296 This is done in the same way as adding a state change note."
13297 (interactive)
13298 (org-add-log-setup 'note nil nil 'findpos nil))
13299
13300 (defvar org-property-end-re)
13301 (defun org-add-log-setup (&optional purpose state prev-state
13302 findpos how extra)
13303 "Set up the post command hook to take a note.
13304 If this is about to TODO state change, the new state is expected in STATE.
13305 When FINDPOS is non-nil, find the correct position for the note in
13306 the current entry. If not, assume that it can be inserted at point.
13307 HOW is an indicator what kind of note should be created.
13308 EXTRA is additional text that will be inserted into the notes buffer."
13309 (let* ((org-log-into-drawer (org-log-into-drawer))
13310 (drawer (cond ((stringp org-log-into-drawer)
13311 org-log-into-drawer)
13312 (org-log-into-drawer "LOGBOOK"))))
13313 (save-restriction
13314 (save-excursion
13315 (when findpos
13316 (org-back-to-heading t)
13317 (narrow-to-region (point) (save-excursion
13318 (outline-next-heading) (point)))
13319 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13320 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13321 "[^\r\n]*\\)?"))
13322 (goto-char (match-end 0))
13323 (cond
13324 (drawer
13325 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13326 nil t)
13327 (progn
13328 (goto-char (match-end 0))
13329 (or org-log-states-order-reversed
13330 (and (re-search-forward org-property-end-re nil t)
13331 (goto-char (1- (match-beginning 0))))))
13332 (insert "\n:" drawer ":\n:END:")
13333 (beginning-of-line 0)
13334 (org-indent-line)
13335 (beginning-of-line 2)
13336 (org-indent-line)
13337 (end-of-line 0)))
13338 ((and org-log-state-notes-insert-after-drawers
13339 (save-excursion
13340 (forward-line) (looking-at org-drawer-regexp)))
13341 (forward-line)
13342 (while (looking-at org-drawer-regexp)
13343 (goto-char (match-end 0))
13344 (re-search-forward org-property-end-re (point-max) t)
13345 (forward-line))
13346 (forward-line -1)))
13347 (unless org-log-states-order-reversed
13348 (and (= (char-after) ?\n) (forward-char 1))
13349 (org-skip-over-state-notes)
13350 (skip-chars-backward " \t\n\r")))
13351 (move-marker org-log-note-marker (point))
13352 (setq org-log-note-purpose purpose
13353 org-log-note-state state
13354 org-log-note-previous-state prev-state
13355 org-log-note-how how
13356 org-log-note-extra extra
13357 org-log-note-effective-time (org-current-effective-time))
13358 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13359
13360 (defun org-skip-over-state-notes ()
13361 "Skip past the list of State notes in an entry."
13362 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13363 (when (ignore-errors (goto-char (org-in-item-p)))
13364 (let* ((struct (org-list-struct))
13365 (prevs (org-list-prevs-alist struct)))
13366 (while (looking-at "[ \t]*- State")
13367 (goto-char (or (org-list-get-next-item (point) struct prevs)
13368 (org-list-get-item-end (point) struct)))))))
13369
13370 (defun org-add-log-note (&optional purpose)
13371 "Pop up a window for taking a note, and add this note later at point."
13372 (remove-hook 'post-command-hook 'org-add-log-note)
13373 (setq org-log-note-window-configuration (current-window-configuration))
13374 (delete-other-windows)
13375 (move-marker org-log-note-return-to (point))
13376 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13377 (goto-char org-log-note-marker)
13378 (org-switch-to-buffer-other-window "*Org Note*")
13379 (erase-buffer)
13380 (if (memq org-log-note-how '(time state))
13381 (let (current-prefix-arg) (org-store-log-note))
13382 (let ((org-inhibit-startup t)) (org-mode))
13383 (insert (format "# Insert note for %s.
13384 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13385 (cond
13386 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13387 ((eq org-log-note-purpose 'done) "closed todo item")
13388 ((eq org-log-note-purpose 'state)
13389 (format "state change from \"%s\" to \"%s\""
13390 (or org-log-note-previous-state "")
13391 (or org-log-note-state "")))
13392 ((eq org-log-note-purpose 'reschedule)
13393 "rescheduling")
13394 ((eq org-log-note-purpose 'delschedule)
13395 "no longer scheduled")
13396 ((eq org-log-note-purpose 'redeadline)
13397 "changing deadline")
13398 ((eq org-log-note-purpose 'deldeadline)
13399 "removing deadline")
13400 ((eq org-log-note-purpose 'refile)
13401 "refiling")
13402 ((eq org-log-note-purpose 'note)
13403 "this entry")
13404 (t (error "This should not happen")))))
13405 (if org-log-note-extra (insert org-log-note-extra))
13406 (org-set-local 'org-finish-function 'org-store-log-note)
13407 (run-hooks 'org-log-buffer-setup-hook)))
13408
13409 (defvar org-note-abort nil) ; dynamically scoped
13410 (defun org-store-log-note ()
13411 "Finish taking a log note, and insert it to where it belongs."
13412 (let ((txt (buffer-string)))
13413 (kill-buffer (current-buffer))
13414 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13415 lines ind bul)
13416 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13417 (setq txt (replace-match "" t t txt)))
13418 (if (string-match "\\s-+\\'" txt)
13419 (setq txt (replace-match "" t t txt)))
13420 (setq lines (org-split-string txt "\n"))
13421 (when (and note (string-match "\\S-" note))
13422 (setq note
13423 (org-replace-escapes
13424 note
13425 (list (cons "%u" (user-login-name))
13426 (cons "%U" user-full-name)
13427 (cons "%t" (format-time-string
13428 (org-time-stamp-format 'long 'inactive)
13429 org-log-note-effective-time))
13430 (cons "%T" (format-time-string
13431 (org-time-stamp-format 'long nil)
13432 org-log-note-effective-time))
13433 (cons "%d" (format-time-string
13434 (org-time-stamp-format nil 'inactive)
13435 org-log-note-effective-time))
13436 (cons "%D" (format-time-string
13437 (org-time-stamp-format nil nil)
13438 org-log-note-effective-time))
13439 (cons "%s" (if org-log-note-state
13440 (concat "\"" org-log-note-state "\"")
13441 ""))
13442 (cons "%S" (if org-log-note-previous-state
13443 (concat "\"" org-log-note-previous-state "\"")
13444 "\"\"")))))
13445 (if lines (setq note (concat note " \\\\")))
13446 (push note lines))
13447 (when (or current-prefix-arg org-note-abort)
13448 (when org-log-into-drawer
13449 (org-remove-empty-drawer-at
13450 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13451 org-log-note-marker))
13452 (setq lines nil))
13453 (when lines
13454 (with-current-buffer (marker-buffer org-log-note-marker)
13455 (save-excursion
13456 (goto-char org-log-note-marker)
13457 (move-marker org-log-note-marker nil)
13458 (end-of-line 1)
13459 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13460 (setq ind (save-excursion
13461 (if (ignore-errors (goto-char (org-in-item-p)))
13462 (let ((struct (org-list-struct)))
13463 (org-list-get-ind
13464 (org-list-get-top-point struct) struct))
13465 (skip-chars-backward " \r\t\n")
13466 (cond
13467 ((and (org-at-heading-p)
13468 org-adapt-indentation)
13469 (1+ (org-current-level)))
13470 ((org-at-heading-p) 0)
13471 (t (org-get-indentation))))))
13472 (setq bul (org-list-bullet-string "-"))
13473 (org-indent-line-to ind)
13474 (insert bul (pop lines))
13475 (let ((ind-body (+ (length bul) ind)))
13476 (while lines
13477 (insert "\n")
13478 (org-indent-line-to ind-body)
13479 (insert (pop lines))))
13480 (message "Note stored")
13481 (org-back-to-heading t)
13482 (org-cycle-hide-drawers 'children))
13483 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13484 ;; from within `org-add-log-note' because `buffer-undo-list'
13485 ;; is then modified outside of `org-with-remote-undo'.
13486 (when (eq this-command 'org-agenda-todo)
13487 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13488 ;; Don't add undo information when called from `org-agenda-todo'
13489 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13490 (set-window-configuration org-log-note-window-configuration)
13491 (with-current-buffer (marker-buffer org-log-note-return-to)
13492 (goto-char org-log-note-return-to))
13493 (move-marker org-log-note-return-to nil)
13494 (and org-log-post-message (message "%s" org-log-post-message))))
13495
13496 (defun org-remove-empty-drawer-at (drawer pos)
13497 "Remove an empty drawer DRAWER at position POS.
13498 POS may also be a marker."
13499 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13500 (save-excursion
13501 (save-restriction
13502 (widen)
13503 (goto-char pos)
13504 (if (org-in-regexp
13505 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13506 (replace-match ""))))))
13507
13508 (defvar org-ts-type nil)
13509 (defun org-sparse-tree (&optional arg type)
13510 "Create a sparse tree, prompt for the details.
13511 This command can create sparse trees. You first need to select the type
13512 of match used to create the tree:
13513
13514 t Show all TODO entries.
13515 T Show entries with a specific TODO keyword.
13516 m Show entries selected by a tags/property match.
13517 p Enter a property name and its value (both with completion on existing
13518 names/values) and show entries with that property.
13519 r Show entries matching a regular expression (`/' can be used as well).
13520 b Show deadlines and scheduled items before a date.
13521 a Show deadlines and scheduled items after a date.
13522 d Show deadlines due within `org-deadline-warning-days'.
13523 D Show deadlines and scheduled items between a date range."
13524 (interactive "P")
13525 (setq type (or type org-sparse-tree-default-date-type))
13526 (setq org-ts-type type)
13527 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13528 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13529 [c]ycle through date types: %s"
13530 (case type
13531 (all "all timestamps")
13532 (scheduled "only scheduled")
13533 (deadline "only deadline")
13534 (active "only active timestamps")
13535 (inactive "only inactive timestamps")
13536 (scheduled-or-deadline "scheduled/deadline")
13537 (closed "with a closed time-stamp")
13538 (otherwise "scheduled/deadline")))
13539 (let ((answer (read-char-exclusive)))
13540 (case answer
13541 (?c
13542 (org-sparse-tree
13543 arg
13544 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13545 inactive closed)))))
13546 (?d (call-interactively #'org-check-deadlines))
13547 (?b (call-interactively #'org-check-before-date))
13548 (?a (call-interactively #'org-check-after-date))
13549 (?D (call-interactively #'org-check-dates-range))
13550 (?t (call-interactively #'org-show-todo-tree))
13551 (?T (org-show-todo-tree '(4)))
13552 (?m (call-interactively #'org-match-sparse-tree))
13553 ((?p ?P)
13554 (let* ((kwd (org-icompleting-read
13555 "Property: " (mapcar #'list (org-buffer-property-keys))))
13556 (value (org-icompleting-read
13557 "Value: " (mapcar #'list (org-property-values kwd)))))
13558 (unless (string-match "\\`{.*}\\'" value)
13559 (setq value (concat "\"" value "\"")))
13560 (org-match-sparse-tree arg (concat kwd "=" value))))
13561 ((?r ?R ?/) (call-interactively #'org-occur))
13562 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13563
13564 (defvar org-occur-highlights nil
13565 "List of overlays used for occur matches.")
13566 (make-variable-buffer-local 'org-occur-highlights)
13567 (defvar org-occur-parameters nil
13568 "Parameters of the active org-occur calls.
13569 This is a list, each call to org-occur pushes as cons cell,
13570 containing the regular expression and the callback, onto the list.
13571 The list can contain several entries if `org-occur' has been called
13572 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13573 will only contain one set of parameters. When the highlights are
13574 removed (for example with `C-c C-c', or with the next edit (depending
13575 on `org-remove-highlights-with-change'), this variable is emptied
13576 as well.")
13577 (make-variable-buffer-local 'org-occur-parameters)
13578
13579 (defun org-occur (regexp &optional keep-previous callback)
13580 "Make a compact tree which shows all matches of REGEXP.
13581 The tree will show the lines where the regexp matches, and all higher
13582 headlines above the match. It will also show the heading after the match,
13583 to make sure editing the matching entry is easy.
13584 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13585 call to `org-occur' will be kept, to allow stacking of calls to this
13586 command.
13587 If CALLBACK is non-nil, it is a function which is called to confirm
13588 that the match should indeed be shown."
13589 (interactive "sRegexp: \nP")
13590 (when (equal regexp "")
13591 (user-error "Regexp cannot be empty"))
13592 (unless keep-previous
13593 (org-remove-occur-highlights nil nil t))
13594 (push (cons regexp callback) org-occur-parameters)
13595 (let ((cnt 0))
13596 (save-excursion
13597 (goto-char (point-min))
13598 (if (or (not keep-previous) ; do not want to keep
13599 (not org-occur-highlights)) ; no previous matches
13600 ;; hide everything
13601 (org-overview))
13602 (while (re-search-forward regexp nil t)
13603 (when (or (not callback)
13604 (save-match-data (funcall callback)))
13605 (setq cnt (1+ cnt))
13606 (when org-highlight-sparse-tree-matches
13607 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13608 (org-show-context 'occur-tree))))
13609 (when org-remove-highlights-with-change
13610 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13611 nil 'local))
13612 (unless org-sparse-tree-open-archived-trees
13613 (org-hide-archived-subtrees (point-min) (point-max)))
13614 (run-hooks 'org-occur-hook)
13615 (if (org-called-interactively-p 'interactive)
13616 (message "%d match(es) for regexp %s" cnt regexp))
13617 cnt))
13618
13619 (defun org-occur-next-match (&optional n reset)
13620 "Function for `next-error-function' to find sparse tree matches.
13621 N is the number of matches to move, when negative move backwards.
13622 RESET is entirely ignored - this function always goes back to the
13623 starting point when no match is found."
13624 (let* ((limit (if (< n 0) (point-min) (point-max)))
13625 (search-func (if (< n 0)
13626 'previous-single-char-property-change
13627 'next-single-char-property-change))
13628 (n (abs n))
13629 (pos (point))
13630 p1)
13631 (catch 'exit
13632 (while (setq p1 (funcall search-func (point) 'org-type))
13633 (when (equal p1 limit)
13634 (goto-char pos)
13635 (error "No more matches"))
13636 (when (equal (get-char-property p1 'org-type) 'org-occur)
13637 (setq n (1- n))
13638 (when (= n 0)
13639 (goto-char p1)
13640 (throw 'exit (point))))
13641 (goto-char p1))
13642 (goto-char p1)
13643 (error "No more matches"))))
13644
13645 (defun org-show-context (&optional key)
13646 "Make sure point and context are visible.
13647 How much context is shown depends upon the variables
13648 `org-show-hierarchy-above', `org-show-following-heading',
13649 `org-show-entry-below' and `org-show-siblings'."
13650 (let ((heading-p (org-at-heading-p t))
13651 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13652 (following-p (org-get-alist-option org-show-following-heading key))
13653 (entry-p (org-get-alist-option org-show-entry-below key))
13654 (siblings-p (org-get-alist-option org-show-siblings key)))
13655 ;; Show heading or entry text
13656 (if (and heading-p (not entry-p))
13657 (org-flag-heading nil) ; only show the heading
13658 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13659 (org-show-hidden-entry))) ; show entire entry
13660 (when following-p
13661 ;; Show next sibling, or heading below text
13662 (save-excursion
13663 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13664 (org-flag-heading nil))))
13665 (when siblings-p (org-show-siblings))
13666 (when hierarchy-p
13667 ;; show all higher headings, possibly with siblings
13668 (save-excursion
13669 (while (and (condition-case nil
13670 (progn (org-up-heading-all 1) t)
13671 (error nil))
13672 (not (bobp)))
13673 (org-flag-heading nil)
13674 (when siblings-p (org-show-siblings)))))))
13675
13676 (defvar org-reveal-start-hook nil
13677 "Hook run before revealing a location.")
13678
13679 (defun org-reveal (&optional siblings)
13680 "Show current entry, hierarchy above it, and the following headline.
13681 This can be used to show a consistent set of context around locations
13682 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13683 not t for the search context.
13684
13685 With optional argument SIBLINGS, on each level of the hierarchy all
13686 siblings are shown. This repairs the tree structure to what it would
13687 look like when opened with hierarchical calls to `org-cycle'.
13688 With double optional argument \\[universal-argument] \\[universal-argument], \
13689 go to the parent and show the
13690 entire tree."
13691 (interactive "P")
13692 (run-hooks 'org-reveal-start-hook)
13693 (let ((org-show-hierarchy-above t)
13694 (org-show-following-heading t)
13695 (org-show-siblings (if siblings t org-show-siblings)))
13696 (org-show-context nil))
13697 (when (equal siblings '(16))
13698 (save-excursion
13699 (when (org-up-heading-safe)
13700 (org-show-subtree)
13701 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13702
13703 (defun org-highlight-new-match (beg end)
13704 "Highlight from BEG to END and mark the highlight is an occur headline."
13705 (let ((ov (make-overlay beg end)))
13706 (overlay-put ov 'face 'secondary-selection)
13707 (overlay-put ov 'org-type 'org-occur)
13708 (push ov org-occur-highlights)))
13709
13710 (defun org-remove-occur-highlights (&optional beg end noremove)
13711 "Remove the occur highlights from the buffer.
13712 BEG and END are ignored. If NOREMOVE is nil, remove this function
13713 from the `before-change-functions' in the current buffer."
13714 (interactive)
13715 (unless org-inhibit-highlight-removal
13716 (mapc 'delete-overlay org-occur-highlights)
13717 (setq org-occur-highlights nil)
13718 (setq org-occur-parameters nil)
13719 (unless noremove
13720 (remove-hook 'before-change-functions
13721 'org-remove-occur-highlights 'local))))
13722
13723 ;;;; Priorities
13724
13725 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13726 "Regular expression matching the priority indicator.")
13727
13728 (defvar org-remove-priority-next-time nil)
13729
13730 (defun org-priority-up ()
13731 "Increase the priority of the current item."
13732 (interactive)
13733 (org-priority 'up))
13734
13735 (defun org-priority-down ()
13736 "Decrease the priority of the current item."
13737 (interactive)
13738 (org-priority 'down))
13739
13740 (defun org-priority (&optional action show)
13741 "Change the priority of an item.
13742 ACTION can be `set', `up', `down', or a character."
13743 (interactive "P")
13744 (if (equal action '(4))
13745 (org-show-priority)
13746 (unless org-enable-priority-commands
13747 (user-error "Priority commands are disabled"))
13748 (setq action (or action 'set))
13749 (let (current new news have remove)
13750 (save-excursion
13751 (org-back-to-heading t)
13752 (if (looking-at org-priority-regexp)
13753 (setq current (string-to-char (match-string 2))
13754 have t))
13755 (cond
13756 ((eq action 'remove)
13757 (setq remove t new ?\ ))
13758 ((or (eq action 'set)
13759 (if (featurep 'xemacs) (characterp action) (integerp action)))
13760 (if (not (eq action 'set))
13761 (setq new action)
13762 (message "Priority %c-%c, SPC to remove: "
13763 org-highest-priority org-lowest-priority)
13764 (save-match-data
13765 (setq new (read-char-exclusive))))
13766 (if (and (= (upcase org-highest-priority) org-highest-priority)
13767 (= (upcase org-lowest-priority) org-lowest-priority))
13768 (setq new (upcase new)))
13769 (cond ((equal new ?\ ) (setq remove t))
13770 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13771 (user-error "Priority must be between `%c' and `%c'"
13772 org-highest-priority org-lowest-priority))))
13773 ((eq action 'up)
13774 (setq new (if have
13775 (1- current) ; normal cycling
13776 ;; last priority was empty
13777 (if (eq last-command this-command)
13778 org-lowest-priority ; wrap around empty to lowest
13779 ;; default
13780 (if org-priority-start-cycle-with-default
13781 org-default-priority
13782 (1- org-default-priority))))))
13783 ((eq action 'down)
13784 (setq new (if have
13785 (1+ current) ; normal cycling
13786 ;; last priority was empty
13787 (if (eq last-command this-command)
13788 org-highest-priority ; wrap around empty to highest
13789 ;; default
13790 (if org-priority-start-cycle-with-default
13791 org-default-priority
13792 (1+ org-default-priority))))))
13793 (t (user-error "Invalid action")))
13794 (if (or (< (upcase new) org-highest-priority)
13795 (> (upcase new) org-lowest-priority))
13796 (if (and (memq action '(up down))
13797 (not have) (not (eq last-command this-command)))
13798 ;; `new' is from default priority
13799 (error
13800 "The default can not be set, see `org-default-priority' why")
13801 ;; normal cycling: `new' is beyond highest/lowest priority
13802 ;; and is wrapped around to the empty priority
13803 (setq remove t)))
13804 (setq news (format "%c" new))
13805 (if have
13806 (if remove
13807 (replace-match "" t t nil 1)
13808 (replace-match news t t nil 2))
13809 (if remove
13810 (user-error "No priority cookie found in line")
13811 (let ((case-fold-search nil))
13812 (looking-at org-todo-line-regexp))
13813 (if (match-end 2)
13814 (progn
13815 (goto-char (match-end 2))
13816 (insert " [#" news "]"))
13817 (goto-char (match-beginning 3))
13818 (insert "[#" news "] "))))
13819 (org-preserve-lc (org-set-tags nil 'align)))
13820 (if remove
13821 (message "Priority removed")
13822 (message "Priority of current item set to %s" news)))))
13823
13824 (defun org-show-priority ()
13825 "Show the priority of the current item.
13826 This priority is composed of the main priority given with the [#A] cookies,
13827 and by additional input from the age of a schedules or deadline entry."
13828 (interactive)
13829 (let ((pri (if (eq major-mode 'org-agenda-mode)
13830 (org-get-at-bol 'priority)
13831 (save-excursion
13832 (save-match-data
13833 (beginning-of-line)
13834 (and (looking-at org-heading-regexp)
13835 (org-get-priority (match-string 0))))))))
13836 (message "Priority is %d" (if pri pri -1000))))
13837
13838 (defun org-get-priority (s)
13839 "Find priority cookie and return priority."
13840 (save-match-data
13841 (if (functionp org-get-priority-function)
13842 (funcall org-get-priority-function)
13843 (if (not (string-match org-priority-regexp s))
13844 (* 1000 (- org-lowest-priority org-default-priority))
13845 (* 1000 (- org-lowest-priority
13846 (string-to-char (match-string 2 s))))))))
13847
13848 ;;;; Tags
13849
13850 (defvar org-agenda-archives-mode)
13851 (defvar org-map-continue-from nil
13852 "Position from where mapping should continue.
13853 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13854
13855 (defvar org-scanner-tags nil
13856 "The current tag list while the tags scanner is running.")
13857 (defvar org-trust-scanner-tags nil
13858 "Should `org-get-tags-at' use the tags for the scanner.
13859 This is for internal dynamical scoping only.
13860 When this is non-nil, the function `org-get-tags-at' will return the value
13861 of `org-scanner-tags' instead of building the list by itself. This
13862 can lead to large speed-ups when the tags scanner is used in a file with
13863 many entries, and when the list of tags is retrieved, for example to
13864 obtain a list of properties. Building the tags list for each entry in such
13865 a file becomes an N^2 operation - but with this variable set, it scales
13866 as N.")
13867
13868 (defun org-scan-tags (action matcher todo-only &optional start-level)
13869 "Scan headline tags with inheritance and produce output ACTION.
13870
13871 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13872 or `agenda' to produce an entry list for an agenda view. It can also be
13873 a Lisp form or a function that should be called at each matched headline, in
13874 this case the return value is a list of all return values from these calls.
13875
13876 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13877 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13878 only lines with a not-done TODO keyword are included in the output.
13879 This should be the same variable that was scoped into
13880 and set by `org-make-tags-matcher' when it constructed MATCHER.
13881
13882 START-LEVEL can be a string with asterisks, reducing the scope to
13883 headlines matching this string."
13884 (require 'org-agenda)
13885 (let* ((re (concat "^"
13886 (if start-level
13887 ;; Get the correct level to match
13888 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13889 org-outline-regexp)
13890 " *\\(\\<\\("
13891 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13892 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13893 (props (list 'face 'default
13894 'done-face 'org-agenda-done
13895 'undone-face 'default
13896 'mouse-face 'highlight
13897 'org-not-done-regexp org-not-done-regexp
13898 'org-todo-regexp org-todo-regexp
13899 'org-complex-heading-regexp org-complex-heading-regexp
13900 'help-echo
13901 (format "mouse-2 or RET jump to org file %s"
13902 (abbreviate-file-name
13903 (or (buffer-file-name (buffer-base-buffer))
13904 (buffer-name (buffer-base-buffer)))))))
13905 (org-map-continue-from nil)
13906 lspos tags tags-list
13907 (tags-alist (list (cons 0 org-file-tags)))
13908 (llast 0) rtn rtn1 level category i txt
13909 todo marker entry priority)
13910 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13911 (setq action (list 'lambda nil action)))
13912 (save-excursion
13913 (goto-char (point-min))
13914 (when (eq action 'sparse-tree)
13915 (org-overview)
13916 (org-remove-occur-highlights))
13917 (while (let (case-fold-search)
13918 (re-search-forward re nil t))
13919 (setq org-map-continue-from nil)
13920 (catch :skip
13921 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13922 tags (if (match-end 4) (org-match-string-no-properties 4)))
13923 (goto-char (setq lspos (match-beginning 0)))
13924 (setq level (org-reduced-level (org-outline-level))
13925 category (org-get-category))
13926 (setq i llast llast level)
13927 ;; remove tag lists from same and sublevels
13928 (while (>= i level)
13929 (when (setq entry (assoc i tags-alist))
13930 (setq tags-alist (delete entry tags-alist)))
13931 (setq i (1- i)))
13932 ;; add the next tags
13933 (when tags
13934 (setq tags (org-split-string tags ":")
13935 tags-alist
13936 (cons (cons level tags) tags-alist)))
13937 ;; compile tags for current headline
13938 (setq tags-list
13939 (if org-use-tag-inheritance
13940 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13941 tags)
13942 org-scanner-tags tags-list)
13943 (when org-use-tag-inheritance
13944 (setcdr (car tags-alist)
13945 (mapcar (lambda (x)
13946 (setq x (copy-sequence x))
13947 (org-add-prop-inherited x))
13948 (cdar tags-alist))))
13949 (when (and tags org-use-tag-inheritance
13950 (or (not (eq t org-use-tag-inheritance))
13951 org-tags-exclude-from-inheritance))
13952 ;; selective inheritance, remove uninherited ones
13953 (setcdr (car tags-alist)
13954 (org-remove-uninherited-tags (cdar tags-alist))))
13955 (when (and
13956
13957 ;; eval matcher only when the todo condition is OK
13958 (and (or (not todo-only) (member todo org-not-done-keywords))
13959 (let ((case-fold-search t) (org-trust-scanner-tags t))
13960 (eval matcher)))
13961
13962 ;; Call the skipper, but return t if it does not skip,
13963 ;; so that the `and' form continues evaluating
13964 (progn
13965 (unless (eq action 'sparse-tree) (org-agenda-skip))
13966 t)
13967
13968 ;; Check if timestamps are deselecting this entry
13969 (or (not todo-only)
13970 (and (member todo org-not-done-keywords)
13971 (or (not org-agenda-tags-todo-honor-ignore-options)
13972 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13973
13974 ;; select this headline
13975 (cond
13976 ((eq action 'sparse-tree)
13977 (and org-highlight-sparse-tree-matches
13978 (org-get-heading) (match-end 0)
13979 (org-highlight-new-match
13980 (match-beginning 1) (match-end 1)))
13981 (org-show-context 'tags-tree))
13982 ((eq action 'agenda)
13983 (setq txt (org-agenda-format-item
13984 ""
13985 (concat
13986 (if (eq org-tags-match-list-sublevels 'indented)
13987 (make-string (1- level) ?.) "")
13988 (org-get-heading))
13989 level category
13990 tags-list)
13991 priority (org-get-priority txt))
13992 (goto-char lspos)
13993 (setq marker (org-agenda-new-marker))
13994 (org-add-props txt props
13995 'org-marker marker 'org-hd-marker marker 'org-category category
13996 'todo-state todo
13997 'priority priority 'type "tagsmatch")
13998 (push txt rtn))
13999 ((functionp action)
14000 (setq org-map-continue-from nil)
14001 (save-excursion
14002 (setq rtn1 (funcall action))
14003 (push rtn1 rtn)))
14004 (t (user-error "Invalid action")))
14005
14006 ;; if we are to skip sublevels, jump to end of subtree
14007 (unless org-tags-match-list-sublevels
14008 (org-end-of-subtree t)
14009 (backward-char 1))))
14010 ;; Get the correct position from where to continue
14011 (if org-map-continue-from
14012 (goto-char org-map-continue-from)
14013 (and (= (point) lspos) (end-of-line 1)))))
14014 (when (and (eq action 'sparse-tree)
14015 (not org-sparse-tree-open-archived-trees))
14016 (org-hide-archived-subtrees (point-min) (point-max)))
14017 (nreverse rtn)))
14018
14019 (defun org-remove-uninherited-tags (tags)
14020 "Remove all tags that are not inherited from the list TAGS."
14021 (cond
14022 ((eq org-use-tag-inheritance t)
14023 (if org-tags-exclude-from-inheritance
14024 (org-delete-all org-tags-exclude-from-inheritance tags)
14025 tags))
14026 ((not org-use-tag-inheritance) nil)
14027 ((stringp org-use-tag-inheritance)
14028 (delq nil (mapcar
14029 (lambda (x)
14030 (if (and (string-match org-use-tag-inheritance x)
14031 (not (member x org-tags-exclude-from-inheritance)))
14032 x nil))
14033 tags)))
14034 ((listp org-use-tag-inheritance)
14035 (delq nil (mapcar
14036 (lambda (x)
14037 (if (member x org-use-tag-inheritance) x nil))
14038 tags)))))
14039
14040 (defun org-match-sparse-tree (&optional todo-only match)
14041 "Create a sparse tree according to tags string MATCH.
14042 MATCH can contain positive and negative selection of tags, like
14043 \"+WORK+URGENT-WITHBOSS\".
14044 If optional argument TODO-ONLY is non-nil, only select lines that are
14045 also TODO lines."
14046 (interactive "P")
14047 (org-agenda-prepare-buffers (list (current-buffer)))
14048 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14049
14050 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14051
14052 (defvar org-cached-props nil)
14053 (defun org-cached-entry-get (pom property)
14054 (if (or (eq t org-use-property-inheritance)
14055 (and (stringp org-use-property-inheritance)
14056 (string-match org-use-property-inheritance property))
14057 (and (listp org-use-property-inheritance)
14058 (member property org-use-property-inheritance)))
14059 ;; Caching is not possible, check it directly
14060 (org-entry-get pom property 'inherit)
14061 ;; Get all properties, so that we can do complicated checks easily
14062 (cdr (assoc property (or org-cached-props
14063 (setq org-cached-props
14064 (org-entry-properties pom)))))))
14065
14066 (defun org-global-tags-completion-table (&optional files)
14067 "Return the list of all tags in all agenda buffer/files.
14068 Optional FILES argument is a list of files which can be used
14069 instead of the agenda files."
14070 (save-excursion
14071 (org-uniquify
14072 (delq nil
14073 (apply 'append
14074 (mapcar
14075 (lambda (file)
14076 (set-buffer (find-file-noselect file))
14077 (append (org-get-buffer-tags)
14078 (mapcar (lambda (x) (if (stringp (car-safe x))
14079 (list (car-safe x)) nil))
14080 org-tag-alist)))
14081 (if (and files (car files))
14082 files
14083 (org-agenda-files))))))))
14084
14085 (defun org-make-tags-matcher (match)
14086 "Create the TAGS/TODO matcher form for the selection string MATCH.
14087
14088 The variable `todo-only' is scoped dynamically into this function.
14089 It will be set to t if the matcher restricts matching to TODO entries,
14090 otherwise will not be touched.
14091
14092 Returns a cons of the selection string MATCH and the constructed
14093 lisp form implementing the matcher. The matcher is to be evaluated
14094 at an Org entry, with point on the headline, and returns t if the
14095 entry matches the selection string MATCH. The returned lisp form
14096 references two variables with information about the entry, which
14097 must be bound around the form's evaluation: todo, the TODO keyword
14098 at the entry (or nil of none); and tags-list, the list of all tags
14099 at the entry including inherited ones. Additionally, the category
14100 of the entry (if any) must be specified as the text property
14101 'org-category on the headline.
14102
14103 See also `org-scan-tags'.
14104 "
14105 (declare (special todo-only))
14106 (unless (boundp 'todo-only)
14107 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14108 (unless match
14109 ;; Get a new match request, with completion against the global
14110 ;; tags table and the local tags in current buffer
14111 (let ((org-last-tags-completion-table
14112 (org-uniquify
14113 (delq nil (append (org-get-buffer-tags)
14114 (org-global-tags-completion-table))))))
14115 (setq match (org-completing-read-no-i
14116 "Match: " 'org-tags-completion-function nil nil nil
14117 'org-tags-history))))
14118
14119 ;; Parse the string and create a lisp form
14120 (let ((match0 match)
14121 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14122 minus tag mm
14123 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14124 orterms term orlist re-p str-p level-p level-op time-p
14125 prop-p pn pv po gv rest (start 0) (ss 0))
14126 ;; Expand group tags
14127 (setq match (org-tags-expand match))
14128
14129 ;; Check if there is a TODO part of this match, which would be the
14130 ;; part after a "/". TO make sure that this slash is not part of
14131 ;; a property value to be matched against, we also check that there
14132 ;; is no " after that slash.
14133 ;; First, find the last slash
14134 (while (string-match "/+" match ss)
14135 (setq start (match-beginning 0) ss (match-end 0)))
14136 (if (and (string-match "/+" match start)
14137 (not (save-match-data (string-match "\"" match start))))
14138 ;; match contains also a todo-matching request
14139 (progn
14140 (setq tagsmatch (substring match 0 (match-beginning 0))
14141 todomatch (substring match (match-end 0)))
14142 (if (string-match "^!" todomatch)
14143 (setq todo-only t todomatch (substring todomatch 1)))
14144 (if (string-match "^\\s-*$" todomatch)
14145 (setq todomatch nil)))
14146 ;; only matching tags
14147 (setq tagsmatch match todomatch nil))
14148
14149 ;; Make the tags matcher
14150 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14151 (setq tagsmatcher t)
14152 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14153 (while (setq term (pop orterms))
14154 (while (and (equal (substring term -1) "\\") orterms)
14155 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14156 (while (string-match re term)
14157 (setq rest (substring term (match-end 0))
14158 minus (and (match-end 1)
14159 (equal (match-string 1 term) "-"))
14160 tag (save-match-data (replace-regexp-in-string
14161 "\\\\-" "-"
14162 (match-string 2 term)))
14163 re-p (equal (string-to-char tag) ?{)
14164 level-p (match-end 4)
14165 prop-p (match-end 5)
14166 mm (cond
14167 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14168 (level-p
14169 (setq level-op (org-op-to-function (match-string 3 term)))
14170 `(,level-op level ,(string-to-number
14171 (match-string 4 term))))
14172 (prop-p
14173 (setq pn (match-string 5 term)
14174 po (match-string 6 term)
14175 pv (match-string 7 term)
14176 re-p (equal (string-to-char pv) ?{)
14177 str-p (equal (string-to-char pv) ?\")
14178 time-p (save-match-data
14179 (string-match "^\"[[<].*[]>]\"$" pv))
14180 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14181 (if time-p (setq pv (org-matcher-time pv)))
14182 (setq po (org-op-to-function po (if time-p 'time str-p)))
14183 (cond
14184 ((equal pn "CATEGORY")
14185 (setq gv '(get-text-property (point) 'org-category)))
14186 ((equal pn "TODO")
14187 (setq gv 'todo))
14188 (t
14189 (setq gv `(org-cached-entry-get nil ,pn))))
14190 (if re-p
14191 (if (eq po 'org<>)
14192 `(not (string-match ,pv (or ,gv "")))
14193 `(string-match ,pv (or ,gv "")))
14194 (if str-p
14195 `(,po (or ,gv "") ,pv)
14196 `(,po (string-to-number (or ,gv ""))
14197 ,(string-to-number pv) ))))
14198 (t `(member ,tag tags-list)))
14199 mm (if minus (list 'not mm) mm)
14200 term rest)
14201 (push mm tagsmatcher))
14202 (push (if (> (length tagsmatcher) 1)
14203 (cons 'and tagsmatcher)
14204 (car tagsmatcher))
14205 orlist)
14206 (setq tagsmatcher nil))
14207 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14208 (setq tagsmatcher
14209 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14210 ;; Make the todo matcher
14211 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14212 (setq todomatcher t)
14213 (setq orterms (org-split-string todomatch "|") orlist nil)
14214 (while (setq term (pop orterms))
14215 (while (string-match re term)
14216 (setq minus (and (match-end 1)
14217 (equal (match-string 1 term) "-"))
14218 kwd (match-string 2 term)
14219 re-p (equal (string-to-char kwd) ?{)
14220 term (substring term (match-end 0))
14221 mm (if re-p
14222 `(string-match ,(substring kwd 1 -1) todo)
14223 (list 'equal 'todo kwd))
14224 mm (if minus (list 'not mm) mm))
14225 (push mm todomatcher))
14226 (push (if (> (length todomatcher) 1)
14227 (cons 'and todomatcher)
14228 (car todomatcher))
14229 orlist)
14230 (setq todomatcher nil))
14231 (setq todomatcher (if (> (length orlist) 1)
14232 (cons 'or orlist) (car orlist))))
14233
14234 ;; Return the string and lisp forms of the matcher
14235 (setq matcher (if todomatcher
14236 (list 'and tagsmatcher todomatcher)
14237 tagsmatcher))
14238 (when todo-only
14239 (setq matcher (list 'and '(member todo org-not-done-keywords)
14240 matcher)))
14241 (cons match0 matcher)))
14242
14243 (defun org-tags-expand (match &optional single-as-list downcased)
14244 "Expand group tags in MATCH.
14245
14246 This replaces every group tag in MATCH with a regexp tag search.
14247 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14248 will be replaced like this:
14249
14250 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14251 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14252 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14253
14254 Replacing by a regexp preserves the structure of the match.
14255 E.g., this expansion
14256
14257 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14258
14259 will match anything tagged with \"Lab\" and \"Home\", or tagged
14260 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14261
14262 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14263 assumed to be a single group tag, and the function will return
14264 the list of tags in this group.
14265
14266 When DOWNCASE is non-nil, expand downcased TAGS."
14267 (if org-group-tags
14268 (let* ((case-fold-search t)
14269 (stable org-mode-syntax-table)
14270 (tal (or org-tag-groups-alist-for-agenda
14271 org-tag-groups-alist))
14272 (tal (if downcased
14273 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14274 (tml (mapcar 'car tal))
14275 (rtnmatch match) rpl)
14276 ;; @ and _ are allowed as word-components in tags
14277 (modify-syntax-entry ?@ "w" stable)
14278 (modify-syntax-entry ?_ "w" stable)
14279 (while (and tml
14280 (with-syntax-table stable
14281 (string-match
14282 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14283 (regexp-opt tml) "\\>\\)") rtnmatch)))
14284 (let* ((dir (match-string 1 rtnmatch))
14285 (tag (match-string 2 rtnmatch))
14286 (tag (if downcased (downcase tag) tag)))
14287 (setq tml (delete tag tml))
14288 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14289 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14290 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14291 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14292 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14293 (if single-as-list
14294 (or (reverse rpl) (list rtnmatch))
14295 rtnmatch))
14296 (if single-as-list (list (if downcased (downcase match) match))
14297 match)))
14298
14299 (defun org-op-to-function (op &optional stringp)
14300 "Turn an operator into the appropriate function."
14301 (setq op
14302 (cond
14303 ((equal op "<" ) '(< string< org-time<))
14304 ((equal op ">" ) '(> org-string> org-time>))
14305 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14306 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14307 ((member op '("=" "==")) '(= string= org-time=))
14308 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14309 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14310
14311 (defun org<> (a b) (not (= a b)))
14312 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14313 (defun org-string>= (a b) (not (string< a b)))
14314 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14315 (defun org-string<> (a b) (not (string= a b)))
14316 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14317 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14318 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14319 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14320 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14321 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14322 (defun org-2ft (s)
14323 "Convert S to a floating point time.
14324 If S is already a number, just return it. If it is a string, parse
14325 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14326 (cond
14327 ((numberp s) s)
14328 ((stringp s)
14329 (condition-case nil
14330 (float-time (apply 'encode-time (org-parse-time-string s)))
14331 (error 0.)))
14332 (t 0.)))
14333
14334 (defun org-time-today ()
14335 "Time in seconds today at 0:00.
14336 Returns the float number of seconds since the beginning of the
14337 epoch to the beginning of today (00:00)."
14338 (float-time (apply 'encode-time
14339 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14340
14341 (defun org-matcher-time (s)
14342 "Interpret a time comparison value."
14343 (save-match-data
14344 (cond
14345 ((string= s "<now>") (float-time))
14346 ((string= s "<today>") (org-time-today))
14347 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14348 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14349 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14350 (+ (org-time-today)
14351 (* (string-to-number (match-string 1 s))
14352 (cdr (assoc (match-string 2 s)
14353 '(("d" . 86400.0) ("w" . 604800.0)
14354 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14355 (t (org-2ft s)))))
14356
14357 (defun org-match-any-p (re list)
14358 "Does re match any element of list?"
14359 (setq list (mapcar (lambda (x) (string-match re x)) list))
14360 (delq nil list))
14361
14362 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14363 (defvar org-tags-overlay (make-overlay 1 1))
14364 (org-detach-overlay org-tags-overlay)
14365
14366 (defun org-get-local-tags-at (&optional pos)
14367 "Get a list of tags defined in the current headline."
14368 (org-get-tags-at pos 'local))
14369
14370 (defun org-get-local-tags ()
14371 "Get a list of tags defined in the current headline."
14372 (org-get-tags-at nil 'local))
14373
14374 (defun org-get-tags-at (&optional pos local)
14375 "Get a list of all headline tags applicable at POS.
14376 POS defaults to point. If tags are inherited, the list contains
14377 the targets in the same sequence as the headlines appear, i.e.
14378 the tags of the current headline come last.
14379 When LOCAL is non-nil, only return tags from the current headline,
14380 ignore inherited ones."
14381 (interactive)
14382 (if (and org-trust-scanner-tags
14383 (or (not pos) (equal pos (point)))
14384 (not local))
14385 org-scanner-tags
14386 (let (tags ltags lastpos parent)
14387 (save-excursion
14388 (save-restriction
14389 (widen)
14390 (goto-char (or pos (point)))
14391 (save-match-data
14392 (catch 'done
14393 (condition-case nil
14394 (progn
14395 (org-back-to-heading t)
14396 (while (not (equal lastpos (point)))
14397 (setq lastpos (point))
14398 (when (looking-at
14399 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14400 (setq ltags (org-split-string
14401 (org-match-string-no-properties 1) ":"))
14402 (when parent
14403 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14404 (setq tags (append
14405 (if parent
14406 (org-remove-uninherited-tags ltags)
14407 ltags)
14408 tags)))
14409 (or org-use-tag-inheritance (throw 'done t))
14410 (if local (throw 'done t))
14411 (or (org-up-heading-safe) (error nil))
14412 (setq parent t)))
14413 (error nil)))))
14414 (if local
14415 tags
14416 (reverse (delete-dups
14417 (reverse (append
14418 (org-remove-uninherited-tags
14419 org-file-tags) tags)))))))))
14420
14421 (defun org-add-prop-inherited (s)
14422 (add-text-properties 0 (length s) '(inherited t) s)
14423 s)
14424
14425 (defun org-toggle-tag (tag &optional onoff)
14426 "Toggle the tag TAG for the current line.
14427 If ONOFF is `on' or `off', don't toggle but set to this state."
14428 (let (res current)
14429 (save-excursion
14430 (org-back-to-heading t)
14431 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14432 (point-at-eol) t)
14433 (progn
14434 (setq current (match-string 1))
14435 (replace-match ""))
14436 (setq current ""))
14437 (setq current (nreverse (org-split-string current ":")))
14438 (cond
14439 ((eq onoff 'on)
14440 (setq res t)
14441 (or (member tag current) (push tag current)))
14442 ((eq onoff 'off)
14443 (or (not (member tag current)) (setq current (delete tag current))))
14444 (t (if (member tag current)
14445 (setq current (delete tag current))
14446 (setq res t)
14447 (push tag current))))
14448 (end-of-line 1)
14449 (if current
14450 (progn
14451 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14452 (org-set-tags nil t))
14453 (delete-horizontal-space))
14454 (run-hooks 'org-after-tags-change-hook))
14455 res))
14456
14457 (defun org-align-tags-here (to-col)
14458 ;; Assumes that this is a headline
14459 "Align tags on the current headline to TO-COL."
14460 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14461 (beginning-of-line 1)
14462 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14463 (< pos (match-beginning 2)))
14464 (progn
14465 (setq tags-l (- (match-end 2) (match-beginning 2)))
14466 (goto-char (match-beginning 1))
14467 (insert " ")
14468 (delete-region (point) (1+ (match-beginning 2)))
14469 (setq ncol (max (current-column)
14470 (1+ col)
14471 (if (> to-col 0)
14472 to-col
14473 (- (abs to-col) tags-l))))
14474 (setq p (point))
14475 (insert (make-string (- ncol (current-column)) ?\ ))
14476 (setq ncol (current-column))
14477 (when indent-tabs-mode (tabify p (point-at-eol)))
14478 (org-move-to-column (min ncol col)))
14479 (goto-char pos))))
14480
14481 (defun org-set-tags-command (&optional arg just-align)
14482 "Call the set-tags command for the current entry."
14483 (interactive "P")
14484 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14485 (org-set-tags arg just-align)
14486 (save-excursion
14487 (unless (and (org-region-active-p)
14488 org-loop-over-headlines-in-active-region)
14489 (org-back-to-heading t))
14490 (org-set-tags arg just-align))))
14491
14492 (defun org-set-tags-to (data)
14493 "Set the tags of the current entry to DATA, replacing the current tags.
14494 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14495 If DATA is nil or the empty string, any tags will be removed."
14496 (interactive "sTags: ")
14497 (setq data
14498 (cond
14499 ((eq data nil) "")
14500 ((equal data "") "")
14501 ((stringp data)
14502 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14503 ":"))
14504 ((listp data)
14505 (concat ":" (mapconcat 'identity data ":") ":"))))
14506 (when data
14507 (save-excursion
14508 (org-back-to-heading t)
14509 (when (looking-at org-complex-heading-regexp)
14510 (if (match-end 5)
14511 (progn
14512 (goto-char (match-beginning 5))
14513 (insert data)
14514 (delete-region (point) (point-at-eol))
14515 (org-set-tags nil 'align))
14516 (goto-char (point-at-eol))
14517 (insert " " data)
14518 (org-set-tags nil 'align)))
14519 (beginning-of-line 1)
14520 (if (looking-at ".*?\\([ \t]+\\)$")
14521 (delete-region (match-beginning 1) (match-end 1))))))
14522
14523 (defun org-align-all-tags ()
14524 "Align the tags i all headings."
14525 (interactive)
14526 (save-excursion
14527 (or (ignore-errors (org-back-to-heading t))
14528 (outline-next-heading))
14529 (if (org-at-heading-p)
14530 (org-set-tags t)
14531 (message "No headings"))))
14532
14533 (defvar org-indent-indentation-per-level)
14534 (defun org-set-tags (&optional arg just-align)
14535 "Set the tags for the current headline.
14536 With prefix ARG, realign all tags in headings in the current buffer.
14537 When JUST-ALIGN is non-nil, only align tags."
14538 (interactive "P")
14539 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14540 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14541 'region-start-level 'region))
14542 org-loop-over-headlines-in-active-region)
14543 (org-map-entries
14544 ;; We don't use ARG and JUST-ALIGN here because these args
14545 ;; are not useful when looping over headlines.
14546 `(org-set-tags)
14547 org-loop-over-headlines-in-active-region
14548 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14549 (let* ((re org-outline-regexp-bol)
14550 (current (unless arg (org-get-tags-string)))
14551 (col (current-column))
14552 (org-setting-tags t)
14553 table current-tags inherited-tags ; computed below when needed
14554 tags p0 c0 c1 rpl di tc level)
14555 (if arg
14556 (save-excursion
14557 (goto-char (point-min))
14558 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14559 (while (re-search-forward re nil t)
14560 (org-set-tags nil t)
14561 (end-of-line 1)))
14562 (message "All tags realigned to column %d" org-tags-column))
14563 (if just-align
14564 (setq tags current)
14565 ;; Get a new set of tags from the user
14566 (save-excursion
14567 (setq table (append org-tag-persistent-alist
14568 (or org-tag-alist (org-get-buffer-tags))
14569 (and
14570 org-complete-tags-always-offer-all-agenda-tags
14571 (org-global-tags-completion-table
14572 (org-agenda-files))))
14573 org-last-tags-completion-table table
14574 current-tags (org-split-string current ":")
14575 inherited-tags (nreverse
14576 (nthcdr (length current-tags)
14577 (nreverse (org-get-tags-at))))
14578 tags
14579 (if (or (eq t org-use-fast-tag-selection)
14580 (and org-use-fast-tag-selection
14581 (delq nil (mapcar 'cdr table))))
14582 (org-fast-tag-selection
14583 current-tags inherited-tags table
14584 (if org-fast-tag-selection-include-todo
14585 org-todo-key-alist))
14586 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14587 (org-trim
14588 (org-icompleting-read "Tags: "
14589 'org-tags-completion-function
14590 nil nil current 'org-tags-history))))))
14591 (while (string-match "[-+&]+" tags)
14592 ;; No boolean logic, just a list
14593 (setq tags (replace-match ":" t t tags))))
14594
14595 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14596
14597 (if org-tags-sort-function
14598 (setq tags (mapconcat 'identity
14599 (sort (org-split-string
14600 tags (org-re "[^[:alnum:]_@#%]+"))
14601 org-tags-sort-function) ":")))
14602
14603 (if (string-match "\\`[\t ]*\\'" tags)
14604 (setq tags "")
14605 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14606 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14607
14608 ;; Insert new tags at the correct column
14609 (beginning-of-line 1)
14610 (setq level (or (and (looking-at org-outline-regexp)
14611 (- (match-end 0) (point) 1))
14612 1))
14613 (cond
14614 ((and (equal current "") (equal tags "")))
14615 ((re-search-forward
14616 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14617 (point-at-eol) t)
14618 (if (equal tags "")
14619 (setq rpl "")
14620 (goto-char (match-beginning 0))
14621 (setq c0 (current-column)
14622 ;; compute offset for the case of org-indent-mode active
14623 di (if (org-bound-and-true-p org-indent-mode)
14624 (* (1- org-indent-indentation-per-level) (1- level))
14625 0)
14626 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14627 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14628 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14629 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14630 (replace-match rpl t t)
14631 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14632 tags)
14633 (t (error "Tags alignment failed")))
14634 (org-move-to-column col)
14635 (unless just-align
14636 (run-hooks 'org-after-tags-change-hook))))))
14637
14638 (defun org-change-tag-in-region (beg end tag off)
14639 "Add or remove TAG for each entry in the region.
14640 This works in the agenda, and also in an org-mode buffer."
14641 (interactive
14642 (list (region-beginning) (region-end)
14643 (let ((org-last-tags-completion-table
14644 (if (derived-mode-p 'org-mode)
14645 (org-uniquify
14646 (delq nil (append (org-get-buffer-tags)
14647 (org-global-tags-completion-table))))
14648 (org-global-tags-completion-table))))
14649 (org-icompleting-read
14650 "Tag: " 'org-tags-completion-function nil nil nil
14651 'org-tags-history))
14652 (progn
14653 (message "[s]et or [r]emove? ")
14654 (equal (read-char-exclusive) ?r))))
14655 (if (fboundp 'deactivate-mark) (deactivate-mark))
14656 (let ((agendap (equal major-mode 'org-agenda-mode))
14657 l1 l2 m buf pos newhead (cnt 0))
14658 (goto-char end)
14659 (setq l2 (1- (org-current-line)))
14660 (goto-char beg)
14661 (setq l1 (org-current-line))
14662 (loop for l from l1 to l2 do
14663 (org-goto-line l)
14664 (setq m (get-text-property (point) 'org-hd-marker))
14665 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14666 (and agendap m))
14667 (setq buf (if agendap (marker-buffer m) (current-buffer))
14668 pos (if agendap m (point)))
14669 (with-current-buffer buf
14670 (save-excursion
14671 (save-restriction
14672 (goto-char pos)
14673 (setq cnt (1+ cnt))
14674 (org-toggle-tag tag (if off 'off 'on))
14675 (setq newhead (org-get-heading)))))
14676 (and agendap (org-agenda-change-all-lines newhead m))))
14677 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14678
14679 (defun org-tags-completion-function (string predicate &optional flag)
14680 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14681 (confirm (lambda (x) (stringp (car x)))))
14682 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14683 (setq s1 (match-string 1 string)
14684 s2 (match-string 2 string))
14685 (setq s1 "" s2 string))
14686 (cond
14687 ((eq flag nil)
14688 ;; try completion
14689 (setq rtn (try-completion s2 ctable confirm))
14690 (if (stringp rtn)
14691 (setq rtn
14692 (concat s1 s2 (substring rtn (length s2))
14693 (if (and org-add-colon-after-tag-completion
14694 (assoc rtn ctable))
14695 ":" ""))))
14696 rtn)
14697 ((eq flag t)
14698 ;; all-completions
14699 (all-completions s2 ctable confirm))
14700 ((eq flag 'lambda)
14701 ;; exact match?
14702 (assoc s2 ctable)))))
14703
14704 (defun org-fast-tag-insert (kwd tags face &optional end)
14705 "Insert KDW, and the TAGS, the latter with face FACE.
14706 Also insert END."
14707 (insert (format "%-12s" (concat kwd ":"))
14708 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14709 (or end "")))
14710
14711 (defun org-fast-tag-show-exit (flag)
14712 (save-excursion
14713 (org-goto-line 3)
14714 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14715 (replace-match ""))
14716 (when flag
14717 (end-of-line 1)
14718 (org-move-to-column (- (window-width) 19) t)
14719 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14720
14721 (defun org-set-current-tags-overlay (current prefix)
14722 "Add an overlay to CURRENT tag with PREFIX."
14723 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14724 (if (featurep 'xemacs)
14725 (org-overlay-display org-tags-overlay (concat prefix s)
14726 'secondary-selection)
14727 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14728 (org-overlay-display org-tags-overlay (concat prefix s)))))
14729
14730 (defvar org-last-tag-selection-key nil)
14731 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14732 "Fast tag selection with single keys.
14733 CURRENT is the current list of tags in the headline, INHERITED is the
14734 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14735 possibly with grouping information. TODO-TABLE is a similar table with
14736 TODO keywords, should these have keys assigned to them.
14737 If the keys are nil, a-z are automatically assigned.
14738 Returns the new tags string, or nil to not change the current settings."
14739 (let* ((fulltable (append table todo-table))
14740 (maxlen (apply 'max (mapcar
14741 (lambda (x)
14742 (if (stringp (car x)) (string-width (car x)) 0))
14743 fulltable)))
14744 (buf (current-buffer))
14745 (expert (eq org-fast-tag-selection-single-key 'expert))
14746 (buffer-tags nil)
14747 (fwidth (+ maxlen 3 1 3))
14748 (ncol (/ (- (window-width) 4) fwidth))
14749 (i-face 'org-done)
14750 (c-face 'org-todo)
14751 tg cnt e c char c1 c2 ntable tbl rtn
14752 ov-start ov-end ov-prefix
14753 (exit-after-next org-fast-tag-selection-single-key)
14754 (done-keywords org-done-keywords)
14755 groups ingroup)
14756 (save-excursion
14757 (beginning-of-line 1)
14758 (if (looking-at
14759 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14760 (setq ov-start (match-beginning 1)
14761 ov-end (match-end 1)
14762 ov-prefix "")
14763 (setq ov-start (1- (point-at-eol))
14764 ov-end (1+ ov-start))
14765 (skip-chars-forward "^\n\r")
14766 (setq ov-prefix
14767 (concat
14768 (buffer-substring (1- (point)) (point))
14769 (if (> (current-column) org-tags-column)
14770 " "
14771 (make-string (- org-tags-column (current-column)) ?\ ))))))
14772 (move-overlay org-tags-overlay ov-start ov-end)
14773 (save-window-excursion
14774 (if expert
14775 (set-buffer (get-buffer-create " *Org tags*"))
14776 (delete-other-windows)
14777 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14778 (org-switch-to-buffer-other-window " *Org tags*"))
14779 (erase-buffer)
14780 (org-set-local 'org-done-keywords done-keywords)
14781 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14782 (org-fast-tag-insert "Current" current c-face "\n\n")
14783 (org-fast-tag-show-exit exit-after-next)
14784 (org-set-current-tags-overlay current ov-prefix)
14785 (setq tbl fulltable char ?a cnt 0)
14786 (while (setq e (pop tbl))
14787 (cond
14788 ((equal (car e) :startgroup)
14789 (push '() groups) (setq ingroup t)
14790 (when (not (= cnt 0))
14791 (setq cnt 0)
14792 (insert "\n"))
14793 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14794 ((equal (car e) :endgroup)
14795 (setq ingroup nil cnt 0)
14796 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14797 ((equal e '(:newline))
14798 (when (not (= cnt 0))
14799 (setq cnt 0)
14800 (insert "\n")
14801 (setq e (car tbl))
14802 (while (equal (car tbl) '(:newline))
14803 (insert "\n")
14804 (setq tbl (cdr tbl)))))
14805 ((equal e '(:grouptags)) nil)
14806 (t
14807 (setq tg (copy-sequence (car e)) c2 nil)
14808 (if (cdr e)
14809 (setq c (cdr e))
14810 ;; automatically assign a character.
14811 (setq c1 (string-to-char
14812 (downcase (substring
14813 tg (if (= (string-to-char tg) ?@) 1 0)))))
14814 (if (or (rassoc c1 ntable) (rassoc c1 table))
14815 (while (or (rassoc char ntable) (rassoc char table))
14816 (setq char (1+ char)))
14817 (setq c2 c1))
14818 (setq c (or c2 char)))
14819 (if ingroup (push tg (car groups)))
14820 (setq tg (org-add-props tg nil 'face
14821 (cond
14822 ((not (assoc tg table))
14823 (org-get-todo-face tg))
14824 ((member tg current) c-face)
14825 ((member tg inherited) i-face))))
14826 (if (equal (caar tbl) :grouptags)
14827 (org-add-props tg nil 'face 'org-tag-group))
14828 (if (and (= cnt 0) (not ingroup)) (insert " "))
14829 (insert "[" c "] " tg (make-string
14830 (- fwidth 4 (length tg)) ?\ ))
14831 (push (cons tg c) ntable)
14832 (when (= (setq cnt (1+ cnt)) ncol)
14833 (insert "\n")
14834 (if ingroup (insert " "))
14835 (setq cnt 0)))))
14836 (setq ntable (nreverse ntable))
14837 (insert "\n")
14838 (goto-char (point-min))
14839 (if (not expert) (org-fit-window-to-buffer))
14840 (setq rtn
14841 (catch 'exit
14842 (while t
14843 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14844 (if (not groups) "no " "")
14845 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14846 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14847 (setq org-last-tag-selection-key c)
14848 (cond
14849 ((= c ?\r) (throw 'exit t))
14850 ((= c ?!)
14851 (setq groups (not groups))
14852 (goto-char (point-min))
14853 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14854 ((= c ?\C-c)
14855 (if (not expert)
14856 (org-fast-tag-show-exit
14857 (setq exit-after-next (not exit-after-next)))
14858 (setq expert nil)
14859 (delete-other-windows)
14860 (set-window-buffer (split-window-vertically) " *Org tags*")
14861 (org-switch-to-buffer-other-window " *Org tags*")
14862 (org-fit-window-to-buffer)))
14863 ((or (= c ?\C-g)
14864 (and (= c ?q) (not (rassoc c ntable))))
14865 (org-detach-overlay org-tags-overlay)
14866 (setq quit-flag t))
14867 ((= c ?\ )
14868 (setq current nil)
14869 (if exit-after-next (setq exit-after-next 'now)))
14870 ((= c ?\t)
14871 (condition-case nil
14872 (setq tg (org-icompleting-read
14873 "Tag: "
14874 (or buffer-tags
14875 (with-current-buffer buf
14876 (org-get-buffer-tags)))))
14877 (quit (setq tg "")))
14878 (when (string-match "\\S-" tg)
14879 (add-to-list 'buffer-tags (list tg))
14880 (if (member tg current)
14881 (setq current (delete tg current))
14882 (push tg current)))
14883 (if exit-after-next (setq exit-after-next 'now)))
14884 ((setq e (rassoc c todo-table) tg (car e))
14885 (with-current-buffer buf
14886 (save-excursion (org-todo tg)))
14887 (if exit-after-next (setq exit-after-next 'now)))
14888 ((setq e (rassoc c ntable) tg (car e))
14889 (if (member tg current)
14890 (setq current (delete tg current))
14891 (loop for g in groups do
14892 (if (member tg g)
14893 (mapc (lambda (x)
14894 (setq current (delete x current)))
14895 g)))
14896 (push tg current))
14897 (if exit-after-next (setq exit-after-next 'now))))
14898
14899 ;; Create a sorted list
14900 (setq current
14901 (sort current
14902 (lambda (a b)
14903 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14904 (if (eq exit-after-next 'now) (throw 'exit t))
14905 (goto-char (point-min))
14906 (beginning-of-line 2)
14907 (delete-region (point) (point-at-eol))
14908 (org-fast-tag-insert "Current" current c-face)
14909 (org-set-current-tags-overlay current ov-prefix)
14910 (while (re-search-forward
14911 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14912 (setq tg (match-string 1))
14913 (add-text-properties
14914 (match-beginning 1) (match-end 1)
14915 (list 'face
14916 (cond
14917 ((member tg current) c-face)
14918 ((member tg inherited) i-face)
14919 (t (get-text-property (match-beginning 1) 'face))))))
14920 (goto-char (point-min)))))
14921 (org-detach-overlay org-tags-overlay)
14922 (if rtn
14923 (mapconcat 'identity current ":")
14924 nil))))
14925
14926 (defun org-get-tags-string ()
14927 "Get the TAGS string in the current headline."
14928 (unless (org-at-heading-p t)
14929 (user-error "Not on a heading"))
14930 (save-excursion
14931 (beginning-of-line 1)
14932 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14933 (org-match-string-no-properties 1)
14934 "")))
14935
14936 (defun org-get-tags ()
14937 "Get the list of tags specified in the current headline."
14938 (org-split-string (org-get-tags-string) ":"))
14939
14940 (defun org-get-buffer-tags ()
14941 "Get a table of all tags used in the buffer, for completion."
14942 (let (tags)
14943 (save-excursion
14944 (goto-char (point-min))
14945 (while (re-search-forward
14946 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14947 (when (equal (char-after (point-at-bol 0)) ?*)
14948 (mapc (lambda (x) (add-to-list 'tags x))
14949 (org-split-string (org-match-string-no-properties 1) ":")))))
14950 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14951 (mapcar 'list tags)))
14952
14953 ;;;; The mapping API
14954
14955 (defun org-map-entries (func &optional match scope &rest skip)
14956 "Call FUNC at each headline selected by MATCH in SCOPE.
14957
14958 FUNC is a function or a lisp form. The function will be called without
14959 arguments, with the cursor positioned at the beginning of the headline.
14960 The return values of all calls to the function will be collected and
14961 returned as a list.
14962
14963 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14964 does not need to preserve point. After evaluation, the cursor will be
14965 moved to the end of the line (presumably of the headline of the
14966 processed entry) and search continues from there. Under some
14967 circumstances, this may not produce the wanted results. For example,
14968 if you have removed (e.g. archived) the current (sub)tree it could
14969 mean that the next entry will be skipped entirely. In such cases, you
14970 can specify the position from where search should continue by making
14971 FUNC set the variable `org-map-continue-from' to the desired buffer
14972 position.
14973
14974 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14975 Only headlines that are matched by this query will be considered during
14976 the iteration. When MATCH is nil or t, all headlines will be
14977 visited by the iteration.
14978
14979 SCOPE determines the scope of this command. It can be any of:
14980
14981 nil The current buffer, respecting the restriction if any
14982 tree The subtree started with the entry at point
14983 region The entries within the active region, if any
14984 region-start-level
14985 The entries within the active region, but only those at
14986 the same level than the first one.
14987 file The current buffer, without restriction
14988 file-with-archives
14989 The current buffer, and any archives associated with it
14990 agenda All agenda files
14991 agenda-with-archives
14992 All agenda files with any archive files associated with them
14993 \(file1 file2 ...)
14994 If this is a list, all files in the list will be scanned
14995
14996 The remaining args are treated as settings for the skipping facilities of
14997 the scanner. The following items can be given here:
14998
14999 archive skip trees with the archive tag
15000 comment skip trees with the COMMENT keyword
15001 function or Emacs Lisp form:
15002 will be used as value for `org-agenda-skip-function', so
15003 whenever the function returns a position, FUNC will not be
15004 called for that entry and search will continue from the
15005 position returned
15006
15007 If your function needs to retrieve the tags including inherited tags
15008 at the *current* entry, you can use the value of the variable
15009 `org-scanner-tags' which will be much faster than getting the value
15010 with `org-get-tags-at'. If your function gets properties with
15011 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15012 to t around the call to `org-entry-properties' to get the same speedup.
15013 Note that if your function moves around to retrieve tags and properties at
15014 a *different* entry, you cannot use these techniques."
15015 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15016 (not (org-region-active-p)))
15017 (let* ((org-agenda-archives-mode nil) ; just to make sure
15018 (org-agenda-skip-archived-trees (memq 'archive skip))
15019 (org-agenda-skip-comment-trees (memq 'comment skip))
15020 (org-agenda-skip-function
15021 (car (org-delete-all '(comment archive) skip)))
15022 (org-tags-match-list-sublevels t)
15023 (start-level (eq scope 'region-start-level))
15024 matcher file res
15025 org-todo-keywords-for-agenda
15026 org-done-keywords-for-agenda
15027 org-todo-keyword-alist-for-agenda
15028 org-drawers-for-agenda
15029 org-tag-alist-for-agenda
15030 todo-only)
15031
15032 (cond
15033 ((eq match t) (setq matcher t))
15034 ((eq match nil) (setq matcher t))
15035 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15036
15037 (save-excursion
15038 (save-restriction
15039 (cond ((eq scope 'tree)
15040 (org-back-to-heading t)
15041 (org-narrow-to-subtree)
15042 (setq scope nil))
15043 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15044 (org-region-active-p))
15045 ;; If needed, set start-level to a string like "2"
15046 (when start-level
15047 (save-excursion
15048 (goto-char (region-beginning))
15049 (unless (org-at-heading-p) (outline-next-heading))
15050 (setq start-level (org-current-level))))
15051 (narrow-to-region (region-beginning)
15052 (save-excursion
15053 (goto-char (region-end))
15054 (unless (and (bolp) (org-at-heading-p))
15055 (outline-next-heading))
15056 (point)))
15057 (setq scope nil)))
15058
15059 (if (not scope)
15060 (progn
15061 (org-agenda-prepare-buffers
15062 (list (buffer-file-name (current-buffer))))
15063 (setq res (org-scan-tags func matcher todo-only start-level)))
15064 ;; Get the right scope
15065 (cond
15066 ((and scope (listp scope) (symbolp (car scope)))
15067 (setq scope (eval scope)))
15068 ((eq scope 'agenda)
15069 (setq scope (org-agenda-files t)))
15070 ((eq scope 'agenda-with-archives)
15071 (setq scope (org-agenda-files t))
15072 (setq scope (org-add-archive-files scope)))
15073 ((eq scope 'file)
15074 (setq scope (list (buffer-file-name))))
15075 ((eq scope 'file-with-archives)
15076 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15077 (org-agenda-prepare-buffers scope)
15078 (while (setq file (pop scope))
15079 (with-current-buffer (org-find-base-buffer-visiting file)
15080 (save-excursion
15081 (save-restriction
15082 (widen)
15083 (goto-char (point-min))
15084 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15085 res)))
15086
15087 ;;;; Properties
15088
15089 ;;; Setting and retrieving properties
15090
15091 (defconst org-special-properties
15092 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15093 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15094 "The special properties valid in Org-mode.
15095
15096 These are properties that are not defined in the property drawer,
15097 but in some other way.")
15098
15099 (defconst org-default-properties
15100 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15101 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15102 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15103 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15104 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15105 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15106 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15107 "Some properties that are used by Org-mode for various purposes.
15108 Being in this list makes sure that they are offered for completion.")
15109
15110 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15111 "Regular expression matching the first line of a property drawer.")
15112
15113 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15114 "Regular expression matching the last line of a property drawer.")
15115
15116 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15117 "Regular expression matching the first line of a property drawer.")
15118
15119 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15120 "Regular expression matching the first line of a property drawer.")
15121
15122 (defconst org-property-drawer-re
15123 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15124 org-property-end-re "\\)\n?")
15125 "Matches an entire property drawer.")
15126
15127 (defconst org-clock-drawer-re
15128 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15129 org-property-end-re "\\)\n?")
15130 "Matches an entire clock drawer.")
15131
15132 (defun org-property-action ()
15133 "Do an action on properties."
15134 (interactive)
15135 (let (c)
15136 (org-at-property-p)
15137 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15138 (setq c (read-char-exclusive))
15139 (cond
15140 ((equal c ?s)
15141 (call-interactively 'org-set-property))
15142 ((equal c ?d)
15143 (call-interactively 'org-delete-property))
15144 ((equal c ?D)
15145 (call-interactively 'org-delete-property-globally))
15146 ((equal c ?c)
15147 (call-interactively 'org-compute-property-at-point))
15148 (t (user-error "No such property action %c" c)))))
15149
15150 (defun org-inc-effort ()
15151 "Increment the value of the effort property in the current entry."
15152 (interactive)
15153 (org-set-effort nil t))
15154
15155 (defvar org-clock-effort) ;; Defined in org-clock.el
15156 (defvar org-clock-current-task) ;; Defined in org-clock.el
15157 (defun org-set-effort (&optional value increment)
15158 "Set the effort property of the current entry.
15159 With numerical prefix arg, use the nth allowed value, 0 stands for the
15160 10th allowed value.
15161
15162 When INCREMENT is non-nil, set the property to the next allowed value."
15163 (interactive "P")
15164 (if (equal value 0) (setq value 10))
15165 (let* ((completion-ignore-case t)
15166 (prop org-effort-property)
15167 (cur (org-entry-get nil prop))
15168 (allowed (org-property-get-allowed-values nil prop 'table))
15169 (existing (mapcar 'list (org-property-values prop)))
15170 (heading (nth 4 (org-heading-components)))
15171 rpl
15172 (val (cond
15173 ((stringp value) value)
15174 ((and allowed (integerp value))
15175 (or (car (nth (1- value) allowed))
15176 (car (org-last allowed))))
15177 ((and allowed increment)
15178 (or (caadr (member (list cur) allowed))
15179 (user-error "Allowed effort values are not set")))
15180 (allowed
15181 (message "Select 1-9,0, [RET%s]: %s"
15182 (if cur (concat "=" cur) "")
15183 (mapconcat 'car allowed " "))
15184 (setq rpl (read-char-exclusive))
15185 (if (equal rpl ?\r)
15186 cur
15187 (setq rpl (- rpl ?0))
15188 (if (equal rpl 0) (setq rpl 10))
15189 (if (and (> rpl 0) (<= rpl (length allowed)))
15190 (car (nth (1- rpl) allowed))
15191 (org-completing-read "Effort: " allowed nil))))
15192 (t
15193 (let (org-completion-use-ido org-completion-use-iswitchb)
15194 (org-completing-read
15195 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15196 (concat "[" cur "]") "")
15197 ": ")
15198 existing nil nil "" nil cur))))))
15199 (unless (equal (org-entry-get nil prop) val)
15200 (org-entry-put nil prop val))
15201 (save-excursion
15202 (org-back-to-heading t)
15203 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15204 (when (string= heading org-clock-current-task)
15205 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15206 (org-clock-update-mode-line))
15207 (message "%s is now %s" prop val)))
15208
15209 (defun org-at-property-p ()
15210 "Is cursor inside a property drawer?"
15211 (save-excursion
15212 (when (equal 'node-property (car (org-element-at-point)))
15213 (beginning-of-line 1)
15214 (looking-at org-property-re))))
15215
15216 (defun org-get-property-block (&optional beg end force)
15217 "Return the (beg . end) range of the body of the property drawer.
15218 BEG and END are the beginning and end of the current subtree, or of
15219 the part before the first headline. If they are not given, they will
15220 be found. If the drawer does not exist and FORCE is non-nil, create
15221 the drawer."
15222 (catch 'exit
15223 (save-excursion
15224 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15225 (progn (org-back-to-heading t) (point))))
15226 (end (or end (and (not (outline-next-heading)) (point-max))
15227 (point))))
15228 (goto-char beg)
15229 (if (re-search-forward org-property-start-re end t)
15230 (setq beg (1+ (match-end 0)))
15231 (if force
15232 (save-excursion
15233 (org-insert-property-drawer)
15234 (setq end (progn (outline-next-heading) (point))))
15235 (throw 'exit nil))
15236 (goto-char beg)
15237 (if (re-search-forward org-property-start-re end t)
15238 (setq beg (1+ (match-end 0)))))
15239 (if (re-search-forward org-property-end-re end t)
15240 (setq end (match-beginning 0))
15241 (or force (throw 'exit nil))
15242 (goto-char beg)
15243 (setq end beg)
15244 (org-indent-line)
15245 (insert ":END:\n"))
15246 (cons beg end)))))
15247
15248 (defun org-entry-properties (&optional pom which specific)
15249 "Get all properties of the entry at point-or-marker POM.
15250 This includes the TODO keyword, the tags, time strings for deadline,
15251 scheduled, and clocking, and any additional properties defined in the
15252 entry. The return value is an alist, keys may occur multiple times
15253 if the property key was used several times.
15254 POM may also be nil, in which case the current entry is used.
15255 If WHICH is nil or `all', get all properties. If WHICH is
15256 `special' or `standard', only get that subclass. If WHICH
15257 is a string only get exactly this property. SPECIFIC can be a string, the
15258 specific property we are interested in. Specifying it can speed
15259 things up because then unnecessary parsing is avoided."
15260 (setq which (or which 'all))
15261 (org-with-wide-buffer
15262 (org-with-point-at pom
15263 (let ((clockstr (substring org-clock-string 0 -1))
15264 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15265 (case-fold-search nil)
15266 beg end range props sum-props key key1 value string clocksum clocksumt)
15267 (when (and (derived-mode-p 'org-mode)
15268 (ignore-errors (org-back-to-heading t)))
15269 (setq beg (point))
15270 (setq sum-props (get-text-property (point) 'org-summaries))
15271 (setq clocksum (get-text-property (point) :org-clock-minutes)
15272 clocksumt (get-text-property (point) :org-clock-minutes-today))
15273 (outline-next-heading)
15274 (setq end (point))
15275 (when (memq which '(all special))
15276 ;; Get the special properties, like TODO and tags
15277 (goto-char beg)
15278 (when (and (or (not specific) (string= specific "TODO"))
15279 (looking-at org-todo-line-regexp) (match-end 2))
15280 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15281 (when (and (or (not specific) (string= specific "PRIORITY"))
15282 (looking-at org-priority-regexp))
15283 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15284 (when (or (not specific) (string= specific "FILE"))
15285 (push (cons "FILE" buffer-file-name) props))
15286 (when (and (or (not specific) (string= specific "TAGS"))
15287 (setq value (org-get-tags-string))
15288 (string-match "\\S-" value))
15289 (push (cons "TAGS" value) props))
15290 (when (and (or (not specific) (string= specific "ALLTAGS"))
15291 (setq value (org-get-tags-at)))
15292 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15293 ":"))
15294 props))
15295 (when (or (not specific) (string= specific "BLOCKED"))
15296 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15297 (when (or (not specific)
15298 (member specific
15299 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15300 "TIMESTAMP" "TIMESTAMP_IA")))
15301 (catch 'match
15302 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15303 (not (text-property-any 0 (length (match-string 0))
15304 'face 'font-lock-comment-face
15305 (match-string 0))))
15306 (setq key (if (match-end 1)
15307 (substring (org-match-string-no-properties 1)
15308 0 -1))
15309 string (if (equal key clockstr)
15310 (org-trim
15311 (buffer-substring-no-properties
15312 (match-beginning 3) (goto-char
15313 (point-at-eol))))
15314 (substring (org-match-string-no-properties 3)
15315 1 -1)))
15316 ;; Get the correct property name from the key. This is
15317 ;; necessary if the user has configured time keywords.
15318 (setq key1 (concat key ":"))
15319 (cond
15320 ((not key)
15321 (setq key
15322 (if (= (char-after (match-beginning 3)) ?\[)
15323 "TIMESTAMP_IA" "TIMESTAMP")))
15324 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15325 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15326 ((equal key1 org-closed-string) (setq key "CLOSED"))
15327 ((equal key1 org-clock-string) (setq key "CLOCK")))
15328 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15329 (progn
15330 (push (cons key string) props)
15331 ;; no need to search further if match is found
15332 (throw 'match t))
15333 (when (or (equal key "CLOCK") (not (assoc key props)))
15334 (push (cons key string) props)))))))
15335
15336 (when (memq which '(all standard))
15337 ;; Get the standard properties, like :PROP: ...
15338 (setq range (org-get-property-block beg end))
15339 (when range
15340 (goto-char (car range))
15341 (while (re-search-forward org-property-re
15342 (cdr range) t)
15343 (setq key (org-match-string-no-properties 2)
15344 value (org-trim (or (org-match-string-no-properties 3) "")))
15345 (unless (member key excluded)
15346 (push (cons key (or value "")) props)))))
15347 (if clocksum
15348 (push (cons "CLOCKSUM"
15349 (org-columns-number-to-string (/ (float clocksum) 60.)
15350 'add_times))
15351 props))
15352 (if clocksumt
15353 (push (cons "CLOCKSUM_T"
15354 (org-columns-number-to-string (/ (float clocksumt) 60.)
15355 'add_times))
15356 props))
15357 (unless (assoc "CATEGORY" props)
15358 (push (cons "CATEGORY" (org-get-category)) props))
15359 (append sum-props (nreverse props)))))))
15360
15361 (defun org-entry-get (pom property &optional inherit literal-nil)
15362 "Get value of PROPERTY for entry or content at point-or-marker POM.
15363 If INHERIT is non-nil and the entry does not have the property,
15364 then also check higher levels of the hierarchy.
15365 If INHERIT is the symbol `selective', use inheritance only if the setting
15366 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15367 If the property is present but empty, the return value is the empty string.
15368 If the property is not present at all, nil is returned.
15369
15370 Return the value as a string.
15371
15372 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15373 do not interpret it as the list atom nil. This is used for inheritance
15374 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15375 (org-with-point-at pom
15376 (if (and inherit (if (eq inherit 'selective)
15377 (org-property-inherit-p property)
15378 t))
15379 (org-entry-get-with-inheritance property literal-nil)
15380 (if (member property org-special-properties)
15381 ;; We need a special property. Use `org-entry-properties'
15382 ;; to retrieve it, but specify the wanted property
15383 (cdr (assoc property (org-entry-properties nil 'special property)))
15384 (org-with-wide-buffer
15385 (let ((range (org-get-property-block)))
15386 (when (and range (not (eq (car range) (cdr range)))
15387 (save-excursion
15388 (goto-char (car range))
15389 (re-search-forward
15390 (concat (org-re-property property) "\\|"
15391 (org-re-property (concat property "+")))
15392 (cdr range) t)))
15393 (let* ((props
15394 (list (or (assoc property org-file-properties)
15395 (assoc property org-global-properties)
15396 (assoc property org-global-properties-fixed))))
15397 (ap (lambda (key)
15398 (when (re-search-forward
15399 (org-re-property key) (cdr range) t)
15400 (setq props
15401 (org-update-property-plist
15402 key
15403 (if (match-end 3)
15404 (org-match-string-no-properties 3) "")
15405 props)))))
15406 val)
15407 (goto-char (car range))
15408 (funcall ap property)
15409 (goto-char (car range))
15410 (while (funcall ap (concat property "+")))
15411 (setq val (cdr (assoc property props)))
15412 (when val (if literal-nil val (org-not-nil val)))))))))))
15413
15414 (defun org-property-or-variable-value (var &optional inherit)
15415 "Check if there is a property fixing the value of VAR.
15416 If yes, return this value. If not, return the current value of the variable."
15417 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15418 (if (and prop (stringp prop) (string-match "\\S-" prop))
15419 (read prop)
15420 (symbol-value var))))
15421
15422 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15423 "Delete the property PROPERTY from entry at point-or-marker POM.
15424 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15425 an empty drawer to delete."
15426 (org-with-point-at pom
15427 (if (member property org-special-properties)
15428 nil ; cannot delete these properties.
15429 (let ((range (org-get-property-block)))
15430 (if (and range
15431 (goto-char (car range))
15432 (re-search-forward
15433 (org-re-property property nil t)
15434 (cdr range) t))
15435 (progn
15436 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15437 (and delete-empty-drawer
15438 (org-remove-empty-drawer-at
15439 delete-empty-drawer (car range)))
15440 t)
15441 nil)))))
15442
15443 ;; Multi-values properties are properties that contain multiple values
15444 ;; These values are assumed to be single words, separated by whitespace.
15445 (defun org-entry-add-to-multivalued-property (pom property value)
15446 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15447 (let* ((old (org-entry-get pom property))
15448 (values (and old (org-split-string old "[ \t]"))))
15449 (setq value (org-entry-protect-space value))
15450 (unless (member value values)
15451 (setq values (append values (list value)))
15452 (org-entry-put pom property
15453 (mapconcat 'identity values " ")))))
15454
15455 (defun org-entry-remove-from-multivalued-property (pom property value)
15456 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15457 (let* ((old (org-entry-get pom property))
15458 (values (and old (org-split-string old "[ \t]"))))
15459 (setq value (org-entry-protect-space value))
15460 (when (member value values)
15461 (setq values (delete value values))
15462 (org-entry-put pom property
15463 (mapconcat 'identity values " ")))))
15464
15465 (defun org-entry-member-in-multivalued-property (pom property value)
15466 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15467 (let* ((old (org-entry-get pom property))
15468 (values (and old (org-split-string old "[ \t]"))))
15469 (setq value (org-entry-protect-space value))
15470 (member value values)))
15471
15472 (defun org-entry-get-multivalued-property (pom property)
15473 "Return a list of values in a multivalued property."
15474 (let* ((value (org-entry-get pom property))
15475 (values (and value (org-split-string value "[ \t]"))))
15476 (mapcar 'org-entry-restore-space values)))
15477
15478 (defun org-entry-put-multivalued-property (pom property &rest values)
15479 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15480 VALUES should be a list of strings. Spaces will be protected."
15481 (org-entry-put pom property
15482 (mapconcat 'org-entry-protect-space values " "))
15483 (let* ((value (org-entry-get pom property))
15484 (values (and value (org-split-string value "[ \t]"))))
15485 (mapcar 'org-entry-restore-space values)))
15486
15487 (defun org-entry-protect-space (s)
15488 "Protect spaces and newline in string S."
15489 (while (string-match " " s)
15490 (setq s (replace-match "%20" t t s)))
15491 (while (string-match "\n" s)
15492 (setq s (replace-match "%0A" t t s)))
15493 s)
15494
15495 (defun org-entry-restore-space (s)
15496 "Restore spaces and newline in string S."
15497 (while (string-match "%20" s)
15498 (setq s (replace-match " " t t s)))
15499 (while (string-match "%0A" s)
15500 (setq s (replace-match "\n" t t s)))
15501 s)
15502
15503 (defvar org-entry-property-inherited-from (make-marker)
15504 "Marker pointing to the entry from where a property was inherited.
15505 Each call to `org-entry-get-with-inheritance' will set this marker to the
15506 location of the entry where the inheritance search matched. If there was
15507 no match, the marker will point nowhere.
15508 Note that also `org-entry-get' calls this function, if the INHERIT flag
15509 is set.")
15510
15511 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15512 "Get PROPERTY of entry or content at point, search higher levels if needed.
15513 The search will stop at the first ancestor which has the property defined.
15514 If the value found is \"nil\", return nil to show that the property
15515 should be considered as undefined (this is the meaning of nil here).
15516 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15517 (move-marker org-entry-property-inherited-from nil)
15518 (let (tmp)
15519 (save-excursion
15520 (save-restriction
15521 (widen)
15522 (catch 'ex
15523 (while t
15524 (when (setq tmp (org-entry-get nil property nil literal-nil))
15525 (or (ignore-errors (org-back-to-heading t))
15526 (goto-char (point-min)))
15527 (move-marker org-entry-property-inherited-from (point))
15528 (throw 'ex tmp))
15529 (or (ignore-errors (org-up-heading-safe))
15530 (throw 'ex nil))))))
15531 (setq tmp (or tmp
15532 (cdr (assoc property org-file-properties))
15533 (cdr (assoc property org-global-properties))
15534 (cdr (assoc property org-global-properties-fixed))))
15535 (if literal-nil tmp (org-not-nil tmp))))
15536
15537 (defvar org-property-changed-functions nil
15538 "Hook called when the value of a property has changed.
15539 Each hook function should accept two arguments, the name of the property
15540 and the new value.")
15541
15542 (defun org-entry-put (pom property value)
15543 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15544 If the value is `nil', it is converted to the empty string.
15545 If it is not a string, an error is raised."
15546 (cond ((null value) (setq value ""))
15547 ((not (stringp value))
15548 (error "Properties values should be strings.")))
15549 (org-with-point-at pom
15550 (org-back-to-heading t)
15551 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15552 range)
15553 (cond
15554 ((equal property "TODO")
15555 (when (and (string-match "\\S-" value)
15556 (not (member value org-todo-keywords-1)))
15557 (user-error "\"%s\" is not a valid TODO state" value))
15558 (if (or (not value)
15559 (not (string-match "\\S-" value)))
15560 (setq value 'none))
15561 (org-todo value)
15562 (org-set-tags nil 'align))
15563 ((equal property "PRIORITY")
15564 (org-priority (if (and value (string-match "\\S-" value))
15565 (string-to-char value) ?\ ))
15566 (org-set-tags nil 'align))
15567 ((equal property "CLOCKSUM")
15568 (if (not (re-search-forward
15569 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15570 (error "Cannot find a clock log")
15571 (goto-char (- (match-end 1) 2))
15572 (cond
15573 ((eq value 'earlier) (org-timestamp-down))
15574 ((eq value 'later) (org-timestamp-up)))
15575 (org-clock-sum-current-item)))
15576 ((equal property "SCHEDULED")
15577 (if (re-search-forward org-scheduled-time-regexp end t)
15578 (cond
15579 ((eq value 'earlier) (org-timestamp-change -1 'day))
15580 ((eq value 'later) (org-timestamp-change 1 'day))
15581 (t (call-interactively 'org-schedule)))
15582 (call-interactively 'org-schedule)))
15583 ((equal property "DEADLINE")
15584 (if (re-search-forward org-deadline-time-regexp end t)
15585 (cond
15586 ((eq value 'earlier) (org-timestamp-change -1 'day))
15587 ((eq value 'later) (org-timestamp-change 1 'day))
15588 (t (call-interactively 'org-deadline)))
15589 (call-interactively 'org-deadline)))
15590 ((member property org-special-properties)
15591 (error "The %s property can not yet be set with `org-entry-put'"
15592 property))
15593 (t ; a non-special property
15594 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15595 (setq range (org-get-property-block beg end 'force))
15596 (goto-char (car range))
15597 (if (re-search-forward
15598 (org-re-property property nil t) (cdr range) t)
15599 (progn
15600 (delete-region (match-beginning 0) (match-end 0))
15601 (goto-char (match-beginning 0)))
15602 (goto-char (cdr range))
15603 (insert "\n")
15604 (backward-char 1)
15605 (org-indent-line))
15606 (insert ":" property ":")
15607 (and value (insert " " value))
15608 (org-indent-line)))))
15609 (run-hook-with-args 'org-property-changed-functions property value)))
15610
15611 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15612 "Get all property keys in the current buffer.
15613 With INCLUDE-SPECIALS, also list the special properties that reflect things
15614 like tags and TODO state.
15615 With INCLUDE-DEFAULTS, also include properties that has special meaning
15616 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15617 and others.
15618 With INCLUDE-COLUMNS, also include property names given in COLUMN
15619 formats in the current buffer."
15620 (let (rtn range cfmt s p)
15621 (save-excursion
15622 (save-restriction
15623 (widen)
15624 (goto-char (point-min))
15625 (while (re-search-forward org-property-start-re nil t)
15626 (setq range (org-get-property-block))
15627 (goto-char (car range))
15628 (while (re-search-forward org-property-re
15629 (cdr range) t)
15630 (add-to-list 'rtn (org-match-string-no-properties 2)))
15631 (outline-next-heading))))
15632
15633 (when include-specials
15634 (setq rtn (append org-special-properties rtn)))
15635
15636 (when include-defaults
15637 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15638 (add-to-list 'rtn org-effort-property))
15639
15640 (when include-columns
15641 (save-excursion
15642 (save-restriction
15643 (widen)
15644 (goto-char (point-min))
15645 (while (re-search-forward
15646 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15647 nil t)
15648 (setq cfmt (match-string 2) s 0)
15649 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15650 cfmt s)
15651 (setq s (match-end 0)
15652 p (match-string 1 cfmt))
15653 (unless (or (equal p "ITEM")
15654 (member p org-special-properties))
15655 (add-to-list 'rtn (match-string 1 cfmt))))))))
15656
15657 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15658
15659 (defun org-property-values (key)
15660 "Return a list of all values of property KEY in the current buffer."
15661 (save-excursion
15662 (save-restriction
15663 (widen)
15664 (goto-char (point-min))
15665 (let ((re (org-re-property key))
15666 values)
15667 (while (re-search-forward re nil t)
15668 (add-to-list 'values (org-trim (match-string 3))))
15669 (delete "" values)))))
15670
15671 (defun org-insert-property-drawer ()
15672 "Insert a property drawer into the current entry."
15673 (org-back-to-heading t)
15674 (looking-at org-outline-regexp)
15675 (let ((indent (if org-adapt-indentation
15676 (- (match-end 0) (match-beginning 0))
15677 0))
15678 (beg (point))
15679 (re (concat "^[ \t]*" org-keyword-time-regexp))
15680 end hiddenp)
15681 (outline-next-heading)
15682 (setq end (point))
15683 (goto-char beg)
15684 (while (re-search-forward re end t))
15685 (setq hiddenp (outline-invisible-p))
15686 (end-of-line 1)
15687 (and (equal (char-after) ?\n) (forward-char 1))
15688 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15689 (if (member (match-string 1) '("CLOCK:" ":END:"))
15690 ;; just skip this line
15691 (beginning-of-line 2)
15692 ;; Drawer start, find the end
15693 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15694 (beginning-of-line 1)))
15695 (org-skip-over-state-notes)
15696 (skip-chars-backward " \t\n\r")
15697 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15698 (forward-char 1))
15699 (goto-char (point-at-eol))
15700 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15701 (beginning-of-line 0)
15702 (org-indent-to-column indent)
15703 (beginning-of-line 2)
15704 (org-indent-to-column indent)
15705 (beginning-of-line 0)
15706 (if hiddenp
15707 (save-excursion
15708 (org-back-to-heading t)
15709 (hide-entry))
15710 (org-flag-drawer t))))
15711
15712 (defun org-insert-drawer (&optional arg drawer)
15713 "Insert a drawer at point.
15714
15715 Optional argument DRAWER, when non-nil, is a string representing
15716 drawer's name. Otherwise, the user is prompted for a name.
15717
15718 If a region is active, insert the drawer around that region
15719 instead.
15720
15721 Point is left between drawer's boundaries."
15722 (interactive "P")
15723 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15724 "LOGBOOK"))
15725 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15726 ;; internally by Org. They are meant to be inserted
15727 ;; automatically.
15728 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15729 ;; Remove system drawers from list. Note: For some reason,
15730 ;; `org-completing-read' ignores the predicate while
15731 ;; `completing-read' handles it fine.
15732 (drawer (if arg "PROPERTIES"
15733 (or drawer
15734 (completing-read
15735 "Drawer: " org-drawers
15736 (lambda (d) (not (member d system-drawers))))))))
15737 (cond
15738 ;; With C-u, fall back on `org-insert-property-drawer'
15739 (arg (org-insert-property-drawer))
15740 ;; With an active region, insert a drawer at point.
15741 ((not (org-region-active-p))
15742 (progn
15743 (unless (bolp) (insert "\n"))
15744 (insert (format ":%s:\n\n:END:\n" drawer))
15745 (forward-line -2)))
15746 ;; Otherwise, insert the drawer at point
15747 (t
15748 (let ((rbeg (region-beginning))
15749 (rend (copy-marker (region-end))))
15750 (unwind-protect
15751 (progn
15752 (goto-char rbeg)
15753 (beginning-of-line)
15754 (when (save-excursion
15755 (re-search-forward org-outline-regexp-bol rend t))
15756 (user-error "Drawers cannot contain headlines"))
15757 ;; Position point at the beginning of the first
15758 ;; non-blank line in region. Insert drawer's opening
15759 ;; there, then indent it.
15760 (org-skip-whitespace)
15761 (beginning-of-line)
15762 (insert ":" drawer ":\n")
15763 (forward-line -1)
15764 (indent-for-tab-command)
15765 ;; Move point to the beginning of the first blank line
15766 ;; after the last non-blank line in region. Insert
15767 ;; drawer's closing, then indent it.
15768 (goto-char rend)
15769 (skip-chars-backward " \r\t\n")
15770 (insert "\n:END:")
15771 (deactivate-mark t)
15772 (indent-for-tab-command)
15773 (unless (eolp) (insert "\n")))
15774 ;; Clear marker, whatever the outcome of insertion is.
15775 (set-marker rend nil)))))))
15776
15777 (defvar org-property-set-functions-alist nil
15778 "Property set function alist.
15779 Each entry should have the following format:
15780
15781 (PROPERTY . READ-FUNCTION)
15782
15783 The read function will be called with the same argument as
15784 `org-completing-read'.")
15785
15786 (defun org-set-property-function (property)
15787 "Get the function that should be used to set PROPERTY.
15788 This is computed according to `org-property-set-functions-alist'."
15789 (or (cdr (assoc property org-property-set-functions-alist))
15790 'org-completing-read))
15791
15792 (defun org-read-property-value (property)
15793 "Read PROPERTY value from user."
15794 (let* ((completion-ignore-case t)
15795 (allowed (org-property-get-allowed-values nil property 'table))
15796 (cur (org-entry-get nil property))
15797 (prompt (concat property " value"
15798 (if (and cur (string-match "\\S-" cur))
15799 (concat " [" cur "]") "") ": "))
15800 (set-function (org-set-property-function property))
15801 (val (if allowed
15802 (funcall set-function prompt allowed nil
15803 (not (get-text-property 0 'org-unrestricted
15804 (caar allowed))))
15805 (let (org-completion-use-ido org-completion-use-iswitchb)
15806 (funcall set-function prompt
15807 (mapcar 'list (org-property-values property))
15808 nil nil "" nil cur)))))
15809 (org-trim val)))
15810
15811 (defvar org-last-set-property nil)
15812 (defvar org-last-set-property-value nil)
15813 (defun org-read-property-name ()
15814 "Read a property name."
15815 (let* ((completion-ignore-case t)
15816 (keys (org-buffer-property-keys nil t t))
15817 (default-prop (or (save-excursion
15818 (save-match-data
15819 (beginning-of-line)
15820 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15821 (null (string= (match-string 1) "END"))
15822 (match-string 1))))
15823 org-last-set-property))
15824 (property (org-icompleting-read
15825 (concat "Property"
15826 (if default-prop (concat " [" default-prop "]") "")
15827 ": ")
15828 (mapcar 'list keys)
15829 nil nil nil nil
15830 default-prop)))
15831 (if (member property keys)
15832 property
15833 (or (cdr (assoc (downcase property)
15834 (mapcar (lambda (x) (cons (downcase x) x))
15835 keys)))
15836 property))))
15837
15838 (defun org-set-property-and-value (use-last)
15839 "Allow to set [PROPERTY]: [value] direction from prompt.
15840 When use-default, don't even ask, just use the last
15841 \"[PROPERTY]: [value]\" string from the history."
15842 (interactive "P")
15843 (let* ((completion-ignore-case t)
15844 (pv (or (and use-last org-last-set-property-value)
15845 (org-completing-read
15846 "Enter a \"[Property]: [value]\" pair: "
15847 nil nil nil nil nil
15848 org-last-set-property-value)))
15849 prop val)
15850 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15851 (setq prop (match-string 1 pv)
15852 val (match-string 2 pv))
15853 (org-set-property prop val))))
15854
15855 (defun org-set-property (property value)
15856 "In the current entry, set PROPERTY to VALUE.
15857 When called interactively, this will prompt for a property name, offering
15858 completion on existing and default properties. And then it will prompt
15859 for a value, offering completion either on allowed values (via an inherited
15860 xxx_ALL property) or on existing values in other instances of this property
15861 in the current file."
15862 (interactive (list nil nil))
15863 (let* ((property (or property (org-read-property-name)))
15864 (value (or value (org-read-property-value property)))
15865 (fn (cdr (assoc property org-properties-postprocess-alist))))
15866 (setq org-last-set-property property)
15867 (setq org-last-set-property-value (concat property ": " value))
15868 ;; Possibly postprocess the inserted value:
15869 (when fn (setq value (funcall fn value)))
15870 (unless (equal (org-entry-get nil property) value)
15871 (org-entry-put nil property value))))
15872
15873 (defun org-delete-property (property &optional delete-empty-drawer)
15874 "In the current entry, delete PROPERTY.
15875 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15876 an empty drawer to delete."
15877 (interactive
15878 (let* ((completion-ignore-case t)
15879 (cat (org-entry-get (point) "CATEGORY"))
15880 (props0 (org-entry-properties nil 'standard))
15881 (props (if cat props0
15882 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15883 (prop (if (< 1 (length props))
15884 (org-icompleting-read "Property: " props nil t)
15885 (caar props))))
15886 (list prop)))
15887 (if (not property)
15888 (message "No property to delete in this entry")
15889 (org-entry-delete nil property delete-empty-drawer)
15890 (message "Property \"%s\" deleted" property)))
15891
15892 (defun org-delete-property-globally (property)
15893 "Remove PROPERTY globally, from all entries."
15894 (interactive
15895 (let* ((completion-ignore-case t)
15896 (prop (org-icompleting-read
15897 "Globally remove property: "
15898 (mapcar 'list (org-buffer-property-keys)))))
15899 (list prop)))
15900 (save-excursion
15901 (save-restriction
15902 (widen)
15903 (goto-char (point-min))
15904 (let ((cnt 0))
15905 (while (re-search-forward
15906 (org-re-property property)
15907 nil t)
15908 (setq cnt (1+ cnt))
15909 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15910 (message "Property \"%s\" removed from %d entries" property cnt)))))
15911
15912 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15913
15914 (defun org-compute-property-at-point ()
15915 "Compute the property at point.
15916 This looks for an enclosing column format, extracts the operator and
15917 then applies it to the property in the column format's scope."
15918 (interactive)
15919 (unless (org-at-property-p)
15920 (user-error "Not at a property"))
15921 (let ((prop (org-match-string-no-properties 2)))
15922 (org-columns-get-format-and-top-level)
15923 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15924 (user-error "No operator defined for property %s" prop))
15925 (org-columns-compute prop)))
15926
15927 (defvar org-property-allowed-value-functions nil
15928 "Hook for functions supplying allowed values for a specific property.
15929 The functions must take a single argument, the name of the property, and
15930 return a flat list of allowed values. If \":ETC\" is one of
15931 the values, this means that these values are intended as defaults for
15932 completion, but that other values should be allowed too.
15933 The functions must return nil if they are not responsible for this
15934 property.")
15935
15936 (defun org-property-get-allowed-values (pom property &optional table)
15937 "Get allowed values for the property PROPERTY.
15938 When TABLE is non-nil, return an alist that can directly be used for
15939 completion."
15940 (let (vals)
15941 (cond
15942 ((equal property "TODO")
15943 (setq vals (org-with-point-at pom
15944 (append org-todo-keywords-1 '("")))))
15945 ((equal property "PRIORITY")
15946 (let ((n org-lowest-priority))
15947 (while (>= n org-highest-priority)
15948 (push (char-to-string n) vals)
15949 (setq n (1- n)))))
15950 ((member property org-special-properties))
15951 ((setq vals (run-hook-with-args-until-success
15952 'org-property-allowed-value-functions property)))
15953 (t
15954 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15955 (when (and vals (string-match "\\S-" vals))
15956 (setq vals (car (read-from-string (concat "(" vals ")"))))
15957 (setq vals (mapcar (lambda (x)
15958 (cond ((stringp x) x)
15959 ((numberp x) (number-to-string x))
15960 ((symbolp x) (symbol-name x))
15961 (t "???")))
15962 vals)))))
15963 (when (member ":ETC" vals)
15964 (setq vals (remove ":ETC" vals))
15965 (org-add-props (car vals) '(org-unrestricted t)))
15966 (if table (mapcar 'list vals) vals)))
15967
15968 (defun org-property-previous-allowed-value (&optional previous)
15969 "Switch to the next allowed value for this property."
15970 (interactive)
15971 (org-property-next-allowed-value t))
15972
15973 (defun org-property-next-allowed-value (&optional previous)
15974 "Switch to the next allowed value for this property."
15975 (interactive)
15976 (unless (org-at-property-p)
15977 (user-error "Not at a property"))
15978 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15979 (key (match-string 2))
15980 (value (match-string 3))
15981 (allowed (or (org-property-get-allowed-values (point) key)
15982 (and (member value '("[ ]" "[-]" "[X]"))
15983 '("[ ]" "[X]"))))
15984 (heading (save-match-data (nth 4 (org-heading-components))))
15985 nval)
15986 (unless allowed
15987 (user-error "Allowed values for this property have not been defined"))
15988 (if previous (setq allowed (reverse allowed)))
15989 (if (member value allowed)
15990 (setq nval (car (cdr (member value allowed)))))
15991 (setq nval (or nval (car allowed)))
15992 (if (equal nval value)
15993 (user-error "Only one allowed value for this property"))
15994 (org-at-property-p)
15995 (replace-match (concat " :" key ": " nval) t t)
15996 (org-indent-line)
15997 (beginning-of-line 1)
15998 (skip-chars-forward " \t")
15999 (when (equal prop org-effort-property)
16000 (save-excursion
16001 (org-back-to-heading t)
16002 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16003 (when (string= org-clock-current-task heading)
16004 (setq org-clock-effort nval)
16005 (org-clock-update-mode-line)))
16006 (run-hook-with-args 'org-property-changed-functions key nval)))
16007
16008 (defun org-find-olp (path &optional this-buffer)
16009 "Return a marker pointing to the entry at outline path OLP.
16010 If anything goes wrong, throw an error.
16011 You can wrap this call to catch the error like this:
16012
16013 (condition-case msg
16014 (org-mobile-locate-entry (match-string 4))
16015 (error (nth 1 msg)))
16016
16017 The return value will then be either a string with the error message,
16018 or a marker if everything is OK.
16019
16020 If THIS-BUFFER is set, the outline path does not contain a file,
16021 only headings."
16022 (let* ((file (if this-buffer buffer-file-name (pop path)))
16023 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16024 (level 1)
16025 (lmin 1)
16026 (lmax 1)
16027 limit re end found pos heading cnt flevel)
16028 (unless buffer (error "File not found :%s" file))
16029 (with-current-buffer buffer
16030 (save-excursion
16031 (save-restriction
16032 (widen)
16033 (setq limit (point-max))
16034 (goto-char (point-min))
16035 (while (setq heading (pop path))
16036 (setq re (format org-complex-heading-regexp-format
16037 (regexp-quote heading)))
16038 (setq cnt 0 pos (point))
16039 (while (re-search-forward re end t)
16040 (setq level (- (match-end 1) (match-beginning 1)))
16041 (if (and (>= level lmin) (<= level lmax))
16042 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16043 (when (= cnt 0) (error "Heading not found on level %d: %s"
16044 lmax heading))
16045 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16046 lmax heading))
16047 (goto-char found)
16048 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16049 (setq end (save-excursion (org-end-of-subtree t t))))
16050 (when (org-at-heading-p)
16051 (point-marker)))))))
16052
16053 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16054 "Find node HEADING in BUFFER.
16055 Return a marker to the heading if it was found, or nil if not.
16056 If POS-ONLY is set, return just the position instead of a marker.
16057
16058 The heading text must match exact, but it may have a TODO keyword,
16059 a priority cookie and tags in the standard locations."
16060 (with-current-buffer (or buffer (current-buffer))
16061 (save-excursion
16062 (save-restriction
16063 (widen)
16064 (goto-char (point-min))
16065 (let (case-fold-search)
16066 (if (re-search-forward
16067 (format org-complex-heading-regexp-format
16068 (regexp-quote heading)) nil t)
16069 (if pos-only
16070 (match-beginning 0)
16071 (move-marker (make-marker) (match-beginning 0)))))))))
16072
16073 (defun org-find-exact-heading-in-directory (heading &optional dir)
16074 "Find Org node headline HEADING in all .org files in directory DIR.
16075 When the target headline is found, return a marker to this location."
16076 (let ((files (directory-files (or dir default-directory)
16077 nil "\\`[^.#].*\\.org\\'"))
16078 file visiting m buffer)
16079 (catch 'found
16080 (while (setq file (pop files))
16081 (message "trying %s" file)
16082 (setq visiting (org-find-base-buffer-visiting file))
16083 (setq buffer (or visiting (find-file-noselect file)))
16084 (setq m (org-find-exact-headline-in-buffer
16085 heading buffer))
16086 (when (and (not m) (not visiting)) (kill-buffer buffer))
16087 (and m (throw 'found m))))))
16088
16089 (defun org-find-entry-with-id (ident)
16090 "Locate the entry that contains the ID property with exact value IDENT.
16091 IDENT can be a string, a symbol or a number, this function will search for
16092 the string representation of it.
16093 Return the position where this entry starts, or nil if there is no such entry."
16094 (interactive "sID: ")
16095 (let ((id (cond
16096 ((stringp ident) ident)
16097 ((symbol-name ident) (symbol-name ident))
16098 ((numberp ident) (number-to-string ident))
16099 (t (error "IDENT %s must be a string, symbol or number" ident))))
16100 (case-fold-search nil))
16101 (save-excursion
16102 (save-restriction
16103 (widen)
16104 (goto-char (point-min))
16105 (when (re-search-forward
16106 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16107 nil t)
16108 (org-back-to-heading t)
16109 (point))))))
16110
16111 ;;;; Timestamps
16112
16113 (defvar org-last-changed-timestamp nil)
16114 (defvar org-last-inserted-timestamp nil
16115 "The last time stamp inserted with `org-insert-time-stamp'.")
16116 (defvar org-ts-what) ; dynamically scoped parameter
16117
16118 (defun org-time-stamp (arg &optional inactive)
16119 "Prompt for a date/time and insert a time stamp.
16120 If the user specifies a time like HH:MM or if this command is
16121 called with at least one prefix argument, the time stamp contains
16122 the date and the time. Otherwise, only the date is be included.
16123
16124 All parts of a date not specified by the user is filled in from
16125 the current date/time. So if you just press return without
16126 typing anything, the time stamp will represent the current
16127 date/time.
16128
16129 If there is already a timestamp at the cursor, it will be
16130 modified.
16131
16132 With two universal prefix arguments, insert an active timestamp
16133 with the current time without prompting the user.
16134
16135 When called from lisp, the timestamp is inactive if INACTIVE is
16136 non-nil."
16137 (interactive "P")
16138 (let* ((ts nil)
16139 (default-time
16140 ;; Default time is either today, or, when entering a range,
16141 ;; the range start.
16142 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16143 (save-excursion
16144 (re-search-backward
16145 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16146 (- (point) 20) t)))
16147 (apply 'encode-time (org-parse-time-string (match-string 1)))
16148 (current-time)))
16149 (default-input (and ts (org-get-compact-tod ts)))
16150 (repeater (save-excursion
16151 (save-match-data
16152 (beginning-of-line)
16153 (when (re-search-forward
16154 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16155 (save-excursion (progn (end-of-line) (point))) t)
16156 (match-string 0)))))
16157 org-time-was-given org-end-time-was-given time)
16158 (cond
16159 ((and (org-at-timestamp-p t)
16160 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16161 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16162 (insert "--")
16163 (setq time (let ((this-command this-command))
16164 (org-read-date arg 'totime nil nil
16165 default-time default-input inactive)))
16166 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16167 ((org-at-timestamp-p t)
16168 (setq time (let ((this-command this-command))
16169 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16170 (when (org-at-timestamp-p t) ; just to get the match data
16171 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16172 (replace-match "")
16173 (setq org-last-changed-timestamp
16174 (org-insert-time-stamp
16175 time (or org-time-was-given arg)
16176 inactive nil nil (list org-end-time-was-given)))
16177 (when repeater (goto-char (1- (point))) (insert " " repeater)
16178 (setq org-last-changed-timestamp
16179 (concat (substring org-last-inserted-timestamp 0 -1)
16180 " " repeater ">"))))
16181 (message "Timestamp updated"))
16182 ((equal arg '(16))
16183 (org-insert-time-stamp (current-time) t inactive))
16184 (t
16185 (setq time (let ((this-command this-command))
16186 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16187 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16188 nil nil (list org-end-time-was-given))))))
16189
16190 ;; FIXME: can we use this for something else, like computing time differences?
16191 (defun org-get-compact-tod (s)
16192 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16193 (let* ((t1 (match-string 1 s))
16194 (h1 (string-to-number (match-string 2 s)))
16195 (m1 (string-to-number (match-string 3 s)))
16196 (t2 (and (match-end 4) (match-string 5 s)))
16197 (h2 (and t2 (string-to-number (match-string 6 s))))
16198 (m2 (and t2 (string-to-number (match-string 7 s))))
16199 dh dm)
16200 (if (not t2)
16201 t1
16202 (setq dh (- h2 h1) dm (- m2 m1))
16203 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16204 (concat t1 "+" (number-to-string dh)
16205 (and (/= 0 dm) (format ":%02d" dm)))))))
16206
16207 (defun org-time-stamp-inactive (&optional arg)
16208 "Insert an inactive time stamp.
16209 An inactive time stamp is enclosed in square brackets instead of angle
16210 brackets. It is inactive in the sense that it does not trigger agenda entries,
16211 does not link to the calendar and cannot be changed with the S-cursor keys.
16212 So these are more for recording a certain time/date."
16213 (interactive "P")
16214 (org-time-stamp arg 'inactive))
16215
16216 (defvar org-date-ovl (make-overlay 1 1))
16217 (overlay-put org-date-ovl 'face 'org-date-selected)
16218 (org-detach-overlay org-date-ovl)
16219
16220 (defvar org-ans1) ; dynamically scoped parameter
16221 (defvar org-ans2) ; dynamically scoped parameter
16222
16223 (defvar org-plain-time-of-day-regexp) ; defined below
16224
16225 (defvar org-overriding-default-time nil) ; dynamically scoped
16226 (defvar org-read-date-overlay nil)
16227 (defvar org-dcst nil) ; dynamically scoped
16228 (defvar org-read-date-history nil)
16229 (defvar org-read-date-final-answer nil)
16230 (defvar org-read-date-analyze-futurep nil)
16231 (defvar org-read-date-analyze-forced-year nil)
16232 (defvar org-read-date-inactive)
16233
16234 (defvar org-read-date-minibuffer-local-map
16235 (let* ((org-replace-disputed-keys nil)
16236 (map (make-sparse-keymap)))
16237 (set-keymap-parent map minibuffer-local-map)
16238 (org-defkey map (kbd ".")
16239 (lambda () (interactive)
16240 ;; Are we at the beginning of the prompt?
16241 (if (looking-back "^[^:]+: ")
16242 (org-eval-in-calendar '(calendar-goto-today))
16243 (insert "."))))
16244 (org-defkey map (kbd "C-.")
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-goto-today))))
16247 (org-defkey map [(meta shift left)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-backward-month 1))))
16250 (org-defkey map [(meta shift right)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-forward-month 1))))
16253 (org-defkey map [(meta shift up)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-backward-year 1))))
16256 (org-defkey map [(meta shift down)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-forward-year 1))))
16259 (org-defkey map [?\e (shift left)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-backward-month 1))))
16262 (org-defkey map [?\e (shift right)]
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(calendar-forward-month 1))))
16265 (org-defkey map [?\e (shift up)]
16266 (lambda () (interactive)
16267 (org-eval-in-calendar '(calendar-backward-year 1))))
16268 (org-defkey map [?\e (shift down)]
16269 (lambda () (interactive)
16270 (org-eval-in-calendar '(calendar-forward-year 1))))
16271 (org-defkey map [(shift up)]
16272 (lambda () (interactive)
16273 (org-eval-in-calendar '(calendar-backward-week 1))))
16274 (org-defkey map [(shift down)]
16275 (lambda () (interactive)
16276 (org-eval-in-calendar '(calendar-forward-week 1))))
16277 (org-defkey map [(shift left)]
16278 (lambda () (interactive)
16279 (org-eval-in-calendar '(calendar-backward-day 1))))
16280 (org-defkey map [(shift right)]
16281 (lambda () (interactive)
16282 (org-eval-in-calendar '(calendar-forward-day 1))))
16283 (org-defkey map "!"
16284 (lambda () (interactive)
16285 (org-eval-in-calendar '(diary-view-entries))
16286 (message "")))
16287 (org-defkey map ">"
16288 (lambda () (interactive)
16289 (org-eval-in-calendar '(scroll-calendar-left 1))))
16290 (org-defkey map "<"
16291 (lambda () (interactive)
16292 (org-eval-in-calendar '(scroll-calendar-right 1))))
16293 (org-defkey map "\C-v"
16294 (lambda () (interactive)
16295 (org-eval-in-calendar
16296 '(calendar-scroll-left-three-months 1))))
16297 (org-defkey map "\M-v"
16298 (lambda () (interactive)
16299 (org-eval-in-calendar
16300 '(calendar-scroll-right-three-months 1))))
16301 map)
16302 "Keymap for minibuffer commands when using `org-read-date'.")
16303
16304 (defvar org-def)
16305 (defvar org-defdecode)
16306 (defvar org-with-time)
16307
16308 (defun org-read-date (&optional org-with-time to-time from-string prompt
16309 default-time default-input inactive)
16310 "Read a date, possibly a time, and make things smooth for the user.
16311 The prompt will suggest to enter an ISO date, but you can also enter anything
16312 which will at least partially be understood by `parse-time-string'.
16313 Unrecognized parts of the date will default to the current day, month, year,
16314 hour and minute. If this command is called to replace a timestamp at point,
16315 or to enter the second timestamp of a range, the default time is taken
16316 from the existing stamp. Furthermore, the command prefers the future,
16317 so if you are giving a date where the year is not given, and the day-month
16318 combination is already past in the current year, it will assume you
16319 mean next year. For details, see the manual. A few examples:
16320
16321 3-2-5 --> 2003-02-05
16322 feb 15 --> currentyear-02-15
16323 2/15 --> currentyear-02-15
16324 sep 12 9 --> 2009-09-12
16325 12:45 --> today 12:45
16326 22 sept 0:34 --> currentyear-09-22 0:34
16327 12 --> currentyear-currentmonth-12
16328 Fri --> nearest Friday after today
16329 -Tue --> last Tuesday
16330 etc.
16331
16332 Furthermore you can specify a relative date by giving, as the *first* thing
16333 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16334 change in days weeks, months, years.
16335 With a single plus or minus, the date is relative to today. With a double
16336 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16337 +4d --> four days from today
16338 +4 --> same as above
16339 +2w --> two weeks from today
16340 ++5 --> five days from default date
16341
16342 The function understands only English month and weekday abbreviations.
16343
16344 While prompting, a calendar is popped up - you can also select the
16345 date with the mouse (button 1). The calendar shows a period of three
16346 months. To scroll it to other months, use the keys `>' and `<'.
16347 If you don't like the calendar, turn it off with
16348 \(setq org-read-date-popup-calendar nil)
16349
16350 With optional argument TO-TIME, the date will immediately be converted
16351 to an internal time.
16352 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16353 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16354 still enter a time, and this function will inform the calling routine
16355 about this change. The calling routine may then choose to change the
16356 format used to insert the time stamp into the buffer to include the time.
16357 With optional argument FROM-STRING, read from this string instead from
16358 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16359 the time/date that is used for everything that is not specified by the
16360 user."
16361 (require 'parse-time)
16362 (let* ((org-time-stamp-rounding-minutes
16363 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16364 (org-dcst org-display-custom-times)
16365 (ct (org-current-time))
16366 (org-def (or org-overriding-default-time default-time ct))
16367 (org-defdecode (decode-time org-def))
16368 (dummy (progn
16369 (when (< (nth 2 org-defdecode) org-extend-today-until)
16370 (setcar (nthcdr 2 org-defdecode) -1)
16371 (setcar (nthcdr 1 org-defdecode) 59)
16372 (setq org-def (apply 'encode-time org-defdecode)
16373 org-defdecode (decode-time org-def)))))
16374 (mouse-autoselect-window nil) ; Don't let the mouse jump
16375 (calendar-frame-setup nil)
16376 (calendar-setup nil)
16377 (calendar-move-hook nil)
16378 (calendar-view-diary-initially-flag nil)
16379 (calendar-view-holidays-initially-flag nil)
16380 (timestr (format-time-string
16381 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16382 (prompt (concat (if prompt (concat prompt " ") "")
16383 (format "Date+time [%s]: " timestr)))
16384 ans (org-ans0 "") org-ans1 org-ans2 final)
16385
16386 (cond
16387 (from-string (setq ans from-string))
16388 (org-read-date-popup-calendar
16389 (save-excursion
16390 (save-window-excursion
16391 (calendar)
16392 (org-eval-in-calendar '(setq cursor-type nil) t)
16393 (unwind-protect
16394 (progn
16395 (calendar-forward-day (- (time-to-days org-def)
16396 (calendar-absolute-from-gregorian
16397 (calendar-current-date))))
16398 (org-eval-in-calendar nil t)
16399 (let* ((old-map (current-local-map))
16400 (map (copy-keymap calendar-mode-map))
16401 (minibuffer-local-map
16402 (copy-keymap org-read-date-minibuffer-local-map)))
16403 (org-defkey map (kbd "RET") 'org-calendar-select)
16404 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16405 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16406 (unwind-protect
16407 (progn
16408 (use-local-map map)
16409 (setq org-read-date-inactive inactive)
16410 (add-hook 'post-command-hook 'org-read-date-display)
16411 (setq org-ans0 (read-string prompt default-input
16412 'org-read-date-history nil))
16413 ;; org-ans0: from prompt
16414 ;; org-ans1: from mouse click
16415 ;; org-ans2: from calendar motion
16416 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16417 (remove-hook 'post-command-hook 'org-read-date-display)
16418 (use-local-map old-map)
16419 (when org-read-date-overlay
16420 (delete-overlay org-read-date-overlay)
16421 (setq org-read-date-overlay nil)))))
16422 (bury-buffer "*Calendar*")))))
16423
16424 (t ; Naked prompt only
16425 (unwind-protect
16426 (setq ans (read-string prompt default-input
16427 'org-read-date-history timestr))
16428 (when org-read-date-overlay
16429 (delete-overlay org-read-date-overlay)
16430 (setq org-read-date-overlay nil)))))
16431
16432 (setq final (org-read-date-analyze ans org-def org-defdecode))
16433
16434 (when org-read-date-analyze-forced-year
16435 (message "Year was forced into %s"
16436 (if org-read-date-force-compatible-dates
16437 "compatible range (1970-2037)"
16438 "range representable on this machine"))
16439 (ding))
16440
16441 ;; One round trip to get rid of 34th of August and stuff like that....
16442 (setq final (decode-time (apply 'encode-time final)))
16443
16444 (setq org-read-date-final-answer ans)
16445
16446 (if to-time
16447 (apply 'encode-time final)
16448 (if (and (boundp 'org-time-was-given) org-time-was-given)
16449 (format "%04d-%02d-%02d %02d:%02d"
16450 (nth 5 final) (nth 4 final) (nth 3 final)
16451 (nth 2 final) (nth 1 final))
16452 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16453
16454 (defun org-read-date-display ()
16455 "Display the current date prompt interpretation in the minibuffer."
16456 (when org-read-date-display-live
16457 (when org-read-date-overlay
16458 (delete-overlay org-read-date-overlay))
16459 (when (minibufferp (current-buffer))
16460 (save-excursion
16461 (end-of-line 1)
16462 (while (not (equal (buffer-substring
16463 (max (point-min) (- (point) 4)) (point))
16464 " "))
16465 (insert " ")))
16466 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16467 " " (or org-ans1 org-ans2)))
16468 (org-end-time-was-given nil)
16469 (f (org-read-date-analyze ans org-def org-defdecode))
16470 (fmts (if org-dcst
16471 org-time-stamp-custom-formats
16472 org-time-stamp-formats))
16473 (fmt (if (or org-with-time
16474 (and (boundp 'org-time-was-given) org-time-was-given))
16475 (cdr fmts)
16476 (car fmts)))
16477 (txt (format-time-string fmt (apply 'encode-time f)))
16478 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16479 (txt (concat "=> " txt)))
16480 (when (and org-end-time-was-given
16481 (string-match org-plain-time-of-day-regexp txt))
16482 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16483 org-end-time-was-given
16484 (substring txt (match-end 0)))))
16485 (when org-read-date-analyze-futurep
16486 (setq txt (concat txt " (=>F)")))
16487 (setq org-read-date-overlay
16488 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16489 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16490
16491 (defun org-read-date-analyze (ans org-def org-defdecode)
16492 "Analyze the combined answer of the date prompt."
16493 ;; FIXME: cleanup and comment
16494 (let ((nowdecode (decode-time))
16495 delta deltan deltaw deltadef year month day
16496 hour minute second wday pm h2 m2 tl wday1
16497 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16498 (setq org-read-date-analyze-futurep nil
16499 org-read-date-analyze-forced-year nil)
16500 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16501 (setq ans "+0"))
16502
16503 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16504 (setq ans (replace-match "" t t ans)
16505 deltan (car delta)
16506 deltaw (nth 1 delta)
16507 deltadef (nth 2 delta)))
16508
16509 ;; Check if there is an iso week date in there. If yes, store the
16510 ;; info and postpone interpreting it until the rest of the parsing
16511 ;; is done.
16512 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16513 (setq iso-year (if (match-end 1)
16514 (org-small-year-to-year
16515 (string-to-number (match-string 1 ans))))
16516 iso-weekday (if (match-end 3)
16517 (string-to-number (match-string 3 ans)))
16518 iso-week (string-to-number (match-string 2 ans)))
16519 (setq ans (replace-match "" t t ans)))
16520
16521 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16522 (when (string-match
16523 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16524 (setq year (if (match-end 2)
16525 (string-to-number (match-string 2 ans))
16526 (progn (setq kill-year t)
16527 (string-to-number (format-time-string "%Y"))))
16528 month (string-to-number (match-string 3 ans))
16529 day (string-to-number (match-string 4 ans)))
16530 (if (< year 100) (setq year (+ 2000 year)))
16531 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16532 t nil ans)))
16533
16534 ;; Help matching dotted european dates
16535 (when (string-match
16536 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16537 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16538 (setq kill-year t)
16539 (string-to-number (format-time-string "%Y")))
16540 day (string-to-number (match-string 1 ans))
16541 month (string-to-number (match-string 2 ans))
16542 ans (replace-match (format "%04d-%02d-%02d" year month day)
16543 t nil ans)))
16544
16545 ;; Help matching american dates, like 5/30 or 5/30/7
16546 (when (string-match
16547 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16548 (setq year (if (match-end 4)
16549 (string-to-number (match-string 4 ans))
16550 (progn (setq kill-year t)
16551 (string-to-number (format-time-string "%Y"))))
16552 month (string-to-number (match-string 1 ans))
16553 day (string-to-number (match-string 2 ans)))
16554 (if (< year 100) (setq year (+ 2000 year)))
16555 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16556 t nil ans)))
16557 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16558 ;; If there is a time with am/pm, and *no* time without it, we convert
16559 ;; so that matching will be successful.
16560 (loop for i from 1 to 2 do ; twice, for end time as well
16561 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16562 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16563 (setq hour (string-to-number (match-string 1 ans))
16564 minute (if (match-end 3)
16565 (string-to-number (match-string 3 ans))
16566 0)
16567 pm (equal ?p
16568 (string-to-char (downcase (match-string 4 ans)))))
16569 (if (and (= hour 12) (not pm))
16570 (setq hour 0)
16571 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16572 (setq ans (replace-match (format "%02d:%02d" hour minute)
16573 t t ans))))
16574
16575 ;; Check if a time range is given as a duration
16576 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16577 (setq hour (string-to-number (match-string 1 ans))
16578 h2 (+ hour (string-to-number (match-string 3 ans)))
16579 minute (string-to-number (match-string 2 ans))
16580 m2 (+ minute (if (match-end 5) (string-to-number
16581 (match-string 5 ans))0)))
16582 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16583 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16584 t t ans)))
16585
16586 ;; Check if there is a time range
16587 (when (boundp 'org-end-time-was-given)
16588 (setq org-time-was-given nil)
16589 (when (and (string-match org-plain-time-of-day-regexp ans)
16590 (match-end 8))
16591 (setq org-end-time-was-given (match-string 8 ans))
16592 (setq ans (concat (substring ans 0 (match-beginning 7))
16593 (substring ans (match-end 7))))))
16594
16595 (setq tl (parse-time-string ans)
16596 day (or (nth 3 tl) (nth 3 org-defdecode))
16597 month (or (nth 4 tl)
16598 (if (and org-read-date-prefer-future
16599 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16600 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16601 (nth 4 org-defdecode)))
16602 year (or (and (not kill-year) (nth 5 tl))
16603 (if (and org-read-date-prefer-future
16604 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16605 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16606 (nth 5 org-defdecode)))
16607 hour (or (nth 2 tl) (nth 2 org-defdecode))
16608 minute (or (nth 1 tl) (nth 1 org-defdecode))
16609 second (or (nth 0 tl) 0)
16610 wday (nth 6 tl))
16611
16612 (when (and (eq org-read-date-prefer-future 'time)
16613 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16614 (equal day (nth 3 nowdecode))
16615 (equal month (nth 4 nowdecode))
16616 (equal year (nth 5 nowdecode))
16617 (nth 2 tl)
16618 (or (< (nth 2 tl) (nth 2 nowdecode))
16619 (and (= (nth 2 tl) (nth 2 nowdecode))
16620 (nth 1 tl)
16621 (< (nth 1 tl) (nth 1 nowdecode)))))
16622 (setq day (1+ day)
16623 futurep t))
16624
16625 ;; Special date definitions below
16626 (cond
16627 (iso-week
16628 ;; There was an iso week
16629 (require 'cal-iso)
16630 (setq futurep nil)
16631 (setq year (or iso-year year)
16632 day (or iso-weekday wday 1)
16633 wday nil ; to make sure that the trigger below does not match
16634 iso-date (calendar-gregorian-from-absolute
16635 (calendar-absolute-from-iso
16636 (list iso-week day year))))
16637 ; FIXME: Should we also push ISO weeks into the future?
16638 ; (when (and org-read-date-prefer-future
16639 ; (not iso-year)
16640 ; (< (calendar-absolute-from-gregorian iso-date)
16641 ; (time-to-days (current-time))))
16642 ; (setq year (1+ year)
16643 ; iso-date (calendar-gregorian-from-absolute
16644 ; (calendar-absolute-from-iso
16645 ; (list iso-week day year)))))
16646 (setq month (car iso-date)
16647 year (nth 2 iso-date)
16648 day (nth 1 iso-date)))
16649 (deltan
16650 (setq futurep nil)
16651 (unless deltadef
16652 (let ((now (decode-time)))
16653 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16654 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16655 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16656 ((equal deltaw "m") (setq month (+ month deltan)))
16657 ((equal deltaw "y") (setq year (+ year deltan)))))
16658 ((and wday (not (nth 3 tl)))
16659 ;; Weekday was given, but no day, so pick that day in the week
16660 ;; on or after the derived date.
16661 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16662 (unless (equal wday wday1)
16663 (setq day (+ day (% (- wday wday1 -7) 7))))))
16664 (if (and (boundp 'org-time-was-given)
16665 (nth 2 tl))
16666 (setq org-time-was-given t))
16667 (if (< year 100) (setq year (+ 2000 year)))
16668 ;; Check of the date is representable
16669 (if org-read-date-force-compatible-dates
16670 (progn
16671 (if (< year 1970)
16672 (setq year 1970 org-read-date-analyze-forced-year t))
16673 (if (> year 2037)
16674 (setq year 2037 org-read-date-analyze-forced-year t)))
16675 (condition-case nil
16676 (ignore (encode-time second minute hour day month year))
16677 (error
16678 (setq year (nth 5 org-defdecode))
16679 (setq org-read-date-analyze-forced-year t))))
16680 (setq org-read-date-analyze-futurep futurep)
16681 (list second minute hour day month year)))
16682
16683 (defvar parse-time-weekdays)
16684 (defun org-read-date-get-relative (s today default)
16685 "Check string S for special relative date string.
16686 TODAY and DEFAULT are internal times, for today and for a default.
16687 Return shift list (N what def-flag)
16688 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16689 N is the number of WHATs to shift.
16690 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16691 the DEFAULT date rather than TODAY."
16692 (require 'parse-time)
16693 (when (and
16694 (string-match
16695 (concat
16696 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16697 "\\([0-9]+\\)?"
16698 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16699 "\\([ \t]\\|$\\)") s)
16700 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16701 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16702 (string-to-char (substring (match-string 1 s) -1))
16703 ?+))
16704 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16705 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16706 (what (if (match-end 3) (match-string 3 s) "d"))
16707 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16708 (date (if rel default today))
16709 (wday (nth 6 (decode-time date)))
16710 delta)
16711 (if wday1
16712 (progn
16713 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16714 (if (= delta 0) (setq delta 7))
16715 (if (= dir ?-)
16716 (progn
16717 (setq delta (- delta 7))
16718 (if (= delta 0) (setq delta -7))))
16719 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16720 (list delta "d" rel))
16721 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16722
16723 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16724 "Turn a user-specified date into the internal representation.
16725 The internal representation needed by the calendar is (month day year).
16726 This is a wrapper to handle the brain-dead convention in calendar that
16727 user function argument order change dependent on argument order."
16728 (if (boundp 'calendar-date-style)
16729 (cond
16730 ((eq calendar-date-style 'american)
16731 (list arg1 arg2 arg3))
16732 ((eq calendar-date-style 'european)
16733 (list arg2 arg1 arg3))
16734 ((eq calendar-date-style 'iso)
16735 (list arg2 arg3 arg1)))
16736 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16737 (if (org-bound-and-true-p european-calendar-style)
16738 (list arg2 arg1 arg3)
16739 (list arg1 arg2 arg3)))))
16740
16741 (defun org-eval-in-calendar (form &optional keepdate)
16742 "Eval FORM in the calendar window and return to current window.
16743 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16744 otherwise stick to the current value of `org-ans2'."
16745 (let ((sf (selected-frame))
16746 (sw (selected-window)))
16747 (select-window (get-buffer-window "*Calendar*" t))
16748 (eval form)
16749 (when (and (not keepdate) (calendar-cursor-to-date))
16750 (let* ((date (calendar-cursor-to-date))
16751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16752 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16753 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16754 (select-window sw)
16755 (org-select-frame-set-input-focus sf)))
16756
16757 (defun org-calendar-select ()
16758 "Return to `org-read-date' with the date currently selected.
16759 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16760 (interactive)
16761 (when (calendar-cursor-to-date)
16762 (let* ((date (calendar-cursor-to-date))
16763 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16764 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16765 (if (active-minibuffer-window) (exit-minibuffer))))
16766
16767 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16768 "Insert a date stamp for the date given by the internal TIME.
16769 WITH-HM means use the stamp format that includes the time of the day.
16770 INACTIVE means use square brackets instead of angular ones, so that the
16771 stamp will not contribute to the agenda.
16772 PRE and POST are optional strings to be inserted before and after the
16773 stamp.
16774 The command returns the inserted time stamp."
16775 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16776 stamp)
16777 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16778 (insert-before-markers (or pre ""))
16779 (when (listp extra)
16780 (setq extra (car extra))
16781 (if (and (stringp extra)
16782 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16783 (setq extra (format "-%02d:%02d"
16784 (string-to-number (match-string 1 extra))
16785 (string-to-number (match-string 2 extra))))
16786 (setq extra nil)))
16787 (when extra
16788 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16789 (insert-before-markers (setq stamp (format-time-string fmt time)))
16790 (insert-before-markers (or post ""))
16791 (setq org-last-inserted-timestamp stamp)))
16792
16793 (defun org-toggle-time-stamp-overlays ()
16794 "Toggle the use of custom time stamp formats."
16795 (interactive)
16796 (setq org-display-custom-times (not org-display-custom-times))
16797 (unless org-display-custom-times
16798 (let ((p (point-min)) (bmp (buffer-modified-p)))
16799 (while (setq p (next-single-property-change p 'display))
16800 (if (and (get-text-property p 'display)
16801 (eq (get-text-property p 'face) 'org-date))
16802 (remove-text-properties
16803 p (setq p (next-single-property-change p 'display))
16804 '(display t))))
16805 (set-buffer-modified-p bmp)))
16806 (if (featurep 'xemacs)
16807 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16808 (org-restart-font-lock)
16809 (setq org-table-may-need-update t)
16810 (if org-display-custom-times
16811 (message "Time stamps are overlaid with custom format")
16812 (message "Time stamp overlays removed")))
16813
16814 (defun org-display-custom-time (beg end)
16815 "Overlay modified time stamp format over timestamp between BEG and END."
16816 (let* ((ts (buffer-substring beg end))
16817 t1 w1 with-hm tf time str w2 (off 0))
16818 (save-match-data
16819 (setq t1 (org-parse-time-string ts t))
16820 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16821 (setq off (- (match-end 0) (match-beginning 0)))))
16822 (setq end (- end off))
16823 (setq w1 (- end beg)
16824 with-hm (and (nth 1 t1) (nth 2 t1))
16825 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16826 time (org-fix-decoded-time t1)
16827 str (org-add-props
16828 (format-time-string
16829 (substring tf 1 -1) (apply 'encode-time time))
16830 nil 'mouse-face 'highlight)
16831 w2 (length str))
16832 (if (not (= w2 w1))
16833 (add-text-properties (1+ beg) (+ 2 beg)
16834 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16835 (if (featurep 'xemacs)
16836 (progn
16837 (put-text-property beg end 'invisible t)
16838 (put-text-property beg end 'end-glyph (make-glyph str)))
16839 (put-text-property beg end 'display str))))
16840
16841 (defun org-translate-time (string)
16842 "Translate all timestamps in STRING to custom format.
16843 But do this only if the variable `org-display-custom-times' is set."
16844 (when org-display-custom-times
16845 (save-match-data
16846 (let* ((start 0)
16847 (re org-ts-regexp-both)
16848 t1 with-hm inactive tf time str beg end)
16849 (while (setq start (string-match re string start))
16850 (setq beg (match-beginning 0)
16851 end (match-end 0)
16852 t1 (save-match-data
16853 (org-parse-time-string (substring string beg end) t))
16854 with-hm (and (nth 1 t1) (nth 2 t1))
16855 inactive (equal (substring string beg (1+ beg)) "[")
16856 tf (funcall (if with-hm 'cdr 'car)
16857 org-time-stamp-custom-formats)
16858 time (org-fix-decoded-time t1)
16859 str (format-time-string
16860 (concat
16861 (if inactive "[" "<") (substring tf 1 -1)
16862 (if inactive "]" ">"))
16863 (apply 'encode-time time))
16864 string (replace-match str t t string)
16865 start (+ start (length str)))))))
16866 string)
16867
16868 (defun org-fix-decoded-time (time)
16869 "Set 0 instead of nil for the first 6 elements of time.
16870 Don't touch the rest."
16871 (let ((n 0))
16872 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16873
16874 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16875
16876 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16877 "Difference between TIMESTAMP-STRING and now in days.
16878 If SECONDS is non-nil, return the difference in seconds."
16879 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16880 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16881 (funcall fdiff (current-time)))))
16882
16883 (defun org-deadline-close (timestamp-string &optional ndays)
16884 "Is the time in TIMESTAMP-STRING close to the current date?"
16885 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16886 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16887 (not (org-entry-is-done-p))))
16888
16889 (defun org-get-wdays (ts &optional delay zero-delay)
16890 "Get the deadline lead time appropriate for timestring TS.
16891 When DELAY is non-nil, get the delay time for scheduled items
16892 instead of the deadline lead time. When ZERO-DELAY is non-nil
16893 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16894 don't try to find the delay cookie in the scheduled timestamp."
16895 (let ((tv (if delay org-scheduled-delay-days
16896 org-deadline-warning-days)))
16897 (cond
16898 ((or (and delay (< tv 0))
16899 (and delay zero-delay (<= tv 0))
16900 (and (not delay) (<= tv 0)))
16901 ;; Enforce this value no matter what
16902 (- tv))
16903 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16904 ;; lead time is specified.
16905 (floor (* (string-to-number (match-string 1 ts))
16906 (cdr (assoc (match-string 2 ts)
16907 '(("d" . 1) ("w" . 7)
16908 ("m" . 30.4) ("y" . 365.25)
16909 ("h" . 0.041667)))))))
16910 ;; go for the default.
16911 (t tv))))
16912
16913 (defun org-calendar-select-mouse (ev)
16914 "Return to `org-read-date' with the date currently selected.
16915 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16916 (interactive "e")
16917 (mouse-set-point ev)
16918 (when (calendar-cursor-to-date)
16919 (let* ((date (calendar-cursor-to-date))
16920 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16921 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16922 (if (active-minibuffer-window) (exit-minibuffer))))
16923
16924 (defun org-check-deadlines (ndays)
16925 "Check if there are any deadlines due or past due.
16926 A deadline is considered due if it happens within `org-deadline-warning-days'
16927 days from today's date. If the deadline appears in an entry marked DONE,
16928 it is not shown. The prefix arg NDAYS can be used to test that many
16929 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16930 (interactive "P")
16931 (let* ((org-warn-days
16932 (cond
16933 ((equal ndays '(4)) 100000)
16934 (ndays (prefix-numeric-value ndays))
16935 (t (abs org-deadline-warning-days))))
16936 (case-fold-search nil)
16937 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16938 (callback
16939 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16940
16941 (message "%d deadlines past-due or due within %d days"
16942 (org-occur regexp nil callback)
16943 org-warn-days)))
16944
16945 (defsubst org-re-timestamp (type)
16946 "Return a regexp for timestamp TYPE.
16947 Allowed values for TYPE are:
16948
16949 all: all timestamps
16950 active: only active timestamps (<...>)
16951 inactive: only inactive timestamps ([...])
16952 scheduled: only scheduled timestamps
16953 deadline: only deadline timestamps
16954 closed: only closed time-stamps
16955
16956 When TYPE is nil, fall back on returning a regexp that matches
16957 both scheduled and deadline timestamps."
16958 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16959 ((eq type 'active) org-ts-regexp)
16960 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16961 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16962 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16963 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16964 ((eq type 'scheduled-or-deadline)
16965 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16966
16967 (defun org-check-before-date (date)
16968 "Check if there are deadlines or scheduled entries before DATE."
16969 (interactive (list (org-read-date)))
16970 (let ((case-fold-search nil)
16971 (regexp (org-re-timestamp org-ts-type))
16972 (callback
16973 (lambda () (time-less-p
16974 (org-time-string-to-time (match-string 1))
16975 (org-time-string-to-time date)))))
16976 (message "%d entries before %s"
16977 (org-occur regexp nil callback) date)))
16978
16979 (defun org-check-after-date (date)
16980 "Check if there are deadlines or scheduled entries after DATE."
16981 (interactive (list (org-read-date)))
16982 (let ((case-fold-search nil)
16983 (regexp (org-re-timestamp org-ts-type))
16984 (callback
16985 (lambda () (not
16986 (time-less-p
16987 (org-time-string-to-time (match-string 1))
16988 (org-time-string-to-time date))))))
16989 (message "%d entries after %s"
16990 (org-occur regexp nil callback) date)))
16991
16992 (defun org-check-dates-range (start-date end-date)
16993 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16994 (interactive (list (org-read-date nil nil nil "Range starts")
16995 (org-read-date nil nil nil "Range end")))
16996 (let ((case-fold-search nil)
16997 (regexp (org-re-timestamp org-ts-type))
16998 (callback
16999 (lambda ()
17000 (let ((match (match-string 1)))
17001 (and
17002 (not (time-less-p
17003 (org-time-string-to-time match)
17004 (org-time-string-to-time start-date)))
17005 (time-less-p
17006 (org-time-string-to-time match)
17007 (org-time-string-to-time end-date)))))))
17008 (message "%d entries between %s and %s"
17009 (org-occur regexp nil callback) start-date end-date)))
17010
17011 (defun org-evaluate-time-range (&optional to-buffer)
17012 "Evaluate a time range by computing the difference between start and end.
17013 Normally the result is just printed in the echo area, but with prefix arg
17014 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17015 If the time range is actually in a table, the result is inserted into the
17016 next column.
17017 For time difference computation, a year is assumed to be exactly 365
17018 days in order to avoid rounding problems."
17019 (interactive "P")
17020 (or
17021 (org-clock-update-time-maybe)
17022 (save-excursion
17023 (unless (org-at-date-range-p t)
17024 (goto-char (point-at-bol))
17025 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17026 (if (not (org-at-date-range-p t))
17027 (user-error "Not at a time-stamp range, and none found in current line")))
17028 (let* ((ts1 (match-string 1))
17029 (ts2 (match-string 2))
17030 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17031 (match-end (match-end 0))
17032 (time1 (org-time-string-to-time ts1))
17033 (time2 (org-time-string-to-time ts2))
17034 (t1 (org-float-time time1))
17035 (t2 (org-float-time time2))
17036 (diff (abs (- t2 t1)))
17037 (negative (< (- t2 t1) 0))
17038 ;; (ys (floor (* 365 24 60 60)))
17039 (ds (* 24 60 60))
17040 (hs (* 60 60))
17041 (fy "%dy %dd %02d:%02d")
17042 (fy1 "%dy %dd")
17043 (fd "%dd %02d:%02d")
17044 (fd1 "%dd")
17045 (fh "%02d:%02d")
17046 y d h m align)
17047 (if havetime
17048 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17049 y 0
17050 d (floor (/ diff ds)) diff (mod diff ds)
17051 h (floor (/ diff hs)) diff (mod diff hs)
17052 m (floor (/ diff 60)))
17053 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17054 y 0
17055 d (floor (+ (/ diff ds) 0.5))
17056 h 0 m 0))
17057 (if (not to-buffer)
17058 (message "%s" (org-make-tdiff-string y d h m))
17059 (if (org-at-table-p)
17060 (progn
17061 (goto-char match-end)
17062 (setq align t)
17063 (and (looking-at " *|") (goto-char (match-end 0))))
17064 (goto-char match-end))
17065 (if (looking-at
17066 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17067 (replace-match ""))
17068 (if negative (insert " -"))
17069 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17070 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17071 (insert " " (format fh h m))))
17072 (if align (org-table-align))
17073 (message "Time difference inserted")))))
17074
17075 (defun org-make-tdiff-string (y d h m)
17076 (let ((fmt "")
17077 (l nil))
17078 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17079 l (push y l)))
17080 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17081 l (push d l)))
17082 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17083 l (push h l)))
17084 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17085 l (push m l)))
17086 (apply 'format fmt (nreverse l))))
17087
17088 (defun org-time-string-to-time (s &optional buffer pos)
17089 "Convert a timestamp string into internal time."
17090 (condition-case errdata
17091 (apply 'encode-time (org-parse-time-string s))
17092 (error (error "Bad timestamp `%s'%s\nError was: %s"
17093 s (if (not (and buffer pos))
17094 ""
17095 (format " at %d in buffer `%s'" pos buffer))
17096 (cdr errdata)))))
17097
17098 (defun org-time-string-to-seconds (s)
17099 "Convert a timestamp string to a number of seconds."
17100 (org-float-time (org-time-string-to-time s)))
17101
17102 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17103 "Convert a time stamp to an absolute day number.
17104 If there is a specifier for a cyclic time stamp, get the closest
17105 date to DAYNR.
17106 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17107 The variable `date' is bound by the calendar when this is called."
17108 (cond
17109 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17110 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17111 daynr
17112 (+ daynr 1000)))
17113 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17114 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17115 (time-to-days (current-time))) (match-string 0 s)
17116 prefer show-all))
17117 (t (time-to-days
17118 (condition-case errdata
17119 (apply 'encode-time (org-parse-time-string s))
17120 (error (error "Bad timestamp `%s'%s\nError was: %s"
17121 s (if (not (and buffer pos))
17122 ""
17123 (format " at %d in buffer `%s'" pos buffer))
17124 (cdr errdata))))))))
17125
17126 (defun org-days-to-iso-week (days)
17127 "Return the iso week number."
17128 (require 'cal-iso)
17129 (car (calendar-iso-from-absolute days)))
17130
17131 (defun org-small-year-to-year (year)
17132 "Convert 2-digit years into 4-digit years.
17133 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17134 The year 2000 cannot be abbreviated. Any year larger than 99
17135 is returned unchanged."
17136 (if (< year 38)
17137 (setq year (+ 2000 year))
17138 (if (< year 100)
17139 (setq year (+ 1900 year))))
17140 year)
17141
17142 (defun org-time-from-absolute (d)
17143 "Return the time corresponding to date D.
17144 D may be an absolute day number, or a calendar-type list (month day year)."
17145 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17146 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17147
17148 (defun org-calendar-holiday ()
17149 "List of holidays, for Diary display in Org-mode."
17150 (require 'holidays)
17151 (let ((hl (funcall
17152 (if (fboundp 'calendar-check-holidays)
17153 'calendar-check-holidays 'check-calendar-holidays) date)))
17154 (if hl (mapconcat 'identity hl "; "))))
17155
17156 (defun org-diary-sexp-entry (sexp entry date)
17157 "Process a SEXP diary ENTRY for DATE."
17158 (require 'diary-lib)
17159 (let ((result (if calendar-debug-sexp
17160 (let ((stack-trace-on-error t))
17161 (eval (car (read-from-string sexp))))
17162 (condition-case nil
17163 (eval (car (read-from-string sexp)))
17164 (error
17165 (beep)
17166 (message "Bad sexp at line %d in %s: %s"
17167 (org-current-line)
17168 (buffer-file-name) sexp)
17169 (sleep-for 2))))))
17170 (cond ((stringp result) (split-string result "; "))
17171 ((and (consp result)
17172 (not (consp (cdr result)))
17173 (stringp (cdr result))) (cdr result))
17174 ((and (consp result)
17175 (stringp (car result))) result)
17176 (result entry))))
17177
17178 (defun org-diary-to-ical-string (frombuf)
17179 "Get iCalendar entries from diary entries in buffer FROMBUF.
17180 This uses the icalendar.el library."
17181 (let* ((tmpdir (if (featurep 'xemacs)
17182 (temp-directory)
17183 temporary-file-directory))
17184 (tmpfile (make-temp-name
17185 (expand-file-name "orgics" tmpdir)))
17186 buf rtn b e)
17187 (with-current-buffer frombuf
17188 (icalendar-export-region (point-min) (point-max) tmpfile)
17189 (setq buf (find-buffer-visiting tmpfile))
17190 (set-buffer buf)
17191 (goto-char (point-min))
17192 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17193 (setq b (match-beginning 0)))
17194 (goto-char (point-max))
17195 (if (re-search-backward "^END:VEVENT" nil t)
17196 (setq e (match-end 0)))
17197 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17198 (kill-buffer buf)
17199 (delete-file tmpfile)
17200 rtn))
17201
17202 (defun org-closest-date (start current change prefer show-all)
17203 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17204 When PREFER is `past', return a date that is either CURRENT or past.
17205 When PREFER is `future', return a date that is either CURRENT or future.
17206 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17207 ;; Make the proper lists from the dates
17208 (catch 'exit
17209 (let ((a1 '(("h" . hour)
17210 ("d" . day)
17211 ("w" . week)
17212 ("m" . month)
17213 ("y" . year)))
17214 (shour (nth 2 (org-parse-time-string start)))
17215 dn dw sday cday n1 n2 n0
17216 d m y y1 y2 date1 date2 nmonths nm ny m2)
17217
17218 (setq start (org-date-to-gregorian start)
17219 current (org-date-to-gregorian
17220 (if show-all
17221 current
17222 (time-to-days (current-time))))
17223 sday (calendar-absolute-from-gregorian start)
17224 cday (calendar-absolute-from-gregorian current))
17225
17226 (if (<= cday sday) (throw 'exit sday))
17227
17228 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17229 (setq dn (string-to-number (match-string 1 change))
17230 dw (cdr (assoc (match-string 2 change) a1)))
17231 (user-error "Invalid change specifier: %s" change))
17232 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17233 (cond
17234 ((eq dw 'hour)
17235 (let ((missing-hours
17236 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17237 dn)))
17238 (setq n1 (if (zerop missing-hours) cday
17239 (- cday (1+ (floor (/ missing-hours 24)))))
17240 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17241 ((eq dw 'day)
17242 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17243 n2 (+ n1 dn)))
17244 ((eq dw 'year)
17245 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17246 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17247 (setq date1 (list m d y1)
17248 n1 (calendar-absolute-from-gregorian date1)
17249 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17250 n2 (calendar-absolute-from-gregorian date2)))
17251 ((eq dw 'month)
17252 ;; approx number of month between the two dates
17253 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17254 ;; How often does dn fit in there?
17255 (setq d (nth 1 start) m (car start) y (nth 2 start)
17256 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17257 m (+ m nm)
17258 ny (floor (/ m 12))
17259 y (+ y ny)
17260 m (- m (* ny 12)))
17261 (while (> m 12) (setq m (- m 12) y (1+ y)))
17262 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17263 (setq m2 (+ m dn) y2 y)
17264 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17265 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17266 (while (<= n2 cday)
17267 (setq n1 n2 m m2 y y2)
17268 (setq m2 (+ m dn) y2 y)
17269 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17270 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17271 ;; Make sure n1 is the earlier date
17272 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17273 (if show-all
17274 (cond
17275 ((eq prefer 'past) (if (= cday n2) n2 n1))
17276 ((eq prefer 'future) (if (= cday n1) n1 n2))
17277 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17278 (cond
17279 ((eq prefer 'past) (if (= cday n2) n2 n1))
17280 ((eq prefer 'future) (if (= cday n1) n1 n2))
17281 (t (if (= cday n1) n1 n2)))))))
17282
17283 (defun org-date-to-gregorian (date)
17284 "Turn any specification of DATE into a Gregorian date for the calendar."
17285 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17286 ((and (listp date) (= (length date) 3)) date)
17287 ((stringp date)
17288 (setq date (org-parse-time-string date))
17289 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17290 ((listp date)
17291 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17292
17293 (defun org-parse-time-string (s &optional nodefault)
17294 "Parse the standard Org-mode time string.
17295 This should be a lot faster than the normal `parse-time-string'.
17296 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17297 hour and minute fields will be nil if not given."
17298 (cond ((string-match org-ts-regexp0 s)
17299 (list 0
17300 (if (or (match-beginning 8) (not nodefault))
17301 (string-to-number (or (match-string 8 s) "0")))
17302 (if (or (match-beginning 7) (not nodefault))
17303 (string-to-number (or (match-string 7 s) "0")))
17304 (string-to-number (match-string 4 s))
17305 (string-to-number (match-string 3 s))
17306 (string-to-number (match-string 2 s))
17307 nil nil nil))
17308 ((string-match "^<[^>]+>$" s)
17309 (decode-time (seconds-to-time (org-matcher-time s))))
17310 (t (error "Not a standard Org-mode time string: %s" s))))
17311
17312 (defun org-timestamp-up (&optional arg)
17313 "Increase the date item at the cursor by one.
17314 If the cursor is on the year, change the year. If it is on the month,
17315 the day or the time, change that.
17316 With prefix ARG, change by that many units."
17317 (interactive "p")
17318 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17319
17320 (defun org-timestamp-down (&optional arg)
17321 "Decrease the date item at the cursor by one.
17322 If the cursor is on the year, change the year. If it is on the month,
17323 the day or the time, change that.
17324 With prefix ARG, change by that many units."
17325 (interactive "p")
17326 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17327
17328 (defun org-timestamp-up-day (&optional arg)
17329 "Increase the date in the time stamp by one day.
17330 With prefix ARG, change that many days."
17331 (interactive "p")
17332 (if (and (not (org-at-timestamp-p t))
17333 (org-at-heading-p))
17334 (org-todo 'up)
17335 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17336
17337 (defun org-timestamp-down-day (&optional arg)
17338 "Decrease the date in the time stamp by one day.
17339 With prefix ARG, change that many days."
17340 (interactive "p")
17341 (if (and (not (org-at-timestamp-p t))
17342 (org-at-heading-p))
17343 (org-todo 'down)
17344 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17345
17346 (defun org-at-timestamp-p (&optional inactive-ok)
17347 "Determine if the cursor is in or at a timestamp."
17348 (interactive)
17349 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17350 (pos (point))
17351 (ans (or (looking-at tsr)
17352 (save-excursion
17353 (skip-chars-backward "^[<\n\r\t")
17354 (if (> (point) (point-min)) (backward-char 1))
17355 (and (looking-at tsr)
17356 (> (- (match-end 0) pos) -1))))))
17357 (and ans
17358 (boundp 'org-ts-what)
17359 (setq org-ts-what
17360 (cond
17361 ((= pos (match-beginning 0)) 'bracket)
17362 ;; Point is considered to be "on the bracket" whether
17363 ;; it's really on it or right after it.
17364 ((= pos (1- (match-end 0))) 'bracket)
17365 ((= pos (match-end 0)) 'after)
17366 ((org-pos-in-match-range pos 2) 'year)
17367 ((org-pos-in-match-range pos 3) 'month)
17368 ((org-pos-in-match-range pos 7) 'hour)
17369 ((org-pos-in-match-range pos 8) 'minute)
17370 ((or (org-pos-in-match-range pos 4)
17371 (org-pos-in-match-range pos 5)) 'day)
17372 ((and (> pos (or (match-end 8) (match-end 5)))
17373 (< pos (match-end 0)))
17374 (- pos (or (match-end 8) (match-end 5))))
17375 (t 'day))))
17376 ans))
17377
17378 (defun org-toggle-timestamp-type ()
17379 "Toggle the type (<active> or [inactive]) of a time stamp."
17380 (interactive)
17381 (when (org-at-timestamp-p t)
17382 (let ((beg (match-beginning 0)) (end (match-end 0))
17383 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17384 (save-excursion
17385 (goto-char beg)
17386 (while (re-search-forward "[][<>]" end t)
17387 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17388 t t)))
17389 (message "Timestamp is now %sactive"
17390 (if (equal (char-after beg) ?<) "" "in")))))
17391
17392 (defun org-at-clock-log-p nil
17393 "Is the cursor on the clock log line?"
17394 (save-excursion
17395 (move-beginning-of-line 1)
17396 (looking-at "^[ \t]*CLOCK:")))
17397
17398 (defvar org-clock-history) ; defined in org-clock.el
17399 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17400 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17401 "Change the date in the time stamp at point.
17402 The date will be changed by N times WHAT. WHAT can be `day', `month',
17403 `year', `minute', `second'. If WHAT is not given, the cursor position
17404 in the timestamp determines what will be changed.
17405 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17406 (let ((origin (point)) origin-cat
17407 with-hm inactive
17408 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17409 org-ts-what
17410 extra rem
17411 ts time time0 fixnext clrgx)
17412 (if (not (org-at-timestamp-p t))
17413 (user-error "Not at a timestamp"))
17414 (if (and (not what) (eq org-ts-what 'bracket))
17415 (org-toggle-timestamp-type)
17416 ;; Point isn't on brackets. Remember the part of the time-stamp
17417 ;; the point was in. Indeed, size of time-stamps may change,
17418 ;; but point must be kept in the same category nonetheless.
17419 (setq origin-cat org-ts-what)
17420 (if (and (not what) (not (eq org-ts-what 'day))
17421 org-display-custom-times
17422 (get-text-property (point) 'display)
17423 (not (get-text-property (1- (point)) 'display)))
17424 (setq org-ts-what 'day))
17425 (setq org-ts-what (or what org-ts-what)
17426 inactive (= (char-after (match-beginning 0)) ?\[)
17427 ts (match-string 0))
17428 (replace-match "")
17429 (when (string-match
17430 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17431 ts)
17432 (setq extra (match-string 1 ts))
17433 (if suppress-tmp-delay
17434 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17435 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17436 (setq with-hm t))
17437 (setq time0 (org-parse-time-string ts))
17438 (when (and updown
17439 (eq org-ts-what 'minute)
17440 (not current-prefix-arg))
17441 ;; This looks like s-up and s-down. Change by one rounding step.
17442 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17443 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17444 (setcar (cdr time0) (+ (nth 1 time0)
17445 (if (> n 0) (- rem) (- dm rem))))))
17446 (setq time
17447 (encode-time (or (car time0) 0)
17448 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17449 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17450 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17451 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17452 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17453 (nthcdr 6 time0)))
17454 (when (and (member org-ts-what '(hour minute))
17455 extra
17456 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17457 (setq extra (org-modify-ts-extra
17458 extra
17459 (if (eq org-ts-what 'hour) 2 5)
17460 n dm)))
17461 (when (integerp org-ts-what)
17462 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17463 (if (eq what 'calendar)
17464 (let ((cal-date (org-get-date-from-calendar)))
17465 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17466 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17467 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17468 (setcar time0 (or (car time0) 0))
17469 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17470 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17471 (setq time (apply 'encode-time time0))))
17472 ;; Insert the new time-stamp, and ensure point stays in the same
17473 ;; category as before (i.e. not after the last position in that
17474 ;; category).
17475 (let ((pos (point)))
17476 ;; Stay before inserted string. `save-excursion' is of no use.
17477 (setq org-last-changed-timestamp
17478 (org-insert-time-stamp time with-hm inactive nil nil extra))
17479 (goto-char pos))
17480 (save-match-data
17481 (looking-at org-ts-regexp3)
17482 (goto-char (cond
17483 ;; `day' category ends before `hour' if any, or at
17484 ;; the end of the day name.
17485 ((eq origin-cat 'day)
17486 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17487 ((eq origin-cat 'hour) (min (match-end 7) origin))
17488 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17489 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17490 ;; `year' and `month' have both fixed size: point
17491 ;; couldn't have moved into another part.
17492 (t origin))))
17493 ;; Update clock if on a CLOCK line.
17494 (org-clock-update-time-maybe)
17495 ;; Maybe adjust the closest clock in `org-clock-history'
17496 (when org-clock-adjust-closest
17497 (if (not (and (org-at-clock-log-p)
17498 (< 1 (length (delq nil (mapcar 'marker-position
17499 org-clock-history))))))
17500 (message "No clock to adjust")
17501 (cond ((save-excursion ; fix previous clock?
17502 (re-search-backward org-ts-regexp0 nil t)
17503 (org-looking-back (concat org-clock-string " \\[")))
17504 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17505 ((save-excursion ; fix next clock?
17506 (re-search-backward org-ts-regexp0 nil t)
17507 (looking-at (concat org-ts-regexp0 "\\] =>")))
17508 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17509 (save-window-excursion
17510 ;; Find closest clock to point, adjust the previous/next one in history
17511 (let* ((p (save-excursion (org-back-to-heading t)))
17512 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17513 (clfixnth
17514 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17515 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17516 (if (not clfixpos)
17517 (message "No clock to adjust")
17518 (save-excursion
17519 (org-goto-marker-or-bmk clfixpos)
17520 (org-show-subtree)
17521 (when (re-search-forward clrgx nil t)
17522 (goto-char (match-beginning 1))
17523 (let (org-clock-adjust-closest)
17524 (org-timestamp-change n org-ts-what updown))
17525 (message "Clock adjusted in %s for heading: %s"
17526 (file-name-nondirectory (buffer-file-name))
17527 (org-get-heading t t)))))))))
17528 ;; Try to recenter the calendar window, if any.
17529 (if (and org-calendar-follow-timestamp-change
17530 (get-buffer-window "*Calendar*" t)
17531 (memq org-ts-what '(day month year)))
17532 (org-recenter-calendar (time-to-days time))))))
17533
17534 (defun org-modify-ts-extra (s pos n dm)
17535 "Change the different parts of the lead-time and repeat fields in timestamp."
17536 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17537 ng h m new rem)
17538 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17539 (cond
17540 ((or (org-pos-in-match-range pos 2)
17541 (org-pos-in-match-range pos 3))
17542 (setq m (string-to-number (match-string 3 s))
17543 h (string-to-number (match-string 2 s)))
17544 (if (org-pos-in-match-range pos 2)
17545 (setq h (+ h n))
17546 (setq n (* dm (org-no-warnings (signum n))))
17547 (when (not (= 0 (setq rem (% m dm))))
17548 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17549 (setq m (+ m n)))
17550 (if (< m 0) (setq m (+ m 60) h (1- h)))
17551 (if (> m 59) (setq m (- m 60) h (1+ h)))
17552 (setq h (min 24 (max 0 h)))
17553 (setq ng 1 new (format "-%02d:%02d" h m)))
17554 ((org-pos-in-match-range pos 6)
17555 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17556 ((org-pos-in-match-range pos 5)
17557 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17558
17559 ((org-pos-in-match-range pos 9)
17560 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17561 ((org-pos-in-match-range pos 8)
17562 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17563
17564 (when ng
17565 (setq s (concat
17566 (substring s 0 (match-beginning ng))
17567 new
17568 (substring s (match-end ng))))))
17569 s))
17570
17571 (defun org-recenter-calendar (date)
17572 "If the calendar is visible, recenter it to DATE."
17573 (let ((cwin (get-buffer-window "*Calendar*" t)))
17574 (when cwin
17575 (let ((calendar-move-hook nil))
17576 (with-selected-window cwin
17577 (calendar-goto-date (if (listp date) date
17578 (calendar-gregorian-from-absolute date))))))))
17579
17580 (defun org-goto-calendar (&optional arg)
17581 "Go to the Emacs calendar at the current date.
17582 If there is a time stamp in the current line, go to that date.
17583 A prefix ARG can be used to force the current date."
17584 (interactive "P")
17585 (let ((tsr org-ts-regexp) diff
17586 (calendar-move-hook nil)
17587 (calendar-view-holidays-initially-flag nil)
17588 (calendar-view-diary-initially-flag nil))
17589 (if (or (org-at-timestamp-p)
17590 (save-excursion
17591 (beginning-of-line 1)
17592 (looking-at (concat ".*" tsr))))
17593 (let ((d1 (time-to-days (current-time)))
17594 (d2 (time-to-days
17595 (org-time-string-to-time (match-string 1)))))
17596 (setq diff (- d2 d1))))
17597 (calendar)
17598 (calendar-goto-today)
17599 (if (and diff (not arg)) (calendar-forward-day diff))))
17600
17601 (defun org-get-date-from-calendar ()
17602 "Return a list (month day year) of date at point in calendar."
17603 (with-current-buffer "*Calendar*"
17604 (save-match-data
17605 (calendar-cursor-to-date))))
17606
17607 (defun org-date-from-calendar ()
17608 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17609 If there is already a time stamp at the cursor position, update it."
17610 (interactive)
17611 (if (org-at-timestamp-p t)
17612 (org-timestamp-change 0 'calendar)
17613 (let ((cal-date (org-get-date-from-calendar)))
17614 (org-insert-time-stamp
17615 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17616
17617 (defcustom org-effort-durations
17618 `(("h" . 60)
17619 ("d" . ,(* 60 8))
17620 ("w" . ,(* 60 8 5))
17621 ("m" . ,(* 60 8 5 4))
17622 ("y" . ,(* 60 8 5 40)))
17623 "Conversion factor to minutes for an effort modifier.
17624
17625 Each entry has the form (MODIFIER . MINUTES).
17626
17627 In an effort string, a number followed by MODIFIER is multiplied
17628 by the specified number of MINUTES to obtain an effort in
17629 minutes.
17630
17631 For example, if the value of this variable is ((\"hours\" . 60)), then an
17632 effort string \"2hours\" is equivalent to 120 minutes."
17633 :group 'org-agenda
17634 :version "24.1"
17635 :type '(alist :key-type (string :tag "Modifier")
17636 :value-type (number :tag "Minutes")))
17637
17638 (defun org-minutes-to-clocksum-string (m)
17639 "Format number of minutes as a clocksum string.
17640 The format is determined by `org-time-clocksum-format',
17641 `org-time-clocksum-use-fractional' and
17642 `org-time-clocksum-fractional-format' and
17643 `org-time-clocksum-use-effort-durations'."
17644 (let ((clocksum "")
17645 (m (round m)) ; Don't allow fractions of minutes
17646 h d w mo y fmt n)
17647 (setq h (if org-time-clocksum-use-effort-durations
17648 (cdr (assoc "h" org-effort-durations)) 60)
17649 d (if org-time-clocksum-use-effort-durations
17650 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17651 w (if org-time-clocksum-use-effort-durations
17652 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17653 mo (if org-time-clocksum-use-effort-durations
17654 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17655 y (if org-time-clocksum-use-effort-durations
17656 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17657 ;; fractional format
17658 (if org-time-clocksum-use-fractional
17659 (cond
17660 ;; single format string
17661 ((stringp org-time-clocksum-fractional-format)
17662 (format org-time-clocksum-fractional-format (/ m (float h))))
17663 ;; choice of fractional formats for different time units
17664 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17665 (> (/ (truncate m) (* y d h)) 0))
17666 (format fmt (/ m (* y d (float h)))))
17667 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17668 (> (/ (truncate m) (* mo d h)) 0))
17669 (format fmt (/ m (* mo d (float h)))))
17670 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17671 (> (/ (truncate m) (* w d h)) 0))
17672 (format fmt (/ m (* w d (float h)))))
17673 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17674 (> (/ (truncate m) (* d h)) 0))
17675 (format fmt (/ m (* d (float h)))))
17676 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17677 (> (/ (truncate m) h) 0))
17678 (format fmt (/ m (float h))))
17679 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17680 (format fmt m))
17681 ;; fall back to smallest time unit with a format
17682 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17683 (format fmt (/ m (float h))))
17684 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17685 (format fmt (/ m (* d (float h)))))
17686 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17687 (format fmt (/ m (* w d (float h)))))
17688 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17689 (format fmt (/ m (* mo d (float h)))))
17690 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17691 (format fmt (/ m (* y d (float h))))))
17692 ;; standard (non-fractional) format, with single format string
17693 (if (stringp org-time-clocksum-format)
17694 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17695 ;; separate formats components
17696 (and (setq fmt (plist-get org-time-clocksum-format :years))
17697 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17698 (plist-get org-time-clocksum-format :require-years))
17699 (setq clocksum (concat clocksum (format fmt n))
17700 m (- m (* n y d h))))
17701 (and (setq fmt (plist-get org-time-clocksum-format :months))
17702 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17703 (plist-get org-time-clocksum-format :require-months))
17704 (setq clocksum (concat clocksum (format fmt n))
17705 m (- m (* n mo d h))))
17706 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17707 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17708 (plist-get org-time-clocksum-format :require-weeks))
17709 (setq clocksum (concat clocksum (format fmt n))
17710 m (- m (* n w d h))))
17711 (and (setq fmt (plist-get org-time-clocksum-format :days))
17712 (or (> (setq n (/ (truncate m) (* d h))) 0)
17713 (plist-get org-time-clocksum-format :require-days))
17714 (setq clocksum (concat clocksum (format fmt n))
17715 m (- m (* n d h))))
17716 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17717 (or (> (setq n (/ (truncate m) h)) 0)
17718 (plist-get org-time-clocksum-format :require-hours))
17719 (setq clocksum (concat clocksum (format fmt n))
17720 m (- m (* n h))))
17721 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17722 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17723 (setq clocksum (concat clocksum (format fmt m))))
17724 ;; return formatted time duration
17725 clocksum))))
17726
17727 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17728 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17729 "Org mode version 8.0")
17730
17731 (defun org-hours-to-clocksum-string (n)
17732 (org-minutes-to-clocksum-string (* n 60)))
17733
17734 (defun org-hh:mm-string-to-minutes (s)
17735 "Convert a string H:MM to a number of minutes.
17736 If the string is just a number, interpret it as minutes.
17737 In fact, the first hh:mm or number in the string will be taken,
17738 there can be extra stuff in the string.
17739 If no number is found, the return value is 0."
17740 (cond
17741 ((integerp s) s)
17742 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17743 (+ (* (string-to-number (match-string 1 s)) 60)
17744 (string-to-number (match-string 2 s))))
17745 ((string-match "\\([0-9]+\\)" s)
17746 (string-to-number (match-string 1 s)))
17747 (t 0)))
17748
17749 (defcustom org-image-actual-width t
17750 "Should we use the actual width of images when inlining them?
17751
17752 When set to `t', always use the image width.
17753
17754 When set to a number, use imagemagick (when available) to set
17755 the image's width to this value.
17756
17757 When set to a number in a list, try to get the width from any
17758 #+ATTR.* keyword if it matches a width specification like
17759
17760 #+ATTR_HTML: :width 300px
17761
17762 and fall back on that number if none is found.
17763
17764 When set to nil, try to get the width from an #+ATTR.* keyword
17765 and fall back on the original width if none is found.
17766
17767 This requires Emacs >= 24.1, build with imagemagick support."
17768 :group 'org-appearance
17769 :version "24.4"
17770 :package-version '(Org . "8.0")
17771 :type '(choice
17772 (const :tag "Use the image width" t)
17773 (integer :tag "Use a number of pixels")
17774 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17775 (const :tag "Use #+ATTR* or don't resize" nil)))
17776
17777 (defcustom org-agenda-inhibit-startup nil
17778 "Inhibit startup when preparing agenda buffers.
17779 When this variable is `t', the initialization of the Org agenda
17780 buffers is inhibited: e.g. the visibility state is not set, the
17781 tables are not re-aligned, etc."
17782 :type 'boolean
17783 :version "24.3"
17784 :group 'org-agenda)
17785
17786 (defcustom org-agenda-ignore-drawer-properties nil
17787 "Avoid updating text properties when building the agenda.
17788 Properties are used to prepare buffers for effort estimates, appointments,
17789 and subtree-local categories.
17790 If you don't use these in the agenda, you can add them to this list and
17791 agenda building will be a bit faster.
17792 The value is a list, with zero or more of the symbols `effort', `appt',
17793 or `category'."
17794 :type '(set :greedy t
17795 (const effort)
17796 (const appt)
17797 (const category))
17798 :version "24.3"
17799 :group 'org-agenda)
17800
17801 (defun org-duration-string-to-minutes (s &optional output-to-string)
17802 "Convert a duration string S to minutes.
17803
17804 A bare number is interpreted as minutes, modifiers can be set by
17805 customizing `org-effort-durations' (which see).
17806
17807 Entries containing a colon are interpreted as H:MM by
17808 `org-hh:mm-string-to-minutes'."
17809 (let ((result 0)
17810 (re (concat "\\([0-9.]+\\) *\\("
17811 (regexp-opt (mapcar 'car org-effort-durations))
17812 "\\)")))
17813 (while (string-match re s)
17814 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17815 (string-to-number (match-string 1 s))))
17816 (setq s (replace-match "" nil t s)))
17817 (setq result (floor result))
17818 (incf result (org-hh:mm-string-to-minutes s))
17819 (if output-to-string (number-to-string result) result)))
17820
17821 ;;;; Files
17822
17823 (defun org-save-all-org-buffers ()
17824 "Save all Org-mode buffers without user confirmation."
17825 (interactive)
17826 (message "Saving all Org-mode buffers...")
17827 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17828 (when (featurep 'org-id) (org-id-locations-save))
17829 (message "Saving all Org-mode buffers... done"))
17830
17831 (defun org-revert-all-org-buffers ()
17832 "Revert all Org-mode buffers.
17833 Prompt for confirmation when there are unsaved changes.
17834 Be sure you know what you are doing before letting this function
17835 overwrite your changes.
17836
17837 This function is useful in a setup where one tracks org files
17838 with a version control system, to revert on one machine after pulling
17839 changes from another. I believe the procedure must be like this:
17840
17841 1. M-x org-save-all-org-buffers
17842 2. Pull changes from the other machine, resolve conflicts
17843 3. M-x org-revert-all-org-buffers"
17844 (interactive)
17845 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17846 (user-error "Abort"))
17847 (save-excursion
17848 (save-window-excursion
17849 (mapc
17850 (lambda (b)
17851 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17852 (with-current-buffer b buffer-file-name))
17853 (org-pop-to-buffer-same-window b)
17854 (revert-buffer t 'no-confirm)))
17855 (buffer-list))
17856 (when (and (featurep 'org-id) org-id-track-globally)
17857 (org-id-locations-load)))))
17858
17859 ;;;; Agenda files
17860
17861 ;;;###autoload
17862 (defun org-switchb (&optional arg)
17863 "Switch between Org buffers.
17864 With one prefix argument, restrict available buffers to files.
17865 With two prefix arguments, restrict available buffers to agenda files.
17866
17867 Defaults to `iswitchb' for buffer name completion.
17868 Set `org-completion-use-ido' to make it use ido instead."
17869 (interactive "P")
17870 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17871 ((equal arg '(16)) (org-buffer-list 'agenda))
17872 (t (org-buffer-list))))
17873 (org-completion-use-iswitchb org-completion-use-iswitchb)
17874 (org-completion-use-ido org-completion-use-ido))
17875 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17876 (setq org-completion-use-iswitchb t))
17877 (org-pop-to-buffer-same-window
17878 (org-icompleting-read "Org buffer: "
17879 (mapcar 'list (mapcar 'buffer-name blist))
17880 nil t))))
17881
17882 ;;; Define some older names previously used for this functionality
17883 ;;;###autoload
17884 (defalias 'org-ido-switchb 'org-switchb)
17885 ;;;###autoload
17886 (defalias 'org-iswitchb 'org-switchb)
17887
17888 (defun org-buffer-list (&optional predicate exclude-tmp)
17889 "Return a list of Org buffers.
17890 PREDICATE can be `export', `files' or `agenda'.
17891
17892 export restrict the list to Export buffers.
17893 files restrict the list to buffers visiting Org files.
17894 agenda restrict the list to buffers visiting agenda files.
17895
17896 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17897 (let* ((bfn nil)
17898 (agenda-files (and (eq predicate 'agenda)
17899 (mapcar 'file-truename (org-agenda-files t))))
17900 (filter
17901 (cond
17902 ((eq predicate 'files)
17903 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17904 ((eq predicate 'export)
17905 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17906 ((eq predicate 'agenda)
17907 (lambda (b)
17908 (with-current-buffer b
17909 (and (derived-mode-p 'org-mode)
17910 (setq bfn (buffer-file-name b))
17911 (member (file-truename bfn) agenda-files)))))
17912 (t (lambda (b) (with-current-buffer b
17913 (or (derived-mode-p 'org-mode)
17914 (string-match "\*Org .*Export"
17915 (buffer-name b)))))))))
17916 (delq nil
17917 (mapcar
17918 (lambda(b)
17919 (if (and (funcall filter b)
17920 (or (not exclude-tmp)
17921 (not (string-match "tmp" (buffer-name b)))))
17922 b
17923 nil))
17924 (buffer-list)))))
17925
17926 (defun org-agenda-files (&optional unrestricted archives)
17927 "Get the list of agenda files.
17928 Optional UNRESTRICTED means return the full list even if a restriction
17929 is currently in place.
17930 When ARCHIVES is t, include all archive files that are really being
17931 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17932 `org-agenda-archives-mode' is t."
17933 (let ((files
17934 (cond
17935 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17936 ((stringp org-agenda-files) (org-read-agenda-file-list))
17937 ((listp org-agenda-files) org-agenda-files)
17938 (t (error "Invalid value of `org-agenda-files'")))))
17939 (setq files (apply 'append
17940 (mapcar (lambda (f)
17941 (if (file-directory-p f)
17942 (directory-files
17943 f t org-agenda-file-regexp)
17944 (list f)))
17945 files)))
17946 (when org-agenda-skip-unavailable-files
17947 (setq files (delq nil
17948 (mapcar (function
17949 (lambda (file)
17950 (and (file-readable-p file) file)))
17951 files))))
17952 (when (or (eq archives t)
17953 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17954 (setq files (org-add-archive-files files)))
17955 files))
17956
17957 (defun org-agenda-file-p (&optional file)
17958 "Return non-nil, if FILE is an agenda file.
17959 If FILE is omitted, use the file associated with the current
17960 buffer."
17961 (member (or file (buffer-file-name))
17962 (org-agenda-files t)))
17963
17964 (defun org-edit-agenda-file-list ()
17965 "Edit the list of agenda files.
17966 Depending on setup, this either uses customize to edit the variable
17967 `org-agenda-files', or it visits the file that is holding the list. In the
17968 latter case, the buffer is set up in a way that saving it automatically kills
17969 the buffer and restores the previous window configuration."
17970 (interactive)
17971 (if (stringp org-agenda-files)
17972 (let ((cw (current-window-configuration)))
17973 (find-file org-agenda-files)
17974 (org-set-local 'org-window-configuration cw)
17975 (org-add-hook 'after-save-hook
17976 (lambda ()
17977 (set-window-configuration
17978 (prog1 org-window-configuration
17979 (kill-buffer (current-buffer))))
17980 (org-install-agenda-files-menu)
17981 (message "New agenda file list installed"))
17982 nil 'local)
17983 (message "%s" (substitute-command-keys
17984 "Edit list and finish with \\[save-buffer]")))
17985 (customize-variable 'org-agenda-files)))
17986
17987 (defun org-store-new-agenda-file-list (list)
17988 "Set new value for the agenda file list and save it correctly."
17989 (if (stringp org-agenda-files)
17990 (let ((fe (org-read-agenda-file-list t)) b u)
17991 (while (setq b (find-buffer-visiting org-agenda-files))
17992 (kill-buffer b))
17993 (with-temp-file org-agenda-files
17994 (insert
17995 (mapconcat
17996 (lambda (f) ;; Keep un-expanded entries.
17997 (if (setq u (assoc f fe))
17998 (cdr u)
17999 f))
18000 list "\n")
18001 "\n")))
18002 (let ((org-mode-hook nil) (org-inhibit-startup t)
18003 (org-insert-mode-line-in-empty-file nil))
18004 (setq org-agenda-files list)
18005 (customize-save-variable 'org-agenda-files org-agenda-files))))
18006
18007 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18008 "Read the list of agenda files from a file.
18009 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18010 filenames, used by `org-store-new-agenda-file-list' to write back
18011 un-expanded file names."
18012 (when (file-directory-p org-agenda-files)
18013 (error "`org-agenda-files' cannot be a single directory"))
18014 (when (stringp org-agenda-files)
18015 (with-temp-buffer
18016 (insert-file-contents org-agenda-files)
18017 (mapcar
18018 (lambda (f)
18019 (let ((e (expand-file-name (substitute-in-file-name f)
18020 org-directory)))
18021 (if pair-with-expansion
18022 (cons e f)
18023 e)))
18024 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18025
18026 ;;;###autoload
18027 (defun org-cycle-agenda-files ()
18028 "Cycle through the files in `org-agenda-files'.
18029 If the current buffer visits an agenda file, find the next one in the list.
18030 If the current buffer does not, find the first agenda file."
18031 (interactive)
18032 (let* ((fs (org-agenda-files t))
18033 (files (append fs (list (car fs))))
18034 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18035 file)
18036 (unless files (user-error "No agenda files"))
18037 (catch 'exit
18038 (while (setq file (pop files))
18039 (if (equal (file-truename file) tcf)
18040 (when (car files)
18041 (find-file (car files))
18042 (throw 'exit t))))
18043 (find-file (car fs)))
18044 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18045
18046 (defun org-agenda-file-to-front (&optional to-end)
18047 "Move/add the current file to the top of the agenda file list.
18048 If the file is not present in the list, it is added to the front. If it is
18049 present, it is moved there. With optional argument TO-END, add/move to the
18050 end of the list."
18051 (interactive "P")
18052 (let ((org-agenda-skip-unavailable-files nil)
18053 (file-alist (mapcar (lambda (x)
18054 (cons (file-truename x) x))
18055 (org-agenda-files t)))
18056 (ctf (file-truename
18057 (or buffer-file-name
18058 (user-error "Please save the current buffer to a file"))))
18059 x had)
18060 (setq x (assoc ctf file-alist) had x)
18061
18062 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18063 (if to-end
18064 (setq file-alist (append (delq x file-alist) (list x)))
18065 (setq file-alist (cons x (delq x file-alist))))
18066 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18067 (org-install-agenda-files-menu)
18068 (message "File %s to %s of agenda file list"
18069 (if had "moved" "added") (if to-end "end" "front"))))
18070
18071 (defun org-remove-file (&optional file)
18072 "Remove current file from the list of files in variable `org-agenda-files'.
18073 These are the files which are being checked for agenda entries.
18074 Optional argument FILE means use this file instead of the current."
18075 (interactive)
18076 (let* ((org-agenda-skip-unavailable-files nil)
18077 (file (or file buffer-file-name
18078 (user-error "Current buffer does not visit a file")))
18079 (true-file (file-truename file))
18080 (afile (abbreviate-file-name file))
18081 (files (delq nil (mapcar
18082 (lambda (x)
18083 (if (equal true-file
18084 (file-truename x))
18085 nil x))
18086 (org-agenda-files t)))))
18087 (if (not (= (length files) (length (org-agenda-files t))))
18088 (progn
18089 (org-store-new-agenda-file-list files)
18090 (org-install-agenda-files-menu)
18091 (message "Removed file: %s" afile))
18092 (message "File was not in list: %s (not removed)" afile))))
18093
18094 (defun org-file-menu-entry (file)
18095 (vector file (list 'find-file file) t))
18096
18097 (defun org-check-agenda-file (file)
18098 "Make sure FILE exists. If not, ask user what to do."
18099 (when (not (file-exists-p file))
18100 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18101 (abbreviate-file-name file))
18102 (let ((r (downcase (read-char-exclusive))))
18103 (cond
18104 ((equal r ?r)
18105 (org-remove-file file)
18106 (throw 'nextfile t))
18107 (t (error "Abort"))))))
18108
18109 (defun org-get-agenda-file-buffer (file)
18110 "Get a buffer visiting FILE. If the buffer needs to be created, add
18111 it to the list of buffers which might be released later."
18112 (let ((buf (org-find-base-buffer-visiting file)))
18113 (if buf
18114 buf ; just return it
18115 ;; Make a new buffer and remember it
18116 (setq buf (find-file-noselect file))
18117 (if buf (push buf org-agenda-new-buffers))
18118 buf)))
18119
18120 (defun org-release-buffers (blist)
18121 "Release all buffers in list, asking the user for confirmation when needed.
18122 When a buffer is unmodified, it is just killed. When modified, it is saved
18123 \(if the user agrees) and then killed."
18124 (let (buf file)
18125 (while (setq buf (pop blist))
18126 (setq file (buffer-file-name buf))
18127 (when (and (buffer-modified-p buf)
18128 file
18129 (y-or-n-p (format "Save file %s? " file)))
18130 (with-current-buffer buf (save-buffer)))
18131 (kill-buffer buf))))
18132
18133 (defun org-agenda-prepare-buffers (files)
18134 "Create buffers for all agenda files, protect archived trees and comments."
18135 (interactive)
18136 (let ((pa '(:org-archived t))
18137 (pc '(:org-comment t))
18138 (pall '(:org-archived t :org-comment t))
18139 (inhibit-read-only t)
18140 (org-inhibit-startup org-agenda-inhibit-startup)
18141 (rea (concat ":" org-archive-tag ":"))
18142 file re pos)
18143 (setq org-tag-alist-for-agenda nil
18144 org-tag-groups-alist-for-agenda nil)
18145 (save-excursion
18146 (save-restriction
18147 (while (setq file (pop files))
18148 (catch 'nextfile
18149 (if (bufferp file)
18150 (set-buffer file)
18151 (org-check-agenda-file file)
18152 (set-buffer (org-get-agenda-file-buffer file)))
18153 (widen)
18154 (org-set-regexps-and-options-for-tags)
18155 (setq pos (point))
18156 (goto-char (point-min))
18157 (let ((case-fold-search t))
18158 (when (search-forward "#+setupfile" nil t)
18159 ;; Don't set all regexps and options systematically as
18160 ;; this is only run for setting agenda tags from setup
18161 ;; file
18162 (org-set-regexps-and-options)))
18163 (or (memq 'category org-agenda-ignore-drawer-properties)
18164 (org-refresh-category-properties))
18165 (or (memq 'effort org-agenda-ignore-drawer-properties)
18166 (org-refresh-properties org-effort-property 'org-effort))
18167 (or (memq 'appt org-agenda-ignore-drawer-properties)
18168 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18169 (setq org-todo-keywords-for-agenda
18170 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18171 (setq org-done-keywords-for-agenda
18172 (append org-done-keywords-for-agenda org-done-keywords))
18173 (setq org-todo-keyword-alist-for-agenda
18174 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18175 (setq org-drawers-for-agenda
18176 (append org-drawers-for-agenda org-drawers))
18177 (setq org-tag-alist-for-agenda
18178 (org-uniquify
18179 (append org-tag-alist-for-agenda
18180 org-tag-alist
18181 org-tag-persistent-alist)))
18182 (if org-group-tags
18183 (setq org-tag-groups-alist-for-agenda
18184 (org-uniquify-alist
18185 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18186 (org-with-silent-modifications
18187 (save-excursion
18188 (remove-text-properties (point-min) (point-max) pall)
18189 (when org-agenda-skip-archived-trees
18190 (goto-char (point-min))
18191 (while (re-search-forward rea nil t)
18192 (if (org-at-heading-p t)
18193 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18194 (goto-char (point-min))
18195 (setq re (format org-heading-keyword-regexp-format
18196 org-comment-string))
18197 (while (re-search-forward re nil t)
18198 (add-text-properties
18199 (match-beginning 0) (org-end-of-subtree t) pc))))
18200 (goto-char pos)))))
18201 (setq org-todo-keywords-for-agenda
18202 (org-uniquify org-todo-keywords-for-agenda))
18203 (setq org-todo-keyword-alist-for-agenda
18204 (org-uniquify org-todo-keyword-alist-for-agenda))))
18205
18206 \f
18207 ;;;; CDLaTeX minor mode
18208
18209 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18210 "Keymap for the minor `org-cdlatex-mode'.")
18211
18212 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18213 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18214 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18215 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18216 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18217
18218 (defvar org-cdlatex-texmathp-advice-is-done nil
18219 "Flag remembering if we have applied the advice to texmathp already.")
18220
18221 (define-minor-mode org-cdlatex-mode
18222 "Toggle the minor `org-cdlatex-mode'.
18223 This mode supports entering LaTeX environment and math in LaTeX fragments
18224 in Org-mode.
18225 \\{org-cdlatex-mode-map}"
18226 nil " OCDL" nil
18227 (when org-cdlatex-mode
18228 (require 'cdlatex)
18229 (run-hooks 'cdlatex-mode-hook)
18230 (cdlatex-compute-tables))
18231 (unless org-cdlatex-texmathp-advice-is-done
18232 (setq org-cdlatex-texmathp-advice-is-done t)
18233 (defadvice texmathp (around org-math-always-on activate)
18234 "Always return t in org-mode buffers.
18235 This is because we want to insert math symbols without dollars even outside
18236 the LaTeX math segments. If Orgmode thinks that point is actually inside
18237 an embedded LaTeX fragment, let texmathp do its job.
18238 \\[org-cdlatex-mode-map]"
18239 (interactive)
18240 (let (p)
18241 (cond
18242 ((not (derived-mode-p 'org-mode)) ad-do-it)
18243 ((eq this-command 'cdlatex-math-symbol)
18244 (setq ad-return-value t
18245 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18246 (t
18247 (let ((p (org-inside-LaTeX-fragment-p)))
18248 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18249 (setq ad-return-value t
18250 texmathp-why '("Org-mode embedded math" . 0))
18251 (if p ad-do-it)))))))))
18252
18253 (defun turn-on-org-cdlatex ()
18254 "Unconditionally turn on `org-cdlatex-mode'."
18255 (org-cdlatex-mode 1))
18256
18257 (defun org-try-cdlatex-tab ()
18258 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18259 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18260 - inside a LaTeX fragment, or
18261 - after the first word in a line, where an abbreviation expansion could
18262 insert a LaTeX environment."
18263 (when org-cdlatex-mode
18264 (cond
18265 ;; Before any word on the line: No expansion possible.
18266 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18267 ;; Just after first word on the line: Expand it. Make sure it
18268 ;; cannot happen on headlines, though.
18269 ((save-excursion
18270 (skip-chars-backward "a-zA-Z0-9*")
18271 (skip-chars-backward " \t")
18272 (and (bolp) (not (org-at-heading-p))))
18273 (cdlatex-tab) t)
18274 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18275
18276 (defun org-cdlatex-underscore-caret (&optional arg)
18277 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18278 Revert to the normal definition outside of these fragments."
18279 (interactive "P")
18280 (if (org-inside-LaTeX-fragment-p)
18281 (call-interactively 'cdlatex-sub-superscript)
18282 (let (org-cdlatex-mode)
18283 (call-interactively (key-binding (vector last-input-event))))))
18284
18285 (defun org-cdlatex-math-modify (&optional arg)
18286 "Execute `cdlatex-math-modify' in LaTeX fragments.
18287 Revert to the normal definition outside of these fragments."
18288 (interactive "P")
18289 (if (org-inside-LaTeX-fragment-p)
18290 (call-interactively 'cdlatex-math-modify)
18291 (let (org-cdlatex-mode)
18292 (call-interactively (key-binding (vector last-input-event))))))
18293
18294
18295 \f
18296 ;;;; LaTeX fragments
18297
18298 (defvar org-latex-regexps
18299 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18300 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18301 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18302 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18303 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18304 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18305 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18306 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18307 "Regular expressions for matching embedded LaTeX.")
18308
18309 (defun org-inside-LaTeX-fragment-p ()
18310 "Test if point is inside a LaTeX fragment.
18311 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18312 sequence appearing also before point.
18313 Even though the matchers for math are configurable, this function assumes
18314 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18315 delimiters are skipped when they have been removed by customization.
18316 The return value is nil, or a cons cell with the delimiter and the
18317 position of this delimiter.
18318
18319 This function does a reasonably good job, but can locally be fooled by
18320 for example currency specifications. For example it will assume being in
18321 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18322 fragments that are properly closed, but during editing, we have to live
18323 with the uncertainty caused by missing closing delimiters. This function
18324 looks only before point, not after."
18325 (catch 'exit
18326 (let ((pos (point))
18327 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18328 (lim (progn
18329 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18330 (point)))
18331 dd-on str (start 0) m re)
18332 (goto-char pos)
18333 (when dodollar
18334 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18335 re (nth 1 (assoc "$" org-latex-regexps)))
18336 (while (string-match re str start)
18337 (cond
18338 ((= (match-end 0) (length str))
18339 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18340 ((= (match-end 0) (- (length str) 5))
18341 (throw 'exit nil))
18342 (t (setq start (match-end 0))))))
18343 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18344 (goto-char pos)
18345 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18346 (and (match-beginning 2) (throw 'exit nil))
18347 ;; count $$
18348 (while (re-search-backward "\\$\\$" lim t)
18349 (setq dd-on (not dd-on)))
18350 (goto-char pos)
18351 (if dd-on (cons "$$" m))))))
18352
18353 (defun org-inside-latex-macro-p ()
18354 "Is point inside a LaTeX macro or its arguments?"
18355 (save-match-data
18356 (org-in-regexp
18357 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18358
18359 (defvar org-latex-fragment-image-overlays nil
18360 "List of overlays carrying the images of latex fragments.")
18361 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18362
18363 (defun org-remove-latex-fragment-image-overlays ()
18364 "Remove all overlays with LaTeX fragment images in current buffer."
18365 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18366 (setq org-latex-fragment-image-overlays nil))
18367
18368 (defun org-preview-latex-fragment (&optional subtree)
18369 "Preview the LaTeX fragment at point, or all locally or globally.
18370 If the cursor is in a LaTeX fragment, create the image and overlay
18371 it over the source code. If there is no fragment at point, display
18372 all fragments in the current text, from one headline to the next. With
18373 prefix SUBTREE, display all fragments in the current subtree. With a
18374 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18375 the cursor is before the first headline,
18376 display all fragments in the buffer.
18377 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18378 (interactive "P")
18379 (unless buffer-file-name
18380 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18381 (when (display-graphic-p)
18382 (org-remove-latex-fragment-image-overlays)
18383 (save-excursion
18384 (save-restriction
18385 (let (beg end at msg)
18386 (cond
18387 ((or (equal subtree '(16))
18388 (not (save-excursion
18389 (re-search-backward org-outline-regexp-bol nil t))))
18390 (setq beg (point-min) end (point-max)
18391 msg "Creating images for buffer...%s"))
18392 ((equal subtree '(4))
18393 (org-back-to-heading)
18394 (setq beg (point) end (org-end-of-subtree t)
18395 msg "Creating images for subtree...%s"))
18396 (t
18397 (if (setq at (org-inside-LaTeX-fragment-p))
18398 (goto-char (max (point-min) (- (cdr at) 2)))
18399 (org-back-to-heading))
18400 (setq beg (point) end (progn (outline-next-heading) (point))
18401 msg (if at "Creating image...%s"
18402 "Creating images for entry...%s"))))
18403 (message msg "")
18404 (narrow-to-region beg end)
18405 (goto-char beg)
18406 (org-format-latex
18407 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18408 (file-name-nondirectory
18409 buffer-file-name)))
18410 default-directory 'overlays msg at 'forbuffer
18411 org-latex-create-formula-image-program)
18412 (message msg "done. Use `C-c C-c' to remove images."))))))
18413
18414 (defun org-format-latex (prefix &optional dir overlays msg at
18415 forbuffer processing-type)
18416 "Replace LaTeX fragments with links to an image, and produce images.
18417 Some of the options can be changed using the variable
18418 `org-format-latex-options'."
18419 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18420 (let* ((prefixnodir (file-name-nondirectory prefix))
18421 (absprefix (expand-file-name prefix dir))
18422 (todir (file-name-directory absprefix))
18423 (opt org-format-latex-options)
18424 (optnew org-format-latex-options)
18425 (matchers (plist-get opt :matchers))
18426 (re-list org-latex-regexps)
18427 (cnt 0) txt hash link beg end re e checkdir
18428 string
18429 m n block-type block linkfile movefile ov)
18430 ;; Check the different regular expressions
18431 (while (setq e (pop re-list))
18432 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18433 block (if block-type "\n\n" ""))
18434 (when (member m matchers)
18435 (goto-char (point-min))
18436 (while (re-search-forward re nil t)
18437 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18438 (or (not overlays)
18439 (not (eq (get-char-property (match-beginning n)
18440 'org-overlay-type)
18441 'org-latex-overlay))))
18442 (cond
18443 ((eq processing-type 'verbatim))
18444 ((eq processing-type 'mathjax)
18445 ;; Prepare for MathJax processing.
18446 (setq string (match-string n))
18447 (when (member m '("$" "$1"))
18448 (save-excursion
18449 (delete-region (match-beginning n) (match-end n))
18450 (goto-char (match-beginning n))
18451 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18452 ((or (eq processing-type 'dvipng)
18453 (eq processing-type 'imagemagick))
18454 ;; Process to an image.
18455 (setq txt (match-string n)
18456 beg (match-beginning n) end (match-end n)
18457 cnt (1+ cnt))
18458 (let ((face (face-at-point))
18459 (fg (plist-get opt :foreground))
18460 (bg (plist-get opt :background))
18461 ;; Ensure full list is printed.
18462 print-length print-level)
18463 (when forbuffer
18464 ;; Get the colors from the face at point.
18465 (goto-char beg)
18466 (when (eq fg 'auto)
18467 (setq fg (face-attribute face :foreground nil 'default)))
18468 (when (eq bg 'auto)
18469 (setq bg (face-attribute face :background nil 'default)))
18470 (setq optnew (copy-sequence opt))
18471 (plist-put optnew :foreground fg)
18472 (plist-put optnew :background bg))
18473 (setq hash (sha1 (prin1-to-string
18474 (list org-format-latex-header
18475 org-latex-default-packages-alist
18476 org-latex-packages-alist
18477 org-format-latex-options
18478 forbuffer txt fg bg)))
18479 linkfile (format "%s_%s.png" prefix hash)
18480 movefile (format "%s_%s.png" absprefix hash)))
18481 (setq link (concat block "[[file:" linkfile "]]" block))
18482 (if msg (message msg cnt))
18483 (goto-char beg)
18484 (unless checkdir ; Ensure the directory exists.
18485 (setq checkdir t)
18486 (or (file-directory-p todir) (make-directory todir t)))
18487 (unless (file-exists-p movefile)
18488 (org-create-formula-image
18489 txt movefile optnew forbuffer processing-type))
18490 (if overlays
18491 (progn
18492 (mapc (lambda (o)
18493 (if (eq (overlay-get o 'org-overlay-type)
18494 'org-latex-overlay)
18495 (delete-overlay o)))
18496 (overlays-in beg end))
18497 (setq ov (make-overlay beg end))
18498 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18499 (if (featurep 'xemacs)
18500 (progn
18501 (overlay-put ov 'invisible t)
18502 (overlay-put
18503 ov 'end-glyph
18504 (make-glyph (vector 'png :file movefile))))
18505 (overlay-put
18506 ov 'display
18507 (list 'image :type 'png :file movefile :ascent 'center)))
18508 (push ov org-latex-fragment-image-overlays)
18509 (goto-char end))
18510 (delete-region beg end)
18511 (insert (org-add-props link
18512 (list 'org-latex-src
18513 (replace-regexp-in-string
18514 "\"" "" txt)
18515 'org-latex-src-embed-type
18516 (if block-type 'paragraph 'character))))))
18517 ((eq processing-type 'mathml)
18518 ;; Process to MathML
18519 (unless (save-match-data (org-format-latex-mathml-available-p))
18520 (user-error "LaTeX to MathML converter not configured"))
18521 (setq txt (match-string n)
18522 beg (match-beginning n) end (match-end n)
18523 cnt (1+ cnt))
18524 (if msg (message msg cnt))
18525 (goto-char beg)
18526 (delete-region beg end)
18527 (insert (org-format-latex-as-mathml
18528 txt block-type prefix dir)))
18529 (t
18530 (error "Unknown conversion type %s for LaTeX fragments"
18531 processing-type)))))))))
18532
18533 (defun org-create-math-formula (latex-frag &optional mathml-file)
18534 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18535 Use `org-latex-to-mathml-convert-command'. If the conversion is
18536 sucessful, return the portion between \"<math...> </math>\"
18537 elements otherwise return nil. When MATHML-FILE is specified,
18538 write the results in to that file. When invoked as an
18539 interactive command, prompt for LATEX-FRAG, with initial value
18540 set to the current active region and echo the results for user
18541 inspection."
18542 (interactive (list (let ((frag (when (org-region-active-p)
18543 (buffer-substring-no-properties
18544 (region-beginning) (region-end)))))
18545 (read-string "LaTeX Fragment: " frag nil frag))))
18546 (unless latex-frag (error "Invalid LaTeX fragment"))
18547 (let* ((tmp-in-file (file-relative-name
18548 (make-temp-name (expand-file-name "ltxmathml-in"))))
18549 (ignore (write-region latex-frag nil tmp-in-file))
18550 (tmp-out-file (file-relative-name
18551 (make-temp-name (expand-file-name "ltxmathml-out"))))
18552 (cmd (format-spec
18553 org-latex-to-mathml-convert-command
18554 `((?j . ,(shell-quote-argument
18555 (expand-file-name org-latex-to-mathml-jar-file)))
18556 (?I . ,(shell-quote-argument tmp-in-file))
18557 (?o . ,(shell-quote-argument tmp-out-file)))))
18558 mathml shell-command-output)
18559 (when (org-called-interactively-p 'any)
18560 (unless (org-format-latex-mathml-available-p)
18561 (user-error "LaTeX to MathML converter not configured")))
18562 (message "Running %s" cmd)
18563 (setq shell-command-output (shell-command-to-string cmd))
18564 (setq mathml
18565 (when (file-readable-p tmp-out-file)
18566 (with-current-buffer (find-file-noselect tmp-out-file t)
18567 (goto-char (point-min))
18568 (when (re-search-forward
18569 (concat
18570 (regexp-quote
18571 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18572 "\\(.\\|\n\\)*"
18573 (regexp-quote "</math>")) nil t)
18574 (prog1 (match-string 0) (kill-buffer))))))
18575 (cond
18576 (mathml
18577 (setq mathml
18578 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18579 (when mathml-file
18580 (write-region mathml nil mathml-file))
18581 (when (org-called-interactively-p 'any)
18582 (message mathml)))
18583 ((message "LaTeX to MathML conversion failed")
18584 (message shell-command-output)))
18585 (delete-file tmp-in-file)
18586 (when (file-exists-p tmp-out-file)
18587 (delete-file tmp-out-file))
18588 mathml))
18589
18590 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18591 prefix &optional dir)
18592 "Use `org-create-math-formula' but check local cache first."
18593 (let* ((absprefix (expand-file-name prefix dir))
18594 (print-length nil) (print-level nil)
18595 (formula-id (concat
18596 "formula-"
18597 (sha1
18598 (prin1-to-string
18599 (list latex-frag
18600 org-latex-to-mathml-convert-command)))))
18601 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18602 (formula-cache-dir (file-name-directory formula-cache)))
18603
18604 (unless (file-directory-p formula-cache-dir)
18605 (make-directory formula-cache-dir t))
18606
18607 (unless (file-exists-p formula-cache)
18608 (org-create-math-formula latex-frag formula-cache))
18609
18610 (if (file-exists-p formula-cache)
18611 ;; Successful conversion. Return the link to MathML file.
18612 (org-add-props
18613 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18614 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18615 'org-latex-src-embed-type (if latex-frag-type
18616 'paragraph 'character)))
18617 ;; Failed conversion. Return the LaTeX fragment verbatim
18618 latex-frag)))
18619
18620 (defun org-create-formula-image (string tofile options buffer &optional type)
18621 "Create an image from LaTeX source using dvipng or convert.
18622 This function calls either `org-create-formula-image-with-dvipng'
18623 or `org-create-formula-image-with-imagemagick' depending on the
18624 value of `org-latex-create-formula-image-program' or on the value
18625 of the optional TYPE variable.
18626
18627 Note: ultimately these two function should be combined as they
18628 share a good deal of logic."
18629 (org-check-external-command
18630 "latex" "needed to convert LaTeX fragments to images")
18631 (funcall
18632 (case (or type org-latex-create-formula-image-program)
18633 ('dvipng
18634 (org-check-external-command
18635 "dvipng" "needed to convert LaTeX fragments to images")
18636 #'org-create-formula-image-with-dvipng)
18637 ('imagemagick
18638 (org-check-external-command
18639 "convert" "you need to install imagemagick")
18640 #'org-create-formula-image-with-imagemagick)
18641 (t (error
18642 "Invalid value of `org-latex-create-formula-image-program'")))
18643 string tofile options buffer))
18644
18645 (declare-function org-export-get-backend "ox" (name))
18646 (declare-function org-export--get-global-options "ox" (&optional backend))
18647 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18648 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18649 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18650 (defun org-create-formula--latex-header ()
18651 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18652 (let ((info (org-combine-plists (org-export--get-global-options
18653 (org-export-get-backend 'latex))
18654 (org-export--get-inbuffer-options
18655 (org-export-get-backend 'latex)))))
18656 (org-latex-guess-babel-language
18657 (org-latex-guess-inputenc
18658 (org-splice-latex-header
18659 org-format-latex-header
18660 org-latex-default-packages-alist
18661 org-latex-packages-alist t
18662 (plist-get info :latex-header)))
18663 info)))
18664
18665 ;; This function borrows from Ganesh Swami's latex2png.el
18666 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18667 "This calls dvipng."
18668 (require 'ox-latex)
18669 (let* ((tmpdir (if (featurep 'xemacs)
18670 (temp-directory)
18671 temporary-file-directory))
18672 (texfilebase (make-temp-name
18673 (expand-file-name "orgtex" tmpdir)))
18674 (texfile (concat texfilebase ".tex"))
18675 (dvifile (concat texfilebase ".dvi"))
18676 (pngfile (concat texfilebase ".png"))
18677 (fnh (if (featurep 'xemacs)
18678 (font-height (face-font 'default))
18679 (face-attribute 'default :height nil)))
18680 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18681 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18682 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18683 "Black"))
18684 (bg (or (plist-get options (if buffer :background :html-background))
18685 "Transparent")))
18686 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18687 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18688 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18689 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18690 (let ((latex-header (org-create-formula--latex-header)))
18691 (with-temp-file texfile
18692 (insert latex-header)
18693 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18694 (let ((dir default-directory))
18695 (condition-case nil
18696 (progn
18697 (cd tmpdir)
18698 (call-process "latex" nil nil nil texfile))
18699 (error nil))
18700 (cd dir))
18701 (if (not (file-exists-p dvifile))
18702 (progn (message "Failed to create dvi file from %s" texfile) nil)
18703 (condition-case nil
18704 (if (featurep 'xemacs)
18705 (call-process "dvipng" nil nil nil
18706 "-fg" fg "-bg" bg
18707 "-T" "tight"
18708 "-o" pngfile
18709 dvifile)
18710 (call-process "dvipng" nil nil nil
18711 "-fg" fg "-bg" bg
18712 "-D" dpi
18713 ;;"-x" scale "-y" scale
18714 "-T" "tight"
18715 "-o" pngfile
18716 dvifile))
18717 (error nil))
18718 (if (not (file-exists-p pngfile))
18719 (if org-format-latex-signal-error
18720 (error "Failed to create png file from %s" texfile)
18721 (message "Failed to create png file from %s" texfile)
18722 nil)
18723 ;; Use the requested file name and clean up
18724 (copy-file pngfile tofile 'replace)
18725 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18726 (if (file-exists-p (concat texfilebase e))
18727 (delete-file (concat texfilebase e))))
18728 pngfile))))
18729
18730 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18731 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18732 "This calls convert, which is included into imagemagick."
18733 (require 'ox-latex)
18734 (let* ((tmpdir (if (featurep 'xemacs)
18735 (temp-directory)
18736 temporary-file-directory))
18737 (texfilebase (make-temp-name
18738 (expand-file-name "orgtex" tmpdir)))
18739 (texfile (concat texfilebase ".tex"))
18740 (pdffile (concat texfilebase ".pdf"))
18741 (pngfile (concat texfilebase ".png"))
18742 (fnh (if (featurep 'xemacs)
18743 (font-height (face-font 'default))
18744 (face-attribute 'default :height nil)))
18745 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18746 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18747 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18748 "black"))
18749 (bg (or (plist-get options (if buffer :background :html-background))
18750 "white")))
18751 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18752 (setq fg (org-latex-color-format fg)))
18753 (if (eq bg 'default) (setq bg (org-latex-color :background))
18754 (setq bg (org-latex-color-format
18755 (if (string= bg "Transparent") "white" bg))))
18756 (let ((latex-header (org-create-formula--latex-header)))
18757 (with-temp-file texfile
18758 (insert latex-header)
18759 (insert "\n\\begin{document}\n"
18760 "\\definecolor{fg}{rgb}{" fg "}\n"
18761 "\\definecolor{bg}{rgb}{" bg "}\n"
18762 "\n\\pagecolor{bg}\n"
18763 "\n{\\color{fg}\n"
18764 string
18765 "\n}\n"
18766 "\n\\end{document}\n")))
18767 (org-latex-compile texfile t)
18768 (if (not (file-exists-p pdffile))
18769 (progn (message "Failed to create pdf file from %s" texfile) nil)
18770 (condition-case nil
18771 (if (featurep 'xemacs)
18772 (call-process "convert" nil nil nil
18773 "-density" "96"
18774 "-trim"
18775 "-antialias"
18776 pdffile
18777 "-quality" "100"
18778 ;; "-sharpen" "0x1.0"
18779 pngfile)
18780 (call-process "convert" nil nil nil
18781 "-density" dpi
18782 "-trim"
18783 "-antialias"
18784 pdffile
18785 "-quality" "100"
18786 ;; "-sharpen" "0x1.0"
18787 pngfile))
18788 (error nil))
18789 (if (not (file-exists-p pngfile))
18790 (if org-format-latex-signal-error
18791 (error "Failed to create png file from %s" texfile)
18792 (message "Failed to create png file from %s" texfile)
18793 nil)
18794 ;; Use the requested file name and clean up
18795 (copy-file pngfile tofile 'replace)
18796 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18797 (if (file-exists-p (concat texfilebase e))
18798 (delete-file (concat texfilebase e))))
18799 pngfile))))
18800
18801 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18802 "Fill a LaTeX header template TPL.
18803 In the template, the following place holders will be recognized:
18804
18805 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18806 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18807 [PACKAGES] \\usepackage statements for PKG
18808 [NO-PACKAGES] do not include PKG
18809 [EXTRA] the string EXTRA
18810 [NO-EXTRA] do not include EXTRA
18811
18812 For backward compatibility, if both the positive and the negative place
18813 holder is missing, the positive one (without the \"NO-\") will be
18814 assumed to be present at the end of the template.
18815 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18816 EXTRA is a string.
18817 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18818 (let (rpl (end ""))
18819 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18820 (setq rpl (if (or (match-end 1) (not def-pkg))
18821 "" (org-latex-packages-to-string def-pkg snippets-p t))
18822 tpl (replace-match rpl t t tpl))
18823 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18824
18825 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18826 (setq rpl (if (or (match-end 1) (not pkg))
18827 "" (org-latex-packages-to-string pkg snippets-p t))
18828 tpl (replace-match rpl t t tpl))
18829 (if pkg (setq end
18830 (concat end "\n"
18831 (org-latex-packages-to-string pkg snippets-p)))))
18832
18833 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18834 (setq rpl (if (or (match-end 1) (not extra))
18835 "" (concat extra "\n"))
18836 tpl (replace-match rpl t t tpl))
18837 (if (and extra (string-match "\\S-" extra))
18838 (setq end (concat end "\n" extra))))
18839
18840 (if (string-match "\\S-" end)
18841 (concat tpl "\n" end)
18842 tpl)))
18843
18844 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18845 "Turn an alist of packages into a string with the \\usepackage macros."
18846 (setq pkg (mapconcat (lambda(p)
18847 (cond
18848 ((stringp p) p)
18849 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18850 (format "%% Package %s omitted" (cadr p)))
18851 ((equal "" (car p))
18852 (format "\\usepackage{%s}" (cadr p)))
18853 (t
18854 (format "\\usepackage[%s]{%s}"
18855 (car p) (cadr p)))))
18856 pkg
18857 "\n"))
18858 (if newline (concat pkg "\n") pkg))
18859
18860 (defun org-dvipng-color (attr)
18861 "Return a RGB color specification for dvipng."
18862 (apply 'format "rgb %s %s %s"
18863 (mapcar 'org-normalize-color
18864 (if (featurep 'xemacs)
18865 (color-rgb-components
18866 (face-property 'default
18867 (cond ((eq attr :foreground) 'foreground)
18868 ((eq attr :background) 'background))))
18869 (color-values (face-attribute 'default attr nil))))))
18870
18871 (defun org-dvipng-color-format (color-name)
18872 "Convert COLOR-NAME to a RGB color value for dvipng."
18873 (apply 'format "rgb %s %s %s"
18874 (mapcar 'org-normalize-color
18875 (color-values color-name))))
18876
18877 (defun org-latex-color (attr)
18878 "Return a RGB color for the LaTeX color package."
18879 (apply 'format "%s,%s,%s"
18880 (mapcar 'org-normalize-color
18881 (if (featurep 'xemacs)
18882 (color-rgb-components
18883 (face-property 'default
18884 (cond ((eq attr :foreground) 'foreground)
18885 ((eq attr :background) 'background))))
18886 (color-values (face-attribute 'default attr nil))))))
18887
18888 (defun org-latex-color-format (color-name)
18889 "Convert COLOR-NAME to a RGB color value."
18890 (apply 'format "%s,%s,%s"
18891 (mapcar 'org-normalize-color
18892 (color-values color-name))))
18893
18894 (defun org-normalize-color (value)
18895 "Return string to be used as color value for an RGB component."
18896 (format "%g" (/ value 65535.0)))
18897
18898
18899 \f
18900 ;; Image display
18901
18902 (defvar org-inline-image-overlays nil)
18903 (make-variable-buffer-local 'org-inline-image-overlays)
18904
18905 (defun org-toggle-inline-images (&optional include-linked)
18906 "Toggle the display of inline images.
18907 INCLUDE-LINKED is passed to `org-display-inline-images'."
18908 (interactive "P")
18909 (if org-inline-image-overlays
18910 (progn
18911 (org-remove-inline-images)
18912 (message "Inline image display turned off"))
18913 (org-display-inline-images include-linked)
18914 (if (and (org-called-interactively-p)
18915 org-inline-image-overlays)
18916 (message "%d images displayed inline"
18917 (length org-inline-image-overlays))
18918 (message "No images to display inline"))))
18919
18920 (defun org-redisplay-inline-images ()
18921 "Refresh the display of inline images."
18922 (interactive)
18923 (if (not org-inline-image-overlays)
18924 (org-toggle-inline-images)
18925 (org-toggle-inline-images)
18926 (org-toggle-inline-images)))
18927
18928 (defun org-display-inline-images (&optional include-linked refresh beg end)
18929 "Display inline images.
18930 Normally only links without a description part are inlined, because this
18931 is how it will work for export. When INCLUDE-LINKED is set, also links
18932 with a description part will be inlined. This can be nice for a quick
18933 look at those images, but it does not reflect what exported files will look
18934 like.
18935 When REFRESH is set, refresh existing images between BEG and END.
18936 This will create new image displays only if necessary.
18937 BEG and END default to the buffer boundaries."
18938 (interactive "P")
18939 (when (display-graphic-p)
18940 (unless refresh
18941 (org-remove-inline-images)
18942 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18943 (save-excursion
18944 (save-restriction
18945 (widen)
18946 (setq beg (or beg (point-min)) end (or end (point-max)))
18947 (goto-char beg)
18948 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18949 (substring (org-image-file-name-regexp) 0 -2)
18950 "\\)\\]" (if include-linked "" "\\]")))
18951 (case-fold-search t)
18952 old file ov img type attrwidth width)
18953 (while (re-search-forward re end t)
18954 (setq old (get-char-property-and-overlay (match-beginning 1)
18955 'org-image-overlay)
18956 file (expand-file-name
18957 (concat (or (match-string 3) "") (match-string 4))))
18958 (when (image-type-available-p 'imagemagick)
18959 (setq attrwidth (if (or (listp org-image-actual-width)
18960 (null org-image-actual-width))
18961 (save-excursion
18962 (save-match-data
18963 (when (re-search-backward
18964 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18965 (save-excursion
18966 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18967 (string-to-number (match-string 1))))))
18968 width (cond ((eq org-image-actual-width t) nil)
18969 ((null org-image-actual-width) attrwidth)
18970 ((numberp org-image-actual-width)
18971 org-image-actual-width)
18972 ((listp org-image-actual-width)
18973 (or attrwidth (car org-image-actual-width))))
18974 type (if width 'imagemagick)))
18975 (when (file-exists-p file)
18976 (if (and (car-safe old) refresh)
18977 (image-refresh (overlay-get (cdr old) 'display))
18978 (setq img (save-match-data (create-image file type nil :width width)))
18979 (when img
18980 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18981 (overlay-put ov 'display img)
18982 (overlay-put ov 'face 'default)
18983 (overlay-put ov 'org-image-overlay t)
18984 (overlay-put ov 'modification-hooks
18985 (list 'org-display-inline-remove-overlay))
18986 (push ov org-inline-image-overlays))))))))))
18987
18988 (define-obsolete-function-alias
18989 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18990
18991 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18992 "Remove inline-display overlay if a corresponding region is modified."
18993 (let ((inhibit-modification-hooks t))
18994 (when (and ov after)
18995 (delete ov org-inline-image-overlays)
18996 (delete-overlay ov))))
18997
18998 (defun org-remove-inline-images ()
18999 "Remove inline display of images."
19000 (interactive)
19001 (mapc 'delete-overlay org-inline-image-overlays)
19002 (setq org-inline-image-overlays nil))
19003
19004 ;;;; Key bindings
19005
19006 ;; Outline functions from `outline-mode-prefix-map'
19007 ;; that can be remapped in Org:
19008 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19009 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19010 (define-key org-mode-map [remap outline-forward-same-level]
19011 'org-forward-heading-same-level)
19012 (define-key org-mode-map [remap outline-backward-same-level]
19013 'org-backward-heading-same-level)
19014 (define-key org-mode-map [remap show-branches]
19015 'org-kill-note-or-show-branches)
19016 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19017 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19018 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19019
19020 ;; Outline functions from `outline-mode-prefix-map' that can not
19021 ;; be remapped in Org:
19022 ;;
19023 ;; - the column "key binding" shows whether the Outline function is still
19024 ;; available in Org mode on the same key that it has been bound to in
19025 ;; Outline mode:
19026 ;; - "overridden": key used for a different functionality in Org mode
19027 ;; - else: key still bound to the same Outline function in Org mode
19028 ;;
19029 ;; | Outline function | key binding | Org replacement |
19030 ;; |------------------------------------+-------------+-----------------------|
19031 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19032 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19033 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19034 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19035 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19036 ;; | `show-entry' | overridden | no replacement |
19037 ;; | `show-children' | `C-c C-i' | visibility cycling |
19038 ;; | `show-branches' | `C-c C-k' | still same function |
19039 ;; | `show-subtree' | overridden | visibility cycling |
19040 ;; | `show-all' | overridden | no replacement |
19041 ;; | `hide-subtree' | overridden | visibility cycling |
19042 ;; | `hide-body' | overridden | no replacement |
19043 ;; | `hide-entry' | overridden | visibility cycling |
19044 ;; | `hide-leaves' | overridden | no replacement |
19045 ;; | `hide-sublevels' | overridden | no replacement |
19046 ;; | `hide-other' | overridden | no replacement |
19047
19048 ;; Make `C-c C-x' a prefix key
19049 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19050
19051 ;; TAB key with modifiers
19052 (org-defkey org-mode-map "\C-i" 'org-cycle)
19053 (org-defkey org-mode-map [(tab)] 'org-cycle)
19054 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19055 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19056 ;; The following line is necessary under Suse GNU/Linux
19057 (unless (featurep 'xemacs)
19058 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19059 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19060 (define-key org-mode-map [backtab] 'org-shifttab)
19061
19062 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19063 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19064 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19065
19066 ;; Cursor keys with modifiers
19067 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19068 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19069 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19070 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19071
19072 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19073 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19074 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19075 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19076
19077 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19078 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19079 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19080 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19081
19082 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19083 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19084 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19085 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19086
19087 ;; Babel keys
19088 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19089 (mapc (lambda (pair)
19090 (define-key org-babel-map (car pair) (cdr pair)))
19091 org-babel-key-bindings)
19092
19093 ;;; Extra keys for tty access.
19094 ;; We only set them when really needed because otherwise the
19095 ;; menus don't show the simple keys
19096
19097 (when (or org-use-extra-keys
19098 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19099 (not window-system))
19100 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19101 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19102 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19103 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19104 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19105 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19106 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19107 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19108 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19109 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19110 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19111 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19112 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19113 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19114 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19115 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19116 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19117 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19118 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19119 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19120 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19121 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19122 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19123 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19124 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19125 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19126 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19127 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19128
19129 ;; All the other keys
19130
19131 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19132 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19133 (if (boundp 'narrow-map)
19134 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19135 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19136 (if (boundp 'narrow-map)
19137 (org-defkey narrow-map "b" 'org-narrow-to-block)
19138 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19139 (if (boundp 'narrow-map)
19140 (org-defkey narrow-map "e" 'org-narrow-to-element)
19141 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19142 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19143 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19144 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19145 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19146 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19147 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19148 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19149 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19150 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19151 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19152 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19153 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19154 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19155 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19156 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19157 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19158 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19159 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19160 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19161 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19162 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19163 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19164 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19165 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19166 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19167 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19168 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19169 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19170 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19171 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19172 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19173 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19174 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19175 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19176 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19177 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19178 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19179 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19180 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19181 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19182 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19183 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19184 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19185 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19186 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19187 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19188 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19189 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19190 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19191 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19192 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19193 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19194 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19195 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19196 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19197 (org-defkey org-mode-map "\C-c^" 'org-sort)
19198 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19199 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19200 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19201 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19202 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19203 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19204 (org-defkey org-mode-map "\C-m" 'org-return)
19205 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19206 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19207 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19208 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19209 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19210 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19211 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19212 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19213 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19214 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19215 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19216 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19217 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19218 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19219 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19220 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19221 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19222 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19223 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19224 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19225 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19226 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19227 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19228
19229 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19230 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19231 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19232
19233 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19234 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19235 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19236 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19237 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19238 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19239 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19240 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19241 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19242 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19243 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19244 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19245 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19246 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19247 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19248 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19249 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19250 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19251 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19252 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19253 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19254 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19255 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19256
19257 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19258 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19259 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19260 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19261 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19262
19263 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19264
19265 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19266
19267 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19268 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19269
19270 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19271
19272
19273 (when (featurep 'xemacs)
19274 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19275
19276
19277 (defconst org-speed-commands-default
19278 '(
19279 ("Outline Navigation")
19280 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19281 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19282 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19283 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19284 ("F" . org-next-block)
19285 ("B" . org-previous-block)
19286 ("u" . (org-speed-move-safe 'outline-up-heading))
19287 ("j" . org-goto)
19288 ("g" . (org-refile t))
19289 ("Outline Visibility")
19290 ("c" . org-cycle)
19291 ("C" . org-shifttab)
19292 (" " . org-display-outline-path)
19293 ("s" . org-narrow-to-subtree)
19294 ("=" . org-columns)
19295 ("Outline Structure Editing")
19296 ("U" . org-shiftmetaup)
19297 ("D" . org-shiftmetadown)
19298 ("r" . org-metaright)
19299 ("l" . org-metaleft)
19300 ("R" . org-shiftmetaright)
19301 ("L" . org-shiftmetaleft)
19302 ("i" . (progn (forward-char 1) (call-interactively
19303 'org-insert-heading-respect-content)))
19304 ("^" . org-sort)
19305 ("w" . org-refile)
19306 ("a" . org-archive-subtree-default-with-confirmation)
19307 ("@" . org-mark-subtree)
19308 ("#" . org-toggle-comment)
19309 ("Clock Commands")
19310 ("I" . org-clock-in)
19311 ("O" . org-clock-out)
19312 ("Meta Data Editing")
19313 ("t" . org-todo)
19314 ("," . (org-priority))
19315 ("0" . (org-priority ?\ ))
19316 ("1" . (org-priority ?A))
19317 ("2" . (org-priority ?B))
19318 ("3" . (org-priority ?C))
19319 (":" . org-set-tags-command)
19320 ("e" . org-set-effort)
19321 ("E" . org-inc-effort)
19322 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19323 (org-entry-put (point) "APPT_WARNTIME" m)))
19324 ("Agenda Views etc")
19325 ("v" . org-agenda)
19326 ("/" . org-sparse-tree)
19327 ("Misc")
19328 ("o" . org-open-at-point)
19329 ("?" . org-speed-command-help)
19330 ("<" . (org-agenda-set-restriction-lock 'subtree))
19331 (">" . (org-agenda-remove-restriction-lock))
19332 )
19333 "The default speed commands.")
19334
19335 (defun org-print-speed-command (e)
19336 (if (> (length (car e)) 1)
19337 (progn
19338 (princ "\n")
19339 (princ (car e))
19340 (princ "\n")
19341 (princ (make-string (length (car e)) ?-))
19342 (princ "\n"))
19343 (princ (car e))
19344 (princ " ")
19345 (if (symbolp (cdr e))
19346 (princ (symbol-name (cdr e)))
19347 (prin1 (cdr e)))
19348 (princ "\n")))
19349
19350 (defun org-speed-command-help ()
19351 "Show the available speed commands."
19352 (interactive)
19353 (if (not org-use-speed-commands)
19354 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19355 (with-output-to-temp-buffer "*Help*"
19356 (princ "User-defined Speed commands\n===========================\n")
19357 (mapc 'org-print-speed-command org-speed-commands-user)
19358 (princ "\n")
19359 (princ "Built-in Speed commands\n=======================\n")
19360 (mapc 'org-print-speed-command org-speed-commands-default))
19361 (with-current-buffer "*Help*"
19362 (setq truncate-lines t))))
19363
19364 (defun org-speed-move-safe (cmd)
19365 "Execute CMD, but make sure that the cursor always ends up in a headline.
19366 If not, return to the original position and throw an error."
19367 (interactive)
19368 (let ((pos (point)))
19369 (call-interactively cmd)
19370 (unless (and (bolp) (org-at-heading-p))
19371 (goto-char pos)
19372 (error "Boundary reached while executing %s" cmd))))
19373
19374 (defvar org-self-insert-command-undo-counter 0)
19375
19376 (defvar org-table-auto-blank-field) ; defined in org-table.el
19377 (defvar org-speed-command nil)
19378
19379 (define-obsolete-function-alias
19380 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19381
19382 (defun org-speed-command-activate (keys)
19383 "Hook for activating single-letter speed commands.
19384 `org-speed-commands-default' specifies a minimal command set.
19385 Use `org-speed-commands-user' for further customization."
19386 (when (or (and (bolp) (looking-at org-outline-regexp))
19387 (and (functionp org-use-speed-commands)
19388 (funcall org-use-speed-commands)))
19389 (cdr (assoc keys (append org-speed-commands-user
19390 org-speed-commands-default)))))
19391
19392 (define-obsolete-function-alias
19393 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19394
19395 (defun org-babel-speed-command-activate (keys)
19396 "Hook for activating single-letter code block commands."
19397 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19398 (cdr (assoc keys org-babel-key-bindings))))
19399
19400 (defcustom org-speed-command-hook
19401 '(org-speed-command-default-hook org-babel-speed-command-hook)
19402 "Hook for activating speed commands at strategic locations.
19403 Hook functions are called in sequence until a valid handler is
19404 found.
19405
19406 Each hook takes a single argument, a user-pressed command key
19407 which is also a `self-insert-command' from the global map.
19408
19409 Within the hook, examine the cursor position and the command key
19410 and return nil or a valid handler as appropriate. Handler could
19411 be one of an interactive command, a function, or a form.
19412
19413 Set `org-use-speed-commands' to non-nil value to enable this
19414 hook. The default setting is `org-speed-command-activate'."
19415 :group 'org-structure
19416 :version "24.1"
19417 :type 'hook)
19418
19419 (defun org-self-insert-command (N)
19420 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19421 If the cursor is in a table looking at whitespace, the whitespace is
19422 overwritten, and the table is not marked as requiring realignment."
19423 (interactive "p")
19424 (org-check-before-invisible-edit 'insert)
19425 (cond
19426 ((and org-use-speed-commands
19427 (setq org-speed-command
19428 (run-hook-with-args-until-success
19429 'org-speed-command-hook (this-command-keys))))
19430 (cond
19431 ((commandp org-speed-command)
19432 (setq this-command org-speed-command)
19433 (call-interactively org-speed-command))
19434 ((functionp org-speed-command)
19435 (funcall org-speed-command))
19436 ((and org-speed-command (listp org-speed-command))
19437 (eval org-speed-command))
19438 (t (let (org-use-speed-commands)
19439 (call-interactively 'org-self-insert-command)))))
19440 ((and
19441 (org-table-p)
19442 (progn
19443 ;; check if we blank the field, and if that triggers align
19444 (and (featurep 'org-table) org-table-auto-blank-field
19445 (member last-command
19446 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19447 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19448 ;; got extra space, this field does not determine column width
19449 (let (org-table-may-need-update) (org-table-blank-field))
19450 ;; no extra space, this field may determine column width
19451 (org-table-blank-field)))
19452 t)
19453 (eq N 1)
19454 (looking-at "[^|\n]* |"))
19455 (let (org-table-may-need-update)
19456 (goto-char (1- (match-end 0)))
19457 (backward-delete-char 1)
19458 (goto-char (match-beginning 0))
19459 (self-insert-command N)))
19460 (t
19461 (setq org-table-may-need-update t)
19462 (self-insert-command N)
19463 (org-fix-tags-on-the-fly)
19464 (if org-self-insert-cluster-for-undo
19465 (if (not (eq last-command 'org-self-insert-command))
19466 (setq org-self-insert-command-undo-counter 1)
19467 (if (>= org-self-insert-command-undo-counter 20)
19468 (setq org-self-insert-command-undo-counter 1)
19469 (and (> org-self-insert-command-undo-counter 0)
19470 buffer-undo-list (listp buffer-undo-list)
19471 (not (cadr buffer-undo-list)) ; remove nil entry
19472 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19473 (setq org-self-insert-command-undo-counter
19474 (1+ org-self-insert-command-undo-counter))))))))
19475
19476 (defun org-check-before-invisible-edit (kind)
19477 "Check is editing if kind KIND would be dangerous with invisible text around.
19478 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19479 ;; First, try to get out of here as quickly as possible, to reduce overhead
19480 (if (and org-catch-invisible-edits
19481 (or (not (boundp 'visible-mode)) (not visible-mode))
19482 (or (get-char-property (point) 'invisible)
19483 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19484 ;; OK, we need to take a closer look
19485 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19486 (invisible-before-point (if (bobp) nil (get-char-property
19487 (1- (point)) 'invisible)))
19488 (border-and-ok-direction
19489 (or
19490 ;; Check if we are acting predictably before invisible text
19491 (and invisible-at-point (not invisible-before-point)
19492 (memq kind '(insert delete-backward)))
19493 ;; Check if we are acting predictably after invisible text
19494 ;; This works not well, and I have turned it off. It seems
19495 ;; better to always show and stop after invisible text.
19496 ;; (and (not invisible-at-point) invisible-before-point
19497 ;; (memq kind '(insert delete)))
19498 )))
19499 (when (or (memq invisible-at-point '(outline org-hide-block t))
19500 (memq invisible-before-point '(outline org-hide-block t)))
19501 (if (eq org-catch-invisible-edits 'error)
19502 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19503 (if (and org-custom-properties-overlays
19504 (y-or-n-p "Display invisible properties in this buffer? "))
19505 (org-toggle-custom-properties-visibility)
19506 ;; Make the area visible
19507 (save-excursion
19508 (if invisible-before-point
19509 (goto-char (previous-single-char-property-change
19510 (point) 'invisible)))
19511 (show-subtree))
19512 (cond
19513 ((eq org-catch-invisible-edits 'show)
19514 ;; That's it, we do the edit after showing
19515 (message
19516 "Unfolding invisible region around point before editing")
19517 (sit-for 1))
19518 ((and (eq org-catch-invisible-edits 'smart)
19519 border-and-ok-direction)
19520 (message "Unfolding invisible region around point before editing"))
19521 (t
19522 ;; Don't do the edit, make the user repeat it in full visibility
19523 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19524
19525 (defun org-fix-tags-on-the-fly ()
19526 (when (and (equal (char-after (point-at-bol)) ?*)
19527 (org-at-heading-p))
19528 (org-align-tags-here org-tags-column)))
19529
19530 (defun org-delete-backward-char (N)
19531 "Like `delete-backward-char', insert whitespace at field end in tables.
19532 When deleting backwards, in tables this function will insert whitespace in
19533 front of the next \"|\" separator, to keep the table aligned. The table will
19534 still be marked for re-alignment if the field did fill the entire column,
19535 because, in this case the deletion might narrow the column."
19536 (interactive "p")
19537 (save-match-data
19538 (org-check-before-invisible-edit 'delete-backward)
19539 (if (and (org-table-p)
19540 (eq N 1)
19541 (string-match "|" (buffer-substring (point-at-bol) (point)))
19542 (looking-at ".*?|"))
19543 (let ((pos (point))
19544 (noalign (looking-at "[^|\n\r]* |"))
19545 (c org-table-may-need-update))
19546 (backward-delete-char N)
19547 (if (not overwrite-mode)
19548 (progn
19549 (skip-chars-forward "^|")
19550 (insert " ")
19551 (goto-char (1- pos))))
19552 ;; noalign: if there were two spaces at the end, this field
19553 ;; does not determine the width of the column.
19554 (if noalign (setq org-table-may-need-update c)))
19555 (backward-delete-char N)
19556 (org-fix-tags-on-the-fly))))
19557
19558 (defun org-delete-char (N)
19559 "Like `delete-char', but insert whitespace at field end in tables.
19560 When deleting characters, in tables this function will insert whitespace in
19561 front of the next \"|\" separator, to keep the table aligned. The table will
19562 still be marked for re-alignment if the field did fill the entire column,
19563 because, in this case the deletion might narrow the column."
19564 (interactive "p")
19565 (save-match-data
19566 (org-check-before-invisible-edit 'delete)
19567 (if (and (org-table-p)
19568 (not (bolp))
19569 (not (= (char-after) ?|))
19570 (eq N 1))
19571 (if (looking-at ".*?|")
19572 (let ((pos (point))
19573 (noalign (looking-at "[^|\n\r]* |"))
19574 (c org-table-may-need-update))
19575 (replace-match
19576 (concat (substring (match-string 0) 1 -1) " |") nil t)
19577 (goto-char pos)
19578 ;; noalign: if there were two spaces at the end, this field
19579 ;; does not determine the width of the column.
19580 (if noalign (setq org-table-may-need-update c)))
19581 (delete-char N))
19582 (delete-char N)
19583 (org-fix-tags-on-the-fly))))
19584
19585 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19586 (put 'org-self-insert-command 'delete-selection
19587 (lambda ()
19588 (not (run-hook-with-args-until-success
19589 'self-insert-uses-region-functions))))
19590 (put 'orgtbl-self-insert-command 'delete-selection
19591 (lambda ()
19592 (not (run-hook-with-args-until-success
19593 'self-insert-uses-region-functions))))
19594 (put 'org-delete-char 'delete-selection 'supersede)
19595 (put 'org-delete-backward-char 'delete-selection 'supersede)
19596 (put 'org-yank 'delete-selection 'yank)
19597
19598 ;; Make `flyspell-mode' delay after some commands
19599 (put 'org-self-insert-command 'flyspell-delayed t)
19600 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19601 (put 'org-delete-char 'flyspell-delayed t)
19602 (put 'org-delete-backward-char 'flyspell-delayed t)
19603
19604 ;; Make pabbrev-mode expand after org-mode commands
19605 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19606 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19607
19608 (defun org-remap (map &rest commands)
19609 "In MAP, remap the functions given in COMMANDS.
19610 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19611 (let (new old)
19612 (while commands
19613 (setq old (pop commands) new (pop commands))
19614 (if (fboundp 'command-remapping)
19615 (org-defkey map (vector 'remap old) new)
19616 (substitute-key-definition old new map global-map)))))
19617
19618 (defun org-transpose-words ()
19619 "Transpose words for Org.
19620 This uses the `org-mode-transpose-word-syntax-table' syntax
19621 table, which interprets characters in `org-emphasis-alist' as
19622 word constituents."
19623 (interactive)
19624 (with-syntax-table org-mode-transpose-word-syntax-table
19625 (call-interactively 'transpose-words)))
19626 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19627
19628 (when (eq org-enable-table-editor 'optimized)
19629 ;; If the user wants maximum table support, we need to hijack
19630 ;; some standard editing functions
19631 (org-remap org-mode-map
19632 'self-insert-command 'org-self-insert-command
19633 'delete-char 'org-delete-char
19634 'delete-backward-char 'org-delete-backward-char)
19635 (org-defkey org-mode-map "|" 'org-force-self-insert))
19636
19637 (defvar org-ctrl-c-ctrl-c-hook nil
19638 "Hook for functions attaching themselves to `C-c C-c'.
19639
19640 This can be used to add additional functionality to the C-c C-c
19641 key which executes context-dependent commands. This hook is run
19642 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19643 run after the last test.
19644
19645 Each function will be called with no arguments. The function
19646 must check if the context is appropriate for it to act. If yes,
19647 it should do its thing and then return a non-nil value. If the
19648 context is wrong, just do nothing and return nil.")
19649
19650 (defvar org-ctrl-c-ctrl-c-final-hook nil
19651 "Hook for functions attaching themselves to `C-c C-c'.
19652
19653 This can be used to add additional functionality to the C-c C-c
19654 key which executes context-dependent commands. This hook is run
19655 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19656 before the first test.
19657
19658 Each function will be called with no arguments. The function
19659 must check if the context is appropriate for it to act. If yes,
19660 it should do its thing and then return a non-nil value. If the
19661 context is wrong, just do nothing and return nil.")
19662
19663 (defvar org-tab-first-hook nil
19664 "Hook for functions to attach themselves to TAB.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.
19666 This hook runs as the first action when TAB is pressed, even before
19667 `org-cycle' messes around with the `outline-regexp' to cater for
19668 inline tasks and plain list item folding.
19669 If any function in this hook returns t, any other actions that
19670 would have been caused by TAB (such as table field motion or visibility
19671 cycling) will not occur.")
19672
19673 (defvar org-tab-after-check-for-table-hook nil
19674 "Hook for functions to attach themselves to TAB.
19675 See `org-ctrl-c-ctrl-c-hook' for more information.
19676 This hook runs after it has been established that the cursor is not in a
19677 table, but before checking if the cursor is in a headline or if global cycling
19678 should be done.
19679 If any function in this hook returns t, not other actions like visibility
19680 cycling will be done.")
19681
19682 (defvar org-tab-after-check-for-cycling-hook nil
19683 "Hook for functions to attach themselves to TAB.
19684 See `org-ctrl-c-ctrl-c-hook' for more information.
19685 This hook runs after it has been established that not table field motion and
19686 not visibility should be done because of current context. This is probably
19687 the place where a package like yasnippets can hook in.")
19688
19689 (defvar org-tab-before-tab-emulation-hook nil
19690 "Hook for functions to attach themselves to TAB.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.
19692 This hook runs after every other options for TAB have been exhausted, but
19693 before indentation and \t insertion takes place.")
19694
19695 (defvar org-metaleft-hook nil
19696 "Hook for functions attaching themselves to `M-left'.
19697 See `org-ctrl-c-ctrl-c-hook' for more information.")
19698 (defvar org-metaright-hook nil
19699 "Hook for functions attaching themselves to `M-right'.
19700 See `org-ctrl-c-ctrl-c-hook' for more information.")
19701 (defvar org-metaup-hook nil
19702 "Hook for functions attaching themselves to `M-up'.
19703 See `org-ctrl-c-ctrl-c-hook' for more information.")
19704 (defvar org-metadown-hook nil
19705 "Hook for functions attaching themselves to `M-down'.
19706 See `org-ctrl-c-ctrl-c-hook' for more information.")
19707 (defvar org-shiftmetaleft-hook nil
19708 "Hook for functions attaching themselves to `M-S-left'.
19709 See `org-ctrl-c-ctrl-c-hook' for more information.")
19710 (defvar org-shiftmetaright-hook nil
19711 "Hook for functions attaching themselves to `M-S-right'.
19712 See `org-ctrl-c-ctrl-c-hook' for more information.")
19713 (defvar org-shiftmetaup-hook nil
19714 "Hook for functions attaching themselves to `M-S-up'.
19715 See `org-ctrl-c-ctrl-c-hook' for more information.")
19716 (defvar org-shiftmetadown-hook nil
19717 "Hook for functions attaching themselves to `M-S-down'.
19718 See `org-ctrl-c-ctrl-c-hook' for more information.")
19719 (defvar org-metareturn-hook nil
19720 "Hook for functions attaching themselves to `M-RET'.
19721 See `org-ctrl-c-ctrl-c-hook' for more information.")
19722 (defvar org-shiftup-hook nil
19723 "Hook for functions attaching themselves to `S-up'.
19724 See `org-ctrl-c-ctrl-c-hook' for more information.")
19725 (defvar org-shiftup-final-hook nil
19726 "Hook for functions attaching themselves to `S-up'.
19727 This one runs after all other options except shift-select have been excluded.
19728 See `org-ctrl-c-ctrl-c-hook' for more information.")
19729 (defvar org-shiftdown-hook nil
19730 "Hook for functions attaching themselves to `S-down'.
19731 See `org-ctrl-c-ctrl-c-hook' for more information.")
19732 (defvar org-shiftdown-final-hook nil
19733 "Hook for functions attaching themselves to `S-down'.
19734 This one runs after all other options except shift-select have been excluded.
19735 See `org-ctrl-c-ctrl-c-hook' for more information.")
19736 (defvar org-shiftleft-hook nil
19737 "Hook for functions attaching themselves to `S-left'.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftleft-final-hook nil
19740 "Hook for functions attaching themselves to `S-left'.
19741 This one runs after all other options except shift-select have been excluded.
19742 See `org-ctrl-c-ctrl-c-hook' for more information.")
19743 (defvar org-shiftright-hook nil
19744 "Hook for functions attaching themselves to `S-right'.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.")
19746 (defvar org-shiftright-final-hook nil
19747 "Hook for functions attaching themselves to `S-right'.
19748 This one runs after all other options except shift-select have been excluded.
19749 See `org-ctrl-c-ctrl-c-hook' for more information.")
19750
19751 (defun org-modifier-cursor-error ()
19752 "Throw an error, a modified cursor command was applied in wrong context."
19753 (user-error "This command is active in special context like tables, headlines or items"))
19754
19755 (defun org-shiftselect-error ()
19756 "Throw an error because Shift-Cursor command was applied in wrong context."
19757 (if (and (boundp 'shift-select-mode) shift-select-mode)
19758 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19759 (user-error "This command works only in special context like headlines or timestamps")))
19760
19761 (defun org-call-for-shift-select (cmd)
19762 (let ((this-command-keys-shift-translated t))
19763 (call-interactively cmd)))
19764
19765 (defun org-shifttab (&optional arg)
19766 "Global visibility cycling or move to previous table field.
19767 Call `org-table-previous-field' within a table.
19768 When ARG is nil, cycle globally through visibility states.
19769 When ARG is a numeric prefix, show contents of this level."
19770 (interactive "P")
19771 (cond
19772 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19773 ((integerp arg)
19774 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19775 (message "Content view to level: %d" arg)
19776 (org-content (prefix-numeric-value arg2))
19777 (org-cycle-show-empty-lines t)
19778 (setq org-cycle-global-status 'overview)))
19779 (t (call-interactively 'org-global-cycle))))
19780
19781 (defun org-shiftmetaleft ()
19782 "Promote subtree or delete table column.
19783 Calls `org-promote-subtree', `org-outdent-item-tree', or
19784 `org-table-delete-column', depending on context. See the
19785 individual commands for more information."
19786 (interactive)
19787 (cond
19788 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19789 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19790 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19791 ((if (not (org-region-active-p)) (org-at-item-p)
19792 (save-excursion (goto-char (region-beginning))
19793 (org-at-item-p)))
19794 (call-interactively 'org-outdent-item-tree))
19795 (t (org-modifier-cursor-error))))
19796
19797 (defun org-shiftmetaright ()
19798 "Demote subtree or insert table column.
19799 Calls `org-demote-subtree', `org-indent-item-tree', or
19800 `org-table-insert-column', depending on context. See the
19801 individual commands for more information."
19802 (interactive)
19803 (cond
19804 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19805 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19806 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19807 ((if (not (org-region-active-p)) (org-at-item-p)
19808 (save-excursion (goto-char (region-beginning))
19809 (org-at-item-p)))
19810 (call-interactively 'org-indent-item-tree))
19811 (t (org-modifier-cursor-error))))
19812
19813 (defun org-shiftmetaup (&optional arg)
19814 "Move subtree up or kill table row.
19815 Calls `org-move-subtree-up' or `org-table-kill-row' or
19816 `org-move-item-up' or `org-timestamp-up', depending on context.
19817 See the individual commands for more information."
19818 (interactive "P")
19819 (cond
19820 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19821 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19822 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19823 ((org-at-item-p) (call-interactively 'org-move-item-up))
19824 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19825 (call-interactively 'org-timestamp-up)))
19826 (t (call-interactively 'org-drag-line-backward))))
19827
19828 (defun org-shiftmetadown (&optional arg)
19829 "Move subtree down or insert table row.
19830 Calls `org-move-subtree-down' or `org-table-insert-row' or
19831 `org-move-item-down' or `org-timestamp-up', depending on context.
19832 See the individual commands for more information."
19833 (interactive "P")
19834 (cond
19835 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19836 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19837 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19838 ((org-at-item-p) (call-interactively 'org-move-item-down))
19839 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19840 (call-interactively 'org-timestamp-down)))
19841 (t (call-interactively 'org-drag-line-forward))))
19842
19843 (defsubst org-hidden-tree-error ()
19844 (user-error
19845 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19846
19847 (defun org-metaleft (&optional arg)
19848 "Promote heading or move table column to left.
19849 Calls `org-do-promote' or `org-table-move-column', depending on context.
19850 With no specific context, calls the Emacs default `backward-word'.
19851 See the individual commands for more information."
19852 (interactive "P")
19853 (cond
19854 ((run-hook-with-args-until-success 'org-metaleft-hook))
19855 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19856 ((org-with-limited-levels
19857 (or (org-at-heading-p)
19858 (and (org-region-active-p)
19859 (save-excursion
19860 (goto-char (region-beginning))
19861 (org-at-heading-p)))))
19862 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19863 (call-interactively 'org-do-promote))
19864 ;; At an inline task.
19865 ((org-at-heading-p)
19866 (call-interactively 'org-inlinetask-promote))
19867 ((or (org-at-item-p)
19868 (and (org-region-active-p)
19869 (save-excursion
19870 (goto-char (region-beginning))
19871 (org-at-item-p))))
19872 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19873 (call-interactively 'org-outdent-item))
19874 (t (call-interactively 'backward-word))))
19875
19876 (defun org-metaright (&optional arg)
19877 "Demote a subtree, a list item or move table column to right.
19878 In front of a drawer or a block keyword, indent it correctly.
19879 With no specific context, calls the Emacs default `forward-word'.
19880 See the individual commands for more information."
19881 (interactive "P")
19882 (cond
19883 ((run-hook-with-args-until-success 'org-metaright-hook))
19884 ((org-at-table-p) (call-interactively 'org-table-move-column))
19885 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19886 ((org-at-block-p) (call-interactively 'org-indent-block))
19887 ((org-with-limited-levels
19888 (or (org-at-heading-p)
19889 (and (org-region-active-p)
19890 (save-excursion
19891 (goto-char (region-beginning))
19892 (org-at-heading-p)))))
19893 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19894 (call-interactively 'org-do-demote))
19895 ;; At an inline task.
19896 ((org-at-heading-p)
19897 (call-interactively 'org-inlinetask-demote))
19898 ((or (org-at-item-p)
19899 (and (org-region-active-p)
19900 (save-excursion
19901 (goto-char (region-beginning))
19902 (org-at-item-p))))
19903 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19904 (call-interactively 'org-indent-item))
19905 (t (call-interactively 'forward-word))))
19906
19907 (defun org-check-for-hidden (what)
19908 "Check if there are hidden headlines/items in the current visual line.
19909 WHAT can be either `headlines' or `items'. If the current line is
19910 an outline or item heading and it has a folded subtree below it,
19911 this function returns t, nil otherwise."
19912 (let ((re (cond
19913 ((eq what 'headlines) org-outline-regexp-bol)
19914 ((eq what 'items) (org-item-beginning-re))
19915 (t (error "This should not happen"))))
19916 beg end)
19917 (save-excursion
19918 (catch 'exit
19919 (unless (org-region-active-p)
19920 (setq beg (point-at-bol))
19921 (beginning-of-line 2)
19922 (while (and (not (eobp)) ;; this is like `next-line'
19923 (get-char-property (1- (point)) 'invisible))
19924 (beginning-of-line 2))
19925 (setq end (point))
19926 (goto-char beg)
19927 (goto-char (point-at-eol))
19928 (setq end (max end (point)))
19929 (while (re-search-forward re end t)
19930 (if (get-char-property (match-beginning 0) 'invisible)
19931 (throw 'exit t))))
19932 nil))))
19933
19934 (defun org-metaup (&optional arg)
19935 "Move subtree up or move table row up.
19936 Calls `org-move-subtree-up' or `org-table-move-row' or
19937 `org-move-item-up', depending on context. See the individual commands
19938 for more information."
19939 (interactive "P")
19940 (cond
19941 ((run-hook-with-args-until-success 'org-metaup-hook))
19942 ((org-region-active-p)
19943 (let* ((a (min (region-beginning) (region-end)))
19944 (b (1- (max (region-beginning) (region-end))))
19945 (c (save-excursion (goto-char a)
19946 (move-beginning-of-line 0)))
19947 (d (save-excursion (goto-char a)
19948 (move-end-of-line 0) (point))))
19949 (transpose-regions a b c d)
19950 (goto-char c)))
19951 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19952 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19953 ((org-at-item-p) (call-interactively 'org-move-item-up))
19954 (t (org-drag-element-backward))))
19955
19956 (defun org-metadown (&optional arg)
19957 "Move subtree down or move table row down.
19958 Calls `org-move-subtree-down' or `org-table-move-row' or
19959 `org-move-item-down', depending on context. See the individual
19960 commands for more information."
19961 (interactive "P")
19962 (cond
19963 ((run-hook-with-args-until-success 'org-metadown-hook))
19964 ((org-region-active-p)
19965 (let* ((a (min (region-beginning) (region-end)))
19966 (b (max (region-beginning) (region-end)))
19967 (c (save-excursion (goto-char b)
19968 (move-beginning-of-line 1)))
19969 (d (save-excursion (goto-char b)
19970 (move-end-of-line 1) (1+ (point)))))
19971 (transpose-regions a b c d)
19972 (goto-char d)))
19973 ((org-at-table-p) (call-interactively 'org-table-move-row))
19974 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19975 ((org-at-item-p) (call-interactively 'org-move-item-down))
19976 (t (org-drag-element-forward))))
19977
19978 (defun org-shiftup (&optional arg)
19979 "Increase item in timestamp or increase priority of current headline.
19980 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19981 depending on context. See the individual commands for more information."
19982 (interactive "P")
19983 (cond
19984 ((run-hook-with-args-until-success 'org-shiftup-hook))
19985 ((and org-support-shift-select (org-region-active-p))
19986 (org-call-for-shift-select 'previous-line))
19987 ((org-at-timestamp-p t)
19988 (call-interactively (if org-edit-timestamp-down-means-later
19989 'org-timestamp-down 'org-timestamp-up)))
19990 ((and (not (eq org-support-shift-select 'always))
19991 org-enable-priority-commands
19992 (org-at-heading-p))
19993 (call-interactively 'org-priority-up))
19994 ((and (not org-support-shift-select) (org-at-item-p))
19995 (call-interactively 'org-previous-item))
19996 ((org-clocktable-try-shift 'up arg))
19997 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19998 (org-support-shift-select
19999 (org-call-for-shift-select 'previous-line))
20000 (t (org-shiftselect-error))))
20001
20002 (defun org-shiftdown (&optional arg)
20003 "Decrease item in timestamp or decrease priority of current headline.
20004 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20005 depending on context. See the individual commands for more information."
20006 (interactive "P")
20007 (cond
20008 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20009 ((and org-support-shift-select (org-region-active-p))
20010 (org-call-for-shift-select 'next-line))
20011 ((org-at-timestamp-p t)
20012 (call-interactively (if org-edit-timestamp-down-means-later
20013 'org-timestamp-up 'org-timestamp-down)))
20014 ((and (not (eq org-support-shift-select 'always))
20015 org-enable-priority-commands
20016 (org-at-heading-p))
20017 (call-interactively 'org-priority-down))
20018 ((and (not org-support-shift-select) (org-at-item-p))
20019 (call-interactively 'org-next-item))
20020 ((org-clocktable-try-shift 'down arg))
20021 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20022 (org-support-shift-select
20023 (org-call-for-shift-select 'next-line))
20024 (t (org-shiftselect-error))))
20025
20026 (defun org-shiftright (&optional arg)
20027 "Cycle the thing at point or in the current line, depending on context.
20028 Depending on context, this does one of the following:
20029
20030 - switch a timestamp at point one day into the future
20031 - on a headline, switch to the next TODO keyword.
20032 - on an item, switch entire list to the next bullet type
20033 - on a property line, switch to the next allowed value
20034 - on a clocktable definition line, move time block into the future"
20035 (interactive "P")
20036 (cond
20037 ((run-hook-with-args-until-success 'org-shiftright-hook))
20038 ((and org-support-shift-select (org-region-active-p))
20039 (org-call-for-shift-select 'forward-char))
20040 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20041 ((and (not (eq org-support-shift-select 'always))
20042 (org-at-heading-p))
20043 (let ((org-inhibit-logging
20044 (not org-treat-S-cursor-todo-selection-as-state-change))
20045 (org-inhibit-blocking
20046 (not org-treat-S-cursor-todo-selection-as-state-change)))
20047 (org-call-with-arg 'org-todo 'right)))
20048 ((or (and org-support-shift-select
20049 (not (eq org-support-shift-select 'always))
20050 (org-at-item-bullet-p))
20051 (and (not org-support-shift-select) (org-at-item-p)))
20052 (org-call-with-arg 'org-cycle-list-bullet nil))
20053 ((and (not (eq org-support-shift-select 'always))
20054 (org-at-property-p))
20055 (call-interactively 'org-property-next-allowed-value))
20056 ((org-clocktable-try-shift 'right arg))
20057 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20058 (org-support-shift-select
20059 (org-call-for-shift-select 'forward-char))
20060 (t (org-shiftselect-error))))
20061
20062 (defun org-shiftleft (&optional arg)
20063 "Cycle the thing at point or in the current line, depending on context.
20064 Depending on context, this does one of the following:
20065
20066 - switch a timestamp at point one day into the past
20067 - on a headline, switch to the previous TODO keyword.
20068 - on an item, switch entire list to the previous bullet type
20069 - on a property line, switch to the previous allowed value
20070 - on a clocktable definition line, move time block into the past"
20071 (interactive "P")
20072 (cond
20073 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20074 ((and org-support-shift-select (org-region-active-p))
20075 (org-call-for-shift-select 'backward-char))
20076 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20077 ((and (not (eq org-support-shift-select 'always))
20078 (org-at-heading-p))
20079 (let ((org-inhibit-logging
20080 (not org-treat-S-cursor-todo-selection-as-state-change))
20081 (org-inhibit-blocking
20082 (not org-treat-S-cursor-todo-selection-as-state-change)))
20083 (org-call-with-arg 'org-todo 'left)))
20084 ((or (and org-support-shift-select
20085 (not (eq org-support-shift-select 'always))
20086 (org-at-item-bullet-p))
20087 (and (not org-support-shift-select) (org-at-item-p)))
20088 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20089 ((and (not (eq org-support-shift-select 'always))
20090 (org-at-property-p))
20091 (call-interactively 'org-property-previous-allowed-value))
20092 ((org-clocktable-try-shift 'left arg))
20093 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20094 (org-support-shift-select
20095 (org-call-for-shift-select 'backward-char))
20096 (t (org-shiftselect-error))))
20097
20098 (defun org-shiftcontrolright ()
20099 "Switch to next TODO set."
20100 (interactive)
20101 (cond
20102 ((and org-support-shift-select (org-region-active-p))
20103 (org-call-for-shift-select 'forward-word))
20104 ((and (not (eq org-support-shift-select 'always))
20105 (org-at-heading-p))
20106 (org-call-with-arg 'org-todo 'nextset))
20107 (org-support-shift-select
20108 (org-call-for-shift-select 'forward-word))
20109 (t (org-shiftselect-error))))
20110
20111 (defun org-shiftcontrolleft ()
20112 "Switch to previous TODO set."
20113 (interactive)
20114 (cond
20115 ((and org-support-shift-select (org-region-active-p))
20116 (org-call-for-shift-select 'backward-word))
20117 ((and (not (eq org-support-shift-select 'always))
20118 (org-at-heading-p))
20119 (org-call-with-arg 'org-todo 'previousset))
20120 (org-support-shift-select
20121 (org-call-for-shift-select 'backward-word))
20122 (t (org-shiftselect-error))))
20123
20124 (defun org-shiftcontrolup (&optional n)
20125 "Change timestamps synchronously up in CLOCK log lines.
20126 Optional argument N tells to change by that many units."
20127 (interactive "P")
20128 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20129 (let (org-support-shift-select)
20130 (org-clock-timestamps-up n))
20131 (user-error "Not at a clock log")))
20132
20133 (defun org-shiftcontroldown (&optional n)
20134 "Change timestamps synchronously down in CLOCK log lines.
20135 Optional argument N tells to change by that many units."
20136 (interactive "P")
20137 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20138 (let (org-support-shift-select)
20139 (org-clock-timestamps-down n))
20140 (user-error "Not at a clock log")))
20141
20142 (defun org-ctrl-c-ret ()
20143 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20144 (interactive)
20145 (cond
20146 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20147 (t (call-interactively 'org-insert-heading))))
20148
20149 (defun org-find-visible ()
20150 (let ((s (point)))
20151 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20152 (get-char-property s 'invisible)))
20153 s))
20154 (defun org-find-invisible ()
20155 (let ((s (point)))
20156 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20157 (not (get-char-property s 'invisible))))
20158 s))
20159
20160 (defun org-copy-visible (beg end)
20161 "Copy the visible parts of the region."
20162 (interactive "r")
20163 (let (snippets s)
20164 (save-excursion
20165 (save-restriction
20166 (narrow-to-region beg end)
20167 (setq s (goto-char (point-min)))
20168 (while (not (= (point) (point-max)))
20169 (goto-char (org-find-invisible))
20170 (push (buffer-substring s (point)) snippets)
20171 (setq s (goto-char (org-find-visible))))))
20172 (kill-new (apply 'concat (nreverse snippets)))))
20173
20174 (defun org-copy-special ()
20175 "Copy region in table or copy current subtree.
20176 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20177 See the individual commands for more information."
20178 (interactive)
20179 (call-interactively
20180 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20181
20182 (defun org-cut-special ()
20183 "Cut region in table or cut current subtree.
20184 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20185 See the individual commands for more information."
20186 (interactive)
20187 (call-interactively
20188 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20189
20190 (defun org-paste-special (arg)
20191 "Paste rectangular region into table, or past subtree relative to level.
20192 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20193 See the individual commands for more information."
20194 (interactive "P")
20195 (if (org-at-table-p)
20196 (org-table-paste-rectangle)
20197 (org-paste-subtree arg)))
20198
20199 (defsubst org-in-fixed-width-region-p ()
20200 "Is point in a fixed-width region?"
20201 (save-match-data
20202 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20203
20204 (defun org-edit-special (&optional arg)
20205 "Call a special editor for the element at point.
20206 When at a table, call the formula editor with `org-table-edit-formulas'.
20207 When in a source code block, call `org-edit-src-code'.
20208 When in a fixed-width region, call `org-edit-fixed-width-region'.
20209 When at an #+INCLUDE keyword, visit the included file.
20210 On a link, call `ffap' to visit the link at point.
20211 Otherwise, return a user error."
20212 (interactive "P")
20213 (let ((element (org-element-at-point)))
20214 (assert (not buffer-read-only) nil
20215 "Buffer is read-only: %s" (buffer-name))
20216 (case (org-element-type element)
20217 (src-block
20218 (if (not arg) (org-edit-src-code)
20219 (let* ((info (org-babel-get-src-block-info))
20220 (lang (nth 0 info))
20221 (params (nth 2 info))
20222 (session (cdr (assq :session params))))
20223 (if (not session) (org-edit-src-code)
20224 ;; At a src-block with a session and function called with
20225 ;; an ARG: switch to the buffer related to the inferior
20226 ;; process.
20227 (switch-to-buffer
20228 (funcall (intern (concat "org-babel-prep-session:" lang))
20229 session params))))))
20230 (keyword
20231 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20232 (find-file
20233 (org-remove-double-quotes
20234 (car (org-split-string (org-element-property :value element)))))
20235 (user-error "No special environment to edit here")))
20236 (table
20237 (if (eq (org-element-property :type element) 'table.el)
20238 (org-edit-src-code)
20239 (call-interactively 'org-table-edit-formulas)))
20240 ;; Only Org tables contain `table-row' type elements.
20241 (table-row (call-interactively 'org-table-edit-formulas))
20242 ((example-block export-block) (org-edit-src-code))
20243 (fixed-width (org-edit-fixed-width-region))
20244 (otherwise
20245 ;; No notable element at point. Though, we may be at a link,
20246 ;; which is an object. Thus, scan deeper.
20247 (if (eq (org-element-type (org-element-context element)) 'link)
20248 (call-interactively 'ffap)
20249 (user-error "No special environment to edit here"))))))
20250
20251 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20252 (defun org-ctrl-c-ctrl-c (&optional arg)
20253 "Set tags in headline, or update according to changed information at point.
20254
20255 This command does many different things, depending on context:
20256
20257 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20258 this is what we do.
20259
20260 - If the cursor is on a statistics cookie, update it.
20261
20262 - If the cursor is in a headline, prompt for tags and insert them
20263 into the current line, aligned to `org-tags-column'. When called
20264 with prefix arg, realign all tags in the current buffer.
20265
20266 - If the cursor is in one of the special #+KEYWORD lines, this
20267 triggers scanning the buffer for these lines and updating the
20268 information.
20269
20270 - If the cursor is inside a table, realign the table. This command
20271 works even if the automatic table editor has been turned off.
20272
20273 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20274 the entire table.
20275
20276 - If the cursor is at a footnote reference or definition, jump to
20277 the corresponding definition or references, respectively.
20278
20279 - If the cursor is a the beginning of a dynamic block, update it.
20280
20281 - If the current buffer is a capture buffer, close note and file it.
20282
20283 - If the cursor is on a <<<target>>>, update radio targets and
20284 corresponding links in this buffer.
20285
20286 - If the cursor is on a numbered item in a plain list, renumber the
20287 ordered list.
20288
20289 - If the cursor is on a checkbox, toggle it.
20290
20291 - If the cursor is on a code block, evaluate it. The variable
20292 `org-confirm-babel-evaluate' can be used to control prompting
20293 before code block evaluation, by default every code block
20294 evaluation requires confirmation. Code block evaluation can be
20295 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20296 (interactive "P")
20297 (cond
20298 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20299 org-occur-highlights
20300 org-latex-fragment-image-overlays)
20301 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20302 (org-remove-occur-highlights)
20303 (org-remove-latex-fragment-image-overlays)
20304 (message "Temporary highlights/overlays removed from current buffer"))
20305 ((and (local-variable-p 'org-finish-function (current-buffer))
20306 (fboundp org-finish-function))
20307 (funcall org-finish-function))
20308 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20309 (t
20310 (let* ((context (org-element-context)) (type (org-element-type context)))
20311 ;; Test if point is within a blank line.
20312 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20313 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20314 (user-error "C-c C-c can do nothing useful at this location"))
20315 (case type
20316 ;; When at a link, act according to the parent instead.
20317 (link (setq context (org-element-property :parent context))
20318 (setq type (org-element-type context)))
20319 ;; Unsupported object types: refer to the first supported
20320 ;; element or object containing it.
20321 ((bold code entity export-snippet inline-babel-call inline-src-block
20322 italic latex-fragment line-break macro strike-through subscript
20323 superscript underline verbatim)
20324 (while (and (setq context (org-element-property :parent context))
20325 (not (memq (setq type (org-element-type context))
20326 '(radio-target paragraph verse-block
20327 table-cell)))))))
20328 ;; For convenience: at the first line of a paragraph on the
20329 ;; same line as an item, apply function on that item instead.
20330 (when (eq type 'paragraph)
20331 (let ((parent (org-element-property :parent context)))
20332 (when (and (eq (org-element-type parent) 'item)
20333 (= (point-at-bol) (org-element-property :begin parent)))
20334 (setq context parent type 'item))))
20335 ;; Act according to type of element or object at point.
20336 (case type
20337 (clock (org-clock-update-time-maybe))
20338 (dynamic-block
20339 (save-excursion
20340 (goto-char (org-element-property :post-affiliated context))
20341 (org-update-dblock)))
20342 (footnote-definition
20343 (goto-char (org-element-property :post-affiliated context))
20344 (call-interactively 'org-footnote-action))
20345 (footnote-reference (call-interactively 'org-footnote-action))
20346 ((headline inlinetask)
20347 (save-excursion (goto-char (org-element-property :begin context))
20348 (call-interactively 'org-set-tags)))
20349 (item
20350 ;; At an item: a double C-u set checkbox to "[-]"
20351 ;; unconditionally, whereas a single one will toggle its
20352 ;; presence. Without a universal argument, if the item
20353 ;; has a checkbox, toggle it. Otherwise repair the list.
20354 (let* ((box (org-element-property :checkbox context))
20355 (struct (org-element-property :structure context))
20356 (old-struct (copy-tree struct))
20357 (parents (org-list-parents-alist struct))
20358 (prevs (org-list-prevs-alist struct))
20359 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20360 (org-list-set-checkbox
20361 (org-element-property :begin context) struct
20362 (cond ((equal arg '(16)) "[-]")
20363 ((and (not box) (equal arg '(4))) "[ ]")
20364 ((or (not box) (equal arg '(4))) nil)
20365 ((eq box 'on) "[ ]")
20366 (t "[X]")))
20367 ;; Mimic `org-list-write-struct' but with grabbing
20368 ;; a return value from `org-list-struct-fix-box'.
20369 (org-list-struct-fix-ind struct parents 2)
20370 (org-list-struct-fix-item-end struct)
20371 (org-list-struct-fix-bul struct prevs)
20372 (org-list-struct-fix-ind struct parents)
20373 (let ((block-item
20374 (org-list-struct-fix-box struct parents prevs orderedp)))
20375 (if (and box (equal struct old-struct))
20376 (if (equal arg '(16))
20377 (message "Checkboxes already reset")
20378 (user-error "Cannot toggle this checkbox: %s"
20379 (if (eq box 'on)
20380 "all subitems checked"
20381 "unchecked subitems")))
20382 (org-list-struct-apply-struct struct old-struct)
20383 (org-update-checkbox-count-maybe))
20384 (when block-item
20385 (message "Checkboxes were removed due to empty box at line %d"
20386 (org-current-line block-item))))))
20387 (keyword
20388 (let ((org-inhibit-startup-visibility-stuff t)
20389 (org-startup-align-all-tables nil))
20390 (when (boundp 'org-table-coordinate-overlays)
20391 (mapc 'delete-overlay org-table-coordinate-overlays)
20392 (setq org-table-coordinate-overlays nil))
20393 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20394 (message "Local setup has been refreshed"))
20395 (plain-list
20396 ;; At a plain list, with a double C-u argument, set
20397 ;; checkboxes of each item to "[-]", whereas a single one
20398 ;; will toggle their presence according to the state of the
20399 ;; first item in the list. Without an argument, repair the
20400 ;; list.
20401 (let* ((begin (org-element-property :contents-begin context))
20402 (beginm (move-marker (make-marker) begin))
20403 (struct (org-element-property :structure context))
20404 (old-struct (copy-tree struct))
20405 (first-box (save-excursion
20406 (goto-char begin)
20407 (looking-at org-list-full-item-re)
20408 (match-string-no-properties 3)))
20409 (new-box (cond ((equal arg '(16)) "[-]")
20410 ((equal arg '(4)) (unless first-box "[ ]"))
20411 ((equal first-box "[X]") "[ ]")
20412 (t "[X]"))))
20413 (cond
20414 (arg
20415 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20416 (org-list-get-all-items
20417 begin struct (org-list-prevs-alist struct))))
20418 ((and first-box (eq (point) begin))
20419 ;; For convenience, when point is at bol on the first
20420 ;; item of the list and no argument is provided, simply
20421 ;; toggle checkbox of that item, if any.
20422 (org-list-set-checkbox begin struct new-box)))
20423 (org-list-write-struct
20424 struct (org-list-parents-alist struct) old-struct)
20425 (org-update-checkbox-count-maybe)
20426 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20427 ((property-drawer node-property)
20428 (call-interactively 'org-property-action))
20429 ((radio-target target)
20430 (call-interactively 'org-update-radio-target-regexp))
20431 (statistics-cookie
20432 (call-interactively 'org-update-statistics-cookies))
20433 ((table table-cell table-row)
20434 ;; At a table, recalculate every field and align it. Also
20435 ;; send the table if necessary. If the table has
20436 ;; a `table.el' type, just give up. At a table row or
20437 ;; cell, maybe recalculate line but always align table.
20438 (if (eq (org-element-property :type context) 'table.el)
20439 (message "Use C-c ' to edit table.el tables")
20440 (let ((org-enable-table-editor t))
20441 (if (or (eq type 'table)
20442 ;; Check if point is at a TBLFM line.
20443 (and (eq type 'table-row)
20444 (= (point) (org-element-property :end context))))
20445 (save-excursion
20446 (if (org-at-TBLFM-p)
20447 (progn (require 'org-table)
20448 (org-table-calc-current-TBLFM))
20449 (goto-char (org-element-property :contents-begin context))
20450 (org-call-with-arg 'org-table-recalculate (or arg t))
20451 (orgtbl-send-table 'maybe)))
20452 (org-table-maybe-eval-formula)
20453 (cond (arg (call-interactively 'org-table-recalculate))
20454 ((org-table-maybe-recalculate-line))
20455 (t (org-table-align)))))))
20456 (timestamp (org-timestamp-change 0 'day))
20457 (otherwise
20458 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20459 (user-error
20460 "C-c C-c can do nothing useful at this location")))))))))
20461
20462 (defun org-mode-restart ()
20463 (interactive)
20464 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20465 (funcall major-mode)
20466 (hack-local-variables)
20467 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20468 (org-indent-mode -1)))
20469 (message "%s restarted" major-mode))
20470
20471 (defun org-kill-note-or-show-branches ()
20472 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20473 (interactive)
20474 (if (not org-finish-function)
20475 (progn
20476 (hide-subtree)
20477 (call-interactively 'show-branches))
20478 (let ((org-note-abort t))
20479 (funcall org-finish-function))))
20480
20481 (defun org-open-line (n)
20482 "Insert a new row in tables, call `open-line' elsewhere.
20483 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20484 (interactive "*p")
20485 (cond
20486 ((not org-special-ctrl-o)
20487 (open-line n))
20488 ((org-at-table-p)
20489 (org-table-insert-row))
20490 (t
20491 (open-line n))))
20492
20493 (defun org-return (&optional indent)
20494 "Goto next table row or insert a newline.
20495 Calls `org-table-next-row' or `newline', depending on context.
20496 See the individual commands for more information."
20497 (interactive)
20498 (let (org-ts-what)
20499 (cond
20500 ((or (bobp) (org-in-src-block-p))
20501 (if indent (newline-and-indent) (newline)))
20502 ((org-at-table-p)
20503 (org-table-justify-field-maybe)
20504 (call-interactively 'org-table-next-row))
20505 ;; when `newline-and-indent' is called within a list, make sure
20506 ;; text moved stays inside the item.
20507 ((and (org-in-item-p) indent)
20508 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20509 (progn
20510 (save-match-data (newline))
20511 (org-indent-line-to (length (match-string 0))))
20512 (let ((ind (org-get-indentation)))
20513 (newline)
20514 (if (org-looking-back org-list-end-re)
20515 (org-indent-line)
20516 (org-indent-line-to ind)))))
20517 ((and org-return-follows-link
20518 (org-at-timestamp-p t)
20519 (not (eq org-ts-what 'after)))
20520 (org-follow-timestamp-link))
20521 ((and org-return-follows-link
20522 (let ((tprop (get-text-property (point) 'face)))
20523 (or (eq tprop 'org-link)
20524 (and (listp tprop) (memq 'org-link tprop)))))
20525 (call-interactively 'org-open-at-point))
20526 ((and (org-at-heading-p)
20527 (looking-at
20528 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20529 (org-show-entry)
20530 (end-of-line 1)
20531 (newline))
20532 (t (if indent (newline-and-indent) (newline))))))
20533
20534 (defun org-return-indent ()
20535 "Goto next table row or insert a newline and indent.
20536 Calls `org-table-next-row' or `newline-and-indent', depending on
20537 context. See the individual commands for more information."
20538 (interactive)
20539 (org-return t))
20540
20541 (defun org-ctrl-c-star ()
20542 "Compute table, or change heading status of lines.
20543 Calls `org-table-recalculate' or `org-toggle-heading',
20544 depending on context."
20545 (interactive)
20546 (cond
20547 ((org-at-table-p)
20548 (call-interactively 'org-table-recalculate))
20549 (t
20550 ;; Convert all lines in region to list items
20551 (call-interactively 'org-toggle-heading))))
20552
20553 (defun org-ctrl-c-minus ()
20554 "Insert separator line in table or modify bullet status of line.
20555 Also turns a plain line or a region of lines into list items.
20556 Calls `org-table-insert-hline', `org-toggle-item', or
20557 `org-cycle-list-bullet', depending on context."
20558 (interactive)
20559 (cond
20560 ((org-at-table-p)
20561 (call-interactively 'org-table-insert-hline))
20562 ((org-region-active-p)
20563 (call-interactively 'org-toggle-item))
20564 ((org-in-item-p)
20565 (call-interactively 'org-cycle-list-bullet))
20566 (t
20567 (call-interactively 'org-toggle-item))))
20568
20569 (defun org-toggle-item (arg)
20570 "Convert headings or normal lines to items, items to normal lines.
20571 If there is no active region, only the current line is considered.
20572
20573 If the first non blank line in the region is a headline, convert
20574 all headlines to items, shifting text accordingly.
20575
20576 If it is an item, convert all items to normal lines.
20577
20578 If it is normal text, change region into a list of items.
20579 With a prefix argument ARG, change the region in a single item."
20580 (interactive "P")
20581 (let ((shift-text
20582 (function
20583 ;; Shift text in current section to IND, from point to END.
20584 ;; The function leaves point to END line.
20585 (lambda (ind end)
20586 (let ((min-i 1000) (end (copy-marker end)))
20587 ;; First determine the minimum indentation (MIN-I) of
20588 ;; the text.
20589 (save-excursion
20590 (catch 'exit
20591 (while (< (point) end)
20592 (let ((i (org-get-indentation)))
20593 (cond
20594 ;; Skip blank lines and inline tasks.
20595 ((looking-at "^[ \t]*$"))
20596 ((looking-at org-outline-regexp-bol))
20597 ;; We can't find less than 0 indentation.
20598 ((zerop i) (throw 'exit (setq min-i 0)))
20599 ((< i min-i) (setq min-i i))))
20600 (forward-line))))
20601 ;; Then indent each line so that a line indented to
20602 ;; MIN-I becomes indented to IND. Ignore blank lines
20603 ;; and inline tasks in the process.
20604 (let ((delta (- ind min-i)))
20605 (while (< (point) end)
20606 (unless (or (looking-at "^[ \t]*$")
20607 (looking-at org-outline-regexp-bol))
20608 (org-indent-line-to (+ (org-get-indentation) delta)))
20609 (forward-line)))))))
20610 (skip-blanks
20611 (function
20612 ;; Return beginning of first non-blank line, starting from
20613 ;; line at POS.
20614 (lambda (pos)
20615 (save-excursion
20616 (goto-char pos)
20617 (skip-chars-forward " \r\t\n")
20618 (point-at-bol)))))
20619 beg end)
20620 ;; Determine boundaries of changes.
20621 (if (org-region-active-p)
20622 (setq beg (funcall skip-blanks (region-beginning))
20623 end (copy-marker (region-end)))
20624 (setq beg (funcall skip-blanks (point-at-bol))
20625 end (copy-marker (point-at-eol))))
20626 ;; Depending on the starting line, choose an action on the text
20627 ;; between BEG and END.
20628 (org-with-limited-levels
20629 (save-excursion
20630 (goto-char beg)
20631 (cond
20632 ;; Case 1. Start at an item: de-itemize. Note that it only
20633 ;; happens when a region is active: `org-ctrl-c-minus'
20634 ;; would call `org-cycle-list-bullet' otherwise.
20635 ((org-at-item-p)
20636 (while (< (point) end)
20637 (when (org-at-item-p)
20638 (skip-chars-forward " \t")
20639 (delete-region (point) (match-end 0)))
20640 (forward-line)))
20641 ;; Case 2. Start at an heading: convert to items.
20642 ((org-at-heading-p)
20643 (let* ((bul (org-list-bullet-string "-"))
20644 (bul-len (length bul))
20645 ;; Indentation of the first heading. It should be
20646 ;; relative to the indentation of its parent, if any.
20647 (start-ind (save-excursion
20648 (cond
20649 ((not org-adapt-indentation) 0)
20650 ((not (outline-previous-heading)) 0)
20651 (t (length (match-string 0))))))
20652 ;; Level of first heading. Further headings will be
20653 ;; compared to it to determine hierarchy in the list.
20654 (ref-level (org-reduced-level (org-outline-level))))
20655 (while (< (point) end)
20656 (let* ((level (org-reduced-level (org-outline-level)))
20657 (delta (max 0 (- level ref-level))))
20658 ;; If current headline is less indented than the first
20659 ;; one, set it as reference, in order to preserve
20660 ;; subtrees.
20661 (when (< level ref-level) (setq ref-level level))
20662 (replace-match bul t t)
20663 (org-indent-line-to (+ start-ind (* delta bul-len)))
20664 ;; Ensure all text down to END (or SECTION-END) belongs
20665 ;; to the newly created item.
20666 (let ((section-end (save-excursion
20667 (or (outline-next-heading) (point)))))
20668 (forward-line)
20669 (funcall shift-text
20670 (+ start-ind (* (1+ delta) bul-len))
20671 (min end section-end)))))))
20672 ;; Case 3. Normal line with ARG: make the first line of region
20673 ;; an item, and shift indentation of others lines to
20674 ;; set them as item's body.
20675 (arg (let* ((bul (org-list-bullet-string "-"))
20676 (bul-len (length bul))
20677 (ref-ind (org-get-indentation)))
20678 (skip-chars-forward " \t")
20679 (insert bul)
20680 (forward-line)
20681 (while (< (point) end)
20682 ;; Ensure that lines less indented than first one
20683 ;; still get included in item body.
20684 (funcall shift-text
20685 (+ ref-ind bul-len)
20686 (min end (save-excursion (or (outline-next-heading)
20687 (point)))))
20688 (forward-line))))
20689 ;; Case 4. Normal line without ARG: turn each non-item line
20690 ;; into an item.
20691 (t
20692 (while (< (point) end)
20693 (unless (or (org-at-heading-p) (org-at-item-p))
20694 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20695 (replace-match
20696 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20697 (forward-line))))))))
20698
20699 (defun org-toggle-heading (&optional nstars)
20700 "Convert headings to normal text, or items or text to headings.
20701 If there is no active region, only convert the current line.
20702
20703 With a \\[universal-argument] prefix, convert the whole list at
20704 point into heading.
20705
20706 In a region:
20707
20708 - If the first non blank line is a headline, remove the stars
20709 from all headlines in the region.
20710
20711 - If it is a normal line, turn each and every normal line (i.e.,
20712 not an heading or an item) in the region into headings. If you
20713 want to convert only the first line of this region, use one
20714 universal prefix argument.
20715
20716 - If it is a plain list item, turn all plain list items into headings.
20717
20718 When converting a line into a heading, the number of stars is chosen
20719 such that the lines become children of the current entry. However,
20720 when a numeric prefix argument is given, its value determines the
20721 number of stars to add."
20722 (interactive "P")
20723 (let ((skip-blanks
20724 (function
20725 ;; Return beginning of first non-blank line, starting from
20726 ;; line at POS.
20727 (lambda (pos)
20728 (save-excursion
20729 (goto-char pos)
20730 (while (org-at-comment-p) (forward-line))
20731 (skip-chars-forward " \r\t\n")
20732 (point-at-bol)))))
20733 beg end toggled)
20734 ;; Determine boundaries of changes. If a universal prefix has
20735 ;; been given, put the list in a region. If region ends at a bol,
20736 ;; do not consider the last line to be in the region.
20737
20738 (when (and current-prefix-arg (org-at-item-p))
20739 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20740 (org-mark-element))
20741
20742 (if (org-region-active-p)
20743 (setq beg (funcall skip-blanks (region-beginning))
20744 end (copy-marker (save-excursion
20745 (goto-char (region-end))
20746 (if (bolp) (point) (point-at-eol)))))
20747 (setq beg (funcall skip-blanks (point-at-bol))
20748 end (copy-marker (point-at-eol))))
20749 ;; Ensure inline tasks don't count as headings.
20750 (org-with-limited-levels
20751 (save-excursion
20752 (goto-char beg)
20753 (cond
20754 ;; Case 1. Started at an heading: de-star headings.
20755 ((org-at-heading-p)
20756 (while (< (point) end)
20757 (when (org-at-heading-p t)
20758 (looking-at org-outline-regexp) (replace-match "")
20759 (setq toggled t))
20760 (forward-line)))
20761 ;; Case 2. Started at an item: change items into headlines.
20762 ;; One star will be added by `org-list-to-subtree'.
20763 ((org-at-item-p)
20764 (let* ((stars (make-string
20765 ;; subtract the star that will be added again by
20766 ;; `org-list-to-subtree'
20767 (if (numberp nstars) (1- nstars)
20768 (or (org-current-level) 0))
20769 ?*))
20770 (add-stars
20771 (cond (nstars "") ; stars from prefix only
20772 ((equal stars "") "") ; before first heading
20773 (org-odd-levels-only "*") ; inside heading, odd
20774 (t "")))) ; inside heading, oddeven
20775 (while (< (point) end)
20776 (when (org-at-item-p)
20777 ;; Pay attention to cases when region ends before list.
20778 (let* ((struct (org-list-struct))
20779 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20780 (save-restriction
20781 (narrow-to-region (point) list-end)
20782 (insert
20783 (org-list-to-subtree
20784 (org-list-parse-list t)
20785 '(:istart (concat stars add-stars (funcall get-stars depth))
20786 :icount (concat stars add-stars (funcall get-stars depth)))))))
20787 (setq toggled t))
20788 (forward-line))))
20789 ;; Case 3. Started at normal text: make every line an heading,
20790 ;; skipping headlines and items.
20791 (t (let* ((stars
20792 (make-string
20793 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20794 (add-stars
20795 (cond (nstars "") ; stars from prefix only
20796 ((equal stars "") "*") ; before first heading
20797 (org-odd-levels-only "**") ; inside heading, odd
20798 (t "*"))) ; inside heading, oddeven
20799 (rpl (concat stars add-stars " "))
20800 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20801 (while (< (point) (if (equal nstars '(4)) lend end))
20802 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20803 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20804 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20805 (forward-line)))))))
20806 (unless toggled (message "Cannot toggle heading from here"))))
20807
20808 (defun org-meta-return (&optional arg)
20809 "Insert a new heading or wrap a region in a table.
20810 Calls `org-insert-heading' or `org-table-wrap-region', depending
20811 on context. See the individual commands for more information."
20812 (interactive "P")
20813 (org-check-before-invisible-edit 'insert)
20814 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20815 (let* ((element (org-element-at-point))
20816 (type (org-element-type element)))
20817 (when (eq type 'table-row)
20818 (setq element (org-element-property :parent element))
20819 (setq type 'table))
20820 (if (and (eq type 'table)
20821 (eq (org-element-property :type element) 'org)
20822 (>= (point) (org-element-property :contents-begin element))
20823 (< (point) (org-element-property :contents-end element)))
20824 (call-interactively 'org-table-wrap-region)
20825 (call-interactively 'org-insert-heading)))))
20826
20827 ;;; Menu entries
20828
20829 (defsubst org-in-subtree-not-table-p ()
20830 "Are we in a subtree and not in a table?"
20831 (and (not (org-before-first-heading-p))
20832 (not (org-at-table-p))))
20833
20834 ;; Define the Org-mode menus
20835 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20836 '("Tbl"
20837 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20838 ["Next Field" org-cycle (org-at-table-p)]
20839 ["Previous Field" org-shifttab (org-at-table-p)]
20840 ["Next Row" org-return (org-at-table-p)]
20841 "--"
20842 ["Blank Field" org-table-blank-field (org-at-table-p)]
20843 ["Edit Field" org-table-edit-field (org-at-table-p)]
20844 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20845 "--"
20846 ("Column"
20847 ["Move Column Left" org-metaleft (org-at-table-p)]
20848 ["Move Column Right" org-metaright (org-at-table-p)]
20849 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20850 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20851 ("Row"
20852 ["Move Row Up" org-metaup (org-at-table-p)]
20853 ["Move Row Down" org-metadown (org-at-table-p)]
20854 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20855 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20856 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20857 "--"
20858 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20859 ("Rectangle"
20860 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20861 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20862 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20863 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20864 "--"
20865 ("Calculate"
20866 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20867 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20868 ["Edit Formulas" org-edit-special (org-at-table-p)]
20869 "--"
20870 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20871 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20872 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20873 "--"
20874 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20875 "--"
20876 ["Sum Column/Rectangle" org-table-sum
20877 (or (org-at-table-p) (org-region-active-p))]
20878 ["Which Column?" org-table-current-column (org-at-table-p)])
20879 ["Debug Formulas"
20880 org-table-toggle-formula-debugger
20881 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20882 ["Show Col/Row Numbers"
20883 org-table-toggle-coordinate-overlays
20884 :style toggle
20885 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20886 "--"
20887 ["Create" org-table-create (and (not (org-at-table-p))
20888 org-enable-table-editor)]
20889 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20890 ["Import from File" org-table-import (not (org-at-table-p))]
20891 ["Export to File" org-table-export (org-at-table-p)]
20892 "--"
20893 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20894
20895 (easy-menu-define org-org-menu org-mode-map "Org menu"
20896 '("Org"
20897 ("Show/Hide"
20898 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20899 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20900 ["Sparse Tree..." org-sparse-tree t]
20901 ["Reveal Context" org-reveal t]
20902 ["Show All" show-all t]
20903 "--"
20904 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20905 "--"
20906 ["New Heading" org-insert-heading t]
20907 ("Navigate Headings"
20908 ["Up" outline-up-heading t]
20909 ["Next" outline-next-visible-heading t]
20910 ["Previous" outline-previous-visible-heading t]
20911 ["Next Same Level" outline-forward-same-level t]
20912 ["Previous Same Level" outline-backward-same-level t]
20913 "--"
20914 ["Jump" org-goto t])
20915 ("Edit Structure"
20916 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20917 "--"
20918 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20919 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20920 "--"
20921 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20922 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20923 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20924 "--"
20925 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20926 "--"
20927 ["Copy visible text" org-copy-visible t]
20928 "--"
20929 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20930 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20931 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20932 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20933 "--"
20934 ["Sort Region/Children" org-sort t]
20935 "--"
20936 ["Convert to odd levels" org-convert-to-odd-levels t]
20937 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20938 ("Editing"
20939 ["Emphasis..." org-emphasize t]
20940 ["Edit Source Example" org-edit-special t]
20941 "--"
20942 ["Footnote new/jump" org-footnote-action t]
20943 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20944 ("Archive"
20945 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20946 "--"
20947 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20948 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20949 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20950 )
20951 "--"
20952 ("Hyperlinks"
20953 ["Store Link (Global)" org-store-link t]
20954 ["Find existing link to here" org-occur-link-in-agenda-files t]
20955 ["Insert Link" org-insert-link t]
20956 ["Follow Link" org-open-at-point t]
20957 "--"
20958 ["Next link" org-next-link t]
20959 ["Previous link" org-previous-link t]
20960 "--"
20961 ["Descriptive Links"
20962 org-toggle-link-display
20963 :style radio
20964 :selected org-descriptive-links
20965 ]
20966 ["Literal Links"
20967 org-toggle-link-display
20968 :style radio
20969 :selected (not org-descriptive-links)])
20970 "--"
20971 ("TODO Lists"
20972 ["TODO/DONE/-" org-todo t]
20973 ("Select keyword"
20974 ["Next keyword" org-shiftright (org-at-heading-p)]
20975 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20976 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20977 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20978 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20979 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20980 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20981 "--"
20982 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20983 :selected org-enforce-todo-dependencies :style toggle :active t]
20984 "Settings for tree at point"
20985 ["Do Children sequentially" org-toggle-ordered-property :style radio
20986 :selected (org-entry-get nil "ORDERED")
20987 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20988 ["Do Children parallel" org-toggle-ordered-property :style radio
20989 :selected (not (org-entry-get nil "ORDERED"))
20990 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20991 "--"
20992 ["Set Priority" org-priority t]
20993 ["Priority Up" org-shiftup t]
20994 ["Priority Down" org-shiftdown t]
20995 "--"
20996 ["Get news from all feeds" org-feed-update-all t]
20997 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20998 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20999 ("TAGS and Properties"
21000 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21001 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21002 "--"
21003 ["Set property" org-set-property (not (org-before-first-heading-p))]
21004 ["Column view of properties" org-columns t]
21005 ["Insert Column View DBlock" org-insert-columns-dblock t])
21006 ("Dates and Scheduling"
21007 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21008 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21009 ("Change Date"
21010 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21011 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21012 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21013 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21014 ["Compute Time Range" org-evaluate-time-range t]
21015 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21016 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21017 "--"
21018 ["Custom time format" org-toggle-time-stamp-overlays
21019 :style radio :selected org-display-custom-times]
21020 "--"
21021 ["Goto Calendar" org-goto-calendar t]
21022 ["Date from Calendar" org-date-from-calendar t]
21023 "--"
21024 ["Start/Restart Timer" org-timer-start t]
21025 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21026 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21027 ["Insert Timer String" org-timer t]
21028 ["Insert Timer Item" org-timer-item t])
21029 ("Logging work"
21030 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21031 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21032 ["Clock out" org-clock-out t]
21033 ["Clock cancel" org-clock-cancel t]
21034 "--"
21035 ["Mark as default task" org-clock-mark-default-task t]
21036 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21037 ["Goto running clock" org-clock-goto t]
21038 "--"
21039 ["Display times" org-clock-display t]
21040 ["Create clock table" org-clock-report t]
21041 "--"
21042 ["Record DONE time"
21043 (progn (setq org-log-done (not org-log-done))
21044 (message "Switching to %s will %s record a timestamp"
21045 (car org-done-keywords)
21046 (if org-log-done "automatically" "not")))
21047 :style toggle :selected org-log-done])
21048 "--"
21049 ["Agenda Command..." org-agenda t]
21050 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21051 ("File List for Agenda")
21052 ("Special views current file"
21053 ["TODO Tree" org-show-todo-tree t]
21054 ["Check Deadlines" org-check-deadlines t]
21055 ["Timeline" org-timeline t]
21056 ["Tags/Property tree" org-match-sparse-tree t])
21057 "--"
21058 ["Export/Publish..." org-export-dispatch t]
21059 ("LaTeX"
21060 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21061 :selected org-cdlatex-mode]
21062 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21063 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21064 ["Modify math symbol" org-cdlatex-math-modify
21065 (org-inside-LaTeX-fragment-p)]
21066 ["Insert citation" org-reftex-citation t]
21067 "--"
21068 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21069 "--"
21070 ("MobileOrg"
21071 ["Push Files and Views" org-mobile-push t]
21072 ["Get Captured and Flagged" org-mobile-pull t]
21073 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21074 "--"
21075 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21076 "--"
21077 ("Documentation"
21078 ["Show Version" org-version t]
21079 ["Info Documentation" org-info t])
21080 ("Customize"
21081 ["Browse Org Group" org-customize t]
21082 "--"
21083 ["Expand This Menu" org-create-customize-menu
21084 (fboundp 'customize-menu-create)])
21085 ["Send bug report" org-submit-bug-report t]
21086 "--"
21087 ("Refresh/Reload"
21088 ["Refresh setup current buffer" org-mode-restart t]
21089 ["Reload Org (after update)" org-reload t]
21090 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21091 ))
21092
21093 (defun org-info (&optional node)
21094 "Read documentation for Org-mode in the info system.
21095 With optional NODE, go directly to that node."
21096 (interactive)
21097 (info (format "(org)%s" (or node ""))))
21098
21099 ;;;###autoload
21100 (defun org-submit-bug-report ()
21101 "Submit a bug report on Org-mode via mail.
21102
21103 Don't hesitate to report any problems or inaccurate documentation.
21104
21105 If you don't have setup sending mail from (X)Emacs, please copy the
21106 output buffer into your mail program, as it gives us important
21107 information about your Org-mode version and configuration."
21108 (interactive)
21109 (require 'reporter)
21110 (org-load-modules-maybe)
21111 (org-require-autoloaded-modules)
21112 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21113 (reporter-submit-bug-report
21114 "emacs-orgmode@gnu.org"
21115 (org-version nil 'full)
21116 (let (list)
21117 (save-window-excursion
21118 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21119 (delete-other-windows)
21120 (erase-buffer)
21121 (insert "You are about to submit a bug report to the Org-mode mailing list.
21122
21123 We would like to add your full Org-mode and Outline configuration to the
21124 bug report. This greatly simplifies the work of the maintainer and
21125 other experts on the mailing list.
21126
21127 HOWEVER, some variables you have customized may contain private
21128 information. The names of customers, colleagues, or friends, might
21129 appear in the form of file names, tags, todo states, or search strings.
21130 If you answer yes to the prompt, you might want to check and remove
21131 such private information before sending the email.")
21132 (add-text-properties (point-min) (point-max) '(face org-warning))
21133 (when (yes-or-no-p "Include your Org-mode configuration ")
21134 (mapatoms
21135 (lambda (v)
21136 (and (boundp v)
21137 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21138 (or (and (symbol-value v)
21139 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21140 (and
21141 (get v 'custom-type) (get v 'standard-value)
21142 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21143 (push v list)))))
21144 (kill-buffer (get-buffer "*Warn about privacy*"))
21145 list))
21146 nil nil
21147 "Remember to cover the basics, that is, what you expected to happen and
21148 what in fact did happen. You don't know how to make a good report? See
21149
21150 http://orgmode.org/manual/Feedback.html#Feedback
21151
21152 Your bug report will be posted to the Org-mode mailing list.
21153 ------------------------------------------------------------------------")
21154 (save-excursion
21155 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21156 (replace-match "\\1Bug: \\3 [\\2]")))))
21157
21158
21159 (defun org-install-agenda-files-menu ()
21160 (let ((bl (buffer-list)))
21161 (save-excursion
21162 (while bl
21163 (set-buffer (pop bl))
21164 (if (derived-mode-p 'org-mode) (setq bl nil)))
21165 (when (derived-mode-p 'org-mode)
21166 (easy-menu-change
21167 '("Org") "File List for Agenda"
21168 (append
21169 (list
21170 ["Edit File List" (org-edit-agenda-file-list) t]
21171 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21172 ["Remove Current File from List" org-remove-file t]
21173 ["Cycle through agenda files" org-cycle-agenda-files t]
21174 ["Occur in all agenda files" org-occur-in-agenda-files t]
21175 "--")
21176 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21177
21178 ;;;; Documentation
21179
21180 (defun org-require-autoloaded-modules ()
21181 (interactive)
21182 (mapc 'require
21183 '(org-agenda org-archive org-attach org-clock org-colview org-id
21184 org-table org-timer)))
21185
21186 ;;;###autoload
21187 (defun org-reload (&optional uncompiled)
21188 "Reload all org lisp files.
21189 With prefix arg UNCOMPILED, load the uncompiled versions."
21190 (interactive "P")
21191 (require 'loadhist)
21192 (let* ((org-dir (org-find-library-dir "org"))
21193 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21194 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21195 (remove-re (mapconcat 'identity
21196 (mapcar (lambda (f) (concat "^" f "$"))
21197 (list (if (featurep 'xemacs)
21198 "org-colview"
21199 "org-colview-xemacs")
21200 "org" "org-loaddefs" "org-version"))
21201 "\\|"))
21202 (feats (delete-dups
21203 (mapcar 'file-name-sans-extension
21204 (mapcar 'file-name-nondirectory
21205 (delq nil
21206 (mapcar 'feature-file
21207 features))))))
21208 (lfeat (append
21209 (sort
21210 (setq feats
21211 (delq nil (mapcar
21212 (lambda (f)
21213 (if (and (string-match feature-re f)
21214 (not (string-match remove-re f)))
21215 f nil))
21216 feats)))
21217 'string-lessp)
21218 (list "org-version" "org")))
21219 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21220 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21221 load-uncore load-misses)
21222 (setq load-misses
21223 (delq 't
21224 (mapcar (lambda (f)
21225 (or (org-load-noerror-mustsuffix (concat org-dir f))
21226 (and (string= org-dir contrib-dir)
21227 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21228 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21229 (add-to-list 'load-uncore f 'append)
21230 't)
21231 f))
21232 lfeat)))
21233 (if load-uncore
21234 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21235 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21236 (if load-misses
21237 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21238 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21239 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21240
21241 ;;;###autoload
21242 (defun org-customize ()
21243 "Call the customize function with org as argument."
21244 (interactive)
21245 (org-load-modules-maybe)
21246 (org-require-autoloaded-modules)
21247 (customize-browse 'org))
21248
21249 (defun org-create-customize-menu ()
21250 "Create a full customization menu for Org-mode, insert it into the menu."
21251 (interactive)
21252 (org-load-modules-maybe)
21253 (org-require-autoloaded-modules)
21254 (if (fboundp 'customize-menu-create)
21255 (progn
21256 (easy-menu-change
21257 '("Org") "Customize"
21258 `(["Browse Org group" org-customize t]
21259 "--"
21260 ,(customize-menu-create 'org)
21261 ["Set" Custom-set t]
21262 ["Save" Custom-save t]
21263 ["Reset to Current" Custom-reset-current t]
21264 ["Reset to Saved" Custom-reset-saved t]
21265 ["Reset to Standard Settings" Custom-reset-standard t]))
21266 (message "\"Org\"-menu now contains full customization menu"))
21267 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21268
21269 ;;;; Miscellaneous stuff
21270
21271 ;;; Generally useful functions
21272
21273 (defun org-get-at-bol (property)
21274 "Get text property PROPERTY at beginning of line."
21275 (get-text-property (point-at-bol) property))
21276
21277 (defun org-find-text-property-in-string (prop s)
21278 "Return the first non-nil value of property PROP in string S."
21279 (or (get-text-property 0 prop s)
21280 (get-text-property (or (next-single-property-change 0 prop s) 0)
21281 prop s)))
21282
21283 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21284 "Display the given MESSAGE as a warning."
21285 (if (fboundp 'display-warning)
21286 (display-warning 'org message
21287 (if (featurep 'xemacs) 'warning :warning))
21288 (let ((buf (get-buffer-create "*Org warnings*")))
21289 (with-current-buffer buf
21290 (goto-char (point-max))
21291 (insert "Warning (Org): " message)
21292 (unless (bolp)
21293 (newline)))
21294 (display-buffer buf)
21295 (sit-for 0))))
21296
21297 (defun org-eval (form)
21298 "Eval FORM and return result."
21299 (condition-case error
21300 (eval form)
21301 (error (format "%%![Error: %s]" error))))
21302
21303 (defun org-in-clocktable-p ()
21304 "Check if the cursor is in a clocktable."
21305 (let ((pos (point)) start)
21306 (save-excursion
21307 (end-of-line 1)
21308 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21309 (setq start (match-beginning 0))
21310 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21311 (>= (match-end 0) pos)
21312 start))))
21313
21314 (defun org-in-commented-line ()
21315 "Is point in a line starting with `#'?"
21316 (equal (char-after (point-at-bol)) ?#))
21317
21318 (defun org-in-indented-comment-line ()
21319 "Is point in a line starting with `#' after some white space?"
21320 (save-excursion
21321 (save-match-data
21322 (goto-char (point-at-bol))
21323 (looking-at "[ \t]*#"))))
21324
21325 (defun org-in-verbatim-emphasis ()
21326 (save-match-data
21327 (and (org-in-regexp org-emph-re 2)
21328 (>= (point) (match-beginning 3))
21329 (<= (point) (match-end 4))
21330 (member (match-string 3) '("=" "~")))))
21331
21332 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21333 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21334 (if (and marker (marker-buffer marker)
21335 (buffer-live-p (marker-buffer marker)))
21336 (progn
21337 (org-pop-to-buffer-same-window (marker-buffer marker))
21338 (if (or (> marker (point-max)) (< marker (point-min)))
21339 (widen))
21340 (goto-char marker)
21341 (org-show-context 'org-goto))
21342 (if bookmark
21343 (bookmark-jump bookmark)
21344 (error "Cannot find location"))))
21345
21346 (defun org-quote-csv-field (s)
21347 "Quote field for inclusion in CSV material."
21348 (if (string-match "[\",]" s)
21349 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21350 s))
21351
21352 (defun org-force-self-insert (N)
21353 "Needed to enforce self-insert under remapping."
21354 (interactive "p")
21355 (self-insert-command N))
21356
21357 (defun org-string-width (s)
21358 "Compute width of string, ignoring invisible characters.
21359 This ignores character with invisibility property `org-link', and also
21360 characters with property `org-cwidth', because these will become invisible
21361 upon the next fontification round."
21362 (let (b l)
21363 (when (or (eq t buffer-invisibility-spec)
21364 (assq 'org-link buffer-invisibility-spec))
21365 (while (setq b (text-property-any 0 (length s)
21366 'invisible 'org-link s))
21367 (setq s (concat (substring s 0 b)
21368 (substring s (or (next-single-property-change
21369 b 'invisible s) (length s)))))))
21370 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21371 (setq s (concat (substring s 0 b)
21372 (substring s (or (next-single-property-change
21373 b 'org-cwidth s) (length s))))))
21374 (setq l (string-width s) b -1)
21375 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21376 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21377 l))
21378
21379 (defun org-shorten-string (s maxlength)
21380 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21381 If the string is shorter or has length MAXLENGTH, just return the
21382 original string. If it is longer, the functions finds a space in the
21383 string, breaks this string off at that locations and adds three dots
21384 as ellipsis. Including the ellipsis, the string will not be longer
21385 than MAXLENGTH. If finding a good breaking point in the string does
21386 not work, the string is just chopped off in the middle of a word
21387 if necessary."
21388 (if (<= (length s) maxlength)
21389 s
21390 (let* ((n (max (- maxlength 4) 1))
21391 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21392 (if (string-match re s)
21393 (concat (match-string 1 s) "...")
21394 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21395
21396 (defun org-get-indentation (&optional line)
21397 "Get the indentation of the current line, interpreting tabs.
21398 When LINE is given, assume it represents a line and compute its indentation."
21399 (if line
21400 (if (string-match "^ *" (org-remove-tabs line))
21401 (match-end 0))
21402 (save-excursion
21403 (beginning-of-line 1)
21404 (skip-chars-forward " \t")
21405 (current-column))))
21406
21407 (defun org-get-string-indentation (s)
21408 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21409 (let ((n -1) (i 0) (w tab-width) c)
21410 (catch 'exit
21411 (while (< (setq n (1+ n)) (length s))
21412 (setq c (aref s n))
21413 (cond ((= c ?\ ) (setq i (1+ i)))
21414 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21415 (t (throw 'exit t)))))
21416 i))
21417
21418 (defun org-remove-tabs (s &optional width)
21419 "Replace tabulators in S with spaces.
21420 Assumes that s is a single line, starting in column 0."
21421 (setq width (or width tab-width))
21422 (while (string-match "\t" s)
21423 (setq s (replace-match
21424 (make-string
21425 (- (* width (/ (+ (match-beginning 0) width) width))
21426 (match-beginning 0)) ?\ )
21427 t t s)))
21428 s)
21429
21430 (defun org-fix-indentation (line ind)
21431 "Fix indentation in LINE.
21432 IND is a cons cell with target and minimum indentation.
21433 If the current indentation in LINE is smaller than the minimum,
21434 leave it alone. If it is larger than ind, set it to the target."
21435 (let* ((l (org-remove-tabs line))
21436 (i (org-get-indentation l))
21437 (i1 (car ind)) (i2 (cdr ind)))
21438 (if (>= i i2) (setq l (substring line i2)))
21439 (if (> i1 0)
21440 (concat (make-string i1 ?\ ) l)
21441 l)))
21442
21443 (defun org-remove-indentation (code &optional n)
21444 "Remove the maximum common indentation from the lines in CODE.
21445 N may optionally be the number of spaces to remove."
21446 (with-temp-buffer
21447 (insert code)
21448 (org-do-remove-indentation n)
21449 (buffer-string)))
21450
21451 (defun org-do-remove-indentation (&optional n)
21452 "Remove the maximum common indentation from the buffer."
21453 (untabify (point-min) (point-max))
21454 (let ((min 10000) re)
21455 (if n
21456 (setq min n)
21457 (goto-char (point-min))
21458 (while (re-search-forward "^ *[^ \n]" nil t)
21459 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21460 (unless (or (= min 0) (= min 10000))
21461 (setq re (format "^ \\{%d\\}" min))
21462 (goto-char (point-min))
21463 (while (re-search-forward re nil t)
21464 (replace-match "")
21465 (end-of-line 1))
21466 min)))
21467
21468 (defun org-fill-template (template alist)
21469 "Find each %key of ALIST in TEMPLATE and replace it."
21470 (let ((case-fold-search nil)
21471 entry key value)
21472 (setq alist (sort (copy-sequence alist)
21473 (lambda (a b) (< (length (car a)) (length (car b))))))
21474 (while (setq entry (pop alist))
21475 (setq template
21476 (replace-regexp-in-string
21477 (concat "%" (regexp-quote (car entry)))
21478 (or (cdr entry) "") template t t)))
21479 template))
21480
21481 (defun org-base-buffer (buffer)
21482 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21483 (if (not buffer)
21484 buffer
21485 (or (buffer-base-buffer buffer)
21486 buffer)))
21487
21488 (defun org-trim (s)
21489 "Remove whitespace at beginning and end of string."
21490 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21491 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21492 s)
21493
21494 (defun org-wrap (string &optional width lines)
21495 "Wrap string to either a number of lines, or a width in characters.
21496 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21497 that costs. If there is a word longer than WIDTH, the text is actually
21498 wrapped to the length of that word.
21499 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21500 many lines, whatever width that takes.
21501 The return value is a list of lines, without newlines at the end."
21502 (let* ((words (org-split-string string "[ \t\n]+"))
21503 (maxword (apply 'max (mapcar 'org-string-width words)))
21504 w ll)
21505 (cond (width
21506 (org-do-wrap words (max maxword width)))
21507 (lines
21508 (setq w maxword)
21509 (setq ll (org-do-wrap words maxword))
21510 (if (<= (length ll) lines)
21511 ll
21512 (setq ll words)
21513 (while (> (length ll) lines)
21514 (setq w (1+ w))
21515 (setq ll (org-do-wrap words w)))
21516 ll))
21517 (t (error "Cannot wrap this")))))
21518
21519 (defun org-do-wrap (words width)
21520 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21521 (let (lines line)
21522 (while words
21523 (setq line (pop words))
21524 (while (and words (< (+ (length line) (length (car words))) width))
21525 (setq line (concat line " " (pop words))))
21526 (setq lines (push line lines)))
21527 (nreverse lines)))
21528
21529 (defun org-split-string (string &optional separators)
21530 "Splits STRING into substrings at SEPARATORS.
21531 No empty strings are returned if there are matches at the beginning
21532 and end of string."
21533 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21534 (start 0)
21535 notfirst
21536 (list nil))
21537 (while (and (string-match rexp string
21538 (if (and notfirst
21539 (= start (match-beginning 0))
21540 (< start (length string)))
21541 (1+ start) start))
21542 (< (match-beginning 0) (length string)))
21543 (setq notfirst t)
21544 (or (eq (match-beginning 0) 0)
21545 (and (eq (match-beginning 0) (match-end 0))
21546 (eq (match-beginning 0) start))
21547 (setq list
21548 (cons (substring string start (match-beginning 0))
21549 list)))
21550 (setq start (match-end 0)))
21551 (or (eq start (length string))
21552 (setq list
21553 (cons (substring string start)
21554 list)))
21555 (nreverse list)))
21556
21557 (defun org-quote-vert (s)
21558 "Replace \"|\" with \"\\vert\"."
21559 (while (string-match "|" s)
21560 (setq s (replace-match "\\vert" t t s)))
21561 s)
21562
21563 (defun org-uuidgen-p (s)
21564 "Is S an ID created by UUIDGEN?"
21565 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21566
21567 (defun org-in-src-block-p (&optional inside)
21568 "Whether point is in a code source block.
21569 When INSIDE is non-nil, don't consider we are within a src block
21570 when point is at #+BEGIN_SRC or #+END_SRC."
21571 (let ((case-fold-search t) ov)
21572 (or (and (setq ov (overlays-at (point)))
21573 (memq 'org-block-background
21574 (overlay-properties (car ov))))
21575 (and (not inside)
21576 (save-match-data
21577 (save-excursion
21578 (beginning-of-line)
21579 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21580
21581 (defun org-context ()
21582 "Return a list of contexts of the current cursor position.
21583 If several contexts apply, all are returned.
21584 Each context entry is a list with a symbol naming the context, and
21585 two positions indicating start and end of the context. Possible
21586 contexts are:
21587
21588 :headline anywhere in a headline
21589 :headline-stars on the leading stars in a headline
21590 :todo-keyword on a TODO keyword (including DONE) in a headline
21591 :tags on the TAGS in a headline
21592 :priority on the priority cookie in a headline
21593 :item on the first line of a plain list item
21594 :item-bullet on the bullet/number of a plain list item
21595 :checkbox on the checkbox in a plain list item
21596 :table in an org-mode table
21597 :table-special on a special filed in a table
21598 :table-table in a table.el table
21599 :clocktable in a clocktable
21600 :src-block in a source block
21601 :link on a hyperlink
21602 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21603 :target on a <<target>>
21604 :radio-target on a <<<radio-target>>>
21605 :latex-fragment on a LaTeX fragment
21606 :latex-preview on a LaTeX fragment with overlaid preview image
21607
21608 This function expects the position to be visible because it uses font-lock
21609 faces as a help to recognize the following contexts: :table-special, :link,
21610 and :keyword."
21611 (let* ((f (get-text-property (point) 'face))
21612 (faces (if (listp f) f (list f)))
21613 (case-fold-search t)
21614 (p (point)) clist o)
21615 ;; First the large context
21616 (cond
21617 ((org-at-heading-p t)
21618 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21619 (when (progn
21620 (beginning-of-line 1)
21621 (looking-at org-todo-line-tags-regexp))
21622 (push (org-point-in-group p 1 :headline-stars) clist)
21623 (push (org-point-in-group p 2 :todo-keyword) clist)
21624 (push (org-point-in-group p 4 :tags) clist))
21625 (goto-char p)
21626 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21627 (if (looking-at "\\[#[A-Z0-9]\\]")
21628 (push (org-point-in-group p 0 :priority) clist)))
21629
21630 ((org-at-item-p)
21631 (push (org-point-in-group p 2 :item-bullet) clist)
21632 (push (list :item (point-at-bol)
21633 (save-excursion (org-end-of-item) (point)))
21634 clist)
21635 (and (org-at-item-checkbox-p)
21636 (push (org-point-in-group p 0 :checkbox) clist)))
21637
21638 ((org-at-table-p)
21639 (push (list :table (org-table-begin) (org-table-end)) clist)
21640 (if (memq 'org-formula faces)
21641 (push (list :table-special
21642 (previous-single-property-change p 'face)
21643 (next-single-property-change p 'face)) clist)))
21644 ((org-at-table-p 'any)
21645 (push (list :table-table) clist)))
21646 (goto-char p)
21647
21648 (let ((case-fold-search t))
21649 ;; New the "medium" contexts: clocktables, source blocks
21650 (cond ((org-in-clocktable-p)
21651 (push (list :clocktable
21652 (and (or (looking-at "#\\+BEGIN: clocktable")
21653 (search-backward "#+BEGIN: clocktable" nil t))
21654 (match-beginning 0))
21655 (and (re-search-forward "#\\+END:?" nil t)
21656 (match-end 0))) clist))
21657 ((org-in-src-block-p)
21658 (push (list :src-block
21659 (and (or (looking-at "#\\+BEGIN_SRC")
21660 (search-backward "#+BEGIN_SRC" nil t))
21661 (match-beginning 0))
21662 (and (search-forward "#+END_SRC" nil t)
21663 (match-beginning 0))) clist))))
21664 (goto-char p)
21665
21666 ;; Now the small context
21667 (cond
21668 ((org-at-timestamp-p)
21669 (push (org-point-in-group p 0 :timestamp) clist))
21670 ((memq 'org-link faces)
21671 (push (list :link
21672 (previous-single-property-change p 'face)
21673 (next-single-property-change p 'face)) clist))
21674 ((memq 'org-special-keyword faces)
21675 (push (list :keyword
21676 (previous-single-property-change p 'face)
21677 (next-single-property-change p 'face)) clist))
21678 ((org-at-target-p)
21679 (push (org-point-in-group p 0 :target) clist)
21680 (goto-char (1- (match-beginning 0)))
21681 (if (looking-at org-radio-target-regexp)
21682 (push (org-point-in-group p 0 :radio-target) clist))
21683 (goto-char p))
21684 ((setq o (car (delq nil
21685 (mapcar
21686 (lambda (x)
21687 (if (memq x org-latex-fragment-image-overlays) x))
21688 (overlays-at (point))))))
21689 (push (list :latex-fragment
21690 (overlay-start o) (overlay-end o)) clist)
21691 (push (list :latex-preview
21692 (overlay-start o) (overlay-end o)) clist))
21693 ((org-inside-LaTeX-fragment-p)
21694 ;; FIXME: positions wrong.
21695 (push (list :latex-fragment (point) (point)) clist)))
21696
21697 (setq clist (nreverse (delq nil clist)))
21698 clist))
21699
21700 ;; FIXME: Compare with at-regexp-p Do we need both?
21701 (defun org-in-regexp (re &optional nlines visually)
21702 "Check if point is inside a match of regexp.
21703 Normally only the current line is checked, but you can include NLINES extra
21704 lines both before and after point into the search.
21705 If VISUALLY is set, require that the cursor is not after the match but
21706 really on, so that the block visually is on the match."
21707 (catch 'exit
21708 (let ((pos (point))
21709 (eol (point-at-eol (+ 1 (or nlines 0))))
21710 (inc (if visually 1 0)))
21711 (save-excursion
21712 (beginning-of-line (- 1 (or nlines 0)))
21713 (while (re-search-forward re eol t)
21714 (if (and (<= (match-beginning 0) pos)
21715 (>= (+ inc (match-end 0)) pos))
21716 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21717
21718 (defun org-at-regexp-p (regexp)
21719 "Is point inside a match of REGEXP in the current line?"
21720 (catch 'exit
21721 (save-excursion
21722 (let ((pos (point)) (end (point-at-eol)))
21723 (beginning-of-line 1)
21724 (while (re-search-forward regexp end t)
21725 (if (and (<= (match-beginning 0) pos)
21726 (>= (match-end 0) pos))
21727 (throw 'exit t)))
21728 nil))))
21729
21730 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21731 "Non-nil when point is between matches of START-RE and END-RE.
21732
21733 Also return a non-nil value when point is on one of the matches.
21734
21735 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21736 buffer positions. Default values are the positions of headlines
21737 surrounding the point.
21738
21739 The functions returns a cons cell whose car (resp. cdr) is the
21740 position before START-RE (resp. after END-RE)."
21741 (save-match-data
21742 (let ((pos (point))
21743 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21744 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21745 beg end)
21746 (save-excursion
21747 ;; Point is on a block when on START-RE or if START-RE can be
21748 ;; found before it...
21749 (and (or (org-at-regexp-p start-re)
21750 (re-search-backward start-re limit-up t))
21751 (setq beg (match-beginning 0))
21752 ;; ... and END-RE after it...
21753 (goto-char (match-end 0))
21754 (re-search-forward end-re limit-down t)
21755 (> (setq end (match-end 0)) pos)
21756 ;; ... without another START-RE in-between.
21757 (goto-char (match-beginning 0))
21758 (not (re-search-backward start-re (1+ beg) t))
21759 ;; Return value.
21760 (cons beg end))))))
21761
21762 (defun org-in-block-p (names)
21763 "Non-nil when point belongs to a block whose name belongs to NAMES.
21764
21765 NAMES is a list of strings containing names of blocks.
21766
21767 Return first block name matched, or nil. Beware that in case of
21768 nested blocks, the returned name may not belong to the closest
21769 block from point."
21770 (save-match-data
21771 (catch 'exit
21772 (let ((case-fold-search t)
21773 (lim-up (save-excursion (outline-previous-heading)))
21774 (lim-down (save-excursion (outline-next-heading))))
21775 (mapc (lambda (name)
21776 (let ((n (regexp-quote name)))
21777 (when (org-between-regexps-p
21778 (concat "^[ \t]*#\\+begin_" n)
21779 (concat "^[ \t]*#\\+end_" n)
21780 lim-up lim-down)
21781 (throw 'exit n))))
21782 names))
21783 nil)))
21784
21785 (defun org-in-drawer-p ()
21786 "Is point within a drawer?"
21787 (save-match-data
21788 (let ((case-fold-search t)
21789 (lim-up (save-excursion (outline-previous-heading)))
21790 (lim-down (save-excursion (outline-next-heading))))
21791 (org-between-regexps-p
21792 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21793 "^[ \t]*:end:.*$"
21794 lim-up lim-down))))
21795
21796 (defun org-occur-in-agenda-files (regexp &optional nlines)
21797 "Call `multi-occur' with buffers for all agenda files."
21798 (interactive "sOrg-files matching: \np")
21799 (let* ((files (org-agenda-files))
21800 (tnames (mapcar 'file-truename files))
21801 (extra org-agenda-text-search-extra-files)
21802 f)
21803 (when (eq (car extra) 'agenda-archives)
21804 (setq extra (cdr extra))
21805 (setq files (org-add-archive-files files)))
21806 (while (setq f (pop extra))
21807 (unless (member (file-truename f) tnames)
21808 (add-to-list 'files f 'append)
21809 (add-to-list 'tnames (file-truename f) 'append)))
21810 (multi-occur
21811 (mapcar (lambda (x)
21812 (with-current-buffer
21813 (or (get-file-buffer x) (find-file-noselect x))
21814 (widen)
21815 (current-buffer)))
21816 files)
21817 regexp)))
21818
21819 (if (boundp 'occur-mode-find-occurrence-hook)
21820 ;; Emacs 23
21821 (add-hook 'occur-mode-find-occurrence-hook
21822 (lambda ()
21823 (when (derived-mode-p 'org-mode)
21824 (org-reveal))))
21825 ;; Emacs 22
21826 (defadvice occur-mode-goto-occurrence
21827 (after org-occur-reveal activate)
21828 (and (derived-mode-p 'org-mode) (org-reveal)))
21829 (defadvice occur-mode-goto-occurrence-other-window
21830 (after org-occur-reveal activate)
21831 (and (derived-mode-p 'org-mode) (org-reveal)))
21832 (defadvice occur-mode-display-occurrence
21833 (after org-occur-reveal activate)
21834 (when (derived-mode-p 'org-mode)
21835 (let ((pos (occur-mode-find-occurrence)))
21836 (with-current-buffer (marker-buffer pos)
21837 (save-excursion
21838 (goto-char pos)
21839 (org-reveal)))))))
21840
21841 (defun org-occur-link-in-agenda-files ()
21842 "Create a link and search for it in the agendas.
21843 The link is not stored in `org-stored-links', it is just created
21844 for the search purpose."
21845 (interactive)
21846 (let ((link (condition-case nil
21847 (org-store-link nil)
21848 (error "Unable to create a link to here"))))
21849 (org-occur-in-agenda-files (regexp-quote link))))
21850
21851 (defun org-reverse-string (string)
21852 "Return the reverse of STRING."
21853 (apply 'string (reverse (string-to-list string))))
21854
21855 ;; defsubst org-uniquify must be defined before first use
21856
21857 (defun org-uniquify-alist (alist)
21858 "Merge elements of ALIST with the same key.
21859
21860 For example, in this alist:
21861
21862 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21863 => '((a 1 3) (b 2))
21864
21865 merge (a 1) and (a 3) into (a 1 3).
21866
21867 The function returns the new ALIST."
21868 (let (rtn)
21869 (mapc
21870 (lambda (e)
21871 (let (n)
21872 (if (not (assoc (car e) rtn))
21873 (push e rtn)
21874 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21875 (setq rtn (assq-delete-all (car e) rtn))
21876 (push n rtn))))
21877 alist)
21878 rtn))
21879
21880 (defun org-delete-all (elts list)
21881 "Remove all elements in ELTS from LIST."
21882 (while elts
21883 (setq list (delete (pop elts) list)))
21884 list)
21885
21886 (defun org-count (cl-item cl-seq)
21887 "Count the number of occurrences of ITEM in SEQ.
21888 Taken from `count' in cl-seq.el with all keyword arguments removed."
21889 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21890 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21891 (while (< cl-start cl-end)
21892 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21893 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21894 (setq cl-start (1+ cl-start)))
21895 cl-count))
21896
21897 (defun org-remove-if (predicate seq)
21898 "Remove everything from SEQ that fulfills PREDICATE."
21899 (let (res e)
21900 (while seq
21901 (setq e (pop seq))
21902 (if (not (funcall predicate e)) (push e res)))
21903 (nreverse res)))
21904
21905 (defun org-remove-if-not (predicate seq)
21906 "Remove everything from SEQ that does not fulfill PREDICATE."
21907 (let (res e)
21908 (while seq
21909 (setq e (pop seq))
21910 (if (funcall predicate e) (push e res)))
21911 (nreverse res)))
21912
21913 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21914 "Reduce two-argument FUNCTION across SEQ.
21915 Taken from `reduce' in cl-seq.el with all keyword arguments but
21916 \":initial-value\" removed."
21917 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21918 (cadr (memq :initial-value cl-keys)))
21919 (cl-seq (pop cl-seq))
21920 (t (funcall cl-func)))))
21921 (while cl-seq
21922 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21923 cl-accum))
21924
21925 (defun org-every (pred seq)
21926 "Return true if PREDICATE is true of every element of SEQ.
21927 Adapted from `every' in cl.el."
21928 (catch 'org-every
21929 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21930 t))
21931
21932 (defun org-some (pred seq)
21933 "Return true if PREDICATE is true of any element of SEQ.
21934 Adapted from `some' in cl.el."
21935 (catch 'org-some
21936 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21937 nil))
21938
21939 (defun org-back-over-empty-lines ()
21940 "Move backwards over whitespace, to the beginning of the first empty line.
21941 Returns the number of empty lines passed."
21942 (let ((pos (point)))
21943 (if (cdr (assoc 'heading org-blank-before-new-entry))
21944 (skip-chars-backward " \t\n\r")
21945 (unless (eobp)
21946 (forward-line -1)))
21947 (beginning-of-line 2)
21948 (goto-char (min (point) pos))
21949 (count-lines (point) pos)))
21950
21951 (defun org-skip-whitespace ()
21952 (skip-chars-forward " \t\n\r"))
21953
21954 (defun org-point-in-group (point group &optional context)
21955 "Check if POINT is in match-group GROUP.
21956 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21957 match. If the match group does not exist or point is not inside it,
21958 return nil."
21959 (and (match-beginning group)
21960 (>= point (match-beginning group))
21961 (<= point (match-end group))
21962 (if context
21963 (list context (match-beginning group) (match-end group))
21964 t)))
21965
21966 (defun org-switch-to-buffer-other-window (&rest args)
21967 "Switch to buffer in a second window on the current frame.
21968 In particular, do not allow pop-up frames.
21969 Returns the newly created buffer."
21970 (org-no-popups
21971 (apply 'switch-to-buffer-other-window args)))
21972
21973 (defun org-combine-plists (&rest plists)
21974 "Create a single property list from all plists in PLISTS.
21975 The process starts by copying the first list, and then setting properties
21976 from the other lists. Settings in the last list are the most significant
21977 ones and overrule settings in the other lists."
21978 (let ((rtn (copy-sequence (pop plists)))
21979 p v ls)
21980 (while plists
21981 (setq ls (pop plists))
21982 (while ls
21983 (setq p (pop ls) v (pop ls))
21984 (setq rtn (plist-put rtn p v))))
21985 rtn))
21986
21987 (defun org-replace-escapes (string table)
21988 "Replace %-escapes in STRING with values in TABLE.
21989 TABLE is an association list with keys like \"%a\" and string values.
21990 The sequences in STRING may contain normal field width and padding information,
21991 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21992 so values can contain further %-escapes if they are define later in TABLE."
21993 (let ((tbl (copy-alist table))
21994 (case-fold-search nil)
21995 (pchg 0)
21996 e re rpl)
21997 (while (setq e (pop tbl))
21998 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21999 (when (and (cdr e) (string-match re (cdr e)))
22000 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22001 (safe "SREF"))
22002 (add-text-properties 0 3 (list 'sref sref) safe)
22003 (setcdr e (replace-match safe t t (cdr e)))))
22004 (while (string-match re string)
22005 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22006 (cdr e)))
22007 (setq string (replace-match rpl t t string))))
22008 (while (setq pchg (next-property-change pchg string))
22009 (let ((sref (get-text-property pchg 'sref string)))
22010 (when (and sref (string-match "SREF" string pchg))
22011 (setq string (replace-match sref t t string)))))
22012 string))
22013
22014 (defun org-sublist (list start end)
22015 "Return a section of LIST, from START to END.
22016 Counting starts at 1."
22017 (let (rtn (c start))
22018 (setq list (nthcdr (1- start) list))
22019 (while (and list (<= c end))
22020 (push (pop list) rtn)
22021 (setq c (1+ c)))
22022 (nreverse rtn)))
22023
22024 (defun org-find-base-buffer-visiting (file)
22025 "Like `find-buffer-visiting' but always return the base buffer and
22026 not an indirect buffer."
22027 (let ((buf (or (get-file-buffer file)
22028 (find-buffer-visiting file))))
22029 (if buf
22030 (or (buffer-base-buffer buf) buf)
22031 nil)))
22032
22033 (defun org-image-file-name-regexp (&optional extensions)
22034 "Return regexp matching the file names of images.
22035 If EXTENSIONS is given, only match these."
22036 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22037 (image-file-name-regexp)
22038 (let ((image-file-name-extensions
22039 (or extensions
22040 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22041 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22042 (concat "\\."
22043 (regexp-opt (nconc (mapcar 'upcase
22044 image-file-name-extensions)
22045 image-file-name-extensions)
22046 t)
22047 "\\'"))))
22048
22049 (defun org-file-image-p (file &optional extensions)
22050 "Return non-nil if FILE is an image."
22051 (save-match-data
22052 (string-match (org-image-file-name-regexp extensions) file)))
22053
22054 (defun org-get-cursor-date (&optional with-time)
22055 "Return the date at cursor in as a time.
22056 This works in the calendar and in the agenda, anywhere else it just
22057 returns the current time.
22058 If WITH-TIME is non-nil, returns the time of the event at point (in
22059 the agenda) or the current time of the day."
22060 (let (date day defd tp tm hod mod)
22061 (when with-time
22062 (setq tp (get-text-property (point) 'time))
22063 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22064 (setq hod (string-to-number (match-string 1 tp))
22065 mod (string-to-number (match-string 2 tp))))
22066 (or tp (let ((now (decode-time)))
22067 (setq hod (nth 2 now)
22068 mod (nth 1 now)))))
22069 (cond
22070 ((eq major-mode 'calendar-mode)
22071 (setq date (calendar-cursor-to-date)
22072 defd (encode-time 0 (or mod 0) (or hod 0)
22073 (nth 1 date) (nth 0 date) (nth 2 date))))
22074 ((eq major-mode 'org-agenda-mode)
22075 (setq day (get-text-property (point) 'day))
22076 (if day
22077 (setq date (calendar-gregorian-from-absolute day)
22078 defd (encode-time 0 (or mod 0) (or hod 0)
22079 (nth 1 date) (nth 0 date) (nth 2 date))))))
22080 (or defd (current-time))))
22081
22082 (defun org-mark-subtree (&optional up)
22083 "Mark the current subtree.
22084 This puts point at the start of the current subtree, and mark at
22085 the end. If a numeric prefix UP is given, move up into the
22086 hierarchy of headlines by UP levels before marking the subtree."
22087 (interactive "P")
22088 (org-with-limited-levels
22089 (cond ((org-at-heading-p) (beginning-of-line))
22090 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22091 (t (outline-previous-visible-heading 1))))
22092 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22093 (if (org-called-interactively-p 'any)
22094 (call-interactively 'org-mark-element)
22095 (org-mark-element)))
22096
22097
22098 ;;; Indentation
22099
22100 (defun org-indent-line ()
22101 "Indent line depending on context."
22102 (interactive)
22103 (let* ((pos (point))
22104 (itemp (org-at-item-p))
22105 (case-fold-search t)
22106 (org-drawer-regexp (or org-drawer-regexp "\000"))
22107 (inline-task-p (and (featurep 'org-inlinetask)
22108 (org-inlinetask-in-task-p)))
22109 (inline-re (and inline-task-p
22110 (org-inlinetask-outline-regexp)))
22111 column)
22112 (if (and orgstruct-is-++ (eq pos (point)))
22113 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22114 (indent-according-to-mode))
22115 (beginning-of-line 1)
22116 (cond
22117 ;; Headings
22118 ((looking-at org-outline-regexp) (setq column 0))
22119 ;; Footnote definition
22120 ((looking-at org-footnote-definition-re) (setq column 0))
22121 ;; Literal examples
22122 ((looking-at "[ \t]*:\\( \\|$\\)")
22123 (setq column (org-get-indentation))) ; do nothing
22124 ;; Lists
22125 ((ignore-errors (goto-char (org-in-item-p)))
22126 (setq column (if itemp
22127 (org-get-indentation)
22128 (org-list-item-body-column (point))))
22129 (goto-char pos))
22130 ;; Drawers
22131 ((and (looking-at "[ \t]*:END:")
22132 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22133 (save-excursion
22134 (goto-char (1- (match-beginning 1)))
22135 (setq column (current-column))))
22136 ;; Special blocks
22137 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22138 (save-excursion
22139 (re-search-backward
22140 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22141 (setq column (org-get-indentation (match-string 0))))
22142 ((and (not (looking-at "[ \t]*#\\+begin_"))
22143 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22144 (save-excursion
22145 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22146 (setq column
22147 (cond ((equal (downcase (match-string 1)) "src")
22148 ;; src blocks: let `org-edit-src-exit' handle them
22149 (org-get-indentation))
22150 ((equal (downcase (match-string 1)) "example")
22151 (max (org-get-indentation)
22152 (org-get-indentation (match-string 0))))
22153 (t
22154 (org-get-indentation (match-string 0))))))
22155 ;; This line has nothing special, look at the previous relevant
22156 ;; line to compute indentation
22157 (t
22158 (beginning-of-line 0)
22159 (while (and (not (bobp))
22160 (not (looking-at org-table-line-regexp))
22161 (not (looking-at org-drawer-regexp))
22162 ;; When point started in an inline task, do not move
22163 ;; above task starting line.
22164 (not (and inline-task-p (looking-at inline-re)))
22165 ;; Skip drawers, blocks, empty lines, verbatim,
22166 ;; comments, tables, footnotes definitions, lists,
22167 ;; inline tasks.
22168 (or (and (looking-at "[ \t]*:END:")
22169 (re-search-backward org-drawer-regexp nil t))
22170 (and (looking-at "[ \t]*#\\+end_")
22171 (re-search-backward "[ \t]*#\\+begin_"nil t))
22172 (looking-at "[ \t]*[\n:#|]")
22173 (looking-at org-footnote-definition-re)
22174 (and (not inline-task-p)
22175 (featurep 'org-inlinetask)
22176 (org-inlinetask-in-task-p)
22177 (or (org-inlinetask-goto-beginning) t))))
22178 (beginning-of-line 0))
22179 (cond
22180 ;; There was a list item above.
22181 ((ignore-errors (goto-char (org-in-item-p)))
22182 (goto-char (org-list-get-top-point (org-list-struct)))
22183 (setq column (org-get-indentation)))
22184 ;; There was an heading above.
22185 ((looking-at "\\*+[ \t]+")
22186 (if (not org-adapt-indentation)
22187 (setq column 0)
22188 (goto-char (match-end 0))
22189 (setq column (current-column))))
22190 ;; A drawer had started and is unfinished
22191 ((looking-at org-drawer-regexp)
22192 (goto-char (1- (match-beginning 1)))
22193 (setq column (current-column)))
22194 ;; Else, nothing noticeable found: get indentation and go on.
22195 (t (setq column (org-get-indentation))))))
22196 ;; Now apply indentation and move cursor accordingly
22197 (goto-char pos)
22198 (if (<= (current-column) (current-indentation))
22199 (org-indent-line-to column)
22200 (save-excursion (org-indent-line-to column)))
22201 ;; Special polishing for properties, see `org-property-format'
22202 (setq column (current-column))
22203 (beginning-of-line 1)
22204 (if (looking-at org-property-re)
22205 (replace-match (concat (match-string 4)
22206 (format org-property-format
22207 (match-string 1) (match-string 3)))
22208 t t))
22209 (org-move-to-column column))))
22210
22211 (defun org-indent-drawer ()
22212 "Indent the drawer at point."
22213 (interactive)
22214 (let ((p (point))
22215 (e (and (save-excursion (re-search-forward ":END:" nil t))
22216 (match-end 0)))
22217 (folded
22218 (save-excursion
22219 (end-of-line)
22220 (when (overlays-at (point))
22221 (member 'invisible (overlay-properties
22222 (car (overlays-at (point)))))))))
22223 (when folded (org-cycle))
22224 (indent-for-tab-command)
22225 (while (and (move-beginning-of-line 2) (< (point) e))
22226 (indent-for-tab-command))
22227 (goto-char p)
22228 (when folded (org-cycle)))
22229 (message "Drawer at point indented"))
22230
22231 (defun org-indent-block ()
22232 "Indent the block at point."
22233 (interactive)
22234 (let ((p (point))
22235 (case-fold-search t)
22236 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22237 (match-end 0)))
22238 (folded
22239 (save-excursion
22240 (end-of-line)
22241 (when (overlays-at (point))
22242 (member 'invisible (overlay-properties
22243 (car (overlays-at (point)))))))))
22244 (when folded (org-cycle))
22245 (indent-for-tab-command)
22246 (while (and (move-beginning-of-line 2) (< (point) e))
22247 (indent-for-tab-command))
22248 (goto-char p)
22249 (when folded (org-cycle)))
22250 (message "Block at point indented"))
22251
22252 (defun org-indent-region (start end)
22253 "Indent region."
22254 (interactive "r")
22255 (save-excursion
22256 (let ((line-end (org-current-line end)))
22257 (goto-char start)
22258 (while (< (org-current-line) line-end)
22259 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22260 (t (call-interactively 'org-indent-line)))
22261 (move-beginning-of-line 2)))))
22262
22263
22264 ;;; Filling
22265
22266 ;; We use our own fill-paragraph and auto-fill functions.
22267
22268 ;; `org-fill-paragraph' relies on adaptive filling and context
22269 ;; checking. Appropriate `fill-prefix' is computed with
22270 ;; `org-adaptive-fill-function'.
22271
22272 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22273 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22274 ;; `org-adaptive-fill-function' value. Internally,
22275 ;; `org-comment-line-break-function' breaks the line.
22276
22277 ;; `org-setup-filling' installs filling and auto-filling related
22278 ;; variables during `org-mode' initialization.
22279
22280 (defvar org-element-paragraph-separate) ; org-element.el
22281 (defun org-setup-filling ()
22282 (require 'org-element)
22283 ;; Prevent auto-fill from inserting unwanted new items.
22284 (when (boundp 'fill-nobreak-predicate)
22285 (org-set-local
22286 'fill-nobreak-predicate
22287 (org-uniquify
22288 (append fill-nobreak-predicate
22289 '(org-fill-line-break-nobreak-p
22290 org-fill-paragraph-with-timestamp-nobreak-p)))))
22291 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22292 (org-set-local 'paragraph-start paragraph-ending)
22293 (org-set-local 'paragraph-separate paragraph-ending))
22294 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22295 (org-set-local 'auto-fill-inhibit-regexp nil)
22296 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22297 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22298 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22299
22300 (defun org-fill-line-break-nobreak-p ()
22301 "Non-nil when a new line at point would create an Org line break."
22302 (save-excursion
22303 (skip-chars-backward "[ \t]")
22304 (skip-chars-backward "\\\\")
22305 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22306
22307 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22308 "Non-nil when a new line at point would split a timestamp."
22309 (and (org-at-timestamp-p t)
22310 (not (looking-at org-ts-regexp-both))))
22311
22312 (declare-function message-in-body-p "message" ())
22313 (defvar orgtbl-line-start-regexp) ; From org-table.el
22314 (defun org-adaptive-fill-function ()
22315 "Compute a fill prefix for the current line.
22316 Return fill prefix, as a string, or nil if current line isn't
22317 meant to be filled. For convenience, if `adaptive-fill-regexp'
22318 matches in paragraphs or comments, use it."
22319 (catch 'exit
22320 (when (derived-mode-p 'message-mode)
22321 (save-excursion
22322 (beginning-of-line)
22323 (cond ((or (not (message-in-body-p))
22324 (looking-at orgtbl-line-start-regexp))
22325 (throw 'exit nil))
22326 ((looking-at message-cite-prefix-regexp)
22327 (throw 'exit (match-string-no-properties 0)))
22328 ((looking-at org-outline-regexp)
22329 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22330 (org-with-wide-buffer
22331 (let* ((p (line-beginning-position))
22332 (element (save-excursion
22333 (beginning-of-line)
22334 (or (ignore-errors (org-element-at-point))
22335 (user-error "An element cannot be parsed line %d"
22336 (line-number-at-pos (point))))))
22337 (type (org-element-type element))
22338 (post-affiliated (org-element-property :post-affiliated element)))
22339 (unless (and post-affiliated (< p post-affiliated))
22340 (case type
22341 (comment
22342 (save-excursion
22343 (beginning-of-line)
22344 (looking-at "[ \t]*")
22345 (concat (match-string 0) "# ")))
22346 (footnote-definition "")
22347 ((item plain-list)
22348 (make-string (org-list-item-body-column
22349 (or post-affiliated
22350 (org-element-property :begin element)))
22351 ? ))
22352 (paragraph
22353 ;; Fill prefix is usually the same as the current line,
22354 ;; unless the paragraph is at the beginning of an item.
22355 (let ((parent (org-element-property :parent element)))
22356 (save-excursion
22357 (beginning-of-line)
22358 (cond ((eq (org-element-type parent) 'item)
22359 (make-string (org-list-item-body-column
22360 (org-element-property :begin parent))
22361 ? ))
22362 ((and adaptive-fill-regexp
22363 ;; Locally disable
22364 ;; `adaptive-fill-function' to let
22365 ;; `fill-context-prefix' handle
22366 ;; `adaptive-fill-regexp' variable.
22367 (let (adaptive-fill-function)
22368 (fill-context-prefix
22369 post-affiliated
22370 (org-element-property :end element)))))
22371 ((looking-at "[ \t]+") (match-string 0))
22372 (t "")))))
22373 (comment-block
22374 ;; Only fill contents if P is within block boundaries.
22375 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22376 (forward-line)
22377 (point)))
22378 (cend (save-excursion
22379 (goto-char (org-element-property :end element))
22380 (skip-chars-backward " \r\t\n")
22381 (line-beginning-position))))
22382 (when (and (>= p cbeg) (< p cend))
22383 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22384 (match-string 0)
22385 ""))))))))))
22386
22387 (declare-function message-goto-body "message" ())
22388 (defvar message-cite-prefix-regexp) ; From message.el
22389 (defun org-fill-paragraph (&optional justify)
22390 "Fill element at point, when applicable.
22391
22392 This function only applies to comment blocks, comments, example
22393 blocks and paragraphs. Also, as a special case, re-align table
22394 when point is at one.
22395
22396 If JUSTIFY is non-nil (interactively, with prefix argument),
22397 justify as well. If `sentence-end-double-space' is non-nil, then
22398 period followed by one space does not end a sentence, so don't
22399 break a line there. The variable `fill-column' controls the
22400 width for filling.
22401
22402 For convenience, when point is at a plain list, an item or
22403 a footnote definition, try to fill the first paragraph within."
22404 (interactive)
22405 (if (and (derived-mode-p 'message-mode)
22406 (or (not (message-in-body-p))
22407 (save-excursion (move-beginning-of-line 1)
22408 (looking-at message-cite-prefix-regexp))))
22409 ;; First ensure filling is correct in message-mode.
22410 (let ((fill-paragraph-function
22411 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22412 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22413 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22414 (paragraph-separate
22415 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22416 (fill-paragraph nil))
22417 (with-syntax-table org-mode-transpose-word-syntax-table
22418 ;; Move to end of line in order to get the first paragraph
22419 ;; within a plain list or a footnote definition.
22420 (let ((element (save-excursion
22421 (end-of-line)
22422 (or (ignore-errors (org-element-at-point))
22423 (user-error "An element cannot be parsed line %d"
22424 (line-number-at-pos (point)))))))
22425 ;; First check if point is in a blank line at the beginning of
22426 ;; the buffer. In that case, ignore filling.
22427 (case (org-element-type element)
22428 ;; Use major mode filling function is src blocks.
22429 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22430 ;; Align Org tables, leave table.el tables as-is.
22431 (table-row (org-table-align) t)
22432 (table
22433 (when (eq (org-element-property :type element) 'org)
22434 (save-excursion
22435 (goto-char (org-element-property :post-affiliated element))
22436 (org-table-align)))
22437 t)
22438 (paragraph
22439 ;; Paragraphs may contain `line-break' type objects.
22440 (let ((beg (max (point-min)
22441 (org-element-property :contents-begin element)))
22442 (end (min (point-max)
22443 (org-element-property :contents-end element))))
22444 ;; Do nothing if point is at an affiliated keyword.
22445 (if (< (line-end-position) beg) t
22446 (when (derived-mode-p 'message-mode)
22447 ;; In `message-mode', do not fill following citation
22448 ;; in current paragraph nor text before message body.
22449 (let ((body-start (save-excursion (message-goto-body))))
22450 (when body-start (setq beg (max body-start beg))))
22451 (when (save-excursion
22452 (re-search-forward
22453 (concat "^" message-cite-prefix-regexp) end t))
22454 (setq end (match-beginning 0))))
22455 ;; Fill paragraph, taking line breaks into account.
22456 ;; For that, slice the paragraph using line breaks as
22457 ;; separators, and fill the parts in reverse order to
22458 ;; avoid messing with markers.
22459 (save-excursion
22460 (goto-char end)
22461 (mapc
22462 (lambda (pos)
22463 (fill-region-as-paragraph pos (point) justify)
22464 (goto-char pos))
22465 ;; Find the list of ending positions for line breaks
22466 ;; in the current paragraph. Add paragraph
22467 ;; beginning to include first slice.
22468 (nreverse
22469 (cons beg
22470 (org-element-map
22471 (org-element--parse-objects
22472 beg end nil (org-element-restriction 'paragraph))
22473 'line-break
22474 (lambda (lb) (org-element-property :end lb)))))))
22475 t)))
22476 ;; Contents of `comment-block' type elements should be
22477 ;; filled as plain text, but only if point is within block
22478 ;; markers.
22479 (comment-block
22480 (let* ((case-fold-search t)
22481 (beg (save-excursion
22482 (goto-char (org-element-property :begin element))
22483 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22484 (forward-line)
22485 (point)))
22486 (end (save-excursion
22487 (goto-char (org-element-property :end element))
22488 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22489 (line-beginning-position))))
22490 (if (or (< (point) beg) (> (point) end)) t
22491 (fill-region-as-paragraph
22492 (save-excursion (end-of-line)
22493 (re-search-backward "^[ \t]*$" beg 'move)
22494 (line-beginning-position))
22495 (save-excursion (beginning-of-line)
22496 (re-search-forward "^[ \t]*$" end 'move)
22497 (line-beginning-position))
22498 justify))))
22499 ;; Fill comments.
22500 (comment
22501 (let ((begin (org-element-property :post-affiliated element))
22502 (end (org-element-property :end element)))
22503 (when (and (>= (point) begin) (<= (point) end))
22504 (let ((begin (save-excursion
22505 (end-of-line)
22506 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22507 (progn (forward-line) (point))
22508 begin)))
22509 (end (save-excursion
22510 (end-of-line)
22511 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22512 (1- (line-beginning-position))
22513 (skip-chars-backward " \r\t\n")
22514 (line-end-position)))))
22515 ;; Do not fill comments when at a blank line.
22516 (when (> end begin)
22517 (let ((fill-prefix
22518 (save-excursion
22519 (beginning-of-line)
22520 (looking-at "[ \t]*#")
22521 (let ((comment-prefix (match-string 0)))
22522 (goto-char (match-end 0))
22523 (if (looking-at adaptive-fill-regexp)
22524 (concat comment-prefix (match-string 0))
22525 (concat comment-prefix " "))))))
22526 (save-excursion
22527 (fill-region-as-paragraph begin end justify))))))
22528 t))
22529 ;; Ignore every other element.
22530 (otherwise t))))))
22531
22532 (defun org-auto-fill-function ()
22533 "Auto-fill function."
22534 ;; Check if auto-filling is meaningful.
22535 (let ((fc (current-fill-column)))
22536 (when (and fc (> (current-column) fc))
22537 (let* ((fill-prefix (org-adaptive-fill-function))
22538 ;; Enforce empty fill prefix, if required. Otherwise, it
22539 ;; will be computed again.
22540 (adaptive-fill-mode (not (equal fill-prefix ""))))
22541 (when fill-prefix (do-auto-fill))))))
22542
22543 (defun org-comment-line-break-function (&optional soft)
22544 "Break line at point and indent, continuing comment if within one.
22545 The inserted newline is marked hard if variable
22546 `use-hard-newlines' is true, unless optional argument SOFT is
22547 non-nil."
22548 (if soft (insert-and-inherit ?\n) (newline 1))
22549 (save-excursion (forward-char -1) (delete-horizontal-space))
22550 (delete-horizontal-space)
22551 (indent-to-left-margin)
22552 (insert-before-markers-and-inherit fill-prefix))
22553
22554
22555 ;;; Comments
22556
22557 ;; Org comments syntax is quite complex. It requires the entire line
22558 ;; to be just a comment. Also, even with the right syntax at the
22559 ;; beginning of line, some some elements (i.e. verse-block or
22560 ;; example-block) don't accept comments. Usual Emacs comment commands
22561 ;; cannot cope with those requirements. Therefore, Org replaces them.
22562
22563 ;; Org still relies on `comment-dwim', but cannot trust
22564 ;; `comment-only-p'. So, `comment-region-function' and
22565 ;; `uncomment-region-function' both point
22566 ;; to`org-comment-or-uncomment-region'. Eventually,
22567 ;; `org-insert-comment' takes care of insertion of comments at the
22568 ;; beginning of line.
22569
22570 ;; `org-setup-comments-handling' install comments related variables
22571 ;; during `org-mode' initialization.
22572
22573 (defun org-setup-comments-handling ()
22574 (interactive)
22575 (org-set-local 'comment-use-syntax nil)
22576 (org-set-local 'comment-start "# ")
22577 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22578 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22579 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22580 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22581
22582 (defun org-insert-comment ()
22583 "Insert an empty comment above current line.
22584 If the line is empty, insert comment at its beginning."
22585 (beginning-of-line)
22586 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22587 (org-indent-line)
22588 (insert "# "))
22589
22590 (defvar comment-empty-lines) ; From newcomment.el.
22591 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22592 "Comment or uncomment each non-blank line in the region.
22593 Uncomment each non-blank line between BEG and END if it only
22594 contains commented lines. Otherwise, comment them."
22595 (save-restriction
22596 ;; Restrict region
22597 (narrow-to-region (save-excursion (goto-char beg)
22598 (skip-chars-forward " \r\t\n" end)
22599 (line-beginning-position))
22600 (save-excursion (goto-char end)
22601 (skip-chars-backward " \r\t\n" beg)
22602 (line-end-position)))
22603 (let ((uncommentp
22604 ;; UNCOMMENTP is non-nil when every non blank line between
22605 ;; BEG and END is a comment.
22606 (save-excursion
22607 (goto-char (point-min))
22608 (while (and (not (eobp))
22609 (let ((element (org-element-at-point)))
22610 (and (eq (org-element-type element) 'comment)
22611 (goto-char (min (point-max)
22612 (org-element-property
22613 :end element)))))))
22614 (eobp))))
22615 (if uncommentp
22616 ;; Only blank lines and comments in region: uncomment it.
22617 (save-excursion
22618 (goto-char (point-min))
22619 (while (not (eobp))
22620 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22621 (replace-match "" nil nil nil 1))
22622 (forward-line)))
22623 ;; Comment each line in region.
22624 (let ((min-indent (point-max)))
22625 ;; First find the minimum indentation across all lines.
22626 (save-excursion
22627 (goto-char (point-min))
22628 (while (and (not (eobp)) (not (zerop min-indent)))
22629 (unless (looking-at "[ \t]*$")
22630 (setq min-indent (min min-indent (current-indentation))))
22631 (forward-line)))
22632 ;; Then loop over all lines.
22633 (save-excursion
22634 (goto-char (point-min))
22635 (while (not (eobp))
22636 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22637 ;; Don't get fooled by invisible text (e.g. link path)
22638 ;; when moving to column MIN-INDENT.
22639 (let ((buffer-invisibility-spec nil))
22640 (org-move-to-column min-indent t))
22641 (insert comment-start))
22642 (forward-line))))))))
22643
22644
22645 ;;; Planning
22646
22647 ;; This section contains tools to operate on timestamp objects, as
22648 ;; returned by, e.g. `org-element-context'.
22649
22650 (defun org-timestamp-has-time-p (timestamp)
22651 "Non-nil when TIMESTAMP has a time specified."
22652 (org-element-property :hour-start timestamp))
22653
22654 (defun org-timestamp-format (timestamp format &optional end utc)
22655 "Format a TIMESTAMP element into a string.
22656
22657 FORMAT is a format specifier to be passed to
22658 `format-time-string'.
22659
22660 When optional argument END is non-nil, use end of date-range or
22661 time-range, if possible.
22662
22663 When optional argument UTC is non-nil, time will be expressed as
22664 Universal Time."
22665 (format-time-string
22666 format
22667 (apply 'encode-time
22668 (cons 0
22669 (mapcar
22670 (lambda (prop) (or (org-element-property prop timestamp) 0))
22671 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22672 '(:minute-start :hour-start :day-start :month-start
22673 :year-start)))))
22674 utc))
22675
22676 (defun org-timestamp-split-range (timestamp &optional end)
22677 "Extract a timestamp object from a date or time range.
22678
22679 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22680 the end of the range. Otherwise, extract its start.
22681
22682 Return a new timestamp object sharing the same parent as
22683 TIMESTAMP."
22684 (let ((type (org-element-property :type timestamp)))
22685 (if (memq type '(active inactive diary)) timestamp
22686 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22687 ;; Set new type.
22688 (org-element-put-property
22689 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22690 ;; Copy start properties over end properties if END is
22691 ;; non-nil. Otherwise, copy end properties over `start' ones.
22692 (let ((p-alist '((:minute-start . :minute-end)
22693 (:hour-start . :hour-end)
22694 (:day-start . :day-end)
22695 (:month-start . :month-end)
22696 (:year-start . :year-end))))
22697 (dolist (p-cell p-alist)
22698 (org-element-put-property
22699 split-ts
22700 (funcall (if end 'car 'cdr) p-cell)
22701 (org-element-property
22702 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22703 ;; Eventually refresh `:raw-value'.
22704 (org-element-put-property split-ts :raw-value nil)
22705 (org-element-put-property
22706 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22707
22708 (defun org-timestamp-translate (timestamp &optional boundary)
22709 "Apply `org-translate-time' on a TIMESTAMP object.
22710 When optional argument BOUNDARY is non-nil, it is either the
22711 symbol `start' or `end'. In this case, only translate the
22712 starting or ending part of TIMESTAMP if it is a date or time
22713 range. Otherwise, translate both parts."
22714 (if (and (not boundary)
22715 (memq (org-element-property :type timestamp)
22716 '(active-range inactive-range)))
22717 (concat
22718 (org-translate-time
22719 (org-element-property :raw-value
22720 (org-timestamp-split-range timestamp)))
22721 "--"
22722 (org-translate-time
22723 (org-element-property :raw-value
22724 (org-timestamp-split-range timestamp t))))
22725 (org-translate-time
22726 (org-element-property
22727 :raw-value
22728 (if (not boundary) timestamp
22729 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22730
22731
22732
22733 ;;; Other stuff.
22734
22735 (defun org-toggle-fixed-width-section (arg)
22736 "Toggle the fixed-width export.
22737 If there is no active region, the QUOTE keyword at the current headline is
22738 inserted or removed. When present, it causes the text between this headline
22739 and the next to be exported as fixed-width text, and unmodified.
22740 If there is an active region, this command adds or removes a colon as the
22741 first character of this line. If the first character of a line is a colon,
22742 this line is also exported in fixed-width font."
22743 (interactive "P")
22744 (let* ((cc 0)
22745 (regionp (org-region-active-p))
22746 (beg (if regionp (region-beginning) (point)))
22747 (end (if regionp (region-end)))
22748 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22749 (case-fold-search nil)
22750 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22751 off)
22752 (if regionp
22753 (save-excursion
22754 (goto-char beg)
22755 (setq cc (current-column))
22756 (beginning-of-line 1)
22757 (setq off (looking-at re))
22758 (while (> nlines 0)
22759 (setq nlines (1- nlines))
22760 (beginning-of-line 1)
22761 (cond
22762 (arg
22763 (org-move-to-column cc t)
22764 (insert ": \n")
22765 (forward-line -1))
22766 ((and off (looking-at re))
22767 (replace-match "" t t nil 1))
22768 ((not off) (org-move-to-column cc t) (insert ": ")))
22769 (forward-line 1)))
22770 (save-excursion
22771 (org-back-to-heading)
22772 (cond
22773 ((looking-at (format org-heading-keyword-regexp-format
22774 org-quote-string))
22775 (goto-char (match-end 1))
22776 (looking-at (concat " +" org-quote-string))
22777 (replace-match "" t t)
22778 (when (eolp) (insert " ")))
22779 ((looking-at org-outline-regexp)
22780 (goto-char (match-end 0))
22781 (insert org-quote-string " ")))))))
22782
22783 (defun org-reftex-citation ()
22784 "Use reftex-citation to insert a citation into the buffer.
22785 This looks for a line like
22786
22787 #+BIBLIOGRAPHY: foo plain option:-d
22788
22789 and derives from it that foo.bib is the bibliography file relevant
22790 for this document. It then installs the necessary environment for RefTeX
22791 to work in this buffer and calls `reftex-citation' to insert a citation
22792 into the buffer.
22793
22794 Export of such citations to both LaTeX and HTML is handled by the contributed
22795 package ox-bibtex by Taru Karttunen."
22796 (interactive)
22797 (let ((reftex-docstruct-symbol 'rds)
22798 (reftex-cite-format "\\cite{%l}")
22799 rds bib)
22800 (save-excursion
22801 (save-restriction
22802 (widen)
22803 (let ((case-fold-search t)
22804 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22805 (if (not (save-excursion
22806 (or (re-search-forward re nil t)
22807 (re-search-backward re nil t))))
22808 (error "No bibliography defined in file")
22809 (setq bib (concat (match-string 1) ".bib")
22810 rds (list (list 'bib bib)))))))
22811 (call-interactively 'reftex-citation)))
22812
22813 ;;;; Functions extending outline functionality
22814
22815 (defun org-beginning-of-line (&optional arg)
22816 "Go to the beginning of the current line. If that is invisible, continue
22817 to a visible line beginning. This makes the function of C-a more intuitive.
22818 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22819 first attempt, and only move to after the tags when the cursor is already
22820 beyond the end of the headline."
22821 (interactive "P")
22822 (let ((pos (point))
22823 (special (if (consp org-special-ctrl-a/e)
22824 (car org-special-ctrl-a/e)
22825 org-special-ctrl-a/e))
22826 deactivate-mark refpos)
22827 (if (org-bound-and-true-p visual-line-mode)
22828 (beginning-of-visual-line 1)
22829 (beginning-of-line 1))
22830 (if (and arg (fboundp 'move-beginning-of-line))
22831 (call-interactively 'move-beginning-of-line)
22832 (if (bobp)
22833 nil
22834 (backward-char 1)
22835 (if (org-truely-invisible-p)
22836 (while (and (not (bobp)) (org-truely-invisible-p))
22837 (backward-char 1)
22838 (beginning-of-line 1))
22839 (forward-char 1))))
22840 (when special
22841 (cond
22842 ((and (looking-at org-complex-heading-regexp)
22843 (= (char-after (match-end 1)) ?\ ))
22844 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22845 (point-at-eol)))
22846 (goto-char
22847 (if (eq special t)
22848 (cond ((> pos refpos) refpos)
22849 ((= pos (point)) refpos)
22850 (t (point)))
22851 (cond ((> pos (point)) (point))
22852 ((not (eq last-command this-command)) (point))
22853 (t refpos)))))
22854 ((org-at-item-p)
22855 ;; Being at an item and not looking at an the item means point
22856 ;; was previously moved to beginning of a visual line, which
22857 ;; doesn't contain the item. Therefore, do nothing special,
22858 ;; just stay here.
22859 (when (looking-at org-list-full-item-re)
22860 ;; Set special position at first white space character after
22861 ;; bullet, and check-box, if any.
22862 (let ((after-bullet
22863 (let ((box (match-end 3)))
22864 (if (not box) (match-end 1)
22865 (let ((after (char-after box)))
22866 (if (and after (= after ? )) (1+ box) box))))))
22867 ;; Special case: Move point to special position when
22868 ;; currently after it or at beginning of line.
22869 (if (eq special t)
22870 (when (or (> pos after-bullet) (= (point) pos))
22871 (goto-char after-bullet))
22872 ;; Reversed case: Move point to special position when
22873 ;; point was already at beginning of line and command is
22874 ;; repeated.
22875 (when (and (= (point) pos) (eq last-command this-command))
22876 (goto-char after-bullet))))))))
22877 (org-no-warnings
22878 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22879 (setq disable-point-adjustment
22880 (or (not (invisible-p (point)))
22881 (not (invisible-p (max (point-min) (1- (point))))))))
22882
22883 (defun org-end-of-line (&optional arg)
22884 "Go to the end of the line.
22885 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22886 tags on the first attempt, and only move to after the tags when
22887 the cursor is already beyond the end of the headline."
22888 (interactive "P")
22889 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22890 org-special-ctrl-a/e))
22891 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22892 'end-of-visual-line)
22893 ((fboundp 'move-end-of-line) 'move-end-of-line)
22894 (t 'end-of-line)))
22895 deactivate-mark)
22896 (if (or (not special) arg) (call-interactively move-fun)
22897 (let* ((element (save-excursion (beginning-of-line)
22898 (org-element-at-point)))
22899 (type (org-element-type element)))
22900 (cond
22901 ((memq type '(headline inlinetask))
22902 (let ((pos (point)))
22903 (beginning-of-line 1)
22904 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22905 (if (eq special t)
22906 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22907 (goto-char (match-beginning 1))
22908 (goto-char (match-end 0)))
22909 (if (or (< pos (match-end 0))
22910 (not (eq this-command last-command)))
22911 (goto-char (match-end 0))
22912 (goto-char (match-beginning 1))))
22913 (call-interactively move-fun))))
22914 ((org-element-property :hiddenp element)
22915 ;; If element is hidden, `move-end-of-line' would put point
22916 ;; after it. Use `end-of-line' to stay on current line.
22917 (call-interactively 'end-of-line))
22918 (t (call-interactively move-fun)))))
22919 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22920 (setq disable-point-adjustment
22921 (or (not (invisible-p (point)))
22922 (not (invisible-p (max (point-min) (1- (point))))))))
22923
22924 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22925 (define-key org-mode-map "\C-e" 'org-end-of-line)
22926
22927 (defun org-backward-sentence (&optional arg)
22928 "Go to beginning of sentence, or beginning of table field.
22929 This will call `backward-sentence' or `org-table-beginning-of-field',
22930 depending on context."
22931 (interactive "P")
22932 (cond
22933 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22934 (t (call-interactively 'backward-sentence))))
22935
22936 (defun org-forward-sentence (&optional arg)
22937 "Go to end of sentence, or end of table field.
22938 This will call `forward-sentence' or `org-table-end-of-field',
22939 depending on context."
22940 (interactive "P")
22941 (cond
22942 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22943 (t (call-interactively 'forward-sentence))))
22944
22945 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22946 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22947
22948 (defun org-kill-line (&optional arg)
22949 "Kill line, to tags or end of line."
22950 (interactive "P")
22951 (cond
22952 ((or (not org-special-ctrl-k)
22953 (bolp)
22954 (not (org-at-heading-p)))
22955 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22956 org-ctrl-k-protect-subtree)
22957 (if (or (eq org-ctrl-k-protect-subtree 'error)
22958 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22959 (user-error "C-k aborted as it would kill a hidden subtree")))
22960 (call-interactively
22961 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22962 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22963 (kill-region (point) (match-beginning 1))
22964 (org-set-tags nil t))
22965 (t (kill-region (point) (point-at-eol)))))
22966
22967 (define-key org-mode-map "\C-k" 'org-kill-line)
22968
22969 (defun org-yank (&optional arg)
22970 "Yank. If the kill is a subtree, treat it specially.
22971 This command will look at the current kill and check if is a single
22972 subtree, or a series of subtrees[1]. If it passes the test, and if the
22973 cursor is at the beginning of a line or after the stars of a currently
22974 empty headline, then the yank is handled specially. How exactly depends
22975 on the value of the following variables, both set by default.
22976
22977 org-yank-folded-subtrees
22978 When set, the subtree(s) will be folded after insertion, but only
22979 if doing so would now swallow text after the yanked text.
22980
22981 org-yank-adjusted-subtrees
22982 When set, the subtree will be promoted or demoted in order to
22983 fit into the local outline tree structure, which means that the level
22984 will be adjusted so that it becomes the smaller one of the two
22985 *visible* surrounding headings.
22986
22987 Any prefix to this command will cause `yank' to be called directly with
22988 no special treatment. In particular, a simple \\[universal-argument] prefix \
22989 will just
22990 plainly yank the text as it is.
22991
22992 \[1] The test checks if the first non-white line is a heading
22993 and if there are no other headings with fewer stars."
22994 (interactive "P")
22995 (org-yank-generic 'yank arg))
22996
22997 (defun org-yank-generic (command arg)
22998 "Perform some yank-like command.
22999
23000 This function implements the behavior described in the `org-yank'
23001 documentation. However, it has been generalized to work for any
23002 interactive command with similar behavior."
23003
23004 ;; pretend to be command COMMAND
23005 (setq this-command command)
23006
23007 (if arg
23008 (call-interactively command)
23009
23010 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23011 (and (org-kill-is-subtree-p)
23012 (or (bolp)
23013 (and (looking-at "[ \t]*$")
23014 (string-match
23015 "\\`\\*+\\'"
23016 (buffer-substring (point-at-bol) (point)))))))
23017 swallowp)
23018 (cond
23019 ((and subtreep org-yank-folded-subtrees)
23020 (let ((beg (point))
23021 end)
23022 (if (and subtreep org-yank-adjusted-subtrees)
23023 (org-paste-subtree nil nil 'for-yank)
23024 (call-interactively command))
23025
23026 (setq end (point))
23027 (goto-char beg)
23028 (when (and (bolp) subtreep
23029 (not (setq swallowp
23030 (org-yank-folding-would-swallow-text beg end))))
23031 (org-with-limited-levels
23032 (or (looking-at org-outline-regexp)
23033 (re-search-forward org-outline-regexp-bol end t))
23034 (while (and (< (point) end) (looking-at org-outline-regexp))
23035 (hide-subtree)
23036 (org-cycle-show-empty-lines 'folded)
23037 (condition-case nil
23038 (outline-forward-same-level 1)
23039 (error (goto-char end))))))
23040 (when swallowp
23041 (message
23042 "Inserted text not folded because that would swallow text"))
23043
23044 (goto-char end)
23045 (skip-chars-forward " \t\n\r")
23046 (beginning-of-line 1)
23047 (push-mark beg 'nomsg)))
23048 ((and subtreep org-yank-adjusted-subtrees)
23049 (let ((beg (point-at-bol)))
23050 (org-paste-subtree nil nil 'for-yank)
23051 (push-mark beg 'nomsg)))
23052 (t
23053 (call-interactively command))))))
23054
23055 (defun org-yank-folding-would-swallow-text (beg end)
23056 "Would hide-subtree at BEG swallow any text after END?"
23057 (let (level)
23058 (org-with-limited-levels
23059 (save-excursion
23060 (goto-char beg)
23061 (when (or (looking-at org-outline-regexp)
23062 (re-search-forward org-outline-regexp-bol end t))
23063 (setq level (org-outline-level)))
23064 (goto-char end)
23065 (skip-chars-forward " \t\r\n\v\f")
23066 (if (or (eobp)
23067 (and (bolp) (looking-at org-outline-regexp)
23068 (<= (org-outline-level) level)))
23069 nil ; Nothing would be swallowed
23070 t))))) ; something would swallow
23071
23072 (define-key org-mode-map "\C-y" 'org-yank)
23073
23074 (defun org-truely-invisible-p ()
23075 "Check if point is at a character currently not visible.
23076 This version does not only check the character property, but also
23077 `visible-mode'."
23078 ;; Early versions of noutline don't have `outline-invisible-p'.
23079 (if (org-bound-and-true-p visible-mode)
23080 nil
23081 (outline-invisible-p)))
23082
23083 (defun org-invisible-p2 ()
23084 "Check if point is at a character currently not visible."
23085 (save-excursion
23086 (if (and (eolp) (not (bobp))) (backward-char 1))
23087 ;; Early versions of noutline don't have `outline-invisible-p'.
23088 (outline-invisible-p)))
23089
23090 (defun org-back-to-heading (&optional invisible-ok)
23091 "Call `outline-back-to-heading', but provide a better error message."
23092 (condition-case nil
23093 (outline-back-to-heading invisible-ok)
23094 (error (error "Before first headline at position %d in buffer %s"
23095 (point) (current-buffer)))))
23096
23097 (defun org-before-first-heading-p ()
23098 "Before first heading?"
23099 (save-excursion
23100 (end-of-line)
23101 (null (re-search-backward org-outline-regexp-bol nil t))))
23102
23103 (defun org-at-heading-p (&optional ignored)
23104 (outline-on-heading-p t))
23105 ;; Compatibility alias with Org versions < 7.8.03
23106 (defalias 'org-on-heading-p 'org-at-heading-p)
23107
23108 (defun org-at-comment-p nil
23109 "Is cursor in a line starting with a # character?"
23110 (save-excursion
23111 (beginning-of-line)
23112 (looking-at "^#")))
23113
23114 (defun org-at-drawer-p nil
23115 "Is cursor at a drawer keyword?"
23116 (save-excursion
23117 (move-beginning-of-line 1)
23118 (looking-at org-drawer-regexp)))
23119
23120 (defun org-at-block-p nil
23121 "Is cursor at a block keyword?"
23122 (save-excursion
23123 (move-beginning-of-line 1)
23124 (looking-at org-block-regexp)))
23125
23126 (defun org-point-at-end-of-empty-headline ()
23127 "If point is at the end of an empty headline, return t, else nil.
23128 If the heading only contains a TODO keyword, it is still still considered
23129 empty."
23130 (and (looking-at "[ \t]*$")
23131 (when org-todo-line-regexp
23132 (save-excursion
23133 (beginning-of-line 1)
23134 (let ((case-fold-search nil))
23135 (looking-at org-todo-line-regexp)
23136 (string= (match-string 3) ""))))))
23137
23138 (defun org-at-heading-or-item-p ()
23139 (or (org-at-heading-p) (org-at-item-p)))
23140
23141 (defun org-at-target-p ()
23142 (or (org-in-regexp org-radio-target-regexp)
23143 (org-in-regexp org-target-regexp)))
23144 ;; Compatibility alias with Org versions < 7.8.03
23145 (defalias 'org-on-target-p 'org-at-target-p)
23146
23147 (defun org-up-heading-all (arg)
23148 "Move to the heading line of which the present line is a subheading.
23149 This function considers both visible and invisible heading lines.
23150 With argument, move up ARG levels."
23151 (if (fboundp 'outline-up-heading-all)
23152 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23153 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23154
23155 (defun org-up-heading-safe ()
23156 "Move to the heading line of which the present line is a subheading.
23157 This version will not throw an error. It will return the level of the
23158 headline found, or nil if no higher level is found.
23159
23160 Also, this function will be a lot faster than `outline-up-heading',
23161 because it relies on stars being the outline starters. This can really
23162 make a significant difference in outlines with very many siblings."
23163 (let (start-level re)
23164 (org-back-to-heading t)
23165 (setq start-level (funcall outline-level))
23166 (if (equal start-level 1)
23167 nil
23168 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23169 (if (re-search-backward re nil t)
23170 (funcall outline-level)))))
23171
23172 (defun org-first-sibling-p ()
23173 "Is this heading the first child of its parents?"
23174 (interactive)
23175 (let ((re org-outline-regexp-bol)
23176 level l)
23177 (unless (org-at-heading-p t)
23178 (user-error "Not at a heading"))
23179 (setq level (funcall outline-level))
23180 (save-excursion
23181 (if (not (re-search-backward re nil t))
23182 t
23183 (setq l (funcall outline-level))
23184 (< l level)))))
23185
23186 (defun org-goto-sibling (&optional previous)
23187 "Goto the next sibling, even if it is invisible.
23188 When PREVIOUS is set, go to the previous sibling instead. Returns t
23189 when a sibling was found. When none is found, return nil and don't
23190 move point."
23191 (let ((fun (if previous 're-search-backward 're-search-forward))
23192 (pos (point))
23193 (re org-outline-regexp-bol)
23194 level l)
23195 (when (condition-case nil (org-back-to-heading t) (error nil))
23196 (setq level (funcall outline-level))
23197 (catch 'exit
23198 (or previous (forward-char 1))
23199 (while (funcall fun re nil t)
23200 (setq l (funcall outline-level))
23201 (when (< l level) (goto-char pos) (throw 'exit nil))
23202 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23203 (goto-char pos)
23204 nil))))
23205
23206 (defun org-show-siblings ()
23207 "Show all siblings of the current headline."
23208 (save-excursion
23209 (while (org-goto-sibling) (org-flag-heading nil)))
23210 (save-excursion
23211 (while (org-goto-sibling 'previous)
23212 (org-flag-heading nil))))
23213
23214 (defun org-goto-first-child ()
23215 "Goto the first child, even if it is invisible.
23216 Return t when a child was found. Otherwise don't move point and
23217 return nil."
23218 (let (level (pos (point)) (re org-outline-regexp-bol))
23219 (when (condition-case nil (org-back-to-heading t) (error nil))
23220 (setq level (outline-level))
23221 (forward-char 1)
23222 (if (and (re-search-forward re nil t) (> (outline-level) level))
23223 (progn (goto-char (match-beginning 0)) t)
23224 (goto-char pos) nil))))
23225
23226 (defun org-show-hidden-entry ()
23227 "Show an entry where even the heading is hidden."
23228 (save-excursion
23229 (org-show-entry)))
23230
23231 (defun org-flag-heading (flag &optional entry)
23232 "Flag the current heading. FLAG non-nil means make invisible.
23233 When ENTRY is non-nil, show the entire entry."
23234 (save-excursion
23235 (org-back-to-heading t)
23236 ;; Check if we should show the entire entry
23237 (if entry
23238 (progn
23239 (org-show-entry)
23240 (save-excursion
23241 (and (outline-next-heading)
23242 (org-flag-heading nil))))
23243 (outline-flag-region (max (point-min) (1- (point)))
23244 (save-excursion (outline-end-of-heading) (point))
23245 flag))))
23246
23247 (defun org-get-next-sibling ()
23248 "Move to next heading of the same level, and return point.
23249 If there is no such heading, return nil.
23250 This is like outline-next-sibling, but invisible headings are ok."
23251 (let ((level (funcall outline-level)))
23252 (outline-next-heading)
23253 (while (and (not (eobp)) (> (funcall outline-level) level))
23254 (outline-next-heading))
23255 (if (or (eobp) (< (funcall outline-level) level))
23256 nil
23257 (point))))
23258
23259 (defun org-get-last-sibling ()
23260 "Move to previous heading of the same level, and return point.
23261 If there is no such heading, return nil."
23262 (let ((opoint (point))
23263 (level (funcall outline-level)))
23264 (outline-previous-heading)
23265 (when (and (/= (point) opoint) (outline-on-heading-p t))
23266 (while (and (> (funcall outline-level) level)
23267 (not (bobp)))
23268 (outline-previous-heading))
23269 (if (< (funcall outline-level) level)
23270 nil
23271 (point)))))
23272
23273 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23274 "Goto to the end of a subtree."
23275 ;; This contains an exact copy of the original function, but it uses
23276 ;; `org-back-to-heading', to make it work also in invisible
23277 ;; trees. And is uses an invisible-ok argument.
23278 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23279 ;; Furthermore, when used inside Org, finding the end of a large subtree
23280 ;; with many children and grandchildren etc, this can be much faster
23281 ;; than the outline version.
23282 (org-back-to-heading invisible-ok)
23283 (let ((first t)
23284 (level (funcall outline-level)))
23285 (if (and (derived-mode-p 'org-mode) (< level 1000))
23286 ;; A true heading (not a plain list item), in Org-mode
23287 ;; This means we can easily find the end by looking
23288 ;; only for the right number of stars. Using a regexp to do
23289 ;; this is so much faster than using a Lisp loop.
23290 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23291 (forward-char 1)
23292 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23293 ;; something else, do it the slow way
23294 (while (and (not (eobp))
23295 (or first (> (funcall outline-level) level)))
23296 (setq first nil)
23297 (outline-next-heading)))
23298 (unless to-heading
23299 (if (memq (preceding-char) '(?\n ?\^M))
23300 (progn
23301 ;; Go to end of line before heading
23302 (forward-char -1)
23303 (if (memq (preceding-char) '(?\n ?\^M))
23304 ;; leave blank line before heading
23305 (forward-char -1))))))
23306 (point))
23307
23308 (defun org-end-of-meta-data-and-drawers ()
23309 "Jump to the first text after meta data and drawers in the current entry.
23310 This will move over empty lines, lines with planning time stamps,
23311 clocking lines, and drawers."
23312 (org-back-to-heading t)
23313 (let ((end (save-excursion (outline-next-heading) (point)))
23314 (re (concat "\\(" org-drawer-regexp "\\)"
23315 "\\|" "[ \t]*" org-keyword-time-regexp)))
23316 (forward-line 1)
23317 (while (re-search-forward re end t)
23318 (if (not (match-end 1))
23319 ;; empty or planning line
23320 (forward-line 1)
23321 ;; a drawer, find the end
23322 (re-search-forward "^[ \t]*:END:" end 'move)
23323 (forward-line 1)))
23324 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23325 (point)))
23326
23327 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23328 "Move forward to the ARG'th subheading at same level as this one.
23329 Stop at the first and last subheadings of a superior heading.
23330 Normally this only looks at visible headings, but when INVISIBLE-OK is
23331 non-nil it will also look at invisible ones."
23332 (interactive "p")
23333 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23334 (if (and arg (< arg 0))
23335 (goto-char (point-min))
23336 (outline-next-heading))
23337 (org-at-heading-p)
23338 (let ((level (- (match-end 0) (match-beginning 0) 1))
23339 (f (if (and arg (< arg 0))
23340 're-search-backward
23341 're-search-forward))
23342 (count (if arg (abs arg) 1))
23343 (result (point)))
23344 (while (and (prog1 (> count 0)
23345 (forward-char (if (and arg (< arg 0)) -1 1)))
23346 (funcall f org-outline-regexp-bol nil 'move))
23347 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23348 (cond ((< l level) (setq count 0))
23349 ((and (= l level)
23350 (or invisible-ok
23351 (progn
23352 (goto-char (line-beginning-position))
23353 (not (outline-invisible-p)))))
23354 (setq count (1- count))
23355 (when (eq l level)
23356 (setq result (point)))))))
23357 (goto-char result))
23358 (beginning-of-line 1)))
23359
23360 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23361 "Move backward to the ARG'th subheading at same level as this one.
23362 Stop at the first and last subheadings of a superior heading."
23363 (interactive "p")
23364 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23365
23366 (defun org-next-block (arg &optional backward block-regexp)
23367 "Jump to the next block.
23368 With a prefix argument ARG, jump forward ARG many source blocks.
23369 When BACKWARD is non-nil, jump to the previous block.
23370 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23371 (interactive "p")
23372 (let ((re (or block-regexp org-block-regexp))
23373 (re-search-fn (or (and backward 're-search-backward)
23374 're-search-forward)))
23375 (if (looking-at re) (forward-char 1))
23376 (condition-case nil
23377 (funcall re-search-fn re nil nil arg)
23378 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23379 (goto-char (match-beginning 0)) (org-show-context)))
23380
23381 (defun org-previous-block (arg &optional block-regexp)
23382 "Jump to the previous block.
23383 With a prefix argument ARG, jump backward ARG many source blocks.
23384 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23385 (interactive "p")
23386 (org-next-block arg t block-regexp))
23387
23388 (defun org-forward-paragraph ()
23389 "Move forward to beginning of next paragraph or equivalent.
23390
23391 The function moves point to the beginning of the next visible
23392 structural element, which can be a paragraph, a table, a list
23393 item, etc. It also provides some special moves for convenience:
23394
23395 - On an affiliated keyword, jump to the beginning of the
23396 relative element.
23397 - On an item or a footnote definition, move to the second
23398 element inside, if any.
23399 - On a table or a property drawer, jump after it.
23400 - On a verse or source block, stop after blank lines."
23401 (interactive)
23402 (when (eobp) (user-error "Cannot move further down"))
23403 (let* ((deactivate-mark nil)
23404 (element (org-element-at-point))
23405 (type (org-element-type element))
23406 (post-affiliated (org-element-property :post-affiliated element))
23407 (contents-begin (org-element-property :contents-begin element))
23408 (contents-end (org-element-property :contents-end element))
23409 (end (let ((end (org-element-property :end element)) (parent element))
23410 (while (and (setq parent (org-element-property :parent parent))
23411 (= (org-element-property :contents-end parent) end))
23412 (setq end (org-element-property :end parent)))
23413 end)))
23414 (cond ((not element)
23415 (skip-chars-forward " \r\t\n")
23416 (or (eobp) (beginning-of-line)))
23417 ;; On affiliated keywords, move to element's beginning.
23418 ((and post-affiliated (< (point) post-affiliated))
23419 (goto-char post-affiliated))
23420 ;; At a table row, move to the end of the table. Similarly,
23421 ;; at a node property, move to the end of the property
23422 ;; drawer.
23423 ((memq type '(node-property table-row))
23424 (goto-char (org-element-property
23425 :end (org-element-property :parent element))))
23426 ((memq type '(property-drawer table)) (goto-char end))
23427 ;; Consider blank lines as separators in verse and source
23428 ;; blocks to ease editing.
23429 ((memq type '(src-block verse-block))
23430 (when (eq type 'src-block)
23431 (setq contents-end
23432 (save-excursion (goto-char end)
23433 (skip-chars-backward " \r\t\n")
23434 (line-beginning-position))))
23435 (beginning-of-line)
23436 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23437 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23438 (goto-char end)
23439 (skip-chars-forward " \r\t\n")
23440 (if (= (point) contents-end) (goto-char end)
23441 (beginning-of-line))))
23442 ;; With no contents, just skip element.
23443 ((not contents-begin) (goto-char end))
23444 ;; If contents are invisible, skip the element altogether.
23445 ((outline-invisible-p (line-end-position))
23446 (case type
23447 (headline
23448 (org-with-limited-levels (outline-next-visible-heading 1)))
23449 ;; At a plain list, make sure we move to the next item
23450 ;; instead of skipping the whole list.
23451 (plain-list (forward-char)
23452 (org-forward-paragraph))
23453 (otherwise (goto-char end))))
23454 ((>= (point) contents-end) (goto-char end))
23455 ((>= (point) contents-begin)
23456 ;; This can only happen on paragraphs and plain lists.
23457 (case type
23458 (paragraph (goto-char end))
23459 ;; At a plain list, try to move to second element in
23460 ;; first item, if possible.
23461 (plain-list (end-of-line)
23462 (org-forward-paragraph))))
23463 ;; When contents start on the middle of a line (e.g. in
23464 ;; items and footnote definitions), try to reach first
23465 ;; element starting after current line.
23466 ((> (line-end-position) contents-begin)
23467 (end-of-line)
23468 (org-forward-paragraph))
23469 (t (goto-char contents-begin)))))
23470
23471 (defun org-backward-paragraph ()
23472 "Move backward to start of previous paragraph or equivalent.
23473
23474 The function moves point to the beginning of the current
23475 structural element, which can be a paragraph, a table, a list
23476 item, etc., or to the beginning of the previous visible one if
23477 point is already there. It also provides some special moves for
23478 convenience:
23479
23480 - On an affiliated keyword, jump to the first one.
23481 - On a table or a property drawer, move to its beginning.
23482 - On a verse or source block, stop before blank lines."
23483 (interactive)
23484 (when (bobp) (user-error "Cannot move further up"))
23485 (let* ((deactivate-mark nil)
23486 (element (org-element-at-point))
23487 (type (org-element-type element))
23488 (contents-begin (org-element-property :contents-begin element))
23489 (contents-end (org-element-property :contents-end element))
23490 (post-affiliated (org-element-property :post-affiliated element))
23491 (begin (org-element-property :begin element)))
23492 (cond
23493 ((not element) (goto-char (point-min)))
23494 ((= (point) begin)
23495 (backward-char)
23496 (org-backward-paragraph))
23497 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23498 ((memq type '(node-property table-row))
23499 (goto-char (org-element-property
23500 :post-affiliated (org-element-property :parent element))))
23501 ((memq type '(property-drawer table)) (goto-char begin))
23502 ((memq type '(src-block verse-block))
23503 (when (eq type 'src-block)
23504 (setq contents-begin
23505 (save-excursion (goto-char begin) (forward-line) (point))))
23506 (if (= (point) contents-begin) (goto-char post-affiliated)
23507 ;; Inside a verse block, see blank lines as paragraph
23508 ;; separators.
23509 (let ((origin (point)))
23510 (skip-chars-backward " \r\t\n" contents-begin)
23511 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23512 (skip-chars-forward " \r\t\n" origin)
23513 (if (= (point) origin) (goto-char contents-begin)
23514 (beginning-of-line))))))
23515 ((not contents-begin) (goto-char (or post-affiliated begin)))
23516 ((eq type 'paragraph)
23517 (goto-char contents-begin)
23518 ;; When at first paragraph in an item or a footnote definition,
23519 ;; move directly to beginning of line.
23520 (let ((parent-contents
23521 (org-element-property
23522 :contents-begin (org-element-property :parent element))))
23523 (when (and parent-contents (= parent-contents contents-begin))
23524 (beginning-of-line))))
23525 ;; At the end of a greater element, move to the beginning of the
23526 ;; last element within.
23527 ((>= (point) contents-end)
23528 (goto-char (1- contents-end))
23529 (org-backward-paragraph))
23530 (t (goto-char (or post-affiliated begin))))
23531 ;; Ensure we never leave point invisible.
23532 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23533
23534 (defun org-forward-element ()
23535 "Move forward by one element.
23536 Move to the next element at the same level, when possible."
23537 (interactive)
23538 (cond ((eobp) (user-error "Cannot move further down"))
23539 ((org-with-limited-levels (org-at-heading-p))
23540 (let ((origin (point)))
23541 (goto-char (org-end-of-subtree nil t))
23542 (unless (org-with-limited-levels (org-at-heading-p))
23543 (goto-char origin)
23544 (user-error "Cannot move further down"))))
23545 (t
23546 (let* ((elem (org-element-at-point))
23547 (end (org-element-property :end elem))
23548 (parent (org-element-property :parent elem)))
23549 (cond ((and parent (= (org-element-property :contents-end parent) end))
23550 (goto-char (org-element-property :end parent)))
23551 ((integer-or-marker-p end) (goto-char end))
23552 (t (message "No element at point")))))))
23553
23554 (defun org-backward-element ()
23555 "Move backward by one element.
23556 Move to the previous element at the same level, when possible."
23557 (interactive)
23558 (cond ((bobp) (user-error "Cannot move further up"))
23559 ((org-with-limited-levels (org-at-heading-p))
23560 ;; At a headline, move to the previous one, if any, or stay
23561 ;; here.
23562 (let ((origin (point)))
23563 (org-with-limited-levels (org-backward-heading-same-level 1))
23564 ;; When current headline has no sibling above, move to its
23565 ;; parent.
23566 (when (= (point) origin)
23567 (or (org-with-limited-levels (org-up-heading-safe))
23568 (progn (goto-char origin)
23569 (user-error "Cannot move further up"))))))
23570 (t
23571 (let* ((trail (org-element-at-point 'keep-trail))
23572 (elem (car trail))
23573 (prev-elem (nth 1 trail))
23574 (beg (org-element-property :begin elem)))
23575 (cond
23576 ;; Move to beginning of current element if point isn't
23577 ;; there already.
23578 ((null beg) (message "No element at point"))
23579 ((/= (point) beg) (goto-char beg))
23580 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23581 ((org-before-first-heading-p) (goto-char (point-min)))
23582 (t (org-back-to-heading)))))))
23583
23584 (defun org-up-element ()
23585 "Move to upper element."
23586 (interactive)
23587 (if (org-with-limited-levels (org-at-heading-p))
23588 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23589 (let* ((elem (org-element-at-point))
23590 (parent (org-element-property :parent elem)))
23591 (if parent (goto-char (org-element-property :begin parent))
23592 (if (org-with-limited-levels (org-before-first-heading-p))
23593 (user-error "No surrounding element")
23594 (org-with-limited-levels (org-back-to-heading)))))))
23595
23596 (defvar org-element-greater-elements)
23597 (defun org-down-element ()
23598 "Move to inner element."
23599 (interactive)
23600 (let ((element (org-element-at-point)))
23601 (cond
23602 ((memq (org-element-type element) '(plain-list table))
23603 (goto-char (org-element-property :contents-begin element))
23604 (forward-char))
23605 ((memq (org-element-type element) org-element-greater-elements)
23606 ;; If contents are hidden, first disclose them.
23607 (when (org-element-property :hiddenp element) (org-cycle))
23608 (goto-char (or (org-element-property :contents-begin element)
23609 (user-error "No content for this element"))))
23610 (t (user-error "No inner element")))))
23611
23612 (defun org-drag-element-backward ()
23613 "Move backward element at point."
23614 (interactive)
23615 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23616 (let* ((trail (org-element-at-point 'keep-trail))
23617 (elem (car trail))
23618 (prev-elem (nth 1 trail)))
23619 ;; Error out if no previous element or previous element is
23620 ;; a parent of the current one.
23621 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23622 (user-error "Cannot drag element backward")
23623 (let ((pos (point)))
23624 (org-element-swap-A-B prev-elem elem)
23625 (goto-char (+ (org-element-property :begin prev-elem)
23626 (- pos (org-element-property :begin elem)))))))))
23627
23628 (defun org-drag-element-forward ()
23629 "Move forward element at point."
23630 (interactive)
23631 (let* ((pos (point))
23632 (elem (org-element-at-point)))
23633 (when (= (point-max) (org-element-property :end elem))
23634 (user-error "Cannot drag element forward"))
23635 (goto-char (org-element-property :end elem))
23636 (let ((next-elem (org-element-at-point)))
23637 (when (or (org-element-nested-p elem next-elem)
23638 (and (eq (org-element-type next-elem) 'headline)
23639 (not (eq (org-element-type elem) 'headline))))
23640 (goto-char pos)
23641 (user-error "Cannot drag element forward"))
23642 ;; Compute new position of point: it's shifted by NEXT-ELEM
23643 ;; body's length (without final blanks) and by the length of
23644 ;; blanks between ELEM and NEXT-ELEM.
23645 (let ((size-next (- (save-excursion
23646 (goto-char (org-element-property :end next-elem))
23647 (skip-chars-backward " \r\t\n")
23648 (forward-line)
23649 ;; Small correction if buffer doesn't end
23650 ;; with a newline character.
23651 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23652 (org-element-property :begin next-elem)))
23653 (size-blank (- (org-element-property :end elem)
23654 (save-excursion
23655 (goto-char (org-element-property :end elem))
23656 (skip-chars-backward " \r\t\n")
23657 (forward-line)
23658 (point)))))
23659 (org-element-swap-A-B elem next-elem)
23660 (goto-char (+ pos size-next size-blank))))))
23661
23662 (defun org-drag-line-forward (arg)
23663 "Drag the line at point ARG lines forward."
23664 (interactive "p")
23665 (dotimes (n (abs arg))
23666 (let ((c (current-column)))
23667 (if (< 0 arg)
23668 (progn
23669 (beginning-of-line 2)
23670 (transpose-lines 1)
23671 (beginning-of-line 0))
23672 (transpose-lines 1)
23673 (beginning-of-line -1))
23674 (org-move-to-column c))))
23675
23676 (defun org-drag-line-backward (arg)
23677 "Drag the line at point ARG lines backward."
23678 (interactive "p")
23679 (org-drag-line-forward (- arg)))
23680
23681 (defun org-mark-element ()
23682 "Put point at beginning of this element, mark at end.
23683
23684 Interactively, if this command is repeated or (in Transient Mark
23685 mode) if the mark is active, it marks the next element after the
23686 ones already marked."
23687 (interactive)
23688 (let (deactivate-mark)
23689 (if (and (org-called-interactively-p 'any)
23690 (or (and (eq last-command this-command) (mark t))
23691 (and transient-mark-mode mark-active)))
23692 (set-mark
23693 (save-excursion
23694 (goto-char (mark))
23695 (goto-char (org-element-property :end (org-element-at-point)))))
23696 (let ((element (org-element-at-point)))
23697 (end-of-line)
23698 (push-mark (org-element-property :end element) t t)
23699 (goto-char (org-element-property :begin element))))))
23700
23701 (defun org-narrow-to-element ()
23702 "Narrow buffer to current element."
23703 (interactive)
23704 (let ((elem (org-element-at-point)))
23705 (cond
23706 ((eq (car elem) 'headline)
23707 (narrow-to-region
23708 (org-element-property :begin elem)
23709 (org-element-property :end elem)))
23710 ((memq (car elem) org-element-greater-elements)
23711 (narrow-to-region
23712 (org-element-property :contents-begin elem)
23713 (org-element-property :contents-end elem)))
23714 (t
23715 (narrow-to-region
23716 (org-element-property :begin elem)
23717 (org-element-property :end elem))))))
23718
23719 (defun org-transpose-element ()
23720 "Transpose current and previous elements, keeping blank lines between.
23721 Point is moved after both elements."
23722 (interactive)
23723 (org-skip-whitespace)
23724 (let ((end (org-element-property :end (org-element-at-point))))
23725 (org-drag-element-backward)
23726 (goto-char end)))
23727
23728 (defun org-unindent-buffer ()
23729 "Un-indent the visible part of the buffer.
23730 Relative indentation (between items, inside blocks, etc.) isn't
23731 modified."
23732 (interactive)
23733 (unless (eq major-mode 'org-mode)
23734 (user-error "Cannot un-indent a buffer not in Org mode"))
23735 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23736 unindent-tree ; For byte-compiler.
23737 (unindent-tree
23738 (function
23739 (lambda (contents)
23740 (mapc
23741 (lambda (element)
23742 (if (memq (org-element-type element) '(headline section))
23743 (funcall unindent-tree (org-element-contents element))
23744 (save-excursion
23745 (save-restriction
23746 (narrow-to-region
23747 (org-element-property :begin element)
23748 (org-element-property :end element))
23749 (org-do-remove-indentation)))))
23750 (reverse contents))))))
23751 (funcall unindent-tree (org-element-contents parse-tree))))
23752
23753 (defun org-show-subtree ()
23754 "Show everything after this heading at deeper levels."
23755 (interactive)
23756 (outline-flag-region
23757 (point)
23758 (save-excursion
23759 (org-end-of-subtree t t))
23760 nil))
23761
23762 (defun org-show-entry ()
23763 "Show the body directly following this heading.
23764 Show the heading too, if it is currently invisible."
23765 (interactive)
23766 (save-excursion
23767 (condition-case nil
23768 (progn
23769 (org-back-to-heading t)
23770 (outline-flag-region
23771 (max (point-min) (1- (point)))
23772 (save-excursion
23773 (if (re-search-forward
23774 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23775 (match-beginning 1)
23776 (point-max)))
23777 nil)
23778 (org-cycle-hide-drawers 'children))
23779 (error nil))))
23780
23781 (defun org-make-options-regexp (kwds &optional extra)
23782 "Make a regular expression for keyword lines."
23783 (concat
23784 "^#\\+\\("
23785 (mapconcat 'regexp-quote kwds "\\|")
23786 (if extra (concat "\\|" extra))
23787 "\\):[ \t]*\\(.*\\)"))
23788
23789 ;; Make isearch reveal the necessary context
23790 (defun org-isearch-end ()
23791 "Reveal context after isearch exits."
23792 (when isearch-success ; only if search was successful
23793 (if (featurep 'xemacs)
23794 ;; Under XEmacs, the hook is run in the correct place,
23795 ;; we directly show the context.
23796 (org-show-context 'isearch)
23797 ;; In Emacs the hook runs *before* restoring the overlays.
23798 ;; So we have to use a one-time post-command-hook to do this.
23799 ;; (Emacs 22 has a special variable, see function `org-mode')
23800 (unless (and (boundp 'isearch-mode-end-hook-quit)
23801 isearch-mode-end-hook-quit)
23802 ;; Only when the isearch was not quitted.
23803 (org-add-hook 'post-command-hook 'org-isearch-post-command
23804 'append 'local)))))
23805
23806 (defun org-isearch-post-command ()
23807 "Remove self from hook, and show context."
23808 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23809 (org-show-context 'isearch))
23810
23811
23812 ;;;; Integration with and fixes for other packages
23813
23814 ;;; Imenu support
23815
23816 (defvar org-imenu-markers nil
23817 "All markers currently used by Imenu.")
23818 (make-variable-buffer-local 'org-imenu-markers)
23819
23820 (defun org-imenu-new-marker (&optional pos)
23821 "Return a new marker for use by Imenu, and remember the marker."
23822 (let ((m (make-marker)))
23823 (move-marker m (or pos (point)))
23824 (push m org-imenu-markers)
23825 m))
23826
23827 (defun org-imenu-get-tree ()
23828 "Produce the index for Imenu."
23829 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23830 (setq org-imenu-markers nil)
23831 (let* ((n org-imenu-depth)
23832 (re (concat "^" (org-get-limited-outline-regexp)))
23833 (subs (make-vector (1+ n) nil))
23834 (last-level 0)
23835 m level head0 head)
23836 (save-excursion
23837 (save-restriction
23838 (widen)
23839 (goto-char (point-max))
23840 (while (re-search-backward re nil t)
23841 (setq level (org-reduced-level (funcall outline-level)))
23842 (when (and (<= level n)
23843 (looking-at org-complex-heading-regexp)
23844 (setq head0 (org-match-string-no-properties 4)))
23845 (setq head (org-link-display-format head0)
23846 m (org-imenu-new-marker))
23847 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23848 (if (>= level last-level)
23849 (push (cons head m) (aref subs level))
23850 (push (cons head (aref subs (1+ level))) (aref subs level))
23851 (loop for i from (1+ level) to n do (aset subs i nil)))
23852 (setq last-level level)))))
23853 (aref subs 1)))
23854
23855 (eval-after-load "imenu"
23856 '(progn
23857 (add-hook 'imenu-after-jump-hook
23858 (lambda ()
23859 (if (derived-mode-p 'org-mode)
23860 (org-show-context 'org-goto))))))
23861
23862 (defun org-link-display-format (link)
23863 "Replace a link with its the description.
23864 If there is no description, use the link target."
23865 (save-match-data
23866 (if (string-match org-bracket-link-analytic-regexp link)
23867 (replace-match (if (match-end 5)
23868 (match-string 5 link)
23869 (concat (match-string 1 link)
23870 (match-string 3 link)))
23871 nil t link)
23872 link)))
23873
23874 (defun org-toggle-link-display ()
23875 "Toggle the literal or descriptive display of links."
23876 (interactive)
23877 (if org-descriptive-links
23878 (progn (org-remove-from-invisibility-spec '(org-link))
23879 (org-restart-font-lock)
23880 (setq org-descriptive-links nil))
23881 (progn (add-to-invisibility-spec '(org-link))
23882 (org-restart-font-lock)
23883 (setq org-descriptive-links t))))
23884
23885 ;; Speedbar support
23886
23887 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23888 "Overlay marking the agenda restriction line in speedbar.")
23889 (overlay-put org-speedbar-restriction-lock-overlay
23890 'face 'org-agenda-restriction-lock)
23891 (overlay-put org-speedbar-restriction-lock-overlay
23892 'help-echo "Agendas are currently limited to this item.")
23893 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23894
23895 (defun org-speedbar-set-agenda-restriction ()
23896 "Restrict future agenda commands to the location at point in speedbar.
23897 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23898 (interactive)
23899 (require 'org-agenda)
23900 (let (p m tp np dir txt)
23901 (cond
23902 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23903 'org-imenu t))
23904 (setq m (get-text-property p 'org-imenu-marker))
23905 (with-current-buffer (marker-buffer m)
23906 (goto-char m)
23907 (org-agenda-set-restriction-lock 'subtree)))
23908 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23909 'speedbar-function 'speedbar-find-file))
23910 (setq tp (previous-single-property-change
23911 (1+ p) 'speedbar-function)
23912 np (next-single-property-change
23913 tp 'speedbar-function)
23914 dir (speedbar-line-directory)
23915 txt (buffer-substring-no-properties (or tp (point-min))
23916 (or np (point-max))))
23917 (with-current-buffer (find-file-noselect
23918 (let ((default-directory dir))
23919 (expand-file-name txt)))
23920 (unless (derived-mode-p 'org-mode)
23921 (user-error "Cannot restrict to non-Org-mode file"))
23922 (org-agenda-set-restriction-lock 'file)))
23923 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23924 (move-overlay org-speedbar-restriction-lock-overlay
23925 (point-at-bol) (point-at-eol))
23926 (setq current-prefix-arg nil)
23927 (org-agenda-maybe-redo)))
23928
23929 (defvar speedbar-file-key-map)
23930 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23931 (eval-after-load "speedbar"
23932 '(progn
23933 (speedbar-add-supported-extension ".org")
23934 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23935 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23936 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23937 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23938 (add-hook 'speedbar-visiting-tag-hook
23939 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23940
23941 ;;; Fixes and Hacks for problems with other packages
23942
23943 ;; Make flyspell not check words in links, to not mess up our keymap
23944 (defvar org-element-affiliated-keywords) ; From org-element.el
23945 (defvar org-element-block-name-alist) ; From org-element.el
23946 (defun org-mode-flyspell-verify ()
23947 "Don't let flyspell put overlays at active buttons, or on
23948 {todo,all-time,additional-option-like}-keywords."
23949 (require 'org-element) ; For `org-element-affiliated-keywords'
23950 (let ((pos (max (1- (point)) (point-min)))
23951 (word (thing-at-point 'word)))
23952 (and (not (get-text-property pos 'keymap))
23953 (not (get-text-property pos 'org-no-flyspell))
23954 (not (member word org-todo-keywords-1))
23955 (not (member word org-all-time-keywords))
23956 (not (member word org-options-keywords))
23957 (not (member word (mapcar 'car org-startup-options)))
23958 (not (member-ignore-case word org-element-affiliated-keywords))
23959 (not (member-ignore-case word (org-get-export-keywords)))
23960 (not (member-ignore-case
23961 word (mapcar 'car org-element-block-name-alist)))
23962 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23963 (not (org-in-src-block-p)))))
23964
23965 (defun org-remove-flyspell-overlays-in (beg end)
23966 "Remove flyspell overlays in region."
23967 (and (org-bound-and-true-p flyspell-mode)
23968 (fboundp 'flyspell-delete-region-overlays)
23969 (flyspell-delete-region-overlays beg end))
23970 (add-text-properties beg end '(org-no-flyspell t)))
23971
23972 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23973 (eval-after-load "bookmark"
23974 '(if (boundp 'bookmark-after-jump-hook)
23975 ;; We can use the hook
23976 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23977 ;; Hook not available, use advice
23978 (defadvice bookmark-jump (after org-make-visible activate)
23979 "Make the position visible."
23980 (org-bookmark-jump-unhide))))
23981
23982 ;; Make sure saveplace shows the location if it was hidden
23983 (eval-after-load "saveplace"
23984 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23985 "Make the position visible."
23986 (org-bookmark-jump-unhide)))
23987
23988 ;; Make sure ecb shows the location if it was hidden
23989 (eval-after-load "ecb"
23990 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23991 "Make hierarchy visible when jumping into location from ECB tree buffer."
23992 (if (derived-mode-p 'org-mode)
23993 (org-show-context))))
23994
23995 (defun org-bookmark-jump-unhide ()
23996 "Unhide the current position, to show the bookmark location."
23997 (and (derived-mode-p 'org-mode)
23998 (or (outline-invisible-p)
23999 (save-excursion (goto-char (max (point-min) (1- (point))))
24000 (outline-invisible-p)))
24001 (org-show-context 'bookmark-jump)))
24002
24003 ;; Make session.el ignore our circular variable
24004 (defvar session-globals-exclude)
24005 (eval-after-load "session"
24006 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24007
24008 ;;;; Finish up
24009
24010 (provide 'org)
24011
24012 (run-hooks 'org-load-hook)
24013
24014 ;;; org.el ends here