]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
957a7d029ec5d40c4e98ed29d8772ffbcde8aeb9
[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 `\\[org-mode]' 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%%"
4350 (floor (* 100.0 (point)) (buffer-size))))
4351 (beginning-of-line 1)
4352 (when (and (looking-at org-table-line-regexp)
4353 ;; Exclude tables in src/example/verbatim/clocktable blocks
4354 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4355 (save-excursion (funcall function))
4356 (or (looking-at org-table-line-regexp)
4357 (forward-char 1)))
4358 (re-search-forward org-table-any-border-regexp nil 1))))
4359 (unless quietly (message "Mapping tables: done")))
4360
4361 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4362 (declare-function org-clock-update-mode-line "org-clock" ())
4363 (declare-function org-resolve-clocks "org-clock"
4364 (&optional also-non-dangling-p prompt last-valid))
4365
4366 (defun org-at-TBLFM-p (&optional pos)
4367 "Return t when point (or POS) is in #+TBLFM line."
4368 (save-excursion
4369 (let ((pos pos)))
4370 (goto-char (or pos (point)))
4371 (beginning-of-line 1)
4372 (looking-at org-TBLFM-regexp)))
4373
4374 (defvar org-clock-start-time)
4375 (defvar org-clock-marker (make-marker)
4376 "Marker recording the last clock-in.")
4377 (defvar org-clock-hd-marker (make-marker)
4378 "Marker recording the last clock-in, but the headline position.")
4379 (defvar org-clock-heading ""
4380 "The heading of the current clock entry.")
4381 (defun org-clock-is-active ()
4382 "Return the buffer where the clock is currently running.
4383 Return nil if no clock is running."
4384 (marker-buffer org-clock-marker))
4385
4386 (defun org-check-running-clock ()
4387 "Check if the current buffer contains the running clock.
4388 If yes, offer to stop it and to save the buffer with the changes."
4389 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4390 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4391 (buffer-name))))
4392 (org-clock-out)
4393 (when (y-or-n-p "Save changed buffer?")
4394 (save-buffer))))
4395
4396 (defun org-clocktable-try-shift (dir n)
4397 "Check if this line starts a clock table, if yes, shift the time block."
4398 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4399 (org-clocktable-shift dir n)))
4400
4401 ;;;###autoload
4402 (defun org-clock-persistence-insinuate ()
4403 "Set up hooks for clock persistence."
4404 (require 'org-clock)
4405 (add-hook 'org-mode-hook 'org-clock-load)
4406 (add-hook 'kill-emacs-hook 'org-clock-save))
4407
4408 (defgroup org-archive nil
4409 "Options concerning archiving in Org-mode."
4410 :tag "Org Archive"
4411 :group 'org-structure)
4412
4413 (defcustom org-archive-location "%s_archive::"
4414 "The location where subtrees should be archived.
4415
4416 The value of this variable is a string, consisting of two parts,
4417 separated by a double-colon. The first part is a filename and
4418 the second part is a headline.
4419
4420 When the filename is omitted, archiving happens in the same file.
4421 %s in the filename will be replaced by the current file
4422 name (without the directory part). Archiving to a different file
4423 is useful to keep archived entries from contributing to the
4424 Org-mode Agenda.
4425
4426 The archived entries will be filed as subtrees of the specified
4427 headline. When the headline is omitted, the subtrees are simply
4428 filed away at the end of the file, as top-level entries. Also in
4429 the heading you can use %s to represent the file name, this can be
4430 useful when using the same archive for a number of different files.
4431
4432 Here are a few examples:
4433 \"%s_archive::\"
4434 If the current file is Projects.org, archive in file
4435 Projects.org_archive, as top-level trees. This is the default.
4436
4437 \"::* Archived Tasks\"
4438 Archive in the current file, under the top-level headline
4439 \"* Archived Tasks\".
4440
4441 \"~/org/archive.org::\"
4442 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4443
4444 \"~/org/archive.org::* From %s\"
4445 Archive in file ~/org/archive.org (absolute path), under headlines
4446 \"From FILENAME\" where file name is the current file name.
4447
4448 \"~/org/datetree.org::datetree/* Finished Tasks\"
4449 The \"datetree/\" string is special, signifying to archive
4450 items to the datetree. Items are placed in either the CLOSED
4451 date of the item, or the current date if there is no CLOSED date.
4452 The heading will be a subentry to the current date. There doesn't
4453 need to be a heading, but there always needs to be a slash after
4454 datetree. For example, to store archived items directly in the
4455 datetree, use \"~/org/datetree.org::datetree/\".
4456
4457 \"basement::** Finished Tasks\"
4458 Archive in file ./basement (relative path), as level 3 trees
4459 below the level 2 heading \"** Finished Tasks\".
4460
4461 You may set this option on a per-file basis by adding to the buffer a
4462 line like
4463
4464 #+ARCHIVE: basement::** Finished Tasks
4465
4466 You may also define it locally for a subtree by setting an ARCHIVE property
4467 in the entry. If such a property is found in an entry, or anywhere up
4468 the hierarchy, it will be used."
4469 :group 'org-archive
4470 :type 'string)
4471
4472 (defcustom org-archive-tag "ARCHIVE"
4473 "The tag that marks a subtree as archived.
4474 An archived subtree does not open during visibility cycling, and does
4475 not contribute to the agenda listings.
4476 After changing this, font-lock must be restarted in the relevant buffers to
4477 get the proper fontification."
4478 :group 'org-archive
4479 :group 'org-keywords
4480 :type 'string)
4481
4482 (defcustom org-agenda-skip-archived-trees t
4483 "Non-nil means the agenda will skip any items located in archived trees.
4484 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4485 variable is no longer recommended, you should leave it at the value t.
4486 Instead, use the key `v' to cycle the archives-mode in the agenda."
4487 :group 'org-archive
4488 :group 'org-agenda-skip
4489 :type 'boolean)
4490
4491 (defcustom org-columns-skip-archived-trees t
4492 "Non-nil means ignore archived trees when creating column view."
4493 :group 'org-archive
4494 :group 'org-properties
4495 :type 'boolean)
4496
4497 (defcustom org-cycle-open-archived-trees nil
4498 "Non-nil means `org-cycle' will open archived trees.
4499 An archived tree is a tree marked with the tag ARCHIVE.
4500 When nil, archived trees will stay folded. You can still open them with
4501 normal outline commands like `show-all', but not with the cycling commands."
4502 :group 'org-archive
4503 :group 'org-cycle
4504 :type 'boolean)
4505
4506 (defcustom org-sparse-tree-open-archived-trees nil
4507 "Non-nil means sparse tree construction shows matches in archived trees.
4508 When nil, matches in these trees are highlighted, but the trees are kept in
4509 collapsed state."
4510 :group 'org-archive
4511 :group 'org-sparse-trees
4512 :type 'boolean)
4513
4514 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4515 "The default date type when building a sparse tree.
4516 When this is nil, a date is a scheduled or a deadline timestamp.
4517 Otherwise, these types are allowed:
4518
4519 all: all timestamps
4520 active: only active timestamps (<...>)
4521 inactive: only inactive timestamps (<...)
4522 scheduled: only scheduled timestamps
4523 deadline: only deadline timestamps"
4524 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4525 (const :tag "All timestamps" all)
4526 (const :tag "Only active timestamps" active)
4527 (const :tag "Only inactive timestamps" inactive)
4528 (const :tag "Only scheduled timestamps" scheduled)
4529 (const :tag "Only deadline timestamps" deadline)
4530 (const :tag "Only closed timestamps" closed))
4531 :version "24.3"
4532 :group 'org-sparse-trees)
4533
4534 (defun org-cycle-hide-archived-subtrees (state)
4535 "Re-hide all archived subtrees after a visibility state change."
4536 (when (and (not org-cycle-open-archived-trees)
4537 (not (memq state '(overview folded))))
4538 (save-excursion
4539 (let* ((globalp (memq state '(contents all)))
4540 (beg (if globalp (point-min) (point)))
4541 (end (if globalp (point-max) (org-end-of-subtree t))))
4542 (org-hide-archived-subtrees beg end)
4543 (goto-char beg)
4544 (if (looking-at (concat ".*:" org-archive-tag ":"))
4545 (message "%s" (substitute-command-keys
4546 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4547
4548 (defun org-force-cycle-archived ()
4549 "Cycle subtree even if it is archived."
4550 (interactive)
4551 (setq this-command 'org-cycle)
4552 (let ((org-cycle-open-archived-trees t))
4553 (call-interactively 'org-cycle)))
4554
4555 (defun org-hide-archived-subtrees (beg end)
4556 "Re-hide all archived subtrees after a visibility state change."
4557 (save-excursion
4558 (let* ((re (concat ":" org-archive-tag ":")))
4559 (goto-char beg)
4560 (while (re-search-forward re end t)
4561 (when (org-at-heading-p)
4562 (org-flag-subtree t)
4563 (org-end-of-subtree t))))))
4564
4565 (declare-function outline-end-of-heading "outline" ())
4566 (declare-function outline-flag-region "outline" (from to flag))
4567 (defun org-flag-subtree (flag)
4568 (save-excursion
4569 (org-back-to-heading t)
4570 (outline-end-of-heading)
4571 (outline-flag-region (point)
4572 (progn (org-end-of-subtree t) (point))
4573 flag)))
4574
4575 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4576
4577 ;; Declare Column View Code
4578
4579 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4580 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4581 (declare-function org-columns-compute "org-colview" (property))
4582
4583 ;; Declare ID code
4584
4585 (declare-function org-id-store-link "org-id")
4586 (declare-function org-id-locations-load "org-id")
4587 (declare-function org-id-locations-save "org-id")
4588 (defvar org-id-track-globally)
4589
4590 ;;; Variables for pre-computed regular expressions, all buffer local
4591
4592 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4593 "Matches first line of a hidden block.")
4594 (make-variable-buffer-local 'org-drawer-regexp)
4595 (defvar org-todo-regexp nil
4596 "Matches any of the TODO state keywords.")
4597 (make-variable-buffer-local 'org-todo-regexp)
4598 (defvar org-not-done-regexp nil
4599 "Matches any of the TODO state keywords except the last one.")
4600 (make-variable-buffer-local 'org-not-done-regexp)
4601 (defvar org-not-done-heading-regexp nil
4602 "Matches a TODO headline that is not done.")
4603 (make-variable-buffer-local 'org-not-done-regexp)
4604 (defvar org-todo-line-regexp nil
4605 "Matches a headline and puts TODO state into group 2 if present.")
4606 (make-variable-buffer-local 'org-todo-line-regexp)
4607 (defvar org-complex-heading-regexp nil
4608 "Matches a headline and puts everything into groups:
4609 group 1: the stars
4610 group 2: The todo keyword, maybe
4611 group 3: Priority cookie
4612 group 4: True headline
4613 group 5: Tags")
4614 (make-variable-buffer-local 'org-complex-heading-regexp)
4615 (defvar org-complex-heading-regexp-format nil
4616 "Printf format to make regexp to match an exact headline.
4617 This regexp will match the headline of any node which has the
4618 exact headline text that is put into the format, but may have any
4619 TODO state, priority and tags.")
4620 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4621 (defvar org-todo-line-tags-regexp nil
4622 "Matches a headline and puts TODO state into group 2 if present.
4623 Also put tags into group 4 if tags are present.")
4624 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4625 (defvar org-ds-keyword-length 12
4626 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4627 (make-variable-buffer-local 'org-ds-keyword-length)
4628 (defvar org-deadline-regexp nil
4629 "Matches the DEADLINE keyword.")
4630 (make-variable-buffer-local 'org-deadline-regexp)
4631 (defvar org-deadline-time-regexp nil
4632 "Matches the DEADLINE keyword together with a time stamp.")
4633 (make-variable-buffer-local 'org-deadline-time-regexp)
4634 (defvar org-deadline-time-hour-regexp nil
4635 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4636 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4637 (defvar org-deadline-line-regexp nil
4638 "Matches the DEADLINE keyword and the rest of the line.")
4639 (make-variable-buffer-local 'org-deadline-line-regexp)
4640 (defvar org-scheduled-regexp nil
4641 "Matches the SCHEDULED keyword.")
4642 (make-variable-buffer-local 'org-scheduled-regexp)
4643 (defvar org-scheduled-time-regexp nil
4644 "Matches the SCHEDULED keyword together with a time stamp.")
4645 (make-variable-buffer-local 'org-scheduled-time-regexp)
4646 (defvar org-scheduled-time-hour-regexp nil
4647 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4648 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4649 (defvar org-closed-time-regexp nil
4650 "Matches the CLOSED keyword together with a time stamp.")
4651 (make-variable-buffer-local 'org-closed-time-regexp)
4652
4653 (defvar org-keyword-time-regexp nil
4654 "Matches any of the 4 keywords, together with the time stamp.")
4655 (make-variable-buffer-local 'org-keyword-time-regexp)
4656 (defvar org-keyword-time-not-clock-regexp nil
4657 "Matches any of the 3 keywords, together with the time stamp.")
4658 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4659 (defvar org-maybe-keyword-time-regexp nil
4660 "Matches a timestamp, possibly preceded by a keyword.")
4661 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4662 (defvar org-all-time-keywords nil
4663 "List of time keywords.")
4664 (make-variable-buffer-local 'org-all-time-keywords)
4665
4666 (defconst org-plain-time-of-day-regexp
4667 (concat
4668 "\\(\\<[012]?[0-9]"
4669 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4670 "\\(--?"
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\)?")
4674 "Regular expression to match a plain time or time range.
4675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4676 groups carry important information:
4677 0 the full match
4678 1 the first time, range or not
4679 8 the second time, if it is a range.")
4680
4681 (defconst org-plain-time-extension-regexp
4682 (concat
4683 "\\(\\<[012]?[0-9]"
4684 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4685 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4686 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4687 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4688 groups carry important information:
4689 0 the full match
4690 7 hours of duration
4691 9 minutes of duration")
4692
4693 (defconst org-stamp-time-of-day-regexp
4694 (concat
4695 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4696 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4697 "\\(--?"
4698 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4699 "Regular expression to match a timestamp time or time range.
4700 After a match, the following groups carry important information:
4701 0 the full match
4702 1 date plus weekday, for back referencing to make sure both times are on the same day
4703 2 the first time, range or not
4704 4 the second time, if it is a range.")
4705
4706 (defconst org-startup-options
4707 '(("fold" org-startup-folded t)
4708 ("overview" org-startup-folded t)
4709 ("nofold" org-startup-folded nil)
4710 ("showall" org-startup-folded nil)
4711 ("showeverything" org-startup-folded showeverything)
4712 ("content" org-startup-folded content)
4713 ("indent" org-startup-indented t)
4714 ("noindent" org-startup-indented nil)
4715 ("hidestars" org-hide-leading-stars t)
4716 ("showstars" org-hide-leading-stars nil)
4717 ("odd" org-odd-levels-only t)
4718 ("oddeven" org-odd-levels-only nil)
4719 ("align" org-startup-align-all-tables t)
4720 ("noalign" org-startup-align-all-tables nil)
4721 ("inlineimages" org-startup-with-inline-images t)
4722 ("noinlineimages" org-startup-with-inline-images nil)
4723 ("latexpreview" org-startup-with-latex-preview t)
4724 ("nolatexpreview" org-startup-with-latex-preview nil)
4725 ("customtime" org-display-custom-times t)
4726 ("logdone" org-log-done time)
4727 ("lognotedone" org-log-done note)
4728 ("nologdone" org-log-done nil)
4729 ("lognoteclock-out" org-log-note-clock-out t)
4730 ("nolognoteclock-out" org-log-note-clock-out nil)
4731 ("logrepeat" org-log-repeat state)
4732 ("lognoterepeat" org-log-repeat note)
4733 ("logdrawer" org-log-into-drawer t)
4734 ("nologdrawer" org-log-into-drawer nil)
4735 ("logstatesreversed" org-log-states-order-reversed t)
4736 ("nologstatesreversed" org-log-states-order-reversed nil)
4737 ("nologrepeat" org-log-repeat nil)
4738 ("logreschedule" org-log-reschedule time)
4739 ("lognotereschedule" org-log-reschedule note)
4740 ("nologreschedule" org-log-reschedule nil)
4741 ("logredeadline" org-log-redeadline time)
4742 ("lognoteredeadline" org-log-redeadline note)
4743 ("nologredeadline" org-log-redeadline nil)
4744 ("logrefile" org-log-refile time)
4745 ("lognoterefile" org-log-refile note)
4746 ("nologrefile" org-log-refile nil)
4747 ("fninline" org-footnote-define-inline t)
4748 ("nofninline" org-footnote-define-inline nil)
4749 ("fnlocal" org-footnote-section nil)
4750 ("fnauto" org-footnote-auto-label t)
4751 ("fnprompt" org-footnote-auto-label nil)
4752 ("fnconfirm" org-footnote-auto-label confirm)
4753 ("fnplain" org-footnote-auto-label plain)
4754 ("fnadjust" org-footnote-auto-adjust t)
4755 ("nofnadjust" org-footnote-auto-adjust nil)
4756 ("constcgs" constants-unit-system cgs)
4757 ("constSI" constants-unit-system SI)
4758 ("noptag" org-tag-persistent-alist nil)
4759 ("hideblocks" org-hide-block-startup t)
4760 ("nohideblocks" org-hide-block-startup nil)
4761 ("beamer" org-startup-with-beamer-mode t)
4762 ("entitiespretty" org-pretty-entities t)
4763 ("entitiesplain" org-pretty-entities nil))
4764 "Variable associated with STARTUP options for org-mode.
4765 Each element is a list of three items: the startup options (as written
4766 in the #+STARTUP line), the corresponding variable, and the value to set
4767 this variable to if the option is found. An optional forth element PUSH
4768 means to push this value onto the list in the variable.")
4769
4770 (defun org-update-property-plist (key val props)
4771 "Update PROPS with KEY and VAL."
4772 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4773 (key (if appending (substring key 0 (- (length key) 1)) key))
4774 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4775 (previous (cdr (assoc key props))))
4776 (if appending
4777 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4778 (cons (cons key val) remainder))))
4779
4780 (defconst org-block-regexp
4781 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4782 "Regular expression for hiding blocks.")
4783 (defconst org-heading-keyword-regexp-format
4784 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4785 "Printf format for a regexp matching a headline with some keyword.
4786 This regexp will match the headline of any node which has the
4787 exact keyword that is put into the format. The keyword isn't in
4788 any group by default, but the stars and the body are.")
4789 (defconst org-heading-keyword-maybe-regexp-format
4790 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4791 "Printf format for a regexp matching a headline, possibly with some keyword.
4792 This regexp can match any headline with the specified keyword, or
4793 without a keyword. The keyword isn't in any group by default,
4794 but the stars and the body are.")
4795
4796 (defcustom org-group-tags t
4797 "When non-nil (the default), use group tags.
4798 This can be turned on/off through `org-toggle-tags-groups'."
4799 :group 'org-tags
4800 :group 'org-startup
4801 :type 'boolean)
4802
4803 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4804
4805 (defun org-toggle-tags-groups ()
4806 "Toggle support for group tags.
4807 Support for group tags is controlled by the option
4808 `org-group-tags', which is non-nil by default."
4809 (interactive)
4810 (setq org-group-tags (not org-group-tags))
4811 (cond ((and (derived-mode-p 'org-agenda-mode)
4812 org-group-tags)
4813 (org-agenda-redo))
4814 ((derived-mode-p 'org-mode)
4815 (let ((org-inhibit-startup t)) (org-mode))))
4816 (message "Groups tags support has been turned %s"
4817 (if org-group-tags "on" "off")))
4818
4819 (defun org-set-regexps-and-options-for-tags ()
4820 "Precompute variables used for tags."
4821 (when (derived-mode-p 'org-mode)
4822 (org-set-local 'org-file-tags nil)
4823 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4824 (splitre "[ \t]+")
4825 (start 0)
4826 tags ftags key value)
4827 (save-excursion
4828 (save-restriction
4829 (widen)
4830 (goto-char (point-min))
4831 (while (re-search-forward re nil t)
4832 (setq key (upcase (org-match-string-no-properties 1))
4833 value (org-match-string-no-properties 2))
4834 (if (stringp value) (setq value (org-trim value)))
4835 (cond
4836 ((equal key "TAGS")
4837 (setq tags (append tags (if tags '("\\n") nil)
4838 (org-split-string value splitre))))
4839 ((equal key "FILETAGS")
4840 (when (string-match "\\S-" value)
4841 (setq ftags
4842 (append
4843 ftags
4844 (apply 'append
4845 (mapcar (lambda (x) (org-split-string x ":"))
4846 (org-split-string value)))))))))))
4847 ;; Process the file tags.
4848 (and ftags (org-set-local 'org-file-tags
4849 (mapcar 'org-add-prop-inherited ftags)))
4850 (org-set-local 'org-tag-groups-alist nil)
4851 ;; Process the tags.
4852 (when (and (not tags) org-tag-alist)
4853 (setq tags
4854 (mapcar
4855 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4856 ((eq (car tg) :endgroup) "}")
4857 ((eq (car tg) :grouptags) ":")
4858 ((eq (car tg) :newline) "\n")
4859 (t (concat (car tg)
4860 (if (characterp (cdr tg))
4861 (format "(%s)" (char-to-string (cdr tg))) "")))))
4862 org-tag-alist)))
4863 (let (tgs g)
4864 (dolist (e tags)
4865 (cond
4866 ((equal e "{")
4867 (progn (push '(:startgroup) tgs)
4868 (when (equal (nth 1 tags) ":")
4869 (push (list (replace-regexp-in-string
4870 "(.+)$" "" (nth 0 tags)))
4871 org-tag-groups-alist)
4872 (setq g 0))))
4873 ((equal e ":") (push '(:grouptags) tgs))
4874 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4875 ((equal e "\\n") (push '(:newline) tgs))
4876 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4877 (push (cons (match-string 1 e)
4878 (string-to-char (match-string 2 e)))
4879 tgs)
4880 (if (and g (> g 0))
4881 (setcar org-tag-groups-alist
4882 (append (car org-tag-groups-alist)
4883 (list (match-string 1 e)))))
4884 (if g (setq g (1+ g))))
4885 (t (push (list e) tgs)
4886 (if (and g (> g 0))
4887 (setcar org-tag-groups-alist
4888 (append (car org-tag-groups-alist) (list e))))
4889 (if g (setq g (1+ g))))))
4890 (org-set-local 'org-tag-alist nil)
4891 (dolist (e tgs)
4892 (or (and (stringp (car e))
4893 (assoc (car e) org-tag-alist))
4894 (push e org-tag-alist)))
4895 ;; Return a list with tag variables
4896 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4897
4898 (defvar org-ota nil)
4899 (defun org-set-regexps-and-options ()
4900 "Precompute regular expressions used in the current buffer."
4901 (when (derived-mode-p 'org-mode)
4902 (org-set-local 'org-todo-kwd-alist nil)
4903 (org-set-local 'org-todo-key-alist nil)
4904 (org-set-local 'org-todo-key-trigger nil)
4905 (org-set-local 'org-todo-keywords-1 nil)
4906 (org-set-local 'org-done-keywords nil)
4907 (org-set-local 'org-todo-heads nil)
4908 (org-set-local 'org-todo-sets nil)
4909 (org-set-local 'org-todo-log-states nil)
4910 (org-set-local 'org-file-properties nil)
4911 (let ((re (org-make-options-regexp
4912 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4913 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4914 "SETUPFILE" "OPTIONS")
4915 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4916 (splitre "[ \t]+")
4917 (scripts org-use-sub-superscripts)
4918 kwds kws0 kwsa key log value cat arch const links hw dws
4919 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4920 (start 0))
4921 (save-excursion
4922 (save-restriction
4923 (widen)
4924 (goto-char (point-min))
4925 (while
4926 (or (and
4927 ext-setup-or-nil
4928 (not org-ota)
4929 (let (ret)
4930 (with-temp-buffer
4931 (insert ext-setup-or-nil)
4932 (let ((major-mode 'org-mode) org-ota)
4933 (setq ret (save-match-data
4934 (org-set-regexps-and-options-for-tags)))))
4935 ;; Append setupfile tags to existing tags
4936 (setq org-ota t)
4937 (setq org-file-tags
4938 (delq nil (append org-file-tags (nth 0 ret)))
4939 org-tag-alist
4940 (delq nil (append org-tag-alist (nth 1 ret)))
4941 org-tag-groups-alist
4942 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4943 (and ext-setup-or-nil
4944 (string-match re ext-setup-or-nil start)
4945 (setq start (match-end 0)))
4946 (and (setq ext-setup-or-nil nil start 0)
4947 (re-search-forward re nil t)))
4948 (setq key (upcase (match-string 1 ext-setup-or-nil))
4949 value (org-match-string-no-properties 2 ext-setup-or-nil))
4950 (if (stringp value) (setq value (org-trim value)))
4951 (cond
4952 ((equal key "CATEGORY")
4953 (setq cat value))
4954 ((member key '("SEQ_TODO" "TODO"))
4955 (push (cons 'sequence (org-split-string value splitre)) kwds))
4956 ((equal key "TYP_TODO")
4957 (push (cons 'type (org-split-string value splitre)) kwds))
4958 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4959 ;; general TODO-like setup
4960 (push (cons (intern (downcase (match-string 1 key)))
4961 (org-split-string value splitre))
4962 kwds))
4963 ((equal key "COLUMNS")
4964 (org-set-local 'org-columns-default-format value))
4965 ((equal key "LINK")
4966 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4967 (push (cons (match-string 1 value)
4968 (org-trim (match-string 2 value)))
4969 links)))
4970 ((equal key "PRIORITIES")
4971 (setq prio (org-split-string value " +")))
4972 ((equal key "PROPERTY")
4973 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4974 (setq props (org-update-property-plist (match-string 1 value)
4975 (match-string 2 value)
4976 props))))
4977 ((equal key "DRAWERS")
4978 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4979 ((equal key "CONSTANTS")
4980 (org-table-set-constants))
4981 ((equal key "STARTUP")
4982 (let ((opts (org-split-string value splitre))
4983 var val)
4984 (dolist (l opts)
4985 (when (setq l (assoc l org-startup-options))
4986 (setq var (nth 1 l) val (nth 2 l))
4987 (if (not (nth 3 l))
4988 (set (make-local-variable var) val)
4989 (if (not (listp (symbol-value var)))
4990 (set (make-local-variable var) nil))
4991 (set (make-local-variable var) (symbol-value var))
4992 (add-to-list var val))))))
4993 ((equal key "ARCHIVE")
4994 (setq arch value)
4995 (remove-text-properties 0 (length arch)
4996 '(face t fontified t) arch))
4997 ((equal key "OPTIONS")
4998 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4999 (setq scripts (read (match-string 2 value)))))
5000 ((and (equal key "SETUPFILE")
5001 ;; Prevent checking in Gnus messages
5002 (not buffer-read-only))
5003 (setq setup-contents (org-file-contents
5004 (expand-file-name
5005 (org-remove-double-quotes value))
5006 'noerror))
5007 (if (not ext-setup-or-nil)
5008 (setq ext-setup-or-nil setup-contents start 0)
5009 (setq ext-setup-or-nil
5010 (concat (substring ext-setup-or-nil 0 start)
5011 "\n" setup-contents "\n"
5012 (substring ext-setup-or-nil start)))))))
5013 ;; search for property blocks
5014 (goto-char (point-min))
5015 (while (re-search-forward org-block-regexp nil t)
5016 (when (equal "PROPERTY" (upcase (match-string 1)))
5017 (setq value (replace-regexp-in-string
5018 "[\n\r]" " " (match-string 4)))
5019 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5020 (setq props (org-update-property-plist (match-string 1 value)
5021 (match-string 2 value)
5022 props)))))))
5023 (org-set-local 'org-use-sub-superscripts scripts)
5024 (when cat
5025 (org-set-local 'org-category (intern cat))
5026 (push (cons "CATEGORY" cat) props))
5027 (when prio
5028 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5029 (setq prio (mapcar 'string-to-char prio))
5030 (org-set-local 'org-highest-priority (nth 0 prio))
5031 (org-set-local 'org-lowest-priority (nth 1 prio))
5032 (org-set-local 'org-default-priority (nth 2 prio)))
5033 (and props (org-set-local 'org-file-properties (nreverse props)))
5034 (and drawers (org-set-local 'org-drawers drawers))
5035 (and arch (org-set-local 'org-archive-location arch))
5036 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5037 ;; Process the TODO keywords
5038 (unless kwds
5039 ;; Use the global values as if they had been given locally.
5040 (setq kwds (default-value 'org-todo-keywords))
5041 (if (stringp (car kwds))
5042 (setq kwds (list (cons org-todo-interpretation
5043 (default-value 'org-todo-keywords)))))
5044 (setq kwds (reverse kwds)))
5045 (setq kwds (nreverse kwds))
5046 (let (inter kw)
5047 (dolist (kws kwds)
5048 (let ((kws (or
5049 (run-hook-with-args-until-success
5050 'org-todo-setup-filter-hook kws)
5051 kws)))
5052 (setq inter (pop kws) sep (member "|" kws)
5053 kws0 (delete "|" (copy-sequence kws))
5054 kwsa nil
5055 kws1 (mapcar
5056 (lambda (x)
5057 ;; 1 2
5058 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5059 (progn
5060 (setq kw (match-string 1 x)
5061 key (and (match-end 2) (match-string 2 x))
5062 log (org-extract-log-state-settings x))
5063 (push (cons kw (and key (string-to-char key))) kwsa)
5064 (and log (push log org-todo-log-states))
5065 kw)
5066 (error "Invalid TODO keyword %s" x)))
5067 kws0)
5068 kwsa (if kwsa (append '((:startgroup))
5069 (nreverse kwsa)
5070 '((:endgroup))))
5071 hw (car kws1)
5072 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5073 tail (list inter hw (car dws) (org-last dws))))
5074 (add-to-list 'org-todo-heads hw 'append)
5075 (push kws1 org-todo-sets)
5076 (setq org-done-keywords (append org-done-keywords dws nil))
5077 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5078 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5079 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5080 (setq org-todo-sets (nreverse org-todo-sets)
5081 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5082 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5083 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5084 ;; Compute the regular expressions and other local variables.
5085 ;; Using `org-outline-regexp-bol' would complicate them much,
5086 ;; because of the fixed white space at the end of that string.
5087 (if (not org-done-keywords)
5088 (setq org-done-keywords (and org-todo-keywords-1
5089 (list (org-last org-todo-keywords-1)))))
5090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5091 (length org-scheduled-string)
5092 (length org-clock-string)
5093 (length org-closed-string)))
5094 org-drawer-regexp
5095 (concat "^[ \t]*:\\("
5096 (mapconcat 'regexp-quote org-drawers "\\|")
5097 "\\):[ \t]*$")
5098 org-not-done-keywords
5099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5100 org-todo-regexp
5101 (concat "\\("
5102 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5103 "\\)")
5104 org-not-done-regexp
5105 (concat "\\("
5106 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5107 "\\)")
5108 org-not-done-heading-regexp
5109 (format org-heading-keyword-regexp-format org-not-done-regexp)
5110 org-todo-line-regexp
5111 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5112 org-complex-heading-regexp
5113 (concat "^\\(\\*+\\)"
5114 "\\(?: +" org-todo-regexp "\\)?"
5115 "\\(?: +\\(\\[#.\\]\\)\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-complex-heading-regexp-format
5120 (concat "^\\(\\*+\\)"
5121 "\\(?: +" org-todo-regexp "\\)?"
5122 "\\(?: +\\(\\[#.\\]\\)\\)?"
5123 "\\(?: +"
5124 ;; Stats cookies can be stuck to body.
5125 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5126 "\\(%s\\)"
5127 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5128 "\\)"
5129 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5130 "[ \t]*$")
5131 org-todo-line-tags-regexp
5132 (concat "^\\(\\*+\\)"
5133 "\\(?: +" org-todo-regexp "\\)?"
5134 "\\(?: +\\(.*?\\)\\)??"
5135 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5136 "[ \t]*$")
5137 org-deadline-regexp (concat "\\<" org-deadline-string)
5138 org-deadline-time-regexp
5139 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5140 org-deadline-time-hour-regexp
5141 (concat "\\<" org-deadline-string
5142 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5143 org-deadline-line-regexp
5144 (concat "\\<\\(" org-deadline-string "\\).*")
5145 org-scheduled-regexp
5146 (concat "\\<" org-scheduled-string)
5147 org-scheduled-time-regexp
5148 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5149 org-scheduled-time-hour-regexp
5150 (concat "\\<" org-scheduled-string
5151 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5152 org-closed-time-regexp
5153 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5154 org-keyword-time-regexp
5155 (concat "\\<\\(" org-scheduled-string
5156 "\\|" org-deadline-string
5157 "\\|" org-closed-string
5158 "\\|" org-clock-string "\\)"
5159 " *[[<]\\([^]>]+\\)[]>]")
5160 org-keyword-time-not-clock-regexp
5161 (concat "\\<\\(" org-scheduled-string
5162 "\\|" org-deadline-string
5163 "\\|" org-closed-string
5164 "\\)"
5165 " *[[<]\\([^]>]+\\)[]>]")
5166 org-maybe-keyword-time-regexp
5167 (concat "\\(\\<\\(" org-scheduled-string
5168 "\\|" org-deadline-string
5169 "\\|" org-closed-string
5170 "\\|" org-clock-string "\\)\\)?"
5171 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5172 org-all-time-keywords
5173 (mapcar (lambda (w) (substring w 0 -1))
5174 (list org-scheduled-string org-deadline-string
5175 org-clock-string org-closed-string)))
5176 (setq org-ota nil)
5177 (org-compute-latex-and-related-regexp))))
5178
5179 (defun org-file-contents (file &optional noerror)
5180 "Return the contents of FILE, as a string."
5181 (if (or (not file) (not (file-readable-p file)))
5182 (if (not noerror)
5183 (error "Cannot read file \"%s\"" file)
5184 (message "Cannot read file \"%s\"" file)
5185 "")
5186 (with-temp-buffer
5187 (insert-file-contents file)
5188 (buffer-string))))
5189
5190 (defun org-extract-log-state-settings (x)
5191 "Extract the log state setting from a TODO keyword string.
5192 This will extract info from a string like \"WAIT(w@/!)\"."
5193 (let (kw key log1 log2)
5194 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5195 (setq kw (match-string 1 x)
5196 key (and (match-end 2) (match-string 2 x))
5197 log1 (and (match-end 3) (match-string 3 x))
5198 log2 (and (match-end 4) (match-string 4 x)))
5199 (and (or log1 log2)
5200 (list kw
5201 (and log1 (if (equal log1 "!") 'time 'note))
5202 (and log2 (if (equal log2 "!") 'time 'note)))))))
5203
5204 (defun org-remove-keyword-keys (list)
5205 "Remove a pair of parenthesis at the end of each string in LIST."
5206 (mapcar (lambda (x)
5207 (if (string-match "(.*)$" x)
5208 (substring x 0 (match-beginning 0))
5209 x))
5210 list))
5211
5212 (defun org-assign-fast-keys (alist)
5213 "Assign fast keys to a keyword-key alist.
5214 Respect keys that are already there."
5215 (let (new (alt ?0))
5216 (dolist (e alist)
5217 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5218 (cdr e)) ;; Key already assigned.
5219 (push e new)
5220 (let ((clist (string-to-list (downcase (car e))))
5221 (used (append new alist)))
5222 (when (= (car clist) ?@)
5223 (pop clist))
5224 (while (and clist (rassoc (car clist) used))
5225 (pop clist))
5226 (unless clist
5227 (while (rassoc alt used)
5228 (incf alt)))
5229 (push (cons (car e) (or (car clist) alt)) new))))
5230 (nreverse new)))
5231
5232 ;;; Some variables used in various places
5233
5234 (defvar org-window-configuration nil
5235 "Used in various places to store a window configuration.")
5236 (defvar org-selected-window nil
5237 "Used in various places to store a window configuration.")
5238 (defvar org-finish-function nil
5239 "Function to be called when `C-c C-c' is used.
5240 This is for getting out of special buffers like capture.")
5241
5242
5243 ;; FIXME: Occasionally check by commenting these, to make sure
5244 ;; no other functions uses these, forgetting to let-bind them.
5245 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5246 (defvar org-last-state)
5247 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5248
5249 ;; Defined somewhere in this file, but used before definition.
5250 (defvar org-entities) ;; defined in org-entities.el
5251 (defvar org-struct-menu)
5252 (defvar org-org-menu)
5253 (defvar org-tbl-menu)
5254
5255 ;;;; Define the Org-mode
5256
5257 ;; We use a before-change function to check if a table might need
5258 ;; an update.
5259 (defvar org-table-may-need-update t
5260 "Indicates that a table might need an update.
5261 This variable is set by `org-before-change-function'.
5262 `org-table-align' sets it back to nil.")
5263 (defun org-before-change-function (beg end)
5264 "Every change indicates that a table might need an update."
5265 (setq org-table-may-need-update t))
5266 (defvar org-mode-map)
5267 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5268 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5269 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5271 (defvar org-table-buffer-is-an nil)
5272
5273 (defvar bidi-paragraph-direction)
5274 (defvar buffer-face-mode-face)
5275
5276 (require 'outline)
5277 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5278 (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"))
5279 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5280
5281 ;; Other stuff we need.
5282 (require 'time-date)
5283 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5284 (require 'easymenu)
5285 (require 'overlay)
5286
5287 ;; (require 'org-macs) moved higher up in the file before it is first used
5288 (require 'org-entities)
5289 ;; (require 'org-compat) moved higher up in the file before it is first used
5290 (require 'org-faces)
5291 (require 'org-list)
5292 (require 'org-pcomplete)
5293 (require 'org-src)
5294 (require 'org-footnote)
5295 (require 'org-macro)
5296
5297 ;; babel
5298 (require 'ob)
5299
5300 ;;;###autoload
5301 (define-derived-mode org-mode outline-mode "Org"
5302 "Outline-based notes management and organizer, alias
5303 \"Carsten's outline-mode for keeping track of everything.\"
5304
5305 Org-mode develops organizational tasks around a NOTES file which
5306 contains information about projects as plain text. Org-mode is
5307 implemented on top of outline-mode, which is ideal to keep the content
5308 of large files well structured. It supports ToDo items, deadlines and
5309 time stamps, which magically appear in the diary listing of the Emacs
5310 calendar. Tables are easily created with a built-in table editor.
5311 Plain text URL-like links connect to websites, emails (VM), Usenet
5312 messages (Gnus), BBDB entries, and any files related to the project.
5313 For printing and sharing of notes, an Org-mode file (or a part of it)
5314 can be exported as a structured ASCII or HTML file.
5315
5316 The following commands are available:
5317
5318 \\{org-mode-map}"
5319
5320 ;; Get rid of Outline menus, they are not needed
5321 ;; Need to do this here because define-derived-mode sets up
5322 ;; the keymap so late. Still, it is a waste to call this each time
5323 ;; we switch another buffer into org-mode.
5324 (if (featurep 'xemacs)
5325 (when (boundp 'outline-mode-menu-heading)
5326 ;; Assume this is Greg's port, it uses easymenu
5327 (easy-menu-remove outline-mode-menu-heading)
5328 (easy-menu-remove outline-mode-menu-show)
5329 (easy-menu-remove outline-mode-menu-hide))
5330 (define-key org-mode-map [menu-bar headings] 'undefined)
5331 (define-key org-mode-map [menu-bar hide] 'undefined)
5332 (define-key org-mode-map [menu-bar show] 'undefined))
5333
5334 (org-load-modules-maybe)
5335 (when (featurep 'xemacs)
5336 (easy-menu-add org-org-menu)
5337 (easy-menu-add org-tbl-menu))
5338 (org-install-agenda-files-menu)
5339 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5340 (add-to-invisibility-spec '(org-cwidth))
5341 (add-to-invisibility-spec '(org-hide-block . t))
5342 (when (featurep 'xemacs)
5343 (org-set-local 'line-move-ignore-invisible t))
5344 (org-set-local 'outline-regexp org-outline-regexp)
5345 (org-set-local 'outline-level 'org-outline-level)
5346 (setq bidi-paragraph-direction 'left-to-right)
5347 (when (and org-ellipsis
5348 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5349 (fboundp 'make-glyph-code))
5350 (unless org-display-table
5351 (setq org-display-table (make-display-table)))
5352 (set-display-table-slot
5353 org-display-table 4
5354 (vconcat (mapcar
5355 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5356 org-ellipsis)))
5357 (if (stringp org-ellipsis) org-ellipsis "..."))))
5358 (setq buffer-display-table org-display-table))
5359 (org-set-regexps-and-options-for-tags)
5360 (org-set-regexps-and-options)
5361 (org-set-font-lock-defaults)
5362 (when (and org-tag-faces (not org-tags-special-faces-re))
5363 ;; tag faces set outside customize.... force initialization.
5364 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5365 ;; Calc embedded
5366 (org-set-local 'calc-embedded-open-mode "# ")
5367 ;; Modify a few syntax entries
5368 (modify-syntax-entry ?@ "w")
5369 (modify-syntax-entry ?\" "\"")
5370 (modify-syntax-entry ?\\ "_")
5371 (modify-syntax-entry ?~ "_")
5372 (if org-startup-truncated (setq truncate-lines t))
5373 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5374 (org-set-local 'font-lock-unfontify-region-function
5375 'org-unfontify-region)
5376 ;; Activate before-change-function
5377 (org-set-local 'org-table-may-need-update t)
5378 (org-add-hook 'before-change-functions 'org-before-change-function nil
5379 'local)
5380 ;; Check for running clock before killing a buffer
5381 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5382 ;; Initialize macros templates.
5383 (org-macro-initialize-templates)
5384 ;; Initialize radio targets.
5385 (org-update-radio-target-regexp)
5386 ;; Indentation.
5387 (org-set-local 'indent-line-function 'org-indent-line)
5388 (org-set-local 'indent-region-function 'org-indent-region)
5389 ;; Filling and auto-filling.
5390 (org-setup-filling)
5391 ;; Comments.
5392 (org-setup-comments-handling)
5393 ;; Beginning/end of defun
5394 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5395 (org-set-local 'end-of-defun-function
5396 (lambda ()
5397 (if (not (org-at-heading-p))
5398 (org-forward-element)
5399 (org-forward-element)
5400 (forward-char -1))))
5401 ;; Next error for sparse trees
5402 (org-set-local 'next-error-function 'org-occur-next-match)
5403 ;; Make sure dependence stuff works reliably, even for users who set it
5404 ;; too late :-(
5405 (if org-enforce-todo-dependencies
5406 (add-hook 'org-blocker-hook
5407 'org-block-todo-from-children-or-siblings-or-parent)
5408 (remove-hook 'org-blocker-hook
5409 'org-block-todo-from-children-or-siblings-or-parent))
5410 (if org-enforce-todo-checkbox-dependencies
5411 (add-hook 'org-blocker-hook
5412 'org-block-todo-from-checkboxes)
5413 (remove-hook 'org-blocker-hook
5414 'org-block-todo-from-checkboxes))
5415
5416 ;; Align options lines
5417 (org-set-local
5418 'align-mode-rules-list
5419 '((org-in-buffer-settings
5420 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5421 (modes . '(org-mode)))))
5422
5423 ;; Imenu
5424 (org-set-local 'imenu-create-index-function
5425 'org-imenu-get-tree)
5426
5427 ;; Make isearch reveal context
5428 (if (or (featurep 'xemacs)
5429 (not (boundp 'outline-isearch-open-invisible-function)))
5430 ;; Emacs 21 and XEmacs make use of the hook
5431 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5432 ;; Emacs 22 deals with this through a special variable
5433 (org-set-local 'outline-isearch-open-invisible-function
5434 (lambda (&rest ignore) (org-show-context 'isearch))))
5435
5436 ;; Setup the pcomplete hooks
5437 (set (make-local-variable 'pcomplete-command-completion-function)
5438 'org-pcomplete-initial)
5439 (set (make-local-variable 'pcomplete-command-name-function)
5440 'org-command-at-point)
5441 (set (make-local-variable 'pcomplete-default-completion-function)
5442 'ignore)
5443 (set (make-local-variable 'pcomplete-parse-arguments-function)
5444 'org-parse-arguments)
5445 (set (make-local-variable 'pcomplete-termination-string) "")
5446 (when (>= emacs-major-version 23)
5447 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5448
5449 ;; If empty file that did not turn on org-mode automatically, make it to.
5450 (if (and org-insert-mode-line-in-empty-file
5451 (org-called-interactively-p 'any)
5452 (= (point-min) (point-max)))
5453 (insert "# -*- mode: org -*-\n\n"))
5454 (unless org-inhibit-startup
5455 (org-unmodified
5456 (and org-startup-with-beamer-mode (org-beamer-mode))
5457 (when org-startup-align-all-tables
5458 (org-table-map-tables 'org-table-align 'quietly))
5459 (when org-startup-with-inline-images
5460 (org-display-inline-images))
5461 (when org-startup-with-latex-preview
5462 (org-preview-latex-fragment))
5463 (unless org-inhibit-startup-visibility-stuff
5464 (org-set-startup-visibility))))
5465 ;; Try to set org-hide correctly
5466 (let ((foreground (org-find-invisible-foreground)))
5467 (if foreground
5468 (set-face-foreground 'org-hide foreground))))
5469
5470 ;; Update `customize-package-emacs-version-alist'
5471 (add-to-list 'customize-package-emacs-version-alist
5472 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5473 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5474 ("8.2.6" . "24.4")))
5475
5476 (defvar org-mode-transpose-word-syntax-table
5477 (let ((st (make-syntax-table)))
5478 (mapc (lambda(c) (modify-syntax-entry
5479 (string-to-char (car c)) "w p" st))
5480 org-emphasis-alist)
5481 st))
5482
5483 (when (fboundp 'abbrev-table-put)
5484 (abbrev-table-put org-mode-abbrev-table
5485 :parents (list text-mode-abbrev-table)))
5486
5487 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5488
5489 (defun org-find-invisible-foreground ()
5490 (let ((candidates (remove
5491 "unspecified-bg"
5492 (nconc
5493 (list (face-background 'default)
5494 (face-background 'org-default))
5495 (mapcar
5496 (lambda (alist)
5497 (when (boundp alist)
5498 (cdr (assoc 'background-color (symbol-value alist)))))
5499 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5500 (list (face-foreground 'org-hide))))))
5501 (car (remove nil candidates))))
5502
5503 (defun org-current-time (&optional rounding-minutes past)
5504 "Current time, possibly rounded to ROUNDING-MINUTES.
5505 When ROUNDING-MINUTES is not an integer, fall back on the car of
5506 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5507 the rounding returns a past time."
5508 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5509 (car org-time-stamp-rounding-minutes)))
5510 (time (decode-time)) res)
5511 (if (< r 1)
5512 (current-time)
5513 (setq res
5514 (apply 'encode-time
5515 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5516 (nthcdr 2 time))))
5517 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5518 (seconds-to-time (- (org-float-time res) (* r 60)))
5519 res))))
5520
5521 (defun org-today ()
5522 "Return today date, considering `org-extend-today-until'."
5523 (time-to-days
5524 (time-subtract (current-time)
5525 (list 0 (* 3600 org-extend-today-until) 0))))
5526
5527 ;;;; Font-Lock stuff, including the activators
5528
5529 (defvar org-mouse-map (make-sparse-keymap))
5530 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5531 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5532 (when org-mouse-1-follows-link
5533 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5534 (when org-tab-follows-link
5535 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5536 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5537
5538 (require 'font-lock)
5539
5540 (defconst org-non-link-chars "]\t\n\r<>")
5541 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5542 "shell" "elisp" "doi" "message"))
5543 (defvar org-link-types-re nil
5544 "Matches a link that has a url-like prefix like \"http:\"")
5545 (defvar org-link-re-with-space nil
5546 "Matches a link with spaces, optional angular brackets around it.")
5547 (defvar org-link-re-with-space2 nil
5548 "Matches a link with spaces, optional angular brackets around it.")
5549 (defvar org-link-re-with-space3 nil
5550 "Matches a link with spaces, only for internal part in bracket links.")
5551 (defvar org-angle-link-re nil
5552 "Matches link with angular brackets, spaces are allowed.")
5553 (defvar org-plain-link-re nil
5554 "Matches plain link, without spaces.")
5555 (defvar org-bracket-link-regexp nil
5556 "Matches a link in double brackets.")
5557 (defvar org-bracket-link-analytic-regexp nil
5558 "Regular expression used to analyze links.
5559 Here is what the match groups contain after a match:
5560 1: http:
5561 2: http
5562 3: path
5563 4: [desc]
5564 5: desc")
5565 (defvar org-bracket-link-analytic-regexp++ nil
5566 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5567 (defvar org-any-link-re nil
5568 "Regular expression matching any link.")
5569
5570 (defconst org-match-sexp-depth 3
5571 "Number of stacked braces for sub/superscript matching.")
5572
5573 (defun org-create-multibrace-regexp (left right n)
5574 "Create a regular expression which will match a balanced sexp.
5575 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5576 as single character strings.
5577 The regexp returned will match the entire expression including the
5578 delimiters. It will also define a single group which contains the
5579 match except for the outermost delimiters. The maximum depth of
5580 stacked delimiters is N. Escaping delimiters is not possible."
5581 (let* ((nothing (concat "[^" left right "]*?"))
5582 (or "\\|")
5583 (re nothing)
5584 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5585 (while (> n 1)
5586 (setq n (1- n)
5587 re (concat re or next)
5588 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5589 (concat left "\\(" re "\\)" right)))
5590
5591 (defvar org-match-substring-regexp
5592 (concat
5593 "\\(\\S-\\)\\([_^]\\)\\("
5594 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5595 "\\|"
5596 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5597 "\\|"
5598 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5599 "The regular expression matching a sub- or superscript.")
5600
5601 (defvar org-match-substring-with-braces-regexp
5602 (concat
5603 "\\(\\S-\\)\\([_^]\\)\\("
5604 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5605 "\\)")
5606 "The regular expression matching a sub- or superscript, forcing braces.")
5607
5608 (defun org-make-link-regexps ()
5609 "Update the link regular expressions.
5610 This should be called after the variable `org-link-types' has changed."
5611 (let ((types-re (regexp-opt org-link-types t)))
5612 (setq org-link-types-re
5613 (concat "\\`" types-re ":")
5614 org-link-re-with-space
5615 (concat "<?" types-re ":"
5616 "\\([^" org-non-link-chars " ]"
5617 "[^" org-non-link-chars "]*"
5618 "[^" org-non-link-chars " ]\\)>?")
5619 org-link-re-with-space2
5620 (concat "<?" types-re ":"
5621 "\\([^" org-non-link-chars " ]"
5622 "[^\t\n\r]*"
5623 "[^" org-non-link-chars " ]\\)>?")
5624 org-link-re-with-space3
5625 (concat "<?" types-re ":"
5626 "\\([^" org-non-link-chars " ]"
5627 "[^\t\n\r]*\\)")
5628 org-angle-link-re
5629 (concat "<" types-re ":"
5630 "\\([^" org-non-link-chars " ]"
5631 "[^" org-non-link-chars "]*"
5632 "\\)>")
5633 org-plain-link-re
5634 (concat
5635 "\\<" types-re ":"
5636 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5637 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5638 org-bracket-link-regexp
5639 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5640 org-bracket-link-analytic-regexp
5641 (concat
5642 "\\[\\["
5643 "\\(" types-re ":\\)?"
5644 "\\([^]]+\\)"
5645 "\\]"
5646 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5647 "\\]")
5648 org-bracket-link-analytic-regexp++
5649 (concat
5650 "\\[\\["
5651 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5652 "\\([^]]+\\)"
5653 "\\]"
5654 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5655 "\\]")
5656 org-any-link-re
5657 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5658 org-angle-link-re "\\)\\|\\("
5659 org-plain-link-re "\\)"))))
5660
5661 (org-make-link-regexps)
5662
5663 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5664 "Regular expression for fast time stamp matching.")
5665 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5666 "Regular expression for fast time stamp matching.")
5667 (defconst org-ts-regexp0
5668 "\\(\\([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 This one does not require the space after the date, so it can be used
5671 on a string that terminates immediately after the date.")
5672 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5673 "Regular expression matching time strings for analysis.")
5674 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5675 "Regular expression matching time stamps, with groups.")
5676 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5677 "Regular expression matching time stamps (also [..]), with groups.")
5678 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5679 "Regular expression matching a time stamp range.")
5680 (defconst org-tr-regexp-both
5681 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5682 "Regular expression matching a time stamp range.")
5683 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5684 org-ts-regexp "\\)?")
5685 "Regular expression matching a time stamp or time stamp range.")
5686 (defconst org-tsr-regexp-both
5687 (concat org-ts-regexp-both "\\(--?-?"
5688 org-ts-regexp-both "\\)?")
5689 "Regular expression matching a time stamp or time stamp range.
5690 The time stamps may be either active or inactive.")
5691
5692 (defvar org-emph-face nil)
5693
5694 (defun org-do-emphasis-faces (limit)
5695 "Run through the buffer and add overlays to emphasized strings."
5696 (let (rtn a)
5697 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5698 (let* ((border (char-after (match-beginning 3)))
5699 (bre (regexp-quote (char-to-string border))))
5700 (if (and (not (= border (char-after (match-beginning 4))))
5701 (not (save-match-data
5702 (string-match (concat bre ".*" bre)
5703 (replace-regexp-in-string
5704 "\n" " "
5705 (substring (match-string 2) 1 -1))))))
5706 (progn
5707 (setq rtn t)
5708 (setq a (assoc (match-string 3) org-emphasis-alist))
5709 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5710 'face
5711 (nth 1 a))
5712 (and (nth 2 a)
5713 (org-remove-flyspell-overlays-in
5714 (match-beginning 0) (match-end 0)))
5715 (add-text-properties (match-beginning 2) (match-end 2)
5716 '(font-lock-multiline t org-emphasis t))
5717 (when org-hide-emphasis-markers
5718 (add-text-properties (match-end 4) (match-beginning 5)
5719 '(invisible org-link))
5720 (add-text-properties (match-beginning 3) (match-end 3)
5721 '(invisible org-link))))))
5722 (goto-char (1+ (match-beginning 0))))
5723 rtn))
5724
5725 (defun org-emphasize (&optional char)
5726 "Insert or change an emphasis, i.e. a font like bold or italic.
5727 If there is an active region, change that region to a new emphasis.
5728 If there is no region, just insert the marker characters and position
5729 the cursor between them.
5730 CHAR should be the marker character. If it is a space, it means to
5731 remove the emphasis of the selected region.
5732 If CHAR is not given (for example in an interactive call) it will be
5733 prompted for."
5734 (interactive)
5735 (let ((erc org-emphasis-regexp-components)
5736 (prompt "")
5737 (string "") beg end move c s)
5738 (if (org-region-active-p)
5739 (setq beg (region-beginning) end (region-end)
5740 string (buffer-substring beg end))
5741 (setq move t))
5742
5743 (unless char
5744 (message "Emphasis marker or tag: [%s]"
5745 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5746 (setq char (read-char-exclusive)))
5747 (if (equal char ?\ )
5748 (setq s "" move nil)
5749 (unless (assoc (char-to-string char) org-emphasis-alist)
5750 (user-error "No such emphasis marker: \"%c\"" char))
5751 (setq s (char-to-string char)))
5752 (while (and (> (length string) 1)
5753 (equal (substring string 0 1) (substring string -1))
5754 (assoc (substring string 0 1) org-emphasis-alist))
5755 (setq string (substring string 1 -1)))
5756 (setq string (concat s string s))
5757 (if beg (delete-region beg end))
5758 (unless (or (bolp)
5759 (string-match (concat "[" (nth 0 erc) "\n]")
5760 (char-to-string (char-before (point)))))
5761 (insert " "))
5762 (unless (or (eobp)
5763 (string-match (concat "[" (nth 1 erc) "\n]")
5764 (char-to-string (char-after (point)))))
5765 (insert " ") (backward-char 1))
5766 (insert string)
5767 (and move (backward-char 1))))
5768
5769 (defconst org-nonsticky-props
5770 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5771
5772 (defsubst org-rear-nonsticky-at (pos)
5773 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5774
5775 (defun org-activate-plain-links (limit)
5776 "Run through the buffer and add overlays to links."
5777 (let (f hl)
5778 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5779 (not (org-in-src-block-p)))
5780 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5781 (setq f (get-text-property (match-beginning 0) 'face))
5782 (setq hl (org-match-string-no-properties 0))
5783 (if (or (eq f 'org-tag)
5784 (and (listp f) (memq 'org-tag f)))
5785 nil
5786 (add-text-properties (match-beginning 0) (match-end 0)
5787 (list 'mouse-face 'highlight
5788 'face 'org-link
5789 'htmlize-link `(:uri ,hl)
5790 'keymap org-mouse-map))
5791 (org-rear-nonsticky-at (match-end 0)))
5792 t)))
5793
5794 (defun org-activate-code (limit)
5795 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5796 (progn
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (remove-text-properties (match-beginning 0) (match-end 0)
5799 '(display t invisible t intangible t))
5800 t)))
5801
5802 (defcustom org-src-fontify-natively nil
5803 "When non-nil, fontify code in code blocks."
5804 :type 'boolean
5805 :version "24.1"
5806 :group 'org-appearance
5807 :group 'org-babel)
5808
5809 (defcustom org-allow-promoting-top-level-subtree nil
5810 "When non-nil, allow promoting a top level subtree.
5811 The leading star of the top level headline will be replaced
5812 by a #."
5813 :type 'boolean
5814 :version "24.1"
5815 :group 'org-appearance)
5816
5817 (defun org-fontify-meta-lines-and-blocks (limit)
5818 (condition-case nil
5819 (org-fontify-meta-lines-and-blocks-1 limit)
5820 (error (message "org-mode fontification error"))))
5821
5822 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5823 "Fontify #+ lines and blocks."
5824 (let ((case-fold-search t))
5825 (if (re-search-forward
5826 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5827 limit t)
5828 (let ((beg (match-beginning 0))
5829 (block-start (match-end 0))
5830 (block-end nil)
5831 (lang (match-string 7))
5832 (beg1 (line-beginning-position 2))
5833 (dc1 (downcase (match-string 2)))
5834 (dc3 (downcase (match-string 3)))
5835 end end1 quoting block-type ovl)
5836 (cond
5837 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5838 ;; a single line of backend-specific content
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (remove-text-properties (match-beginning 0) (match-end 0)
5841 '(display t invisible t intangible t))
5842 (add-text-properties (match-beginning 1) (match-end 3)
5843 '(font-lock-fontified t face org-meta-line))
5844 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5845 '(font-lock-fontified t face org-block))
5846 ; for backend-specific code
5847 t)
5848 ((and (match-end 4) (equal dc3 "+begin"))
5849 ;; Truly a block
5850 (setq block-type (downcase (match-string 5))
5851 quoting (member block-type org-protecting-blocks))
5852 (when (re-search-forward
5853 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5854 nil t) ;; on purpose, we look further than LIMIT
5855 (setq end (min (point-max) (match-end 0))
5856 end1 (min (point-max) (1- (match-beginning 0))))
5857 (setq block-end (match-beginning 0))
5858 (when quoting
5859 (remove-text-properties beg end
5860 '(display t invisible t intangible t)))
5861 (add-text-properties
5862 beg end
5863 '(font-lock-fontified t font-lock-multiline t))
5864 (add-text-properties beg beg1 '(face org-meta-line))
5865 (add-text-properties end1 (min (point-max) (1+ end))
5866 '(face org-meta-line)) ; for end_src
5867 (cond
5868 ((and lang (not (string= lang "")) org-src-fontify-natively)
5869 (org-src-font-lock-fontify-block lang block-start block-end)
5870 ;; remove old background overlays
5871 (mapc (lambda (ov)
5872 (if (eq (overlay-get ov 'face) 'org-block-background)
5873 (delete-overlay ov)))
5874 (overlays-at (/ (+ beg1 block-end) 2)))
5875 ;; add a background overlay
5876 (setq ovl (make-overlay beg1 block-end))
5877 (overlay-put ovl 'face 'org-block-background)
5878 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5879 (quoting
5880 (add-text-properties beg1 (min (point-max) (1+ end1))
5881 '(face org-block))) ; end of source block
5882 ((not org-fontify-quote-and-verse-blocks))
5883 ((string= block-type "quote")
5884 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5885 ((string= block-type "verse")
5886 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5887 (add-text-properties beg beg1 '(face org-block-begin-line))
5888 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5889 '(face org-block-end-line))
5890 t))
5891 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5892 (add-text-properties
5893 beg (match-end 3)
5894 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5895 '(font-lock-fontified t invisible t)
5896 '(font-lock-fontified t face org-document-info-keyword)))
5897 (add-text-properties
5898 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5899 (if (string-equal dc1 "+title:")
5900 '(font-lock-fontified t face org-document-title)
5901 '(font-lock-fontified t face org-document-info))))
5902 ((or (equal dc1 "+results")
5903 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5904 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5905 "+call:" "+header:" "+headers:" "+name:"))
5906 (and (match-end 4) (equal dc3 "+attr")))
5907 (add-text-properties
5908 beg (match-end 0)
5909 '(font-lock-fontified t face org-meta-line))
5910 t)
5911 ((member dc3 '(" " ""))
5912 (add-text-properties
5913 beg (match-end 0)
5914 '(font-lock-fontified t face font-lock-comment-face)))
5915 ((not (member (char-after beg) '(?\ ?\t)))
5916 ;; just any other in-buffer setting, but not indented
5917 (add-text-properties
5918 beg (match-end 0)
5919 '(font-lock-fontified t face org-meta-line))
5920 t)
5921 (t nil))))))
5922
5923 (defun org-activate-angle-links (limit)
5924 "Run through the buffer and add overlays to links."
5925 (if (and (re-search-forward org-angle-link-re limit t)
5926 (not (org-in-src-block-p)))
5927 (progn
5928 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5929 (add-text-properties (match-beginning 0) (match-end 0)
5930 (list 'mouse-face 'highlight
5931 'keymap org-mouse-map))
5932 (org-rear-nonsticky-at (match-end 0))
5933 t)))
5934
5935 (defun org-activate-footnote-links (limit)
5936 "Run through the buffer and add overlays to footnotes."
5937 (let ((fn (org-footnote-next-reference-or-definition limit)))
5938 (when fn
5939 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5940 (org-remove-flyspell-overlays-in beg end)
5941 (add-text-properties beg end
5942 (list 'mouse-face 'highlight
5943 'keymap org-mouse-map
5944 'help-echo
5945 (if (= (point-at-bol) beg)
5946 "Footnote definition"
5947 "Footnote reference")
5948 'font-lock-fontified t
5949 'font-lock-multiline t
5950 'face 'org-footnote))))))
5951
5952 (defun org-activate-bracket-links (limit)
5953 "Run through the buffer and add overlays to bracketed links."
5954 (if (and (re-search-forward org-bracket-link-regexp limit t)
5955 (not (org-in-src-block-p)))
5956 (let* ((hl (org-match-string-no-properties 1))
5957 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5958 (ip (org-maybe-intangible
5959 (list 'invisible 'org-link
5960 'keymap org-mouse-map 'mouse-face 'highlight
5961 'font-lock-multiline t 'help-echo help
5962 'htmlize-link `(:uri ,hl))))
5963 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5964 'font-lock-multiline t 'help-echo help
5965 'htmlize-link `(:uri ,hl))))
5966 ;; We need to remove the invisible property here. Table narrowing
5967 ;; may have made some of this invisible.
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (remove-text-properties (match-beginning 0) (match-end 0)
5970 '(invisible nil))
5971 (if (match-end 3)
5972 (progn
5973 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5974 (org-rear-nonsticky-at (match-beginning 3))
5975 (add-text-properties (match-beginning 3) (match-end 3) vp)
5976 (org-rear-nonsticky-at (match-end 3))
5977 (add-text-properties (match-end 3) (match-end 0) ip)
5978 (org-rear-nonsticky-at (match-end 0)))
5979 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5980 (org-rear-nonsticky-at (match-beginning 1))
5981 (add-text-properties (match-beginning 1) (match-end 1) vp)
5982 (org-rear-nonsticky-at (match-end 1))
5983 (add-text-properties (match-end 1) (match-end 0) ip)
5984 (org-rear-nonsticky-at (match-end 0)))
5985 t)))
5986
5987 (defun org-activate-dates (limit)
5988 "Run through the buffer and add overlays to dates."
5989 (if (and (re-search-forward org-tsr-regexp-both limit t)
5990 (not (equal (char-before (match-beginning 0)) 91)))
5991 (progn
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5993 (add-text-properties (match-beginning 0) (match-end 0)
5994 (list 'mouse-face 'highlight
5995 'keymap org-mouse-map))
5996 (org-rear-nonsticky-at (match-end 0))
5997 (when org-display-custom-times
5998 (if (match-end 3)
5999 (org-display-custom-time (match-beginning 3) (match-end 3)))
6000 (org-display-custom-time (match-beginning 1) (match-end 1)))
6001 t)))
6002
6003 (defvar org-target-link-regexp nil
6004 "Regular expression matching radio targets in plain text.")
6005 (make-variable-buffer-local 'org-target-link-regexp)
6006 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6007 "Regular expression matching a link target.")
6008 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6009 "Regular expression matching a radio target.")
6010 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6011 "Regular expression matching any target.")
6012
6013 (defun org-activate-target-links (limit)
6014 "Run through the buffer and add overlays to target matches."
6015 (when org-target-link-regexp
6016 (let ((case-fold-search t))
6017 (if (re-search-forward org-target-link-regexp limit t)
6018 (progn
6019 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6020 (add-text-properties (match-beginning 0) (match-end 0)
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map
6023 'help-echo "Radio target link"
6024 'org-linked-text t))
6025 (org-rear-nonsticky-at (match-end 0))
6026 t)))))
6027
6028 (defun org-update-radio-target-regexp ()
6029 "Find all radio targets in this file and update the regular expression."
6030 (interactive)
6031 (when (memq 'radio org-activate-links)
6032 (setq org-target-link-regexp
6033 (org-make-target-link-regexp (org-all-targets 'radio)))
6034 (org-restart-font-lock)))
6035
6036 (defun org-hide-wide-columns (limit)
6037 (let (s e)
6038 (setq s (text-property-any (point) (or limit (point-max))
6039 'org-cwidth t))
6040 (when s
6041 (setq e (next-single-property-change s 'org-cwidth))
6042 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6043 (goto-char e)
6044 t)))
6045
6046 (defvar org-latex-and-related-regexp nil
6047 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6048 (defvar org-match-substring-regexp)
6049 (defvar org-match-substring-with-braces-regexp)
6050
6051 (defun org-compute-latex-and-related-regexp ()
6052 "Compute regular expression for LaTeX, entities and sub/superscript.
6053 Result depends on variable `org-highlight-latex-and-related'."
6054 (org-set-local
6055 'org-latex-and-related-regexp
6056 (let* ((re-sub
6057 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6058 ((eq org-use-sub-superscripts '{})
6059 (list org-match-substring-with-braces-regexp))
6060 (org-use-sub-superscripts (list org-match-substring-regexp))))
6061 (re-latex
6062 (when (memq 'latex org-highlight-latex-and-related)
6063 (let ((matchers (plist-get org-format-latex-options :matchers)))
6064 (delq nil
6065 (mapcar (lambda (x)
6066 (and (member (car x) matchers) (nth 1 x)))
6067 org-latex-regexps)))))
6068 (re-entities
6069 (when (memq 'entities org-highlight-latex-and-related)
6070 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6071 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6072
6073 (defun org-do-latex-and-related (limit)
6074 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6075 LIMIT bounds the search for syntax to highlight. Stop at first
6076 highlighted object, if any. Return t if some highlighting was
6077 done, nil otherwise."
6078 (when (org-string-nw-p org-latex-and-related-regexp)
6079 (catch 'found
6080 (while (re-search-forward org-latex-and-related-regexp limit t)
6081 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6082 'face))
6083 '(org-code org-verbatim underline))
6084 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6085 '(?_ ?^))
6086 1
6087 0)))
6088 (font-lock-prepend-text-property
6089 (+ offset (match-beginning 0)) (match-end 0)
6090 'face 'org-latex-and-related)
6091 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6092 '(font-lock-multiline t)))
6093 (throw 'found t)))
6094 nil)))
6095
6096 (defun org-restart-font-lock ()
6097 "Restart `font-lock-mode', to force refontification."
6098 (when (and (boundp 'font-lock-mode) font-lock-mode)
6099 (font-lock-mode -1)
6100 (font-lock-mode 1)))
6101
6102 (defun org-all-targets (&optional radio)
6103 "Return a list of all targets in this file.
6104 When optional argument RADIO is non-nil, only find radio
6105 targets."
6106 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6107 (save-excursion
6108 (goto-char (point-min))
6109 (while (re-search-forward re nil t)
6110 ;; Make sure point is really within the object.
6111 (backward-char)
6112 (let ((obj (org-element-context)))
6113 (when (memq (org-element-type obj) '(radio-target target))
6114 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6115 rtn)))
6116
6117 (defun org-make-target-link-regexp (targets)
6118 "Make regular expression matching all strings in TARGETS.
6119 The regular expression finds the targets also if there is a line break
6120 between words."
6121 (and targets
6122 (concat
6123 "\\_<\\("
6124 (mapconcat
6125 (lambda (x)
6126 (setq x (regexp-quote x))
6127 (while (string-match " +" x)
6128 (setq x (replace-match "\\s-+" t t x)))
6129 x)
6130 targets
6131 "\\|")
6132 "\\)\\_>")))
6133
6134 (defun org-activate-tags (limit)
6135 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6136 (progn
6137 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6138 (add-text-properties (match-beginning 1) (match-end 1)
6139 (list 'mouse-face 'highlight
6140 'keymap org-mouse-map))
6141 (org-rear-nonsticky-at (match-end 1))
6142 t)))
6143
6144 (defun org-outline-level ()
6145 "Compute the outline level of the heading at point.
6146 If this is called at a normal headline, the level is the number of stars.
6147 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6148 (save-excursion
6149 (if (not (condition-case nil
6150 (org-back-to-heading t)
6151 (error nil)))
6152 0
6153 (looking-at org-outline-regexp)
6154 (1- (- (match-end 0) (match-beginning 0))))))
6155
6156 (defvar org-font-lock-keywords nil)
6157
6158 (defsubst org-re-property (property &optional literal allow-null)
6159 "Return a regexp matching a PROPERTY line.
6160
6161 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6162 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6163 non-nil, match properties even without a value.
6164
6165 Match group 3 is set to the value when it exists. If there is no
6166 value and ALLOW-NULL is non-nil, it is set to the empty string."
6167 (concat
6168 "^\\(?4:[ \t]*\\)"
6169 (format "\\(?1::\\(?2:%s\\):\\)"
6170 (if literal property (regexp-quote property)))
6171 (if allow-null
6172 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6173 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6174
6175 (defconst org-property-re
6176 (org-re-property ".*?" 'literal t)
6177 "Regular expression matching a property line.
6178 There are four matching groups:
6179 1: :PROPKEY: including the leading and trailing colon,
6180 2: PROPKEY without the leading and trailing colon,
6181 3: PROPVAL without leading or trailing spaces,
6182 4: the indentation of the current line,
6183 5: trailing whitespace.")
6184
6185 (defvar org-font-lock-hook nil
6186 "Functions to be called for special font lock stuff.")
6187
6188 (defvar org-font-lock-set-keywords-hook nil
6189 "Functions that can manipulate `org-font-lock-extra-keywords'.
6190 This is called after `org-font-lock-extra-keywords' is defined, but before
6191 it is installed to be used by font lock. This can be useful if something
6192 needs to be inserted at a specific position in the font-lock sequence.")
6193
6194 (defun org-font-lock-hook (limit)
6195 "Run `org-font-lock-hook' within LIMIT."
6196 (run-hook-with-args 'org-font-lock-hook limit))
6197
6198 (defun org-set-font-lock-defaults ()
6199 "Set font lock defaults for the current buffer."
6200 (let* ((em org-fontify-emphasized-text)
6201 (lk org-activate-links)
6202 (org-font-lock-extra-keywords
6203 (list
6204 ;; Call the hook
6205 '(org-font-lock-hook)
6206 ;; Headlines
6207 `(,(if org-fontify-whole-heading-line
6208 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6209 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6210 (1 (org-get-level-face 1))
6211 (2 (org-get-level-face 2))
6212 (3 (org-get-level-face 3)))
6213 ;; Table lines
6214 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6215 (1 'org-table t))
6216 ;; Table internals
6217 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6218 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6219 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6220 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6221 ;; Drawers
6222 (list org-drawer-regexp '(0 'org-special-keyword t))
6223 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6224 ;; Properties
6225 (list org-property-re
6226 '(1 'org-special-keyword t)
6227 '(3 'org-property-value t))
6228 ;; Links
6229 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6230 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6231 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6232 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6233 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6234 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6235 (if (memq 'footnote lk) '(org-activate-footnote-links))
6236 ;; Targets.
6237 (list org-any-target-regexp '(0 'org-target t))
6238 ;; Diary sexps.
6239 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6240 ;; Macro
6241 '("{{{.+}}}" (0 'org-macro t))
6242 '(org-hide-wide-columns (0 nil append))
6243 ;; TODO keyword
6244 (list (format org-heading-keyword-regexp-format
6245 org-todo-regexp)
6246 '(2 (org-get-todo-face 2) t))
6247 ;; DONE
6248 (if org-fontify-done-headline
6249 (list (format org-heading-keyword-regexp-format
6250 (concat
6251 "\\(?:"
6252 (mapconcat 'regexp-quote org-done-keywords "\\|")
6253 "\\)"))
6254 '(2 'org-headline-done t))
6255 nil)
6256 ;; Priorities
6257 '(org-font-lock-add-priority-faces)
6258 ;; Tags
6259 '(org-font-lock-add-tag-faces)
6260 ;; Tags groups
6261 (if (and org-group-tags org-tag-groups-alist)
6262 (list (concat org-outline-regexp-bol ".+\\(:"
6263 (regexp-opt (mapcar 'car org-tag-groups-alist))
6264 ":\\).*$")
6265 '(1 'org-tag-group prepend)))
6266 ;; Special keywords
6267 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6268 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6269 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6270 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6271 ;; Emphasis
6272 (if em
6273 (if (featurep 'xemacs)
6274 '(org-do-emphasis-faces (0 nil append))
6275 '(org-do-emphasis-faces)))
6276 ;; Checkboxes
6277 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6278 1 'org-checkbox prepend)
6279 (if (cdr (assq 'checkbox org-list-automatic-rules))
6280 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6281 (0 (org-get-checkbox-statistics-face) t)))
6282 ;; Description list items
6283 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6284 1 'org-list-dt prepend)
6285 ;; ARCHIVEd headings
6286 (list (concat
6287 org-outline-regexp-bol
6288 "\\(.*:" org-archive-tag ":.*\\)")
6289 '(1 'org-archived prepend))
6290 ;; Specials
6291 '(org-do-latex-and-related)
6292 '(org-fontify-entities)
6293 '(org-raise-scripts)
6294 ;; Code
6295 '(org-activate-code (1 'org-code t))
6296 ;; COMMENT
6297 (list (format org-heading-keyword-regexp-format
6298 (concat "\\("
6299 org-comment-string "\\|" org-quote-string
6300 "\\)"))
6301 '(2 'org-special-keyword t))
6302 ;; Blocks and meta lines
6303 '(org-fontify-meta-lines-and-blocks))))
6304 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6305 (run-hooks 'org-font-lock-set-keywords-hook)
6306 ;; Now set the full font-lock-keywords
6307 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6308 (org-set-local 'font-lock-defaults
6309 '(org-font-lock-keywords t nil nil backward-paragraph))
6310 (kill-local-variable 'font-lock-keywords) nil))
6311
6312 (defun org-toggle-pretty-entities ()
6313 "Toggle the composition display of entities as UTF8 characters."
6314 (interactive)
6315 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6316 (org-restart-font-lock)
6317 (if org-pretty-entities
6318 (message "Entities are now displayed as UTF8 characters")
6319 (save-restriction
6320 (widen)
6321 (org-decompose-region (point-min) (point-max))
6322 (message "Entities are now displayed as plain text"))))
6323
6324 (defvar org-custom-properties-overlays nil
6325 "List of overlays used for custom properties.")
6326 (make-variable-buffer-local 'org-custom-properties-overlays)
6327
6328 (defun org-toggle-custom-properties-visibility ()
6329 "Display or hide properties in `org-custom-properties'."
6330 (interactive)
6331 (if org-custom-properties-overlays
6332 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6333 (setq org-custom-properties-overlays nil))
6334 (unless (not org-custom-properties)
6335 (save-excursion
6336 (save-restriction
6337 (widen)
6338 (goto-char (point-min))
6339 (while (re-search-forward org-property-re nil t)
6340 (mapc (lambda(p)
6341 (when (equal p (substring (match-string 1) 1 -1))
6342 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6343 (overlay-put o 'invisible t)
6344 (overlay-put o 'org-custom-property t)
6345 (push o org-custom-properties-overlays))))
6346 org-custom-properties)))))))
6347
6348 (defun org-fontify-entities (limit)
6349 "Find an entity to fontify."
6350 (let (ee)
6351 (when org-pretty-entities
6352 (catch 'match
6353 (while (re-search-forward
6354 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6355 limit t)
6356 (if (and (not (org-in-indented-comment-line))
6357 (setq ee (org-entity-get (match-string 1)))
6358 (= (length (nth 6 ee)) 1))
6359 (let*
6360 ((end (if (equal (match-string 2) "{}")
6361 (match-end 2)
6362 (match-end 1))))
6363 (add-text-properties
6364 (match-beginning 0) end
6365 (list 'font-lock-fontified t))
6366 (compose-region (match-beginning 0) end
6367 (nth 6 ee) nil)
6368 (backward-char 1)
6369 (throw 'match t))))
6370 nil))))
6371
6372 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6373 "Fontify string S like in Org-mode."
6374 (with-temp-buffer
6375 (insert s)
6376 (let ((org-odd-levels-only odd-levels))
6377 (org-mode)
6378 (org-font-lock-ensure)
6379 (buffer-string))))
6380
6381 (defvar org-m nil)
6382 (defvar org-l nil)
6383 (defvar org-f nil)
6384 (defun org-get-level-face (n)
6385 "Get the right face for match N in font-lock matching of headlines."
6386 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6387 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6388 (if org-cycle-level-faces
6389 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6390 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6391 (cond
6392 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6393 ((eq n 2) org-f)
6394 (t (if org-level-color-stars-only nil org-f))))
6395
6396
6397 (defun org-get-todo-face (kwd)
6398 "Get the right face for a TODO keyword KWD.
6399 If KWD is a number, get the corresponding match group."
6400 (if (numberp kwd) (setq kwd (match-string kwd)))
6401 (or (org-face-from-face-or-color
6402 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6403 (and (member kwd org-done-keywords) 'org-done)
6404 'org-todo))
6405
6406 (defun org-face-from-face-or-color (context inherit face-or-color)
6407 "Create a face list that inherits INHERIT, but sets the foreground color.
6408 When FACE-OR-COLOR is not a string, just return it."
6409 (if (stringp face-or-color)
6410 (list :inherit inherit
6411 (cdr (assoc context org-faces-easy-properties))
6412 face-or-color)
6413 face-or-color))
6414
6415 (defun org-font-lock-add-tag-faces (limit)
6416 "Add the special tag faces."
6417 (when (and org-tag-faces org-tags-special-faces-re)
6418 (while (re-search-forward org-tags-special-faces-re limit t)
6419 (add-text-properties (match-beginning 1) (match-end 1)
6420 (list 'face (org-get-tag-face 1)
6421 'font-lock-fontified t))
6422 (backward-char 1))))
6423
6424 (defun org-font-lock-add-priority-faces (limit)
6425 "Add the special priority faces."
6426 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6427 (when (save-match-data (org-at-heading-p))
6428 (add-text-properties
6429 (match-beginning 0) (match-end 0)
6430 (list 'face (or (org-face-from-face-or-color
6431 'priority 'org-priority
6432 (cdr (assoc (char-after (match-beginning 1))
6433 org-priority-faces)))
6434 'org-priority)
6435 'font-lock-fontified t)))))
6436
6437 (defun org-get-tag-face (kwd)
6438 "Get the right face for a TODO keyword KWD.
6439 If KWD is a number, get the corresponding match group."
6440 (if (numberp kwd) (setq kwd (match-string kwd)))
6441 (or (org-face-from-face-or-color
6442 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6443 'org-tag))
6444
6445 (defun org-unfontify-region (beg end &optional maybe_loudly)
6446 "Remove fontification and activation overlays from links."
6447 (font-lock-default-unfontify-region beg end)
6448 (let* ((buffer-undo-list t)
6449 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6450 (inhibit-modification-hooks t)
6451 deactivate-mark buffer-file-name buffer-file-truename)
6452 (org-decompose-region beg end)
6453 (remove-text-properties beg end
6454 '(mouse-face t keymap t org-linked-text t
6455 invisible t intangible t
6456 org-no-flyspell t org-emphasis t))
6457 (org-remove-font-lock-display-properties beg end)))
6458
6459 (defconst org-script-display '(((raise -0.3) (height 0.7))
6460 ((raise 0.3) (height 0.7))
6461 ((raise -0.5))
6462 ((raise 0.5)))
6463 "Display properties for showing superscripts and subscripts.")
6464
6465 (defun org-remove-font-lock-display-properties (beg end)
6466 "Remove specific display properties that have been added by font lock.
6467 The will remove the raise properties that are used to show superscripts
6468 and subscripts."
6469 (let (next prop)
6470 (while (< beg end)
6471 (setq next (next-single-property-change beg 'display nil end)
6472 prop (get-text-property beg 'display))
6473 (if (member prop org-script-display)
6474 (put-text-property beg next 'display nil))
6475 (setq beg next))))
6476
6477 (defun org-raise-scripts (limit)
6478 "Add raise properties to sub/superscripts."
6479 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6480 (if (re-search-forward
6481 (if (eq org-use-sub-superscripts t)
6482 org-match-substring-regexp
6483 org-match-substring-with-braces-regexp)
6484 limit t)
6485 (let* ((pos (point)) table-p comment-p
6486 (mpos (match-beginning 3))
6487 (emph-p (get-text-property mpos 'org-emphasis))
6488 (link-p (get-text-property mpos 'mouse-face))
6489 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6490 (goto-char (point-at-bol))
6491 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6492 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6493 (goto-char pos)
6494 ;; Handle a_b^c
6495 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6496 (if (or comment-p emph-p link-p keyw-p)
6497 t
6498 (put-text-property (match-beginning 3) (match-end 0)
6499 'display
6500 (if (equal (char-after (match-beginning 2)) ?^)
6501 (nth (if table-p 3 1) org-script-display)
6502 (nth (if table-p 2 0) org-script-display)))
6503 (add-text-properties (match-beginning 2) (match-end 2)
6504 (list 'invisible t
6505 'org-dwidth t 'org-dwidth-n 1))
6506 (if (and (eq (char-after (match-beginning 3)) ?{)
6507 (eq (char-before (match-end 3)) ?}))
6508 (progn
6509 (add-text-properties
6510 (match-beginning 3) (1+ (match-beginning 3))
6511 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6512 (add-text-properties
6513 (1- (match-end 3)) (match-end 3)
6514 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6515 t)))))
6516
6517 ;;;; Visibility cycling, including org-goto and indirect buffer
6518
6519 ;;; Cycling
6520
6521 (defvar org-cycle-global-status nil)
6522 (make-variable-buffer-local 'org-cycle-global-status)
6523 (put 'org-cycle-global-status 'org-state t)
6524 (defvar org-cycle-subtree-status nil)
6525 (make-variable-buffer-local 'org-cycle-subtree-status)
6526 (put 'org-cycle-subtree-status 'org-state t)
6527
6528 (defvar org-inlinetask-min-level)
6529
6530 (defun org-unlogged-message (&rest args)
6531 "Display a message, but avoid logging it in the *Messages* buffer."
6532 (let ((message-log-max nil))
6533 (apply 'message args)))
6534
6535 ;;;###autoload
6536 (defun org-cycle (&optional arg)
6537 "TAB-action and visibility cycling for Org-mode.
6538
6539 This is the command invoked in Org-mode by the TAB key. Its main purpose
6540 is outline visibility cycling, but it also invokes other actions
6541 in special contexts.
6542
6543 - When this function is called with a prefix argument, rotate the entire
6544 buffer through 3 states (global cycling)
6545 1. OVERVIEW: Show only top-level headlines.
6546 2. CONTENTS: Show all headlines of all levels, but no body text.
6547 3. SHOW ALL: Show everything.
6548 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6549 determined by the variable `org-startup-folded', and by any VISIBILITY
6550 properties in the buffer.
6551 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6552 including any drawers.
6553
6554 - When inside a table, re-align the table and move to the next field.
6555
6556 - When point is at the beginning of a headline, rotate the subtree started
6557 by this line through 3 different states (local cycling)
6558 1. FOLDED: Only the main headline is shown.
6559 2. CHILDREN: The main headline and the direct children are shown.
6560 From this state, you can move to one of the children
6561 and zoom in further.
6562 3. SUBTREE: Show the entire subtree, including body text.
6563 If there is no subtree, switch directly from CHILDREN to FOLDED.
6564
6565 - When point is at the beginning of an empty headline and the variable
6566 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6567 of the headline by demoting and promoting it to likely levels. This
6568 speeds up creation document structure by pressing TAB once or several
6569 times right after creating a new headline.
6570
6571 - When there is a numeric prefix, go up to a heading with level ARG, do
6572 a `show-subtree' and return to the previous cursor position. If ARG
6573 is negative, go up that many levels.
6574
6575 - When point is not at the beginning of a headline, execute the global
6576 binding for TAB, which is re-indenting the line. See the option
6577 `org-cycle-emulate-tab' for details.
6578
6579 - Special case: if point is at the beginning of the buffer and there is
6580 no headline in line 1, this function will act as if called with prefix arg
6581 (C-u TAB, same as S-TAB) also when called without prefix arg.
6582 But only if also the variable `org-cycle-global-at-bob' is t."
6583 (interactive "P")
6584 (org-load-modules-maybe)
6585 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6586 (and org-cycle-level-after-item/entry-creation
6587 (or (org-cycle-level)
6588 (org-cycle-item-indentation))))
6589 (let* ((limit-level
6590 (or org-cycle-max-level
6591 (and (boundp 'org-inlinetask-min-level)
6592 org-inlinetask-min-level
6593 (1- org-inlinetask-min-level))))
6594 (nstars (and limit-level
6595 (if org-odd-levels-only
6596 (and limit-level (1- (* limit-level 2)))
6597 limit-level)))
6598 (org-outline-regexp
6599 (if (not (derived-mode-p 'org-mode))
6600 outline-regexp
6601 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6602 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6603 (not (looking-at org-outline-regexp))))
6604 (org-cycle-hook
6605 (if bob-special
6606 (delq 'org-optimize-window-after-visibility-change
6607 (copy-sequence org-cycle-hook))
6608 org-cycle-hook))
6609 (pos (point)))
6610
6611 (if (or bob-special (equal arg '(4)))
6612 ;; special case: use global cycling
6613 (setq arg t))
6614
6615 (cond
6616
6617 ((equal arg '(16))
6618 (setq last-command 'dummy)
6619 (org-set-startup-visibility)
6620 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6621
6622 ((equal arg '(64))
6623 (show-all)
6624 (org-unlogged-message "Entire buffer visible, including drawers"))
6625
6626 ;; Try cdlatex TAB completion
6627 ((org-try-cdlatex-tab))
6628
6629 ;; Table: enter it or move to the next field.
6630 ((org-at-table-p 'any)
6631 (if (org-at-table.el-p)
6632 (message "%s" "Use C-c ' to edit table.el tables")
6633 (if arg (org-table-edit-field t)
6634 (org-table-justify-field-maybe)
6635 (call-interactively 'org-table-next-field))))
6636
6637 ((run-hook-with-args-until-success
6638 'org-tab-after-check-for-table-hook))
6639
6640 ;; Global cycling: delegate to `org-cycle-internal-global'.
6641 ((eq arg t) (org-cycle-internal-global))
6642
6643 ;; Drawers: delegate to `org-flag-drawer'.
6644 ((and org-drawers org-drawer-regexp
6645 (save-excursion
6646 (beginning-of-line 1)
6647 (looking-at org-drawer-regexp)))
6648 (org-flag-drawer ; toggle block visibility
6649 (not (get-char-property (match-end 0) 'invisible))))
6650
6651 ;; Show-subtree, ARG levels up from here.
6652 ((integerp arg)
6653 (save-excursion
6654 (org-back-to-heading)
6655 (outline-up-heading (if (< arg 0) (- arg)
6656 (- (funcall outline-level) arg)))
6657 (org-show-subtree)))
6658
6659 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6660 ((and (featurep 'org-inlinetask)
6661 (org-inlinetask-at-task-p)
6662 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6663 (org-inlinetask-toggle-visibility))
6664
6665 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6666 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6667 (save-excursion (beginning-of-line 1)
6668 (looking-at org-outline-regexp)))
6669 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6670 (org-cycle-internal-local))
6671
6672 ;; From there: TAB emulation and template completion.
6673 (buffer-read-only (org-back-to-heading))
6674
6675 ((run-hook-with-args-until-success
6676 'org-tab-after-check-for-cycling-hook))
6677
6678 ((org-try-structure-completion))
6679
6680 ((run-hook-with-args-until-success
6681 'org-tab-before-tab-emulation-hook))
6682
6683 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6684 (or (not (bolp))
6685 (not (looking-at org-outline-regexp))))
6686 (call-interactively (global-key-binding "\t")))
6687
6688 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6689 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6690 (or (and (eq org-cycle-emulate-tab 'white)
6691 (= (match-end 0) (point-at-eol)))
6692 (and (eq org-cycle-emulate-tab 'whitestart)
6693 (>= (match-end 0) pos))))
6694 t
6695 (eq org-cycle-emulate-tab t))
6696 (call-interactively (global-key-binding "\t")))
6697
6698 (t (save-excursion
6699 (org-back-to-heading)
6700 (org-cycle)))))))
6701
6702 (defun org-cycle-internal-global ()
6703 "Do the global cycling action."
6704 ;; Hack to avoid display of messages for .org attachments in Gnus
6705 (let ((ga (string-match "\\*fontification" (buffer-name))))
6706 (cond
6707 ((and (eq last-command this-command)
6708 (eq org-cycle-global-status 'overview))
6709 ;; We just created the overview - now do table of contents
6710 ;; This can be slow in very large buffers, so indicate action
6711 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6712 (unless ga (org-unlogged-message "CONTENTS..."))
6713 (org-content)
6714 (unless ga (org-unlogged-message "CONTENTS...done"))
6715 (setq org-cycle-global-status 'contents)
6716 (run-hook-with-args 'org-cycle-hook 'contents))
6717
6718 ((and (eq last-command this-command)
6719 (eq org-cycle-global-status 'contents))
6720 ;; We just showed the table of contents - now show everything
6721 (run-hook-with-args 'org-pre-cycle-hook 'all)
6722 (show-all)
6723 (unless ga (org-unlogged-message "SHOW ALL"))
6724 (setq org-cycle-global-status 'all)
6725 (run-hook-with-args 'org-cycle-hook 'all))
6726
6727 (t
6728 ;; Default action: go to overview
6729 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6730 (org-overview)
6731 (unless ga (org-unlogged-message "OVERVIEW"))
6732 (setq org-cycle-global-status 'overview)
6733 (run-hook-with-args 'org-cycle-hook 'overview)))))
6734
6735 (defvar org-called-with-limited-levels nil
6736 "Non-nil when `org-with-limited-levels' is currently active.")
6737
6738 (defun org-cycle-internal-local ()
6739 "Do the local cycling action."
6740 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6741 ;; First, determine end of headline (EOH), end of subtree or item
6742 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6743 (save-excursion
6744 (if (org-at-item-p)
6745 (progn
6746 (beginning-of-line)
6747 (setq struct (org-list-struct))
6748 (setq eoh (point-at-eol))
6749 (setq eos (org-list-get-item-end-before-blank (point) struct))
6750 (setq has-children (org-list-has-child-p (point) struct)))
6751 (org-back-to-heading)
6752 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6753 (setq eos (save-excursion (org-end-of-subtree t t)
6754 (when (bolp) (backward-char)) (point)))
6755 (setq has-children
6756 (or (save-excursion
6757 (let ((level (funcall outline-level)))
6758 (outline-next-heading)
6759 (and (org-at-heading-p t)
6760 (> (funcall outline-level) level))))
6761 (save-excursion
6762 (org-list-search-forward (org-item-beginning-re) eos t)))))
6763 ;; Determine end invisible part of buffer (EOL)
6764 (beginning-of-line 2)
6765 ;; XEmacs doesn't have `next-single-char-property-change'
6766 (if (featurep 'xemacs)
6767 (while (and (not (eobp)) ;; this is like `next-line'
6768 (get-char-property (1- (point)) 'invisible))
6769 (beginning-of-line 2))
6770 (while (and (not (eobp)) ;; this is like `next-line'
6771 (get-char-property (1- (point)) 'invisible))
6772 (goto-char (next-single-char-property-change (point) 'invisible))
6773 (and (eolp) (beginning-of-line 2))))
6774 (setq eol (point)))
6775 ;; Find out what to do next and set `this-command'
6776 (cond
6777 ((= eos eoh)
6778 ;; Nothing is hidden behind this heading
6779 (unless (org-before-first-heading-p)
6780 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6781 (org-unlogged-message "EMPTY ENTRY")
6782 (setq org-cycle-subtree-status nil)
6783 (save-excursion
6784 (goto-char eos)
6785 (outline-next-heading)
6786 (if (outline-invisible-p) (org-flag-heading nil))))
6787 ((and (or (>= eol eos)
6788 (not (string-match "\\S-" (buffer-substring eol eos))))
6789 (or has-children
6790 (not (setq children-skipped
6791 org-cycle-skip-children-state-if-no-children))))
6792 ;; Entire subtree is hidden in one line: children view
6793 (unless (org-before-first-heading-p)
6794 (run-hook-with-args 'org-pre-cycle-hook 'children))
6795 (if (org-at-item-p)
6796 (org-list-set-item-visibility (point-at-bol) struct 'children)
6797 (org-show-entry)
6798 (org-with-limited-levels (show-children))
6799 ;; FIXME: This slows down the func way too much.
6800 ;; How keep drawers hidden in subtree anyway?
6801 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6802 ;; (org-cycle-hide-drawers 'subtree))
6803
6804 ;; Fold every list in subtree to top-level items.
6805 (when (eq org-cycle-include-plain-lists 'integrate)
6806 (save-excursion
6807 (org-back-to-heading)
6808 (while (org-list-search-forward (org-item-beginning-re) eos t)
6809 (beginning-of-line 1)
6810 (let* ((struct (org-list-struct))
6811 (prevs (org-list-prevs-alist struct))
6812 (end (org-list-get-bottom-point struct)))
6813 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6814 (org-list-get-all-items (point) struct prevs))
6815 (goto-char (if (< end eos) end eos)))))))
6816 (org-unlogged-message "CHILDREN")
6817 (save-excursion
6818 (goto-char eos)
6819 (outline-next-heading)
6820 (if (outline-invisible-p) (org-flag-heading nil)))
6821 (setq org-cycle-subtree-status 'children)
6822 (unless (org-before-first-heading-p)
6823 (run-hook-with-args 'org-cycle-hook 'children)))
6824 ((or children-skipped
6825 (and (eq last-command this-command)
6826 (eq org-cycle-subtree-status 'children)))
6827 ;; We just showed the children, or no children are there,
6828 ;; now show everything.
6829 (unless (org-before-first-heading-p)
6830 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6831 (outline-flag-region eoh eos nil)
6832 (org-unlogged-message
6833 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6834 (setq org-cycle-subtree-status 'subtree)
6835 (unless (org-before-first-heading-p)
6836 (run-hook-with-args 'org-cycle-hook 'subtree)))
6837 (t
6838 ;; Default action: hide the subtree.
6839 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6840 (outline-flag-region eoh eos t)
6841 (org-unlogged-message "FOLDED")
6842 (setq org-cycle-subtree-status 'folded)
6843 (unless (org-before-first-heading-p)
6844 (run-hook-with-args 'org-cycle-hook 'folded))))))
6845
6846 ;;;###autoload
6847 (defun org-global-cycle (&optional arg)
6848 "Cycle the global visibility. For details see `org-cycle'.
6849 With \\[universal-argument] prefix arg, switch to startup visibility.
6850 With a numeric prefix, show all headlines up to that level."
6851 (interactive "P")
6852 (let ((org-cycle-include-plain-lists
6853 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6854 (cond
6855 ((integerp arg)
6856 (show-all)
6857 (hide-sublevels arg)
6858 (setq org-cycle-global-status 'contents))
6859 ((equal arg '(4))
6860 (org-set-startup-visibility)
6861 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6862 (t
6863 (org-cycle '(4))))))
6864
6865 (defun org-set-startup-visibility ()
6866 "Set the visibility required by startup options and properties."
6867 (cond
6868 ((eq org-startup-folded t)
6869 (org-overview))
6870 ((eq org-startup-folded 'content)
6871 (org-content))
6872 ((or (eq org-startup-folded 'showeverything)
6873 (eq org-startup-folded nil))
6874 (show-all)))
6875 (unless (eq org-startup-folded 'showeverything)
6876 (if org-hide-block-startup (org-hide-block-all))
6877 (org-set-visibility-according-to-property 'no-cleanup)
6878 (org-cycle-hide-archived-subtrees 'all)
6879 (org-cycle-hide-drawers 'all)
6880 (org-cycle-show-empty-lines t)))
6881
6882 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6883 "Switch subtree visibilities according to :VISIBILITY: property."
6884 (interactive)
6885 (let (org-show-entry-below state)
6886 (save-excursion
6887 (goto-char (point-min))
6888 (while (re-search-forward
6889 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6890 nil t)
6891 (setq state (match-string 1))
6892 (save-excursion
6893 (org-back-to-heading t)
6894 (hide-subtree)
6895 (org-reveal)
6896 (cond
6897 ((equal state '("fold" "folded"))
6898 (hide-subtree))
6899 ((equal state "children")
6900 (org-show-hidden-entry)
6901 (show-children))
6902 ((equal state "content")
6903 (save-excursion
6904 (save-restriction
6905 (org-narrow-to-subtree)
6906 (org-content))))
6907 ((member state '("all" "showall"))
6908 (show-subtree)))))
6909 (unless no-cleanup
6910 (org-cycle-hide-archived-subtrees 'all)
6911 (org-cycle-hide-drawers 'all)
6912 (org-cycle-show-empty-lines 'all)))))
6913
6914 ;; This function uses outline-regexp instead of the more fundamental
6915 ;; org-outline-regexp so that org-cycle-global works outside of Org
6916 ;; buffers, where outline-regexp is needed.
6917 (defun org-overview ()
6918 "Switch to overview mode, showing only top-level headlines.
6919 This shows all headlines with a level equal or greater than the level
6920 of the first headline in the buffer. This is important, because if the
6921 first headline is not level one, then (hide-sublevels 1) gives confusing
6922 results."
6923 (interactive)
6924 (save-excursion
6925 (let ((level
6926 (save-excursion
6927 (goto-char (point-min))
6928 (if (re-search-forward (concat "^" outline-regexp) nil t)
6929 (progn
6930 (goto-char (match-beginning 0))
6931 (funcall outline-level))))))
6932 (and level (hide-sublevels level)))))
6933
6934 (defun org-content (&optional arg)
6935 "Show all headlines in the buffer, like a table of contents.
6936 With numerical argument N, show content up to level N."
6937 (interactive "P")
6938 (org-overview)
6939 (save-excursion
6940 ;; Visit all headings and show their offspring
6941 (and (integerp arg) (org-overview))
6942 (goto-char (point-max))
6943 (catch 'exit
6944 (while (and (progn (condition-case nil
6945 (outline-previous-visible-heading 1)
6946 (error (goto-char (point-min))))
6947 t)
6948 (looking-at org-outline-regexp))
6949 (if (integerp arg)
6950 (show-children (1- arg))
6951 (show-branches))
6952 (if (bobp) (throw 'exit nil))))))
6953
6954 (defun org-optimize-window-after-visibility-change (state)
6955 "Adjust the window after a change in outline visibility.
6956 This function is the default value of the hook `org-cycle-hook'."
6957 (when (get-buffer-window (current-buffer))
6958 (cond
6959 ((eq state 'content) nil)
6960 ((eq state 'all) nil)
6961 ((eq state 'folded) nil)
6962 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6963 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6964
6965 (defun org-remove-empty-overlays-at (pos)
6966 "Remove outline overlays that do not contain non-white stuff."
6967 (mapc
6968 (lambda (o)
6969 (and (eq 'outline (overlay-get o 'invisible))
6970 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6971 (overlay-end o))))
6972 (delete-overlay o)))
6973 (overlays-at pos)))
6974
6975 (defun org-clean-visibility-after-subtree-move ()
6976 "Fix visibility issues after moving a subtree."
6977 ;; First, find a reasonable region to look at:
6978 ;; Start two siblings above, end three below
6979 (let* ((beg (save-excursion
6980 (and (org-get-last-sibling)
6981 (org-get-last-sibling))
6982 (point)))
6983 (end (save-excursion
6984 (and (org-get-next-sibling)
6985 (org-get-next-sibling)
6986 (org-get-next-sibling))
6987 (if (org-at-heading-p)
6988 (point-at-eol)
6989 (point))))
6990 (level (looking-at "\\*+"))
6991 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6992 (save-excursion
6993 (save-restriction
6994 (narrow-to-region beg end)
6995 (when re
6996 ;; Properly fold already folded siblings
6997 (goto-char (point-min))
6998 (while (re-search-forward re nil t)
6999 (if (and (not (outline-invisible-p))
7000 (save-excursion
7001 (goto-char (point-at-eol)) (outline-invisible-p)))
7002 (hide-entry))))
7003 (org-cycle-show-empty-lines 'overview)
7004 (org-cycle-hide-drawers 'overview)))))
7005
7006 (defun org-cycle-show-empty-lines (state)
7007 "Show empty lines above all visible headlines.
7008 The region to be covered depends on STATE when called through
7009 `org-cycle-hook'. Lisp program can use t for STATE to get the
7010 entire buffer covered. Note that an empty line is only shown if there
7011 are at least `org-cycle-separator-lines' empty lines before the headline."
7012 (when (not (= org-cycle-separator-lines 0))
7013 (save-excursion
7014 (let* ((n (abs org-cycle-separator-lines))
7015 (re (cond
7016 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7017 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7018 (t (let ((ns (number-to-string (- n 2))))
7019 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7020 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7021 beg end b e)
7022 (cond
7023 ((memq state '(overview contents t))
7024 (setq beg (point-min) end (point-max)))
7025 ((memq state '(children folded))
7026 (setq beg (point) end (progn (org-end-of-subtree t t)
7027 (beginning-of-line 2)
7028 (point)))))
7029 (when beg
7030 (goto-char beg)
7031 (while (re-search-forward re end t)
7032 (unless (get-char-property (match-end 1) 'invisible)
7033 (setq e (match-end 1))
7034 (if (< org-cycle-separator-lines 0)
7035 (setq b (save-excursion
7036 (goto-char (match-beginning 0))
7037 (org-back-over-empty-lines)
7038 (if (save-excursion
7039 (goto-char (max (point-min) (1- (point))))
7040 (org-at-heading-p))
7041 (1- (point))
7042 (point))))
7043 (setq b (match-beginning 1)))
7044 (outline-flag-region b e nil)))))))
7045 ;; Never hide empty lines at the end of the file.
7046 (save-excursion
7047 (goto-char (point-max))
7048 (outline-previous-heading)
7049 (outline-end-of-heading)
7050 (if (and (looking-at "[ \t\n]+")
7051 (= (match-end 0) (point-max)))
7052 (outline-flag-region (point) (match-end 0) nil))))
7053
7054 (defun org-show-empty-lines-in-parent ()
7055 "Move to the parent and re-show empty lines before visible headlines."
7056 (save-excursion
7057 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7058 (org-cycle-show-empty-lines context))))
7059
7060 (defun org-files-list ()
7061 "Return `org-agenda-files' list, plus all open org-mode files.
7062 This is useful for operations that need to scan all of a user's
7063 open and agenda-wise Org files."
7064 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7065 (dolist (buf (buffer-list))
7066 (with-current-buffer buf
7067 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7068 (let ((file (expand-file-name (buffer-file-name))))
7069 (unless (member file files)
7070 (push file files))))))
7071 files))
7072
7073 (defsubst org-entry-beginning-position ()
7074 "Return the beginning position of the current entry."
7075 (save-excursion (outline-back-to-heading t) (point)))
7076
7077 (defsubst org-entry-end-position ()
7078 "Return the end position of the current entry."
7079 (save-excursion (outline-next-heading) (point)))
7080
7081 (defun org-cycle-hide-drawers (state)
7082 "Re-hide all drawers after a visibility state change."
7083 (when (and (derived-mode-p 'org-mode)
7084 (not (memq state '(overview folded contents))))
7085 (save-excursion
7086 (let* ((globalp (memq state '(contents all)))
7087 (beg (if globalp (point-min) (point)))
7088 (end (if globalp (point-max)
7089 (if (eq state 'children)
7090 (save-excursion (outline-next-heading) (point))
7091 (org-end-of-subtree t)))))
7092 (goto-char beg)
7093 (while (re-search-forward org-drawer-regexp end t)
7094 (org-flag-drawer t))))))
7095
7096 (defun org-cycle-hide-inline-tasks (state)
7097 "Re-hide inline tasks when switching to `contents' or `children'
7098 visibility state."
7099 (case state
7100 (contents
7101 (when (org-bound-and-true-p org-inlinetask-min-level)
7102 (hide-sublevels (1- org-inlinetask-min-level))))
7103 (children
7104 (when (featurep 'org-inlinetask)
7105 (save-excursion
7106 (while (and (outline-next-heading)
7107 (org-inlinetask-at-task-p))
7108 (org-inlinetask-toggle-visibility)
7109 (org-inlinetask-goto-end)))))))
7110
7111 (defun org-flag-drawer (flag)
7112 "When FLAG is non-nil, hide the drawer we are within.
7113 Otherwise make it visible."
7114 (save-excursion
7115 (beginning-of-line 1)
7116 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7117 (let ((b (match-end 0)))
7118 (if (re-search-forward
7119 "^[ \t]*:END:"
7120 (save-excursion (outline-next-heading) (point)) t)
7121 (outline-flag-region b (point-at-eol) flag)
7122 (user-error ":END: line missing at position %s" b))))))
7123
7124 (defun org-subtree-end-visible-p ()
7125 "Is the end of the current subtree visible?"
7126 (pos-visible-in-window-p
7127 (save-excursion (org-end-of-subtree t) (point))))
7128
7129 (defun org-first-headline-recenter ()
7130 "Move cursor to the first headline and recenter the headline."
7131 (goto-char (point-min))
7132 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7133 (set-window-start (selected-window) (point-at-bol))))
7134
7135 ;;; Saving and restoring visibility
7136
7137 (defun org-outline-overlay-data (&optional use-markers)
7138 "Return a list of the locations of all outline overlays.
7139 These are overlays with the `invisible' property value `outline'.
7140 The return value is a list of cons cells, with start and stop
7141 positions for each overlay.
7142 If USE-MARKERS is set, return the positions as markers."
7143 (let (beg end)
7144 (save-excursion
7145 (save-restriction
7146 (widen)
7147 (delq nil
7148 (mapcar (lambda (o)
7149 (when (eq (overlay-get o 'invisible) 'outline)
7150 (setq beg (overlay-start o)
7151 end (overlay-end o))
7152 (and beg end (> end beg)
7153 (if use-markers
7154 (cons (move-marker (make-marker) beg)
7155 (move-marker (make-marker) end))
7156 (cons beg end)))))
7157 (overlays-in (point-min) (point-max))))))))
7158
7159 (defun org-set-outline-overlay-data (data)
7160 "Create visibility overlays for all positions in DATA.
7161 DATA should have been made by `org-outline-overlay-data'."
7162 (let (o)
7163 (save-excursion
7164 (save-restriction
7165 (widen)
7166 (show-all)
7167 (mapc (lambda (c)
7168 (outline-flag-region (car c) (cdr c) t))
7169 data)))))
7170
7171 ;;; Folding of blocks
7172
7173 (defvar org-hide-block-overlays nil
7174 "Overlays hiding blocks.")
7175 (make-variable-buffer-local 'org-hide-block-overlays)
7176
7177 (defun org-block-map (function &optional start end)
7178 "Call FUNCTION at the head of all source blocks in the current buffer.
7179 Optional arguments START and END can be used to limit the range."
7180 (let ((start (or start (point-min)))
7181 (end (or end (point-max))))
7182 (save-excursion
7183 (goto-char start)
7184 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7185 (save-excursion
7186 (save-match-data
7187 (goto-char (match-beginning 0))
7188 (funcall function)))))))
7189
7190 (defun org-hide-block-toggle-all ()
7191 "Toggle the visibility of all blocks in the current buffer."
7192 (org-block-map #'org-hide-block-toggle))
7193
7194 (defun org-hide-block-all ()
7195 "Fold all blocks in the current buffer."
7196 (interactive)
7197 (org-show-block-all)
7198 (org-block-map #'org-hide-block-toggle-maybe))
7199
7200 (defun org-show-block-all ()
7201 "Unfold all blocks in the current buffer."
7202 (interactive)
7203 (mapc 'delete-overlay org-hide-block-overlays)
7204 (setq org-hide-block-overlays nil))
7205
7206 (defun org-hide-block-toggle-maybe ()
7207 "Toggle visibility of block at point."
7208 (interactive)
7209 (let ((case-fold-search t))
7210 (if (save-excursion
7211 (beginning-of-line 1)
7212 (looking-at org-block-regexp))
7213 (progn (org-hide-block-toggle)
7214 t) ;; to signal that we took action
7215 nil))) ;; to signal that we did not
7216
7217 (defun org-hide-block-toggle (&optional force)
7218 "Toggle the visibility of the current block."
7219 (interactive)
7220 (save-excursion
7221 (beginning-of-line)
7222 (if (re-search-forward org-block-regexp nil t)
7223 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7224 (end (match-end 0)) ;; end of entire body
7225 ov)
7226 (if (memq t (mapcar (lambda (overlay)
7227 (eq (overlay-get overlay 'invisible)
7228 'org-hide-block))
7229 (overlays-at start)))
7230 (if (or (not force) (eq force 'off))
7231 (mapc (lambda (ov)
7232 (when (member ov org-hide-block-overlays)
7233 (setq org-hide-block-overlays
7234 (delq ov org-hide-block-overlays)))
7235 (when (eq (overlay-get ov 'invisible)
7236 'org-hide-block)
7237 (delete-overlay ov)))
7238 (overlays-at start)))
7239 (setq ov (make-overlay start end))
7240 (overlay-put ov 'invisible 'org-hide-block)
7241 ;; make the block accessible to isearch
7242 (overlay-put
7243 ov 'isearch-open-invisible
7244 (lambda (ov)
7245 (when (member ov org-hide-block-overlays)
7246 (setq org-hide-block-overlays
7247 (delq ov org-hide-block-overlays)))
7248 (when (eq (overlay-get ov 'invisible)
7249 'org-hide-block)
7250 (delete-overlay ov))))
7251 (push ov org-hide-block-overlays)))
7252 (user-error "Not looking at a source block"))))
7253
7254 ;; org-tab-after-check-for-cycling-hook
7255 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7256 ;; Remove overlays when changing major mode
7257 (add-hook 'org-mode-hook
7258 (lambda () (org-add-hook 'change-major-mode-hook
7259 'org-show-block-all 'append 'local)))
7260
7261 ;;; Org-goto
7262
7263 (defvar org-goto-window-configuration nil)
7264 (defvar org-goto-marker nil)
7265 (defvar org-goto-map)
7266 (defun org-goto-map ()
7267 "Set the keymap `org-goto'."
7268 (setq org-goto-map
7269 (let ((map (make-sparse-keymap)))
7270 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7271 mouse-drag-region universal-argument org-occur)))
7272 (dolist (cmd cmds)
7273 (substitute-key-definition cmd cmd map global-map)))
7274 (suppress-keymap map)
7275 (org-defkey map "\C-m" 'org-goto-ret)
7276 (org-defkey map [(return)] 'org-goto-ret)
7277 (org-defkey map [(left)] 'org-goto-left)
7278 (org-defkey map [(right)] 'org-goto-right)
7279 (org-defkey map [(control ?g)] 'org-goto-quit)
7280 (org-defkey map "\C-i" 'org-cycle)
7281 (org-defkey map [(tab)] 'org-cycle)
7282 (org-defkey map [(down)] 'outline-next-visible-heading)
7283 (org-defkey map [(up)] 'outline-previous-visible-heading)
7284 (if org-goto-auto-isearch
7285 (if (fboundp 'define-key-after)
7286 (define-key-after map [t] 'org-goto-local-auto-isearch)
7287 nil)
7288 (org-defkey map "q" 'org-goto-quit)
7289 (org-defkey map "n" 'outline-next-visible-heading)
7290 (org-defkey map "p" 'outline-previous-visible-heading)
7291 (org-defkey map "f" 'outline-forward-same-level)
7292 (org-defkey map "b" 'outline-backward-same-level)
7293 (org-defkey map "u" 'outline-up-heading))
7294 (org-defkey map "/" 'org-occur)
7295 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7296 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7297 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7298 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7299 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7300 map)))
7301
7302 (defconst org-goto-help
7303 "Browse buffer copy, to find location or copy text.%s
7304 RET=jump to location C-g=quit and return to previous location
7305 [Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7306
7307 (defvar org-goto-start-pos) ; dynamically scoped parameter
7308
7309 (defun org-goto (&optional alternative-interface)
7310 "Look up a different location in the current file, keeping current visibility.
7311
7312 When you want look-up or go to a different location in a
7313 document, the fastest way is often to fold the entire buffer and
7314 then dive into the tree. This method has the disadvantage, that
7315 the previous location will be folded, which may not be what you
7316 want.
7317
7318 This command works around this by showing a copy of the current
7319 buffer in an indirect buffer, in overview mode. You can dive
7320 into the tree in that copy, use org-occur and incremental search
7321 to find a location. When pressing RET or `Q', the command
7322 returns to the original buffer in which the visibility is still
7323 unchanged. After RET it will also jump to the location selected
7324 in the indirect buffer and expose the headline hierarchy above.
7325
7326 With a prefix argument, use the alternative interface: e.g., if
7327 `org-goto-interface' is `outline' use `outline-path-completion'."
7328 (interactive "P")
7329 (org-goto-map)
7330 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7331 (org-refile-use-outline-path t)
7332 (org-refile-target-verify-function nil)
7333 (interface
7334 (if (not alternative-interface)
7335 org-goto-interface
7336 (if (eq org-goto-interface 'outline)
7337 'outline-path-completion
7338 'outline)))
7339 (org-goto-start-pos (point))
7340 (selected-point
7341 (if (eq interface 'outline)
7342 (car (org-get-location (current-buffer) org-goto-help))
7343 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7344 (org-refile-check-position pa)
7345 (nth 3 pa)))))
7346 (if selected-point
7347 (progn
7348 (org-mark-ring-push org-goto-start-pos)
7349 (goto-char selected-point)
7350 (if (or (outline-invisible-p) (org-invisible-p2))
7351 (org-show-context 'org-goto)))
7352 (message "Quit"))))
7353
7354 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7355 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7356 (defvar org-goto-local-auto-isearch-map) ; defined below
7357
7358 (defun org-get-location (buf help)
7359 "Let the user select a location in the Org-mode buffer BUF.
7360 This function uses a recursive edit. It returns the selected position
7361 or nil."
7362 (org-no-popups
7363 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7364 (isearch-hide-immediately nil)
7365 (isearch-search-fun-function
7366 (lambda () 'org-goto-local-search-headings))
7367 (org-goto-selected-point org-goto-exit-command))
7368 (save-excursion
7369 (save-window-excursion
7370 (delete-other-windows)
7371 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7372 (org-pop-to-buffer-same-window
7373 (condition-case nil
7374 (make-indirect-buffer (current-buffer) "*org-goto*")
7375 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7376 (with-output-to-temp-buffer "*Org Help*"
7377 (princ (format help (if org-goto-auto-isearch
7378 " Just type for auto-isearch."
7379 " n/p/f/b/u to navigate, q to quit."))))
7380 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7381 (setq buffer-read-only nil)
7382 (let ((org-startup-truncated t)
7383 (org-startup-folded nil)
7384 (org-startup-align-all-tables nil))
7385 (org-mode)
7386 (org-overview))
7387 (setq buffer-read-only t)
7388 (if (and (boundp 'org-goto-start-pos)
7389 (integer-or-marker-p org-goto-start-pos))
7390 (let ((org-show-hierarchy-above t)
7391 (org-show-siblings t)
7392 (org-show-following-heading t))
7393 (goto-char org-goto-start-pos)
7394 (and (outline-invisible-p) (org-show-context)))
7395 (goto-char (point-min)))
7396 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7397 (message "Select location and press RET")
7398 (use-local-map org-goto-map)
7399 (recursive-edit)))
7400 (kill-buffer "*org-goto*")
7401 (cons org-goto-selected-point org-goto-exit-command))))
7402
7403 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7404 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7405 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7406 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7407
7408 (defun org-goto-local-search-headings (string bound noerror)
7409 "Search and make sure that any matches are in headlines."
7410 (catch 'return
7411 (while (if isearch-forward
7412 (search-forward string bound noerror)
7413 (search-backward string bound noerror))
7414 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7415 (and (member :headline context)
7416 (not (member :tags context))))
7417 (throw 'return (point))))))
7418
7419 (defun org-goto-local-auto-isearch ()
7420 "Start isearch."
7421 (interactive)
7422 (goto-char (point-min))
7423 (let ((keys (this-command-keys)))
7424 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7425 (isearch-mode t)
7426 (isearch-process-search-char (string-to-char keys)))))
7427
7428 (defun org-goto-ret (&optional arg)
7429 "Finish `org-goto' by going to the new location."
7430 (interactive "P")
7431 (setq org-goto-selected-point (point)
7432 org-goto-exit-command 'return)
7433 (throw 'exit nil))
7434
7435 (defun org-goto-left ()
7436 "Finish `org-goto' by going to the new location."
7437 (interactive)
7438 (if (org-at-heading-p)
7439 (progn
7440 (beginning-of-line 1)
7441 (setq org-goto-selected-point (point)
7442 org-goto-exit-command 'left)
7443 (throw 'exit nil))
7444 (user-error "Not on a heading")))
7445
7446 (defun org-goto-right ()
7447 "Finish `org-goto' by going to the new location."
7448 (interactive)
7449 (if (org-at-heading-p)
7450 (progn
7451 (setq org-goto-selected-point (point)
7452 org-goto-exit-command 'right)
7453 (throw 'exit nil))
7454 (user-error "Not on a heading")))
7455
7456 (defun org-goto-quit ()
7457 "Finish `org-goto' without cursor motion."
7458 (interactive)
7459 (setq org-goto-selected-point nil)
7460 (setq org-goto-exit-command 'quit)
7461 (throw 'exit nil))
7462
7463 ;;; Indirect buffer display of subtrees
7464
7465 (defvar org-indirect-dedicated-frame nil
7466 "This is the frame being used for indirect tree display.")
7467 (defvar org-last-indirect-buffer nil)
7468
7469 (defun org-tree-to-indirect-buffer (&optional arg)
7470 "Create indirect buffer and narrow it to current subtree.
7471 With a numerical prefix ARG, go up to this level and then take that tree.
7472 If ARG is negative, go up that many levels.
7473
7474 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7475 indirect buffer previously made with this command, to avoid proliferation of
7476 indirect buffers. However, when you call the command with a \
7477 \\[universal-argument] prefix, or
7478 when `org-indirect-buffer-display' is `new-frame', the last buffer
7479 is kept so that you can work with several indirect buffers at the same time.
7480 If `org-indirect-buffer-display' is `dedicated-frame', the \
7481 \\[universal-argument] prefix also
7482 requests that a new frame be made for the new buffer, so that the dedicated
7483 frame is not changed."
7484 (interactive "P")
7485 (let ((cbuf (current-buffer))
7486 (cwin (selected-window))
7487 (pos (point))
7488 beg end level heading ibuf)
7489 (save-excursion
7490 (org-back-to-heading t)
7491 (when (numberp arg)
7492 (setq level (org-outline-level))
7493 (if (< arg 0) (setq arg (+ level arg)))
7494 (while (> (setq level (org-outline-level)) arg)
7495 (org-up-heading-safe)))
7496 (setq beg (point)
7497 heading (org-get-heading))
7498 (org-end-of-subtree t t)
7499 (if (org-at-heading-p) (backward-char 1))
7500 (setq end (point)))
7501 (if (and (buffer-live-p org-last-indirect-buffer)
7502 (not (eq org-indirect-buffer-display 'new-frame))
7503 (not arg))
7504 (kill-buffer org-last-indirect-buffer))
7505 (setq ibuf (org-get-indirect-buffer cbuf)
7506 org-last-indirect-buffer ibuf)
7507 (cond
7508 ((or (eq org-indirect-buffer-display 'new-frame)
7509 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7510 (select-frame (make-frame))
7511 (delete-other-windows)
7512 (org-pop-to-buffer-same-window ibuf)
7513 (org-set-frame-title heading))
7514 ((eq org-indirect-buffer-display 'dedicated-frame)
7515 (raise-frame
7516 (select-frame (or (and org-indirect-dedicated-frame
7517 (frame-live-p org-indirect-dedicated-frame)
7518 org-indirect-dedicated-frame)
7519 (setq org-indirect-dedicated-frame (make-frame)))))
7520 (delete-other-windows)
7521 (org-pop-to-buffer-same-window ibuf)
7522 (org-set-frame-title (concat "Indirect: " heading)))
7523 ((eq org-indirect-buffer-display 'current-window)
7524 (org-pop-to-buffer-same-window ibuf))
7525 ((eq org-indirect-buffer-display 'other-window)
7526 (pop-to-buffer ibuf))
7527 (t (error "Invalid value")))
7528 (if (featurep 'xemacs)
7529 (save-excursion (org-mode) (turn-on-font-lock)))
7530 (narrow-to-region beg end)
7531 (show-all)
7532 (goto-char pos)
7533 (run-hook-with-args 'org-cycle-hook 'all)
7534 (and (window-live-p cwin) (select-window cwin))))
7535
7536 (defun org-get-indirect-buffer (&optional buffer)
7537 (setq buffer (or buffer (current-buffer)))
7538 (let ((n 1) (base (buffer-name buffer)) bname)
7539 (while (buffer-live-p
7540 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7541 (setq n (1+ n)))
7542 (condition-case nil
7543 (make-indirect-buffer buffer bname 'clone)
7544 (error (make-indirect-buffer buffer bname)))))
7545
7546 (defun org-set-frame-title (title)
7547 "Set the title of the current frame to the string TITLE."
7548 ;; FIXME: how to name a single frame in XEmacs???
7549 (unless (featurep 'xemacs)
7550 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7551
7552 ;;;; Structure editing
7553
7554 ;;; Inserting headlines
7555
7556 (defun org-previous-line-empty-p (&optional next)
7557 "Is the previous line a blank line?
7558 When NEXT is non-nil, check the next line instead."
7559 (save-excursion
7560 (and (not (bobp))
7561 (or (beginning-of-line (if next 2 0)) t)
7562 (save-match-data
7563 (looking-at "[ \t]*$")))))
7564
7565 (defun org-insert-heading (&optional arg invisible-ok)
7566 "Insert a new heading or an item with the same depth at point.
7567
7568 If point is at the beginning of a heading or a list item, insert
7569 a new heading or a new item above the current one. If point is
7570 at the beginning of a normal line, turn the line into a heading.
7571
7572 If point is in the middle of a headline or a list item, split the
7573 headline or the item and create a new headline/item with the text
7574 in the current line after point \(see `org-M-RET-may-split-line'
7575 on how to modify this behavior).
7576
7577 With one universal prefix argument, set the user option
7578 `org-insert-heading-respect-content' to t for the duration of
7579 the command. This modifies the behavior described above in this
7580 ways: on list items and at the beginning of normal lines, force
7581 the insertion of a heading after the current subtree.
7582
7583 With two universal prefix arguments, insert the heading at the
7584 end of the grandparent subtree. For example, if point is within
7585 a 2nd-level heading, then it will insert a 2nd-level heading at
7586 the end of the 1st-level parent heading.
7587
7588 When INVISIBLE-OK is set, stop at invisible headlines when going
7589 back. This is important for non-interactive uses of the
7590 command."
7591 (interactive "P")
7592 (if (org-called-interactively-p 'any) (org-reveal))
7593 (let ((itemp (org-in-item-p))
7594 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7595 (respect-content (or org-insert-heading-respect-content
7596 (equal arg '(4))))
7597 (initial-content "")
7598 (adjust-empty-lines t))
7599
7600 (cond
7601
7602 ((or (= (buffer-size) 0)
7603 (and (not (save-excursion
7604 (and (ignore-errors (org-back-to-heading invisible-ok))
7605 (org-at-heading-p))))
7606 (or arg (not itemp))))
7607 ;; At beginning of buffer or so high up that only a heading
7608 ;; makes sense.
7609 (cond ((and (bolp) (not respect-content)) (insert "* "))
7610 ((not respect-content)
7611 (unless may-split (end-of-line))
7612 (insert "\n* "))
7613 ((re-search-forward org-outline-regexp-bol nil t)
7614 (beginning-of-line)
7615 (insert "* \n")
7616 (backward-char))
7617 (t (goto-char (point-max))
7618 (insert "\n* ")))
7619 (run-hooks 'org-insert-heading-hook))
7620
7621 ((and itemp (not (member arg '((4) (16)))))
7622 ;; Insert an item
7623 (org-insert-item))
7624
7625 (t
7626 ;; Maybe move at the end of the subtree
7627 (when (equal arg '(16))
7628 (org-up-heading-safe)
7629 (org-end-of-subtree t))
7630 ;; Insert a heading
7631 (save-restriction
7632 (widen)
7633 (let* ((level nil)
7634 (on-heading (org-at-heading-p))
7635 (empty-line-p (if on-heading
7636 (org-previous-line-empty-p)
7637 ;; We will decide later
7638 nil))
7639 ;; Get a level string to fall back on
7640 (fix-level
7641 (if (org-before-first-heading-p) "*"
7642 (save-excursion
7643 (org-back-to-heading t)
7644 (if (org-previous-line-empty-p) (setq empty-line-p t))
7645 (looking-at org-outline-regexp)
7646 (make-string (1- (length (match-string 0))) ?*))))
7647 (stars
7648 (save-excursion
7649 (condition-case nil
7650 (progn
7651 (org-back-to-heading invisible-ok)
7652 (when (and (not on-heading)
7653 (featurep 'org-inlinetask)
7654 (integerp org-inlinetask-min-level)
7655 (>= (length (match-string 0))
7656 org-inlinetask-min-level))
7657 ;; Find a heading level before the inline task
7658 (while (and (setq level (org-up-heading-safe))
7659 (>= level org-inlinetask-min-level)))
7660 (if (org-at-heading-p)
7661 (org-back-to-heading invisible-ok)
7662 (error "This should not happen")))
7663 (unless (and (save-excursion
7664 (save-match-data
7665 (org-backward-heading-same-level
7666 1 invisible-ok))
7667 (= (point) (match-beginning 0)))
7668 (not (org-previous-line-empty-p t)))
7669 (setq empty-line-p (or empty-line-p
7670 (org-previous-line-empty-p))))
7671 (match-string 0))
7672 (error (or fix-level "* ")))))
7673 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7674 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7675 pos hide-previous previous-pos)
7676
7677 ;; If we insert after content, move there and clean up whitespace
7678 (when (and respect-content
7679 (not (org-looking-at-p org-outline-regexp-bol)))
7680 (if (not (org-before-first-heading-p))
7681 (org-end-of-subtree nil t)
7682 (re-search-forward org-outline-regexp-bol)
7683 (beginning-of-line 0))
7684 (skip-chars-backward " \r\n")
7685 (and (not (looking-back "^\\*+" (line-beginning-position)))
7686 (looking-at "[ \t]+") (replace-match ""))
7687 (unless (eobp) (forward-char 1))
7688 (when (looking-at "^\\*")
7689 (unless (bobp) (backward-char 1))
7690 (insert "\n")))
7691
7692 ;; If we are splitting, grab the text that should be moved to the new headline
7693 (when may-split
7694 (if (org-on-heading-p)
7695 ;; This is a heading, we split intelligently (keeping tags)
7696 (let ((pos (point)))
7697 (goto-char (point-at-bol))
7698 (unless (looking-at org-complex-heading-regexp)
7699 (error "This should not happen"))
7700 (when (and (match-beginning 4)
7701 (> pos (match-beginning 4))
7702 (< pos (match-end 4)))
7703 (setq initial-content (buffer-substring pos (match-end 4)))
7704 (goto-char pos)
7705 (delete-region (point) (match-end 4))
7706 (if (looking-at "[ \t]*$")
7707 (replace-match "")
7708 (insert (make-string (length initial-content) ?\ )))
7709 (setq initial-content (org-trim initial-content)))
7710 (goto-char pos))
7711 ;; a normal line
7712 (setq initial-content
7713 (org-trim (buffer-substring (point) (point-at-eol))))
7714 (delete-region (point) (point-at-eol))))
7715
7716 ;; If we are at the beginning of the line, insert before it. Else after
7717 (cond
7718 ((and (bolp) (looking-at "[ \t]*$")))
7719 ((and (bolp) (not (looking-at "[ \t]*$")))
7720 (open-line 1))
7721 (t
7722 (goto-char (point-at-eol))
7723 (insert "\n")))
7724
7725 ;; Insert the new heading
7726 (insert stars)
7727 (just-one-space)
7728 (insert initial-content)
7729 (when adjust-empty-lines
7730 (if (or (not blank)
7731 (and blank (not (org-previous-line-empty-p))))
7732 (org-N-empty-lines-before-current (if blank 1 0))))
7733 (run-hooks 'org-insert-heading-hook)))))))
7734
7735 (defun org-N-empty-lines-before-current (N)
7736 "Make the number of empty lines before current exactly N.
7737 So this will delete or add empty lines."
7738 (save-excursion
7739 (beginning-of-line)
7740 (let ((p (point)))
7741 (skip-chars-backward " \r\t\n")
7742 (unless (bolp) (forward-line))
7743 (delete-region (point) p))
7744 (when (> N 0) (insert (make-string N ?\n)))))
7745
7746 (defun org-get-heading (&optional no-tags no-todo)
7747 "Return the heading of the current entry, without the stars.
7748 When NO-TAGS is non-nil, don't include tags.
7749 When NO-TODO is non-nil, don't include TODO keywords."
7750 (save-excursion
7751 (org-back-to-heading t)
7752 (cond
7753 ((and no-tags no-todo)
7754 (looking-at org-complex-heading-regexp)
7755 (match-string 4))
7756 (no-tags
7757 (looking-at (concat org-outline-regexp
7758 "\\(.*?\\)"
7759 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7760 (match-string 1))
7761 (no-todo
7762 (looking-at org-todo-line-regexp)
7763 (match-string 3))
7764 (t (looking-at org-heading-regexp)
7765 (match-string 2)))))
7766
7767 (defvar orgstruct-mode) ; defined below
7768
7769 (defun org-heading-components ()
7770 "Return the components of the current heading.
7771 This is a list with the following elements:
7772 - the level as an integer
7773 - the reduced level, different if `org-odd-levels-only' is set.
7774 - the TODO keyword, or nil
7775 - the priority character, like ?A, or nil if no priority is given
7776 - the headline text itself, or the tags string if no headline text
7777 - the tags string, or nil."
7778 (save-excursion
7779 (org-back-to-heading t)
7780 (if (let (case-fold-search)
7781 (looking-at
7782 (if orgstruct-mode
7783 org-heading-regexp
7784 org-complex-heading-regexp)))
7785 (if orgstruct-mode
7786 (list (length (match-string 1))
7787 (org-reduced-level (length (match-string 1)))
7788 nil
7789 nil
7790 (match-string 2)
7791 nil)
7792 (list (length (match-string 1))
7793 (org-reduced-level (length (match-string 1)))
7794 (org-match-string-no-properties 2)
7795 (and (match-end 3) (aref (match-string 3) 2))
7796 (org-match-string-no-properties 4)
7797 (org-match-string-no-properties 5))))))
7798
7799 (defun org-get-entry ()
7800 "Get the entry text, after heading, entire subtree."
7801 (save-excursion
7802 (org-back-to-heading t)
7803 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7804
7805 (defun org-insert-heading-after-current ()
7806 "Insert a new heading with same level as current, after current subtree."
7807 (interactive)
7808 (org-back-to-heading)
7809 (org-insert-heading)
7810 (org-move-subtree-down)
7811 (end-of-line 1))
7812
7813 (defun org-insert-heading-respect-content (&optional invisible-ok)
7814 "Insert heading with `org-insert-heading-respect-content' set to t."
7815 (interactive)
7816 (org-insert-heading '(4) invisible-ok))
7817
7818 (defun org-insert-todo-heading-respect-content (&optional force-state)
7819 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7820 (interactive)
7821 (org-insert-todo-heading force-state '(4)))
7822
7823 (defun org-insert-todo-heading (arg &optional force-heading)
7824 "Insert a new heading with the same level and TODO state as current heading.
7825 If the heading has no TODO state, or if the state is DONE, use the first
7826 state (TODO by default). Also with one prefix arg, force first state. With
7827 two prefix args, force inserting at the end of the parent subtree."
7828 (interactive "P")
7829 (when (or force-heading (not (org-insert-item 'checkbox)))
7830 (org-insert-heading (or (and (equal arg '(16)) '(16))
7831 force-heading))
7832 (save-excursion
7833 (org-back-to-heading)
7834 (outline-previous-heading)
7835 (looking-at org-todo-line-regexp))
7836 (let*
7837 ((new-mark-x
7838 (if (or (equal arg '(4))
7839 (not (match-beginning 2))
7840 (member (match-string 2) org-done-keywords))
7841 (car org-todo-keywords-1)
7842 (match-string 2)))
7843 (new-mark
7844 (or
7845 (run-hook-with-args-until-success
7846 'org-todo-get-default-hook new-mark-x nil)
7847 new-mark-x)))
7848 (beginning-of-line 1)
7849 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7850 (if org-treat-insert-todo-heading-as-state-change
7851 (org-todo new-mark)
7852 (insert new-mark " "))))
7853 (when org-provide-todo-statistics
7854 (org-update-parent-todo-statistics))))
7855
7856 (defun org-insert-subheading (arg)
7857 "Insert a new subheading and demote it.
7858 Works for outline headings and for plain lists alike."
7859 (interactive "P")
7860 (org-insert-heading arg)
7861 (cond
7862 ((org-at-heading-p) (org-do-demote))
7863 ((org-at-item-p) (org-indent-item))))
7864
7865 (defun org-insert-todo-subheading (arg)
7866 "Insert a new subheading with TODO keyword or checkbox and demote it.
7867 Works for outline headings and for plain lists alike."
7868 (interactive "P")
7869 (org-insert-todo-heading arg)
7870 (cond
7871 ((org-at-heading-p) (org-do-demote))
7872 ((org-at-item-p) (org-indent-item))))
7873
7874 ;;; Promotion and Demotion
7875
7876 (defvar org-after-demote-entry-hook nil
7877 "Hook run after an entry has been demoted.
7878 The cursor will be at the beginning of the entry.
7879 When a subtree is being demoted, the hook will be called for each node.")
7880
7881 (defvar org-after-promote-entry-hook nil
7882 "Hook run after an entry has been promoted.
7883 The cursor will be at the beginning of the entry.
7884 When a subtree is being promoted, the hook will be called for each node.")
7885
7886 (defun org-promote-subtree ()
7887 "Promote the entire subtree.
7888 See also `org-promote'."
7889 (interactive)
7890 (save-excursion
7891 (org-with-limited-levels (org-map-tree 'org-promote)))
7892 (org-fix-position-after-promote))
7893
7894 (defun org-demote-subtree ()
7895 "Demote the entire subtree. See `org-demote'.
7896 See also `org-promote'."
7897 (interactive)
7898 (save-excursion
7899 (org-with-limited-levels (org-map-tree 'org-demote)))
7900 (org-fix-position-after-promote))
7901
7902
7903 (defun org-do-promote ()
7904 "Promote the current heading higher up the tree.
7905 If the region is active in `transient-mark-mode', promote all headings
7906 in the region."
7907 (interactive)
7908 (save-excursion
7909 (if (org-region-active-p)
7910 (org-map-region 'org-promote (region-beginning) (region-end))
7911 (org-promote)))
7912 (org-fix-position-after-promote))
7913
7914 (defun org-do-demote ()
7915 "Demote the current heading lower down the tree.
7916 If the region is active in `transient-mark-mode', demote all headings
7917 in the region."
7918 (interactive)
7919 (save-excursion
7920 (if (org-region-active-p)
7921 (org-map-region 'org-demote (region-beginning) (region-end))
7922 (org-demote)))
7923 (org-fix-position-after-promote))
7924
7925 (defun org-fix-position-after-promote ()
7926 "Make sure that after pro/demotion cursor position is right."
7927 (let ((pos (point)))
7928 (when (save-excursion
7929 (beginning-of-line 1)
7930 (looking-at org-todo-line-regexp)
7931 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7932 (cond ((eobp) (insert " "))
7933 ((eolp) (insert " "))
7934 ((equal (char-after) ?\ ) (forward-char 1))))))
7935
7936 (defun org-current-level ()
7937 "Return the level of the current entry, or nil if before the first headline.
7938 The level is the number of stars at the beginning of the headline."
7939 (save-excursion
7940 (org-with-limited-levels
7941 (if (ignore-errors (org-back-to-heading t))
7942 (funcall outline-level)))))
7943
7944 (defun org-get-previous-line-level ()
7945 "Return the outline depth of the last headline before the current line.
7946 Returns 0 for the first headline in the buffer, and nil if before the
7947 first headline."
7948 (and (org-current-level)
7949 (or (and (/= (line-beginning-position) (point-min))
7950 (save-excursion (beginning-of-line 0) (org-current-level)))
7951 0)))
7952
7953 (defun org-reduced-level (l)
7954 "Compute the effective level of a heading.
7955 This takes into account the setting of `org-odd-levels-only'."
7956 (cond
7957 ((zerop l) 0)
7958 (org-odd-levels-only (1+ (floor (/ l 2))))
7959 (t l)))
7960
7961 (defun org-level-increment ()
7962 "Return the number of stars that will be added or removed at a
7963 time to headlines when structure editing, based on the value of
7964 `org-odd-levels-only'."
7965 (if org-odd-levels-only 2 1))
7966
7967 (defun org-get-valid-level (level &optional change)
7968 "Rectify a level change under the influence of `org-odd-levels-only'
7969 LEVEL is a current level, CHANGE is by how much the level should be
7970 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7971 even level numbers will become the next higher odd number."
7972 (if org-odd-levels-only
7973 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7974 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7975 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7976 (max 1 (+ level (or change 0)))))
7977
7978 (if (boundp 'define-obsolete-function-alias)
7979 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7980 (define-obsolete-function-alias 'org-get-legal-level
7981 'org-get-valid-level)
7982 (define-obsolete-function-alias 'org-get-legal-level
7983 'org-get-valid-level "23.1")))
7984
7985 (defun org-promote ()
7986 "Promote the current heading higher up the tree.
7987 If the region is active in `transient-mark-mode', promote all headings
7988 in the region."
7989 (org-back-to-heading t)
7990 (let* ((level (save-match-data (funcall outline-level)))
7991 (after-change-functions (remove 'flyspell-after-change-function
7992 after-change-functions))
7993 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7994 (diff (abs (- level (length up-head) -1))))
7995 (cond ((and (= level 1) org-called-with-limited-levels
7996 org-allow-promoting-top-level-subtree)
7997 (replace-match "# " nil t))
7998 ((= level 1)
7999 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8000 (t (replace-match up-head nil t)))
8001 ;; Fixup tag positioning
8002 (unless (= level 1)
8003 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8004 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8005 (run-hooks 'org-after-promote-entry-hook)))
8006
8007 (defun org-demote ()
8008 "Demote the current heading lower down the tree.
8009 If the region is active in `transient-mark-mode', demote all headings
8010 in the region."
8011 (org-back-to-heading t)
8012 (let* ((level (save-match-data (funcall outline-level)))
8013 (after-change-functions (remove 'flyspell-after-change-function
8014 after-change-functions))
8015 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8016 (diff (abs (- level (length down-head) -1))))
8017 (replace-match down-head nil t)
8018 ;; Fixup tag positioning
8019 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8020 (if org-adapt-indentation (org-fixup-indentation diff))
8021 (run-hooks 'org-after-demote-entry-hook)))
8022
8023 (defun org-cycle-level ()
8024 "Cycle the level of an empty headline through possible states.
8025 This goes first to child, then to parent, level, then up the hierarchy.
8026 After top level, it switches back to sibling level."
8027 (interactive)
8028 (let ((org-adapt-indentation nil))
8029 (when (org-point-at-end-of-empty-headline)
8030 (setq this-command 'org-cycle-level) ; Only needed for caching
8031 (let ((cur-level (org-current-level))
8032 (prev-level (org-get-previous-line-level)))
8033 (cond
8034 ;; If first headline in file, promote to top-level.
8035 ((= prev-level 0)
8036 (loop repeat (/ (- cur-level 1) (org-level-increment))
8037 do (org-do-promote)))
8038 ;; If same level as prev, demote one.
8039 ((= prev-level cur-level)
8040 (org-do-demote))
8041 ;; If parent is top-level, promote to top level if not already.
8042 ((= prev-level 1)
8043 (loop repeat (/ (- cur-level 1) (org-level-increment))
8044 do (org-do-promote)))
8045 ;; If top-level, return to prev-level.
8046 ((= cur-level 1)
8047 (loop repeat (/ (- prev-level 1) (org-level-increment))
8048 do (org-do-demote)))
8049 ;; If less than prev-level, promote one.
8050 ((< cur-level prev-level)
8051 (org-do-promote))
8052 ;; If deeper than prev-level, promote until higher than
8053 ;; prev-level.
8054 ((> cur-level prev-level)
8055 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8056 do (org-do-promote))))
8057 t))))
8058
8059 (defun org-map-tree (fun)
8060 "Call FUN for every heading underneath the current one."
8061 (org-back-to-heading)
8062 (let ((level (funcall outline-level)))
8063 (save-excursion
8064 (funcall fun)
8065 (while (and (progn
8066 (outline-next-heading)
8067 (> (funcall outline-level) level))
8068 (not (eobp)))
8069 (funcall fun)))))
8070
8071 (defun org-map-region (fun beg end)
8072 "Call FUN for every heading between BEG and END."
8073 (let ((org-ignore-region t))
8074 (save-excursion
8075 (setq end (copy-marker end))
8076 (goto-char beg)
8077 (if (and (re-search-forward org-outline-regexp-bol nil t)
8078 (< (point) end))
8079 (funcall fun))
8080 (while (and (progn
8081 (outline-next-heading)
8082 (< (point) end))
8083 (not (eobp)))
8084 (funcall fun)))))
8085
8086 (defvar org-property-end-re) ; silence byte-compiler
8087 (defun org-fixup-indentation (diff)
8088 "Change the indentation in the current entry by DIFF.
8089 However, if any line in the current entry has no indentation, or if it
8090 would end up with no indentation after the change, nothing at all is done."
8091 (save-excursion
8092 (let ((end (save-excursion (outline-next-heading)
8093 (point-marker)))
8094 (prohibit (if (> diff 0)
8095 "^\\S-"
8096 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8097 col)
8098 (unless (save-excursion (end-of-line 1)
8099 (re-search-forward prohibit end t))
8100 (while (and (< (point) end)
8101 (re-search-forward "^[ \t]+" end t))
8102 (goto-char (match-end 0))
8103 (setq col (current-column))
8104 (if (< diff 0) (replace-match ""))
8105 (org-indent-to-column (+ diff col))))
8106 (move-marker end nil))))
8107
8108 (defun org-convert-to-odd-levels ()
8109 "Convert an org-mode file with all levels allowed to one with odd levels.
8110 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8111 level 5 etc."
8112 (interactive)
8113 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8114 (let ((outline-level 'org-outline-level)
8115 (org-odd-levels-only nil) n)
8116 (save-excursion
8117 (goto-char (point-min))
8118 (while (re-search-forward "^\\*\\*+ " nil t)
8119 (setq n (- (length (match-string 0)) 2))
8120 (while (>= (setq n (1- n)) 0)
8121 (org-demote))
8122 (end-of-line 1))))))
8123
8124 (defun org-convert-to-oddeven-levels ()
8125 "Convert an org-mode file with only odd levels to one with odd/even levels.
8126 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8127 file contains a section with an even level, conversion would
8128 destroy the structure of the file. An error is signaled in this
8129 case."
8130 (interactive)
8131 (goto-char (point-min))
8132 ;; First check if there are no even levels
8133 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8134 (org-show-context t)
8135 (error "Not all levels are odd in this file. Conversion not possible"))
8136 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8137 (let ((outline-regexp org-outline-regexp)
8138 (outline-level 'org-outline-level)
8139 (org-odd-levels-only nil) n)
8140 (save-excursion
8141 (goto-char (point-min))
8142 (while (re-search-forward "^\\*\\*+ " nil t)
8143 (setq n (/ (1- (length (match-string 0))) 2))
8144 (while (>= (setq n (1- n)) 0)
8145 (org-promote))
8146 (end-of-line 1))))))
8147
8148 (defun org-tr-level (n)
8149 "Make N odd if required."
8150 (if org-odd-levels-only (1+ (/ n 2)) n))
8151
8152 ;;; Vertical tree motion, cutting and pasting of subtrees
8153
8154 (defun org-move-subtree-up (&optional arg)
8155 "Move the current subtree up past ARG headlines of the same level."
8156 (interactive "p")
8157 (org-move-subtree-down (- (prefix-numeric-value arg))))
8158
8159 (defun org-move-subtree-down (&optional arg)
8160 "Move the current subtree down past ARG headlines of the same level."
8161 (interactive "p")
8162 (setq arg (prefix-numeric-value arg))
8163 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8164 'org-get-last-sibling))
8165 (ins-point (make-marker))
8166 (cnt (abs arg))
8167 (col (current-column))
8168 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8169 ;; Select the tree
8170 (org-back-to-heading)
8171 (setq beg0 (point))
8172 (save-excursion
8173 (setq ne-beg (org-back-over-empty-lines))
8174 (setq beg (point)))
8175 (save-match-data
8176 (save-excursion (outline-end-of-heading)
8177 (setq folded (outline-invisible-p)))
8178 (progn (org-end-of-subtree nil t)
8179 (unless (eobp) (backward-char))))
8180 (outline-next-heading)
8181 (setq ne-end (org-back-over-empty-lines))
8182 (setq end (point))
8183 (goto-char beg0)
8184 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8185 ;; include less whitespace
8186 (save-excursion
8187 (goto-char beg)
8188 (forward-line (- ne-beg ne-end))
8189 (setq beg (point))))
8190 ;; Find insertion point, with error handling
8191 (while (> cnt 0)
8192 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8193 (progn (goto-char beg0)
8194 (user-error "Cannot move past superior level or buffer limit")))
8195 (setq cnt (1- cnt)))
8196 (if (> arg 0)
8197 ;; Moving forward - still need to move over subtree
8198 (progn (org-end-of-subtree t t)
8199 (save-excursion
8200 (org-back-over-empty-lines)
8201 (or (bolp) (newline)))))
8202 (setq ne-ins (org-back-over-empty-lines))
8203 (move-marker ins-point (point))
8204 (setq txt (buffer-substring beg end))
8205 (org-save-markers-in-region beg end)
8206 (delete-region beg end)
8207 (org-remove-empty-overlays-at beg)
8208 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8209 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8210 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8211 (let ((bbb (point)))
8212 (insert-before-markers txt)
8213 (org-reinstall-markers-in-region bbb)
8214 (move-marker ins-point bbb))
8215 (or (bolp) (insert "\n"))
8216 (setq ins-end (point))
8217 (goto-char ins-point)
8218 (org-skip-whitespace)
8219 (when (and (< arg 0)
8220 (org-first-sibling-p)
8221 (> ne-ins ne-beg))
8222 ;; Move whitespace back to beginning
8223 (save-excursion
8224 (goto-char ins-end)
8225 (let ((kill-whole-line t))
8226 (kill-line (- ne-ins ne-beg)) (point)))
8227 (insert (make-string (- ne-ins ne-beg) ?\n)))
8228 (move-marker ins-point nil)
8229 (if folded
8230 (hide-subtree)
8231 (org-show-entry)
8232 (show-children)
8233 (org-cycle-hide-drawers 'children))
8234 (org-clean-visibility-after-subtree-move)
8235 ;; move back to the initial column we were at
8236 (move-to-column col)))
8237
8238 (defvar org-subtree-clip ""
8239 "Clipboard for cut and paste of subtrees.
8240 This is actually only a copy of the kill, because we use the normal kill
8241 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8242
8243 (defvar org-subtree-clip-folded nil
8244 "Was the last copied subtree folded?
8245 This is used to fold the tree back after pasting.")
8246
8247 (defun org-cut-subtree (&optional n)
8248 "Cut the current subtree into the clipboard.
8249 With prefix arg N, cut this many sequential subtrees.
8250 This is a short-hand for marking the subtree and then cutting it."
8251 (interactive "p")
8252 (org-copy-subtree n 'cut))
8253
8254 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8255 "Copy the current subtree it in the clipboard.
8256 With prefix arg N, copy this many sequential subtrees.
8257 This is a short-hand for marking the subtree and then copying it.
8258 If CUT is non-nil, actually cut the subtree.
8259 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8260 of some markers in the region, even if CUT is non-nil. This is
8261 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8262 (interactive "p")
8263 (let (beg end folded (beg0 (point)))
8264 (if (org-called-interactively-p 'any)
8265 (org-back-to-heading nil) ; take what looks like a subtree
8266 (org-back-to-heading t)) ; take what is really there
8267 (setq beg (point))
8268 (skip-chars-forward " \t\r\n")
8269 (save-match-data
8270 (if nosubtrees
8271 (outline-next-heading)
8272 (save-excursion (outline-end-of-heading)
8273 (setq folded (outline-invisible-p)))
8274 (condition-case nil
8275 (org-forward-heading-same-level (1- n) t)
8276 (error nil))
8277 (org-end-of-subtree t t)))
8278 (setq end (point))
8279 (goto-char beg0)
8280 (when (> end beg)
8281 (setq org-subtree-clip-folded folded)
8282 (when (or cut force-store-markers)
8283 (org-save-markers-in-region beg end))
8284 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8285 (setq org-subtree-clip (current-kill 0))
8286 (message "%s: Subtree(s) with %d characters"
8287 (if cut "Cut" "Copied")
8288 (length org-subtree-clip)))))
8289
8290 (defun org-paste-subtree (&optional level tree for-yank)
8291 "Paste the clipboard as a subtree, with modification of headline level.
8292 The entire subtree is promoted or demoted in order to match a new headline
8293 level.
8294
8295 If the cursor is at the beginning of a headline, the same level as
8296 that headline is used to paste the tree.
8297
8298 If not, the new level is derived from the *visible* headings
8299 before and after the insertion point, and taken to be the inferior headline
8300 level of the two. So if the previous visible heading is level 3 and the
8301 next is level 4 (or vice versa), level 4 will be used for insertion.
8302 This makes sure that the subtree remains an independent subtree and does
8303 not swallow low level entries.
8304
8305 You can also force a different level, either by using a numeric prefix
8306 argument, or by inserting the heading marker by hand. For example, if the
8307 cursor is after \"*****\", then the tree will be shifted to level 5.
8308
8309 If optional TREE is given, use this text instead of the kill ring.
8310
8311 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8312 move back over whitespace before inserting, and move point to the end of
8313 the inserted text when done."
8314 (interactive "P")
8315 (setq tree (or tree (and kill-ring (current-kill 0))))
8316 (unless (org-kill-is-subtree-p tree)
8317 (user-error "%s"
8318 (substitute-command-keys
8319 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8320 (org-with-limited-levels
8321 (let* ((visp (not (outline-invisible-p)))
8322 (txt tree)
8323 (^re_ "\\(\\*+\\)[ \t]*")
8324 (old-level (if (string-match org-outline-regexp-bol txt)
8325 (- (match-end 0) (match-beginning 0) 1)
8326 -1))
8327 (force-level (cond (level (prefix-numeric-value level))
8328 ((and (looking-at "[ \t]*$")
8329 (string-match
8330 "^\\*+$" (buffer-substring
8331 (point-at-bol) (point))))
8332 (- (match-end 0) (match-beginning 0)))
8333 ((and (bolp)
8334 (looking-at org-outline-regexp))
8335 (- (match-end 0) (point) 1))))
8336 (previous-level (save-excursion
8337 (condition-case nil
8338 (progn
8339 (outline-previous-visible-heading 1)
8340 (if (looking-at ^re_)
8341 (- (match-end 0) (match-beginning 0) 1)
8342 1))
8343 (error 1))))
8344 (next-level (save-excursion
8345 (condition-case nil
8346 (progn
8347 (or (looking-at org-outline-regexp)
8348 (outline-next-visible-heading 1))
8349 (if (looking-at ^re_)
8350 (- (match-end 0) (match-beginning 0) 1)
8351 1))
8352 (error 1))))
8353 (new-level (or force-level (max previous-level next-level)))
8354 (shift (if (or (= old-level -1)
8355 (= new-level -1)
8356 (= old-level new-level))
8357 0
8358 (- new-level old-level)))
8359 (delta (if (> shift 0) -1 1))
8360 (func (if (> shift 0) 'org-demote 'org-promote))
8361 (org-odd-levels-only nil)
8362 beg end newend)
8363 ;; Remove the forced level indicator
8364 (if force-level
8365 (delete-region (point-at-bol) (point)))
8366 ;; Paste
8367 (beginning-of-line (if (bolp) 1 2))
8368 (setq beg (point))
8369 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8370 (insert-before-markers txt)
8371 (unless (string-match "\n\\'" txt) (insert "\n"))
8372 (setq newend (point))
8373 (org-reinstall-markers-in-region beg)
8374 (setq end (point))
8375 (goto-char beg)
8376 (skip-chars-forward " \t\n\r")
8377 (setq beg (point))
8378 (if (and (outline-invisible-p) visp)
8379 (save-excursion (outline-show-heading)))
8380 ;; Shift if necessary
8381 (unless (= shift 0)
8382 (save-restriction
8383 (narrow-to-region beg end)
8384 (while (not (= shift 0))
8385 (org-map-region func (point-min) (point-max))
8386 (setq shift (+ delta shift)))
8387 (goto-char (point-min))
8388 (setq newend (point-max))))
8389 (when (or (org-called-interactively-p 'interactive) for-yank)
8390 (message "Clipboard pasted as level %d subtree" new-level))
8391 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8392 kill-ring
8393 (eq org-subtree-clip (current-kill 0))
8394 org-subtree-clip-folded)
8395 ;; The tree was folded before it was killed/copied
8396 (hide-subtree))
8397 (and for-yank (goto-char newend)))))
8398
8399 (defun org-kill-is-subtree-p (&optional txt)
8400 "Check if the current kill is an outline subtree, or a set of trees.
8401 Returns nil if kill does not start with a headline, or if the first
8402 headline level is not the largest headline level in the tree.
8403 So this will actually accept several entries of equal levels as well,
8404 which is OK for `org-paste-subtree'.
8405 If optional TXT is given, check this string instead of the current kill."
8406 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8407 (re (org-get-limited-outline-regexp))
8408 (^re (concat "^" re))
8409 (start-level (and kill
8410 (string-match
8411 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8412 kill)
8413 (- (match-end 2) (match-beginning 2) 1)))
8414 (start (1+ (or (match-beginning 2) -1))))
8415 (if (not start-level)
8416 (progn
8417 nil) ;; does not even start with a heading
8418 (catch 'exit
8419 (while (setq start (string-match ^re kill (1+ start)))
8420 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8421 (throw 'exit nil)))
8422 t))))
8423
8424 (defvar org-markers-to-move nil
8425 "Markers that should be moved with a cut-and-paste operation.
8426 Those markers are stored together with their positions relative to
8427 the start of the region.")
8428
8429 (defun org-save-markers-in-region (beg end)
8430 "Check markers in region.
8431 If these markers are between BEG and END, record their position relative
8432 to BEG, so that after moving the block of text, we can put the markers back
8433 into place.
8434 This function gets called just before an entry or tree gets cut from the
8435 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8436 called immediately, to move the markers with the entries."
8437 (setq org-markers-to-move nil)
8438 (when (featurep 'org-clock)
8439 (org-clock-save-markers-for-cut-and-paste beg end))
8440 (when (featurep 'org-agenda)
8441 (org-agenda-save-markers-for-cut-and-paste beg end)))
8442
8443 (defun org-check-and-save-marker (marker beg end)
8444 "Check if MARKER is between BEG and END.
8445 If yes, remember the marker and the distance to BEG."
8446 (when (and (marker-buffer marker)
8447 (equal (marker-buffer marker) (current-buffer)))
8448 (if (and (>= marker beg) (< marker end))
8449 (push (cons marker (- marker beg)) org-markers-to-move))))
8450
8451 (defun org-reinstall-markers-in-region (beg)
8452 "Move all remembered markers to their position relative to BEG."
8453 (mapc (lambda (x)
8454 (move-marker (car x) (+ beg (cdr x))))
8455 org-markers-to-move)
8456 (setq org-markers-to-move nil))
8457
8458 (defun org-narrow-to-subtree ()
8459 "Narrow buffer to the current subtree."
8460 (interactive)
8461 (save-excursion
8462 (save-match-data
8463 (org-with-limited-levels
8464 (narrow-to-region
8465 (progn (org-back-to-heading t) (point))
8466 (progn (org-end-of-subtree t t)
8467 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8468 (point)))))))
8469
8470 (defun org-narrow-to-block ()
8471 "Narrow buffer to the current block."
8472 (interactive)
8473 (let* ((case-fold-search t)
8474 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8475 "^[ \t]*#\\+end_.*")))
8476 (if blockp
8477 (narrow-to-region (car blockp) (cdr blockp))
8478 (user-error "Not in a block"))))
8479
8480 (eval-when-compile
8481 (defvar org-property-drawer-re))
8482
8483 (defvar org-property-start-re) ;; defined below
8484 (defun org-clone-subtree-with-time-shift (n &optional shift)
8485 "Clone the task (subtree) at point N times.
8486 The clones will be inserted as siblings.
8487
8488 In interactive use, the user will be prompted for the number of
8489 clones to be produced. If the entry has a timestamp, the user
8490 will also be prompted for a time shift, which may be a repeater
8491 as used in time stamps, for example `+3d'. To disable this,
8492 you can call the function with a universal prefix argument.
8493
8494 When a valid repeater is given and the entry contains any time
8495 stamps, the clones will become a sequence in time, with time
8496 stamps in the subtree shifted for each clone produced. If SHIFT
8497 is nil or the empty string, time stamps will be left alone. The
8498 ID property of the original subtree is removed.
8499
8500 If the original subtree did contain time stamps with a repeater,
8501 the following will happen:
8502 - the repeater will be removed in each clone
8503 - an additional clone will be produced, with the current, unshifted
8504 date(s) in the entry.
8505 - the original entry will be placed *after* all the clones, with
8506 repeater intact.
8507 - the start days in the repeater in the original entry will be shifted
8508 to past the last clone.
8509 In this way you can spell out a number of instances of a repeating task,
8510 and still retain the repeater to cover future instances of the task."
8511 (interactive "nNumber of clones to produce: ")
8512 (let ((shift
8513 (or shift
8514 (if (and (not (equal current-prefix-arg '(4)))
8515 (save-excursion
8516 (re-search-forward org-ts-regexp-both
8517 (save-excursion
8518 (org-end-of-subtree t)
8519 (point)) t)))
8520 (read-from-minibuffer
8521 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8522 ""))) ;; No time shift
8523 (n-no-remove -1)
8524 (drawer-re org-drawer-regexp)
8525 beg end template task idprop
8526 shift-n shift-what doshift nmin nmax)
8527 (if (not (and (integerp n) (> n 0)))
8528 (error "Invalid number of replications %s" n))
8529 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8530 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8531 shift)))
8532 (error "Invalid shift specification %s" shift))
8533 (when doshift
8534 (setq shift-n (string-to-number (match-string 1 shift))
8535 shift-what (cdr (assoc (match-string 2 shift)
8536 '(("d" . day) ("w" . week)
8537 ("m" . month) ("y" . year))))))
8538 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8539 (setq nmin 1 nmax n)
8540 (org-back-to-heading t)
8541 (setq beg (point))
8542 (setq idprop (org-entry-get nil "ID"))
8543 (org-end-of-subtree t t)
8544 (or (bolp) (insert "\n"))
8545 (setq end (point))
8546 (setq template (buffer-substring beg end))
8547 (when (and doshift
8548 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8549 (delete-region beg end)
8550 (setq end beg)
8551 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8552 (goto-char end)
8553 (loop for n from nmin to nmax do
8554 ;; prepare clone
8555 (with-temp-buffer
8556 (insert template)
8557 (org-mode)
8558 (goto-char (point-min))
8559 (org-show-subtree)
8560 (and idprop (if org-clone-delete-id
8561 (org-entry-delete nil "ID")
8562 (org-id-get-create t)))
8563 (unless (= n 0)
8564 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8565 (kill-whole-line))
8566 (goto-char (point-min))
8567 (while (re-search-forward drawer-re nil t)
8568 (mapc (lambda (d)
8569 (org-remove-empty-drawer-at d (point)))
8570 org-drawers)))
8571 (goto-char (point-min))
8572 (when doshift
8573 (while (re-search-forward org-ts-regexp-both nil t)
8574 (org-timestamp-change (* n shift-n) shift-what))
8575 (unless (= n n-no-remove)
8576 (goto-char (point-min))
8577 (while (re-search-forward org-ts-regexp nil t)
8578 (save-excursion
8579 (goto-char (match-beginning 0))
8580 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8581 (delete-region (match-beginning 1) (match-end 1)))))))
8582 (setq task (buffer-string)))
8583 (insert task))
8584 (goto-char beg)))
8585
8586 ;;; Outline Sorting
8587
8588 (defun org-sort (with-case)
8589 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8590 Optional argument WITH-CASE means sort case-sensitively."
8591 (interactive "P")
8592 (cond
8593 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8594 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8595 (t
8596 (org-call-with-arg 'org-sort-entries with-case))))
8597
8598 (defun org-sort-remove-invisible (s)
8599 "Remove invisible links from string S."
8600 (remove-text-properties 0 (length s) org-rm-props s)
8601 (while (string-match org-bracket-link-regexp s)
8602 (setq s (replace-match (if (match-end 2)
8603 (match-string 3 s)
8604 (match-string 1 s))
8605 t t s)))
8606 (let ((st (format " %s " s)))
8607 (while (string-match org-emph-re st)
8608 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8609 (setq s (substring st 1 -1)))
8610 s)
8611
8612 (defvar org-priority-regexp) ; defined later in the file
8613
8614 (defvar org-after-sorting-entries-or-items-hook nil
8615 "Hook that is run after a bunch of entries or items have been sorted.
8616 When children are sorted, the cursor is in the parent line when this
8617 hook gets called. When a region or a plain list is sorted, the cursor
8618 will be in the first entry of the sorted region/list.")
8619
8620 (defun org-sort-entries
8621 (&optional with-case sorting-type getkey-func compare-func property)
8622 "Sort entries on a certain level of an outline tree.
8623 If there is an active region, the entries in the region are sorted.
8624 Else, if the cursor is before the first entry, sort the top-level items.
8625 Else, the children of the entry at point are sorted.
8626
8627 Sorting can be alphabetically, numerically, by date/time as given by
8628 a time stamp, by a property, by priority order, or by a custom function.
8629
8630 The command prompts for the sorting type unless it has been given to the
8631 function through the SORTING-TYPE argument, which needs to be a character,
8632 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8633 precise meaning of each character:
8634
8635 n Numerically, by converting the beginning of the entry/item to a number.
8636 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8637 o By order of TODO keywords.
8638 t By date/time, either the first active time stamp in the entry, or, if
8639 none exist, by the first inactive one.
8640 s By the scheduled date/time.
8641 d By deadline date/time.
8642 c By creation time, which is assumed to be the first inactive time stamp
8643 at the beginning of a line.
8644 p By priority according to the cookie.
8645 r By the value of a property.
8646
8647 Capital letters will reverse the sort order.
8648
8649 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8650 called with point at the beginning of the record. It must return either
8651 a string or a number that should serve as the sorting key for that record.
8652
8653 Comparing entries ignores case by default. However, with an optional argument
8654 WITH-CASE, the sorting considers case as well.
8655
8656 Sorting is done against the visible part of the headlines, it ignores hidden
8657 links."
8658 (interactive "P")
8659 (let ((case-func (if with-case 'identity 'downcase))
8660 (cmstr
8661 ;; The clock marker is lost when using `sort-subr', let's
8662 ;; store the clocking string.
8663 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8664 (save-excursion
8665 (goto-char org-clock-marker)
8666 (buffer-substring-no-properties (line-beginning-position)
8667 (point)))))
8668 start beg end stars re re2
8669 txt what tmp)
8670 ;; Find beginning and end of region to sort
8671 (cond
8672 ((org-region-active-p)
8673 ;; we will sort the region
8674 (setq end (region-end)
8675 what "region")
8676 (goto-char (region-beginning))
8677 (if (not (org-at-heading-p)) (outline-next-heading))
8678 (setq start (point)))
8679 ((or (org-at-heading-p)
8680 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8681 ;; we will sort the children of the current headline
8682 (org-back-to-heading)
8683 (setq start (point)
8684 end (progn (org-end-of-subtree t t)
8685 (or (bolp) (insert "\n"))
8686 (when (>= (org-back-over-empty-lines) 1)
8687 (forward-line 1))
8688 (point))
8689 what "children")
8690 (goto-char start)
8691 (show-subtree)
8692 (outline-next-heading))
8693 (t
8694 ;; we will sort the top-level entries in this file
8695 (goto-char (point-min))
8696 (or (org-at-heading-p) (outline-next-heading))
8697 (setq start (point))
8698 (goto-char (point-max))
8699 (beginning-of-line 1)
8700 (when (looking-at ".*?\\S-")
8701 ;; File ends in a non-white line
8702 (end-of-line 1)
8703 (insert "\n"))
8704 (setq end (point-max))
8705 (setq what "top-level")
8706 (goto-char start)
8707 (show-all)))
8708
8709 (setq beg (point))
8710 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8711
8712 (looking-at "\\(\\*+\\)")
8713 (setq stars (match-string 1)
8714 re (concat "^" (regexp-quote stars) " +")
8715 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8716 txt (buffer-substring beg end))
8717 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8718 (if (and (not (equal stars "*")) (string-match re2 txt))
8719 (user-error "Region to sort contains a level above the first entry"))
8720
8721 (unless sorting-type
8722 (message
8723 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8724 [t]ime [s]cheduled [d]eadline [c]reated
8725 A/N/P/R/O/F/T/S/D/C means reversed:"
8726 what)
8727 (setq sorting-type (read-char-exclusive))
8728
8729 (unless getkey-func
8730 (and (= (downcase sorting-type) ?f)
8731 (setq getkey-func
8732 (org-icompleting-read "Sort using function: "
8733 obarray 'fboundp t nil nil))
8734 (setq getkey-func (intern getkey-func))))
8735
8736 (and (= (downcase sorting-type) ?r)
8737 (not property)
8738 (setq property
8739 (org-icompleting-read "Property: "
8740 (mapcar 'list (org-buffer-property-keys t))
8741 nil t))))
8742
8743 (message "Sorting entries...")
8744
8745 (save-restriction
8746 (narrow-to-region start end)
8747 (let ((dcst (downcase sorting-type))
8748 (case-fold-search nil)
8749 (now (current-time)))
8750 (sort-subr
8751 (/= dcst sorting-type)
8752 ;; This function moves to the beginning character of the "record" to
8753 ;; be sorted.
8754 (lambda nil
8755 (if (re-search-forward re nil t)
8756 (goto-char (match-beginning 0))
8757 (goto-char (point-max))))
8758 ;; This function moves to the last character of the "record" being
8759 ;; sorted.
8760 (lambda nil
8761 (save-match-data
8762 (condition-case nil
8763 (outline-forward-same-level 1)
8764 (error
8765 (goto-char (point-max))))))
8766 ;; This function returns the value that gets sorted against.
8767 (lambda nil
8768 (cond
8769 ((= dcst ?n)
8770 (if (looking-at org-complex-heading-regexp)
8771 (string-to-number (org-sort-remove-invisible (match-string 4)))
8772 nil))
8773 ((= dcst ?a)
8774 (if (looking-at org-complex-heading-regexp)
8775 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8776 nil))
8777 ((= dcst ?t)
8778 (let ((end (save-excursion (outline-next-heading) (point))))
8779 (if (or (re-search-forward org-ts-regexp end t)
8780 (re-search-forward org-ts-regexp-both end t))
8781 (org-time-string-to-seconds (match-string 0))
8782 (org-float-time now))))
8783 ((= dcst ?c)
8784 (let ((end (save-excursion (outline-next-heading) (point))))
8785 (if (re-search-forward
8786 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8787 end t)
8788 (org-time-string-to-seconds (match-string 0))
8789 (org-float-time now))))
8790 ((= dcst ?s)
8791 (let ((end (save-excursion (outline-next-heading) (point))))
8792 (if (re-search-forward org-scheduled-time-regexp end t)
8793 (org-time-string-to-seconds (match-string 1))
8794 (org-float-time now))))
8795 ((= dcst ?d)
8796 (let ((end (save-excursion (outline-next-heading) (point))))
8797 (if (re-search-forward org-deadline-time-regexp end t)
8798 (org-time-string-to-seconds (match-string 1))
8799 (org-float-time now))))
8800 ((= dcst ?p)
8801 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8802 (string-to-char (match-string 2))
8803 org-default-priority))
8804 ((= dcst ?r)
8805 (or (org-entry-get nil property) ""))
8806 ((= dcst ?o)
8807 (if (looking-at org-complex-heading-regexp)
8808 (- 9999 (length (member (match-string 2)
8809 org-todo-keywords-1)))))
8810 ((= dcst ?f)
8811 (if getkey-func
8812 (progn
8813 (setq tmp (funcall getkey-func))
8814 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8815 tmp)
8816 (error "Invalid key function `%s'" getkey-func)))
8817 (t (error "Invalid sorting type `%c'" sorting-type))))
8818 nil
8819 (cond
8820 ((= dcst ?a) 'string<)
8821 ((= dcst ?f) compare-func)
8822 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8823 (run-hooks 'org-after-sorting-entries-or-items-hook)
8824 ;; Reset the clock marker if needed
8825 (when cmstr
8826 (save-excursion
8827 (goto-char start)
8828 (search-forward cmstr nil t)
8829 (move-marker org-clock-marker (point))))
8830 (message "Sorting entries...done")))
8831
8832 (defun org-do-sort (table what &optional with-case sorting-type)
8833 "Sort TABLE of WHAT according to SORTING-TYPE.
8834 The user will be prompted for the SORTING-TYPE if the call to this
8835 function does not specify it. WHAT is only for the prompt, to indicate
8836 what is being sorted. The sorting key will be extracted from
8837 the car of the elements of the table.
8838 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8839 (unless sorting-type
8840 (message
8841 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8842 what)
8843 (setq sorting-type (read-char-exclusive)))
8844 (let ((dcst (downcase sorting-type))
8845 extractfun comparefun)
8846 ;; Define the appropriate functions
8847 (cond
8848 ((= dcst ?n)
8849 (setq extractfun 'string-to-number
8850 comparefun (if (= dcst sorting-type) '< '>)))
8851 ((= dcst ?a)
8852 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8853 (lambda(x) (downcase (org-sort-remove-invisible x))))
8854 comparefun (if (= dcst sorting-type)
8855 'string<
8856 (lambda (a b) (and (not (string< a b))
8857 (not (string= a b)))))))
8858 ((= dcst ?t)
8859 (setq extractfun
8860 (lambda (x)
8861 (if (or (string-match org-ts-regexp x)
8862 (string-match org-ts-regexp-both x))
8863 (org-float-time
8864 (org-time-string-to-time (match-string 0 x)))
8865 0))
8866 comparefun (if (= dcst sorting-type) '< '>)))
8867 (t (error "Invalid sorting type `%c'" sorting-type)))
8868
8869 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8870 table)
8871 (lambda (a b) (funcall comparefun (car a) (car b))))))
8872
8873
8874 ;;; The orgstruct minor mode
8875
8876 ;; Define a minor mode which can be used in other modes in order to
8877 ;; integrate the org-mode structure editing commands.
8878
8879 ;; This is really a hack, because the org-mode structure commands use
8880 ;; keys which normally belong to the major mode. Here is how it
8881 ;; works: The minor mode defines all the keys necessary to operate the
8882 ;; structure commands, but wraps the commands into a function which
8883 ;; tests if the cursor is currently at a headline or a plain list
8884 ;; item. If that is the case, the structure command is used,
8885 ;; temporarily setting many Org-mode variables like regular
8886 ;; expressions for filling etc. However, when any of those keys is
8887 ;; used at a different location, function uses `key-binding' to look
8888 ;; up if the key has an associated command in another currently active
8889 ;; keymap (minor modes, major mode, global), and executes that
8890 ;; command. There might be problems if any of the keys is otherwise
8891 ;; used as a prefix key.
8892
8893 (defcustom orgstruct-heading-prefix-regexp ""
8894 "Regexp that matches the custom prefix of Org headlines in
8895 orgstruct(++)-mode."
8896 :group 'org
8897 :version "24.4"
8898 :package-version '(Org . "8.3")
8899 :type 'regexp)
8900 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8901
8902 (defcustom orgstruct-setup-hook nil
8903 "Hook run after orgstruct-mode-map is filled."
8904 :group 'org
8905 :version "24.4"
8906 :package-version '(Org . "8.0")
8907 :type 'hook)
8908
8909 (defvar orgstruct-initialized nil)
8910
8911 (defvar org-local-vars nil
8912 "List of local variables, for use by `orgstruct-mode'.")
8913
8914 ;;;###autoload
8915 (define-minor-mode orgstruct-mode
8916 "Toggle the minor mode `orgstruct-mode'.
8917 This mode is for using Org-mode structure commands in other
8918 modes. The following keys behave as if Org-mode were active, if
8919 the cursor is on a headline, or on a plain list item (both as
8920 defined by Org-mode)."
8921 nil " OrgStruct" (make-sparse-keymap)
8922 (funcall (if orgstruct-mode
8923 'add-to-invisibility-spec
8924 'remove-from-invisibility-spec)
8925 '(outline . t))
8926 (when orgstruct-mode
8927 (org-load-modules-maybe)
8928 (unless orgstruct-initialized
8929 (orgstruct-setup)
8930 (setq orgstruct-initialized t))))
8931
8932 ;;;###autoload
8933 (defun turn-on-orgstruct ()
8934 "Unconditionally turn on `orgstruct-mode'."
8935 (orgstruct-mode 1))
8936
8937 (defvar org-fb-vars nil)
8938 (make-variable-buffer-local 'org-fb-vars)
8939 (defun orgstruct++-mode (&optional arg)
8940 "Toggle `orgstruct-mode', the enhanced version of it.
8941 In addition to setting orgstruct-mode, this also exports all
8942 indentation and autofilling variables from org-mode into the
8943 buffer. It will also recognize item context in multiline items."
8944 (interactive "P")
8945 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8946 (if (< arg 1)
8947 (progn (orgstruct-mode -1)
8948 (mapc (lambda(v)
8949 (org-set-local (car v)
8950 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8951 org-fb-vars))
8952 (orgstruct-mode 1)
8953 (setq org-fb-vars nil)
8954 (unless org-local-vars
8955 (setq org-local-vars (org-get-local-variables)))
8956 (let (var val)
8957 (mapc
8958 (lambda (x)
8959 (when (string-match
8960 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8961 (symbol-name (car x)))
8962 (setq var (car x) val (nth 1 x))
8963 (push (list var `(quote ,(eval var))) org-fb-vars)
8964 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8965 org-local-vars)
8966 (org-set-local 'orgstruct-is-++ t))))
8967
8968 (defvar orgstruct-is-++ nil
8969 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8970 (make-variable-buffer-local 'orgstruct-is-++)
8971
8972 ;;;###autoload
8973 (defun turn-on-orgstruct++ ()
8974 "Unconditionally turn on `orgstruct++-mode'."
8975 (orgstruct++-mode 1))
8976
8977 (defun orgstruct-error ()
8978 "Error when there is no default binding for a structure key."
8979 (interactive)
8980 (funcall (if (fboundp 'user-error)
8981 'user-error
8982 'error)
8983 "This key has no function outside structure elements"))
8984
8985 (defun orgstruct-setup ()
8986 "Setup orgstruct keymap."
8987 (dolist (cell '((org-demote . t)
8988 (org-metaleft . t)
8989 (org-metaright . t)
8990 (org-promote . t)
8991 (org-shiftmetaleft . t)
8992 (org-shiftmetaright . t)
8993 org-backward-element
8994 org-backward-heading-same-level
8995 org-ctrl-c-ret
8996 org-ctrl-c-minus
8997 org-ctrl-c-star
8998 org-cycle
8999 org-forward-heading-same-level
9000 org-insert-heading
9001 org-insert-heading-respect-content
9002 org-kill-note-or-show-branches
9003 org-mark-subtree
9004 org-meta-return
9005 org-metadown
9006 org-metaup
9007 org-narrow-to-subtree
9008 org-promote-subtree
9009 org-reveal
9010 org-shiftdown
9011 org-shiftleft
9012 org-shiftmetadown
9013 org-shiftmetaup
9014 org-shiftright
9015 org-shifttab
9016 org-shifttab
9017 org-shiftup
9018 org-show-subtree
9019 org-sort
9020 org-up-element
9021 outline-demote
9022 outline-next-visible-heading
9023 outline-previous-visible-heading
9024 outline-promote
9025 outline-up-heading
9026 show-children))
9027 (let ((f (or (car-safe cell) cell))
9028 (disable-when-heading-prefix (cdr-safe cell)))
9029 (when (fboundp f)
9030 (let ((new-bindings))
9031 (dolist (binding (nconc (where-is-internal f org-mode-map)
9032 (where-is-internal f outline-mode-map)))
9033 (push binding new-bindings)
9034 ;; TODO use local-function-key-map
9035 (dolist (rep '(("<tab>" . "TAB")
9036 ("<return>" . "RET")
9037 ("<escape>" . "ESC")
9038 ("<delete>" . "DEL")))
9039 (setq binding (read-kbd-macro
9040 (let ((case-fold-search))
9041 (replace-regexp-in-string
9042 (regexp-quote (cdr rep))
9043 (car rep)
9044 (key-description binding)))))
9045 (pushnew binding new-bindings :test 'equal)))
9046 (dolist (binding new-bindings)
9047 (let ((key (lookup-key orgstruct-mode-map binding)))
9048 (when (or (not key) (numberp key))
9049 (condition-case nil
9050 (org-defkey orgstruct-mode-map
9051 binding
9052 (orgstruct-make-binding f binding disable-when-heading-prefix))
9053 (error nil)))))))))
9054 (run-hooks 'orgstruct-setup-hook))
9055
9056 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9057 "Create a function for binding in the structure minor mode.
9058 FUN is the command to call inside a table. KEY is the key that
9059 should be checked in for a command to execute outside of tables.
9060 Non-nil `disable-when-heading-prefix' means to disable the command
9061 if `orgstruct-heading-prefix-regexp' is not empty."
9062 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9063 (let ((nname name)
9064 (i 0))
9065 (while (fboundp (intern nname))
9066 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9067 (setq name (intern nname)))
9068 (eval
9069 (let ((bindings '((org-heading-regexp
9070 (concat "^"
9071 orgstruct-heading-prefix-regexp
9072 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9073 (org-outline-regexp
9074 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9075 (org-outline-regexp-bol
9076 (concat "^" org-outline-regexp))
9077 (outline-regexp org-outline-regexp)
9078 (outline-heading-end-regexp "\n")
9079 (outline-level 'org-outline-level)
9080 (outline-heading-alist))))
9081 `(defun ,name (arg)
9082 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9083 "Outside of structure, run the binding of `"
9084 (key-description key) "'."
9085 (when disable-when-heading-prefix
9086 (concat
9087 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9088 "back to the default binding due to limitations of Org's implementation of\n"
9089 "`" (symbol-name fun) "'.")))
9090 (interactive "p")
9091 (let* ((disable
9092 ,(and disable-when-heading-prefix
9093 '(not (string= orgstruct-heading-prefix-regexp ""))))
9094 (fallback
9095 (or disable
9096 (not
9097 (let* ,bindings
9098 (org-context-p 'headline 'item
9099 ,(when (memq fun
9100 '(org-insert-heading
9101 org-insert-heading-respect-content
9102 org-meta-return))
9103 '(when orgstruct-is-++
9104 'item-body))))))))
9105 (if fallback
9106 (let* ((orgstruct-mode)
9107 (binding
9108 (let ((key ,key))
9109 (catch 'exit
9110 (dolist
9111 (rep
9112 '(nil
9113 ("<\\([^>]*\\)tab>" . "\\1TAB")
9114 ("<\\([^>]*\\)return>" . "\\1RET")
9115 ("<\\([^>]*\\)escape>" . "\\1ESC")
9116 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9117 nil)
9118 (when rep
9119 (setq key (read-kbd-macro
9120 (let ((case-fold-search))
9121 (replace-regexp-in-string
9122 (car rep)
9123 (cdr rep)
9124 (key-description key))))))
9125 (when (key-binding key)
9126 (throw 'exit (key-binding key))))))))
9127 (if (keymapp binding)
9128 (org-set-transient-map binding)
9129 (let ((func (or binding
9130 (unless disable
9131 'orgstruct-error))))
9132 (when func
9133 (call-interactively func)))))
9134 (org-run-like-in-org-mode
9135 (lambda ()
9136 (interactive)
9137 (let* ,bindings
9138 (call-interactively ',fun)))))))))
9139 name))
9140
9141 (defun org-contextualize-keys (alist contexts)
9142 "Return valid elements in ALIST depending on CONTEXTS.
9143
9144 `org-agenda-custom-commands' or `org-capture-templates' are the
9145 values used for ALIST, and `org-agenda-custom-commands-contexts'
9146 or `org-capture-templates-contexts' are the associated contexts
9147 definitions."
9148 (let ((contexts
9149 ;; normalize contexts
9150 (mapcar
9151 (lambda(c) (cond ((listp (cadr c))
9152 (list (car c) (car c) (cadr c)))
9153 ((string= "" (cadr c))
9154 (list (car c) (car c) (caddr c)))
9155 (t c)))
9156 contexts))
9157 (a alist) r s)
9158 ;; loop over all commands or templates
9159 (dolist (c a)
9160 (let (vrules repl)
9161 (cond
9162 ((not (assoc (car c) contexts))
9163 (push c r))
9164 ((and (assoc (car c) contexts)
9165 (setq vrules (org-contextualize-validate-key
9166 (car c) contexts)))
9167 (mapc (lambda (vr)
9168 (when (not (equal (car vr) (cadr vr)))
9169 (setq repl vr)))
9170 vrules)
9171 (if (not repl) (push c r)
9172 (push (cadr repl) s)
9173 (push
9174 (cons (car c)
9175 (cdr (or (assoc (cadr repl) alist)
9176 (error "Undefined key `%s' as contextual replacement for `%s'"
9177 (cadr repl) (car c)))))
9178 r))))))
9179 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9180 (delq
9181 nil
9182 (delete-dups
9183 (mapcar (lambda (x)
9184 (let ((tpl (car x)))
9185 (when (not (delq
9186 nil
9187 (mapcar (lambda (y)
9188 (equal y tpl))
9189 s)))
9190 x)))
9191 (reverse r))))))
9192
9193 (defun org-contextualize-validate-key (key contexts)
9194 "Check CONTEXTS for agenda or capture KEY."
9195 (let (rr res)
9196 (dolist (r contexts)
9197 (mapc
9198 (lambda (rr)
9199 (when
9200 (and (equal key (car r))
9201 (if (functionp rr) (funcall rr)
9202 (or (and (eq (car rr) 'in-file)
9203 (buffer-file-name)
9204 (string-match (cdr rr) (buffer-file-name)))
9205 (and (eq (car rr) 'in-mode)
9206 (string-match (cdr rr) (symbol-name major-mode)))
9207 (and (eq (car rr) 'in-buffer)
9208 (string-match (cdr rr) (buffer-name)))
9209 (when (and (eq (car rr) 'not-in-file)
9210 (buffer-file-name))
9211 (not (string-match (cdr rr) (buffer-file-name))))
9212 (when (eq (car rr) 'not-in-mode)
9213 (not (string-match (cdr rr) (symbol-name major-mode))))
9214 (when (eq (car rr) 'not-in-buffer)
9215 (not (string-match (cdr rr) (buffer-name)))))))
9216 (push r res)))
9217 (car (last r))))
9218 (delete-dups (delq nil res))))
9219
9220 (defun org-context-p (&rest contexts)
9221 "Check if local context is any of CONTEXTS.
9222 Possible values in the list of contexts are `table', `headline', and `item'."
9223 (let ((pos (point)))
9224 (goto-char (point-at-bol))
9225 (prog1 (or (and (memq 'table contexts)
9226 (looking-at "[ \t]*|"))
9227 (and (memq 'headline contexts)
9228 (looking-at org-outline-regexp))
9229 (and (memq 'item contexts)
9230 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9231 (and (memq 'item-body contexts)
9232 (org-in-item-p)))
9233 (goto-char pos))))
9234
9235 (defun org-get-local-variables ()
9236 "Return a list of all local variables in an Org mode buffer."
9237 (let (varlist)
9238 (with-current-buffer (get-buffer-create "*Org tmp*")
9239 (erase-buffer)
9240 (org-mode)
9241 (setq varlist (buffer-local-variables)))
9242 (kill-buffer "*Org tmp*")
9243 (delq nil
9244 (mapcar
9245 (lambda (x)
9246 (setq x
9247 (if (symbolp x)
9248 (list x)
9249 (list (car x) (cdr x))))
9250 (if (and (not (get (car x) 'org-state))
9251 (string-match
9252 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9253 (symbol-name (car x))))
9254 x nil))
9255 varlist))))
9256
9257 (defun org-clone-local-variables (from-buffer &optional regexp)
9258 "Clone local variables from FROM-BUFFER.
9259 Optional argument REGEXP selects variables to clone."
9260 (mapc
9261 (lambda (pair)
9262 (and (symbolp (car pair))
9263 (or (null regexp)
9264 (string-match regexp (symbol-name (car pair))))
9265 (set (make-local-variable (car pair))
9266 (cdr pair))))
9267 (buffer-local-variables from-buffer)))
9268
9269 ;;;###autoload
9270 (defun org-run-like-in-org-mode (cmd)
9271 "Run a command, pretending that the current buffer is in Org-mode.
9272 This will temporarily bind local variables that are typically bound in
9273 Org-mode to the values they have in Org-mode, and then interactively
9274 call CMD."
9275 (org-load-modules-maybe)
9276 (unless org-local-vars
9277 (setq org-local-vars (org-get-local-variables)))
9278 (let (binds)
9279 (dolist (var org-local-vars)
9280 (when (or (not (boundp (car var)))
9281 (eq (symbol-value (car var))
9282 (default-value (car var))))
9283 (push (list (car var) `(quote ,(cadr var))) binds)))
9284 (eval `(let ,binds
9285 (call-interactively (quote ,cmd))))))
9286
9287 ;;;; Archiving
9288
9289 (defun org-get-category (&optional pos force-refresh)
9290 "Get the category applying to position POS."
9291 (save-match-data
9292 (if force-refresh (org-refresh-category-properties))
9293 (let ((pos (or pos (point))))
9294 (or (get-text-property pos 'org-category)
9295 (progn (org-refresh-category-properties)
9296 (get-text-property pos 'org-category))))))
9297
9298 (defun org-refresh-category-properties ()
9299 "Refresh category text properties in the buffer."
9300 (let ((case-fold-search t)
9301 (inhibit-read-only t)
9302 (def-cat (cond
9303 ((null org-category)
9304 (if buffer-file-name
9305 (file-name-sans-extension
9306 (file-name-nondirectory buffer-file-name))
9307 "???"))
9308 ((symbolp org-category) (symbol-name org-category))
9309 (t org-category)))
9310 beg end cat pos optionp)
9311 (org-with-silent-modifications
9312 (save-excursion
9313 (save-restriction
9314 (widen)
9315 (goto-char (point-min))
9316 (put-text-property (point) (point-max) 'org-category def-cat)
9317 (while (re-search-forward
9318 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9319 (setq pos (match-end 0)
9320 optionp (equal (char-after (match-beginning 0)) ?#)
9321 cat (org-trim (match-string 2)))
9322 (if optionp
9323 (setq beg (point-at-bol) end (point-max))
9324 (org-back-to-heading t)
9325 (setq beg (point) end (org-end-of-subtree t t)))
9326 (put-text-property beg end 'org-category cat)
9327 (put-text-property beg end 'org-category-position beg)
9328 (goto-char pos)))))))
9329
9330 (defun org-refresh-properties (dprop tprop)
9331 "Refresh buffer text properties.
9332 DPROP is the drawer property and TPROP is the corresponding text
9333 property to set."
9334 (let ((case-fold-search t)
9335 (inhibit-read-only t) p)
9336 (org-with-silent-modifications
9337 (save-excursion
9338 (save-restriction
9339 (widen)
9340 (goto-char (point-min))
9341 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9342 (setq p (org-match-string-no-properties 1))
9343 (save-excursion
9344 (org-back-to-heading t)
9345 (put-text-property
9346 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9347
9348
9349 ;;;; Link Stuff
9350
9351 ;;; Link abbreviations
9352
9353 (defun org-link-expand-abbrev (link)
9354 "Apply replacements as defined in `org-link-abbrev-alist'."
9355 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9356 (let* ((key (match-string 1 link))
9357 (as (or (assoc key org-link-abbrev-alist-local)
9358 (assoc key org-link-abbrev-alist)))
9359 (tag (and (match-end 2) (match-string 3 link)))
9360 rpl)
9361 (if (not as)
9362 link
9363 (setq rpl (cdr as))
9364 (cond
9365 ((symbolp rpl) (funcall rpl tag))
9366 ((string-match "%(\\([^)]+\\))" rpl)
9367 (replace-match
9368 (save-match-data
9369 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9370 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9371 ((string-match "%h" rpl)
9372 (replace-match (url-hexify-string (or tag "")) t t rpl))
9373 (t (concat rpl tag)))))
9374 link))
9375
9376 ;;; Storing and inserting links
9377
9378 (defvar org-insert-link-history nil
9379 "Minibuffer history for links inserted with `org-insert-link'.")
9380
9381 (defvar org-stored-links nil
9382 "Contains the links stored with `org-store-link'.")
9383
9384 (defvar org-store-link-plist nil
9385 "Plist with info about the most recently link created with `org-store-link'.")
9386
9387 (defvar org-link-protocols nil
9388 "Link protocols added to Org-mode using `org-add-link-type'.")
9389
9390 (defvar org-store-link-functions nil
9391 "List of functions that are called to create and store a link.
9392 Each function will be called in turn until one returns a non-nil
9393 value. Each function should check if it is responsible for creating
9394 this link (for example by looking at the major mode).
9395 If not, it must exit and return nil.
9396 If yes, it should return a non-nil value after a calling
9397 `org-store-link-props' with a list of properties and values.
9398 Special properties are:
9399
9400 :type The link prefix, like \"http\". This must be given.
9401 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9402 This is obligatory as well.
9403 :description Optional default description for the second pair
9404 of brackets in an Org-mode link. The user can still change
9405 this when inserting this link into an Org-mode buffer.
9406
9407 In addition to these, any additional properties can be specified
9408 and then used in capture templates.")
9409
9410 (defun org-add-link-type (type &optional follow export)
9411 "Add TYPE to the list of `org-link-types'.
9412 Re-compute all regular expressions depending on `org-link-types'
9413
9414 FOLLOW and EXPORT are two functions.
9415
9416 FOLLOW should take the link path as the single argument and do whatever
9417 is necessary to follow the link, for example find a file or display
9418 a mail message.
9419
9420 EXPORT should format the link path for export to one of the export formats.
9421 It should be a function accepting three arguments:
9422
9423 path the path of the link, the text after the prefix (like \"http:\")
9424 desc the description of the link, if any, or a description added by
9425 org-export-normalize-links if there is none
9426 format the export format, a symbol like `html' or `latex' or `ascii'..
9427
9428 The function may use the FORMAT information to return different values
9429 depending on the format. The return value will be put literally into
9430 the exported file. If the return value is nil, this means Org should
9431 do what it normally does with links which do not have EXPORT defined.
9432
9433 Org-mode has a built-in default for exporting links. If you are happy with
9434 this default, there is no need to define an export function for the link
9435 type. For a simple example of an export function, see `org-bbdb.el'."
9436 (add-to-list 'org-link-types type t)
9437 (org-make-link-regexps)
9438 (if (assoc type org-link-protocols)
9439 (setcdr (assoc type org-link-protocols) (list follow export))
9440 (push (list type follow export) org-link-protocols)))
9441
9442 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9443 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9444
9445 ;;;###autoload
9446 (defun org-store-link (arg)
9447 "\\<org-mode-map>Store an org-link to the current location.
9448 This link is added to `org-stored-links' and can later be inserted
9449 into an org-buffer with \\[org-insert-link].
9450
9451 For some link types, a prefix arg is interpreted.
9452 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9453 For file links, arg negates `org-context-in-file-links'.
9454
9455 A double prefix arg force skipping storing functions that are not
9456 part of Org's core.
9457
9458 A triple prefix arg force storing a link for each line in the
9459 active region."
9460 (interactive "P")
9461 (org-load-modules-maybe)
9462 (if (and (equal arg '(64)) (org-region-active-p))
9463 (save-excursion
9464 (let ((end (region-end)))
9465 (goto-char (region-beginning))
9466 (set-mark (point))
9467 (while (< (point-at-eol) end)
9468 (move-end-of-line 1) (activate-mark)
9469 (let (current-prefix-arg)
9470 (call-interactively 'org-store-link))
9471 (move-beginning-of-line 2)
9472 (set-mark (point)))))
9473 (org-with-limited-levels
9474 (setq org-store-link-plist nil)
9475 (let (link cpltxt desc description search
9476 txt custom-id agenda-link sfuns sfunsn)
9477 (cond
9478
9479 ;; Store a link using an external link type
9480 ((and (not (equal arg '(16)))
9481 (setq sfuns
9482 (delq
9483 nil (mapcar (lambda (f)
9484 (let (fs) (if (funcall f) (push f fs))))
9485 org-store-link-functions))
9486 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9487 (or (and (cdr sfuns)
9488 (funcall (intern
9489 (completing-read
9490 "Which function for creating the link? "
9491 sfunsn nil t (car sfunsn)))))
9492 (funcall (caar sfuns)))
9493 (setq link (plist-get org-store-link-plist :link)
9494 desc (or (plist-get org-store-link-plist
9495 :description)
9496 link))))
9497
9498 ;; Store a link from a source code buffer
9499 ((org-src-edit-buffer-p)
9500 (let (label gc)
9501 (while (or (not label)
9502 (save-excursion
9503 (save-restriction
9504 (widen)
9505 (goto-char (point-min))
9506 (re-search-forward
9507 (regexp-quote (format org-coderef-label-format label))
9508 nil t))))
9509 (when label (message "Label exists already") (sit-for 2))
9510 (setq label (read-string "Code line label: " label)))
9511 (end-of-line 1)
9512 (setq link (format org-coderef-label-format label))
9513 (setq gc (- 79 (length link)))
9514 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9515 (insert link)
9516 (setq link (concat "(" label ")") desc nil)))
9517
9518 ;; We are in the agenda, link to referenced location
9519 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9520 (let ((m (or (get-text-property (point) 'org-hd-marker)
9521 (get-text-property (point) 'org-marker))))
9522 (when m
9523 (org-with-point-at m
9524 (setq agenda-link
9525 (if (org-called-interactively-p 'any)
9526 (call-interactively 'org-store-link)
9527 (org-store-link nil)))))))
9528
9529 ((eq major-mode 'calendar-mode)
9530 (let ((cd (calendar-cursor-to-date)))
9531 (setq link
9532 (format-time-string
9533 (car org-time-stamp-formats)
9534 (apply 'encode-time
9535 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9536 nil nil nil))))
9537 (org-store-link-props :type "calendar" :date cd)))
9538
9539 ((eq major-mode 'help-mode)
9540 (setq link (concat "help:" (save-excursion
9541 (goto-char (point-min))
9542 (looking-at "^[^ ]+")
9543 (match-string 0))))
9544 (org-store-link-props :type "help"))
9545
9546 ((eq major-mode 'w3-mode)
9547 (setq cpltxt (if (and (buffer-name)
9548 (not (string-match "Untitled" (buffer-name))))
9549 (buffer-name)
9550 (url-view-url t))
9551 link (url-view-url t))
9552 (org-store-link-props :type "w3" :url (url-view-url t)))
9553
9554 ((eq major-mode 'image-mode)
9555 (setq cpltxt (concat "file:"
9556 (abbreviate-file-name buffer-file-name))
9557 link cpltxt)
9558 (org-store-link-props :type "image" :file buffer-file-name))
9559
9560 ;; In dired, store a link to the file of the current line
9561 ((eq major-mode 'dired-mode)
9562 (let ((file (dired-get-filename nil t)))
9563 (setq file (if file
9564 (abbreviate-file-name
9565 (expand-file-name (dired-get-filename nil t)))
9566 ;; otherwise, no file so use current directory.
9567 default-directory))
9568 (setq cpltxt (concat "file:" file)
9569 link cpltxt)))
9570
9571 ((setq search (run-hook-with-args-until-success
9572 'org-create-file-search-functions))
9573 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9574 "::" search))
9575 (setq cpltxt (or description link)))
9576
9577 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9578 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9579 (cond
9580 ;; Store a link using the target at point
9581 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9582 (setq cpltxt
9583 (concat "file:"
9584 (abbreviate-file-name
9585 (buffer-file-name (buffer-base-buffer)))
9586 "::" (match-string 1))
9587 link cpltxt))
9588 ((and (featurep 'org-id)
9589 (or (eq org-id-link-to-org-use-id t)
9590 (and (org-called-interactively-p 'any)
9591 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9592 (and (eq org-id-link-to-org-use-id
9593 'create-if-interactive-and-no-custom-id)
9594 (not custom-id))))
9595 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9596 ;; Store a link using the ID at point
9597 (setq link (condition-case nil
9598 (prog1 (org-id-store-link)
9599 (setq desc (or (plist-get org-store-link-plist
9600 :description)
9601 "")))
9602 (error
9603 ;; Probably before first headline, link only to file
9604 (concat "file:"
9605 (abbreviate-file-name
9606 (buffer-file-name (buffer-base-buffer))))))))
9607 (t
9608 ;; Just link to current headline
9609 (setq cpltxt (concat "file:"
9610 (abbreviate-file-name
9611 (buffer-file-name (buffer-base-buffer)))))
9612 ;; Add a context search string
9613 (when (org-xor org-context-in-file-links arg)
9614 (let* ((ee (org-element-at-point))
9615 (et (org-element-type ee))
9616 (ev (plist-get (cadr ee) :value))
9617 (ek (plist-get (cadr ee) :key))
9618 (eok (and (stringp ek) (string-match "name" ek))))
9619 (setq txt (cond
9620 ((org-at-heading-p) nil)
9621 ((and (eq et 'keyword) eok) ev)
9622 ((org-region-active-p)
9623 (buffer-substring (region-beginning) (region-end)))))
9624 (when (or (null txt) (string-match "\\S-" txt))
9625 (setq cpltxt
9626 (concat cpltxt "::"
9627 (condition-case nil
9628 (org-make-org-heading-search-string txt)
9629 (error "")))
9630 desc (or (and (eq et 'keyword) eok ev)
9631 (nth 4 (ignore-errors (org-heading-components)))
9632 "NONE")))))
9633 (if (string-match "::\\'" cpltxt)
9634 (setq cpltxt (substring cpltxt 0 -2)))
9635 (setq link cpltxt))))
9636
9637 ((buffer-file-name (buffer-base-buffer))
9638 ;; Just link to this file here.
9639 (setq cpltxt (concat "file:"
9640 (abbreviate-file-name
9641 (buffer-file-name (buffer-base-buffer)))))
9642 ;; Add a context string.
9643 (when (org-xor org-context-in-file-links arg)
9644 (setq txt (if (org-region-active-p)
9645 (buffer-substring (region-beginning) (region-end))
9646 (buffer-substring (point-at-bol) (point-at-eol))))
9647 ;; Only use search option if there is some text.
9648 (when (string-match "\\S-" txt)
9649 (setq cpltxt
9650 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9651 desc "NONE")))
9652 (setq link cpltxt))
9653
9654 ((org-called-interactively-p 'interactive)
9655 (user-error "No method for storing a link from this buffer"))
9656
9657 (t (setq link nil)))
9658
9659 ;; We're done setting link and desc, clean up
9660 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9661 (setq link (or link cpltxt)
9662 desc (or desc cpltxt))
9663 (cond ((equal desc "NONE") (setq desc nil))
9664 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9665 (let ((d0 (match-string 3 desc))
9666 (p0 (match-string 5 desc)))
9667 (setq desc
9668 (replace-regexp-in-string
9669 org-bracket-link-regexp
9670 (concat (or p0 d0)
9671 (if (equal (length (match-string 0 desc))
9672 (length desc)) "*" "")) desc)))))
9673
9674 ;; Return the link
9675 (if (not (and (or (org-called-interactively-p 'any)
9676 executing-kbd-macro)
9677 link))
9678 (or agenda-link (and link (org-make-link-string link desc)))
9679 (push (list link desc) org-stored-links)
9680 (message "Stored: %s" (or desc link))
9681 (when custom-id
9682 (setq link (concat "file:" (abbreviate-file-name
9683 (buffer-file-name)) "::#" custom-id))
9684 (push (list link desc) org-stored-links))
9685 (car org-stored-links))))))
9686
9687 (defun org-store-link-props (&rest plist)
9688 "Store link properties, extract names and addresses."
9689 (let (x adr)
9690 (when (setq x (plist-get plist :from))
9691 (setq adr (mail-extract-address-components x))
9692 (setq plist (plist-put plist :fromname (car adr)))
9693 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9694 (when (setq x (plist-get plist :to))
9695 (setq adr (mail-extract-address-components x))
9696 (setq plist (plist-put plist :toname (car adr)))
9697 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9698 (let ((from (plist-get plist :from))
9699 (to (plist-get plist :to)))
9700 (when (and from to org-from-is-user-regexp)
9701 (setq plist
9702 (plist-put plist :fromto
9703 (if (string-match org-from-is-user-regexp from)
9704 (concat "to %t")
9705 (concat "from %f"))))))
9706 (setq org-store-link-plist plist))
9707
9708 (defun org-add-link-props (&rest plist)
9709 "Add these properties to the link property list."
9710 (let (key value)
9711 (while plist
9712 (setq key (pop plist) value (pop plist))
9713 (setq org-store-link-plist
9714 (plist-put org-store-link-plist key value)))))
9715
9716 (defun org-email-link-description (&optional fmt)
9717 "Return the description part of an email link.
9718 This takes information from `org-store-link-plist' and formats it
9719 according to FMT (default from `org-email-link-description-format')."
9720 (setq fmt (or fmt org-email-link-description-format))
9721 (let* ((p org-store-link-plist)
9722 (to (plist-get p :toaddress))
9723 (from (plist-get p :fromaddress))
9724 (table
9725 (list
9726 (cons "%c" (plist-get p :fromto))
9727 (cons "%F" (plist-get p :from))
9728 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9729 (cons "%T" (plist-get p :to))
9730 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9731 (cons "%s" (plist-get p :subject))
9732 (cons "%d" (plist-get p :date))
9733 (cons "%m" (plist-get p :message-id)))))
9734 (when (string-match "%c" fmt)
9735 ;; Check if the user wrote this message
9736 (if (and org-from-is-user-regexp from to
9737 (save-match-data (string-match org-from-is-user-regexp from)))
9738 (setq fmt (replace-match "to %t" t t fmt))
9739 (setq fmt (replace-match "from %f" t t fmt))))
9740 (org-replace-escapes fmt table)))
9741
9742 (defun org-make-org-heading-search-string (&optional string)
9743 "Make search string for the current headline or STRING."
9744 (let ((s (or string
9745 (and (derived-mode-p 'org-mode)
9746 (save-excursion
9747 (org-back-to-heading t)
9748 (org-element-property :raw-value (org-element-at-point))))))
9749 (lines org-context-in-file-links))
9750 (or string (setq s (concat "*" s))) ; Add * for headlines
9751 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9752 (when (and string (integerp lines) (> lines 0))
9753 (let ((slines (org-split-string s "\n")))
9754 (when (< lines (length slines))
9755 (setq s (mapconcat
9756 'identity
9757 (reverse (nthcdr (- (length slines) lines)
9758 (reverse slines))) "\n")))))
9759 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9760
9761 (defun org-make-link-string (link &optional description)
9762 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9763 (unless (string-match "\\S-" link)
9764 (error "Empty link"))
9765 (when (and description
9766 (stringp description)
9767 (not (string-match "\\S-" description)))
9768 (setq description nil))
9769 (when (stringp description)
9770 ;; Remove brackets from the description, they are fatal.
9771 (while (string-match "\\[" description)
9772 (setq description (replace-match "{" t t description)))
9773 (while (string-match "\\]" description)
9774 (setq description (replace-match "}" t t description))))
9775 (when (equal link description)
9776 ;; No description needed, it is identical
9777 (setq description nil))
9778 (when (and (not description)
9779 (not (string-match (org-image-file-name-regexp) link))
9780 (not (equal link (org-link-escape link))))
9781 (setq description (org-extract-attributes link)))
9782 (setq link
9783 (cond ((string-match (org-image-file-name-regexp) link) link)
9784 ((string-match org-link-types-re link)
9785 (concat (match-string 1 link)
9786 (org-link-escape (substring link (match-end 1)))))
9787 (t (org-link-escape link))))
9788 (concat "[[" link "]"
9789 (if description (concat "[" description "]") "")
9790 "]"))
9791
9792 (defconst org-link-escape-chars
9793 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9794 "List of characters that should be escaped in link.
9795 This is the list that is used for internal purposes.")
9796
9797 (defconst org-link-escape-chars-browser
9798 '(?\ ?\")
9799 "List of escapes for characters that are problematic in links.
9800 This is the list that is used before handing over to the browser.")
9801
9802 (defun org-link-escape (text &optional table merge)
9803 "Return percent escaped representation of TEXT.
9804 TEXT is a string with the text to escape.
9805 Optional argument TABLE is a list with characters that should be
9806 escaped. When nil, `org-link-escape-chars' is used.
9807 If optional argument MERGE is set, merge TABLE into
9808 `org-link-escape-chars'."
9809 (cond
9810 ((and table merge)
9811 (mapc (lambda (defchr)
9812 (unless (member defchr table)
9813 (setq table (cons defchr table)))) org-link-escape-chars))
9814 ((null table)
9815 (setq table org-link-escape-chars)))
9816 (mapconcat
9817 (lambda (char)
9818 (if (or (member char table)
9819 (and (or (< char 32) (= char 37) (> char 126))
9820 org-url-hexify-p))
9821 (mapconcat (lambda (sequence-element)
9822 (format "%%%.2X" sequence-element))
9823 (or (encode-coding-char char 'utf-8)
9824 (error "Unable to percent escape character: %s"
9825 (char-to-string char))) "")
9826 (char-to-string char))) text ""))
9827
9828 (defun org-link-unescape (str)
9829 "Unhex hexified Unicode strings as returned from the JavaScript function
9830 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9831 (unless (and (null str) (string= "" str))
9832 (let ((pos 0) (case-fold-search t) unhexed)
9833 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9834 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9835 (setq str (replace-match unhexed t t str))
9836 (setq pos (+ pos (length unhexed))))))
9837 str)
9838
9839 (defun org-link-unescape-compound (hex)
9840 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9841 Note: this function also decodes single byte encodings like
9842 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9843 (save-match-data
9844 (let* ((bytes (cdr (split-string hex "%")))
9845 (ret "")
9846 (eat 0)
9847 (sum 0))
9848 (while bytes
9849 (let* ((val (string-to-number (pop bytes) 16))
9850 (shift-xor
9851 (if (= 0 eat)
9852 (cond
9853 ((>= val 252) (cons 6 252))
9854 ((>= val 248) (cons 5 248))
9855 ((>= val 240) (cons 4 240))
9856 ((>= val 224) (cons 3 224))
9857 ((>= val 192) (cons 2 192))
9858 (t (cons 0 0)))
9859 (cons 6 128))))
9860 (if (>= val 192) (setq eat (car shift-xor)))
9861 (setq val (logxor val (cdr shift-xor)))
9862 (setq sum (+ (lsh sum (car shift-xor)) val))
9863 (if (> eat 0) (setq eat (- eat 1)))
9864 (cond
9865 ((= 0 eat) ;multi byte
9866 (setq ret (concat ret (org-char-to-string sum)))
9867 (setq sum 0))
9868 ((not bytes) ; single byte(s)
9869 (setq ret (org-link-unescape-single-byte-sequence hex))))
9870 )) ;; end (while bytes
9871 ret )))
9872
9873 (defun org-link-unescape-single-byte-sequence (hex)
9874 "Unhexify hex-encoded single byte character sequences."
9875 (mapconcat (lambda (byte)
9876 (char-to-string (string-to-number byte 16)))
9877 (cdr (split-string hex "%")) ""))
9878
9879 (defun org-xor (a b)
9880 "Exclusive or."
9881 (if a (not b) b))
9882
9883 (defun org-fixup-message-id-for-http (s)
9884 "Replace special characters in a message id, so it can be used in an http query."
9885 (when (string-match "%" s)
9886 (setq s (mapconcat (lambda (c)
9887 (if (eq c ?%)
9888 "%25"
9889 (char-to-string c)))
9890 s "")))
9891 (while (string-match "<" s)
9892 (setq s (replace-match "%3C" t t s)))
9893 (while (string-match ">" s)
9894 (setq s (replace-match "%3E" t t s)))
9895 (while (string-match "@" s)
9896 (setq s (replace-match "%40" t t s)))
9897 s)
9898
9899 (defun org-link-prettify (link)
9900 "Return a human-readable representation of LINK.
9901 The car of LINK must be a raw link the cdr of LINK must be either
9902 a link description or nil."
9903 (let ((desc (or (cadr link) "<no description>")))
9904 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9905 "<" (car link) ">")))
9906
9907 ;;;###autoload
9908 (defun org-insert-link-global ()
9909 "Insert a link like Org-mode does.
9910 This command can be called in any mode to insert a link in Org-mode syntax."
9911 (interactive)
9912 (org-load-modules-maybe)
9913 (org-run-like-in-org-mode 'org-insert-link))
9914
9915 (defun org-insert-all-links (&optional keep)
9916 "Insert all links in `org-stored-links'."
9917 (interactive "P")
9918 (let ((links (copy-sequence org-stored-links)) l)
9919 (while (setq l (if keep (pop links) (pop org-stored-links)))
9920 (insert "- ")
9921 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9922 (insert "\n"))))
9923
9924 (defun org-link-fontify-links-to-this-file ()
9925 "Fontify links to the current file in `org-stored-links'."
9926 (let ((f (buffer-file-name)) a b)
9927 (setq a (mapcar (lambda(l)
9928 (let ((ll (car l)))
9929 (when (and (string-match "^file:\\(.+\\)::" ll)
9930 (equal f (expand-file-name (match-string 1 ll))))
9931 ll)))
9932 org-stored-links))
9933 (when (featurep 'org-id)
9934 (setq b (mapcar (lambda(l)
9935 (let ((ll (car l)))
9936 (when (and (string-match "^id:\\(.+\\)$" ll)
9937 (equal f (expand-file-name
9938 (or (org-id-find-id-file
9939 (match-string 1 ll)) ""))))
9940 ll)))
9941 org-stored-links)))
9942 (mapcar (lambda(l)
9943 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9944 (delq nil (append a b)))))
9945
9946 (defvar org-link-links-in-this-file nil)
9947 (defun org-insert-link (&optional complete-file link-location default-description)
9948 "Insert a link. At the prompt, enter the link.
9949
9950 Completion can be used to insert any of the link protocol prefixes like
9951 http or ftp in use.
9952
9953 The history can be used to select a link previously stored with
9954 `org-store-link'. When the empty string is entered (i.e. if you just
9955 press RET at the prompt), the link defaults to the most recently
9956 stored link. As SPC triggers completion in the minibuffer, you need to
9957 use M-SPC or C-q SPC to force the insertion of a space character.
9958
9959 You will also be prompted for a description, and if one is given, it will
9960 be displayed in the buffer instead of the link.
9961
9962 If there is already a link at point, this command will allow you to edit link
9963 and description parts.
9964
9965 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9966 be selected using completion. The path to the file will be relative to the
9967 current directory if the file is in the current directory or a subdirectory.
9968 Otherwise, the link will be the absolute path as completed in the minibuffer
9969 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9970 option `org-link-file-path-type'.
9971
9972 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9973 the current directory or below.
9974
9975 With three \\[universal-argument] prefixes, negate the meaning of
9976 `org-keep-stored-link-after-insertion'.
9977
9978 If `org-make-link-description-function' is non-nil, this function will be
9979 called with the link target, and the result will be the default
9980 link description.
9981
9982 If the LINK-LOCATION parameter is non-nil, this value will be
9983 used as the link location instead of reading one interactively.
9984
9985 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9986 be used as the default description."
9987 (interactive "P")
9988 (let* ((wcf (current-window-configuration))
9989 (origbuf (current-buffer))
9990 (region (if (org-region-active-p)
9991 (buffer-substring (region-beginning) (region-end))))
9992 (remove (and region (list (region-beginning) (region-end))))
9993 (desc region)
9994 tmphist ; byte-compile incorrectly complains about this
9995 (link link-location)
9996 (abbrevs org-link-abbrev-alist-local)
9997 entry file all-prefixes auto-desc)
9998 (cond
9999 (link-location) ; specified by arg, just use it.
10000 ((org-in-regexp org-bracket-link-regexp 1)
10001 ;; We do have a link at point, and we are going to edit it.
10002 (setq remove (list (match-beginning 0) (match-end 0)))
10003 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10004 (setq link (read-string "Link: "
10005 (org-link-unescape
10006 (org-match-string-no-properties 1)))))
10007 ((or (org-in-regexp org-angle-link-re)
10008 (org-in-regexp org-plain-link-re))
10009 ;; Convert to bracket link
10010 (setq remove (list (match-beginning 0) (match-end 0))
10011 link (read-string "Link: "
10012 (org-remove-angle-brackets (match-string 0)))))
10013 ((member complete-file '((4) (16)))
10014 ;; Completing read for file names.
10015 (setq link (org-file-complete-link complete-file)))
10016 (t
10017 ;; Read link, with completion for stored links.
10018 (org-link-fontify-links-to-this-file)
10019 (org-switch-to-buffer-other-window "*Org Links*")
10020 (with-current-buffer "*Org Links*"
10021 (erase-buffer)
10022 (insert "Insert a link.
10023 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10024 (when org-stored-links
10025 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10026 (insert (mapconcat 'org-link-prettify
10027 (reverse org-stored-links) "\n")))
10028 (goto-char (point-min)))
10029 (let ((cw (selected-window)))
10030 (select-window (get-buffer-window "*Org Links*" 'visible))
10031 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10032 (unless (pos-visible-in-window-p (point-max))
10033 (org-fit-window-to-buffer))
10034 (and (window-live-p cw) (select-window cw)))
10035 ;; Fake a link history, containing the stored links.
10036 (setq tmphist (append (mapcar 'car org-stored-links)
10037 org-insert-link-history))
10038 (setq all-prefixes (append (mapcar 'car abbrevs)
10039 (mapcar 'car org-link-abbrev-alist)
10040 org-link-types))
10041 (unwind-protect
10042 (progn
10043 (setq link
10044 (org-completing-read
10045 "Link: "
10046 (append
10047 (mapcar (lambda (x) (concat x ":"))
10048 all-prefixes)
10049 (mapcar 'car org-stored-links))
10050 nil nil nil
10051 'tmphist
10052 (caar org-stored-links)))
10053 (if (not (string-match "\\S-" link))
10054 (user-error "No link selected"))
10055 (mapc (lambda(l)
10056 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10057 org-stored-links)
10058 (if (or (member link all-prefixes)
10059 (and (equal ":" (substring link -1))
10060 (member (substring link 0 -1) all-prefixes)
10061 (setq link (substring link 0 -1))))
10062 (setq link (with-current-buffer origbuf
10063 (org-link-try-special-completion link)))))
10064 (set-window-configuration wcf)
10065 (kill-buffer "*Org Links*"))
10066 (setq entry (assoc link org-stored-links))
10067 (or entry (push link org-insert-link-history))
10068 (setq desc (or desc (nth 1 entry)))))
10069
10070 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10071 (not org-keep-stored-link-after-insertion))
10072 (setq org-stored-links (delq (assoc link org-stored-links)
10073 org-stored-links)))
10074
10075 (if (and (string-match org-plain-link-re link)
10076 (not (string-match org-ts-regexp link)))
10077 ;; URL-like link, normalize the use of angular brackets.
10078 (setq link (org-remove-angle-brackets link)))
10079
10080 ;; Check if we are linking to the current file with a search
10081 ;; option If yes, simplify the link by using only the search
10082 ;; option.
10083 (when (and buffer-file-name
10084 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10085 (let* ((path (match-string 1 link))
10086 (case-fold-search nil)
10087 (search (match-string 2 link)))
10088 (save-match-data
10089 (if (equal (file-truename buffer-file-name) (file-truename path))
10090 ;; We are linking to this same file, with a search option
10091 (setq link search)))))
10092
10093 ;; Check if we can/should use a relative path. If yes, simplify the link
10094 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10095 (let* ((type (match-string 1 link))
10096 (path (match-string 2 link))
10097 (origpath path)
10098 (case-fold-search nil))
10099 (cond
10100 ((or (eq org-link-file-path-type 'absolute)
10101 (equal complete-file '(16)))
10102 (setq path (abbreviate-file-name (expand-file-name path))))
10103 ((eq org-link-file-path-type 'noabbrev)
10104 (setq path (expand-file-name path)))
10105 ((eq org-link-file-path-type 'relative)
10106 (setq path (file-relative-name path)))
10107 (t
10108 (save-match-data
10109 (if (string-match (concat "^" (regexp-quote
10110 (expand-file-name
10111 (file-name-as-directory
10112 default-directory))))
10113 (expand-file-name path))
10114 ;; We are linking a file with relative path name.
10115 (setq path (substring (expand-file-name path)
10116 (match-end 0)))
10117 (setq path (abbreviate-file-name (expand-file-name path)))))))
10118 (setq link (concat type path))
10119 (if (equal desc origpath)
10120 (setq desc path))))
10121
10122 (if org-make-link-description-function
10123 (setq desc
10124 (or (condition-case nil
10125 (funcall org-make-link-description-function link desc)
10126 (error (progn (message "Can't get link description from `%s'"
10127 (symbol-name org-make-link-description-function))
10128 (sit-for 2) nil)))
10129 (read-string "Description: " default-description)))
10130 (if default-description (setq desc default-description)
10131 (setq desc (or (and auto-desc desc)
10132 (read-string "Description: " desc)))))
10133
10134 (unless (string-match "\\S-" desc) (setq desc nil))
10135 (if remove (apply 'delete-region remove))
10136 (insert (org-make-link-string link desc))))
10137
10138 (defun org-link-try-special-completion (type)
10139 "If there is completion support for link type TYPE, offer it."
10140 (let ((fun (intern (concat "org-" type "-complete-link"))))
10141 (if (functionp fun)
10142 (funcall fun)
10143 (read-string "Link (no completion support): " (concat type ":")))))
10144
10145 (defun org-file-complete-link (&optional arg)
10146 "Create a file link using completion."
10147 (let (file link)
10148 (setq file (org-iread-file-name "File: "))
10149 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10150 (pwd1 (file-name-as-directory (abbreviate-file-name
10151 (expand-file-name ".")))))
10152 (cond
10153 ((equal arg '(16))
10154 (setq link (concat
10155 "file:"
10156 (abbreviate-file-name (expand-file-name file)))))
10157 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10158 (setq link (concat "file:" (match-string 1 file))))
10159 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10160 (expand-file-name file))
10161 (setq link (concat
10162 "file:" (match-string 1 (expand-file-name file)))))
10163 (t (setq link (concat "file:" file)))))
10164 link))
10165
10166 (defun org-iread-file-name (&rest args)
10167 "Read-file-name using `ido-mode' speedup if available.
10168 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10169 See `read-file-name' for a description of parameters."
10170 (org-without-partial-completion
10171 (if (and org-completion-use-ido
10172 (fboundp 'ido-read-file-name)
10173 (boundp 'ido-mode) ido-mode
10174 (listp (second args)))
10175 (let ((ido-enter-matching-directory nil))
10176 (apply 'ido-read-file-name args))
10177 (apply 'read-file-name args))))
10178
10179 (defun org-completing-read (&rest args)
10180 "Completing-read with SPACE being a normal character."
10181 (let ((enable-recursive-minibuffers t)
10182 (minibuffer-local-completion-map
10183 (copy-keymap minibuffer-local-completion-map)))
10184 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10185 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10186 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10187 (apply 'org-icompleting-read args)))
10188
10189 (defun org-completing-read-no-i (&rest args)
10190 (let (org-completion-use-ido org-completion-use-iswitchb)
10191 (apply 'org-completing-read args)))
10192
10193 (defun org-iswitchb-completing-read (prompt choices &rest args)
10194 "Use iswitch as a completing-read replacement to choose from choices.
10195 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10196 from."
10197 (let* ((iswitchb-use-virtual-buffers nil)
10198 (iswitchb-make-buflist-hook
10199 (lambda ()
10200 (setq iswitchb-temp-buflist choices))))
10201 (iswitchb-read-buffer prompt)))
10202
10203 (defun org-icompleting-read (&rest args)
10204 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10205 (org-without-partial-completion
10206 (if (and org-completion-use-ido
10207 (fboundp 'ido-completing-read)
10208 (boundp 'ido-mode) ido-mode
10209 (listp (second args)))
10210 (let ((ido-enter-matching-directory nil))
10211 (apply 'ido-completing-read (concat (car args))
10212 (if (consp (car (nth 1 args)))
10213 (mapcar 'car (nth 1 args))
10214 (nth 1 args))
10215 (cddr args)))
10216 (if (and org-completion-use-iswitchb
10217 (boundp 'iswitchb-mode) iswitchb-mode
10218 (listp (second args)))
10219 (apply 'org-iswitchb-completing-read (concat (car args))
10220 (if (consp (car (nth 1 args)))
10221 (mapcar 'car (nth 1 args))
10222 (nth 1 args))
10223 (cddr args))
10224 (apply 'completing-read args)))))
10225
10226 (defun org-extract-attributes (s)
10227 "Extract the attributes cookie from a string and set as text property."
10228 (let (a attr (start 0) key value)
10229 (save-match-data
10230 (when (string-match "{{\\([^}]+\\)}}$" s)
10231 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10232 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10233 (setq key (match-string 1 a) value (match-string 2 a)
10234 start (match-end 0)
10235 attr (plist-put attr (intern key) value))))
10236 (org-add-props s nil 'org-attr attr))
10237 s))
10238
10239 ;;; Opening/following a link
10240
10241 (defvar org-link-search-failed nil)
10242
10243 (defvar org-open-link-functions nil
10244 "Hook for functions finding a plain text link.
10245 These functions must take a single argument, the link content.
10246 They will be called for links that look like [[link text][description]]
10247 when LINK TEXT does not have a protocol like \"http:\" and does not look
10248 like a filename (e.g. \"./blue.png\").
10249
10250 These functions will be called *before* Org attempts to resolve the
10251 link by doing text searches in the current buffer - so if you want a
10252 link \"[[target]]\" to still find \"<<target>>\", your function should
10253 handle this as a special case.
10254
10255 When the function does handle the link, it must return a non-nil value.
10256 If it decides that it is not responsible for this link, it must return
10257 nil to indicate that that Org-mode can continue with other options
10258 like exact and fuzzy text search.")
10259
10260 (defun org-next-link (&optional search-backward)
10261 "Move forward to the next link.
10262 If the link is in hidden text, expose it."
10263 (interactive "P")
10264 (when (and org-link-search-failed (eq this-command last-command))
10265 (goto-char (point-min))
10266 (message "Link search wrapped back to beginning of buffer"))
10267 (setq org-link-search-failed nil)
10268 (let* ((pos (point))
10269 (ct (org-context))
10270 (a (assoc :link ct))
10271 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10272 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10273 ((looking-at org-any-link-re)
10274 ;; Don't stay stuck at link without an org-link face
10275 (forward-char (if search-backward -1 1))))
10276 (if (funcall srch-fun org-any-link-re nil t)
10277 (progn
10278 (goto-char (match-beginning 0))
10279 (if (outline-invisible-p) (org-show-context)))
10280 (goto-char pos)
10281 (setq org-link-search-failed t)
10282 (message "No further link found"))))
10283
10284 (defun org-previous-link ()
10285 "Move backward to the previous link.
10286 If the link is in hidden text, expose it."
10287 (interactive)
10288 (funcall 'org-next-link t))
10289
10290 (defun org-translate-link (s)
10291 "Translate a link string if a translation function has been defined."
10292 (if (and org-link-translation-function
10293 (fboundp org-link-translation-function)
10294 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10295 (progn
10296 (setq s (funcall org-link-translation-function
10297 (match-string 1 s) (match-string 2 s)))
10298 (concat (car s) ":" (cdr s)))
10299 s))
10300
10301 (defun org-translate-link-from-planner (type path)
10302 "Translate a link from Emacs Planner syntax so that Org can follow it.
10303 This is still an experimental function, your mileage may vary."
10304 (cond
10305 ((member type '("http" "https" "news" "ftp"))
10306 ;; standard Internet links are the same.
10307 nil)
10308 ((and (equal type "irc") (string-match "^//" path))
10309 ;; Planner has two / at the beginning of an irc link, we have 1.
10310 ;; We should have zero, actually....
10311 (setq path (substring path 1)))
10312 ((and (equal type "lisp") (string-match "^/" path))
10313 ;; Planner has a slash, we do not.
10314 (setq type "elisp" path (substring path 1)))
10315 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10316 ;; A typical message link. Planner has the id after the final slash,
10317 ;; we separate it with a hash mark
10318 (setq path (concat (match-string 1 path) "#"
10319 (org-remove-angle-brackets (match-string 2 path))))))
10320 (cons type path))
10321
10322 (defun org-find-file-at-mouse (ev)
10323 "Open file link or URL at mouse."
10324 (interactive "e")
10325 (mouse-set-point ev)
10326 (org-open-at-point 'in-emacs))
10327
10328 (defun org-open-at-mouse (ev)
10329 "Open file link or URL at mouse.
10330 See the docstring of `org-open-file' for details."
10331 (interactive "e")
10332 (mouse-set-point ev)
10333 (if (eq major-mode 'org-agenda-mode)
10334 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10335 (org-open-at-point))
10336
10337 (defvar org-window-config-before-follow-link nil
10338 "The window configuration before following a link.
10339 This is saved in case the need arises to restore it.")
10340
10341 (defvar org-open-link-marker (make-marker)
10342 "Marker pointing to the location where `org-open-at-point' was called.")
10343
10344 ;;;###autoload
10345 (defun org-open-at-point-global ()
10346 "Follow a link like Org-mode does.
10347 This command can be called in any mode to follow a link that has
10348 Org-mode syntax."
10349 (interactive)
10350 (org-run-like-in-org-mode 'org-open-at-point))
10351
10352 ;;;###autoload
10353 (defun org-open-link-from-string (s &optional arg reference-buffer)
10354 "Open a link in the string S, as if it was in Org-mode."
10355 (interactive "sLink: \nP")
10356 (let ((reference-buffer (or reference-buffer (current-buffer))))
10357 (with-temp-buffer
10358 (let ((org-inhibit-startup (not reference-buffer)))
10359 (org-mode)
10360 (insert s)
10361 (goto-char (point-min))
10362 (when reference-buffer
10363 (setq org-link-abbrev-alist-local
10364 (with-current-buffer reference-buffer
10365 org-link-abbrev-alist-local)))
10366 (org-open-at-point arg reference-buffer)))))
10367
10368 (defvar org-open-at-point-functions nil
10369 "Hook that is run when following a link at point.
10370
10371 Functions in this hook must return t if they identify and follow
10372 a link at point. If they don't find anything interesting at point,
10373 they must return nil.")
10374
10375 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10376 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10377 (defun org-open-at-point (&optional arg reference-buffer)
10378 "Open link at or after point.
10379 If there is no link at point, this function will search forward up to
10380 the end of the current line.
10381 Normally, files will be opened by an appropriate application. If the
10382 optional prefix argument ARG is non-nil, Emacs will visit the file.
10383 With a double prefix argument, try to open outside of Emacs, in the
10384 application the system uses for this file type."
10385 (interactive "P")
10386 ;; if in a code block, then open the block's results
10387 (unless (call-interactively #'org-babel-open-src-block-result)
10388 (org-load-modules-maybe)
10389 (move-marker org-open-link-marker (point))
10390 (setq org-window-config-before-follow-link (current-window-configuration))
10391 (org-remove-occur-highlights nil nil t)
10392 (cond
10393 ((and (org-at-heading-p)
10394 (not (org-at-timestamp-p t))
10395 (not (org-in-regexp
10396 (concat org-plain-link-re "\\|"
10397 org-bracket-link-regexp "\\|"
10398 org-angle-link-re "\\|"
10399 "[ \t]:[^ \t\n]+:[ \t]*$")))
10400 (not (get-text-property (point) 'org-linked-text)))
10401 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10402 (lk0 (car lkall))
10403 (lk (if (stringp lk0) (list lk0) lk0))
10404 (lkend (cdr lkall)))
10405 (mapcar (lambda(l)
10406 (search-forward l nil lkend)
10407 (goto-char (match-beginning 0))
10408 (org-open-at-point))
10409 lk))
10410 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10411 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10412 ((and (org-at-timestamp-p t)
10413 (not (org-in-regexp org-bracket-link-regexp)))
10414 (org-follow-timestamp-link))
10415 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10416 (not (org-in-regexp org-any-link-re)))
10417 (org-footnote-action))
10418 (t
10419 (let (type path link line search (pos (point)))
10420 (catch 'match
10421 (save-excursion
10422 (or (org-in-regexp org-plain-link-re)
10423 (skip-chars-forward "^]\n\r"))
10424 (when (org-in-regexp org-bracket-link-regexp 1)
10425 (setq link (org-extract-attributes
10426 (org-link-unescape (org-match-string-no-properties 1))))
10427 (while (string-match " *\n *" link)
10428 (setq link (replace-match " " t t link)))
10429 (setq link (org-link-expand-abbrev link))
10430 (cond
10431 ((or (file-name-absolute-p link)
10432 (string-match "^\\.\\.?/" link))
10433 (setq type "file" path link))
10434 ((string-match org-link-re-with-space3 link)
10435 (setq type (match-string 1 link) path (match-string 2 link)))
10436 ((string-match "^help:+\\(.+\\)" link)
10437 (setq type "help" path (match-string 1 link)))
10438 (t (setq type "thisfile" path link)))
10439 (throw 'match t)))
10440
10441 (when (get-text-property (point) 'org-linked-text)
10442 (setq type "thisfile"
10443 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10444 (1+ (point)) (point))
10445 path (buffer-substring
10446 (or (previous-single-property-change pos 'org-linked-text)
10447 (point-min))
10448 (or (next-single-property-change pos 'org-linked-text)
10449 (point-max)))
10450 ;; Ensure we will search for a <<<radio>>> link, not
10451 ;; a simple reference like <<ref>>
10452 path (concat "<" path))
10453 (throw 'match t))
10454
10455 (save-excursion
10456 (when (or (org-in-regexp org-angle-link-re)
10457 (let ((match (org-in-regexp org-plain-link-re)))
10458 ;; Check a plain link is not within a bracket link
10459 (and match
10460 (save-excursion
10461 (save-match-data
10462 (progn
10463 (goto-char (car match))
10464 (not (org-in-regexp org-bracket-link-regexp)))))))
10465 (let ((line_ending (save-excursion (end-of-line) (point))))
10466 ;; We are in a line before a plain or bracket link
10467 (or (re-search-forward org-plain-link-re line_ending t)
10468 (re-search-forward org-bracket-link-regexp line_ending t))))
10469 (setq type (match-string 1)
10470 path (org-link-unescape (match-string 2)))
10471 (throw 'match t)))
10472 (save-excursion
10473 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10474 (setq type "tags"
10475 path (match-string 1))
10476 (while (string-match ":" path)
10477 (setq path (replace-match "+" t t path)))
10478 (throw 'match t)))
10479 (when (org-in-regexp "<\\([^><\n]+\\)>")
10480 (setq type "tree-match"
10481 path (match-string 1))
10482 (throw 'match t)))
10483 (unless path
10484 (user-error "No link found"))
10485
10486 ;; switch back to reference buffer
10487 ;; needed when if called in a temporary buffer through
10488 ;; org-open-link-from-string
10489 (with-current-buffer (or reference-buffer (current-buffer))
10490
10491 ;; Remove any trailing spaces in path
10492 (if (string-match " +\\'" path)
10493 (setq path (replace-match "" t t path)))
10494 (if (and org-link-translation-function
10495 (fboundp org-link-translation-function))
10496 ;; Check if we need to translate the link
10497 (let ((tmp (funcall org-link-translation-function type path)))
10498 (setq type (car tmp) path (cdr tmp))))
10499
10500 (cond
10501
10502 ((assoc type org-link-protocols)
10503 (funcall (nth 1 (assoc type org-link-protocols)) path))
10504
10505 ((equal type "help")
10506 (let ((f-or-v (intern path)))
10507 (cond ((fboundp f-or-v)
10508 (describe-function f-or-v))
10509 ((boundp f-or-v)
10510 (describe-variable f-or-v))
10511 (t (error "Not a known function or variable")))))
10512
10513 ((equal type "mailto")
10514 (let ((cmd (car org-link-mailto-program))
10515 (args (cdr org-link-mailto-program)) args1
10516 (address path) (subject "") a)
10517 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10518 (setq address (match-string 1 path)
10519 subject (org-link-escape (match-string 2 path))))
10520 (while args
10521 (cond
10522 ((not (stringp (car args))) (push (pop args) args1))
10523 (t (setq a (pop args))
10524 (if (string-match "%a" a)
10525 (setq a (replace-match address t t a)))
10526 (if (string-match "%s" a)
10527 (setq a (replace-match subject t t a)))
10528 (push a args1))))
10529 (apply cmd (nreverse args1))))
10530
10531 ((member type '("http" "https" "ftp" "news"))
10532 (browse-url
10533 (concat type ":"
10534 (if (org-string-match-p
10535 (concat "[[:nonascii:]"
10536 org-link-escape-chars-browser "]")
10537 path)
10538 (org-link-escape path org-link-escape-chars-browser)
10539 path))))
10540
10541 ((string= type "doi")
10542 (browse-url
10543 (concat org-doi-server-url
10544 (if (org-string-match-p
10545 (concat "[[:nonascii:]"
10546 org-link-escape-chars-browser "]")
10547 path)
10548 (org-link-escape path org-link-escape-chars-browser)
10549 path))))
10550
10551 ((member type '("message"))
10552 (browse-url (concat type ":" path)))
10553
10554 ((string= type "tags")
10555 (org-tags-view arg path))
10556
10557 ((string= type "tree-match")
10558 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10559
10560 ((string= type "file")
10561 (if (string-match "::\\([0-9]+\\)\\'" path)
10562 (setq line (string-to-number (match-string 1 path))
10563 path (substring path 0 (match-beginning 0)))
10564 (if (string-match "::\\(.+\\)\\'" path)
10565 (setq search (match-string 1 path)
10566 path (substring path 0 (match-beginning 0)))))
10567 (if (string-match "[*?{]" (file-name-nondirectory path))
10568 (dired path)
10569 (org-open-file path arg line search)))
10570
10571 ((string= type "shell")
10572 (let ((buf (generate-new-buffer "*Org Shell Output"))
10573 (cmd path))
10574 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10575 (string-match org-confirm-shell-link-not-regexp cmd))
10576 (not org-confirm-shell-link-function)
10577 (funcall org-confirm-shell-link-function
10578 (format "Execute \"%s\" in shell? "
10579 (org-add-props cmd nil
10580 'face 'org-warning))))
10581 (progn
10582 (message "Executing %s" cmd)
10583 (shell-command cmd buf)
10584 (if (featurep 'midnight)
10585 (setq clean-buffer-list-kill-buffer-names
10586 (cons buf clean-buffer-list-kill-buffer-names))))
10587 (error "Abort"))))
10588
10589 ((string= type "elisp")
10590 (let ((cmd path))
10591 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10592 (string-match org-confirm-elisp-link-not-regexp cmd))
10593 (not org-confirm-elisp-link-function)
10594 (funcall org-confirm-elisp-link-function
10595 (format "Execute \"%s\" as elisp? "
10596 (org-add-props cmd nil
10597 'face 'org-warning))))
10598 (message "%s => %s" cmd
10599 (if (equal (string-to-char cmd) ?\()
10600 (eval (read cmd))
10601 (call-interactively (read cmd))))
10602 (error "Abort"))))
10603
10604 ((and (string= type "thisfile")
10605 (or (run-hook-with-args-until-success
10606 'org-open-link-functions path)
10607 (and link
10608 (string-match "^id:" link)
10609 (or (featurep 'org-id) (require 'org-id))
10610 (progn
10611 (funcall (nth 1 (assoc "id" org-link-protocols))
10612 (substring path 3))
10613 t)))))
10614
10615 ((string= type "thisfile")
10616 (if arg
10617 (switch-to-buffer-other-window
10618 (org-get-buffer-for-internal-link (current-buffer)))
10619 (org-mark-ring-push))
10620 (let ((cmd `(org-link-search
10621 ,path
10622 ,(cond ((equal arg '(4)) ''occur)
10623 ((equal arg '(16)) ''org-occur))
10624 ,pos)))
10625 (condition-case nil (let ((org-link-search-inhibit-query t))
10626 (eval cmd))
10627 (error (progn (widen) (eval cmd))))))
10628
10629 (t (browse-url-at-point)))))))
10630 (move-marker org-open-link-marker nil)
10631 (run-hook-with-args 'org-follow-link-hook)))
10632
10633 (defsubst org-uniquify (list)
10634 "Non-destructively remove duplicate elements from LIST."
10635 (let ((res (copy-sequence list))) (delete-dups res)))
10636
10637 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10638 "Offer links in the current entry and return the selected link.
10639 If there is only one link, return it.
10640 If NTH is an integer, return the NTH link found.
10641 If ZERO is a string, check also this string for a link, and if
10642 there is one, return it."
10643 (with-current-buffer buffer
10644 (save-excursion
10645 (save-restriction
10646 (widen)
10647 (goto-char marker)
10648 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10649 "\\(" org-angle-link-re "\\)\\|"
10650 "\\(" org-plain-link-re "\\)"))
10651 (cnt ?0)
10652 (in-emacs (if (integerp nth) nil nth))
10653 have-zero end links link c)
10654 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10655 (push (match-string 0 zero) links)
10656 (setq cnt (1- cnt) have-zero t))
10657 (save-excursion
10658 (org-back-to-heading t)
10659 (setq end (save-excursion (outline-next-heading) (point)))
10660 (while (re-search-forward re end t)
10661 (push (match-string 0) links))
10662 (setq links (org-uniquify (reverse links))))
10663 (cond
10664 ((null links)
10665 (message "No links"))
10666 ((equal (length links) 1)
10667 (setq link (car links)))
10668 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10669 (setq link (nth (if have-zero nth (1- nth)) links)))
10670 (t ; we have to select a link
10671 (save-excursion
10672 (save-window-excursion
10673 (delete-other-windows)
10674 (with-output-to-temp-buffer "*Select Link*"
10675 (mapc (lambda (l)
10676 (if (not (string-match org-bracket-link-regexp l))
10677 (princ (format "[%c] %s\n" (incf cnt)
10678 (org-remove-angle-brackets l)))
10679 (if (match-end 3)
10680 (princ (format "[%c] %s (%s)\n" (incf cnt)
10681 (match-string 3 l) (match-string 1 l)))
10682 (princ (format "[%c] %s\n" (incf cnt)
10683 (match-string 1 l))))))
10684 links))
10685 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10686 (message "Select link to open, RET to open all:")
10687 (setq c (read-char-exclusive))
10688 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10689 (when (equal c ?q) (error "Abort"))
10690 (if (equal c ?\C-m)
10691 (setq link links)
10692 (setq nth (- c ?0))
10693 (if have-zero (setq nth (1+ nth)))
10694 (unless (and (integerp nth) (>= (length links) nth))
10695 (user-error "Invalid link selection"))
10696 (setq link (nth (1- nth) links)))))
10697 (cons link end))))))
10698
10699 ;; Add special file links that specify the way of opening
10700
10701 (org-add-link-type "file+sys" 'org-open-file-with-system)
10702 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10703 (defun org-open-file-with-system (path)
10704 "Open file at PATH using the system way of opening it."
10705 (org-open-file path 'system))
10706 (defun org-open-file-with-emacs (path)
10707 "Open file at PATH in Emacs."
10708 (org-open-file path 'emacs))
10709
10710
10711 ;;; File search
10712
10713 (defvar org-create-file-search-functions nil
10714 "List of functions to construct the right search string for a file link.
10715 These functions are called in turn with point at the location to
10716 which the link should point.
10717
10718 A function in the hook should first test if it would like to
10719 handle this file type, for example by checking the `major-mode'
10720 or the file extension. If it decides not to handle this file, it
10721 should just return nil to give other functions a chance. If it
10722 does handle the file, it must return the search string to be used
10723 when following the link. The search string will be part of the
10724 file link, given after a double colon, and `org-open-at-point'
10725 will automatically search for it. If special measures must be
10726 taken to make the search successful, another function should be
10727 added to the companion hook `org-execute-file-search-functions',
10728 which see.
10729
10730 A function in this hook may also use `setq' to set the variable
10731 `description' to provide a suggestion for the descriptive text to
10732 be used for this link when it gets inserted into an Org-mode
10733 buffer with \\[org-insert-link].")
10734
10735 (defvar org-execute-file-search-functions nil
10736 "List of functions to execute a file search triggered by a link.
10737
10738 Functions added to this hook must accept a single argument, the
10739 search string that was part of the file link, the part after the
10740 double colon. The function must first check if it would like to
10741 handle this search, for example by checking the `major-mode' or
10742 the file extension. If it decides not to handle this search, it
10743 should just return nil to give other functions a chance. If it
10744 does handle the search, it must return a non-nil value to keep
10745 other functions from trying.
10746
10747 Each function can access the current prefix argument through the
10748 variable `current-prefix-arg'. Note that a single prefix is used
10749 to force opening a link in Emacs, so it may be good to only use a
10750 numeric or double prefix to guide the search function.
10751
10752 In case this is needed, a function in this hook can also restore
10753 the window configuration before `org-open-at-point' was called using:
10754
10755 (set-window-configuration org-window-config-before-follow-link)")
10756
10757 (defun org-link-search (s &optional type avoid-pos stealth)
10758 "Search for a link search option.
10759 If S is surrounded by forward slashes, it is interpreted as a
10760 regular expression. In org-mode files, this will create an `org-occur'
10761 sparse tree. In ordinary files, `occur' will be used to list matches.
10762 If the current buffer is in `dired-mode', grep will be used to search
10763 in all files. If AVOID-POS is given, ignore matches near that position.
10764
10765 When optional argument STEALTH is non-nil, do not modify
10766 visibility around point, thus ignoring
10767 `org-show-hierarchy-above', `org-show-following-heading' and
10768 `org-show-siblings' variables."
10769 (let ((case-fold-search t)
10770 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10771 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10772 (append '(("") (" ") ("\t") ("\n"))
10773 org-emphasis-alist)
10774 "\\|") "\\)"))
10775 (pos (point))
10776 (pre nil) (post nil)
10777 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10778 (cond
10779 ;; First check if there are any special search functions
10780 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10781 ;; Now try the builtin stuff
10782 ((and (equal (string-to-char s0) ?#)
10783 (> (length s0) 1)
10784 (save-excursion
10785 (goto-char (point-min))
10786 (and
10787 (re-search-forward
10788 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10789 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10790 (setq type 'dedicated
10791 pos (match-beginning 0))))
10792 ;; There is an exact target for this
10793 (goto-char pos)
10794 (org-back-to-heading t)))
10795 ((save-excursion
10796 (goto-char (point-min))
10797 (and
10798 (re-search-forward
10799 (concat "<<" (regexp-quote s0) ">>") nil t)
10800 (setq type 'dedicated
10801 pos (match-beginning 0))))
10802 ;; There is an exact target for this
10803 (goto-char pos))
10804 ((save-excursion
10805 (goto-char (point-min))
10806 (and
10807 (re-search-forward
10808 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10809 (setq type 'dedicated pos (match-beginning 0))))
10810 ;; Found an element with a matching #+name affiliated keyword.
10811 (goto-char pos))
10812 ((and (string-match "^(\\(.*\\))$" s0)
10813 (save-excursion
10814 (goto-char (point-min))
10815 (and
10816 (re-search-forward
10817 (concat "[^[]" (regexp-quote
10818 (format org-coderef-label-format
10819 (match-string 1 s0))))
10820 nil t)
10821 (setq type 'dedicated
10822 pos (1+ (match-beginning 0))))))
10823 ;; There is a coderef target for this
10824 (goto-char pos))
10825 ((string-match "^/\\(.*\\)/$" s)
10826 ;; A regular expression
10827 (cond
10828 ((derived-mode-p 'org-mode)
10829 (org-occur (match-string 1 s)))
10830 (t (org-do-occur (match-string 1 s)))))
10831 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10832 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10833 (goto-char (point-min))
10834 (cond
10835 ((let (case-fold-search)
10836 (re-search-forward (format org-complex-heading-regexp-format
10837 (regexp-quote s))
10838 nil t))
10839 ;; OK, found a match
10840 (setq type 'dedicated)
10841 (goto-char (match-beginning 0)))
10842 ((and (not org-link-search-inhibit-query)
10843 (eq org-link-search-must-match-exact-headline 'query-to-create)
10844 (y-or-n-p "No match - create this as a new heading? "))
10845 (goto-char (point-max))
10846 (or (bolp) (newline))
10847 (insert "* " s "\n")
10848 (beginning-of-line 0))
10849 (t
10850 (goto-char pos)
10851 (error "No match"))))
10852 (t
10853 ;; A normal search string
10854 (when (equal (string-to-char s) ?*)
10855 ;; Anchor on headlines, post may include tags.
10856 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10857 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10858 s (substring s 1)))
10859 (remove-text-properties
10860 0 (length s)
10861 '(face nil mouse-face nil keymap nil fontified nil) s)
10862 ;; Make a series of regular expressions to find a match
10863 (setq words (org-split-string s "[ \n\r\t]+")
10864
10865 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10866 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10867 "\\)" markers)
10868 re2a_ (concat "\\(" (mapconcat 'downcase words
10869 "[ \t\r\n]+") "\\)[ \t\r\n]")
10870 re2a (concat "[ \t\r\n]" re2a_)
10871 re4_ (concat "\\(" (mapconcat 'downcase words
10872 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10873 re4 (concat "[^a-zA-Z_]" re4_)
10874
10875 re1 (concat pre re2 post)
10876 re3 (concat pre (if pre re4_ re4) post)
10877 re5 (concat pre ".*" re4)
10878 re2 (concat pre re2)
10879 re2a (concat pre (if pre re2a_ re2a))
10880 re4 (concat pre (if pre re4_ re4))
10881 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10882 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10883 re5 "\\)"))
10884 (cond
10885 ((eq type 'org-occur) (org-occur reall))
10886 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10887 (t (goto-char (point-min))
10888 (setq type 'fuzzy)
10889 (if (or (and (org-search-not-self 1 re0 nil t)
10890 (setq type 'dedicated))
10891 (org-search-not-self 1 re1 nil t)
10892 (org-search-not-self 1 re2 nil t)
10893 (org-search-not-self 1 re2a nil t)
10894 (org-search-not-self 1 re3 nil t)
10895 (org-search-not-self 1 re4 nil t)
10896 (org-search-not-self 1 re5 nil t))
10897 (goto-char (match-beginning 1))
10898 (goto-char pos)
10899 (error "No match"))))))
10900 (and (derived-mode-p 'org-mode)
10901 (not stealth)
10902 (org-show-context 'link-search))
10903 type))
10904
10905 (defun org-search-not-self (group &rest args)
10906 "Execute `re-search-forward', but only accept matches that do not
10907 enclose the position of `org-open-link-marker'."
10908 (let ((m org-open-link-marker))
10909 (catch 'exit
10910 (while (apply #'re-search-forward args)
10911 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10912 (goto-char (match-end group))
10913 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10914 (> (match-beginning 0) (marker-position m))
10915 (< (match-end 0) (marker-position m)))
10916 (save-match-data
10917 (or (not (org-in-regexp
10918 org-bracket-link-analytic-regexp 1))
10919 (not (match-end 4)) ; no description
10920 (and (<= (match-beginning 4) (point))
10921 (>= (match-end 4) (point))))))
10922 (throw 'exit (point))))))))
10923
10924 (defun org-get-buffer-for-internal-link (buffer)
10925 "Return a buffer to be used for displaying the link target of internal links."
10926 (cond
10927 ((not org-display-internal-link-with-indirect-buffer)
10928 buffer)
10929 ((string-match "(Clone)$" (buffer-name buffer))
10930 (message "Buffer is already a clone, not making another one")
10931 ;; we also do not modify visibility in this case
10932 buffer)
10933 (t ; make a new indirect buffer for displaying the link
10934 (let* ((bn (buffer-name buffer))
10935 (ibn (concat bn "(Clone)"))
10936 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10937 (with-current-buffer ib (org-overview))
10938 ib))))
10939
10940 (defun org-do-occur (regexp &optional cleanup)
10941 "Call the Emacs command `occur'.
10942 If CLEANUP is non-nil, remove the printout of the regular expression
10943 in the *Occur* buffer. This is useful if the regex is long and not useful
10944 to read."
10945 (occur regexp)
10946 (when cleanup
10947 (let ((cwin (selected-window)) win beg end)
10948 (when (setq win (get-buffer-window "*Occur*"))
10949 (select-window win))
10950 (goto-char (point-min))
10951 (when (re-search-forward "match[a-z]+" nil t)
10952 (setq beg (match-end 0))
10953 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10954 (setq end (1- (match-beginning 0)))))
10955 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10956 (goto-char (point-min))
10957 (select-window cwin))))
10958
10959 ;;; The mark ring for links jumps
10960
10961 (defvar org-mark-ring nil
10962 "Mark ring for positions before jumps in Org-mode.")
10963 (defvar org-mark-ring-last-goto nil
10964 "Last position in the mark ring used to go back.")
10965 ;; Fill and close the ring
10966 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10967 (loop for i from 1 to org-mark-ring-length do
10968 (push (make-marker) org-mark-ring))
10969 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10970 org-mark-ring)
10971
10972 (defun org-mark-ring-push (&optional pos buffer)
10973 "Put the current position or POS into the mark ring and rotate it."
10974 (interactive)
10975 (setq pos (or pos (point)))
10976 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10977 (move-marker (car org-mark-ring)
10978 (or pos (point))
10979 (or buffer (current-buffer)))
10980 (message "%s"
10981 (substitute-command-keys
10982 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10983
10984 (defun org-mark-ring-goto (&optional n)
10985 "Jump to the previous position in the mark ring.
10986 With prefix arg N, jump back that many stored positions. When
10987 called several times in succession, walk through the entire ring.
10988 Org-mode commands jumping to a different position in the current file,
10989 or to another Org-mode file, automatically push the old position
10990 onto the ring."
10991 (interactive "p")
10992 (let (p m)
10993 (if (eq last-command this-command)
10994 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10995 (setq p org-mark-ring))
10996 (setq org-mark-ring-last-goto p)
10997 (setq m (car p))
10998 (org-pop-to-buffer-same-window (marker-buffer m))
10999 (goto-char m)
11000 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11001
11002 (defun org-remove-angle-brackets (s)
11003 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11004 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11005 s)
11006 (defun org-add-angle-brackets (s)
11007 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11008 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11009 s)
11010 (defun org-remove-double-quotes (s)
11011 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11012 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11013 s)
11014
11015 ;;; Following specific links
11016
11017 (defun org-follow-timestamp-link ()
11018 "Open an agenda view for the time-stamp date/range at point."
11019 (cond
11020 ((org-at-date-range-p t)
11021 (let ((org-agenda-start-on-weekday)
11022 (t1 (match-string 1))
11023 (t2 (match-string 2)) tt1 tt2)
11024 (setq tt1 (time-to-days (org-time-string-to-time t1))
11025 tt2 (time-to-days (org-time-string-to-time t2)))
11026 (let ((org-agenda-buffer-tmp-name
11027 (format "*Org Agenda(a:%s)"
11028 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11029 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11030 ((org-at-timestamp-p t)
11031 (let ((org-agenda-buffer-tmp-name
11032 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11033 (org-agenda-list nil (time-to-days (org-time-string-to-time
11034 (substring (match-string 1) 0 10)))
11035 1)))
11036 (t (error "This should not happen"))))
11037
11038
11039 ;;; Following file links
11040 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11041 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11042 (declare-function mailcap-mime-info
11043 "mailcap" (string &optional request no-decode))
11044 (defvar org-wait nil)
11045 (defun org-open-file (path &optional in-emacs line search)
11046 "Open the file at PATH.
11047 First, this expands any special file name abbreviations. Then the
11048 configuration variable `org-file-apps' is checked if it contains an
11049 entry for this file type, and if yes, the corresponding command is launched.
11050
11051 If no application is found, Emacs simply visits the file.
11052
11053 With optional prefix argument IN-EMACS, Emacs will visit the file.
11054 With a double \\[universal-argument] \\[universal-argument] \
11055 prefix arg, Org tries to avoid opening in Emacs
11056 and to use an external application to visit the file.
11057
11058 Optional LINE specifies a line to go to, optional SEARCH a string
11059 to search for. If LINE or SEARCH is given, the file will be
11060 opened in Emacs, unless an entry from org-file-apps that makes
11061 use of groups in a regexp matches.
11062
11063 If you want to change the way frames are used when following a
11064 link, please customize `org-link-frame-setup'.
11065
11066 If the file does not exist, an error is thrown."
11067 (let* ((file (if (equal path "")
11068 buffer-file-name
11069 (substitute-in-file-name (expand-file-name path))))
11070 (file-apps (append org-file-apps (org-default-apps)))
11071 (apps (org-remove-if
11072 'org-file-apps-entry-match-against-dlink-p file-apps))
11073 (apps-dlink (org-remove-if-not
11074 'org-file-apps-entry-match-against-dlink-p file-apps))
11075 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11076 (dirp (if remp nil (file-directory-p file)))
11077 (file (if (and dirp org-open-directory-means-index-dot-org)
11078 (concat (file-name-as-directory file) "index.org")
11079 file))
11080 (a-m-a-p (assq 'auto-mode apps))
11081 (dfile (downcase file))
11082 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11083 (link (cond ((and (eq line nil)
11084 (eq search nil))
11085 file)
11086 (line
11087 (concat file "::" (number-to-string line)))
11088 (search
11089 (concat file "::" search))))
11090 (dlink (downcase link))
11091 (old-buffer (current-buffer))
11092 (old-pos (point))
11093 (old-mode major-mode)
11094 ext cmd link-match-data)
11095 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11096 (setq ext (match-string 1 dfile))
11097 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11098 (setq ext (match-string 1 dfile))))
11099 (cond
11100 ((member in-emacs '((16) system))
11101 (setq cmd (cdr (assoc 'system apps))))
11102 (in-emacs (setq cmd 'emacs))
11103 (t
11104 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11105 (and dirp (cdr (assoc 'directory apps)))
11106 ; first, try matching against apps-dlink
11107 ; if we get a match here, store the match data for later
11108 (let ((match (assoc-default dlink apps-dlink
11109 'string-match)))
11110 (if match
11111 (progn (setq link-match-data (match-data))
11112 match)
11113 (progn (setq in-emacs (or in-emacs line search))
11114 nil))) ; if we have no match in apps-dlink,
11115 ; always open the file in emacs if line or search
11116 ; is given (for backwards compatibility)
11117 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11118 'string-match)
11119 (cdr (assoc ext apps))
11120 (cdr (assoc t apps))))))
11121 (when (eq cmd 'system)
11122 (setq cmd (cdr (assoc 'system apps))))
11123 (when (eq cmd 'default)
11124 (setq cmd (cdr (assoc t apps))))
11125 (when (eq cmd 'mailcap)
11126 (require 'mailcap)
11127 (mailcap-parse-mailcaps)
11128 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11129 (command (mailcap-mime-info mime-type)))
11130 (if (stringp command)
11131 (setq cmd command)
11132 (setq cmd 'emacs))))
11133 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11134 (not (file-exists-p file))
11135 (not org-open-non-existing-files))
11136 (user-error "No such file: %s" file))
11137 (cond
11138 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11139 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11140 (while (string-match "['\"]%s['\"]" cmd)
11141 (setq cmd (replace-match "%s" t t cmd)))
11142 (while (string-match "%s" cmd)
11143 (setq cmd (replace-match
11144 (save-match-data
11145 (shell-quote-argument
11146 (convert-standard-filename file)))
11147 t t cmd)))
11148
11149 ;; Replace "%1", "%2" etc. in command with group matches from regex
11150 (save-match-data
11151 (let ((match-index 1)
11152 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11153 (set-match-data link-match-data)
11154 (while (<= match-index number-of-groups)
11155 (let ((regex (concat "%" (number-to-string match-index)))
11156 (replace-with (match-string match-index dlink)))
11157 (while (string-match regex cmd)
11158 (setq cmd (replace-match replace-with t t cmd))))
11159 (setq match-index (+ match-index 1)))))
11160
11161 (save-window-excursion
11162 (message "Running %s...done" cmd)
11163 (start-process-shell-command cmd nil cmd)
11164 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11165 ((or (stringp cmd)
11166 (eq cmd 'emacs))
11167 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11168 (widen)
11169 (if line (org-goto-line line)
11170 (if search (org-link-search search))))
11171 ((consp cmd)
11172 (let ((file (convert-standard-filename file)))
11173 (save-match-data
11174 (set-match-data link-match-data)
11175 (eval cmd))))
11176 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11177 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11178 (or (not (equal old-buffer (current-buffer)))
11179 (not (equal old-pos (point))))
11180 (org-mark-ring-push old-pos old-buffer))))
11181
11182 (defun org-file-apps-entry-match-against-dlink-p (entry)
11183 "This function returns non-nil if `entry' uses a regular
11184 expression which should be matched against the whole link by
11185 org-open-file.
11186
11187 It assumes that is the case when the entry uses a regular
11188 expression which has at least one grouping construct and the
11189 action is either a lisp form or a command string containing
11190 `%1', i.e. using at least one subexpression match as a
11191 parameter."
11192 (let ((selector (car entry))
11193 (action (cdr entry)))
11194 (if (stringp selector)
11195 (and (> (regexp-opt-depth selector) 0)
11196 (or (and (stringp action)
11197 (string-match "%[0-9]" action))
11198 (consp action)))
11199 nil)))
11200
11201 (defun org-default-apps ()
11202 "Return the default applications for this operating system."
11203 (cond
11204 ((eq system-type 'darwin)
11205 org-file-apps-defaults-macosx)
11206 ((eq system-type 'windows-nt)
11207 org-file-apps-defaults-windowsnt)
11208 (t org-file-apps-defaults-gnu)))
11209
11210 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11211 "Convert extensions to regular expressions in the cars of LIST.
11212 Also, weed out any non-string entries, because the return value is used
11213 only for regexp matching.
11214 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11215 point to the symbol `emacs', indicating that the file should
11216 be opened in Emacs."
11217 (append
11218 (delq nil
11219 (mapcar (lambda (x)
11220 (if (not (stringp (car x)))
11221 nil
11222 (if (string-match "\\W" (car x))
11223 x
11224 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11225 list))
11226 (if add-auto-mode
11227 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11228
11229 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11230 (defun org-file-remote-p (file)
11231 "Test whether FILE specifies a location on a remote system.
11232 Return non-nil if the location is indeed remote.
11233
11234 For example, the filename \"/user@host:/foo\" specifies a location
11235 on the system \"/user@host:\"."
11236 (cond ((fboundp 'file-remote-p)
11237 (file-remote-p file))
11238 ((fboundp 'tramp-handle-file-remote-p)
11239 (tramp-handle-file-remote-p file))
11240 ((and (boundp 'ange-ftp-name-format)
11241 (string-match (car ange-ftp-name-format) file))
11242 t)))
11243
11244
11245 ;;;; Refiling
11246
11247 (defun org-get-org-file ()
11248 "Read a filename, with default directory `org-directory'."
11249 (let ((default (or org-default-notes-file remember-data-file)))
11250 (read-file-name (format "File name [%s]: " default)
11251 (file-name-as-directory org-directory)
11252 default)))
11253
11254 (defun org-notes-order-reversed-p ()
11255 "Check if the current file should receive notes in reversed order."
11256 (cond
11257 ((not org-reverse-note-order) nil)
11258 ((eq t org-reverse-note-order) t)
11259 ((not (listp org-reverse-note-order)) nil)
11260 (t (catch 'exit
11261 (dolist (entry org-reverse-note-order)
11262 (if (string-match (car entry) buffer-file-name)
11263 (throw 'exit (cdr entry))))))))
11264
11265 (defvar org-refile-target-table nil
11266 "The list of refile targets, created by `org-refile'.")
11267
11268 (defvar org-agenda-new-buffers nil
11269 "Buffers created to visit agenda files.")
11270
11271 (defvar org-refile-cache nil
11272 "Cache for refile targets.")
11273
11274 (defvar org-refile-markers nil
11275 "All the markers used for caching refile locations.")
11276
11277 (defun org-refile-marker (pos)
11278 "Get a new refile marker, but only if caching is in use."
11279 (if (not org-refile-use-cache)
11280 pos
11281 (let ((m (make-marker)))
11282 (move-marker m pos)
11283 (push m org-refile-markers)
11284 m)))
11285
11286 (defun org-refile-cache-clear ()
11287 "Clear the refile cache and disable all the markers."
11288 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11289 (setq org-refile-markers nil)
11290 (setq org-refile-cache nil)
11291 (message "Refile cache has been cleared"))
11292
11293 (defun org-refile-cache-check-set (set)
11294 "Check if all the markers in the cache still have live buffers."
11295 (let (marker)
11296 (catch 'exit
11297 (while (and set (setq marker (nth 3 (pop set))))
11298 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11299 (when (and marker (null (marker-buffer marker)))
11300 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11301 (sit-for 3)
11302 (throw 'exit nil)))
11303 t)))
11304
11305 (defun org-refile-cache-put (set &rest identifiers)
11306 "Push the refile targets SET into the cache, under IDENTIFIERS."
11307 (let* ((key (sha1 (prin1-to-string identifiers)))
11308 (entry (assoc key org-refile-cache)))
11309 (if entry
11310 (setcdr entry set)
11311 (push (cons key set) org-refile-cache))))
11312
11313 (defun org-refile-cache-get (&rest identifiers)
11314 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11315 (cond
11316 ((not org-refile-cache) nil)
11317 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11318 (t
11319 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11320 org-refile-cache))))
11321 (and set (org-refile-cache-check-set set) set)))))
11322
11323 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11324 "Produce a table with refile targets."
11325 (let ((case-fold-search nil)
11326 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11327 (entries (or org-refile-targets '((nil . (:level . 1)))))
11328 targets tgs txt re files desc descre fast-path-p level pos0)
11329 (message "Getting targets...")
11330 (with-current-buffer (or default-buffer (current-buffer))
11331 (dolist (entry entries)
11332 (setq files (car entry) desc (cdr entry))
11333 (setq fast-path-p nil)
11334 (cond
11335 ((null files) (setq files (list (current-buffer))))
11336 ((eq files 'org-agenda-files)
11337 (setq files (org-agenda-files 'unrestricted)))
11338 ((and (symbolp files) (fboundp files))
11339 (setq files (funcall files)))
11340 ((and (symbolp files) (boundp files))
11341 (setq files (symbol-value files))))
11342 (if (stringp files) (setq files (list files)))
11343 (cond
11344 ((eq (car desc) :tag)
11345 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11346 ((eq (car desc) :todo)
11347 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11348 ((eq (car desc) :regexp)
11349 (setq descre (cdr desc)))
11350 ((eq (car desc) :level)
11351 (setq descre (concat "^\\*\\{" (number-to-string
11352 (if org-odd-levels-only
11353 (1- (* 2 (cdr desc)))
11354 (cdr desc)))
11355 "\\}[ \t]")))
11356 ((eq (car desc) :maxlevel)
11357 (setq fast-path-p t)
11358 (setq descre (concat "^\\*\\{1," (number-to-string
11359 (if org-odd-levels-only
11360 (1- (* 2 (cdr desc)))
11361 (cdr desc)))
11362 "\\}[ \t]")))
11363 (t (error "Bad refiling target description %s" desc)))
11364 (dolist (f files)
11365 (with-current-buffer
11366 (if (bufferp f) f (org-get-agenda-file-buffer f))
11367 (or
11368 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11369 (progn
11370 (if (bufferp f) (setq f (buffer-file-name
11371 (buffer-base-buffer f))))
11372 (setq f (and f (expand-file-name f)))
11373 (if (eq org-refile-use-outline-path 'file)
11374 (push (list (file-name-nondirectory f) f nil nil) tgs))
11375 (save-excursion
11376 (save-restriction
11377 (widen)
11378 (goto-char (point-min))
11379 (while (re-search-forward descre nil t)
11380 (goto-char (setq pos0 (point-at-bol)))
11381 (catch 'next
11382 (when org-refile-target-verify-function
11383 (save-match-data
11384 (or (funcall org-refile-target-verify-function)
11385 (throw 'next t))))
11386 (when (and (looking-at org-complex-heading-regexp)
11387 (not (member (match-string 4) excluded-entries))
11388 (match-string 4))
11389 (setq level (org-reduced-level
11390 (- (match-end 1) (match-beginning 1)))
11391 txt (org-link-display-format (match-string 4))
11392 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11393 re (format org-complex-heading-regexp-format
11394 (regexp-quote (match-string 4))))
11395 (when org-refile-use-outline-path
11396 (setq txt (mapconcat
11397 'org-protect-slash
11398 (append
11399 (if (eq org-refile-use-outline-path
11400 'file)
11401 (list (file-name-nondirectory
11402 (buffer-file-name
11403 (buffer-base-buffer))))
11404 (if (eq org-refile-use-outline-path
11405 'full-file-path)
11406 (list (buffer-file-name
11407 (buffer-base-buffer)))))
11408 (org-get-outline-path fast-path-p
11409 level txt)
11410 (list txt))
11411 "/")))
11412 (push (list txt f re (org-refile-marker (point)))
11413 tgs)))
11414 (when (= (point) pos0)
11415 ;; verification function has not moved point
11416 (goto-char (point-at-eol))))))))
11417 (when org-refile-use-cache
11418 (org-refile-cache-put tgs (buffer-file-name) descre))
11419 (setq targets (append tgs targets))))))
11420 (message "Getting targets...done")
11421 (nreverse targets)))
11422
11423 (defun org-protect-slash (s)
11424 (while (string-match "/" s)
11425 (setq s (replace-match "\\" t t s)))
11426 s)
11427
11428 (defvar org-olpa (make-vector 20 nil))
11429
11430 (defun org-get-outline-path (&optional fastp level heading)
11431 "Return the outline path to the current entry, as a list.
11432
11433 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11434 routine which makes outline path derivations for an entire file,
11435 avoiding backtracing. Refile target collection makes use of that."
11436 (if fastp
11437 (progn
11438 (if (> level 19)
11439 (error "Outline path failure, more than 19 levels"))
11440 (loop for i from level upto 19 do
11441 (aset org-olpa i nil))
11442 (prog1
11443 (delq nil (append org-olpa nil))
11444 (aset org-olpa level heading)))
11445 (let (rtn case-fold-search)
11446 (save-excursion
11447 (save-restriction
11448 (widen)
11449 (while (org-up-heading-safe)
11450 (when (looking-at org-complex-heading-regexp)
11451 (push (org-trim
11452 (replace-regexp-in-string
11453 ;; Remove statistical/checkboxes cookies
11454 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11455 (org-match-string-no-properties 4)))
11456 rtn)))
11457 rtn)))))
11458
11459 (defun org-format-outline-path (path &optional width prefix separator)
11460 "Format the outline path PATH for display.
11461 WIDTH is the maximum number of characters that is available.
11462 PREFIX is a prefix to be included in the returned string,
11463 such as the file name.
11464 SEPARATOR is inserted between the different parts of the path,
11465 the default is \"/\"."
11466 (setq width (or width 79))
11467 (if prefix (setq width (- width (length prefix))))
11468 (if (not path)
11469 (or prefix "")
11470 (let* ((nsteps (length path))
11471 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11472 (maxwidth (if (<= total-width width)
11473 10000 ;; everything fits
11474 ;; we need to shorten the level headings
11475 (/ (- width nsteps) nsteps)))
11476 (org-odd-levels-only nil)
11477 (n 0)
11478 (total (1+ (length prefix))))
11479 (setq maxwidth (max maxwidth 10))
11480 (concat prefix
11481 (if prefix (or separator "/"))
11482 (mapconcat
11483 (lambda (h)
11484 (setq n (1+ n))
11485 (if (and (= n nsteps) (< maxwidth 10000))
11486 (setq maxwidth (- total-width total)))
11487 (if (< (length h) maxwidth)
11488 (progn (setq total (+ total (length h) 1)) h)
11489 (setq h (substring h 0 (- maxwidth 2))
11490 total (+ total maxwidth 1))
11491 (if (string-match "[ \t]+\\'" h)
11492 (setq h (substring h 0 (match-beginning 0))))
11493 (setq h (concat h "..")))
11494 (org-add-props h nil 'face
11495 (nth (% (1- n) org-n-level-faces)
11496 org-level-faces))
11497 h)
11498 path (or separator "/"))))))
11499
11500 (defun org-display-outline-path (&optional file current separator just-return-string)
11501 "Display the current outline path in the echo area.
11502
11503 If FILE is non-nil, prepend the output with the file name.
11504 If CURRENT is non-nil, append the current heading to the output.
11505 SEPARATOR is passed through to `org-format-outline-path'. It separates
11506 the different parts of the path and defaults to \"/\".
11507 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11508 (interactive "P")
11509 (let* (case-fold-search
11510 (bfn (buffer-file-name (buffer-base-buffer)))
11511 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11512 res)
11513 (if current (setq path (append path
11514 (save-excursion
11515 (org-back-to-heading t)
11516 (if (looking-at org-complex-heading-regexp)
11517 (list (match-string 4)))))))
11518 (setq res
11519 (org-format-outline-path
11520 path
11521 (1- (frame-width))
11522 (and file bfn (concat (file-name-nondirectory bfn) separator))
11523 separator))
11524 (if just-return-string
11525 (org-no-properties res)
11526 (org-unlogged-message "%s" res))))
11527
11528 (defvar org-refile-history nil
11529 "History for refiling operations.")
11530
11531 (defvar org-after-refile-insert-hook nil
11532 "Hook run after `org-refile' has inserted its stuff at the new location.
11533 Note that this is still *before* the stuff will be removed from
11534 the *old* location.")
11535
11536 (defvar org-capture-last-stored-marker)
11537 (defvar org-refile-keep nil
11538 "Non-nil means `org-refile' will copy instead of refile.")
11539
11540 (defun org-copy ()
11541 "Like `org-refile', but copy."
11542 (interactive)
11543 (let ((org-refile-keep t))
11544 (funcall 'org-refile nil nil nil "Copy")))
11545
11546 (defun org-refile (&optional goto default-buffer rfloc msg)
11547 "Move the entry or entries at point to another heading.
11548 The list of target headings is compiled using the information in
11549 `org-refile-targets', which see.
11550
11551 At the target location, the entry is filed as a subitem of the target
11552 heading. Depending on `org-reverse-note-order', the new subitem will
11553 either be the first or the last subitem.
11554
11555 If there is an active region, all entries in that region will be moved.
11556 However, the region must fulfill the requirement that the first heading
11557 is the first one sets the top-level of the moved text - at most siblings
11558 below it are allowed.
11559
11560 With prefix arg GOTO, the command will only visit the target location
11561 and not actually move anything.
11562
11563 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11564 go to the location where the last refiling operation has put the subtree.
11565
11566 With a numeric prefix argument of `2', refile to the running clock.
11567
11568 With a numeric prefix argument of `3', emulate `org-refile-keep'
11569 being set to t and copy to the target location, don't move it.
11570 Beware that keeping refiled entries may result in duplicated ID
11571 properties.
11572
11573 RFLOC can be a refile location obtained in a different way.
11574
11575 MSG is a string to replace \"Refile\" in the default prompt with
11576 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11577
11578 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11579
11580 If you are using target caching (see `org-refile-use-cache'),
11581 you have to clear the target cache in order to find new targets.
11582 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11583 prefix argument (`C-u C-u C-u C-c C-w')."
11584
11585 (interactive "P")
11586 (if (member goto '(0 (64)))
11587 (org-refile-cache-clear)
11588 (let* ((actionmsg (cond (msg msg)
11589 ((equal goto 3) "Refile (and keep)")
11590 (t "Refile")))
11591 (cbuf (current-buffer))
11592 (regionp (org-region-active-p))
11593 (region-start (and regionp (region-beginning)))
11594 (region-end (and regionp (region-end)))
11595 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11596 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11597 pos it nbuf file re level reversed)
11598 (setq last-command nil)
11599 (when regionp
11600 (goto-char region-start)
11601 (or (bolp) (goto-char (point-at-bol)))
11602 (setq region-start (point))
11603 (unless (or (org-kill-is-subtree-p
11604 (buffer-substring region-start region-end))
11605 (prog1 org-refile-active-region-within-subtree
11606 (let ((s (point-at-eol)))
11607 (org-toggle-heading)
11608 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11609 (user-error "The region is not a (sequence of) subtree(s)")))
11610 (if (equal goto '(16))
11611 (org-refile-goto-last-stored)
11612 (when (or
11613 (and (equal goto 2)
11614 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11615 (prog1
11616 (setq it (list (or org-clock-heading "running clock")
11617 (buffer-file-name
11618 (marker-buffer org-clock-hd-marker))
11619 ""
11620 (marker-position org-clock-hd-marker)))
11621 (setq goto nil)))
11622 (setq it (or rfloc
11623 (let (heading-text)
11624 (save-excursion
11625 (unless (and goto (listp goto))
11626 (org-back-to-heading t)
11627 (setq heading-text
11628 (nth 4 (org-heading-components))))
11629
11630 (org-refile-get-location
11631 (cond ((and goto (listp goto)) "Goto")
11632 (regionp (concat actionmsg " region to"))
11633 (t (concat actionmsg " subtree \""
11634 heading-text "\" to")))
11635 default-buffer
11636 (and (not (equal '(4) goto))
11637 org-refile-allow-creating-parent-nodes)
11638 goto))))))
11639 (setq file (nth 1 it)
11640 re (nth 2 it)
11641 pos (nth 3 it))
11642 (if (and (not goto)
11643 pos
11644 (equal (buffer-file-name) file)
11645 (if regionp
11646 (and (>= pos region-start)
11647 (<= pos region-end))
11648 (and (>= pos (point))
11649 (< pos (save-excursion
11650 (org-end-of-subtree t t))))))
11651 (error "Cannot refile to position inside the tree or region"))
11652
11653 (setq nbuf (or (find-buffer-visiting file)
11654 (find-file-noselect file)))
11655 (if (and goto (not (equal goto 3)))
11656 (progn
11657 (org-pop-to-buffer-same-window nbuf)
11658 (goto-char pos)
11659 (org-show-context 'org-goto))
11660 (if regionp
11661 (progn
11662 (org-kill-new (buffer-substring region-start region-end))
11663 (org-save-markers-in-region region-start region-end))
11664 (org-copy-subtree 1 nil t))
11665 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11666 (find-file-noselect file)))
11667 (setq reversed (org-notes-order-reversed-p))
11668 (save-excursion
11669 (save-restriction
11670 (widen)
11671 (if pos
11672 (progn
11673 (goto-char pos)
11674 (looking-at org-outline-regexp)
11675 (setq level (org-get-valid-level (funcall outline-level) 1))
11676 (goto-char
11677 (if reversed
11678 (or (outline-next-heading) (point-max))
11679 (or (save-excursion (org-get-next-sibling))
11680 (org-end-of-subtree t t)
11681 (point-max)))))
11682 (setq level 1)
11683 (if (not reversed)
11684 (goto-char (point-max))
11685 (goto-char (point-min))
11686 (or (outline-next-heading) (goto-char (point-max)))))
11687 (if (not (bolp)) (newline))
11688 (org-paste-subtree level)
11689 (when org-log-refile
11690 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11691 (unless (eq org-log-refile 'note)
11692 (save-excursion (org-add-log-note))))
11693 (and org-auto-align-tags
11694 (let ((org-loop-over-headlines-in-active-region nil))
11695 (org-set-tags nil t)))
11696 (let ((bookmark-name (plist-get org-bookmark-names-plist
11697 :last-refile)))
11698 (when bookmark-name
11699 (with-demoted-errors
11700 (bookmark-set bookmark-name))))
11701 ;; If we are refiling for capture, make sure that the
11702 ;; last-capture pointers point here
11703 (when (org-bound-and-true-p org-refile-for-capture)
11704 (let ((bookmark-name (plist-get org-bookmark-names-plist
11705 :last-capture-marker)))
11706 (when bookmark-name
11707 (with-demoted-errors
11708 (bookmark-set bookmark-name))))
11709 (move-marker org-capture-last-stored-marker (point)))
11710 (if (fboundp 'deactivate-mark) (deactivate-mark))
11711 (run-hooks 'org-after-refile-insert-hook))))
11712 (unless org-refile-keep
11713 (if regionp
11714 (delete-region (point) (+ (point) (- region-end region-start)))
11715 (delete-region
11716 (and (org-back-to-heading t) (point))
11717 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11718 (when (featurep 'org-inlinetask)
11719 (org-inlinetask-remove-END-maybe))
11720 (setq org-markers-to-move nil)
11721 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11722
11723 (defun org-refile-goto-last-stored ()
11724 "Go to the location where the last refile was stored."
11725 (interactive)
11726 (bookmark-jump "org-refile-last-stored")
11727 (message "This is the location of the last refile"))
11728
11729 (defun org-refile--get-location (refloc tbl)
11730 "When user refile to REFLOC, find the associated target in TBL.
11731 Also check `org-refile-target-table'."
11732 (car (delq
11733 nil
11734 (mapcar
11735 (lambda (r) (or (assoc r tbl)
11736 (assoc r org-refile-target-table)))
11737 (list (replace-regexp-in-string "/$" "" refloc)
11738 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11739
11740 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11741 no-exclude)
11742 "Prompt the user for a refile location, using PROMPT.
11743 PROMPT should not be suffixed with a colon and a space, because
11744 this function appends the default value from
11745 `org-refile-history' automatically, if that is not empty.
11746 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11747 this is used for the GOTO interface."
11748 (let ((org-refile-targets org-refile-targets)
11749 (org-refile-use-outline-path org-refile-use-outline-path)
11750 excluded-entries)
11751 (when (and (derived-mode-p 'org-mode)
11752 (not org-refile-use-cache)
11753 (not no-exclude))
11754 (org-map-tree
11755 (lambda()
11756 (setq excluded-entries
11757 (append excluded-entries (list (org-get-heading t t)))))))
11758 (setq org-refile-target-table
11759 (org-refile-get-targets default-buffer excluded-entries)))
11760 (unless org-refile-target-table
11761 (user-error "No refile targets"))
11762 (let* ((cbuf (current-buffer))
11763 (partial-completion-mode nil)
11764 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11765 (cfunc (if (and org-refile-use-outline-path
11766 org-outline-path-complete-in-steps)
11767 'org-olpath-completing-read
11768 'org-icompleting-read))
11769 (extra (if org-refile-use-outline-path "/" ""))
11770 (cbnex (concat (buffer-name) extra))
11771 (filename (and cfn (expand-file-name cfn)))
11772 (tbl (mapcar
11773 (lambda (x)
11774 (if (and (not (member org-refile-use-outline-path
11775 '(file full-file-path)))
11776 (not (equal filename (nth 1 x))))
11777 (cons (concat (car x) extra " ("
11778 (file-name-nondirectory (nth 1 x)) ")")
11779 (cdr x))
11780 (cons (concat (car x) extra) (cdr x))))
11781 org-refile-target-table))
11782 (completion-ignore-case t)
11783 cdef
11784 (prompt (concat prompt
11785 (or (and (car org-refile-history)
11786 (concat " (default " (car org-refile-history) ")"))
11787 (and (assoc cbnex tbl) (setq cdef cbnex)
11788 (concat " (default " cbnex ")"))) ": "))
11789 pa answ parent-target child parent old-hist)
11790 (setq old-hist org-refile-history)
11791 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11792 nil 'org-refile-history (or cdef (car org-refile-history))))
11793 (if (setq pa (org-refile--get-location answ tbl))
11794 (progn
11795 (org-refile-check-position pa)
11796 (when (or (not org-refile-history)
11797 (not (eq old-hist org-refile-history))
11798 (not (equal (car pa) (car org-refile-history))))
11799 (setq org-refile-history
11800 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11801 org-refile-history
11802 (cdr org-refile-history))))
11803 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11804 (pop org-refile-history)))
11805 pa)
11806 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11807 (progn
11808 (setq parent (match-string 1 answ)
11809 child (match-string 2 answ))
11810 (setq parent-target (org-refile--get-location parent tbl))
11811 (when (and parent-target
11812 (or (eq new-nodes t)
11813 (and (eq new-nodes 'confirm)
11814 (y-or-n-p (format "Create new node \"%s\"? "
11815 child)))))
11816 (org-refile-new-child parent-target child)))
11817 (user-error "Invalid target location")))))
11818
11819 (declare-function org-string-nw-p "org-macs" (s))
11820 (defun org-refile-check-position (refile-pointer)
11821 "Check if the refile pointer matches the headline to which it points."
11822 (let* ((file (nth 1 refile-pointer))
11823 (re (nth 2 refile-pointer))
11824 (pos (nth 3 refile-pointer))
11825 buffer)
11826 (if (and (not (markerp pos)) (not file))
11827 (user-error "Please save the buffer to a file before refiling")
11828 (when (org-string-nw-p re)
11829 (setq buffer (if (markerp pos)
11830 (marker-buffer pos)
11831 (or (find-buffer-visiting file)
11832 (find-file-noselect file))))
11833 (with-current-buffer buffer
11834 (save-excursion
11835 (save-restriction
11836 (widen)
11837 (goto-char pos)
11838 (beginning-of-line 1)
11839 (unless (org-looking-at-p re)
11840 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11841
11842 (defun org-refile-new-child (parent-target child)
11843 "Use refile target PARENT-TARGET to add new CHILD below it."
11844 (unless parent-target
11845 (error "Cannot find parent for new node"))
11846 (let ((file (nth 1 parent-target))
11847 (pos (nth 3 parent-target))
11848 level)
11849 (with-current-buffer (or (find-buffer-visiting file)
11850 (find-file-noselect file))
11851 (save-excursion
11852 (save-restriction
11853 (widen)
11854 (if pos
11855 (goto-char pos)
11856 (goto-char (point-max))
11857 (if (not (bolp)) (newline)))
11858 (when (looking-at org-outline-regexp)
11859 (setq level (funcall outline-level))
11860 (org-end-of-subtree t t))
11861 (org-back-over-empty-lines)
11862 (insert "\n" (make-string
11863 (if pos (org-get-valid-level level 1) 1) ?*)
11864 " " child "\n")
11865 (beginning-of-line 0)
11866 (list (concat (car parent-target) "/" child) file "" (point)))))))
11867
11868 (defun org-olpath-completing-read (prompt collection &rest args)
11869 "Read an outline path like a file name."
11870 (let ((thetable collection)
11871 (org-completion-use-ido nil) ; does not work with ido.
11872 (org-completion-use-iswitchb nil)) ; or iswitchb
11873 (apply
11874 'org-icompleting-read prompt
11875 (lambda (string predicate &optional flag)
11876 (let (rtn r f (l (length string)))
11877 (cond
11878 ((eq flag nil)
11879 ;; try completion
11880 (try-completion string thetable))
11881 ((eq flag t)
11882 ;; all-completions
11883 (setq rtn (all-completions string thetable predicate))
11884 (mapcar
11885 (lambda (x)
11886 (setq r (substring x l))
11887 (if (string-match " ([^)]*)$" x)
11888 (setq f (match-string 0 x))
11889 (setq f ""))
11890 (if (string-match "/" r)
11891 (concat string (substring r 0 (match-end 0)) f)
11892 x))
11893 rtn))
11894 ((eq flag 'lambda)
11895 ;; exact match?
11896 (assoc string thetable)))))
11897 args)))
11898
11899 ;;;; Dynamic blocks
11900
11901 (defun org-find-dblock (name)
11902 "Find the first dynamic block with name NAME in the buffer.
11903 If not found, stay at current position and return nil."
11904 (let ((case-fold-search t) pos)
11905 (save-excursion
11906 (goto-char (point-min))
11907 (setq pos (and (re-search-forward
11908 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11909 (match-beginning 0))))
11910 (if pos (goto-char pos))
11911 pos))
11912
11913 (defconst org-dblock-start-re
11914 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11915 "Matches the start line of a dynamic block, with parameters.")
11916
11917 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11918 "Matches the end of a dynamic block.")
11919
11920 (defun org-create-dblock (plist)
11921 "Create a dynamic block section, with parameters taken from PLIST.
11922 PLIST must contain a :name entry which is used as name of the block."
11923 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11924 (end-of-line 1)
11925 (newline))
11926 (let ((col (current-column))
11927 (name (plist-get plist :name)))
11928 (insert "#+BEGIN: " name)
11929 (while plist
11930 (if (eq (car plist) :name)
11931 (setq plist (cddr plist))
11932 (insert " " (prin1-to-string (pop plist)))))
11933 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11934 (beginning-of-line -2)))
11935
11936 (defun org-prepare-dblock ()
11937 "Prepare dynamic block for refresh.
11938 This empties the block, puts the cursor at the insert position and returns
11939 the property list including an extra property :name with the block name."
11940 (unless (looking-at org-dblock-start-re)
11941 (user-error "Not at a dynamic block"))
11942 (let* ((begdel (1+ (match-end 0)))
11943 (name (org-no-properties (match-string 1)))
11944 (params (append (list :name name)
11945 (read (concat "(" (match-string 3) ")")))))
11946 (save-excursion
11947 (beginning-of-line 1)
11948 (skip-chars-forward " \t")
11949 (setq params (plist-put params :indentation-column (current-column))))
11950 (unless (re-search-forward org-dblock-end-re nil t)
11951 (error "Dynamic block not terminated"))
11952 (setq params
11953 (append params
11954 (list :content (buffer-substring
11955 begdel (match-beginning 0)))))
11956 (delete-region begdel (match-beginning 0))
11957 (goto-char begdel)
11958 (open-line 1)
11959 params))
11960
11961 (defun org-map-dblocks (&optional command)
11962 "Apply COMMAND to all dynamic blocks in the current buffer.
11963 If COMMAND is not given, use `org-update-dblock'."
11964 (let ((cmd (or command 'org-update-dblock)))
11965 (save-excursion
11966 (goto-char (point-min))
11967 (while (re-search-forward org-dblock-start-re nil t)
11968 (goto-char (match-beginning 0))
11969 (save-excursion
11970 (condition-case nil
11971 (funcall cmd)
11972 (error (message "Error during update of dynamic block"))))
11973 (unless (re-search-forward org-dblock-end-re nil t)
11974 (error "Dynamic block not terminated"))))))
11975
11976 (defun org-dblock-update (&optional arg)
11977 "User command for updating dynamic blocks.
11978 Update the dynamic block at point. With prefix ARG, update all dynamic
11979 blocks in the buffer."
11980 (interactive "P")
11981 (if arg
11982 (org-update-all-dblocks)
11983 (or (looking-at org-dblock-start-re)
11984 (org-beginning-of-dblock))
11985 (org-update-dblock)))
11986
11987 (defun org-update-dblock ()
11988 "Update the dynamic block at point.
11989 This means to empty the block, parse for parameters and then call
11990 the correct writing function."
11991 (interactive)
11992 (save-excursion
11993 (let* ((win (selected-window))
11994 (pos (point))
11995 (line (org-current-line))
11996 (params (org-prepare-dblock))
11997 (name (plist-get params :name))
11998 (indent (plist-get params :indentation-column))
11999 (cmd (intern (concat "org-dblock-write:" name))))
12000 (message "Updating dynamic block `%s' at line %d..." name line)
12001 (funcall cmd params)
12002 (message "Updating dynamic block `%s' at line %d...done" name line)
12003 (goto-char pos)
12004 (when (and indent (> indent 0))
12005 (setq indent (make-string indent ?\ ))
12006 (save-excursion
12007 (select-window win)
12008 (org-beginning-of-dblock)
12009 (forward-line 1)
12010 (while (not (looking-at org-dblock-end-re))
12011 (insert indent)
12012 (beginning-of-line 2))
12013 (when (looking-at org-dblock-end-re)
12014 (and (looking-at "[ \t]+")
12015 (replace-match ""))
12016 (insert indent)))))))
12017
12018 (defun org-beginning-of-dblock ()
12019 "Find the beginning of the dynamic block at point.
12020 Error if there is no such block at point."
12021 (let ((pos (point))
12022 beg)
12023 (end-of-line 1)
12024 (if (and (re-search-backward org-dblock-start-re nil t)
12025 (setq beg (match-beginning 0))
12026 (re-search-forward org-dblock-end-re nil t)
12027 (> (match-end 0) pos))
12028 (goto-char beg)
12029 (goto-char pos)
12030 (error "Not in a dynamic block"))))
12031
12032 (defun org-update-all-dblocks ()
12033 "Update all dynamic blocks in the buffer.
12034 This function can be used in a hook."
12035 (interactive)
12036 (when (derived-mode-p 'org-mode)
12037 (org-map-dblocks 'org-update-dblock)))
12038
12039
12040 ;;;; Completion
12041
12042 (declare-function org-export-backend-name "org-export" (cl-x))
12043 (declare-function org-export-backend-options "org-export" (cl-x))
12044 (defun org-get-export-keywords ()
12045 "Return a list of all currently understood export keywords.
12046 Export keywords include options, block names, attributes and
12047 keywords relative to each registered export back-end."
12048 (let (keywords)
12049 (dolist (backend
12050 (org-bound-and-true-p org-export--registered-backends)
12051 (delq nil keywords))
12052 ;; Back-end name (for keywords, like #+LATEX:)
12053 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12054 (dolist (option-entry (org-export-backend-options backend))
12055 ;; Back-end options.
12056 (push (nth 1 option-entry) keywords)))))
12057
12058 (defconst org-options-keywords
12059 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12060 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12061 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12062 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12063 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12064
12065 (defcustom org-structure-template-alist
12066 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12067 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12068 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12069 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12070 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12071 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12072 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12073 "<literal style=\"latex\">\n?\n</literal>")
12074 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12075 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12076 "<literal style=\"html\">\n?\n</literal>")
12077 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12078 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12079 ("A" "#+ASCII: " "")
12080 ("i" "#+INDEX: ?" "#+INDEX: ?")
12081 ("I" "#+INCLUDE: %file ?"
12082 "<include file=%file markup=\"?\">"))
12083 "Structure completion elements.
12084 This is a list of abbreviation keys and values. The value gets inserted
12085 if you type `<' followed by the key and then press the completion key,
12086 usually `M-TAB'. %file will be replaced by a file name after prompting
12087 for the file using completion. The cursor will be placed at the position
12088 of the `?' in the template.
12089 There are two templates for each key, the first uses the original Org syntax,
12090 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12091 the default when the /org-mtags.el/ module has been loaded. See also the
12092 variable `org-mtags-prefer-muse-templates'."
12093 :group 'org-completion
12094 :type '(repeat
12095 (list
12096 (string :tag "Key")
12097 (string :tag "Template")
12098 (string :tag "Muse Template"))))
12099
12100 (defun org-try-structure-completion ()
12101 "Try to complete a structure template before point.
12102 This looks for strings like \"<e\" on an otherwise empty line and
12103 expands them."
12104 (let ((l (buffer-substring (point-at-bol) (point)))
12105 a)
12106 (when (and (looking-at "[ \t]*$")
12107 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12108 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12109 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12110 (match-beginning 1)) a)
12111 t)))
12112
12113 (defun org-complete-expand-structure-template (start cell)
12114 "Expand a structure template."
12115 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12116 (rpl (nth (if musep 2 1) cell))
12117 (ind ""))
12118 (delete-region start (point))
12119 (when (string-match "\\`#\\+" rpl)
12120 (cond
12121 ((bolp))
12122 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12123 (setq ind (buffer-substring (point-at-bol) (point))))
12124 (t (newline))))
12125 (setq start (point))
12126 (if (string-match "%file" rpl)
12127 (setq rpl (replace-match
12128 (concat
12129 "\""
12130 (save-match-data
12131 (abbreviate-file-name (read-file-name "Include file: ")))
12132 "\"")
12133 t t rpl)))
12134 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12135 (concat "\n" ind)))
12136 (insert rpl)
12137 (if (re-search-backward "\\?" start t) (delete-char 1))))
12138
12139 ;;;; TODO, DEADLINE, Comments
12140
12141 (defun org-toggle-comment ()
12142 "Change the COMMENT state of an entry."
12143 (interactive)
12144 (save-excursion
12145 (org-back-to-heading)
12146 (let (case-fold-search)
12147 (cond
12148 ((looking-at (format org-heading-keyword-regexp-format
12149 org-comment-string))
12150 (goto-char (match-end 1))
12151 (looking-at (concat " +" org-comment-string))
12152 (replace-match "" t t)
12153 (when (eolp) (insert " ")))
12154 ((looking-at org-outline-regexp)
12155 (goto-char (match-end 0))
12156 (insert org-comment-string " "))))))
12157
12158 (defvar org-last-todo-state-is-todo nil
12159 "This is non-nil when the last TODO state change led to a TODO state.
12160 If the last change removed the TODO tag or switched to DONE, then
12161 this is nil.")
12162
12163 (defvar org-setting-tags nil) ; dynamically skipped
12164
12165 (defvar org-todo-setup-filter-hook nil
12166 "Hook for functions that pre-filter todo specs.
12167 Each function takes a todo spec and returns either nil or the spec
12168 transformed into canonical form." )
12169
12170 (defvar org-todo-get-default-hook nil
12171 "Hook for functions that get a default item for todo.
12172 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12173 nil or a string to be used for the todo mark." )
12174
12175 (defvar org-agenda-headline-snapshot-before-repeat)
12176
12177 (defun org-current-effective-time ()
12178 "Return current time adjusted for `org-extend-today-until' variable."
12179 (let* ((ct (org-current-time))
12180 (dct (decode-time ct))
12181 (ct1
12182 (cond
12183 (org-use-last-clock-out-time-as-effective-time
12184 (or (org-clock-get-last-clock-out-time) ct))
12185 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12186 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12187 (t ct))))
12188 ct1))
12189
12190 (defun org-todo-yesterday (&optional arg)
12191 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12192 (interactive "P")
12193 (if (eq major-mode 'org-agenda-mode)
12194 (apply 'org-agenda-todo-yesterday arg)
12195 (let* ((hour (third (decode-time
12196 (org-current-time))))
12197 (org-extend-today-until (1+ hour)))
12198 (org-todo arg))))
12199
12200 (defvar org-block-entry-blocking ""
12201 "First entry preventing the TODO state change.")
12202
12203 (defun org-todo (&optional arg)
12204 "Change the TODO state of an item.
12205 The state of an item is given by a keyword at the start of the heading,
12206 like
12207 *** TODO Write paper
12208 *** DONE Call mom
12209
12210 The different keywords are specified in the variable `org-todo-keywords'.
12211 By default the available states are \"TODO\" and \"DONE\".
12212 So for this example: when the item starts with TODO, it is changed to DONE.
12213 When it starts with DONE, the DONE is removed. And when neither TODO nor
12214 DONE are present, add TODO at the beginning of the heading.
12215
12216 With \\[universal-argument] prefix arg, use completion to determine the new \
12217 state.
12218 With numeric prefix arg, switch to that state.
12219 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12220 keywords (nextset).
12221 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12222 With a numeric prefix arg of 0, inhibit note taking for the change.
12223
12224 For calling through lisp, arg is also interpreted in the following way:
12225 `none' -> empty state
12226 \"\" (empty string) -> switch to empty state
12227 `done' -> switch to DONE
12228 `nextset' -> switch to the next set of keywords
12229 `previousset' -> switch to the previous set of keywords
12230 \"WAITING\" -> switch to the specified keyword, but only if it
12231 really is a member of `org-todo-keywords'."
12232 (interactive "P")
12233 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12234 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12235 'region-start-level 'region))
12236 org-loop-over-headlines-in-active-region)
12237 (org-map-entries
12238 `(org-todo ,arg)
12239 org-loop-over-headlines-in-active-region
12240 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12241 (if (equal arg '(16)) (setq arg 'nextset))
12242 (let ((org-blocker-hook org-blocker-hook)
12243 commentp
12244 case-fold-search)
12245 (when (equal arg '(64))
12246 (setq arg nil org-blocker-hook nil))
12247 (when (and org-blocker-hook
12248 (or org-inhibit-blocking
12249 (org-entry-get nil "NOBLOCKING")))
12250 (setq org-blocker-hook nil))
12251 (save-excursion
12252 (catch 'exit
12253 (org-back-to-heading t)
12254 (when (looking-at (concat "^\\*+ " org-comment-string))
12255 (org-toggle-comment)
12256 (setq commentp t))
12257 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12258 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12259 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12260 (let* ((match-data (match-data))
12261 (startpos (point-at-bol))
12262 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12263 (org-log-done org-log-done)
12264 (org-log-repeat org-log-repeat)
12265 (org-todo-log-states org-todo-log-states)
12266 (org-inhibit-logging
12267 (if (equal arg 0)
12268 (progn (setq arg nil) 'note) org-inhibit-logging))
12269 (this (match-string 1))
12270 (hl-pos (match-beginning 0))
12271 (head (org-get-todo-sequence-head this))
12272 (ass (assoc head org-todo-kwd-alist))
12273 (interpret (nth 1 ass))
12274 (done-word (nth 3 ass))
12275 (final-done-word (nth 4 ass))
12276 (org-last-state (or this ""))
12277 (completion-ignore-case t)
12278 (member (member this org-todo-keywords-1))
12279 (tail (cdr member))
12280 (org-state (cond
12281 ((and org-todo-key-trigger
12282 (or (and (equal arg '(4))
12283 (eq org-use-fast-todo-selection 'prefix))
12284 (and (not arg) org-use-fast-todo-selection
12285 (not (eq org-use-fast-todo-selection
12286 'prefix)))))
12287 ;; Use fast selection
12288 (org-fast-todo-selection))
12289 ((and (equal arg '(4))
12290 (or (not org-use-fast-todo-selection)
12291 (not org-todo-key-trigger)))
12292 ;; Read a state with completion
12293 (org-icompleting-read
12294 "State: " (mapcar 'list org-todo-keywords-1)
12295 nil t))
12296 ((eq arg 'right)
12297 (if this
12298 (if tail (car tail) nil)
12299 (car org-todo-keywords-1)))
12300 ((eq arg 'left)
12301 (if (equal member org-todo-keywords-1)
12302 nil
12303 (if this
12304 (nth (- (length org-todo-keywords-1)
12305 (length tail) 2)
12306 org-todo-keywords-1)
12307 (org-last org-todo-keywords-1))))
12308 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12309 (setq arg nil))) ; hack to fall back to cycling
12310 (arg
12311 ;; user or caller requests a specific state
12312 (cond
12313 ((equal arg "") nil)
12314 ((eq arg 'none) nil)
12315 ((eq arg 'done) (or done-word (car org-done-keywords)))
12316 ((eq arg 'nextset)
12317 (or (car (cdr (member head org-todo-heads)))
12318 (car org-todo-heads)))
12319 ((eq arg 'previousset)
12320 (let ((org-todo-heads (reverse org-todo-heads)))
12321 (or (car (cdr (member head org-todo-heads)))
12322 (car org-todo-heads))))
12323 ((car (member arg org-todo-keywords-1)))
12324 ((stringp arg)
12325 (user-error "State `%s' not valid in this file" arg))
12326 ((nth (1- (prefix-numeric-value arg))
12327 org-todo-keywords-1))))
12328 ((null member) (or head (car org-todo-keywords-1)))
12329 ((equal this final-done-word) nil) ;; -> make empty
12330 ((null tail) nil) ;; -> first entry
12331 ((memq interpret '(type priority))
12332 (if (eq this-command last-command)
12333 (car tail)
12334 (if (> (length tail) 0)
12335 (or done-word (car org-done-keywords))
12336 nil)))
12337 (t
12338 (car tail))))
12339 (org-state (or
12340 (run-hook-with-args-until-success
12341 'org-todo-get-default-hook org-state org-last-state)
12342 org-state))
12343 (next (if org-state (concat " " org-state " ") " "))
12344 (change-plist (list :type 'todo-state-change :from this :to org-state
12345 :position startpos))
12346 dolog now-done-p)
12347 (when org-blocker-hook
12348 (setq org-last-todo-state-is-todo
12349 (not (member this org-done-keywords)))
12350 (unless (save-excursion
12351 (save-match-data
12352 (org-with-wide-buffer
12353 (run-hook-with-args-until-failure
12354 'org-blocker-hook change-plist))))
12355 (if (org-called-interactively-p 'interactive)
12356 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12357 this org-state org-block-entry-blocking)
12358 ;; fail silently
12359 (message "TODO state change from %s to %s blocked (by \"%s\")"
12360 this org-state org-block-entry-blocking)
12361 (throw 'exit nil))))
12362 (store-match-data match-data)
12363 (replace-match next t t)
12364 (unless (pos-visible-in-window-p hl-pos)
12365 (message "TODO state changed to %s" (org-trim next)))
12366 (unless head
12367 (setq head (org-get-todo-sequence-head org-state)
12368 ass (assoc head org-todo-kwd-alist)
12369 interpret (nth 1 ass)
12370 done-word (nth 3 ass)
12371 final-done-word (nth 4 ass)))
12372 (when (memq arg '(nextset previousset))
12373 (message "Keyword-Set %d/%d: %s"
12374 (- (length org-todo-sets) -1
12375 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12376 (length org-todo-sets)
12377 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12378 (setq org-last-todo-state-is-todo
12379 (not (member org-state org-done-keywords)))
12380 (setq now-done-p (and (member org-state org-done-keywords)
12381 (not (member this org-done-keywords))))
12382 (and logging (org-local-logging logging))
12383 (when (and (or org-todo-log-states org-log-done)
12384 (not (eq org-inhibit-logging t))
12385 (not (memq arg '(nextset previousset))))
12386 ;; we need to look at recording a time and note
12387 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12388 (nth 2 (assoc this org-todo-log-states))))
12389 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12390 (setq dolog 'time))
12391 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12392 (and org-state
12393 (member org-state org-not-done-keywords)
12394 (not (member this org-not-done-keywords))))
12395 ;; This is now a todo state and was not one before
12396 ;; If there was a CLOSED time stamp, get rid of it.
12397 (org-add-planning-info nil nil 'closed))
12398 (when (and now-done-p org-log-done)
12399 ;; It is now done, and it was not done before
12400 (org-add-planning-info 'closed (org-current-effective-time))
12401 (if (and (not dolog) (eq 'note org-log-done))
12402 (org-add-log-setup 'done org-state this 'findpos 'note)))
12403 (when (and org-state dolog)
12404 ;; This is a non-nil state, and we need to log it
12405 (org-add-log-setup 'state org-state this 'findpos dolog)))
12406 ;; Fixup tag positioning
12407 (org-todo-trigger-tag-changes org-state)
12408 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12409 (when org-provide-todo-statistics
12410 (org-update-parent-todo-statistics))
12411 (run-hooks 'org-after-todo-state-change-hook)
12412 (if (and arg (not (member org-state org-done-keywords)))
12413 (setq head (org-get-todo-sequence-head org-state)))
12414 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12415 ;; Do we need to trigger a repeat?
12416 (when now-done-p
12417 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12418 ;; This is for the agenda, take a snapshot of the headline.
12419 (save-match-data
12420 (setq org-agenda-headline-snapshot-before-repeat
12421 (org-get-heading))))
12422 (org-auto-repeat-maybe org-state))
12423 ;; Fixup cursor location if close to the keyword
12424 (if (and (outline-on-heading-p)
12425 (not (bolp))
12426 (save-excursion (beginning-of-line 1)
12427 (looking-at org-todo-line-regexp))
12428 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12429 (progn
12430 (goto-char (or (match-end 2) (match-end 1)))
12431 (and (looking-at " ") (just-one-space))))
12432 (when org-trigger-hook
12433 (save-excursion
12434 (run-hook-with-args 'org-trigger-hook change-plist)))
12435 (when commentp (org-toggle-comment))))))))
12436
12437 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12438 "Block turning an entry into a TODO, using the hierarchy.
12439 This checks whether the current task should be blocked from state
12440 changes. Such blocking occurs when:
12441
12442 1. The task has children which are not all in a completed state.
12443
12444 2. A task has a parent with the property :ORDERED:, and there
12445 are siblings prior to the current task with incomplete
12446 status.
12447
12448 3. The parent of the task is blocked because it has siblings that should
12449 be done first, or is child of a block grandparent TODO entry."
12450
12451 (if (not org-enforce-todo-dependencies)
12452 t ; if locally turned off don't block
12453 (catch 'dont-block
12454 ;; If this is not a todo state change, or if this entry is already DONE,
12455 ;; do not block
12456 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12457 (member (plist-get change-plist :from)
12458 (cons 'done org-done-keywords))
12459 (member (plist-get change-plist :to)
12460 (cons 'todo org-not-done-keywords))
12461 (not (plist-get change-plist :to)))
12462 (throw 'dont-block t))
12463 ;; If this task has children, and any are undone, it's blocked
12464 (save-excursion
12465 (org-back-to-heading t)
12466 (let ((this-level (funcall outline-level)))
12467 (outline-next-heading)
12468 (let ((child-level (funcall outline-level)))
12469 (while (and (not (eobp))
12470 (> child-level this-level))
12471 ;; this todo has children, check whether they are all
12472 ;; completed
12473 (if (and (not (org-entry-is-done-p))
12474 (org-entry-is-todo-p))
12475 (progn (setq org-block-entry-blocking (org-get-heading))
12476 (throw 'dont-block nil)))
12477 (outline-next-heading)
12478 (setq child-level (funcall outline-level))))))
12479 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12480 ;; any previous siblings are undone, it's blocked
12481 (save-excursion
12482 (org-back-to-heading t)
12483 (let* ((pos (point))
12484 (parent-pos (and (org-up-heading-safe) (point))))
12485 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12486 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12487 (forward-line 1)
12488 (re-search-forward org-not-done-heading-regexp pos t))
12489 (setq org-block-entry-blocking (match-string 0))
12490 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12491 ;; Search further up the hierarchy, to see if an ancestor is blocked
12492 (while t
12493 (goto-char parent-pos)
12494 (if (not (looking-at org-not-done-heading-regexp))
12495 (throw 'dont-block t)) ; do not block, parent is not a TODO
12496 (setq pos (point))
12497 (setq parent-pos (and (org-up-heading-safe) (point)))
12498 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12499 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12500 (forward-line 1)
12501 (re-search-forward org-not-done-heading-regexp pos t)
12502 (setq org-block-entry-blocking (org-get-heading)))
12503 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12504
12505 (defcustom org-track-ordered-property-with-tag nil
12506 "Should the ORDERED property also be shown as a tag?
12507 The ORDERED property decides if an entry should require subtasks to be
12508 completed in sequence. Since a property is not very visible, setting
12509 this option means that toggling the ORDERED property with the command
12510 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12511 not relevant for the behavior, but it makes things more visible.
12512
12513 Note that toggling the tag with tags commands will not change the property
12514 and therefore not influence behavior!
12515
12516 This can be t, meaning the tag ORDERED should be used, It can also be a
12517 string to select a different tag for this task."
12518 :group 'org-todo
12519 :type '(choice
12520 (const :tag "No tracking" nil)
12521 (const :tag "Track with ORDERED tag" t)
12522 (string :tag "Use other tag")))
12523
12524 (defun org-toggle-ordered-property ()
12525 "Toggle the ORDERED property of the current entry.
12526 For better visibility, you can track the value of this property with a tag.
12527 See variable `org-track-ordered-property-with-tag'."
12528 (interactive)
12529 (let* ((t1 org-track-ordered-property-with-tag)
12530 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12531 (save-excursion
12532 (org-back-to-heading)
12533 (if (org-entry-get nil "ORDERED")
12534 (progn
12535 (org-delete-property "ORDERED" "PROPERTIES")
12536 (and tag (org-toggle-tag tag 'off))
12537 (message "Subtasks can be completed in arbitrary order"))
12538 (org-entry-put nil "ORDERED" "t")
12539 (and tag (org-toggle-tag tag 'on))
12540 (message "Subtasks must be completed in sequence")))))
12541
12542 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12543 (defun org-block-todo-from-checkboxes (change-plist)
12544 "Block turning an entry into a TODO, using checkboxes.
12545 This checks whether the current task should be blocked from state
12546 changes because there are unchecked boxes in this entry."
12547 (if (not org-enforce-todo-checkbox-dependencies)
12548 t ; if locally turned off don't block
12549 (catch 'dont-block
12550 ;; If this is not a todo state change, or if this entry is already DONE,
12551 ;; do not block
12552 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12553 (member (plist-get change-plist :from)
12554 (cons 'done org-done-keywords))
12555 (member (plist-get change-plist :to)
12556 (cons 'todo org-not-done-keywords))
12557 (not (plist-get change-plist :to)))
12558 (throw 'dont-block t))
12559 ;; If this task has checkboxes that are not checked, it's blocked
12560 (save-excursion
12561 (org-back-to-heading t)
12562 (let ((beg (point)) end)
12563 (outline-next-heading)
12564 (setq end (point))
12565 (goto-char beg)
12566 (if (org-list-search-forward
12567 (concat (org-item-beginning-re)
12568 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12569 "\\[[- ]\\]")
12570 end t)
12571 (progn
12572 (if (boundp 'org-blocked-by-checkboxes)
12573 (setq org-blocked-by-checkboxes t))
12574 (throw 'dont-block nil)))))
12575 t))) ; do not block
12576
12577 (defun org-entry-blocked-p ()
12578 "Is the current entry blocked?"
12579 (org-with-silent-modifications
12580 (if (org-entry-get nil "NOBLOCKING")
12581 nil ;; Never block this entry
12582 (not (run-hook-with-args-until-failure
12583 'org-blocker-hook
12584 (list :type 'todo-state-change
12585 :position (point)
12586 :from 'todo
12587 :to 'done))))))
12588
12589 (defun org-update-statistics-cookies (all)
12590 "Update the statistics cookie, either from TODO or from checkboxes.
12591 This should be called with the cursor in a line with a statistics cookie."
12592 (interactive "P")
12593 (if all
12594 (progn
12595 (org-update-checkbox-count 'all)
12596 (org-map-entries 'org-update-parent-todo-statistics))
12597 (if (not (org-at-heading-p))
12598 (org-update-checkbox-count)
12599 (let ((pos (point-marker))
12600 end l1 l2)
12601 (ignore-errors (org-back-to-heading t))
12602 (if (not (org-at-heading-p))
12603 (org-update-checkbox-count)
12604 (setq l1 (org-outline-level))
12605 (setq end (save-excursion
12606 (outline-next-heading)
12607 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12608 (point)))
12609 (if (and (save-excursion
12610 (re-search-forward
12611 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12612 (not (save-excursion (re-search-forward
12613 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12614 (org-update-checkbox-count)
12615 (if (and l2 (> l2 l1))
12616 (progn
12617 (goto-char end)
12618 (org-update-parent-todo-statistics))
12619 (goto-char pos)
12620 (beginning-of-line 1)
12621 (while (re-search-forward
12622 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12623 (point-at-eol) t)
12624 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12625 (goto-char pos)
12626 (move-marker pos nil)))))
12627
12628 (defvar org-entry-property-inherited-from) ;; defined below
12629 (defun org-update-parent-todo-statistics ()
12630 "Update any statistics cookie in the parent of the current headline.
12631 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12632 the entire subtree and this will travel up the hierarchy and update
12633 statistics everywhere."
12634 (let* ((prop (save-excursion (org-up-heading-safe)
12635 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12636 (recursive (or (not org-hierarchical-todo-statistics)
12637 (and prop (string-match "\\<recursive\\>" prop))))
12638 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12639 0))
12640 (first t)
12641 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12642 level ltoggle l1 new ndel
12643 (cnt-all 0) (cnt-done 0) is-percent kwd
12644 checkbox-beg ov ovs ove cookie-present)
12645 (catch 'exit
12646 (save-excursion
12647 (beginning-of-line 1)
12648 (setq ltoggle (funcall outline-level))
12649 ;; Three situations are to consider:
12650
12651 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12652 ;; to the top-level ancestor on the headline;
12653
12654 ;; 2. If parent has "recursive" property, repeat up to the
12655 ;; headline setting that property, taking inheritance into
12656 ;; account;
12657
12658 ;; 3. Else, move up to direct parent and proceed only once.
12659 (while (and (setq level (org-up-heading-safe))
12660 (or recursive first)
12661 (>= (point) lim))
12662 (setq first nil cookie-present nil)
12663 (unless (and level
12664 (not (string-match
12665 "\\<checkbox\\>"
12666 (downcase (or (org-entry-get nil "COOKIE_DATA")
12667 "")))))
12668 (throw 'exit nil))
12669 (while (re-search-forward box-re (point-at-eol) t)
12670 (setq cnt-all 0 cnt-done 0 cookie-present t)
12671 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12672 (save-match-data
12673 (unless (outline-next-heading) (throw 'exit nil))
12674 (while (and (looking-at org-complex-heading-regexp)
12675 (> (setq l1 (length (match-string 1))) level))
12676 (setq kwd (and (or recursive (= l1 ltoggle))
12677 (match-string 2)))
12678 (if (or (eq org-provide-todo-statistics 'all-headlines)
12679 (and (listp org-provide-todo-statistics)
12680 (or (member kwd org-provide-todo-statistics)
12681 (member kwd org-done-keywords))))
12682 (setq cnt-all (1+ cnt-all))
12683 (if (eq org-provide-todo-statistics t)
12684 (and kwd (setq cnt-all (1+ cnt-all)))))
12685 (and (member kwd org-done-keywords)
12686 (setq cnt-done (1+ cnt-done)))
12687 (outline-next-heading)))
12688 (setq new
12689 (if is-percent
12690 (format "[%d%%]" (floor (* 100.0 cnt-done)
12691 (max 1 cnt-all)))
12692 (format "[%d/%d]" cnt-done cnt-all))
12693 ndel (- (match-end 0) checkbox-beg))
12694 ;; handle overlays when updating cookie from column view
12695 (when (setq ov (car (overlays-at checkbox-beg)))
12696 (setq ovs (overlay-start ov) ove (overlay-end ov))
12697 (delete-overlay ov))
12698 (goto-char checkbox-beg)
12699 (insert new)
12700 (delete-region (point) (+ (point) ndel))
12701 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12702 (when ov (move-overlay ov ovs ove)))
12703 (when cookie-present
12704 (run-hook-with-args 'org-after-todo-statistics-hook
12705 cnt-done (- cnt-all cnt-done))))))
12706 (run-hooks 'org-todo-statistics-hook)))
12707
12708 (defvar org-after-todo-statistics-hook nil
12709 "Hook that is called after a TODO statistics cookie has been updated.
12710 Each function is called with two arguments: the number of not-done entries
12711 and the number of done entries.
12712
12713 For example, the following function, when added to this hook, will switch
12714 an entry to DONE when all children are done, and back to TODO when new
12715 entries are set to a TODO status. Note that this hook is only called
12716 when there is a statistics cookie in the headline!
12717
12718 (defun org-summary-todo (n-done n-not-done)
12719 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12720 (let (org-log-done org-log-states) ; turn off logging
12721 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12722 ")
12723
12724 (defvar org-todo-statistics-hook nil
12725 "Hook that is run whenever Org thinks TODO statistics should be updated.
12726 This hook runs even if there is no statistics cookie present, in which case
12727 `org-after-todo-statistics-hook' would not run.")
12728
12729 (defun org-todo-trigger-tag-changes (state)
12730 "Apply the changes defined in `org-todo-state-tags-triggers'."
12731 (let ((l org-todo-state-tags-triggers)
12732 changes)
12733 (when (or (not state) (equal state ""))
12734 (setq changes (append changes (cdr (assoc "" l)))))
12735 (when (and (stringp state) (> (length state) 0))
12736 (setq changes (append changes (cdr (assoc state l)))))
12737 (when (member state org-not-done-keywords)
12738 (setq changes (append changes (cdr (assoc 'todo l)))))
12739 (when (member state org-done-keywords)
12740 (setq changes (append changes (cdr (assoc 'done l)))))
12741 (dolist (c changes)
12742 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12743
12744 (defun org-local-logging (value)
12745 "Get logging settings from a property VALUE."
12746 ;; Directly set the variables, they are already local.
12747 (setq org-log-done nil
12748 org-log-repeat nil
12749 org-todo-log-states nil)
12750 (dolist (w (org-split-string value))
12751 (let* (a)
12752 (cond
12753 ((setq a (assoc w org-startup-options))
12754 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12755 (set (nth 1 a) (nth 2 a))))
12756 ((setq a (org-extract-log-state-settings w))
12757 (and (member (car a) org-todo-keywords-1)
12758 (push a org-todo-log-states)))))))
12759
12760 (defun org-get-todo-sequence-head (kwd)
12761 "Return the head of the TODO sequence to which KWD belongs.
12762 If KWD is not set, check if there is a text property remembering the
12763 right sequence."
12764 (let (p)
12765 (cond
12766 ((not kwd)
12767 (or (get-text-property (point-at-bol) 'org-todo-head)
12768 (progn
12769 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12770 nil (point-at-eol)))
12771 (get-text-property p 'org-todo-head))))
12772 ((not (member kwd org-todo-keywords-1))
12773 (car org-todo-keywords-1))
12774 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12775
12776 (defun org-fast-todo-selection ()
12777 "Fast TODO keyword selection with single keys.
12778 Returns the new TODO keyword, or nil if no state change should occur."
12779 (let* ((fulltable org-todo-key-alist)
12780 (done-keywords org-done-keywords) ;; needed for the faces.
12781 (maxlen (apply 'max (mapcar
12782 (lambda (x)
12783 (if (stringp (car x)) (string-width (car x)) 0))
12784 fulltable)))
12785 (expert nil)
12786 (fwidth (+ maxlen 3 1 3))
12787 (ncol (/ (- (window-width) 4) fwidth))
12788 tg cnt c tbl
12789 groups ingroup)
12790 (save-excursion
12791 (save-window-excursion
12792 (if expert
12793 (set-buffer (get-buffer-create " *Org todo*"))
12794 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12795 (erase-buffer)
12796 (org-set-local 'org-done-keywords done-keywords)
12797 (setq tbl fulltable cnt 0)
12798 (dolist (e tbl)
12799 (cond
12800 ((equal e '(:startgroup))
12801 (push '() groups) (setq ingroup t)
12802 (when (not (= cnt 0))
12803 (setq cnt 0)
12804 (insert "\n"))
12805 (insert "{ "))
12806 ((equal e '(:endgroup))
12807 (setq ingroup nil cnt 0)
12808 (insert "}\n"))
12809 ((equal e '(:newline))
12810 (when (not (= cnt 0))
12811 (setq cnt 0)
12812 (insert "\n")
12813 (setq e (car tbl))
12814 (while (equal (car tbl) '(:newline))
12815 (insert "\n")
12816 (setq tbl (cdr tbl)))))
12817 (t
12818 (setq tg (car e) c (cdr e))
12819 (if ingroup (push tg (car groups)))
12820 (setq tg (org-add-props tg nil 'face
12821 (org-get-todo-face tg)))
12822 (if (and (= cnt 0) (not ingroup)) (insert " "))
12823 (insert "[" c "] " tg (make-string
12824 (- fwidth 4 (length tg)) ?\ ))
12825 (when (= (setq cnt (1+ cnt)) ncol)
12826 (insert "\n")
12827 (if ingroup (insert " "))
12828 (setq cnt 0)))))
12829 (insert "\n")
12830 (goto-char (point-min))
12831 (if (not expert) (org-fit-window-to-buffer))
12832 (message "[a-z..]:Set [SPC]:clear")
12833 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12834 (cond
12835 ((or (= c ?\C-g)
12836 (and (= c ?q) (not (rassoc c fulltable))))
12837 (setq quit-flag t))
12838 ((= c ?\ ) nil)
12839 ((setq e (rassoc c fulltable) tg (car e))
12840 tg)
12841 (t (setq quit-flag t)))))))
12842
12843 (defun org-entry-is-todo-p ()
12844 (member (org-get-todo-state) org-not-done-keywords))
12845
12846 (defun org-entry-is-done-p ()
12847 (member (org-get-todo-state) org-done-keywords))
12848
12849 (defun org-get-todo-state ()
12850 "Return the TODO keyword of the current subtree."
12851 (save-excursion
12852 (org-back-to-heading t)
12853 (and (looking-at org-todo-line-regexp)
12854 (match-end 2)
12855 (match-string 2))))
12856
12857 (defun org-at-date-range-p (&optional inactive-ok)
12858 "Is the cursor inside a date range?"
12859 (interactive)
12860 (save-excursion
12861 (catch 'exit
12862 (let ((pos (point)))
12863 (skip-chars-backward "^[<\r\n")
12864 (skip-chars-backward "<[")
12865 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12866 (>= (match-end 0) pos)
12867 (throw 'exit t))
12868 (skip-chars-backward "^<[\r\n")
12869 (skip-chars-backward "<[")
12870 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12871 (>= (match-end 0) pos)
12872 (throw 'exit t)))
12873 nil)))
12874
12875 (defun org-get-repeat (&optional tagline)
12876 "Check if there is a deadline/schedule with repeater in this entry."
12877 (save-match-data
12878 (save-excursion
12879 (org-back-to-heading t)
12880 (and (re-search-forward (if tagline
12881 (concat tagline "\\s-*" org-repeat-re)
12882 org-repeat-re)
12883 (org-entry-end-position) t)
12884 (match-string-no-properties 1)))))
12885
12886 (defvar org-last-changed-timestamp)
12887 (defvar org-last-inserted-timestamp)
12888 (defvar org-log-post-message)
12889 (defvar org-log-note-purpose)
12890 (defvar org-log-note-how)
12891 (defvar org-log-note-extra)
12892 (defun org-auto-repeat-maybe (done-word)
12893 "Check if the current headline contains a repeated deadline/schedule.
12894 If yes, set TODO state back to what it was and change the base date
12895 of repeating deadline/scheduled time stamps to new date.
12896 This function is run automatically after each state change to a DONE state."
12897 ;; last-state is dynamically scoped into this function
12898 (let* ((repeat (org-get-repeat))
12899 (aa (assoc org-last-state org-todo-kwd-alist))
12900 (interpret (nth 1 aa))
12901 (head (nth 2 aa))
12902 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12903 (msg "Entry repeats: ")
12904 (org-log-done nil)
12905 (org-todo-log-states nil)
12906 re type n what ts time to-state)
12907 (when repeat
12908 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12909 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12910 org-todo-repeat-to-state))
12911 (unless (and to-state (member to-state org-todo-keywords-1))
12912 (setq to-state (if (eq interpret 'type) org-last-state head)))
12913 (org-todo to-state)
12914 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12915 (org-entry-put nil "LAST_REPEAT" (format-time-string
12916 (org-time-stamp-format t t))))
12917 (when org-log-repeat
12918 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12919 (memq 'org-add-log-note post-command-hook))
12920 ;; OK, we are already setup for some record
12921 (if (eq org-log-repeat 'note)
12922 ;; make sure we take a note, not only a time stamp
12923 (setq org-log-note-how 'note))
12924 ;; Set up for taking a record
12925 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12926 org-last-state
12927 'findpos org-log-repeat)))
12928 (org-back-to-heading t)
12929 (org-add-planning-info nil nil 'closed)
12930 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12931 org-deadline-time-regexp "\\)\\|\\("
12932 org-ts-regexp "\\)"))
12933 (while (re-search-forward
12934 re (save-excursion (outline-next-heading) (point)) t)
12935 (setq type (if (match-end 1) org-scheduled-string
12936 (if (match-end 3) org-deadline-string "Plain:"))
12937 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12938 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12939 (setq n (string-to-number (match-string 2 ts))
12940 what (match-string 3 ts))
12941 (if (equal what "w") (setq n (* n 7) what "d"))
12942 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12943 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12944 ;; Preparation, see if we need to modify the start date for the change
12945 (when (match-end 1)
12946 (setq time (save-match-data (org-time-string-to-time ts)))
12947 (cond
12948 ((equal (match-string 1 ts) ".")
12949 ;; Shift starting date to today
12950 (org-timestamp-change
12951 (- (org-today) (time-to-days time))
12952 'day))
12953 ((equal (match-string 1 ts) "+")
12954 (let ((nshiftmax 10) (nshift 0))
12955 (while (or (= nshift 0)
12956 (<= (time-to-days time)
12957 (time-to-days (current-time))))
12958 (when (= (incf nshift) nshiftmax)
12959 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12960 (error "Abort")))
12961 (org-timestamp-change n (cdr (assoc what whata)))
12962 (org-at-timestamp-p t)
12963 (setq ts (match-string 1))
12964 (setq time (save-match-data (org-time-string-to-time ts)))))
12965 (org-timestamp-change (- n) (cdr (assoc what whata)))
12966 ;; rematch, so that we have everything in place for the real shift
12967 (org-at-timestamp-p t)
12968 (setq ts (match-string 1))
12969 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12970 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12971 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12972 (setq org-log-post-message msg)
12973 (message "%s" msg))))
12974
12975 (defun org-show-todo-tree (arg)
12976 "Make a compact tree which shows all headlines marked with TODO.
12977 The tree will show the lines where the regexp matches, and all higher
12978 headlines above the match.
12979 With a \\[universal-argument] prefix, prompt for a regexp to match.
12980 With a numeric prefix N, construct a sparse tree for the Nth element
12981 of `org-todo-keywords-1'."
12982 (interactive "P")
12983 (let ((case-fold-search nil)
12984 (kwd-re
12985 (cond ((null arg) org-not-done-regexp)
12986 ((equal arg '(4))
12987 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12988 (mapcar 'list org-todo-keywords-1))))
12989 (concat "\\("
12990 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12991 "\\)\\>")))
12992 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12993 (regexp-quote (nth (1- (prefix-numeric-value arg))
12994 org-todo-keywords-1)))
12995 (t (user-error "Invalid prefix argument: %s" arg)))))
12996 (message "%d TODO entries found"
12997 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12998
12999 (defun org-deadline (arg &optional time)
13000 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13001 With one universal prefix argument, remove any deadline from the item.
13002 With two universal prefix arguments, prompt for a warning delay.
13003 With argument TIME, set the deadline at the corresponding date. TIME
13004 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13005 (interactive "P")
13006 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13007 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13008 'region-start-level 'region))
13009 org-loop-over-headlines-in-active-region)
13010 (org-map-entries
13011 `(org-deadline ',arg ,time)
13012 org-loop-over-headlines-in-active-region
13013 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13014 (let* ((old-date (org-entry-get nil "DEADLINE"))
13015 (old-date-time (if old-date (org-time-string-to-time old-date)))
13016 (repeater (and old-date
13017 (string-match
13018 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13019 old-date)
13020 (match-string 1 old-date))))
13021 (cond
13022 ((equal arg '(4))
13023 (when (and old-date org-log-redeadline)
13024 (org-add-log-setup 'deldeadline nil old-date 'findpos
13025 org-log-redeadline))
13026 (org-remove-timestamp-with-keyword org-deadline-string)
13027 (message "Item no longer has a deadline."))
13028 ((equal arg '(16))
13029 (save-excursion
13030 (org-back-to-heading t)
13031 (if (re-search-forward
13032 org-deadline-time-regexp
13033 (save-excursion (outline-next-heading) (point)) t)
13034 (let* ((rpl0 (match-string 1))
13035 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13036 (replace-match
13037 (concat org-deadline-string
13038 " <" rpl
13039 (format " -%dd"
13040 (abs
13041 (- (time-to-days
13042 (save-match-data
13043 (org-read-date nil t nil "Warn starting from" old-date-time)))
13044 (time-to-days old-date-time))))
13045 ">") t t))
13046 (user-error "No deadline information to update"))))
13047 (t
13048 (org-add-planning-info 'deadline time 'closed)
13049 (when (and old-date org-log-redeadline
13050 (not (equal old-date
13051 (substring org-last-inserted-timestamp 1 -1))))
13052 (org-add-log-setup 'redeadline nil old-date 'findpos
13053 org-log-redeadline))
13054 (when repeater
13055 (save-excursion
13056 (org-back-to-heading t)
13057 (when (re-search-forward (concat org-deadline-string " "
13058 org-last-inserted-timestamp)
13059 (save-excursion
13060 (outline-next-heading) (point)) t)
13061 (goto-char (1- (match-end 0)))
13062 (insert " " repeater)
13063 (setq org-last-inserted-timestamp
13064 (concat (substring org-last-inserted-timestamp 0 -1)
13065 " " repeater
13066 (substring org-last-inserted-timestamp -1))))))
13067 (message "Deadline on %s" org-last-inserted-timestamp))))))
13068
13069 (defun org-schedule (arg &optional time)
13070 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13071 With one universal prefix argument, remove any scheduling date from the item.
13072 With two universal prefix arguments, prompt for a delay cookie.
13073 With argument TIME, scheduled at the corresponding date. TIME can
13074 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13075 (interactive "P")
13076 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13077 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13078 'region-start-level 'region))
13079 org-loop-over-headlines-in-active-region)
13080 (org-map-entries
13081 `(org-schedule ',arg ,time)
13082 org-loop-over-headlines-in-active-region
13083 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13084 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13085 (old-date-time (if old-date (org-time-string-to-time old-date)))
13086 (repeater (and old-date
13087 (string-match
13088 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13089 old-date)
13090 (match-string 1 old-date))))
13091 (cond
13092 ((equal arg '(4))
13093 (progn
13094 (when (and old-date org-log-reschedule)
13095 (org-add-log-setup 'delschedule nil old-date 'findpos
13096 org-log-reschedule))
13097 (org-remove-timestamp-with-keyword org-scheduled-string)
13098 (message "Item is no longer scheduled.")))
13099 ((equal arg '(16))
13100 (save-excursion
13101 (org-back-to-heading t)
13102 (if (re-search-forward
13103 org-scheduled-time-regexp
13104 (save-excursion (outline-next-heading) (point)) t)
13105 (let* ((rpl0 (match-string 1))
13106 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13107 (replace-match
13108 (concat org-scheduled-string
13109 " <" rpl
13110 (format " -%dd"
13111 (abs
13112 (- (time-to-days
13113 (save-match-data
13114 (org-read-date nil t nil "Delay until" old-date-time)))
13115 (time-to-days old-date-time))))
13116 ">") t t))
13117 (user-error "No scheduled information to update"))))
13118 (t
13119 (org-add-planning-info 'scheduled time 'closed)
13120 (when (and old-date org-log-reschedule
13121 (not (equal old-date
13122 (substring org-last-inserted-timestamp 1 -1))))
13123 (org-add-log-setup 'reschedule nil old-date 'findpos
13124 org-log-reschedule))
13125 (when repeater
13126 (save-excursion
13127 (org-back-to-heading t)
13128 (when (re-search-forward (concat org-scheduled-string " "
13129 org-last-inserted-timestamp)
13130 (save-excursion
13131 (outline-next-heading) (point)) t)
13132 (goto-char (1- (match-end 0)))
13133 (insert " " repeater)
13134 (setq org-last-inserted-timestamp
13135 (concat (substring org-last-inserted-timestamp 0 -1)
13136 " " repeater
13137 (substring org-last-inserted-timestamp -1))))))
13138 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13139
13140 (defun org-get-scheduled-time (pom &optional inherit)
13141 "Get the scheduled time as a time tuple, of a format suitable
13142 for calling org-schedule with, or if there is no scheduling,
13143 returns nil."
13144 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13145 (when time
13146 (apply 'encode-time (org-parse-time-string time)))))
13147
13148 (defun org-get-deadline-time (pom &optional inherit)
13149 "Get the deadline as a time tuple, of a format suitable for
13150 calling org-deadline with, or if there is no scheduling, returns
13151 nil."
13152 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13153 (when time
13154 (apply 'encode-time (org-parse-time-string time)))))
13155
13156 (defun org-remove-timestamp-with-keyword (keyword)
13157 "Remove all time stamps with KEYWORD in the current entry."
13158 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13159 beg)
13160 (save-excursion
13161 (org-back-to-heading t)
13162 (setq beg (point))
13163 (outline-next-heading)
13164 (while (re-search-backward re beg t)
13165 (replace-match "")
13166 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13167 (equal (char-before) ?\ ))
13168 (backward-delete-char 1)
13169 (if (string-match "^[ \t]*$" (buffer-substring
13170 (point-at-bol) (point-at-eol)))
13171 (delete-region (point-at-bol)
13172 (min (point-max) (1+ (point-at-eol))))))))))
13173
13174 (defvar org-time-was-given) ; dynamically scoped parameter
13175 (defvar org-end-time-was-given) ; dynamically scoped parameter
13176
13177 (defun org-add-planning-info (what &optional time &rest remove)
13178 "Insert new timestamp with keyword in the line directly after the headline.
13179 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13180 If non is given, the user is prompted for a date.
13181 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13182 be removed."
13183 (interactive)
13184 (let (org-time-was-given org-end-time-was-given ts
13185 end default-time default-input)
13186
13187 (catch 'exit
13188 (when (and (memq what '(scheduled deadline))
13189 (or (not time)
13190 (and (stringp time)
13191 (string-match "^[-+]+[0-9]" time))))
13192 ;; Try to get a default date/time from existing timestamp
13193 (save-excursion
13194 (org-back-to-heading t)
13195 (setq end (save-excursion (outline-next-heading) (point)))
13196 (when (re-search-forward (if (eq what 'scheduled)
13197 org-scheduled-time-regexp
13198 org-deadline-time-regexp)
13199 end t)
13200 (setq ts (match-string 1)
13201 default-time
13202 (apply 'encode-time (org-parse-time-string ts))
13203 default-input (and ts (org-get-compact-tod ts))))))
13204 (when what
13205 (setq time
13206 (if (stringp time)
13207 ;; This is a string (relative or absolute), set proper date
13208 (apply 'encode-time
13209 (org-read-date-analyze
13210 time default-time (decode-time default-time)))
13211 ;; If necessary, get the time from the user
13212 (or time (org-read-date nil 'to-time nil nil
13213 default-time default-input)))))
13214
13215 (when (and org-insert-labeled-timestamps-at-point
13216 (member what '(scheduled deadline)))
13217 (insert
13218 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13219 (org-insert-time-stamp time org-time-was-given
13220 nil nil nil (list org-end-time-was-given))
13221 (setq what nil))
13222 (save-excursion
13223 (save-restriction
13224 (let (col list elt ts buffer-invisibility-spec)
13225 (org-back-to-heading t)
13226 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13227 (goto-char (match-end 1))
13228 (setq col (current-column))
13229 (goto-char (match-end 0))
13230 (if (eobp) (insert "\n") (forward-char 1))
13231 (when (and (not what)
13232 (not (looking-at
13233 (concat "[ \t]*"
13234 org-keyword-time-not-clock-regexp))))
13235 ;; Nothing to add, nothing to remove...... :-)
13236 (throw 'exit nil))
13237 (if (and (not (looking-at org-outline-regexp))
13238 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13239 "[^\r\n]*"))
13240 (not (equal (match-string 1) org-clock-string)))
13241 (narrow-to-region (match-beginning 0) (match-end 0))
13242 (insert-before-markers "\n")
13243 (backward-char 1)
13244 (narrow-to-region (point) (point))
13245 (and org-adapt-indentation (org-indent-to-column col)))
13246 ;; Check if we have to remove something.
13247 (setq list (cons what remove))
13248 (while list
13249 (setq elt (pop list))
13250 (when (or (and (eq elt 'scheduled)
13251 (re-search-forward org-scheduled-time-regexp nil t))
13252 (and (eq elt 'deadline)
13253 (re-search-forward org-deadline-time-regexp nil t))
13254 (and (eq elt 'closed)
13255 (re-search-forward org-closed-time-regexp nil t)))
13256 (replace-match "")
13257 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13258 (and (looking-at "[ \t]+") (replace-match ""))
13259 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13260 (when what
13261 (insert
13262 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13263 (cond ((eq what 'scheduled) org-scheduled-string)
13264 ((eq what 'deadline) org-deadline-string)
13265 ((eq what 'closed) org-closed-string))
13266 " ")
13267 (setq ts (org-insert-time-stamp
13268 time
13269 (or org-time-was-given
13270 (and (eq what 'closed) org-log-done-with-time))
13271 (eq what 'closed)
13272 nil nil (list org-end-time-was-given)))
13273 (insert
13274 (if (not (or (bolp) (eq (char-before) ?\ )
13275 (memq (char-after) '(32 10))
13276 (eobp))) " " ""))
13277 (end-of-line 1))
13278 (goto-char (point-min))
13279 (widen)
13280 (if (and (looking-at "[ \t]*\n")
13281 (equal (char-before) ?\n))
13282 (delete-region (1- (point)) (point-at-eol)))
13283 ts))))))
13284
13285 (defvar org-log-note-marker (make-marker))
13286 (defvar org-log-note-purpose nil)
13287 (defvar org-log-note-state nil)
13288 (defvar org-log-note-previous-state nil)
13289 (defvar org-log-note-how nil)
13290 (defvar org-log-note-extra nil)
13291 (defvar org-log-note-window-configuration nil)
13292 (defvar org-log-note-return-to (make-marker))
13293 (defvar org-log-note-effective-time nil
13294 "Remembered current time so that dynamically scoped
13295 `org-extend-today-until' affects tha timestamps in state change
13296 log")
13297
13298 (defvar org-log-post-message nil
13299 "Message to be displayed after a log note has been stored.
13300 The auto-repeater uses this.")
13301
13302 (defun org-add-note ()
13303 "Add a note to the current entry.
13304 This is done in the same way as adding a state change note."
13305 (interactive)
13306 (org-add-log-setup 'note nil nil 'findpos nil))
13307
13308 (defvar org-property-end-re)
13309 (defun org-add-log-setup (&optional purpose state prev-state
13310 findpos how extra)
13311 "Set up the post command hook to take a note.
13312 If this is about to TODO state change, the new state is expected in STATE.
13313 When FINDPOS is non-nil, find the correct position for the note in
13314 the current entry. If not, assume that it can be inserted at point.
13315 HOW is an indicator what kind of note should be created.
13316 EXTRA is additional text that will be inserted into the notes buffer."
13317 (let* ((org-log-into-drawer (org-log-into-drawer))
13318 (drawer (cond ((stringp org-log-into-drawer)
13319 org-log-into-drawer)
13320 (org-log-into-drawer "LOGBOOK"))))
13321 (save-restriction
13322 (save-excursion
13323 (when findpos
13324 (org-back-to-heading t)
13325 (narrow-to-region (point) (save-excursion
13326 (outline-next-heading) (point)))
13327 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13328 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13329 "[^\r\n]*\\)?"))
13330 (goto-char (match-end 0))
13331 (cond
13332 (drawer
13333 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13334 nil t)
13335 (progn
13336 (goto-char (match-end 0))
13337 (or org-log-states-order-reversed
13338 (and (re-search-forward org-property-end-re nil t)
13339 (goto-char (1- (match-beginning 0))))))
13340 (insert "\n:" drawer ":\n:END:")
13341 (beginning-of-line 0)
13342 (org-indent-line)
13343 (beginning-of-line 2)
13344 (org-indent-line)
13345 (end-of-line 0)))
13346 ((and org-log-state-notes-insert-after-drawers
13347 (save-excursion
13348 (forward-line) (looking-at org-drawer-regexp)))
13349 (forward-line)
13350 (while (looking-at org-drawer-regexp)
13351 (goto-char (match-end 0))
13352 (re-search-forward org-property-end-re (point-max) t)
13353 (forward-line))
13354 (forward-line -1)))
13355 (unless org-log-states-order-reversed
13356 (and (= (char-after) ?\n) (forward-char 1))
13357 (org-skip-over-state-notes)
13358 (skip-chars-backward " \t\n\r")))
13359 (move-marker org-log-note-marker (point))
13360 (setq org-log-note-purpose purpose
13361 org-log-note-state state
13362 org-log-note-previous-state prev-state
13363 org-log-note-how how
13364 org-log-note-extra extra
13365 org-log-note-effective-time (org-current-effective-time))
13366 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13367
13368 (defun org-skip-over-state-notes ()
13369 "Skip past the list of State notes in an entry."
13370 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13371 (when (ignore-errors (goto-char (org-in-item-p)))
13372 (let* ((struct (org-list-struct))
13373 (prevs (org-list-prevs-alist struct)))
13374 (while (looking-at "[ \t]*- State")
13375 (goto-char (or (org-list-get-next-item (point) struct prevs)
13376 (org-list-get-item-end (point) struct)))))))
13377
13378 (defun org-add-log-note (&optional purpose)
13379 "Pop up a window for taking a note, and add this note later at point."
13380 (remove-hook 'post-command-hook 'org-add-log-note)
13381 (setq org-log-note-window-configuration (current-window-configuration))
13382 (delete-other-windows)
13383 (move-marker org-log-note-return-to (point))
13384 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13385 (goto-char org-log-note-marker)
13386 (org-switch-to-buffer-other-window "*Org Note*")
13387 (erase-buffer)
13388 (if (memq org-log-note-how '(time state))
13389 (let (current-prefix-arg) (org-store-log-note))
13390 (let ((org-inhibit-startup t)) (org-mode))
13391 (insert (format "# Insert note for %s.
13392 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13393 (cond
13394 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13395 ((eq org-log-note-purpose 'done) "closed todo item")
13396 ((eq org-log-note-purpose 'state)
13397 (format "state change from \"%s\" to \"%s\""
13398 (or org-log-note-previous-state "")
13399 (or org-log-note-state "")))
13400 ((eq org-log-note-purpose 'reschedule)
13401 "rescheduling")
13402 ((eq org-log-note-purpose 'delschedule)
13403 "no longer scheduled")
13404 ((eq org-log-note-purpose 'redeadline)
13405 "changing deadline")
13406 ((eq org-log-note-purpose 'deldeadline)
13407 "removing deadline")
13408 ((eq org-log-note-purpose 'refile)
13409 "refiling")
13410 ((eq org-log-note-purpose 'note)
13411 "this entry")
13412 (t (error "This should not happen")))))
13413 (if org-log-note-extra (insert org-log-note-extra))
13414 (org-set-local 'org-finish-function 'org-store-log-note)
13415 (run-hooks 'org-log-buffer-setup-hook)))
13416
13417 (defvar org-note-abort nil) ; dynamically scoped
13418 (defun org-store-log-note ()
13419 "Finish taking a log note, and insert it to where it belongs."
13420 (let ((txt (buffer-string)))
13421 (kill-buffer (current-buffer))
13422 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13423 lines ind bul)
13424 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13425 (setq txt (replace-match "" t t txt)))
13426 (if (string-match "\\s-+\\'" txt)
13427 (setq txt (replace-match "" t t txt)))
13428 (setq lines (org-split-string txt "\n"))
13429 (when (and note (string-match "\\S-" note))
13430 (setq note
13431 (org-replace-escapes
13432 note
13433 (list (cons "%u" (user-login-name))
13434 (cons "%U" user-full-name)
13435 (cons "%t" (format-time-string
13436 (org-time-stamp-format 'long 'inactive)
13437 org-log-note-effective-time))
13438 (cons "%T" (format-time-string
13439 (org-time-stamp-format 'long nil)
13440 org-log-note-effective-time))
13441 (cons "%d" (format-time-string
13442 (org-time-stamp-format nil 'inactive)
13443 org-log-note-effective-time))
13444 (cons "%D" (format-time-string
13445 (org-time-stamp-format nil nil)
13446 org-log-note-effective-time))
13447 (cons "%s" (if org-log-note-state
13448 (concat "\"" org-log-note-state "\"")
13449 ""))
13450 (cons "%S" (if org-log-note-previous-state
13451 (concat "\"" org-log-note-previous-state "\"")
13452 "\"\"")))))
13453 (if lines (setq note (concat note " \\\\")))
13454 (push note lines))
13455 (when (or current-prefix-arg org-note-abort)
13456 (when org-log-into-drawer
13457 (org-remove-empty-drawer-at
13458 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13459 org-log-note-marker))
13460 (setq lines nil))
13461 (when lines
13462 (with-current-buffer (marker-buffer org-log-note-marker)
13463 (save-excursion
13464 (goto-char org-log-note-marker)
13465 (move-marker org-log-note-marker nil)
13466 (end-of-line 1)
13467 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13468 (setq ind (save-excursion
13469 (if (ignore-errors (goto-char (org-in-item-p)))
13470 (let ((struct (org-list-struct)))
13471 (org-list-get-ind
13472 (org-list-get-top-point struct) struct))
13473 (skip-chars-backward " \r\t\n")
13474 (cond
13475 ((and (org-at-heading-p)
13476 org-adapt-indentation)
13477 (1+ (org-current-level)))
13478 ((org-at-heading-p) 0)
13479 (t (org-get-indentation))))))
13480 (setq bul (org-list-bullet-string "-"))
13481 (org-indent-line-to ind)
13482 (insert bul (pop lines))
13483 (let ((ind-body (+ (length bul) ind)))
13484 (while lines
13485 (insert "\n")
13486 (org-indent-line-to ind-body)
13487 (insert (pop lines))))
13488 (message "Note stored")
13489 (org-back-to-heading t)
13490 (org-cycle-hide-drawers 'children))
13491 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13492 ;; from within `org-add-log-note' because `buffer-undo-list'
13493 ;; is then modified outside of `org-with-remote-undo'.
13494 (when (eq this-command 'org-agenda-todo)
13495 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13496 ;; Don't add undo information when called from `org-agenda-todo'
13497 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13498 (set-window-configuration org-log-note-window-configuration)
13499 (with-current-buffer (marker-buffer org-log-note-return-to)
13500 (goto-char org-log-note-return-to))
13501 (move-marker org-log-note-return-to nil)
13502 (and org-log-post-message (message "%s" org-log-post-message))))
13503
13504 (defun org-remove-empty-drawer-at (drawer pos)
13505 "Remove an empty drawer DRAWER at position POS.
13506 POS may also be a marker."
13507 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13508 (save-excursion
13509 (save-restriction
13510 (widen)
13511 (goto-char pos)
13512 (if (org-in-regexp
13513 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13514 (replace-match ""))))))
13515
13516 (defvar org-ts-type nil)
13517 (defun org-sparse-tree (&optional arg type)
13518 "Create a sparse tree, prompt for the details.
13519 This command can create sparse trees. You first need to select the type
13520 of match used to create the tree:
13521
13522 t Show all TODO entries.
13523 T Show entries with a specific TODO keyword.
13524 m Show entries selected by a tags/property match.
13525 p Enter a property name and its value (both with completion on existing
13526 names/values) and show entries with that property.
13527 r Show entries matching a regular expression (`/' can be used as well).
13528 b Show deadlines and scheduled items before a date.
13529 a Show deadlines and scheduled items after a date.
13530 d Show deadlines due within `org-deadline-warning-days'.
13531 D Show deadlines and scheduled items between a date range."
13532 (interactive "P")
13533 (setq type (or type org-sparse-tree-default-date-type))
13534 (setq org-ts-type type)
13535 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13536 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13537 [c]ycle through date types: %s"
13538 (case type
13539 (all "all timestamps")
13540 (scheduled "only scheduled")
13541 (deadline "only deadline")
13542 (active "only active timestamps")
13543 (inactive "only inactive timestamps")
13544 (scheduled-or-deadline "scheduled/deadline")
13545 (closed "with a closed time-stamp")
13546 (otherwise "scheduled/deadline")))
13547 (let ((answer (read-char-exclusive)))
13548 (case answer
13549 (?c
13550 (org-sparse-tree
13551 arg
13552 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13553 inactive closed)))))
13554 (?d (call-interactively #'org-check-deadlines))
13555 (?b (call-interactively #'org-check-before-date))
13556 (?a (call-interactively #'org-check-after-date))
13557 (?D (call-interactively #'org-check-dates-range))
13558 (?t (call-interactively #'org-show-todo-tree))
13559 (?T (org-show-todo-tree '(4)))
13560 (?m (call-interactively #'org-match-sparse-tree))
13561 ((?p ?P)
13562 (let* ((kwd (org-icompleting-read
13563 "Property: " (mapcar #'list (org-buffer-property-keys))))
13564 (value (org-icompleting-read
13565 "Value: " (mapcar #'list (org-property-values kwd)))))
13566 (unless (string-match "\\`{.*}\\'" value)
13567 (setq value (concat "\"" value "\"")))
13568 (org-match-sparse-tree arg (concat kwd "=" value))))
13569 ((?r ?R ?/) (call-interactively #'org-occur))
13570 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13571
13572 (defvar org-occur-highlights nil
13573 "List of overlays used for occur matches.")
13574 (make-variable-buffer-local 'org-occur-highlights)
13575 (defvar org-occur-parameters nil
13576 "Parameters of the active org-occur calls.
13577 This is a list, each call to org-occur pushes as cons cell,
13578 containing the regular expression and the callback, onto the list.
13579 The list can contain several entries if `org-occur' has been called
13580 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13581 will only contain one set of parameters. When the highlights are
13582 removed (for example with `C-c C-c', or with the next edit (depending
13583 on `org-remove-highlights-with-change'), this variable is emptied
13584 as well.")
13585 (make-variable-buffer-local 'org-occur-parameters)
13586
13587 (defun org-occur (regexp &optional keep-previous callback)
13588 "Make a compact tree which shows all matches of REGEXP.
13589 The tree will show the lines where the regexp matches, and all higher
13590 headlines above the match. It will also show the heading after the match,
13591 to make sure editing the matching entry is easy.
13592 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13593 call to `org-occur' will be kept, to allow stacking of calls to this
13594 command.
13595 If CALLBACK is non-nil, it is a function which is called to confirm
13596 that the match should indeed be shown."
13597 (interactive "sRegexp: \nP")
13598 (when (equal regexp "")
13599 (user-error "Regexp cannot be empty"))
13600 (unless keep-previous
13601 (org-remove-occur-highlights nil nil t))
13602 (push (cons regexp callback) org-occur-parameters)
13603 (let ((cnt 0))
13604 (save-excursion
13605 (goto-char (point-min))
13606 (if (or (not keep-previous) ; do not want to keep
13607 (not org-occur-highlights)) ; no previous matches
13608 ;; hide everything
13609 (org-overview))
13610 (while (re-search-forward regexp nil t)
13611 (when (or (not callback)
13612 (save-match-data (funcall callback)))
13613 (setq cnt (1+ cnt))
13614 (when org-highlight-sparse-tree-matches
13615 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13616 (org-show-context 'occur-tree))))
13617 (when org-remove-highlights-with-change
13618 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13619 nil 'local))
13620 (unless org-sparse-tree-open-archived-trees
13621 (org-hide-archived-subtrees (point-min) (point-max)))
13622 (run-hooks 'org-occur-hook)
13623 (if (org-called-interactively-p 'interactive)
13624 (message "%d match(es) for regexp %s" cnt regexp))
13625 cnt))
13626
13627 (defun org-occur-next-match (&optional n reset)
13628 "Function for `next-error-function' to find sparse tree matches.
13629 N is the number of matches to move, when negative move backwards.
13630 RESET is entirely ignored - this function always goes back to the
13631 starting point when no match is found."
13632 (let* ((limit (if (< n 0) (point-min) (point-max)))
13633 (search-func (if (< n 0)
13634 'previous-single-char-property-change
13635 'next-single-char-property-change))
13636 (n (abs n))
13637 (pos (point))
13638 p1)
13639 (catch 'exit
13640 (while (setq p1 (funcall search-func (point) 'org-type))
13641 (when (equal p1 limit)
13642 (goto-char pos)
13643 (error "No more matches"))
13644 (when (equal (get-char-property p1 'org-type) 'org-occur)
13645 (setq n (1- n))
13646 (when (= n 0)
13647 (goto-char p1)
13648 (throw 'exit (point))))
13649 (goto-char p1))
13650 (goto-char p1)
13651 (error "No more matches"))))
13652
13653 (defun org-show-context (&optional key)
13654 "Make sure point and context are visible.
13655 How much context is shown depends upon the variables
13656 `org-show-hierarchy-above', `org-show-following-heading',
13657 `org-show-entry-below' and `org-show-siblings'."
13658 (let ((heading-p (org-at-heading-p t))
13659 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13660 (following-p (org-get-alist-option org-show-following-heading key))
13661 (entry-p (org-get-alist-option org-show-entry-below key))
13662 (siblings-p (org-get-alist-option org-show-siblings key)))
13663 ;; Show heading or entry text
13664 (if (and heading-p (not entry-p))
13665 (org-flag-heading nil) ; only show the heading
13666 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13667 (org-show-hidden-entry))) ; show entire entry
13668 (when following-p
13669 ;; Show next sibling, or heading below text
13670 (save-excursion
13671 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13672 (org-flag-heading nil))))
13673 (when siblings-p (org-show-siblings))
13674 (when hierarchy-p
13675 ;; show all higher headings, possibly with siblings
13676 (save-excursion
13677 (while (and (condition-case nil
13678 (progn (org-up-heading-all 1) t)
13679 (error nil))
13680 (not (bobp)))
13681 (org-flag-heading nil)
13682 (when siblings-p (org-show-siblings)))))))
13683
13684 (defvar org-reveal-start-hook nil
13685 "Hook run before revealing a location.")
13686
13687 (defun org-reveal (&optional siblings)
13688 "Show current entry, hierarchy above it, and the following headline.
13689 This can be used to show a consistent set of context around locations
13690 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13691 not t for the search context.
13692
13693 With optional argument SIBLINGS, on each level of the hierarchy all
13694 siblings are shown. This repairs the tree structure to what it would
13695 look like when opened with hierarchical calls to `org-cycle'.
13696 With double optional argument \\[universal-argument] \\[universal-argument], \
13697 go to the parent and show the
13698 entire tree."
13699 (interactive "P")
13700 (run-hooks 'org-reveal-start-hook)
13701 (let ((org-show-hierarchy-above t)
13702 (org-show-following-heading t)
13703 (org-show-siblings (if siblings t org-show-siblings)))
13704 (org-show-context nil))
13705 (when (equal siblings '(16))
13706 (save-excursion
13707 (when (org-up-heading-safe)
13708 (org-show-subtree)
13709 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13710
13711 (defun org-highlight-new-match (beg end)
13712 "Highlight from BEG to END and mark the highlight is an occur headline."
13713 (let ((ov (make-overlay beg end)))
13714 (overlay-put ov 'face 'secondary-selection)
13715 (overlay-put ov 'org-type 'org-occur)
13716 (push ov org-occur-highlights)))
13717
13718 (defun org-remove-occur-highlights (&optional beg end noremove)
13719 "Remove the occur highlights from the buffer.
13720 BEG and END are ignored. If NOREMOVE is nil, remove this function
13721 from the `before-change-functions' in the current buffer."
13722 (interactive)
13723 (unless org-inhibit-highlight-removal
13724 (mapc 'delete-overlay org-occur-highlights)
13725 (setq org-occur-highlights nil)
13726 (setq org-occur-parameters nil)
13727 (unless noremove
13728 (remove-hook 'before-change-functions
13729 'org-remove-occur-highlights 'local))))
13730
13731 ;;;; Priorities
13732
13733 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13734 "Regular expression matching the priority indicator.")
13735
13736 (defvar org-remove-priority-next-time nil)
13737
13738 (defun org-priority-up ()
13739 "Increase the priority of the current item."
13740 (interactive)
13741 (org-priority 'up))
13742
13743 (defun org-priority-down ()
13744 "Decrease the priority of the current item."
13745 (interactive)
13746 (org-priority 'down))
13747
13748 (defun org-priority (&optional action show)
13749 "Change the priority of an item.
13750 ACTION can be `set', `up', `down', or a character."
13751 (interactive "P")
13752 (if (equal action '(4))
13753 (org-show-priority)
13754 (unless org-enable-priority-commands
13755 (user-error "Priority commands are disabled"))
13756 (setq action (or action 'set))
13757 (let (current new news have remove)
13758 (save-excursion
13759 (org-back-to-heading t)
13760 (if (looking-at org-priority-regexp)
13761 (setq current (string-to-char (match-string 2))
13762 have t))
13763 (cond
13764 ((eq action 'remove)
13765 (setq remove t new ?\ ))
13766 ((or (eq action 'set)
13767 (if (featurep 'xemacs) (characterp action) (integerp action)))
13768 (if (not (eq action 'set))
13769 (setq new action)
13770 (message "Priority %c-%c, SPC to remove: "
13771 org-highest-priority org-lowest-priority)
13772 (save-match-data
13773 (setq new (read-char-exclusive))))
13774 (if (and (= (upcase org-highest-priority) org-highest-priority)
13775 (= (upcase org-lowest-priority) org-lowest-priority))
13776 (setq new (upcase new)))
13777 (cond ((equal new ?\ ) (setq remove t))
13778 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13779 (user-error "Priority must be between `%c' and `%c'"
13780 org-highest-priority org-lowest-priority))))
13781 ((eq action 'up)
13782 (setq new (if have
13783 (1- current) ; normal cycling
13784 ;; last priority was empty
13785 (if (eq last-command this-command)
13786 org-lowest-priority ; wrap around empty to lowest
13787 ;; default
13788 (if org-priority-start-cycle-with-default
13789 org-default-priority
13790 (1- org-default-priority))))))
13791 ((eq action 'down)
13792 (setq new (if have
13793 (1+ current) ; normal cycling
13794 ;; last priority was empty
13795 (if (eq last-command this-command)
13796 org-highest-priority ; wrap around empty to highest
13797 ;; default
13798 (if org-priority-start-cycle-with-default
13799 org-default-priority
13800 (1+ org-default-priority))))))
13801 (t (user-error "Invalid action")))
13802 (if (or (< (upcase new) org-highest-priority)
13803 (> (upcase new) org-lowest-priority))
13804 (if (and (memq action '(up down))
13805 (not have) (not (eq last-command this-command)))
13806 ;; `new' is from default priority
13807 (error
13808 "The default can not be set, see `org-default-priority' why")
13809 ;; normal cycling: `new' is beyond highest/lowest priority
13810 ;; and is wrapped around to the empty priority
13811 (setq remove t)))
13812 (setq news (format "%c" new))
13813 (if have
13814 (if remove
13815 (replace-match "" t t nil 1)
13816 (replace-match news t t nil 2))
13817 (if remove
13818 (user-error "No priority cookie found in line")
13819 (let ((case-fold-search nil))
13820 (looking-at org-todo-line-regexp))
13821 (if (match-end 2)
13822 (progn
13823 (goto-char (match-end 2))
13824 (insert " [#" news "]"))
13825 (goto-char (match-beginning 3))
13826 (insert "[#" news "] "))))
13827 (org-preserve-lc (org-set-tags nil 'align)))
13828 (if remove
13829 (message "Priority removed")
13830 (message "Priority of current item set to %s" news)))))
13831
13832 (defun org-show-priority ()
13833 "Show the priority of the current item.
13834 This priority is composed of the main priority given with the [#A] cookies,
13835 and by additional input from the age of a schedules or deadline entry."
13836 (interactive)
13837 (let ((pri (if (eq major-mode 'org-agenda-mode)
13838 (org-get-at-bol 'priority)
13839 (save-excursion
13840 (save-match-data
13841 (beginning-of-line)
13842 (and (looking-at org-heading-regexp)
13843 (org-get-priority (match-string 0))))))))
13844 (message "Priority is %d" (if pri pri -1000))))
13845
13846 (defun org-get-priority (s)
13847 "Find priority cookie and return priority."
13848 (save-match-data
13849 (if (functionp org-get-priority-function)
13850 (funcall org-get-priority-function)
13851 (if (not (string-match org-priority-regexp s))
13852 (* 1000 (- org-lowest-priority org-default-priority))
13853 (* 1000 (- org-lowest-priority
13854 (string-to-char (match-string 2 s))))))))
13855
13856 ;;;; Tags
13857
13858 (defvar org-agenda-archives-mode)
13859 (defvar org-map-continue-from nil
13860 "Position from where mapping should continue.
13861 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13862
13863 (defvar org-scanner-tags nil
13864 "The current tag list while the tags scanner is running.")
13865 (defvar org-trust-scanner-tags nil
13866 "Should `org-get-tags-at' use the tags for the scanner.
13867 This is for internal dynamical scoping only.
13868 When this is non-nil, the function `org-get-tags-at' will return the value
13869 of `org-scanner-tags' instead of building the list by itself. This
13870 can lead to large speed-ups when the tags scanner is used in a file with
13871 many entries, and when the list of tags is retrieved, for example to
13872 obtain a list of properties. Building the tags list for each entry in such
13873 a file becomes an N^2 operation - but with this variable set, it scales
13874 as N.")
13875
13876 (defun org-scan-tags (action matcher todo-only &optional start-level)
13877 "Scan headline tags with inheritance and produce output ACTION.
13878
13879 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13880 or `agenda' to produce an entry list for an agenda view. It can also be
13881 a Lisp form or a function that should be called at each matched headline, in
13882 this case the return value is a list of all return values from these calls.
13883
13884 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13885 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13886 only lines with a not-done TODO keyword are included in the output.
13887 This should be the same variable that was scoped into
13888 and set by `org-make-tags-matcher' when it constructed MATCHER.
13889
13890 START-LEVEL can be a string with asterisks, reducing the scope to
13891 headlines matching this string."
13892 (require 'org-agenda)
13893 (let* ((re (concat "^"
13894 (if start-level
13895 ;; Get the correct level to match
13896 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13897 org-outline-regexp)
13898 " *\\(\\<\\("
13899 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13900 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13901 (props (list 'face 'default
13902 'done-face 'org-agenda-done
13903 'undone-face 'default
13904 'mouse-face 'highlight
13905 'org-not-done-regexp org-not-done-regexp
13906 'org-todo-regexp org-todo-regexp
13907 'org-complex-heading-regexp org-complex-heading-regexp
13908 'help-echo
13909 (format "mouse-2 or RET jump to org file %s"
13910 (abbreviate-file-name
13911 (or (buffer-file-name (buffer-base-buffer))
13912 (buffer-name (buffer-base-buffer)))))))
13913 (org-map-continue-from nil)
13914 lspos tags tags-list
13915 (tags-alist (list (cons 0 org-file-tags)))
13916 (llast 0) rtn rtn1 level category i txt
13917 todo marker entry priority)
13918 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13919 (setq action (list 'lambda nil action)))
13920 (save-excursion
13921 (goto-char (point-min))
13922 (when (eq action 'sparse-tree)
13923 (org-overview)
13924 (org-remove-occur-highlights))
13925 (while (let (case-fold-search)
13926 (re-search-forward re nil t))
13927 (setq org-map-continue-from nil)
13928 (catch :skip
13929 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13930 tags (if (match-end 4) (org-match-string-no-properties 4)))
13931 (goto-char (setq lspos (match-beginning 0)))
13932 (setq level (org-reduced-level (org-outline-level))
13933 category (org-get-category))
13934 (setq i llast llast level)
13935 ;; remove tag lists from same and sublevels
13936 (while (>= i level)
13937 (when (setq entry (assoc i tags-alist))
13938 (setq tags-alist (delete entry tags-alist)))
13939 (setq i (1- i)))
13940 ;; add the next tags
13941 (when tags
13942 (setq tags (org-split-string tags ":")
13943 tags-alist
13944 (cons (cons level tags) tags-alist)))
13945 ;; compile tags for current headline
13946 (setq tags-list
13947 (if org-use-tag-inheritance
13948 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13949 tags)
13950 org-scanner-tags tags-list)
13951 (when org-use-tag-inheritance
13952 (setcdr (car tags-alist)
13953 (mapcar (lambda (x)
13954 (setq x (copy-sequence x))
13955 (org-add-prop-inherited x))
13956 (cdar tags-alist))))
13957 (when (and tags org-use-tag-inheritance
13958 (or (not (eq t org-use-tag-inheritance))
13959 org-tags-exclude-from-inheritance))
13960 ;; selective inheritance, remove uninherited ones
13961 (setcdr (car tags-alist)
13962 (org-remove-uninherited-tags (cdar tags-alist))))
13963 (when (and
13964
13965 ;; eval matcher only when the todo condition is OK
13966 (and (or (not todo-only) (member todo org-not-done-keywords))
13967 (let ((case-fold-search t) (org-trust-scanner-tags t))
13968 (eval matcher)))
13969
13970 ;; Call the skipper, but return t if it does not skip,
13971 ;; so that the `and' form continues evaluating
13972 (progn
13973 (unless (eq action 'sparse-tree) (org-agenda-skip))
13974 t)
13975
13976 ;; Check if timestamps are deselecting this entry
13977 (or (not todo-only)
13978 (and (member todo org-not-done-keywords)
13979 (or (not org-agenda-tags-todo-honor-ignore-options)
13980 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13981
13982 ;; select this headline
13983 (cond
13984 ((eq action 'sparse-tree)
13985 (and org-highlight-sparse-tree-matches
13986 (org-get-heading) (match-end 0)
13987 (org-highlight-new-match
13988 (match-beginning 1) (match-end 1)))
13989 (org-show-context 'tags-tree))
13990 ((eq action 'agenda)
13991 (setq txt (org-agenda-format-item
13992 ""
13993 (concat
13994 (if (eq org-tags-match-list-sublevels 'indented)
13995 (make-string (1- level) ?.) "")
13996 (org-get-heading))
13997 level category
13998 tags-list)
13999 priority (org-get-priority txt))
14000 (goto-char lspos)
14001 (setq marker (org-agenda-new-marker))
14002 (org-add-props txt props
14003 'org-marker marker 'org-hd-marker marker 'org-category category
14004 'todo-state todo
14005 'priority priority 'type "tagsmatch")
14006 (push txt rtn))
14007 ((functionp action)
14008 (setq org-map-continue-from nil)
14009 (save-excursion
14010 (setq rtn1 (funcall action))
14011 (push rtn1 rtn)))
14012 (t (user-error "Invalid action")))
14013
14014 ;; if we are to skip sublevels, jump to end of subtree
14015 (unless org-tags-match-list-sublevels
14016 (org-end-of-subtree t)
14017 (backward-char 1))))
14018 ;; Get the correct position from where to continue
14019 (if org-map-continue-from
14020 (goto-char org-map-continue-from)
14021 (and (= (point) lspos) (end-of-line 1)))))
14022 (when (and (eq action 'sparse-tree)
14023 (not org-sparse-tree-open-archived-trees))
14024 (org-hide-archived-subtrees (point-min) (point-max)))
14025 (nreverse rtn)))
14026
14027 (defun org-remove-uninherited-tags (tags)
14028 "Remove all tags that are not inherited from the list TAGS."
14029 (cond
14030 ((eq org-use-tag-inheritance t)
14031 (if org-tags-exclude-from-inheritance
14032 (org-delete-all org-tags-exclude-from-inheritance tags)
14033 tags))
14034 ((not org-use-tag-inheritance) nil)
14035 ((stringp org-use-tag-inheritance)
14036 (delq nil (mapcar
14037 (lambda (x)
14038 (if (and (string-match org-use-tag-inheritance x)
14039 (not (member x org-tags-exclude-from-inheritance)))
14040 x nil))
14041 tags)))
14042 ((listp org-use-tag-inheritance)
14043 (delq nil (mapcar
14044 (lambda (x)
14045 (if (member x org-use-tag-inheritance) x nil))
14046 tags)))))
14047
14048 (defun org-match-sparse-tree (&optional todo-only match)
14049 "Create a sparse tree according to tags string MATCH.
14050 MATCH can contain positive and negative selection of tags, like
14051 \"+WORK+URGENT-WITHBOSS\".
14052 If optional argument TODO-ONLY is non-nil, only select lines that are
14053 also TODO lines."
14054 (interactive "P")
14055 (org-agenda-prepare-buffers (list (current-buffer)))
14056 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14057
14058 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14059
14060 (defvar org-cached-props nil)
14061 (defun org-cached-entry-get (pom property)
14062 (if (or (eq t org-use-property-inheritance)
14063 (and (stringp org-use-property-inheritance)
14064 (string-match org-use-property-inheritance property))
14065 (and (listp org-use-property-inheritance)
14066 (member property org-use-property-inheritance)))
14067 ;; Caching is not possible, check it directly
14068 (org-entry-get pom property 'inherit)
14069 ;; Get all properties, so that we can do complicated checks easily
14070 (cdr (assoc property (or org-cached-props
14071 (setq org-cached-props
14072 (org-entry-properties pom)))))))
14073
14074 (defun org-global-tags-completion-table (&optional files)
14075 "Return the list of all tags in all agenda buffer/files.
14076 Optional FILES argument is a list of files which can be used
14077 instead of the agenda files."
14078 (save-excursion
14079 (org-uniquify
14080 (delq nil
14081 (apply 'append
14082 (mapcar
14083 (lambda (file)
14084 (set-buffer (find-file-noselect file))
14085 (append (org-get-buffer-tags)
14086 (mapcar (lambda (x) (if (stringp (car-safe x))
14087 (list (car-safe x)) nil))
14088 org-tag-alist)))
14089 (if (and files (car files))
14090 files
14091 (org-agenda-files))))))))
14092
14093 (defun org-make-tags-matcher (match)
14094 "Create the TAGS/TODO matcher form for the selection string MATCH.
14095
14096 The variable `todo-only' is scoped dynamically into this function.
14097 It will be set to t if the matcher restricts matching to TODO entries,
14098 otherwise will not be touched.
14099
14100 Returns a cons of the selection string MATCH and the constructed
14101 lisp form implementing the matcher. The matcher is to be evaluated
14102 at an Org entry, with point on the headline, and returns t if the
14103 entry matches the selection string MATCH. The returned lisp form
14104 references two variables with information about the entry, which
14105 must be bound around the form's evaluation: todo, the TODO keyword
14106 at the entry (or nil of none); and tags-list, the list of all tags
14107 at the entry including inherited ones. Additionally, the category
14108 of the entry (if any) must be specified as the text property
14109 'org-category on the headline.
14110
14111 See also `org-scan-tags'.
14112 "
14113 (declare (special todo-only))
14114 (unless (boundp 'todo-only)
14115 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14116 (unless match
14117 ;; Get a new match request, with completion against the global
14118 ;; tags table and the local tags in current buffer
14119 (let ((org-last-tags-completion-table
14120 (org-uniquify
14121 (delq nil (append (org-get-buffer-tags)
14122 (org-global-tags-completion-table))))))
14123 (setq match (org-completing-read-no-i
14124 "Match: " 'org-tags-completion-function nil nil nil
14125 'org-tags-history))))
14126
14127 ;; Parse the string and create a lisp form
14128 (let ((match0 match)
14129 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14130 minus tag mm
14131 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14132 orterms orlist re-p str-p level-p level-op time-p
14133 prop-p pn pv po gv rest (start 0) (ss 0))
14134 ;; Expand group tags
14135 (setq match (org-tags-expand match))
14136
14137 ;; Check if there is a TODO part of this match, which would be the
14138 ;; part after a "/". TO make sure that this slash is not part of
14139 ;; a property value to be matched against, we also check that there
14140 ;; is no " after that slash.
14141 ;; First, find the last slash
14142 (while (string-match "/+" match ss)
14143 (setq start (match-beginning 0) ss (match-end 0)))
14144 (if (and (string-match "/+" match start)
14145 (not (save-match-data (string-match "\"" match start))))
14146 ;; match contains also a todo-matching request
14147 (progn
14148 (setq tagsmatch (substring match 0 (match-beginning 0))
14149 todomatch (substring match (match-end 0)))
14150 (if (string-match "^!" todomatch)
14151 (setq todo-only t todomatch (substring todomatch 1)))
14152 (if (string-match "^\\s-*$" todomatch)
14153 (setq todomatch nil)))
14154 ;; only matching tags
14155 (setq tagsmatch match todomatch nil))
14156
14157 ;; Make the tags matcher
14158 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14159 (setq tagsmatcher t)
14160 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14161 (dolist (term orterms)
14162 (while (and (equal (substring term -1) "\\") orterms)
14163 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14164 (while (string-match re term)
14165 (setq rest (substring term (match-end 0))
14166 minus (and (match-end 1)
14167 (equal (match-string 1 term) "-"))
14168 tag (save-match-data (replace-regexp-in-string
14169 "\\\\-" "-"
14170 (match-string 2 term)))
14171 re-p (equal (string-to-char tag) ?{)
14172 level-p (match-end 4)
14173 prop-p (match-end 5)
14174 mm (cond
14175 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14176 (level-p
14177 (setq level-op (org-op-to-function (match-string 3 term)))
14178 `(,level-op level ,(string-to-number
14179 (match-string 4 term))))
14180 (prop-p
14181 (setq pn (match-string 5 term)
14182 po (match-string 6 term)
14183 pv (match-string 7 term)
14184 re-p (equal (string-to-char pv) ?{)
14185 str-p (equal (string-to-char pv) ?\")
14186 time-p (save-match-data
14187 (string-match "^\"[[<].*[]>]\"$" pv))
14188 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14189 (if time-p (setq pv (org-matcher-time pv)))
14190 (setq po (org-op-to-function po (if time-p 'time str-p)))
14191 (cond
14192 ((equal pn "CATEGORY")
14193 (setq gv '(get-text-property (point) 'org-category)))
14194 ((equal pn "TODO")
14195 (setq gv 'todo))
14196 (t
14197 (setq gv `(org-cached-entry-get nil ,pn))))
14198 (if re-p
14199 (if (eq po 'org<>)
14200 `(not (string-match ,pv (or ,gv "")))
14201 `(string-match ,pv (or ,gv "")))
14202 (if str-p
14203 `(,po (or ,gv "") ,pv)
14204 `(,po (string-to-number (or ,gv ""))
14205 ,(string-to-number pv) ))))
14206 (t `(member ,tag tags-list)))
14207 mm (if minus (list 'not mm) mm)
14208 term rest)
14209 (push mm tagsmatcher))
14210 (push (if (> (length tagsmatcher) 1)
14211 (cons 'and tagsmatcher)
14212 (car tagsmatcher))
14213 orlist)
14214 (setq tagsmatcher nil))
14215 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14216 (setq tagsmatcher
14217 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14218 ;; Make the todo matcher
14219 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14220 (setq todomatcher t)
14221 (setq orterms (org-split-string todomatch "|") orlist nil)
14222 (dolist (term orterms)
14223 (while (string-match re term)
14224 (setq minus (and (match-end 1)
14225 (equal (match-string 1 term) "-"))
14226 kwd (match-string 2 term)
14227 re-p (equal (string-to-char kwd) ?{)
14228 term (substring term (match-end 0))
14229 mm (if re-p
14230 `(string-match ,(substring kwd 1 -1) todo)
14231 (list 'equal 'todo kwd))
14232 mm (if minus (list 'not mm) mm))
14233 (push mm todomatcher))
14234 (push (if (> (length todomatcher) 1)
14235 (cons 'and todomatcher)
14236 (car todomatcher))
14237 orlist)
14238 (setq todomatcher nil))
14239 (setq todomatcher (if (> (length orlist) 1)
14240 (cons 'or orlist) (car orlist))))
14241
14242 ;; Return the string and lisp forms of the matcher
14243 (setq matcher (if todomatcher
14244 (list 'and tagsmatcher todomatcher)
14245 tagsmatcher))
14246 (when todo-only
14247 (setq matcher (list 'and '(member todo org-not-done-keywords)
14248 matcher)))
14249 (cons match0 matcher)))
14250
14251 (defun org-tags-expand (match &optional single-as-list downcased)
14252 "Expand group tags in MATCH.
14253
14254 This replaces every group tag in MATCH with a regexp tag search.
14255 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14256 will be replaced like this:
14257
14258 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14259 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14260 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14261
14262 Replacing by a regexp preserves the structure of the match.
14263 E.g., this expansion
14264
14265 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14266
14267 will match anything tagged with \"Lab\" and \"Home\", or tagged
14268 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14269
14270 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14271 assumed to be a single group tag, and the function will return
14272 the list of tags in this group.
14273
14274 When DOWNCASE is non-nil, expand downcased TAGS."
14275 (if org-group-tags
14276 (let* ((case-fold-search t)
14277 (stable org-mode-syntax-table)
14278 (tal (or org-tag-groups-alist-for-agenda
14279 org-tag-groups-alist))
14280 (tal (if downcased
14281 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14282 (tml (mapcar 'car tal))
14283 (rtnmatch match) rpl)
14284 ;; @ and _ are allowed as word-components in tags
14285 (modify-syntax-entry ?@ "w" stable)
14286 (modify-syntax-entry ?_ "w" stable)
14287 (while (and tml
14288 (with-syntax-table stable
14289 (string-match
14290 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14291 (regexp-opt tml) "\\>\\)")
14292 rtnmatch)))
14293 (let* ((dir (match-string 1 rtnmatch))
14294 (tag (match-string 2 rtnmatch))
14295 (tag (if downcased (downcase tag) tag)))
14296 (setq tml (delete tag tml))
14297 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14298 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14299 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14300 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14301 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14302 (if single-as-list
14303 (or (reverse rpl) (list rtnmatch))
14304 rtnmatch))
14305 (if single-as-list (list (if downcased (downcase match) match))
14306 match)))
14307
14308 (defun org-op-to-function (op &optional stringp)
14309 "Turn an operator into the appropriate function."
14310 (setq op
14311 (cond
14312 ((equal op "<" ) '(< string< org-time<))
14313 ((equal op ">" ) '(> org-string> org-time>))
14314 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14315 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14316 ((member op '("=" "==")) '(= string= org-time=))
14317 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14318 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14319
14320 (defun org<> (a b) (not (= a b)))
14321 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14322 (defun org-string>= (a b) (not (string< a b)))
14323 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14324 (defun org-string<> (a b) (not (string= a b)))
14325 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14326 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14327 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14328 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14329 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14330 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14331 (defun org-2ft (s)
14332 "Convert S to a floating point time.
14333 If S is already a number, just return it. If it is a string, parse
14334 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14335 (cond
14336 ((numberp s) s)
14337 ((stringp s)
14338 (condition-case nil
14339 (float-time (apply 'encode-time (org-parse-time-string s)))
14340 (error 0.)))
14341 (t 0.)))
14342
14343 (defun org-time-today ()
14344 "Time in seconds today at 0:00.
14345 Returns the float number of seconds since the beginning of the
14346 epoch to the beginning of today (00:00)."
14347 (float-time (apply 'encode-time
14348 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14349
14350 (defun org-matcher-time (s)
14351 "Interpret a time comparison value."
14352 (save-match-data
14353 (cond
14354 ((string= s "<now>") (float-time))
14355 ((string= s "<today>") (org-time-today))
14356 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14357 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14358 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14359 (+ (org-time-today)
14360 (* (string-to-number (match-string 1 s))
14361 (cdr (assoc (match-string 2 s)
14362 '(("d" . 86400.0) ("w" . 604800.0)
14363 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14364 (t (org-2ft s)))))
14365
14366 (defun org-match-any-p (re list)
14367 "Does re match any element of list?"
14368 (setq list (mapcar (lambda (x) (string-match re x)) list))
14369 (delq nil list))
14370
14371 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14372 (defvar org-tags-overlay (make-overlay 1 1))
14373 (org-detach-overlay org-tags-overlay)
14374
14375 (defun org-get-local-tags-at (&optional pos)
14376 "Get a list of tags defined in the current headline."
14377 (org-get-tags-at pos 'local))
14378
14379 (defun org-get-local-tags ()
14380 "Get a list of tags defined in the current headline."
14381 (org-get-tags-at nil 'local))
14382
14383 (defun org-get-tags-at (&optional pos local)
14384 "Get a list of all headline tags applicable at POS.
14385 POS defaults to point. If tags are inherited, the list contains
14386 the targets in the same sequence as the headlines appear, i.e.
14387 the tags of the current headline come last.
14388 When LOCAL is non-nil, only return tags from the current headline,
14389 ignore inherited ones."
14390 (interactive)
14391 (if (and org-trust-scanner-tags
14392 (or (not pos) (equal pos (point)))
14393 (not local))
14394 org-scanner-tags
14395 (let (tags ltags lastpos parent)
14396 (save-excursion
14397 (save-restriction
14398 (widen)
14399 (goto-char (or pos (point)))
14400 (save-match-data
14401 (catch 'done
14402 (condition-case nil
14403 (progn
14404 (org-back-to-heading t)
14405 (while (not (equal lastpos (point)))
14406 (setq lastpos (point))
14407 (when (looking-at
14408 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14409 (setq ltags (org-split-string
14410 (org-match-string-no-properties 1) ":"))
14411 (when parent
14412 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14413 (setq tags (append
14414 (if parent
14415 (org-remove-uninherited-tags ltags)
14416 ltags)
14417 tags)))
14418 (or org-use-tag-inheritance (throw 'done t))
14419 (if local (throw 'done t))
14420 (or (org-up-heading-safe) (error nil))
14421 (setq parent t)))
14422 (error nil)))))
14423 (if local
14424 tags
14425 (reverse (delete-dups
14426 (reverse (append
14427 (org-remove-uninherited-tags
14428 org-file-tags)
14429 tags)))))))))
14430
14431 (defun org-add-prop-inherited (s)
14432 (add-text-properties 0 (length s) '(inherited t) s)
14433 s)
14434
14435 (defun org-toggle-tag (tag &optional onoff)
14436 "Toggle the tag TAG for the current line.
14437 If ONOFF is `on' or `off', don't toggle but set to this state."
14438 (let (res current)
14439 (save-excursion
14440 (org-back-to-heading t)
14441 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14442 (point-at-eol) t)
14443 (progn
14444 (setq current (match-string 1))
14445 (replace-match ""))
14446 (setq current ""))
14447 (setq current (nreverse (org-split-string current ":")))
14448 (cond
14449 ((eq onoff 'on)
14450 (setq res t)
14451 (or (member tag current) (push tag current)))
14452 ((eq onoff 'off)
14453 (or (not (member tag current)) (setq current (delete tag current))))
14454 (t (if (member tag current)
14455 (setq current (delete tag current))
14456 (setq res t)
14457 (push tag current))))
14458 (end-of-line 1)
14459 (if current
14460 (progn
14461 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14462 (org-set-tags nil t))
14463 (delete-horizontal-space))
14464 (run-hooks 'org-after-tags-change-hook))
14465 res))
14466
14467 (defun org-align-tags-here (to-col)
14468 ;; Assumes that this is a headline
14469 "Align tags on the current headline to TO-COL."
14470 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14471 (beginning-of-line 1)
14472 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14473 (< pos (match-beginning 2)))
14474 (progn
14475 (setq tags-l (- (match-end 2) (match-beginning 2)))
14476 (goto-char (match-beginning 1))
14477 (insert " ")
14478 (delete-region (point) (1+ (match-beginning 2)))
14479 (setq ncol (max (current-column)
14480 (1+ col)
14481 (if (> to-col 0)
14482 to-col
14483 (- (abs to-col) tags-l))))
14484 (setq p (point))
14485 (insert (make-string (- ncol (current-column)) ?\ ))
14486 (setq ncol (current-column))
14487 (when indent-tabs-mode (tabify p (point-at-eol)))
14488 (org-move-to-column (min ncol col)))
14489 (goto-char pos))))
14490
14491 (defun org-set-tags-command (&optional arg just-align)
14492 "Call the set-tags command for the current entry."
14493 (interactive "P")
14494 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14495 (org-set-tags arg just-align)
14496 (save-excursion
14497 (unless (and (org-region-active-p)
14498 org-loop-over-headlines-in-active-region)
14499 (org-back-to-heading t))
14500 (org-set-tags arg just-align))))
14501
14502 (defun org-set-tags-to (data)
14503 "Set the tags of the current entry to DATA, replacing the current tags.
14504 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14505 If DATA is nil or the empty string, any tags will be removed."
14506 (interactive "sTags: ")
14507 (setq data
14508 (cond
14509 ((eq data nil) "")
14510 ((equal data "") "")
14511 ((stringp data)
14512 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14513 ":"))
14514 ((listp data)
14515 (concat ":" (mapconcat 'identity data ":") ":"))))
14516 (when data
14517 (save-excursion
14518 (org-back-to-heading t)
14519 (when (looking-at org-complex-heading-regexp)
14520 (if (match-end 5)
14521 (progn
14522 (goto-char (match-beginning 5))
14523 (insert data)
14524 (delete-region (point) (point-at-eol))
14525 (org-set-tags nil 'align))
14526 (goto-char (point-at-eol))
14527 (insert " " data)
14528 (org-set-tags nil 'align)))
14529 (beginning-of-line 1)
14530 (if (looking-at ".*?\\([ \t]+\\)$")
14531 (delete-region (match-beginning 1) (match-end 1))))))
14532
14533 (defun org-align-all-tags ()
14534 "Align the tags i all headings."
14535 (interactive)
14536 (save-excursion
14537 (or (ignore-errors (org-back-to-heading t))
14538 (outline-next-heading))
14539 (if (org-at-heading-p)
14540 (org-set-tags t)
14541 (message "No headings"))))
14542
14543 (defvar org-indent-indentation-per-level)
14544 (defun org-set-tags (&optional arg just-align)
14545 "Set the tags for the current headline.
14546 With prefix ARG, realign all tags in headings in the current buffer.
14547 When JUST-ALIGN is non-nil, only align tags."
14548 (interactive "P")
14549 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14550 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14551 'region-start-level 'region))
14552 org-loop-over-headlines-in-active-region)
14553 (org-map-entries
14554 ;; We don't use ARG and JUST-ALIGN here because these args
14555 ;; are not useful when looping over headlines.
14556 `(org-set-tags)
14557 org-loop-over-headlines-in-active-region
14558 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14559 (let* ((re org-outline-regexp-bol)
14560 (current (unless arg (org-get-tags-string)))
14561 (col (current-column))
14562 (org-setting-tags t)
14563 table current-tags inherited-tags ; computed below when needed
14564 tags p0 c0 c1 rpl di tc level)
14565 (if arg
14566 (save-excursion
14567 (goto-char (point-min))
14568 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14569 (while (re-search-forward re nil t)
14570 (org-set-tags nil t)
14571 (end-of-line 1)))
14572 (message "All tags realigned to column %d" org-tags-column))
14573 (if just-align
14574 (setq tags current)
14575 ;; Get a new set of tags from the user
14576 (save-excursion
14577 (setq table (append org-tag-persistent-alist
14578 (or org-tag-alist (org-get-buffer-tags))
14579 (and
14580 org-complete-tags-always-offer-all-agenda-tags
14581 (org-global-tags-completion-table
14582 (org-agenda-files))))
14583 org-last-tags-completion-table table
14584 current-tags (org-split-string current ":")
14585 inherited-tags (nreverse
14586 (nthcdr (length current-tags)
14587 (nreverse (org-get-tags-at))))
14588 tags
14589 (if (or (eq t org-use-fast-tag-selection)
14590 (and org-use-fast-tag-selection
14591 (delq nil (mapcar 'cdr table))))
14592 (org-fast-tag-selection
14593 current-tags inherited-tags table
14594 (if org-fast-tag-selection-include-todo
14595 org-todo-key-alist))
14596 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14597 (org-trim
14598 (org-icompleting-read "Tags: "
14599 'org-tags-completion-function
14600 nil nil current 'org-tags-history))))))
14601 (while (string-match "[-+&]+" tags)
14602 ;; No boolean logic, just a list
14603 (setq tags (replace-match ":" t t tags))))
14604
14605 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14606
14607 (if org-tags-sort-function
14608 (setq tags (mapconcat 'identity
14609 (sort (org-split-string
14610 tags (org-re "[^[:alnum:]_@#%]+"))
14611 org-tags-sort-function) ":")))
14612
14613 (if (string-match "\\`[\t ]*\\'" tags)
14614 (setq tags "")
14615 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14616 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14617
14618 ;; Insert new tags at the correct column
14619 (beginning-of-line 1)
14620 (setq level (or (and (looking-at org-outline-regexp)
14621 (- (match-end 0) (point) 1))
14622 1))
14623 (cond
14624 ((and (equal current "") (equal tags "")))
14625 ((re-search-forward
14626 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14627 (point-at-eol) t)
14628 (if (equal tags "")
14629 (setq rpl "")
14630 (goto-char (match-beginning 0))
14631 (setq c0 (current-column)
14632 ;; compute offset for the case of org-indent-mode active
14633 di (if (org-bound-and-true-p org-indent-mode)
14634 (* (1- org-indent-indentation-per-level) (1- level))
14635 0)
14636 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14637 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14638 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14639 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14640 (replace-match rpl t t)
14641 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14642 tags)
14643 (t (error "Tags alignment failed")))
14644 (org-move-to-column col)
14645 (unless just-align
14646 (run-hooks 'org-after-tags-change-hook))))))
14647
14648 (defun org-change-tag-in-region (beg end tag off)
14649 "Add or remove TAG for each entry in the region.
14650 This works in the agenda, and also in an org-mode buffer."
14651 (interactive
14652 (list (region-beginning) (region-end)
14653 (let ((org-last-tags-completion-table
14654 (if (derived-mode-p 'org-mode)
14655 (org-uniquify
14656 (delq nil (append (org-get-buffer-tags)
14657 (org-global-tags-completion-table))))
14658 (org-global-tags-completion-table))))
14659 (org-icompleting-read
14660 "Tag: " 'org-tags-completion-function nil nil nil
14661 'org-tags-history))
14662 (progn
14663 (message "[s]et or [r]emove? ")
14664 (equal (read-char-exclusive) ?r))))
14665 (if (fboundp 'deactivate-mark) (deactivate-mark))
14666 (let ((agendap (equal major-mode 'org-agenda-mode))
14667 l1 l2 m buf pos newhead (cnt 0))
14668 (goto-char end)
14669 (setq l2 (1- (org-current-line)))
14670 (goto-char beg)
14671 (setq l1 (org-current-line))
14672 (loop for l from l1 to l2 do
14673 (org-goto-line l)
14674 (setq m (get-text-property (point) 'org-hd-marker))
14675 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14676 (and agendap m))
14677 (setq buf (if agendap (marker-buffer m) (current-buffer))
14678 pos (if agendap m (point)))
14679 (with-current-buffer buf
14680 (save-excursion
14681 (save-restriction
14682 (goto-char pos)
14683 (setq cnt (1+ cnt))
14684 (org-toggle-tag tag (if off 'off 'on))
14685 (setq newhead (org-get-heading)))))
14686 (and agendap (org-agenda-change-all-lines newhead m))))
14687 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14688
14689 (defun org-tags-completion-function (string predicate &optional flag)
14690 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14691 (confirm (lambda (x) (stringp (car x)))))
14692 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14693 (setq s1 (match-string 1 string)
14694 s2 (match-string 2 string))
14695 (setq s1 "" s2 string))
14696 (cond
14697 ((eq flag nil)
14698 ;; try completion
14699 (setq rtn (try-completion s2 ctable confirm))
14700 (if (stringp rtn)
14701 (setq rtn
14702 (concat s1 s2 (substring rtn (length s2))
14703 (if (and org-add-colon-after-tag-completion
14704 (assoc rtn ctable))
14705 ":" ""))))
14706 rtn)
14707 ((eq flag t)
14708 ;; all-completions
14709 (all-completions s2 ctable confirm))
14710 ((eq flag 'lambda)
14711 ;; exact match?
14712 (assoc s2 ctable)))))
14713
14714 (defun org-fast-tag-insert (kwd tags face &optional end)
14715 "Insert KDW, and the TAGS, the latter with face FACE.
14716 Also insert END."
14717 (insert (format "%-12s" (concat kwd ":"))
14718 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14719 (or end "")))
14720
14721 (defun org-fast-tag-show-exit (flag)
14722 (save-excursion
14723 (org-goto-line 3)
14724 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14725 (replace-match ""))
14726 (when flag
14727 (end-of-line 1)
14728 (org-move-to-column (- (window-width) 19) t)
14729 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14730
14731 (defun org-set-current-tags-overlay (current prefix)
14732 "Add an overlay to CURRENT tag with PREFIX."
14733 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14734 (if (featurep 'xemacs)
14735 (org-overlay-display org-tags-overlay (concat prefix s)
14736 'secondary-selection)
14737 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14738 (org-overlay-display org-tags-overlay (concat prefix s)))))
14739
14740 (defvar org-last-tag-selection-key nil)
14741 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14742 "Fast tag selection with single keys.
14743 CURRENT is the current list of tags in the headline, INHERITED is the
14744 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14745 possibly with grouping information. TODO-TABLE is a similar table with
14746 TODO keywords, should these have keys assigned to them.
14747 If the keys are nil, a-z are automatically assigned.
14748 Returns the new tags string, or nil to not change the current settings."
14749 (let* ((fulltable (append table todo-table))
14750 (maxlen (apply 'max (mapcar
14751 (lambda (x)
14752 (if (stringp (car x)) (string-width (car x)) 0))
14753 fulltable)))
14754 (buf (current-buffer))
14755 (expert (eq org-fast-tag-selection-single-key 'expert))
14756 (buffer-tags nil)
14757 (fwidth (+ maxlen 3 1 3))
14758 (ncol (/ (- (window-width) 4) fwidth))
14759 (i-face 'org-done)
14760 (c-face 'org-todo)
14761 tg cnt c char c1 c2 ntable tbl rtn
14762 ov-start ov-end ov-prefix
14763 (exit-after-next org-fast-tag-selection-single-key)
14764 (done-keywords org-done-keywords)
14765 groups ingroup)
14766 (save-excursion
14767 (beginning-of-line 1)
14768 (if (looking-at
14769 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14770 (setq ov-start (match-beginning 1)
14771 ov-end (match-end 1)
14772 ov-prefix "")
14773 (setq ov-start (1- (point-at-eol))
14774 ov-end (1+ ov-start))
14775 (skip-chars-forward "^\n\r")
14776 (setq ov-prefix
14777 (concat
14778 (buffer-substring (1- (point)) (point))
14779 (if (> (current-column) org-tags-column)
14780 " "
14781 (make-string (- org-tags-column (current-column)) ?\ ))))))
14782 (move-overlay org-tags-overlay ov-start ov-end)
14783 (save-window-excursion
14784 (if expert
14785 (set-buffer (get-buffer-create " *Org tags*"))
14786 (delete-other-windows)
14787 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14788 (org-switch-to-buffer-other-window " *Org tags*"))
14789 (erase-buffer)
14790 (org-set-local 'org-done-keywords done-keywords)
14791 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14792 (org-fast-tag-insert "Current" current c-face "\n\n")
14793 (org-fast-tag-show-exit exit-after-next)
14794 (org-set-current-tags-overlay current ov-prefix)
14795 (setq tbl fulltable char ?a cnt 0)
14796 (dolist (e tbl)
14797 (cond
14798 ((equal (car e) :startgroup)
14799 (push '() groups) (setq ingroup t)
14800 (when (not (= cnt 0))
14801 (setq cnt 0)
14802 (insert "\n"))
14803 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14804 ((equal (car e) :endgroup)
14805 (setq ingroup nil cnt 0)
14806 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14807 ((equal e '(:newline))
14808 (when (not (= cnt 0))
14809 (setq cnt 0)
14810 (insert "\n")
14811 (setq e (car tbl))
14812 (while (equal (car tbl) '(:newline))
14813 (insert "\n")
14814 (setq tbl (cdr tbl)))))
14815 ((equal e '(:grouptags)) nil)
14816 (t
14817 (setq tg (copy-sequence (car e)) c2 nil)
14818 (if (cdr e)
14819 (setq c (cdr e))
14820 ;; automatically assign a character.
14821 (setq c1 (string-to-char
14822 (downcase (substring
14823 tg (if (= (string-to-char tg) ?@) 1 0)))))
14824 (if (or (rassoc c1 ntable) (rassoc c1 table))
14825 (while (or (rassoc char ntable) (rassoc char table))
14826 (setq char (1+ char)))
14827 (setq c2 c1))
14828 (setq c (or c2 char)))
14829 (if ingroup (push tg (car groups)))
14830 (setq tg (org-add-props tg nil 'face
14831 (cond
14832 ((not (assoc tg table))
14833 (org-get-todo-face tg))
14834 ((member tg current) c-face)
14835 ((member tg inherited) i-face))))
14836 (if (equal (caar tbl) :grouptags)
14837 (org-add-props tg nil 'face 'org-tag-group))
14838 (if (and (= cnt 0) (not ingroup)) (insert " "))
14839 (insert "[" c "] " tg (make-string
14840 (- fwidth 4 (length tg)) ?\ ))
14841 (push (cons tg c) ntable)
14842 (when (= (setq cnt (1+ cnt)) ncol)
14843 (insert "\n")
14844 (if ingroup (insert " "))
14845 (setq cnt 0)))))
14846 (setq ntable (nreverse ntable))
14847 (insert "\n")
14848 (goto-char (point-min))
14849 (if (not expert) (org-fit-window-to-buffer))
14850 (setq rtn
14851 (catch 'exit
14852 (while t
14853 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14854 (if (not groups) "no " "")
14855 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14856 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14857 (setq org-last-tag-selection-key c)
14858 (cond
14859 ((= c ?\r) (throw 'exit t))
14860 ((= c ?!)
14861 (setq groups (not groups))
14862 (goto-char (point-min))
14863 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14864 ((= c ?\C-c)
14865 (if (not expert)
14866 (org-fast-tag-show-exit
14867 (setq exit-after-next (not exit-after-next)))
14868 (setq expert nil)
14869 (delete-other-windows)
14870 (set-window-buffer (split-window-vertically) " *Org tags*")
14871 (org-switch-to-buffer-other-window " *Org tags*")
14872 (org-fit-window-to-buffer)))
14873 ((or (= c ?\C-g)
14874 (and (= c ?q) (not (rassoc c ntable))))
14875 (org-detach-overlay org-tags-overlay)
14876 (setq quit-flag t))
14877 ((= c ?\ )
14878 (setq current nil)
14879 (if exit-after-next (setq exit-after-next 'now)))
14880 ((= c ?\t)
14881 (condition-case nil
14882 (setq tg (org-icompleting-read
14883 "Tag: "
14884 (or buffer-tags
14885 (with-current-buffer buf
14886 (org-get-buffer-tags)))))
14887 (quit (setq tg "")))
14888 (when (string-match "\\S-" tg)
14889 (add-to-list 'buffer-tags (list tg))
14890 (if (member tg current)
14891 (setq current (delete tg current))
14892 (push tg current)))
14893 (if exit-after-next (setq exit-after-next 'now)))
14894 ((setq e (rassoc c todo-table) tg (car e))
14895 (with-current-buffer buf
14896 (save-excursion (org-todo tg)))
14897 (if exit-after-next (setq exit-after-next 'now)))
14898 ((setq e (rassoc c ntable) tg (car e))
14899 (if (member tg current)
14900 (setq current (delete tg current))
14901 (loop for g in groups do
14902 (if (member tg g)
14903 (mapc (lambda (x)
14904 (setq current (delete x current)))
14905 g)))
14906 (push tg current))
14907 (if exit-after-next (setq exit-after-next 'now))))
14908
14909 ;; Create a sorted list
14910 (setq current
14911 (sort current
14912 (lambda (a b)
14913 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14914 (if (eq exit-after-next 'now) (throw 'exit t))
14915 (goto-char (point-min))
14916 (beginning-of-line 2)
14917 (delete-region (point) (point-at-eol))
14918 (org-fast-tag-insert "Current" current c-face)
14919 (org-set-current-tags-overlay current ov-prefix)
14920 (while (re-search-forward
14921 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14922 (setq tg (match-string 1))
14923 (add-text-properties
14924 (match-beginning 1) (match-end 1)
14925 (list 'face
14926 (cond
14927 ((member tg current) c-face)
14928 ((member tg inherited) i-face)
14929 (t (get-text-property (match-beginning 1) 'face))))))
14930 (goto-char (point-min)))))
14931 (org-detach-overlay org-tags-overlay)
14932 (if rtn
14933 (mapconcat 'identity current ":")
14934 nil))))
14935
14936 (defun org-get-tags-string ()
14937 "Get the TAGS string in the current headline."
14938 (unless (org-at-heading-p t)
14939 (user-error "Not on a heading"))
14940 (save-excursion
14941 (beginning-of-line 1)
14942 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14943 (org-match-string-no-properties 1)
14944 "")))
14945
14946 (defun org-get-tags ()
14947 "Get the list of tags specified in the current headline."
14948 (org-split-string (org-get-tags-string) ":"))
14949
14950 (defun org-get-buffer-tags ()
14951 "Get a table of all tags used in the buffer, for completion."
14952 (let (tags)
14953 (save-excursion
14954 (goto-char (point-min))
14955 (while (re-search-forward
14956 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14957 (when (equal (char-after (point-at-bol 0)) ?*)
14958 (mapc (lambda (x) (add-to-list 'tags x))
14959 (org-split-string (org-match-string-no-properties 1) ":")))))
14960 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14961 (mapcar 'list tags)))
14962
14963 ;;;; The mapping API
14964
14965 (defun org-map-entries (func &optional match scope &rest skip)
14966 "Call FUNC at each headline selected by MATCH in SCOPE.
14967
14968 FUNC is a function or a lisp form. The function will be called without
14969 arguments, with the cursor positioned at the beginning of the headline.
14970 The return values of all calls to the function will be collected and
14971 returned as a list.
14972
14973 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14974 does not need to preserve point. After evaluation, the cursor will be
14975 moved to the end of the line (presumably of the headline of the
14976 processed entry) and search continues from there. Under some
14977 circumstances, this may not produce the wanted results. For example,
14978 if you have removed (e.g. archived) the current (sub)tree it could
14979 mean that the next entry will be skipped entirely. In such cases, you
14980 can specify the position from where search should continue by making
14981 FUNC set the variable `org-map-continue-from' to the desired buffer
14982 position.
14983
14984 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14985 Only headlines that are matched by this query will be considered during
14986 the iteration. When MATCH is nil or t, all headlines will be
14987 visited by the iteration.
14988
14989 SCOPE determines the scope of this command. It can be any of:
14990
14991 nil The current buffer, respecting the restriction if any
14992 tree The subtree started with the entry at point
14993 region The entries within the active region, if any
14994 region-start-level
14995 The entries within the active region, but only those at
14996 the same level than the first one.
14997 file The current buffer, without restriction
14998 file-with-archives
14999 The current buffer, and any archives associated with it
15000 agenda All agenda files
15001 agenda-with-archives
15002 All agenda files with any archive files associated with them
15003 \(file1 file2 ...)
15004 If this is a list, all files in the list will be scanned
15005
15006 The remaining args are treated as settings for the skipping facilities of
15007 the scanner. The following items can be given here:
15008
15009 archive skip trees with the archive tag
15010 comment skip trees with the COMMENT keyword
15011 function or Emacs Lisp form:
15012 will be used as value for `org-agenda-skip-function', so
15013 whenever the function returns a position, FUNC will not be
15014 called for that entry and search will continue from the
15015 position returned
15016
15017 If your function needs to retrieve the tags including inherited tags
15018 at the *current* entry, you can use the value of the variable
15019 `org-scanner-tags' which will be much faster than getting the value
15020 with `org-get-tags-at'. If your function gets properties with
15021 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15022 to t around the call to `org-entry-properties' to get the same speedup.
15023 Note that if your function moves around to retrieve tags and properties at
15024 a *different* entry, you cannot use these techniques."
15025 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15026 (not (org-region-active-p)))
15027 (let* ((org-agenda-archives-mode nil) ; just to make sure
15028 (org-agenda-skip-archived-trees (memq 'archive skip))
15029 (org-agenda-skip-comment-trees (memq 'comment skip))
15030 (org-agenda-skip-function
15031 (car (org-delete-all '(comment archive) skip)))
15032 (org-tags-match-list-sublevels t)
15033 (start-level (eq scope 'region-start-level))
15034 matcher file res
15035 org-todo-keywords-for-agenda
15036 org-done-keywords-for-agenda
15037 org-todo-keyword-alist-for-agenda
15038 org-drawers-for-agenda
15039 org-tag-alist-for-agenda
15040 todo-only)
15041
15042 (cond
15043 ((eq match t) (setq matcher t))
15044 ((eq match nil) (setq matcher t))
15045 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15046
15047 (save-excursion
15048 (save-restriction
15049 (cond ((eq scope 'tree)
15050 (org-back-to-heading t)
15051 (org-narrow-to-subtree)
15052 (setq scope nil))
15053 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15054 (org-region-active-p))
15055 ;; If needed, set start-level to a string like "2"
15056 (when start-level
15057 (save-excursion
15058 (goto-char (region-beginning))
15059 (unless (org-at-heading-p) (outline-next-heading))
15060 (setq start-level (org-current-level))))
15061 (narrow-to-region (region-beginning)
15062 (save-excursion
15063 (goto-char (region-end))
15064 (unless (and (bolp) (org-at-heading-p))
15065 (outline-next-heading))
15066 (point)))
15067 (setq scope nil)))
15068
15069 (if (not scope)
15070 (progn
15071 (org-agenda-prepare-buffers
15072 (list (buffer-file-name (current-buffer))))
15073 (setq res (org-scan-tags func matcher todo-only start-level)))
15074 ;; Get the right scope
15075 (cond
15076 ((and scope (listp scope) (symbolp (car scope)))
15077 (setq scope (eval scope)))
15078 ((eq scope 'agenda)
15079 (setq scope (org-agenda-files t)))
15080 ((eq scope 'agenda-with-archives)
15081 (setq scope (org-agenda-files t))
15082 (setq scope (org-add-archive-files scope)))
15083 ((eq scope 'file)
15084 (setq scope (list (buffer-file-name))))
15085 ((eq scope 'file-with-archives)
15086 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15087 (org-agenda-prepare-buffers scope)
15088 (dolist (file scope)
15089 (with-current-buffer (org-find-base-buffer-visiting file)
15090 (save-excursion
15091 (save-restriction
15092 (widen)
15093 (goto-char (point-min))
15094 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15095 res)))
15096
15097 ;;;; Properties
15098
15099 ;;; Setting and retrieving properties
15100
15101 (defconst org-special-properties
15102 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15103 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15104 "The special properties valid in Org-mode.
15105
15106 These are properties that are not defined in the property drawer,
15107 but in some other way.")
15108
15109 (defconst org-default-properties
15110 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15111 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15112 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15113 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15114 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15115 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15116 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15117 "Some properties that are used by Org-mode for various purposes.
15118 Being in this list makes sure that they are offered for completion.")
15119
15120 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15121 "Regular expression matching the first line of a property drawer.")
15122
15123 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15124 "Regular expression matching the last line of a property drawer.")
15125
15126 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15127 "Regular expression matching the first line of a property drawer.")
15128
15129 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15130 "Regular expression matching the first line of a property drawer.")
15131
15132 (defconst org-property-drawer-re
15133 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15134 org-property-end-re "\\)\n?")
15135 "Matches an entire property drawer.")
15136
15137 (defconst org-clock-drawer-re
15138 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15139 org-property-end-re "\\)\n?")
15140 "Matches an entire clock drawer.")
15141
15142 (defun org-property-action ()
15143 "Do an action on properties."
15144 (interactive)
15145 (let (c)
15146 (org-at-property-p)
15147 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15148 (setq c (read-char-exclusive))
15149 (cond
15150 ((equal c ?s)
15151 (call-interactively 'org-set-property))
15152 ((equal c ?d)
15153 (call-interactively 'org-delete-property))
15154 ((equal c ?D)
15155 (call-interactively 'org-delete-property-globally))
15156 ((equal c ?c)
15157 (call-interactively 'org-compute-property-at-point))
15158 (t (user-error "No such property action %c" c)))))
15159
15160 (defun org-inc-effort ()
15161 "Increment the value of the effort property in the current entry."
15162 (interactive)
15163 (org-set-effort nil t))
15164
15165 (defvar org-clock-effort) ;; Defined in org-clock.el
15166 (defvar org-clock-current-task) ;; Defined in org-clock.el
15167 (defun org-set-effort (&optional value increment)
15168 "Set the effort property of the current entry.
15169 With numerical prefix arg, use the nth allowed value, 0 stands for the
15170 10th allowed value.
15171
15172 When INCREMENT is non-nil, set the property to the next allowed value."
15173 (interactive "P")
15174 (if (equal value 0) (setq value 10))
15175 (let* ((completion-ignore-case t)
15176 (prop org-effort-property)
15177 (cur (org-entry-get nil prop))
15178 (allowed (org-property-get-allowed-values nil prop 'table))
15179 (existing (mapcar 'list (org-property-values prop)))
15180 (heading (nth 4 (org-heading-components)))
15181 rpl
15182 (val (cond
15183 ((stringp value) value)
15184 ((and allowed (integerp value))
15185 (or (car (nth (1- value) allowed))
15186 (car (org-last allowed))))
15187 ((and allowed increment)
15188 (or (caadr (member (list cur) allowed))
15189 (user-error "Allowed effort values are not set")))
15190 (allowed
15191 (message "Select 1-9,0, [RET%s]: %s"
15192 (if cur (concat "=" cur) "")
15193 (mapconcat 'car allowed " "))
15194 (setq rpl (read-char-exclusive))
15195 (if (equal rpl ?\r)
15196 cur
15197 (setq rpl (- rpl ?0))
15198 (if (equal rpl 0) (setq rpl 10))
15199 (if (and (> rpl 0) (<= rpl (length allowed)))
15200 (car (nth (1- rpl) allowed))
15201 (org-completing-read "Effort: " allowed nil))))
15202 (t
15203 (let (org-completion-use-ido org-completion-use-iswitchb)
15204 (org-completing-read
15205 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15206 (concat "[" cur "]") "")
15207 ": ")
15208 existing nil nil "" nil cur))))))
15209 (unless (equal (org-entry-get nil prop) val)
15210 (org-entry-put nil prop val))
15211 (save-excursion
15212 (org-back-to-heading t)
15213 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15214 (when (string= heading org-clock-current-task)
15215 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15216 (org-clock-update-mode-line))
15217 (message "%s is now %s" prop val)))
15218
15219 (defun org-at-property-p ()
15220 "Is cursor inside a property drawer?"
15221 (save-excursion
15222 (when (equal 'node-property (car (org-element-at-point)))
15223 (beginning-of-line 1)
15224 (looking-at org-property-re))))
15225
15226 (defun org-get-property-block (&optional beg end force)
15227 "Return the (beg . end) range of the body of the property drawer.
15228 BEG and END are the beginning and end of the current subtree, or of
15229 the part before the first headline. If they are not given, they will
15230 be found. If the drawer does not exist and FORCE is non-nil, create
15231 the drawer."
15232 (catch 'exit
15233 (save-excursion
15234 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15235 (progn (org-back-to-heading t) (point))))
15236 (end (or end (and (not (outline-next-heading)) (point-max))
15237 (point))))
15238 (goto-char beg)
15239 (if (re-search-forward org-property-start-re end t)
15240 (setq beg (1+ (match-end 0)))
15241 (if force
15242 (save-excursion
15243 (org-insert-property-drawer)
15244 (setq end (progn (outline-next-heading) (point))))
15245 (throw 'exit nil))
15246 (goto-char beg)
15247 (if (re-search-forward org-property-start-re end t)
15248 (setq beg (1+ (match-end 0)))))
15249 (if (re-search-forward org-property-end-re end t)
15250 (setq end (match-beginning 0))
15251 (or force (throw 'exit nil))
15252 (goto-char beg)
15253 (setq end beg)
15254 (org-indent-line)
15255 (insert ":END:\n"))
15256 (cons beg end)))))
15257
15258 (defun org-entry-properties (&optional pom which specific)
15259 "Get all properties of the entry at point-or-marker POM.
15260 This includes the TODO keyword, the tags, time strings for deadline,
15261 scheduled, and clocking, and any additional properties defined in the
15262 entry. The return value is an alist, keys may occur multiple times
15263 if the property key was used several times.
15264 POM may also be nil, in which case the current entry is used.
15265 If WHICH is nil or `all', get all properties. If WHICH is
15266 `special' or `standard', only get that subclass. If WHICH
15267 is a string only get exactly this property. SPECIFIC can be a string, the
15268 specific property we are interested in. Specifying it can speed
15269 things up because then unnecessary parsing is avoided."
15270 (setq which (or which 'all))
15271 (org-with-wide-buffer
15272 (org-with-point-at pom
15273 (let ((clockstr (substring org-clock-string 0 -1))
15274 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15275 (case-fold-search nil)
15276 beg end range props sum-props key key1 value string clocksum clocksumt)
15277 (when (and (derived-mode-p 'org-mode)
15278 (ignore-errors (org-back-to-heading t)))
15279 (setq beg (point))
15280 (setq sum-props (get-text-property (point) 'org-summaries))
15281 (setq clocksum (get-text-property (point) :org-clock-minutes)
15282 clocksumt (get-text-property (point) :org-clock-minutes-today))
15283 (outline-next-heading)
15284 (setq end (point))
15285 (when (memq which '(all special))
15286 ;; Get the special properties, like TODO and tags
15287 (goto-char beg)
15288 (when (and (or (not specific) (string= specific "TODO"))
15289 (looking-at org-todo-line-regexp) (match-end 2))
15290 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15291 (when (and (or (not specific) (string= specific "PRIORITY"))
15292 (looking-at org-priority-regexp))
15293 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15294 (when (or (not specific) (string= specific "FILE"))
15295 (push (cons "FILE" buffer-file-name) props))
15296 (when (and (or (not specific) (string= specific "TAGS"))
15297 (setq value (org-get-tags-string))
15298 (string-match "\\S-" value))
15299 (push (cons "TAGS" value) props))
15300 (when (and (or (not specific) (string= specific "ALLTAGS"))
15301 (setq value (org-get-tags-at)))
15302 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15303 ":"))
15304 props))
15305 (when (or (not specific) (string= specific "BLOCKED"))
15306 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15307 (when (or (not specific)
15308 (member specific
15309 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15310 "TIMESTAMP" "TIMESTAMP_IA")))
15311 (catch 'match
15312 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15313 (not (text-property-any 0 (length (match-string 0))
15314 'face 'font-lock-comment-face
15315 (match-string 0))))
15316 (setq key (if (match-end 1)
15317 (substring (org-match-string-no-properties 1)
15318 0 -1))
15319 string (if (equal key clockstr)
15320 (org-trim
15321 (buffer-substring-no-properties
15322 (match-beginning 3) (goto-char
15323 (point-at-eol))))
15324 (substring (org-match-string-no-properties 3)
15325 1 -1)))
15326 ;; Get the correct property name from the key. This is
15327 ;; necessary if the user has configured time keywords.
15328 (setq key1 (concat key ":"))
15329 (cond
15330 ((not key)
15331 (setq key
15332 (if (= (char-after (match-beginning 3)) ?\[)
15333 "TIMESTAMP_IA" "TIMESTAMP")))
15334 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15335 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15336 ((equal key1 org-closed-string) (setq key "CLOSED"))
15337 ((equal key1 org-clock-string) (setq key "CLOCK")))
15338 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15339 (progn
15340 (push (cons key string) props)
15341 ;; no need to search further if match is found
15342 (throw 'match t))
15343 (when (or (equal key "CLOCK") (not (assoc key props)))
15344 (push (cons key string) props)))))))
15345
15346 (when (memq which '(all standard))
15347 ;; Get the standard properties, like :PROP: ...
15348 (setq range (org-get-property-block beg end))
15349 (when range
15350 (goto-char (car range))
15351 (while (re-search-forward org-property-re
15352 (cdr range) t)
15353 (setq key (org-match-string-no-properties 2)
15354 value (org-trim (or (org-match-string-no-properties 3) "")))
15355 (unless (member key excluded)
15356 (push (cons key (or value "")) props)))))
15357 (if clocksum
15358 (push (cons "CLOCKSUM"
15359 (org-columns-number-to-string (/ (float clocksum) 60.)
15360 'add_times))
15361 props))
15362 (if clocksumt
15363 (push (cons "CLOCKSUM_T"
15364 (org-columns-number-to-string (/ (float clocksumt) 60.)
15365 'add_times))
15366 props))
15367 (unless (assoc "CATEGORY" props)
15368 (push (cons "CATEGORY" (org-get-category)) props))
15369 (append sum-props (nreverse props)))))))
15370
15371 (defun org-entry-get (pom property &optional inherit literal-nil)
15372 "Get value of PROPERTY for entry or content at point-or-marker POM.
15373 If INHERIT is non-nil and the entry does not have the property,
15374 then also check higher levels of the hierarchy.
15375 If INHERIT is the symbol `selective', use inheritance only if the setting
15376 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15377 If the property is present but empty, the return value is the empty string.
15378 If the property is not present at all, nil is returned.
15379
15380 Return the value as a string.
15381
15382 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15383 do not interpret it as the list atom nil. This is used for inheritance
15384 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15385 (org-with-point-at pom
15386 (if (and inherit (if (eq inherit 'selective)
15387 (org-property-inherit-p property)
15388 t))
15389 (org-entry-get-with-inheritance property literal-nil)
15390 (if (member property org-special-properties)
15391 ;; We need a special property. Use `org-entry-properties'
15392 ;; to retrieve it, but specify the wanted property
15393 (cdr (assoc property (org-entry-properties nil 'special property)))
15394 (org-with-wide-buffer
15395 (let ((range (org-get-property-block)))
15396 (when (and range (not (eq (car range) (cdr range)))
15397 (save-excursion
15398 (goto-char (car range))
15399 (re-search-forward
15400 (concat (org-re-property property) "\\|"
15401 (org-re-property (concat property "+")))
15402 (cdr range) t)))
15403 (let* ((props
15404 (list (or (assoc property org-file-properties)
15405 (assoc property org-global-properties)
15406 (assoc property org-global-properties-fixed))))
15407 (ap (lambda (key)
15408 (when (re-search-forward
15409 (org-re-property key) (cdr range) t)
15410 (setq props
15411 (org-update-property-plist
15412 key
15413 (if (match-end 3)
15414 (org-match-string-no-properties 3) "")
15415 props)))))
15416 val)
15417 (goto-char (car range))
15418 (funcall ap property)
15419 (goto-char (car range))
15420 (while (funcall ap (concat property "+")))
15421 (setq val (cdr (assoc property props)))
15422 (when val (if literal-nil val (org-not-nil val)))))))))))
15423
15424 (defun org-property-or-variable-value (var &optional inherit)
15425 "Check if there is a property fixing the value of VAR.
15426 If yes, return this value. If not, return the current value of the variable."
15427 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15428 (if (and prop (stringp prop) (string-match "\\S-" prop))
15429 (read prop)
15430 (symbol-value var))))
15431
15432 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15433 "Delete the property PROPERTY from entry at point-or-marker POM.
15434 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15435 an empty drawer to delete."
15436 (org-with-point-at pom
15437 (if (member property org-special-properties)
15438 nil ; cannot delete these properties.
15439 (let ((range (org-get-property-block)))
15440 (if (and range
15441 (goto-char (car range))
15442 (re-search-forward
15443 (org-re-property property nil t)
15444 (cdr range) t))
15445 (progn
15446 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15447 (and delete-empty-drawer
15448 (org-remove-empty-drawer-at
15449 delete-empty-drawer (car range)))
15450 t)
15451 nil)))))
15452
15453 ;; Multi-values properties are properties that contain multiple values
15454 ;; These values are assumed to be single words, separated by whitespace.
15455 (defun org-entry-add-to-multivalued-property (pom property value)
15456 "Add VALUE to the 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 (unless (member value values)
15461 (setq values (append values (list value)))
15462 (org-entry-put pom property
15463 (mapconcat 'identity values " ")))))
15464
15465 (defun org-entry-remove-from-multivalued-property (pom property value)
15466 "Remove VALUE from 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 (when (member value values)
15471 (setq values (delete value values))
15472 (org-entry-put pom property
15473 (mapconcat 'identity values " ")))))
15474
15475 (defun org-entry-member-in-multivalued-property (pom property value)
15476 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15477 (let* ((old (org-entry-get pom property))
15478 (values (and old (org-split-string old "[ \t]"))))
15479 (setq value (org-entry-protect-space value))
15480 (member value values)))
15481
15482 (defun org-entry-get-multivalued-property (pom property)
15483 "Return a list of values in a multivalued property."
15484 (let* ((value (org-entry-get pom property))
15485 (values (and value (org-split-string value "[ \t]"))))
15486 (mapcar 'org-entry-restore-space values)))
15487
15488 (defun org-entry-put-multivalued-property (pom property &rest values)
15489 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15490 VALUES should be a list of strings. Spaces will be protected."
15491 (org-entry-put pom property
15492 (mapconcat 'org-entry-protect-space values " "))
15493 (let* ((value (org-entry-get pom property))
15494 (values (and value (org-split-string value "[ \t]"))))
15495 (mapcar 'org-entry-restore-space values)))
15496
15497 (defun org-entry-protect-space (s)
15498 "Protect spaces and newline in string S."
15499 (while (string-match " " s)
15500 (setq s (replace-match "%20" t t s)))
15501 (while (string-match "\n" s)
15502 (setq s (replace-match "%0A" t t s)))
15503 s)
15504
15505 (defun org-entry-restore-space (s)
15506 "Restore spaces and newline in string S."
15507 (while (string-match "%20" s)
15508 (setq s (replace-match " " t t s)))
15509 (while (string-match "%0A" s)
15510 (setq s (replace-match "\n" t t s)))
15511 s)
15512
15513 (defvar org-entry-property-inherited-from (make-marker)
15514 "Marker pointing to the entry from where a property was inherited.
15515 Each call to `org-entry-get-with-inheritance' will set this marker to the
15516 location of the entry where the inheritance search matched. If there was
15517 no match, the marker will point nowhere.
15518 Note that also `org-entry-get' calls this function, if the INHERIT flag
15519 is set.")
15520
15521 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15522 "Get PROPERTY of entry or content at point, search higher levels if needed.
15523 The search will stop at the first ancestor which has the property defined.
15524 If the value found is \"nil\", return nil to show that the property
15525 should be considered as undefined (this is the meaning of nil here).
15526 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15527 (move-marker org-entry-property-inherited-from nil)
15528 (let (tmp)
15529 (save-excursion
15530 (save-restriction
15531 (widen)
15532 (catch 'ex
15533 (while t
15534 (when (setq tmp (org-entry-get nil property nil literal-nil))
15535 (or (ignore-errors (org-back-to-heading t))
15536 (goto-char (point-min)))
15537 (move-marker org-entry-property-inherited-from (point))
15538 (throw 'ex tmp))
15539 (or (ignore-errors (org-up-heading-safe))
15540 (throw 'ex nil))))))
15541 (setq tmp (or tmp
15542 (cdr (assoc property org-file-properties))
15543 (cdr (assoc property org-global-properties))
15544 (cdr (assoc property org-global-properties-fixed))))
15545 (if literal-nil tmp (org-not-nil tmp))))
15546
15547 (defvar org-property-changed-functions nil
15548 "Hook called when the value of a property has changed.
15549 Each hook function should accept two arguments, the name of the property
15550 and the new value.")
15551
15552 (defun org-entry-put (pom property value)
15553 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15554 If the value is nil, it is converted to the empty string.
15555 If it is not a string, an error is raised."
15556 (cond ((null value) (setq value ""))
15557 ((not (stringp value))
15558 (error "Properties values should be strings.")))
15559 (org-with-point-at pom
15560 (org-back-to-heading t)
15561 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15562 range)
15563 (cond
15564 ((equal property "TODO")
15565 (when (and (string-match "\\S-" value)
15566 (not (member value org-todo-keywords-1)))
15567 (user-error "\"%s\" is not a valid TODO state" value))
15568 (if (or (not value)
15569 (not (string-match "\\S-" value)))
15570 (setq value 'none))
15571 (org-todo value)
15572 (org-set-tags nil 'align))
15573 ((equal property "PRIORITY")
15574 (org-priority (if (and value (string-match "\\S-" value))
15575 (string-to-char value) ?\ ))
15576 (org-set-tags nil 'align))
15577 ((equal property "CLOCKSUM")
15578 (if (not (re-search-forward
15579 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15580 (error "Cannot find a clock log")
15581 (goto-char (- (match-end 1) 2))
15582 (cond
15583 ((eq value 'earlier) (org-timestamp-down))
15584 ((eq value 'later) (org-timestamp-up)))
15585 (org-clock-sum-current-item)))
15586 ((equal property "SCHEDULED")
15587 (if (re-search-forward org-scheduled-time-regexp end t)
15588 (cond
15589 ((eq value 'earlier) (org-timestamp-change -1 'day))
15590 ((eq value 'later) (org-timestamp-change 1 'day))
15591 (t (call-interactively 'org-schedule)))
15592 (call-interactively 'org-schedule)))
15593 ((equal property "DEADLINE")
15594 (if (re-search-forward org-deadline-time-regexp end t)
15595 (cond
15596 ((eq value 'earlier) (org-timestamp-change -1 'day))
15597 ((eq value 'later) (org-timestamp-change 1 'day))
15598 (t (call-interactively 'org-deadline)))
15599 (call-interactively 'org-deadline)))
15600 ((member property org-special-properties)
15601 (error "The %s property can not yet be set with `org-entry-put'"
15602 property))
15603 (t ; a non-special property
15604 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15605 (setq range (org-get-property-block beg end 'force))
15606 (goto-char (car range))
15607 (if (re-search-forward
15608 (org-re-property property nil t) (cdr range) t)
15609 (progn
15610 (delete-region (match-beginning 0) (match-end 0))
15611 (goto-char (match-beginning 0)))
15612 (goto-char (cdr range))
15613 (insert "\n")
15614 (backward-char 1)
15615 (org-indent-line))
15616 (insert ":" property ":")
15617 (and value (insert " " value))
15618 (org-indent-line)))))
15619 (run-hook-with-args 'org-property-changed-functions property value)))
15620
15621 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15622 "Get all property keys in the current buffer.
15623 With INCLUDE-SPECIALS, also list the special properties that reflect things
15624 like tags and TODO state.
15625 With INCLUDE-DEFAULTS, also include properties that has special meaning
15626 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15627 and others.
15628 With INCLUDE-COLUMNS, also include property names given in COLUMN
15629 formats in the current buffer."
15630 (let (rtn range cfmt s p)
15631 (save-excursion
15632 (save-restriction
15633 (widen)
15634 (goto-char (point-min))
15635 (while (re-search-forward org-property-start-re nil t)
15636 (setq range (org-get-property-block))
15637 (goto-char (car range))
15638 (while (re-search-forward org-property-re
15639 (cdr range) t)
15640 (add-to-list 'rtn (org-match-string-no-properties 2)))
15641 (outline-next-heading))))
15642
15643 (when include-specials
15644 (setq rtn (append org-special-properties rtn)))
15645
15646 (when include-defaults
15647 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15648 (add-to-list 'rtn org-effort-property))
15649
15650 (when include-columns
15651 (save-excursion
15652 (save-restriction
15653 (widen)
15654 (goto-char (point-min))
15655 (while (re-search-forward
15656 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15657 nil t)
15658 (setq cfmt (match-string 2) s 0)
15659 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15660 cfmt s)
15661 (setq s (match-end 0)
15662 p (match-string 1 cfmt))
15663 (unless (or (equal p "ITEM")
15664 (member p org-special-properties))
15665 (add-to-list 'rtn (match-string 1 cfmt))))))))
15666
15667 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15668
15669 (defun org-property-values (key)
15670 "Return a list of all values of property KEY in the current buffer."
15671 (save-excursion
15672 (save-restriction
15673 (widen)
15674 (goto-char (point-min))
15675 (let ((re (org-re-property key))
15676 values)
15677 (while (re-search-forward re nil t)
15678 (add-to-list 'values (org-trim (match-string 3))))
15679 (delete "" values)))))
15680
15681 (defun org-insert-property-drawer ()
15682 "Insert a property drawer into the current entry."
15683 (org-back-to-heading t)
15684 (looking-at org-outline-regexp)
15685 (let ((indent (if org-adapt-indentation
15686 (- (match-end 0) (match-beginning 0))
15687 0))
15688 (beg (point))
15689 (re (concat "^[ \t]*" org-keyword-time-regexp))
15690 end hiddenp)
15691 (outline-next-heading)
15692 (setq end (point))
15693 (goto-char beg)
15694 (while (re-search-forward re end t))
15695 (setq hiddenp (outline-invisible-p))
15696 (end-of-line 1)
15697 (and (equal (char-after) ?\n) (forward-char 1))
15698 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15699 (if (member (match-string 1) '("CLOCK:" ":END:"))
15700 ;; just skip this line
15701 (beginning-of-line 2)
15702 ;; Drawer start, find the end
15703 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15704 (beginning-of-line 1)))
15705 (org-skip-over-state-notes)
15706 (skip-chars-backward " \t\n\r")
15707 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15708 (forward-char 1))
15709 (goto-char (point-at-eol))
15710 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15711 (beginning-of-line 0)
15712 (org-indent-to-column indent)
15713 (beginning-of-line 2)
15714 (org-indent-to-column indent)
15715 (beginning-of-line 0)
15716 (if hiddenp
15717 (save-excursion
15718 (org-back-to-heading t)
15719 (hide-entry))
15720 (org-flag-drawer t))))
15721
15722 (defun org-insert-drawer (&optional arg drawer)
15723 "Insert a drawer at point.
15724
15725 Optional argument DRAWER, when non-nil, is a string representing
15726 drawer's name. Otherwise, the user is prompted for a name.
15727
15728 If a region is active, insert the drawer around that region
15729 instead.
15730
15731 Point is left between drawer's boundaries."
15732 (interactive "P")
15733 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15734 "LOGBOOK"))
15735 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15736 ;; internally by Org. They are meant to be inserted
15737 ;; automatically.
15738 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15739 ;; Remove system drawers from list. Note: For some reason,
15740 ;; `org-completing-read' ignores the predicate while
15741 ;; `completing-read' handles it fine.
15742 (drawer (if arg "PROPERTIES"
15743 (or drawer
15744 (completing-read
15745 "Drawer: " org-drawers
15746 (lambda (d) (not (member d system-drawers))))))))
15747 (cond
15748 ;; With C-u, fall back on `org-insert-property-drawer'
15749 (arg (org-insert-property-drawer))
15750 ;; With an active region, insert a drawer at point.
15751 ((not (org-region-active-p))
15752 (progn
15753 (unless (bolp) (insert "\n"))
15754 (insert (format ":%s:\n\n:END:\n" drawer))
15755 (forward-line -2)))
15756 ;; Otherwise, insert the drawer at point
15757 (t
15758 (let ((rbeg (region-beginning))
15759 (rend (copy-marker (region-end))))
15760 (unwind-protect
15761 (progn
15762 (goto-char rbeg)
15763 (beginning-of-line)
15764 (when (save-excursion
15765 (re-search-forward org-outline-regexp-bol rend t))
15766 (user-error "Drawers cannot contain headlines"))
15767 ;; Position point at the beginning of the first
15768 ;; non-blank line in region. Insert drawer's opening
15769 ;; there, then indent it.
15770 (org-skip-whitespace)
15771 (beginning-of-line)
15772 (insert ":" drawer ":\n")
15773 (forward-line -1)
15774 (indent-for-tab-command)
15775 ;; Move point to the beginning of the first blank line
15776 ;; after the last non-blank line in region. Insert
15777 ;; drawer's closing, then indent it.
15778 (goto-char rend)
15779 (skip-chars-backward " \r\t\n")
15780 (insert "\n:END:")
15781 (deactivate-mark t)
15782 (indent-for-tab-command)
15783 (unless (eolp) (insert "\n")))
15784 ;; Clear marker, whatever the outcome of insertion is.
15785 (set-marker rend nil)))))))
15786
15787 (defvar org-property-set-functions-alist nil
15788 "Property set function alist.
15789 Each entry should have the following format:
15790
15791 (PROPERTY . READ-FUNCTION)
15792
15793 The read function will be called with the same argument as
15794 `org-completing-read'.")
15795
15796 (defun org-set-property-function (property)
15797 "Get the function that should be used to set PROPERTY.
15798 This is computed according to `org-property-set-functions-alist'."
15799 (or (cdr (assoc property org-property-set-functions-alist))
15800 'org-completing-read))
15801
15802 (defun org-read-property-value (property)
15803 "Read PROPERTY value from user."
15804 (let* ((completion-ignore-case t)
15805 (allowed (org-property-get-allowed-values nil property 'table))
15806 (cur (org-entry-get nil property))
15807 (prompt (concat property " value"
15808 (if (and cur (string-match "\\S-" cur))
15809 (concat " [" cur "]") "") ": "))
15810 (set-function (org-set-property-function property))
15811 (val (if allowed
15812 (funcall set-function prompt allowed nil
15813 (not (get-text-property 0 'org-unrestricted
15814 (caar allowed))))
15815 (let (org-completion-use-ido org-completion-use-iswitchb)
15816 (funcall set-function prompt
15817 (mapcar 'list (org-property-values property))
15818 nil nil "" nil cur)))))
15819 (org-trim val)))
15820
15821 (defvar org-last-set-property nil)
15822 (defvar org-last-set-property-value nil)
15823 (defun org-read-property-name ()
15824 "Read a property name."
15825 (let* ((completion-ignore-case t)
15826 (keys (org-buffer-property-keys nil t t))
15827 (default-prop (or (save-excursion
15828 (save-match-data
15829 (beginning-of-line)
15830 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15831 (null (string= (match-string 1) "END"))
15832 (match-string 1))))
15833 org-last-set-property))
15834 (property (org-icompleting-read
15835 (concat "Property"
15836 (if default-prop (concat " [" default-prop "]") "")
15837 ": ")
15838 (mapcar 'list keys)
15839 nil nil nil nil
15840 default-prop)))
15841 (if (member property keys)
15842 property
15843 (or (cdr (assoc (downcase property)
15844 (mapcar (lambda (x) (cons (downcase x) x))
15845 keys)))
15846 property))))
15847
15848 (defun org-set-property-and-value (use-last)
15849 "Allow to set [PROPERTY]: [value] direction from prompt.
15850 When use-default, don't even ask, just use the last
15851 \"[PROPERTY]: [value]\" string from the history."
15852 (interactive "P")
15853 (let* ((completion-ignore-case t)
15854 (pv (or (and use-last org-last-set-property-value)
15855 (org-completing-read
15856 "Enter a \"[Property]: [value]\" pair: "
15857 nil nil nil nil nil
15858 org-last-set-property-value)))
15859 prop val)
15860 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15861 (setq prop (match-string 1 pv)
15862 val (match-string 2 pv))
15863 (org-set-property prop val))))
15864
15865 (defun org-set-property (property value)
15866 "In the current entry, set PROPERTY to VALUE.
15867 When called interactively, this will prompt for a property name, offering
15868 completion on existing and default properties. And then it will prompt
15869 for a value, offering completion either on allowed values (via an inherited
15870 xxx_ALL property) or on existing values in other instances of this property
15871 in the current file."
15872 (interactive (list nil nil))
15873 (let* ((property (or property (org-read-property-name)))
15874 (value (or value (org-read-property-value property)))
15875 (fn (cdr (assoc property org-properties-postprocess-alist))))
15876 (setq org-last-set-property property)
15877 (setq org-last-set-property-value (concat property ": " value))
15878 ;; Possibly postprocess the inserted value:
15879 (when fn (setq value (funcall fn value)))
15880 (unless (equal (org-entry-get nil property) value)
15881 (org-entry-put nil property value))))
15882
15883 (defun org-delete-property (property &optional delete-empty-drawer)
15884 "In the current entry, delete PROPERTY.
15885 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15886 an empty drawer to delete."
15887 (interactive
15888 (let* ((completion-ignore-case t)
15889 (cat (org-entry-get (point) "CATEGORY"))
15890 (props0 (org-entry-properties nil 'standard))
15891 (props (if cat props0
15892 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15893 (prop (if (< 1 (length props))
15894 (org-icompleting-read "Property: " props nil t)
15895 (caar props))))
15896 (list prop)))
15897 (if (not property)
15898 (message "No property to delete in this entry")
15899 (org-entry-delete nil property delete-empty-drawer)
15900 (message "Property \"%s\" deleted" property)))
15901
15902 (defun org-delete-property-globally (property)
15903 "Remove PROPERTY globally, from all entries."
15904 (interactive
15905 (let* ((completion-ignore-case t)
15906 (prop (org-icompleting-read
15907 "Globally remove property: "
15908 (mapcar 'list (org-buffer-property-keys)))))
15909 (list prop)))
15910 (save-excursion
15911 (save-restriction
15912 (widen)
15913 (goto-char (point-min))
15914 (let ((cnt 0))
15915 (while (re-search-forward
15916 (org-re-property property)
15917 nil t)
15918 (setq cnt (1+ cnt))
15919 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15920 (message "Property \"%s\" removed from %d entries" property cnt)))))
15921
15922 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15923
15924 (defun org-compute-property-at-point ()
15925 "Compute the property at point.
15926 This looks for an enclosing column format, extracts the operator and
15927 then applies it to the property in the column format's scope."
15928 (interactive)
15929 (unless (org-at-property-p)
15930 (user-error "Not at a property"))
15931 (let ((prop (org-match-string-no-properties 2)))
15932 (org-columns-get-format-and-top-level)
15933 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15934 (user-error "No operator defined for property %s" prop))
15935 (org-columns-compute prop)))
15936
15937 (defvar org-property-allowed-value-functions nil
15938 "Hook for functions supplying allowed values for a specific property.
15939 The functions must take a single argument, the name of the property, and
15940 return a flat list of allowed values. If \":ETC\" is one of
15941 the values, this means that these values are intended as defaults for
15942 completion, but that other values should be allowed too.
15943 The functions must return nil if they are not responsible for this
15944 property.")
15945
15946 (defun org-property-get-allowed-values (pom property &optional table)
15947 "Get allowed values for the property PROPERTY.
15948 When TABLE is non-nil, return an alist that can directly be used for
15949 completion."
15950 (let (vals)
15951 (cond
15952 ((equal property "TODO")
15953 (setq vals (org-with-point-at pom
15954 (append org-todo-keywords-1 '("")))))
15955 ((equal property "PRIORITY")
15956 (let ((n org-lowest-priority))
15957 (while (>= n org-highest-priority)
15958 (push (char-to-string n) vals)
15959 (setq n (1- n)))))
15960 ((member property org-special-properties))
15961 ((setq vals (run-hook-with-args-until-success
15962 'org-property-allowed-value-functions property)))
15963 (t
15964 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15965 (when (and vals (string-match "\\S-" vals))
15966 (setq vals (car (read-from-string (concat "(" vals ")"))))
15967 (setq vals (mapcar (lambda (x)
15968 (cond ((stringp x) x)
15969 ((numberp x) (number-to-string x))
15970 ((symbolp x) (symbol-name x))
15971 (t "???")))
15972 vals)))))
15973 (when (member ":ETC" vals)
15974 (setq vals (remove ":ETC" vals))
15975 (org-add-props (car vals) '(org-unrestricted t)))
15976 (if table (mapcar 'list vals) vals)))
15977
15978 (defun org-property-previous-allowed-value (&optional previous)
15979 "Switch to the next allowed value for this property."
15980 (interactive)
15981 (org-property-next-allowed-value t))
15982
15983 (defun org-property-next-allowed-value (&optional previous)
15984 "Switch to the next allowed value for this property."
15985 (interactive)
15986 (unless (org-at-property-p)
15987 (user-error "Not at a property"))
15988 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15989 (key (match-string 2))
15990 (value (match-string 3))
15991 (allowed (or (org-property-get-allowed-values (point) key)
15992 (and (member value '("[ ]" "[-]" "[X]"))
15993 '("[ ]" "[X]"))))
15994 (heading (save-match-data (nth 4 (org-heading-components))))
15995 nval)
15996 (unless allowed
15997 (user-error "Allowed values for this property have not been defined"))
15998 (if previous (setq allowed (reverse allowed)))
15999 (if (member value allowed)
16000 (setq nval (car (cdr (member value allowed)))))
16001 (setq nval (or nval (car allowed)))
16002 (if (equal nval value)
16003 (user-error "Only one allowed value for this property"))
16004 (org-at-property-p)
16005 (replace-match (concat " :" key ": " nval) t t)
16006 (org-indent-line)
16007 (beginning-of-line 1)
16008 (skip-chars-forward " \t")
16009 (when (equal prop org-effort-property)
16010 (save-excursion
16011 (org-back-to-heading t)
16012 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16013 (when (string= org-clock-current-task heading)
16014 (setq org-clock-effort nval)
16015 (org-clock-update-mode-line)))
16016 (run-hook-with-args 'org-property-changed-functions key nval)))
16017
16018 (defun org-find-olp (path &optional this-buffer)
16019 "Return a marker pointing to the entry at outline path OLP.
16020 If anything goes wrong, throw an error.
16021 You can wrap this call to catch the error like this:
16022
16023 (condition-case msg
16024 (org-mobile-locate-entry (match-string 4))
16025 (error (nth 1 msg)))
16026
16027 The return value will then be either a string with the error message,
16028 or a marker if everything is OK.
16029
16030 If THIS-BUFFER is set, the outline path does not contain a file,
16031 only headings."
16032 (let* ((file (if this-buffer buffer-file-name (pop path)))
16033 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16034 (level 1)
16035 (lmin 1)
16036 (lmax 1)
16037 limit re end found pos heading cnt flevel)
16038 (unless buffer (error "File not found :%s" file))
16039 (with-current-buffer buffer
16040 (save-excursion
16041 (save-restriction
16042 (widen)
16043 (setq limit (point-max))
16044 (goto-char (point-min))
16045 (dolist (heading path)
16046 (setq re (format org-complex-heading-regexp-format
16047 (regexp-quote heading)))
16048 (setq cnt 0 pos (point))
16049 (while (re-search-forward re end t)
16050 (setq level (- (match-end 1) (match-beginning 1)))
16051 (if (and (>= level lmin) (<= level lmax))
16052 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16053 (when (= cnt 0) (error "Heading not found on level %d: %s"
16054 lmax heading))
16055 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16056 lmax heading))
16057 (goto-char found)
16058 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16059 (setq end (save-excursion (org-end-of-subtree t t))))
16060 (when (org-at-heading-p)
16061 (point-marker)))))))
16062
16063 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16064 "Find node HEADING in BUFFER.
16065 Return a marker to the heading if it was found, or nil if not.
16066 If POS-ONLY is set, return just the position instead of a marker.
16067
16068 The heading text must match exact, but it may have a TODO keyword,
16069 a priority cookie and tags in the standard locations."
16070 (with-current-buffer (or buffer (current-buffer))
16071 (save-excursion
16072 (save-restriction
16073 (widen)
16074 (goto-char (point-min))
16075 (let (case-fold-search)
16076 (if (re-search-forward
16077 (format org-complex-heading-regexp-format
16078 (regexp-quote heading)) nil t)
16079 (if pos-only
16080 (match-beginning 0)
16081 (move-marker (make-marker) (match-beginning 0)))))))))
16082
16083 (defun org-find-exact-heading-in-directory (heading &optional dir)
16084 "Find Org node headline HEADING in all .org files in directory DIR.
16085 When the target headline is found, return a marker to this location."
16086 (let ((files (directory-files (or dir default-directory)
16087 nil "\\`[^.#].*\\.org\\'"))
16088 file visiting m buffer)
16089 (catch 'found
16090 (dolist (file files)
16091 (message "trying %s" file)
16092 (setq visiting (org-find-base-buffer-visiting file))
16093 (setq buffer (or visiting (find-file-noselect file)))
16094 (setq m (org-find-exact-headline-in-buffer
16095 heading buffer))
16096 (when (and (not m) (not visiting)) (kill-buffer buffer))
16097 (and m (throw 'found m))))))
16098
16099 (defun org-find-entry-with-id (ident)
16100 "Locate the entry that contains the ID property with exact value IDENT.
16101 IDENT can be a string, a symbol or a number, this function will search for
16102 the string representation of it.
16103 Return the position where this entry starts, or nil if there is no such entry."
16104 (interactive "sID: ")
16105 (let ((id (cond
16106 ((stringp ident) ident)
16107 ((symbol-name ident) (symbol-name ident))
16108 ((numberp ident) (number-to-string ident))
16109 (t (error "IDENT %s must be a string, symbol or number" ident))))
16110 (case-fold-search nil))
16111 (save-excursion
16112 (save-restriction
16113 (widen)
16114 (goto-char (point-min))
16115 (when (re-search-forward
16116 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16117 nil t)
16118 (org-back-to-heading t)
16119 (point))))))
16120
16121 ;;;; Timestamps
16122
16123 (defvar org-last-changed-timestamp nil)
16124 (defvar org-last-inserted-timestamp nil
16125 "The last time stamp inserted with `org-insert-time-stamp'.")
16126 (defvar org-ts-what) ; dynamically scoped parameter
16127
16128 (defun org-time-stamp (arg &optional inactive)
16129 "Prompt for a date/time and insert a time stamp.
16130 If the user specifies a time like HH:MM or if this command is
16131 called with at least one prefix argument, the time stamp contains
16132 the date and the time. Otherwise, only the date is be included.
16133
16134 All parts of a date not specified by the user is filled in from
16135 the current date/time. So if you just press return without
16136 typing anything, the time stamp will represent the current
16137 date/time.
16138
16139 If there is already a timestamp at the cursor, it will be
16140 modified.
16141
16142 With two universal prefix arguments, insert an active timestamp
16143 with the current time without prompting the user.
16144
16145 When called from lisp, the timestamp is inactive if INACTIVE is
16146 non-nil."
16147 (interactive "P")
16148 (let* ((ts nil)
16149 (default-time
16150 ;; Default time is either today, or, when entering a range,
16151 ;; the range start.
16152 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16153 (save-excursion
16154 (re-search-backward
16155 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16156 (- (point) 20) t)))
16157 (apply 'encode-time (org-parse-time-string (match-string 1)))
16158 (current-time)))
16159 (default-input (and ts (org-get-compact-tod ts)))
16160 (repeater (save-excursion
16161 (save-match-data
16162 (beginning-of-line)
16163 (when (re-search-forward
16164 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16165 (save-excursion (progn (end-of-line) (point))) t)
16166 (match-string 0)))))
16167 org-time-was-given org-end-time-was-given time)
16168 (cond
16169 ((and (org-at-timestamp-p t)
16170 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16171 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16172 (insert "--")
16173 (setq time (let ((this-command this-command))
16174 (org-read-date arg 'totime nil nil
16175 default-time default-input inactive)))
16176 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16177 ((org-at-timestamp-p t)
16178 (setq time (let ((this-command this-command))
16179 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16180 (when (org-at-timestamp-p t) ; just to get the match data
16181 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16182 (replace-match "")
16183 (setq org-last-changed-timestamp
16184 (org-insert-time-stamp
16185 time (or org-time-was-given arg)
16186 inactive nil nil (list org-end-time-was-given)))
16187 (when repeater (goto-char (1- (point))) (insert " " repeater)
16188 (setq org-last-changed-timestamp
16189 (concat (substring org-last-inserted-timestamp 0 -1)
16190 " " repeater ">"))))
16191 (message "Timestamp updated"))
16192 ((equal arg '(16))
16193 (org-insert-time-stamp (current-time) t inactive))
16194 (t
16195 (setq time (let ((this-command this-command))
16196 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16197 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16198 nil nil (list org-end-time-was-given))))))
16199
16200 ;; FIXME: can we use this for something else, like computing time differences?
16201 (defun org-get-compact-tod (s)
16202 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16203 (let* ((t1 (match-string 1 s))
16204 (h1 (string-to-number (match-string 2 s)))
16205 (m1 (string-to-number (match-string 3 s)))
16206 (t2 (and (match-end 4) (match-string 5 s)))
16207 (h2 (and t2 (string-to-number (match-string 6 s))))
16208 (m2 (and t2 (string-to-number (match-string 7 s))))
16209 dh dm)
16210 (if (not t2)
16211 t1
16212 (setq dh (- h2 h1) dm (- m2 m1))
16213 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16214 (concat t1 "+" (number-to-string dh)
16215 (and (/= 0 dm) (format ":%02d" dm)))))))
16216
16217 (defun org-time-stamp-inactive (&optional arg)
16218 "Insert an inactive time stamp.
16219 An inactive time stamp is enclosed in square brackets instead of angle
16220 brackets. It is inactive in the sense that it does not trigger agenda entries,
16221 does not link to the calendar and cannot be changed with the S-cursor keys.
16222 So these are more for recording a certain time/date."
16223 (interactive "P")
16224 (org-time-stamp arg 'inactive))
16225
16226 (defvar org-date-ovl (make-overlay 1 1))
16227 (overlay-put org-date-ovl 'face 'org-date-selected)
16228 (org-detach-overlay org-date-ovl)
16229
16230 (defvar org-ans1) ; dynamically scoped parameter
16231 (defvar org-ans2) ; dynamically scoped parameter
16232
16233 (defvar org-plain-time-of-day-regexp) ; defined below
16234
16235 (defvar org-overriding-default-time nil) ; dynamically scoped
16236 (defvar org-read-date-overlay nil)
16237 (defvar org-dcst nil) ; dynamically scoped
16238 (defvar org-read-date-history nil)
16239 (defvar org-read-date-final-answer nil)
16240 (defvar org-read-date-analyze-futurep nil)
16241 (defvar org-read-date-analyze-forced-year nil)
16242 (defvar org-read-date-inactive)
16243
16244 (defvar org-read-date-minibuffer-local-map
16245 (let* ((org-replace-disputed-keys nil)
16246 (map (make-sparse-keymap)))
16247 (set-keymap-parent map minibuffer-local-map)
16248 (org-defkey map (kbd ".")
16249 (lambda () (interactive)
16250 ;; Are we at the beginning of the prompt?
16251 (if (looking-back "^[^:]+: ")
16252 (org-eval-in-calendar '(calendar-goto-today))
16253 (insert "."))))
16254 (org-defkey map (kbd "C-.")
16255 (lambda () (interactive)
16256 (org-eval-in-calendar '(calendar-goto-today))))
16257 (org-defkey map [(meta shift left)]
16258 (lambda () (interactive)
16259 (org-eval-in-calendar '(calendar-backward-month 1))))
16260 (org-defkey map [(meta shift right)]
16261 (lambda () (interactive)
16262 (org-eval-in-calendar '(calendar-forward-month 1))))
16263 (org-defkey map [(meta shift up)]
16264 (lambda () (interactive)
16265 (org-eval-in-calendar '(calendar-backward-year 1))))
16266 (org-defkey map [(meta shift down)]
16267 (lambda () (interactive)
16268 (org-eval-in-calendar '(calendar-forward-year 1))))
16269 (org-defkey map [?\e (shift left)]
16270 (lambda () (interactive)
16271 (org-eval-in-calendar '(calendar-backward-month 1))))
16272 (org-defkey map [?\e (shift right)]
16273 (lambda () (interactive)
16274 (org-eval-in-calendar '(calendar-forward-month 1))))
16275 (org-defkey map [?\e (shift up)]
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(calendar-backward-year 1))))
16278 (org-defkey map [?\e (shift down)]
16279 (lambda () (interactive)
16280 (org-eval-in-calendar '(calendar-forward-year 1))))
16281 (org-defkey map [(shift up)]
16282 (lambda () (interactive)
16283 (org-eval-in-calendar '(calendar-backward-week 1))))
16284 (org-defkey map [(shift down)]
16285 (lambda () (interactive)
16286 (org-eval-in-calendar '(calendar-forward-week 1))))
16287 (org-defkey map [(shift left)]
16288 (lambda () (interactive)
16289 (org-eval-in-calendar '(calendar-backward-day 1))))
16290 (org-defkey map [(shift right)]
16291 (lambda () (interactive)
16292 (org-eval-in-calendar '(calendar-forward-day 1))))
16293 (org-defkey map "!"
16294 (lambda () (interactive)
16295 (org-eval-in-calendar '(diary-view-entries))
16296 (message "")))
16297 (org-defkey map ">"
16298 (lambda () (interactive)
16299 (org-eval-in-calendar '(scroll-calendar-left 1))))
16300 (org-defkey map "<"
16301 (lambda () (interactive)
16302 (org-eval-in-calendar '(scroll-calendar-right 1))))
16303 (org-defkey map "\C-v"
16304 (lambda () (interactive)
16305 (org-eval-in-calendar
16306 '(calendar-scroll-left-three-months 1))))
16307 (org-defkey map "\M-v"
16308 (lambda () (interactive)
16309 (org-eval-in-calendar
16310 '(calendar-scroll-right-three-months 1))))
16311 map)
16312 "Keymap for minibuffer commands when using `org-read-date'.")
16313
16314 (defvar org-def)
16315 (defvar org-defdecode)
16316 (defvar org-with-time)
16317
16318 (defun org-read-date (&optional org-with-time to-time from-string prompt
16319 default-time default-input inactive)
16320 "Read a date, possibly a time, and make things smooth for the user.
16321 The prompt will suggest to enter an ISO date, but you can also enter anything
16322 which will at least partially be understood by `parse-time-string'.
16323 Unrecognized parts of the date will default to the current day, month, year,
16324 hour and minute. If this command is called to replace a timestamp at point,
16325 or to enter the second timestamp of a range, the default time is taken
16326 from the existing stamp. Furthermore, the command prefers the future,
16327 so if you are giving a date where the year is not given, and the day-month
16328 combination is already past in the current year, it will assume you
16329 mean next year. For details, see the manual. A few examples:
16330
16331 3-2-5 --> 2003-02-05
16332 feb 15 --> currentyear-02-15
16333 2/15 --> currentyear-02-15
16334 sep 12 9 --> 2009-09-12
16335 12:45 --> today 12:45
16336 22 sept 0:34 --> currentyear-09-22 0:34
16337 12 --> currentyear-currentmonth-12
16338 Fri --> nearest Friday after today
16339 -Tue --> last Tuesday
16340 etc.
16341
16342 Furthermore you can specify a relative date by giving, as the *first* thing
16343 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16344 change in days weeks, months, years.
16345 With a single plus or minus, the date is relative to today. With a double
16346 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16347 +4d --> four days from today
16348 +4 --> same as above
16349 +2w --> two weeks from today
16350 ++5 --> five days from default date
16351
16352 The function understands only English month and weekday abbreviations.
16353
16354 While prompting, a calendar is popped up - you can also select the
16355 date with the mouse (button 1). The calendar shows a period of three
16356 months. To scroll it to other months, use the keys `>' and `<'.
16357 If you don't like the calendar, turn it off with
16358 (setq org-read-date-popup-calendar nil)
16359
16360 With optional argument TO-TIME, the date will immediately be converted
16361 to an internal time.
16362 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16363 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16364 still enter a time, and this function will inform the calling routine
16365 about this change. The calling routine may then choose to change the
16366 format used to insert the time stamp into the buffer to include the time.
16367 With optional argument FROM-STRING, read from this string instead from
16368 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16369 the time/date that is used for everything that is not specified by the
16370 user."
16371 (require 'parse-time)
16372 (let* ((org-time-stamp-rounding-minutes
16373 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16374 (org-dcst org-display-custom-times)
16375 (ct (org-current-time))
16376 (org-def (or org-overriding-default-time default-time ct))
16377 (org-defdecode (decode-time org-def))
16378 (dummy (progn
16379 (when (< (nth 2 org-defdecode) org-extend-today-until)
16380 (setcar (nthcdr 2 org-defdecode) -1)
16381 (setcar (nthcdr 1 org-defdecode) 59)
16382 (setq org-def (apply 'encode-time org-defdecode)
16383 org-defdecode (decode-time org-def)))))
16384 (mouse-autoselect-window nil) ; Don't let the mouse jump
16385 (calendar-frame-setup nil)
16386 (calendar-setup nil)
16387 (calendar-move-hook nil)
16388 (calendar-view-diary-initially-flag nil)
16389 (calendar-view-holidays-initially-flag nil)
16390 (timestr (format-time-string
16391 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16392 (prompt (concat (if prompt (concat prompt " ") "")
16393 (format "Date+time [%s]: " timestr)))
16394 ans (org-ans0 "") org-ans1 org-ans2 final)
16395
16396 (cond
16397 (from-string (setq ans from-string))
16398 (org-read-date-popup-calendar
16399 (save-excursion
16400 (save-window-excursion
16401 (calendar)
16402 (org-eval-in-calendar '(setq cursor-type nil) t)
16403 (unwind-protect
16404 (progn
16405 (calendar-forward-day (- (time-to-days org-def)
16406 (calendar-absolute-from-gregorian
16407 (calendar-current-date))))
16408 (org-eval-in-calendar nil t)
16409 (let* ((old-map (current-local-map))
16410 (map (copy-keymap calendar-mode-map))
16411 (minibuffer-local-map
16412 (copy-keymap org-read-date-minibuffer-local-map)))
16413 (org-defkey map (kbd "RET") 'org-calendar-select)
16414 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16415 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16416 (unwind-protect
16417 (progn
16418 (use-local-map map)
16419 (setq org-read-date-inactive inactive)
16420 (add-hook 'post-command-hook 'org-read-date-display)
16421 (setq org-ans0 (read-string prompt default-input
16422 'org-read-date-history nil))
16423 ;; org-ans0: from prompt
16424 ;; org-ans1: from mouse click
16425 ;; org-ans2: from calendar motion
16426 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16427 (remove-hook 'post-command-hook 'org-read-date-display)
16428 (use-local-map old-map)
16429 (when org-read-date-overlay
16430 (delete-overlay org-read-date-overlay)
16431 (setq org-read-date-overlay nil)))))
16432 (bury-buffer "*Calendar*")))))
16433
16434 (t ; Naked prompt only
16435 (unwind-protect
16436 (setq ans (read-string prompt default-input
16437 'org-read-date-history timestr))
16438 (when org-read-date-overlay
16439 (delete-overlay org-read-date-overlay)
16440 (setq org-read-date-overlay nil)))))
16441
16442 (setq final (org-read-date-analyze ans org-def org-defdecode))
16443
16444 (when org-read-date-analyze-forced-year
16445 (message "Year was forced into %s"
16446 (if org-read-date-force-compatible-dates
16447 "compatible range (1970-2037)"
16448 "range representable on this machine"))
16449 (ding))
16450
16451 ;; One round trip to get rid of 34th of August and stuff like that....
16452 (setq final (decode-time (apply 'encode-time final)))
16453
16454 (setq org-read-date-final-answer ans)
16455
16456 (if to-time
16457 (apply 'encode-time final)
16458 (if (and (boundp 'org-time-was-given) org-time-was-given)
16459 (format "%04d-%02d-%02d %02d:%02d"
16460 (nth 5 final) (nth 4 final) (nth 3 final)
16461 (nth 2 final) (nth 1 final))
16462 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16463
16464 (defun org-read-date-display ()
16465 "Display the current date prompt interpretation in the minibuffer."
16466 (when org-read-date-display-live
16467 (when org-read-date-overlay
16468 (delete-overlay org-read-date-overlay))
16469 (when (minibufferp (current-buffer))
16470 (save-excursion
16471 (end-of-line 1)
16472 (while (not (equal (buffer-substring
16473 (max (point-min) (- (point) 4)) (point))
16474 " "))
16475 (insert " ")))
16476 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16477 " " (or org-ans1 org-ans2)))
16478 (org-end-time-was-given nil)
16479 (f (org-read-date-analyze ans org-def org-defdecode))
16480 (fmts (if org-dcst
16481 org-time-stamp-custom-formats
16482 org-time-stamp-formats))
16483 (fmt (if (or org-with-time
16484 (and (boundp 'org-time-was-given) org-time-was-given))
16485 (cdr fmts)
16486 (car fmts)))
16487 (txt (format-time-string fmt (apply 'encode-time f)))
16488 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16489 (txt (concat "=> " txt)))
16490 (when (and org-end-time-was-given
16491 (string-match org-plain-time-of-day-regexp txt))
16492 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16493 org-end-time-was-given
16494 (substring txt (match-end 0)))))
16495 (when org-read-date-analyze-futurep
16496 (setq txt (concat txt " (=>F)")))
16497 (setq org-read-date-overlay
16498 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16499 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16500
16501 (defun org-read-date-analyze (ans org-def org-defdecode)
16502 "Analyze the combined answer of the date prompt."
16503 ;; FIXME: cleanup and comment
16504 (let ((nowdecode (decode-time))
16505 delta deltan deltaw deltadef year month day
16506 hour minute second wday pm h2 m2 tl wday1
16507 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16508 (setq org-read-date-analyze-futurep nil
16509 org-read-date-analyze-forced-year nil)
16510 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16511 (setq ans "+0"))
16512
16513 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16514 (setq ans (replace-match "" t t ans)
16515 deltan (car delta)
16516 deltaw (nth 1 delta)
16517 deltadef (nth 2 delta)))
16518
16519 ;; Check if there is an iso week date in there. If yes, store the
16520 ;; info and postpone interpreting it until the rest of the parsing
16521 ;; is done.
16522 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16523 (setq iso-year (if (match-end 1)
16524 (org-small-year-to-year
16525 (string-to-number (match-string 1 ans))))
16526 iso-weekday (if (match-end 3)
16527 (string-to-number (match-string 3 ans)))
16528 iso-week (string-to-number (match-string 2 ans)))
16529 (setq ans (replace-match "" t t ans)))
16530
16531 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16532 (when (string-match
16533 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16534 (setq year (if (match-end 2)
16535 (string-to-number (match-string 2 ans))
16536 (progn (setq kill-year t)
16537 (string-to-number (format-time-string "%Y"))))
16538 month (string-to-number (match-string 3 ans))
16539 day (string-to-number (match-string 4 ans)))
16540 (if (< year 100) (setq year (+ 2000 year)))
16541 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16542 t nil ans)))
16543
16544 ;; Help matching dotted european dates
16545 (when (string-match
16546 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16547 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16548 (setq kill-year t)
16549 (string-to-number (format-time-string "%Y")))
16550 day (string-to-number (match-string 1 ans))
16551 month (string-to-number (match-string 2 ans))
16552 ans (replace-match (format "%04d-%02d-%02d" year month day)
16553 t nil ans)))
16554
16555 ;; Help matching american dates, like 5/30 or 5/30/7
16556 (when (string-match
16557 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16558 (setq year (if (match-end 4)
16559 (string-to-number (match-string 4 ans))
16560 (progn (setq kill-year t)
16561 (string-to-number (format-time-string "%Y"))))
16562 month (string-to-number (match-string 1 ans))
16563 day (string-to-number (match-string 2 ans)))
16564 (if (< year 100) (setq year (+ 2000 year)))
16565 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16566 t nil ans)))
16567 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16568 ;; If there is a time with am/pm, and *no* time without it, we convert
16569 ;; so that matching will be successful.
16570 (loop for i from 1 to 2 do ; twice, for end time as well
16571 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16572 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16573 (setq hour (string-to-number (match-string 1 ans))
16574 minute (if (match-end 3)
16575 (string-to-number (match-string 3 ans))
16576 0)
16577 pm (equal ?p
16578 (string-to-char (downcase (match-string 4 ans)))))
16579 (if (and (= hour 12) (not pm))
16580 (setq hour 0)
16581 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16582 (setq ans (replace-match (format "%02d:%02d" hour minute)
16583 t t ans))))
16584
16585 ;; Check if a time range is given as a duration
16586 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16587 (setq hour (string-to-number (match-string 1 ans))
16588 h2 (+ hour (string-to-number (match-string 3 ans)))
16589 minute (string-to-number (match-string 2 ans))
16590 m2 (+ minute (if (match-end 5) (string-to-number
16591 (match-string 5 ans))0)))
16592 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16593 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16594 t t ans)))
16595
16596 ;; Check if there is a time range
16597 (when (boundp 'org-end-time-was-given)
16598 (setq org-time-was-given nil)
16599 (when (and (string-match org-plain-time-of-day-regexp ans)
16600 (match-end 8))
16601 (setq org-end-time-was-given (match-string 8 ans))
16602 (setq ans (concat (substring ans 0 (match-beginning 7))
16603 (substring ans (match-end 7))))))
16604
16605 (setq tl (parse-time-string ans)
16606 day (or (nth 3 tl) (nth 3 org-defdecode))
16607 month (or (nth 4 tl)
16608 (if (and org-read-date-prefer-future
16609 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16610 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16611 (nth 4 org-defdecode)))
16612 year (or (and (not kill-year) (nth 5 tl))
16613 (if (and org-read-date-prefer-future
16614 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16615 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16616 (nth 5 org-defdecode)))
16617 hour (or (nth 2 tl) (nth 2 org-defdecode))
16618 minute (or (nth 1 tl) (nth 1 org-defdecode))
16619 second (or (nth 0 tl) 0)
16620 wday (nth 6 tl))
16621
16622 (when (and (eq org-read-date-prefer-future 'time)
16623 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16624 (equal day (nth 3 nowdecode))
16625 (equal month (nth 4 nowdecode))
16626 (equal year (nth 5 nowdecode))
16627 (nth 2 tl)
16628 (or (< (nth 2 tl) (nth 2 nowdecode))
16629 (and (= (nth 2 tl) (nth 2 nowdecode))
16630 (nth 1 tl)
16631 (< (nth 1 tl) (nth 1 nowdecode)))))
16632 (setq day (1+ day)
16633 futurep t))
16634
16635 ;; Special date definitions below
16636 (cond
16637 (iso-week
16638 ;; There was an iso week
16639 (require 'cal-iso)
16640 (setq futurep nil)
16641 (setq year (or iso-year year)
16642 day (or iso-weekday wday 1)
16643 wday nil ; to make sure that the trigger below does not match
16644 iso-date (calendar-gregorian-from-absolute
16645 (calendar-absolute-from-iso
16646 (list iso-week day year))))
16647 ; FIXME: Should we also push ISO weeks into the future?
16648 ; (when (and org-read-date-prefer-future
16649 ; (not iso-year)
16650 ; (< (calendar-absolute-from-gregorian iso-date)
16651 ; (time-to-days (current-time))))
16652 ; (setq year (1+ year)
16653 ; iso-date (calendar-gregorian-from-absolute
16654 ; (calendar-absolute-from-iso
16655 ; (list iso-week day year)))))
16656 (setq month (car iso-date)
16657 year (nth 2 iso-date)
16658 day (nth 1 iso-date)))
16659 (deltan
16660 (setq futurep nil)
16661 (unless deltadef
16662 (let ((now (decode-time)))
16663 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16664 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16665 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16666 ((equal deltaw "m") (setq month (+ month deltan)))
16667 ((equal deltaw "y") (setq year (+ year deltan)))))
16668 ((and wday (not (nth 3 tl)))
16669 ;; Weekday was given, but no day, so pick that day in the week
16670 ;; on or after the derived date.
16671 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16672 (unless (equal wday wday1)
16673 (setq day (+ day (% (- wday wday1 -7) 7))))))
16674 (if (and (boundp 'org-time-was-given)
16675 (nth 2 tl))
16676 (setq org-time-was-given t))
16677 (if (< year 100) (setq year (+ 2000 year)))
16678 ;; Check of the date is representable
16679 (if org-read-date-force-compatible-dates
16680 (progn
16681 (if (< year 1970)
16682 (setq year 1970 org-read-date-analyze-forced-year t))
16683 (if (> year 2037)
16684 (setq year 2037 org-read-date-analyze-forced-year t)))
16685 (condition-case nil
16686 (ignore (encode-time second minute hour day month year))
16687 (error
16688 (setq year (nth 5 org-defdecode))
16689 (setq org-read-date-analyze-forced-year t))))
16690 (setq org-read-date-analyze-futurep futurep)
16691 (list second minute hour day month year)))
16692
16693 (defvar parse-time-weekdays)
16694 (defun org-read-date-get-relative (s today default)
16695 "Check string S for special relative date string.
16696 TODAY and DEFAULT are internal times, for today and for a default.
16697 Return shift list (N what def-flag)
16698 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16699 N is the number of WHATs to shift.
16700 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16701 the DEFAULT date rather than TODAY."
16702 (require 'parse-time)
16703 (when (and
16704 (string-match
16705 (concat
16706 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16707 "\\([0-9]+\\)?"
16708 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16709 "\\([ \t]\\|$\\)") s)
16710 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16711 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16712 (string-to-char (substring (match-string 1 s) -1))
16713 ?+))
16714 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16715 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16716 (what (if (match-end 3) (match-string 3 s) "d"))
16717 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16718 (date (if rel default today))
16719 (wday (nth 6 (decode-time date)))
16720 delta)
16721 (if wday1
16722 (progn
16723 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16724 (if (= delta 0) (setq delta 7))
16725 (if (= dir ?-)
16726 (progn
16727 (setq delta (- delta 7))
16728 (if (= delta 0) (setq delta -7))))
16729 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16730 (list delta "d" rel))
16731 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16732
16733 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16734 "Turn a user-specified date into the internal representation.
16735 The internal representation needed by the calendar is (month day year).
16736 This is a wrapper to handle the brain-dead convention in calendar that
16737 user function argument order change dependent on argument order."
16738 (if (boundp 'calendar-date-style)
16739 (cond
16740 ((eq calendar-date-style 'american)
16741 (list arg1 arg2 arg3))
16742 ((eq calendar-date-style 'european)
16743 (list arg2 arg1 arg3))
16744 ((eq calendar-date-style 'iso)
16745 (list arg2 arg3 arg1)))
16746 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16747 (if (org-bound-and-true-p european-calendar-style)
16748 (list arg2 arg1 arg3)
16749 (list arg1 arg2 arg3)))))
16750
16751 (defun org-eval-in-calendar (form &optional keepdate)
16752 "Eval FORM in the calendar window and return to current window.
16753 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16754 otherwise stick to the current value of `org-ans2'."
16755 (let ((sf (selected-frame))
16756 (sw (selected-window)))
16757 (select-window (get-buffer-window "*Calendar*" t))
16758 (eval form)
16759 (when (and (not keepdate) (calendar-cursor-to-date))
16760 (let* ((date (calendar-cursor-to-date))
16761 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16762 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16763 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16764 (select-window sw)
16765 (org-select-frame-set-input-focus sf)))
16766
16767 (defun org-calendar-select ()
16768 "Return to `org-read-date' with the date currently selected.
16769 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16770 (interactive)
16771 (when (calendar-cursor-to-date)
16772 (let* ((date (calendar-cursor-to-date))
16773 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16774 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16775 (if (active-minibuffer-window) (exit-minibuffer))))
16776
16777 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16778 "Insert a date stamp for the date given by the internal TIME.
16779 WITH-HM means use the stamp format that includes the time of the day.
16780 INACTIVE means use square brackets instead of angular ones, so that the
16781 stamp will not contribute to the agenda.
16782 PRE and POST are optional strings to be inserted before and after the
16783 stamp.
16784 The command returns the inserted time stamp."
16785 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16786 stamp)
16787 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16788 (insert-before-markers (or pre ""))
16789 (when (listp extra)
16790 (setq extra (car extra))
16791 (if (and (stringp extra)
16792 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16793 (setq extra (format "-%02d:%02d"
16794 (string-to-number (match-string 1 extra))
16795 (string-to-number (match-string 2 extra))))
16796 (setq extra nil)))
16797 (when extra
16798 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16799 (insert-before-markers (setq stamp (format-time-string fmt time)))
16800 (insert-before-markers (or post ""))
16801 (setq org-last-inserted-timestamp stamp)))
16802
16803 (defun org-toggle-time-stamp-overlays ()
16804 "Toggle the use of custom time stamp formats."
16805 (interactive)
16806 (setq org-display-custom-times (not org-display-custom-times))
16807 (unless org-display-custom-times
16808 (let ((p (point-min)) (bmp (buffer-modified-p)))
16809 (while (setq p (next-single-property-change p 'display))
16810 (if (and (get-text-property p 'display)
16811 (eq (get-text-property p 'face) 'org-date))
16812 (remove-text-properties
16813 p (setq p (next-single-property-change p 'display))
16814 '(display t))))
16815 (set-buffer-modified-p bmp)))
16816 (if (featurep 'xemacs)
16817 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16818 (org-restart-font-lock)
16819 (setq org-table-may-need-update t)
16820 (if org-display-custom-times
16821 (message "Time stamps are overlaid with custom format")
16822 (message "Time stamp overlays removed")))
16823
16824 (defun org-display-custom-time (beg end)
16825 "Overlay modified time stamp format over timestamp between BEG and END."
16826 (let* ((ts (buffer-substring beg end))
16827 t1 w1 with-hm tf time str w2 (off 0))
16828 (save-match-data
16829 (setq t1 (org-parse-time-string ts t))
16830 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16831 (setq off (- (match-end 0) (match-beginning 0)))))
16832 (setq end (- end off))
16833 (setq w1 (- end beg)
16834 with-hm (and (nth 1 t1) (nth 2 t1))
16835 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16836 time (org-fix-decoded-time t1)
16837 str (org-add-props
16838 (format-time-string
16839 (substring tf 1 -1) (apply 'encode-time time))
16840 nil 'mouse-face 'highlight)
16841 w2 (length str))
16842 (if (not (= w2 w1))
16843 (add-text-properties (1+ beg) (+ 2 beg)
16844 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16845 (if (featurep 'xemacs)
16846 (progn
16847 (put-text-property beg end 'invisible t)
16848 (put-text-property beg end 'end-glyph (make-glyph str)))
16849 (put-text-property beg end 'display str))))
16850
16851 (defun org-translate-time (string)
16852 "Translate all timestamps in STRING to custom format.
16853 But do this only if the variable `org-display-custom-times' is set."
16854 (when org-display-custom-times
16855 (save-match-data
16856 (let* ((start 0)
16857 (re org-ts-regexp-both)
16858 t1 with-hm inactive tf time str beg end)
16859 (while (setq start (string-match re string start))
16860 (setq beg (match-beginning 0)
16861 end (match-end 0)
16862 t1 (save-match-data
16863 (org-parse-time-string (substring string beg end) t))
16864 with-hm (and (nth 1 t1) (nth 2 t1))
16865 inactive (equal (substring string beg (1+ beg)) "[")
16866 tf (funcall (if with-hm 'cdr 'car)
16867 org-time-stamp-custom-formats)
16868 time (org-fix-decoded-time t1)
16869 str (format-time-string
16870 (concat
16871 (if inactive "[" "<") (substring tf 1 -1)
16872 (if inactive "]" ">"))
16873 (apply 'encode-time time))
16874 string (replace-match str t t string)
16875 start (+ start (length str)))))))
16876 string)
16877
16878 (defun org-fix-decoded-time (time)
16879 "Set 0 instead of nil for the first 6 elements of time.
16880 Don't touch the rest."
16881 (let ((n 0))
16882 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16883
16884 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16885
16886 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16887 "Difference between TIMESTAMP-STRING and now in days.
16888 If SECONDS is non-nil, return the difference in seconds."
16889 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16890 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16891 (funcall fdiff (current-time)))))
16892
16893 (defun org-deadline-close (timestamp-string &optional ndays)
16894 "Is the time in TIMESTAMP-STRING close to the current date?"
16895 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16896 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16897 (not (org-entry-is-done-p))))
16898
16899 (defun org-get-wdays (ts &optional delay zero-delay)
16900 "Get the deadline lead time appropriate for timestring TS.
16901 When DELAY is non-nil, get the delay time for scheduled items
16902 instead of the deadline lead time. When ZERO-DELAY is non-nil
16903 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16904 don't try to find the delay cookie in the scheduled timestamp."
16905 (let ((tv (if delay org-scheduled-delay-days
16906 org-deadline-warning-days)))
16907 (cond
16908 ((or (and delay (< tv 0))
16909 (and delay zero-delay (<= tv 0))
16910 (and (not delay) (<= tv 0)))
16911 ;; Enforce this value no matter what
16912 (- tv))
16913 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16914 ;; lead time is specified.
16915 (floor (* (string-to-number (match-string 1 ts))
16916 (cdr (assoc (match-string 2 ts)
16917 '(("d" . 1) ("w" . 7)
16918 ("m" . 30.4) ("y" . 365.25)
16919 ("h" . 0.041667)))))))
16920 ;; go for the default.
16921 (t tv))))
16922
16923 (defun org-calendar-select-mouse (ev)
16924 "Return to `org-read-date' with the date currently selected.
16925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16926 (interactive "e")
16927 (mouse-set-point ev)
16928 (when (calendar-cursor-to-date)
16929 (let* ((date (calendar-cursor-to-date))
16930 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16931 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16932 (if (active-minibuffer-window) (exit-minibuffer))))
16933
16934 (defun org-check-deadlines (ndays)
16935 "Check if there are any deadlines due or past due.
16936 A deadline is considered due if it happens within `org-deadline-warning-days'
16937 days from today's date. If the deadline appears in an entry marked DONE,
16938 it is not shown. The prefix arg NDAYS can be used to test that many
16939 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16940 (interactive "P")
16941 (let* ((org-warn-days
16942 (cond
16943 ((equal ndays '(4)) 100000)
16944 (ndays (prefix-numeric-value ndays))
16945 (t (abs org-deadline-warning-days))))
16946 (case-fold-search nil)
16947 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16948 (callback
16949 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16950
16951 (message "%d deadlines past-due or due within %d days"
16952 (org-occur regexp nil callback)
16953 org-warn-days)))
16954
16955 (defsubst org-re-timestamp (type)
16956 "Return a regexp for timestamp TYPE.
16957 Allowed values for TYPE are:
16958
16959 all: all timestamps
16960 active: only active timestamps (<...>)
16961 inactive: only inactive timestamps ([...])
16962 scheduled: only scheduled timestamps
16963 deadline: only deadline timestamps
16964 closed: only closed time-stamps
16965
16966 When TYPE is nil, fall back on returning a regexp that matches
16967 both scheduled and deadline timestamps."
16968 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>\r\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16969 ((eq type 'active) org-ts-regexp)
16970 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]")
16971 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16972 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16973 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"))
16974 ((eq type 'scheduled-or-deadline)
16975 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16976
16977 (defun org-check-before-date (date)
16978 "Check if there are deadlines or scheduled entries before DATE."
16979 (interactive (list (org-read-date)))
16980 (let ((case-fold-search nil)
16981 (regexp (org-re-timestamp org-ts-type))
16982 (callback
16983 (lambda () (time-less-p
16984 (org-time-string-to-time (match-string 1))
16985 (org-time-string-to-time date)))))
16986 (message "%d entries before %s"
16987 (org-occur regexp nil callback) date)))
16988
16989 (defun org-check-after-date (date)
16990 "Check if there are deadlines or scheduled entries after DATE."
16991 (interactive (list (org-read-date)))
16992 (let ((case-fold-search nil)
16993 (regexp (org-re-timestamp org-ts-type))
16994 (callback
16995 (lambda () (not
16996 (time-less-p
16997 (org-time-string-to-time (match-string 1))
16998 (org-time-string-to-time date))))))
16999 (message "%d entries after %s"
17000 (org-occur regexp nil callback) date)))
17001
17002 (defun org-check-dates-range (start-date end-date)
17003 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17004 (interactive (list (org-read-date nil nil nil "Range starts")
17005 (org-read-date nil nil nil "Range end")))
17006 (let ((case-fold-search nil)
17007 (regexp (org-re-timestamp org-ts-type))
17008 (callback
17009 (lambda ()
17010 (let ((match (match-string 1)))
17011 (and
17012 (not (time-less-p
17013 (org-time-string-to-time match)
17014 (org-time-string-to-time start-date)))
17015 (time-less-p
17016 (org-time-string-to-time match)
17017 (org-time-string-to-time end-date)))))))
17018 (message "%d entries between %s and %s"
17019 (org-occur regexp nil callback) start-date end-date)))
17020
17021 (defun org-evaluate-time-range (&optional to-buffer)
17022 "Evaluate a time range by computing the difference between start and end.
17023 Normally the result is just printed in the echo area, but with prefix arg
17024 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17025 If the time range is actually in a table, the result is inserted into the
17026 next column.
17027 For time difference computation, a year is assumed to be exactly 365
17028 days in order to avoid rounding problems."
17029 (interactive "P")
17030 (or
17031 (org-clock-update-time-maybe)
17032 (save-excursion
17033 (unless (org-at-date-range-p t)
17034 (goto-char (point-at-bol))
17035 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17036 (if (not (org-at-date-range-p t))
17037 (user-error "Not at a time-stamp range, and none found in current line")))
17038 (let* ((ts1 (match-string 1))
17039 (ts2 (match-string 2))
17040 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17041 (match-end (match-end 0))
17042 (time1 (org-time-string-to-time ts1))
17043 (time2 (org-time-string-to-time ts2))
17044 (t1 (org-float-time time1))
17045 (t2 (org-float-time time2))
17046 (diff (abs (- t2 t1)))
17047 (negative (< (- t2 t1) 0))
17048 ;; (ys (floor (* 365 24 60 60)))
17049 (ds (* 24 60 60))
17050 (hs (* 60 60))
17051 (fy "%dy %dd %02d:%02d")
17052 (fy1 "%dy %dd")
17053 (fd "%dd %02d:%02d")
17054 (fd1 "%dd")
17055 (fh "%02d:%02d")
17056 y d h m align)
17057 (if havetime
17058 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17059 y 0
17060 d (floor (/ diff ds)) diff (mod diff ds)
17061 h (floor (/ diff hs)) diff (mod diff hs)
17062 m (floor (/ diff 60)))
17063 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17064 y 0
17065 d (floor (+ (/ diff ds) 0.5))
17066 h 0 m 0))
17067 (if (not to-buffer)
17068 (message "%s" (org-make-tdiff-string y d h m))
17069 (if (org-at-table-p)
17070 (progn
17071 (goto-char match-end)
17072 (setq align t)
17073 (and (looking-at " *|") (goto-char (match-end 0))))
17074 (goto-char match-end))
17075 (if (looking-at
17076 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17077 (replace-match ""))
17078 (if negative (insert " -"))
17079 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17080 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17081 (insert " " (format fh h m))))
17082 (if align (org-table-align))
17083 (message "Time difference inserted")))))
17084
17085 (defun org-make-tdiff-string (y d h m)
17086 (let ((fmt "")
17087 (l nil))
17088 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17089 l (push y l)))
17090 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17091 l (push d l)))
17092 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17093 l (push h l)))
17094 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17095 l (push m l)))
17096 (apply 'format fmt (nreverse l))))
17097
17098 (defun org-time-string-to-time (s &optional buffer pos)
17099 "Convert a timestamp string into internal time."
17100 (condition-case errdata
17101 (apply 'encode-time (org-parse-time-string s))
17102 (error (error "Bad timestamp `%s'%s\nError was: %s"
17103 s (if (not (and buffer pos))
17104 ""
17105 (format-message " at %d in buffer `%s'" pos buffer))
17106 (cdr errdata)))))
17107
17108 (defun org-time-string-to-seconds (s)
17109 "Convert a timestamp string to a number of seconds."
17110 (org-float-time (org-time-string-to-time s)))
17111
17112 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17113 "Convert a time stamp to an absolute day number.
17114 If there is a specifier for a cyclic time stamp, get the closest
17115 date to DAYNR.
17116 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17117 The variable `date' is bound by the calendar when this is called."
17118 (cond
17119 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17120 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17121 daynr
17122 (+ daynr 1000)))
17123 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17124 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17125 (time-to-days (current-time))) (match-string 0 s)
17126 prefer show-all))
17127 (t (time-to-days
17128 (condition-case errdata
17129 (apply 'encode-time (org-parse-time-string s))
17130 (error (error "Bad timestamp `%s'%s\nError was: %s"
17131 s (if (not (and buffer pos))
17132 ""
17133 (format-message " at %d in buffer `%s'" pos buffer))
17134 (cdr errdata))))))))
17135
17136 (defun org-days-to-iso-week (days)
17137 "Return the iso week number."
17138 (require 'cal-iso)
17139 (car (calendar-iso-from-absolute days)))
17140
17141 (defun org-small-year-to-year (year)
17142 "Convert 2-digit years into 4-digit years.
17143 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17144 The year 2000 cannot be abbreviated. Any year larger than 99
17145 is returned unchanged."
17146 (if (< year 38)
17147 (setq year (+ 2000 year))
17148 (if (< year 100)
17149 (setq year (+ 1900 year))))
17150 year)
17151
17152 (defun org-time-from-absolute (d)
17153 "Return the time corresponding to date D.
17154 D may be an absolute day number, or a calendar-type list (month day year)."
17155 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17156 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17157
17158 (defun org-calendar-holiday ()
17159 "List of holidays, for Diary display in Org-mode."
17160 (require 'holidays)
17161 (let ((hl (funcall
17162 (if (fboundp 'calendar-check-holidays)
17163 'calendar-check-holidays 'check-calendar-holidays) date)))
17164 (if hl (mapconcat 'identity hl "; "))))
17165
17166 (defun org-diary-sexp-entry (sexp entry date)
17167 "Process a SEXP diary ENTRY for DATE."
17168 (require 'diary-lib)
17169 (let ((result (if calendar-debug-sexp
17170 (let ((stack-trace-on-error t))
17171 (eval (car (read-from-string sexp))))
17172 (condition-case nil
17173 (eval (car (read-from-string sexp)))
17174 (error
17175 (beep)
17176 (message "Bad sexp at line %d in %s: %s"
17177 (org-current-line)
17178 (buffer-file-name) sexp)
17179 (sleep-for 2))))))
17180 (cond ((stringp result) (split-string result "; "))
17181 ((and (consp result)
17182 (not (consp (cdr result)))
17183 (stringp (cdr result))) (cdr result))
17184 ((and (consp result)
17185 (stringp (car result))) result)
17186 (result entry))))
17187
17188 (defun org-diary-to-ical-string (frombuf)
17189 "Get iCalendar entries from diary entries in buffer FROMBUF.
17190 This uses the icalendar.el library."
17191 (let* ((tmpdir (if (featurep 'xemacs)
17192 (temp-directory)
17193 temporary-file-directory))
17194 (tmpfile (make-temp-name
17195 (expand-file-name "orgics" tmpdir)))
17196 buf rtn b e)
17197 (with-current-buffer frombuf
17198 (icalendar-export-region (point-min) (point-max) tmpfile)
17199 (setq buf (find-buffer-visiting tmpfile))
17200 (set-buffer buf)
17201 (goto-char (point-min))
17202 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17203 (setq b (match-beginning 0)))
17204 (goto-char (point-max))
17205 (if (re-search-backward "^END:VEVENT" nil t)
17206 (setq e (match-end 0)))
17207 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17208 (kill-buffer buf)
17209 (delete-file tmpfile)
17210 rtn))
17211
17212 (defun org-closest-date (start current change prefer show-all)
17213 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17214 When PREFER is `past', return a date that is either CURRENT or past.
17215 When PREFER is `future', return a date that is either CURRENT or future.
17216 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17217 ;; Make the proper lists from the dates
17218 (catch 'exit
17219 (let ((a1 '(("h" . hour)
17220 ("d" . day)
17221 ("w" . week)
17222 ("m" . month)
17223 ("y" . year)))
17224 (shour (nth 2 (org-parse-time-string start)))
17225 dn dw sday cday n1 n2 n0
17226 d m y y1 y2 date1 date2 nmonths nm ny m2)
17227
17228 (setq start (org-date-to-gregorian start)
17229 current (org-date-to-gregorian
17230 (if show-all
17231 current
17232 (time-to-days (current-time))))
17233 sday (calendar-absolute-from-gregorian start)
17234 cday (calendar-absolute-from-gregorian current))
17235
17236 (if (<= cday sday) (throw 'exit sday))
17237
17238 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17239 (setq dn (string-to-number (match-string 1 change))
17240 dw (cdr (assoc (match-string 2 change) a1)))
17241 (user-error "Invalid change specifier: %s" change))
17242 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17243 (cond
17244 ((eq dw 'hour)
17245 (let ((missing-hours
17246 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17247 dn)))
17248 (setq n1 (if (zerop missing-hours) cday
17249 (- cday (1+ (floor (/ missing-hours 24)))))
17250 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17251 ((eq dw 'day)
17252 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17253 n2 (+ n1 dn)))
17254 ((eq dw 'year)
17255 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17256 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17257 (setq date1 (list m d y1)
17258 n1 (calendar-absolute-from-gregorian date1)
17259 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17260 n2 (calendar-absolute-from-gregorian date2)))
17261 ((eq dw 'month)
17262 ;; approx number of month between the two dates
17263 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17264 ;; How often does dn fit in there?
17265 (setq d (nth 1 start) m (car start) y (nth 2 start)
17266 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17267 m (+ m nm)
17268 ny (floor (/ m 12))
17269 y (+ y ny)
17270 m (- m (* ny 12)))
17271 (while (> m 12) (setq m (- m 12) y (1+ y)))
17272 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17273 (setq m2 (+ m dn) y2 y)
17274 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17275 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17276 (while (<= n2 cday)
17277 (setq n1 n2 m m2 y y2)
17278 (setq m2 (+ m dn) y2 y)
17279 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17280 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17281 ;; Make sure n1 is the earlier date
17282 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17283 (if show-all
17284 (cond
17285 ((eq prefer 'past) (if (= cday n2) n2 n1))
17286 ((eq prefer 'future) (if (= cday n1) n1 n2))
17287 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17288 (cond
17289 ((eq prefer 'past) (if (= cday n2) n2 n1))
17290 ((eq prefer 'future) (if (= cday n1) n1 n2))
17291 (t (if (= cday n1) n1 n2)))))))
17292
17293 (defun org-date-to-gregorian (date)
17294 "Turn any specification of DATE into a Gregorian date for the calendar."
17295 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17296 ((and (listp date) (= (length date) 3)) date)
17297 ((stringp date)
17298 (setq date (org-parse-time-string date))
17299 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17300 ((listp date)
17301 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17302
17303 (defun org-parse-time-string (s &optional nodefault)
17304 "Parse the standard Org-mode time string.
17305 This should be a lot faster than the normal `parse-time-string'.
17306 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17307 hour and minute fields will be nil if not given."
17308 (cond ((string-match org-ts-regexp0 s)
17309 (list 0
17310 (if (or (match-beginning 8) (not nodefault))
17311 (string-to-number (or (match-string 8 s) "0")))
17312 (if (or (match-beginning 7) (not nodefault))
17313 (string-to-number (or (match-string 7 s) "0")))
17314 (string-to-number (match-string 4 s))
17315 (string-to-number (match-string 3 s))
17316 (string-to-number (match-string 2 s))
17317 nil nil nil))
17318 ((string-match "^<[^>]+>$" s)
17319 (decode-time (seconds-to-time (org-matcher-time s))))
17320 (t (error "Not a standard Org-mode time string: %s" s))))
17321
17322 (defun org-timestamp-up (&optional arg)
17323 "Increase the date item at the cursor by one.
17324 If the cursor is on the year, change the year. If it is on the month,
17325 the day or the time, change that.
17326 With prefix ARG, change by that many units."
17327 (interactive "p")
17328 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17329
17330 (defun org-timestamp-down (&optional arg)
17331 "Decrease the date item at the cursor by one.
17332 If the cursor is on the year, change the year. If it is on the month,
17333 the day or the time, change that.
17334 With prefix ARG, change by that many units."
17335 (interactive "p")
17336 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17337
17338 (defun org-timestamp-up-day (&optional arg)
17339 "Increase the date in the time stamp by one day.
17340 With prefix ARG, change that many days."
17341 (interactive "p")
17342 (if (and (not (org-at-timestamp-p t))
17343 (org-at-heading-p))
17344 (org-todo 'up)
17345 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17346
17347 (defun org-timestamp-down-day (&optional arg)
17348 "Decrease the date in the time stamp by one day.
17349 With prefix ARG, change that many days."
17350 (interactive "p")
17351 (if (and (not (org-at-timestamp-p t))
17352 (org-at-heading-p))
17353 (org-todo 'down)
17354 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17355
17356 (defun org-at-timestamp-p (&optional inactive-ok)
17357 "Determine if the cursor is in or at a timestamp."
17358 (interactive)
17359 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17360 (pos (point))
17361 (ans (or (looking-at tsr)
17362 (save-excursion
17363 (skip-chars-backward "^[<\n\r\t")
17364 (if (> (point) (point-min)) (backward-char 1))
17365 (and (looking-at tsr)
17366 (> (- (match-end 0) pos) -1))))))
17367 (and ans
17368 (boundp 'org-ts-what)
17369 (setq org-ts-what
17370 (cond
17371 ((= pos (match-beginning 0)) 'bracket)
17372 ;; Point is considered to be "on the bracket" whether
17373 ;; it's really on it or right after it.
17374 ((= pos (1- (match-end 0))) 'bracket)
17375 ((= pos (match-end 0)) 'after)
17376 ((org-pos-in-match-range pos 2) 'year)
17377 ((org-pos-in-match-range pos 3) 'month)
17378 ((org-pos-in-match-range pos 7) 'hour)
17379 ((org-pos-in-match-range pos 8) 'minute)
17380 ((or (org-pos-in-match-range pos 4)
17381 (org-pos-in-match-range pos 5)) 'day)
17382 ((and (> pos (or (match-end 8) (match-end 5)))
17383 (< pos (match-end 0)))
17384 (- pos (or (match-end 8) (match-end 5))))
17385 (t 'day))))
17386 ans))
17387
17388 (defun org-toggle-timestamp-type ()
17389 "Toggle the type (<active> or [inactive]) of a time stamp."
17390 (interactive)
17391 (when (org-at-timestamp-p t)
17392 (let ((beg (match-beginning 0)) (end (match-end 0))
17393 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17394 (save-excursion
17395 (goto-char beg)
17396 (while (re-search-forward "[][<>]" end t)
17397 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17398 t t)))
17399 (message "Timestamp is now %sactive"
17400 (if (equal (char-after beg) ?<) "" "in")))))
17401
17402 (defun org-at-clock-log-p nil
17403 "Is the cursor on the clock log line?"
17404 (save-excursion
17405 (move-beginning-of-line 1)
17406 (looking-at "^[ \t]*CLOCK:")))
17407
17408 (defvar org-clock-history) ; defined in org-clock.el
17409 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17410 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17411 "Change the date in the time stamp at point.
17412 The date will be changed by N times WHAT. WHAT can be `day', `month',
17413 `year', `minute', `second'. If WHAT is not given, the cursor position
17414 in the timestamp determines what will be changed.
17415 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17416 (let ((origin (point)) origin-cat
17417 with-hm inactive
17418 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17419 org-ts-what
17420 extra rem
17421 ts time time0 fixnext clrgx)
17422 (if (not (org-at-timestamp-p t))
17423 (user-error "Not at a timestamp"))
17424 (if (and (not what) (eq org-ts-what 'bracket))
17425 (org-toggle-timestamp-type)
17426 ;; Point isn't on brackets. Remember the part of the time-stamp
17427 ;; the point was in. Indeed, size of time-stamps may change,
17428 ;; but point must be kept in the same category nonetheless.
17429 (setq origin-cat org-ts-what)
17430 (if (and (not what) (not (eq org-ts-what 'day))
17431 org-display-custom-times
17432 (get-text-property (point) 'display)
17433 (not (get-text-property (1- (point)) 'display)))
17434 (setq org-ts-what 'day))
17435 (setq org-ts-what (or what org-ts-what)
17436 inactive (= (char-after (match-beginning 0)) ?\[)
17437 ts (match-string 0))
17438 (replace-match "")
17439 (when (string-match
17440 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17441 ts)
17442 (setq extra (match-string 1 ts))
17443 (if suppress-tmp-delay
17444 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17445 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17446 (setq with-hm t))
17447 (setq time0 (org-parse-time-string ts))
17448 (when (and updown
17449 (eq org-ts-what 'minute)
17450 (not current-prefix-arg))
17451 ;; This looks like s-up and s-down. Change by one rounding step.
17452 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17453 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17454 (setcar (cdr time0) (+ (nth 1 time0)
17455 (if (> n 0) (- rem) (- dm rem))))))
17456 (setq time
17457 (encode-time (or (car time0) 0)
17458 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17459 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17460 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17461 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17462 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17463 (nthcdr 6 time0)))
17464 (when (and (member org-ts-what '(hour minute))
17465 extra
17466 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17467 (setq extra (org-modify-ts-extra
17468 extra
17469 (if (eq org-ts-what 'hour) 2 5)
17470 n dm)))
17471 (when (integerp org-ts-what)
17472 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17473 (if (eq what 'calendar)
17474 (let ((cal-date (org-get-date-from-calendar)))
17475 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17476 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17477 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17478 (setcar time0 (or (car time0) 0))
17479 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17480 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17481 (setq time (apply 'encode-time time0))))
17482 ;; Insert the new time-stamp, and ensure point stays in the same
17483 ;; category as before (i.e. not after the last position in that
17484 ;; category).
17485 (let ((pos (point)))
17486 ;; Stay before inserted string. `save-excursion' is of no use.
17487 (setq org-last-changed-timestamp
17488 (org-insert-time-stamp time with-hm inactive nil nil extra))
17489 (goto-char pos))
17490 (save-match-data
17491 (looking-at org-ts-regexp3)
17492 (goto-char (cond
17493 ;; `day' category ends before `hour' if any, or at
17494 ;; the end of the day name.
17495 ((eq origin-cat 'day)
17496 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17497 ((eq origin-cat 'hour) (min (match-end 7) origin))
17498 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17499 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17500 ;; `year' and `month' have both fixed size: point
17501 ;; couldn't have moved into another part.
17502 (t origin))))
17503 ;; Update clock if on a CLOCK line.
17504 (org-clock-update-time-maybe)
17505 ;; Maybe adjust the closest clock in `org-clock-history'
17506 (when org-clock-adjust-closest
17507 (if (not (and (org-at-clock-log-p)
17508 (< 1 (length (delq nil (mapcar 'marker-position
17509 org-clock-history))))))
17510 (message "No clock to adjust")
17511 (cond ((save-excursion ; fix previous clock?
17512 (re-search-backward org-ts-regexp0 nil t)
17513 (org-looking-back (concat org-clock-string " \\[")))
17514 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17515 ((save-excursion ; fix next clock?
17516 (re-search-backward org-ts-regexp0 nil t)
17517 (looking-at (concat org-ts-regexp0 "\\] =>")))
17518 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17519 (save-window-excursion
17520 ;; Find closest clock to point, adjust the previous/next one in history
17521 (let* ((p (save-excursion (org-back-to-heading t)))
17522 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17523 (clfixnth
17524 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17525 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17526 (if (not clfixpos)
17527 (message "No clock to adjust")
17528 (save-excursion
17529 (org-goto-marker-or-bmk clfixpos)
17530 (org-show-subtree)
17531 (when (re-search-forward clrgx nil t)
17532 (goto-char (match-beginning 1))
17533 (let (org-clock-adjust-closest)
17534 (org-timestamp-change n org-ts-what updown))
17535 (message "Clock adjusted in %s for heading: %s"
17536 (file-name-nondirectory (buffer-file-name))
17537 (org-get-heading t t)))))))))
17538 ;; Try to recenter the calendar window, if any.
17539 (if (and org-calendar-follow-timestamp-change
17540 (get-buffer-window "*Calendar*" t)
17541 (memq org-ts-what '(day month year)))
17542 (org-recenter-calendar (time-to-days time))))))
17543
17544 (defun org-modify-ts-extra (s pos n dm)
17545 "Change the different parts of the lead-time and repeat fields in timestamp."
17546 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17547 ng h m new rem)
17548 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17549 (cond
17550 ((or (org-pos-in-match-range pos 2)
17551 (org-pos-in-match-range pos 3))
17552 (setq m (string-to-number (match-string 3 s))
17553 h (string-to-number (match-string 2 s)))
17554 (if (org-pos-in-match-range pos 2)
17555 (setq h (+ h n))
17556 (setq n (* dm (org-no-warnings (signum n))))
17557 (when (not (= 0 (setq rem (% m dm))))
17558 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17559 (setq m (+ m n)))
17560 (if (< m 0) (setq m (+ m 60) h (1- h)))
17561 (if (> m 59) (setq m (- m 60) h (1+ h)))
17562 (setq h (min 24 (max 0 h)))
17563 (setq ng 1 new (format "-%02d:%02d" h m)))
17564 ((org-pos-in-match-range pos 6)
17565 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17566 ((org-pos-in-match-range pos 5)
17567 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17568
17569 ((org-pos-in-match-range pos 9)
17570 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17571 ((org-pos-in-match-range pos 8)
17572 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17573
17574 (when ng
17575 (setq s (concat
17576 (substring s 0 (match-beginning ng))
17577 new
17578 (substring s (match-end ng))))))
17579 s))
17580
17581 (defun org-recenter-calendar (date)
17582 "If the calendar is visible, recenter it to DATE."
17583 (let ((cwin (get-buffer-window "*Calendar*" t)))
17584 (when cwin
17585 (let ((calendar-move-hook nil))
17586 (with-selected-window cwin
17587 (calendar-goto-date (if (listp date) date
17588 (calendar-gregorian-from-absolute date))))))))
17589
17590 (defun org-goto-calendar (&optional arg)
17591 "Go to the Emacs calendar at the current date.
17592 If there is a time stamp in the current line, go to that date.
17593 A prefix ARG can be used to force the current date."
17594 (interactive "P")
17595 (let ((tsr org-ts-regexp) diff
17596 (calendar-move-hook nil)
17597 (calendar-view-holidays-initially-flag nil)
17598 (calendar-view-diary-initially-flag nil))
17599 (if (or (org-at-timestamp-p)
17600 (save-excursion
17601 (beginning-of-line 1)
17602 (looking-at (concat ".*" tsr))))
17603 (let ((d1 (time-to-days (current-time)))
17604 (d2 (time-to-days
17605 (org-time-string-to-time (match-string 1)))))
17606 (setq diff (- d2 d1))))
17607 (calendar)
17608 (calendar-goto-today)
17609 (if (and diff (not arg)) (calendar-forward-day diff))))
17610
17611 (defun org-get-date-from-calendar ()
17612 "Return a list (month day year) of date at point in calendar."
17613 (with-current-buffer "*Calendar*"
17614 (save-match-data
17615 (calendar-cursor-to-date))))
17616
17617 (defun org-date-from-calendar ()
17618 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17619 If there is already a time stamp at the cursor position, update it."
17620 (interactive)
17621 (if (org-at-timestamp-p t)
17622 (org-timestamp-change 0 'calendar)
17623 (let ((cal-date (org-get-date-from-calendar)))
17624 (org-insert-time-stamp
17625 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17626
17627 (defcustom org-effort-durations
17628 `(("h" . 60)
17629 ("d" . ,(* 60 8))
17630 ("w" . ,(* 60 8 5))
17631 ("m" . ,(* 60 8 5 4))
17632 ("y" . ,(* 60 8 5 40)))
17633 "Conversion factor to minutes for an effort modifier.
17634
17635 Each entry has the form (MODIFIER . MINUTES).
17636
17637 In an effort string, a number followed by MODIFIER is multiplied
17638 by the specified number of MINUTES to obtain an effort in
17639 minutes.
17640
17641 For example, if the value of this variable is ((\"hours\" . 60)), then an
17642 effort string \"2hours\" is equivalent to 120 minutes."
17643 :group 'org-agenda
17644 :version "24.1"
17645 :type '(alist :key-type (string :tag "Modifier")
17646 :value-type (number :tag "Minutes")))
17647
17648 (defun org-minutes-to-clocksum-string (m)
17649 "Format number of minutes as a clocksum string.
17650 The format is determined by `org-time-clocksum-format',
17651 `org-time-clocksum-use-fractional' and
17652 `org-time-clocksum-fractional-format' and
17653 `org-time-clocksum-use-effort-durations'."
17654 (let ((clocksum "")
17655 (m (round m)) ; Don't allow fractions of minutes
17656 h d w mo y fmt n)
17657 (setq h (if org-time-clocksum-use-effort-durations
17658 (cdr (assoc "h" org-effort-durations)) 60)
17659 d (if org-time-clocksum-use-effort-durations
17660 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17661 w (if org-time-clocksum-use-effort-durations
17662 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17663 mo (if org-time-clocksum-use-effort-durations
17664 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17665 y (if org-time-clocksum-use-effort-durations
17666 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17667 ;; fractional format
17668 (if org-time-clocksum-use-fractional
17669 (cond
17670 ;; single format string
17671 ((stringp org-time-clocksum-fractional-format)
17672 (format org-time-clocksum-fractional-format (/ m (float h))))
17673 ;; choice of fractional formats for different time units
17674 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17675 (> (/ (truncate m) (* y d h)) 0))
17676 (format fmt (/ m (* y d (float h)))))
17677 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17678 (> (/ (truncate m) (* mo d h)) 0))
17679 (format fmt (/ m (* mo d (float h)))))
17680 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17681 (> (/ (truncate m) (* w d h)) 0))
17682 (format fmt (/ m (* w d (float h)))))
17683 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17684 (> (/ (truncate m) (* d h)) 0))
17685 (format fmt (/ m (* d (float h)))))
17686 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17687 (> (/ (truncate m) h) 0))
17688 (format fmt (/ m (float h))))
17689 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17690 (format fmt m))
17691 ;; fall back to smallest time unit with a format
17692 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17693 (format fmt (/ m (float h))))
17694 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17695 (format fmt (/ m (* d (float h)))))
17696 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17697 (format fmt (/ m (* w d (float h)))))
17698 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17699 (format fmt (/ m (* mo d (float h)))))
17700 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17701 (format fmt (/ m (* y d (float h))))))
17702 ;; standard (non-fractional) format, with single format string
17703 (if (stringp org-time-clocksum-format)
17704 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17705 ;; separate formats components
17706 (and (setq fmt (plist-get org-time-clocksum-format :years))
17707 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17708 (plist-get org-time-clocksum-format :require-years))
17709 (setq clocksum (concat clocksum (format fmt n))
17710 m (- m (* n y d h))))
17711 (and (setq fmt (plist-get org-time-clocksum-format :months))
17712 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17713 (plist-get org-time-clocksum-format :require-months))
17714 (setq clocksum (concat clocksum (format fmt n))
17715 m (- m (* n mo d h))))
17716 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17717 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17718 (plist-get org-time-clocksum-format :require-weeks))
17719 (setq clocksum (concat clocksum (format fmt n))
17720 m (- m (* n w d h))))
17721 (and (setq fmt (plist-get org-time-clocksum-format :days))
17722 (or (> (setq n (/ (truncate m) (* d h))) 0)
17723 (plist-get org-time-clocksum-format :require-days))
17724 (setq clocksum (concat clocksum (format fmt n))
17725 m (- m (* n d h))))
17726 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17727 (or (> (setq n (/ (truncate m) h)) 0)
17728 (plist-get org-time-clocksum-format :require-hours))
17729 (setq clocksum (concat clocksum (format fmt n))
17730 m (- m (* n h))))
17731 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17732 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17733 (setq clocksum (concat clocksum (format fmt m))))
17734 ;; return formatted time duration
17735 clocksum))))
17736
17737 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17738 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17739 "Org mode version 8.0")
17740
17741 (defun org-hours-to-clocksum-string (n)
17742 (org-minutes-to-clocksum-string (* n 60)))
17743
17744 (defun org-hh:mm-string-to-minutes (s)
17745 "Convert a string H:MM to a number of minutes.
17746 If the string is just a number, interpret it as minutes.
17747 In fact, the first hh:mm or number in the string will be taken,
17748 there can be extra stuff in the string.
17749 If no number is found, the return value is 0."
17750 (cond
17751 ((integerp s) s)
17752 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17753 (+ (* (string-to-number (match-string 1 s)) 60)
17754 (string-to-number (match-string 2 s))))
17755 ((string-match "\\([0-9]+\\)" s)
17756 (string-to-number (match-string 1 s)))
17757 (t 0)))
17758
17759 (defcustom org-image-actual-width t
17760 "Should we use the actual width of images when inlining them?
17761
17762 When set to t, always use the image width.
17763
17764 When set to a number, use imagemagick (when available) to set
17765 the image's width to this value.
17766
17767 When set to a number in a list, try to get the width from any
17768 #+ATTR.* keyword if it matches a width specification like
17769
17770 #+ATTR_HTML: :width 300px
17771
17772 and fall back on that number if none is found.
17773
17774 When set to nil, try to get the width from an #+ATTR.* keyword
17775 and fall back on the original width if none is found.
17776
17777 This requires Emacs >= 24.1, build with imagemagick support."
17778 :group 'org-appearance
17779 :version "24.4"
17780 :package-version '(Org . "8.0")
17781 :type '(choice
17782 (const :tag "Use the image width" t)
17783 (integer :tag "Use a number of pixels")
17784 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17785 (const :tag "Use #+ATTR* or don't resize" nil)))
17786
17787 (defcustom org-agenda-inhibit-startup nil
17788 "Inhibit startup when preparing agenda buffers.
17789 When this variable is t, the initialization of the Org agenda
17790 buffers is inhibited: e.g. the visibility state is not set, the
17791 tables are not re-aligned, etc."
17792 :type 'boolean
17793 :version "24.3"
17794 :group 'org-agenda)
17795
17796 (defcustom org-agenda-ignore-drawer-properties nil
17797 "Avoid updating text properties when building the agenda.
17798 Properties are used to prepare buffers for effort estimates, appointments,
17799 and subtree-local categories.
17800 If you don't use these in the agenda, you can add them to this list and
17801 agenda building will be a bit faster.
17802 The value is a list, with zero or more of the symbols `effort', `appt',
17803 or `category'."
17804 :type '(set :greedy t
17805 (const effort)
17806 (const appt)
17807 (const category))
17808 :version "24.3"
17809 :group 'org-agenda)
17810
17811 (defun org-duration-string-to-minutes (s &optional output-to-string)
17812 "Convert a duration string S to minutes.
17813
17814 A bare number is interpreted as minutes, modifiers can be set by
17815 customizing `org-effort-durations' (which see).
17816
17817 Entries containing a colon are interpreted as H:MM by
17818 `org-hh:mm-string-to-minutes'."
17819 (let ((result 0)
17820 (re (concat "\\([0-9.]+\\) *\\("
17821 (regexp-opt (mapcar 'car org-effort-durations))
17822 "\\)")))
17823 (while (string-match re s)
17824 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17825 (string-to-number (match-string 1 s))))
17826 (setq s (replace-match "" nil t s)))
17827 (setq result (floor result))
17828 (incf result (org-hh:mm-string-to-minutes s))
17829 (if output-to-string (number-to-string result) result)))
17830
17831 ;;;; Files
17832
17833 (defun org-save-all-org-buffers ()
17834 "Save all Org-mode buffers without user confirmation."
17835 (interactive)
17836 (message "Saving all Org-mode buffers...")
17837 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17838 (when (featurep 'org-id) (org-id-locations-save))
17839 (message "Saving all Org-mode buffers... done"))
17840
17841 (defun org-revert-all-org-buffers ()
17842 "Revert all Org-mode buffers.
17843 Prompt for confirmation when there are unsaved changes.
17844 Be sure you know what you are doing before letting this function
17845 overwrite your changes.
17846
17847 This function is useful in a setup where one tracks org files
17848 with a version control system, to revert on one machine after pulling
17849 changes from another. I believe the procedure must be like this:
17850
17851 1. M-x org-save-all-org-buffers
17852 2. Pull changes from the other machine, resolve conflicts
17853 3. M-x org-revert-all-org-buffers"
17854 (interactive)
17855 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17856 (user-error "Abort"))
17857 (save-excursion
17858 (save-window-excursion
17859 (mapc
17860 (lambda (b)
17861 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17862 (with-current-buffer b buffer-file-name))
17863 (org-pop-to-buffer-same-window b)
17864 (revert-buffer t 'no-confirm)))
17865 (buffer-list))
17866 (when (and (featurep 'org-id) org-id-track-globally)
17867 (org-id-locations-load)))))
17868
17869 ;;;; Agenda files
17870
17871 ;;;###autoload
17872 (defun org-switchb (&optional arg)
17873 "Switch between Org buffers.
17874 With one prefix argument, restrict available buffers to files.
17875 With two prefix arguments, restrict available buffers to agenda files.
17876
17877 Defaults to `iswitchb' for buffer name completion.
17878 Set `org-completion-use-ido' to make it use ido instead."
17879 (interactive "P")
17880 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17881 ((equal arg '(16)) (org-buffer-list 'agenda))
17882 (t (org-buffer-list))))
17883 (org-completion-use-iswitchb org-completion-use-iswitchb)
17884 (org-completion-use-ido org-completion-use-ido))
17885 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17886 (setq org-completion-use-iswitchb t))
17887 (org-pop-to-buffer-same-window
17888 (org-icompleting-read "Org buffer: "
17889 (mapcar 'list (mapcar 'buffer-name blist))
17890 nil t))))
17891
17892 ;;; Define some older names previously used for this functionality
17893 ;;;###autoload
17894 (defalias 'org-ido-switchb 'org-switchb)
17895 ;;;###autoload
17896 (defalias 'org-iswitchb 'org-switchb)
17897
17898 (defun org-buffer-list (&optional predicate exclude-tmp)
17899 "Return a list of Org buffers.
17900 PREDICATE can be `export', `files' or `agenda'.
17901
17902 export restrict the list to Export buffers.
17903 files restrict the list to buffers visiting Org files.
17904 agenda restrict the list to buffers visiting agenda files.
17905
17906 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17907 (let* ((bfn nil)
17908 (agenda-files (and (eq predicate 'agenda)
17909 (mapcar 'file-truename (org-agenda-files t))))
17910 (filter
17911 (cond
17912 ((eq predicate 'files)
17913 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17914 ((eq predicate 'export)
17915 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17916 ((eq predicate 'agenda)
17917 (lambda (b)
17918 (with-current-buffer b
17919 (and (derived-mode-p 'org-mode)
17920 (setq bfn (buffer-file-name b))
17921 (member (file-truename bfn) agenda-files)))))
17922 (t (lambda (b) (with-current-buffer b
17923 (or (derived-mode-p 'org-mode)
17924 (string-match "\\*Org .*Export"
17925 (buffer-name b)))))))))
17926 (delq nil
17927 (mapcar
17928 (lambda(b)
17929 (if (and (funcall filter b)
17930 (or (not exclude-tmp)
17931 (not (string-match "tmp" (buffer-name b)))))
17932 b
17933 nil))
17934 (buffer-list)))))
17935
17936 (defun org-agenda-files (&optional unrestricted archives)
17937 "Get the list of agenda files.
17938 Optional UNRESTRICTED means return the full list even if a restriction
17939 is currently in place.
17940 When ARCHIVES is t, include all archive files that are really being
17941 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17942 `org-agenda-archives-mode' is t."
17943 (let ((files
17944 (cond
17945 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17946 ((stringp org-agenda-files) (org-read-agenda-file-list))
17947 ((listp org-agenda-files) org-agenda-files)
17948 (t (error "Invalid value of `org-agenda-files'")))))
17949 (setq files (apply 'append
17950 (mapcar (lambda (f)
17951 (if (file-directory-p f)
17952 (directory-files
17953 f t org-agenda-file-regexp)
17954 (list f)))
17955 files)))
17956 (when org-agenda-skip-unavailable-files
17957 (setq files (delq nil
17958 (mapcar (function
17959 (lambda (file)
17960 (and (file-readable-p file) file)))
17961 files))))
17962 (when (or (eq archives t)
17963 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17964 (setq files (org-add-archive-files files)))
17965 files))
17966
17967 (defun org-agenda-file-p (&optional file)
17968 "Return non-nil, if FILE is an agenda file.
17969 If FILE is omitted, use the file associated with the current
17970 buffer."
17971 (member (or file (buffer-file-name))
17972 (org-agenda-files t)))
17973
17974 (defun org-edit-agenda-file-list ()
17975 "Edit the list of agenda files.
17976 Depending on setup, this either uses customize to edit the variable
17977 `org-agenda-files', or it visits the file that is holding the list. In the
17978 latter case, the buffer is set up in a way that saving it automatically kills
17979 the buffer and restores the previous window configuration."
17980 (interactive)
17981 (if (stringp org-agenda-files)
17982 (let ((cw (current-window-configuration)))
17983 (find-file org-agenda-files)
17984 (org-set-local 'org-window-configuration cw)
17985 (org-add-hook 'after-save-hook
17986 (lambda ()
17987 (set-window-configuration
17988 (prog1 org-window-configuration
17989 (kill-buffer (current-buffer))))
17990 (org-install-agenda-files-menu)
17991 (message "New agenda file list installed"))
17992 nil 'local)
17993 (message "%s" (substitute-command-keys
17994 "Edit list and finish with \\[save-buffer]")))
17995 (customize-variable 'org-agenda-files)))
17996
17997 (defun org-store-new-agenda-file-list (list)
17998 "Set new value for the agenda file list and save it correctly."
17999 (if (stringp org-agenda-files)
18000 (let ((fe (org-read-agenda-file-list t)) b u)
18001 (while (setq b (find-buffer-visiting org-agenda-files))
18002 (kill-buffer b))
18003 (with-temp-file org-agenda-files
18004 (insert
18005 (mapconcat
18006 (lambda (f) ;; Keep un-expanded entries.
18007 (if (setq u (assoc f fe))
18008 (cdr u)
18009 f))
18010 list "\n")
18011 "\n")))
18012 (let ((org-mode-hook nil) (org-inhibit-startup t)
18013 (org-insert-mode-line-in-empty-file nil))
18014 (setq org-agenda-files list)
18015 (customize-save-variable 'org-agenda-files org-agenda-files))))
18016
18017 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18018 "Read the list of agenda files from a file.
18019 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18020 filenames, used by `org-store-new-agenda-file-list' to write back
18021 un-expanded file names."
18022 (when (file-directory-p org-agenda-files)
18023 (error "`org-agenda-files' cannot be a single directory"))
18024 (when (stringp org-agenda-files)
18025 (with-temp-buffer
18026 (insert-file-contents org-agenda-files)
18027 (mapcar
18028 (lambda (f)
18029 (let ((e (expand-file-name (substitute-in-file-name f)
18030 org-directory)))
18031 (if pair-with-expansion
18032 (cons e f)
18033 e)))
18034 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18035
18036 ;;;###autoload
18037 (defun org-cycle-agenda-files ()
18038 "Cycle through the files in `org-agenda-files'.
18039 If the current buffer visits an agenda file, find the next one in the list.
18040 If the current buffer does not, find the first agenda file."
18041 (interactive)
18042 (let* ((fs (org-agenda-files t))
18043 (files (append fs (list (car fs))))
18044 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18045 file)
18046 (unless files (user-error "No agenda files"))
18047 (catch 'exit
18048 (dolist (file files)
18049 (if (equal (file-truename file) tcf)
18050 (when (car files)
18051 (find-file (car files))
18052 (throw 'exit t))))
18053 (find-file (car fs)))
18054 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18055
18056 (defun org-agenda-file-to-front (&optional to-end)
18057 "Move/add the current file to the top of the agenda file list.
18058 If the file is not present in the list, it is added to the front. If it is
18059 present, it is moved there. With optional argument TO-END, add/move to the
18060 end of the list."
18061 (interactive "P")
18062 (let ((org-agenda-skip-unavailable-files nil)
18063 (file-alist (mapcar (lambda (x)
18064 (cons (file-truename x) x))
18065 (org-agenda-files t)))
18066 (ctf (file-truename
18067 (or buffer-file-name
18068 (user-error "Please save the current buffer to a file"))))
18069 x had)
18070 (setq x (assoc ctf file-alist) had x)
18071
18072 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18073 (if to-end
18074 (setq file-alist (append (delq x file-alist) (list x)))
18075 (setq file-alist (cons x (delq x file-alist))))
18076 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18077 (org-install-agenda-files-menu)
18078 (message "File %s to %s of agenda file list"
18079 (if had "moved" "added") (if to-end "end" "front"))))
18080
18081 (defun org-remove-file (&optional file)
18082 "Remove current file from the list of files in variable `org-agenda-files'.
18083 These are the files which are being checked for agenda entries.
18084 Optional argument FILE means use this file instead of the current."
18085 (interactive)
18086 (let* ((org-agenda-skip-unavailable-files nil)
18087 (file (or file buffer-file-name
18088 (user-error "Current buffer does not visit a file")))
18089 (true-file (file-truename file))
18090 (afile (abbreviate-file-name file))
18091 (files (delq nil (mapcar
18092 (lambda (x)
18093 (if (equal true-file
18094 (file-truename x))
18095 nil x))
18096 (org-agenda-files t)))))
18097 (if (not (= (length files) (length (org-agenda-files t))))
18098 (progn
18099 (org-store-new-agenda-file-list files)
18100 (org-install-agenda-files-menu)
18101 (message "Removed file: %s" afile))
18102 (message "File was not in list: %s (not removed)" afile))))
18103
18104 (defun org-file-menu-entry (file)
18105 (vector file (list 'find-file file) t))
18106
18107 (defun org-check-agenda-file (file)
18108 "Make sure FILE exists. If not, ask user what to do."
18109 (when (not (file-exists-p file))
18110 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18111 (abbreviate-file-name file))
18112 (let ((r (downcase (read-char-exclusive))))
18113 (cond
18114 ((equal r ?r)
18115 (org-remove-file file)
18116 (throw 'nextfile t))
18117 (t (error "Abort"))))))
18118
18119 (defun org-get-agenda-file-buffer (file)
18120 "Get a buffer visiting FILE. If the buffer needs to be created, add
18121 it to the list of buffers which might be released later."
18122 (let ((buf (org-find-base-buffer-visiting file)))
18123 (if buf
18124 buf ; just return it
18125 ;; Make a new buffer and remember it
18126 (setq buf (find-file-noselect file))
18127 (if buf (push buf org-agenda-new-buffers))
18128 buf)))
18129
18130 (defun org-release-buffers (blist)
18131 "Release all buffers in list, asking the user for confirmation when needed.
18132 When a buffer is unmodified, it is just killed. When modified, it is saved
18133 \(if the user agrees) and then killed."
18134 (let (file)
18135 (dolist (buf blist)
18136 (setq file (buffer-file-name buf))
18137 (when (and (buffer-modified-p buf)
18138 file
18139 (y-or-n-p (format "Save file %s? " file)))
18140 (with-current-buffer buf (save-buffer)))
18141 (kill-buffer buf))))
18142
18143 (defun org-agenda-prepare-buffers (files)
18144 "Create buffers for all agenda files, protect archived trees and comments."
18145 (interactive)
18146 (let ((pa '(:org-archived t))
18147 (pc '(:org-comment t))
18148 (pall '(:org-archived t :org-comment t))
18149 (inhibit-read-only t)
18150 (org-inhibit-startup org-agenda-inhibit-startup)
18151 (rea (concat ":" org-archive-tag ":"))
18152 file re pos)
18153 (setq org-tag-alist-for-agenda nil
18154 org-tag-groups-alist-for-agenda nil)
18155 (save-excursion
18156 (save-restriction
18157 (dolist (file files)
18158 (catch 'nextfile
18159 (if (bufferp file)
18160 (set-buffer file)
18161 (org-check-agenda-file file)
18162 (set-buffer (org-get-agenda-file-buffer file)))
18163 (widen)
18164 (org-set-regexps-and-options-for-tags)
18165 (setq pos (point))
18166 (goto-char (point-min))
18167 (let ((case-fold-search t))
18168 (when (search-forward "#+setupfile" nil t)
18169 ;; Don't set all regexps and options systematically as
18170 ;; this is only run for setting agenda tags from setup
18171 ;; file
18172 (org-set-regexps-and-options)))
18173 (or (memq 'category org-agenda-ignore-drawer-properties)
18174 (org-refresh-category-properties))
18175 (or (memq 'effort org-agenda-ignore-drawer-properties)
18176 (org-refresh-properties org-effort-property 'org-effort))
18177 (or (memq 'appt org-agenda-ignore-drawer-properties)
18178 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18179 (setq org-todo-keywords-for-agenda
18180 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18181 (setq org-done-keywords-for-agenda
18182 (append org-done-keywords-for-agenda org-done-keywords))
18183 (setq org-todo-keyword-alist-for-agenda
18184 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18185 (setq org-drawers-for-agenda
18186 (append org-drawers-for-agenda org-drawers))
18187 (setq org-tag-alist-for-agenda
18188 (org-uniquify
18189 (append org-tag-alist-for-agenda
18190 org-tag-alist
18191 org-tag-persistent-alist)))
18192 (if org-group-tags
18193 (setq org-tag-groups-alist-for-agenda
18194 (org-uniquify-alist
18195 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18196 (org-with-silent-modifications
18197 (save-excursion
18198 (remove-text-properties (point-min) (point-max) pall)
18199 (when org-agenda-skip-archived-trees
18200 (goto-char (point-min))
18201 (while (re-search-forward rea nil t)
18202 (if (org-at-heading-p t)
18203 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18204 (goto-char (point-min))
18205 (setq re (format org-heading-keyword-regexp-format
18206 org-comment-string))
18207 (while (re-search-forward re nil t)
18208 (add-text-properties
18209 (match-beginning 0) (org-end-of-subtree t) pc))))
18210 (goto-char pos)))))
18211 (setq org-todo-keywords-for-agenda
18212 (org-uniquify org-todo-keywords-for-agenda))
18213 (setq org-todo-keyword-alist-for-agenda
18214 (org-uniquify org-todo-keyword-alist-for-agenda))))
18215
18216 \f
18217 ;;;; CDLaTeX minor mode
18218
18219 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18220 "Keymap for the minor `org-cdlatex-mode'.")
18221
18222 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18223 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18224 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18225 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18226 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18227
18228 (defvar org-cdlatex-texmathp-advice-is-done nil
18229 "Flag remembering if we have applied the advice to texmathp already.")
18230
18231 (define-minor-mode org-cdlatex-mode
18232 "Toggle the minor `org-cdlatex-mode'.
18233 This mode supports entering LaTeX environment and math in LaTeX fragments
18234 in Org-mode.
18235 \\{org-cdlatex-mode-map}"
18236 nil " OCDL" nil
18237 (when org-cdlatex-mode
18238 (require 'cdlatex)
18239 (run-hooks 'cdlatex-mode-hook)
18240 (cdlatex-compute-tables))
18241 (unless org-cdlatex-texmathp-advice-is-done
18242 (setq org-cdlatex-texmathp-advice-is-done t)
18243 (defadvice texmathp (around org-math-always-on activate)
18244 "Always return t in org-mode buffers.
18245 This is because we want to insert math symbols without dollars even outside
18246 the LaTeX math segments. If Orgmode thinks that point is actually inside
18247 an embedded LaTeX fragment, let texmathp do its job.
18248 \\[org-cdlatex-mode-map]"
18249 (interactive)
18250 (let (p)
18251 (cond
18252 ((not (derived-mode-p 'org-mode)) ad-do-it)
18253 ((eq this-command 'cdlatex-math-symbol)
18254 (setq ad-return-value t
18255 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18256 (t
18257 (let ((p (org-inside-LaTeX-fragment-p)))
18258 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18259 (setq ad-return-value t
18260 texmathp-why '("Org-mode embedded math" . 0))
18261 (if p ad-do-it)))))))))
18262
18263 (defun turn-on-org-cdlatex ()
18264 "Unconditionally turn on `org-cdlatex-mode'."
18265 (org-cdlatex-mode 1))
18266
18267 (defun org-try-cdlatex-tab ()
18268 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18269 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18270 - inside a LaTeX fragment, or
18271 - after the first word in a line, where an abbreviation expansion could
18272 insert a LaTeX environment."
18273 (when org-cdlatex-mode
18274 (cond
18275 ;; Before any word on the line: No expansion possible.
18276 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18277 ;; Just after first word on the line: Expand it. Make sure it
18278 ;; cannot happen on headlines, though.
18279 ((save-excursion
18280 (skip-chars-backward "a-zA-Z0-9*")
18281 (skip-chars-backward " \t")
18282 (and (bolp) (not (org-at-heading-p))))
18283 (cdlatex-tab) t)
18284 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18285
18286 (defun org-cdlatex-underscore-caret (&optional arg)
18287 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18288 Revert to the normal definition outside of these fragments."
18289 (interactive "P")
18290 (if (org-inside-LaTeX-fragment-p)
18291 (call-interactively 'cdlatex-sub-superscript)
18292 (let (org-cdlatex-mode)
18293 (call-interactively (key-binding (vector last-input-event))))))
18294
18295 (defun org-cdlatex-math-modify (&optional arg)
18296 "Execute `cdlatex-math-modify' in LaTeX fragments.
18297 Revert to the normal definition outside of these fragments."
18298 (interactive "P")
18299 (if (org-inside-LaTeX-fragment-p)
18300 (call-interactively 'cdlatex-math-modify)
18301 (let (org-cdlatex-mode)
18302 (call-interactively (key-binding (vector last-input-event))))))
18303
18304
18305 \f
18306 ;;;; LaTeX fragments
18307
18308 (defvar org-latex-regexps
18309 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18310 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18311 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18312 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18313 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18314 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18315 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18316 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18317 "Regular expressions for matching embedded LaTeX.")
18318
18319 (defun org-inside-LaTeX-fragment-p ()
18320 "Test if point is inside a LaTeX fragment.
18321 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18322 sequence appearing also before point.
18323 Even though the matchers for math are configurable, this function assumes
18324 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18325 delimiters are skipped when they have been removed by customization.
18326 The return value is nil, or a cons cell with the delimiter and the
18327 position of this delimiter.
18328
18329 This function does a reasonably good job, but can locally be fooled by
18330 for example currency specifications. For example it will assume being in
18331 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18332 fragments that are properly closed, but during editing, we have to live
18333 with the uncertainty caused by missing closing delimiters. This function
18334 looks only before point, not after."
18335 (catch 'exit
18336 (let ((pos (point))
18337 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18338 (lim (progn
18339 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18340 (point)))
18341 dd-on str (start 0) m re)
18342 (goto-char pos)
18343 (when dodollar
18344 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18345 re (nth 1 (assoc "$" org-latex-regexps)))
18346 (while (string-match re str start)
18347 (cond
18348 ((= (match-end 0) (length str))
18349 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18350 ((= (match-end 0) (- (length str) 5))
18351 (throw 'exit nil))
18352 (t (setq start (match-end 0))))))
18353 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18354 (goto-char pos)
18355 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18356 (and (match-beginning 2) (throw 'exit nil))
18357 ;; count $$
18358 (while (re-search-backward "\\$\\$" lim t)
18359 (setq dd-on (not dd-on)))
18360 (goto-char pos)
18361 (if dd-on (cons "$$" m))))))
18362
18363 (defun org-inside-latex-macro-p ()
18364 "Is point inside a LaTeX macro or its arguments?"
18365 (save-match-data
18366 (org-in-regexp
18367 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18368
18369 (defvar org-latex-fragment-image-overlays nil
18370 "List of overlays carrying the images of latex fragments.")
18371 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18372
18373 (defun org-remove-latex-fragment-image-overlays ()
18374 "Remove all overlays with LaTeX fragment images in current buffer."
18375 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18376 (setq org-latex-fragment-image-overlays nil))
18377
18378 (defun org-preview-latex-fragment (&optional subtree)
18379 "Preview the LaTeX fragment at point, or all locally or globally.
18380 If the cursor is in a LaTeX fragment, create the image and overlay
18381 it over the source code. If there is no fragment at point, display
18382 all fragments in the current text, from one headline to the next. With
18383 prefix SUBTREE, display all fragments in the current subtree. With a
18384 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18385 the cursor is before the first headline,
18386 display all fragments in the buffer.
18387 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18388 (interactive "P")
18389 (unless buffer-file-name
18390 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18391 (when (display-graphic-p)
18392 (org-remove-latex-fragment-image-overlays)
18393 (save-excursion
18394 (save-restriction
18395 (let (beg end at msg)
18396 (cond
18397 ((or (equal subtree '(16))
18398 (not (save-excursion
18399 (re-search-backward org-outline-regexp-bol nil t))))
18400 (setq beg (point-min) end (point-max)
18401 msg "Creating images for buffer...%s"))
18402 ((equal subtree '(4))
18403 (org-back-to-heading)
18404 (setq beg (point) end (org-end-of-subtree t)
18405 msg "Creating images for subtree...%s"))
18406 (t
18407 (if (setq at (org-inside-LaTeX-fragment-p))
18408 (goto-char (max (point-min) (- (cdr at) 2)))
18409 (org-back-to-heading))
18410 (setq beg (point) end (progn (outline-next-heading) (point))
18411 msg (if at "Creating image...%s"
18412 "Creating images for entry...%s"))))
18413 (message msg "")
18414 (narrow-to-region beg end)
18415 (goto-char beg)
18416 (org-format-latex
18417 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18418 (file-name-nondirectory
18419 buffer-file-name)))
18420 default-directory 'overlays msg at 'forbuffer
18421 org-latex-create-formula-image-program)
18422 (message msg "done. Use `C-c C-c' to remove images."))))))
18423
18424 (defun org-format-latex (prefix &optional dir overlays msg at
18425 forbuffer processing-type)
18426 "Replace LaTeX fragments with links to an image, and produce images.
18427 Some of the options can be changed using the variable
18428 `org-format-latex-options'."
18429 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18430 (let* ((prefixnodir (file-name-nondirectory prefix))
18431 (absprefix (expand-file-name prefix dir))
18432 (todir (file-name-directory absprefix))
18433 (opt org-format-latex-options)
18434 (optnew org-format-latex-options)
18435 (matchers (plist-get opt :matchers))
18436 (re-list org-latex-regexps)
18437 (cnt 0) txt hash link beg end re checkdir
18438 string
18439 m n block-type block linkfile movefile ov)
18440 ;; Check the different regular expressions
18441 (dolist (e re-list)
18442 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18443 block (if block-type "\n\n" ""))
18444 (when (member m matchers)
18445 (goto-char (point-min))
18446 (while (re-search-forward re nil t)
18447 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18448 (or (not overlays)
18449 (not (eq (get-char-property (match-beginning n)
18450 'org-overlay-type)
18451 'org-latex-overlay))))
18452 (cond
18453 ((eq processing-type 'verbatim))
18454 ((eq processing-type 'mathjax)
18455 ;; Prepare for MathJax processing.
18456 (setq string (match-string n))
18457 (when (member m '("$" "$1"))
18458 (save-excursion
18459 (delete-region (match-beginning n) (match-end n))
18460 (goto-char (match-beginning n))
18461 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18462 ((or (eq processing-type 'dvipng)
18463 (eq processing-type 'imagemagick))
18464 ;; Process to an image.
18465 (setq txt (match-string n)
18466 beg (match-beginning n) end (match-end n)
18467 cnt (1+ cnt))
18468 (let ((face (face-at-point))
18469 (fg (plist-get opt :foreground))
18470 (bg (plist-get opt :background))
18471 ;; Ensure full list is printed.
18472 print-length print-level)
18473 (when forbuffer
18474 ;; Get the colors from the face at point.
18475 (goto-char beg)
18476 (when (eq fg 'auto)
18477 (setq fg (face-attribute face :foreground nil 'default)))
18478 (when (eq bg 'auto)
18479 (setq bg (face-attribute face :background nil 'default)))
18480 (setq optnew (copy-sequence opt))
18481 (plist-put optnew :foreground fg)
18482 (plist-put optnew :background bg))
18483 (setq hash (sha1 (prin1-to-string
18484 (list org-format-latex-header
18485 org-latex-default-packages-alist
18486 org-latex-packages-alist
18487 org-format-latex-options
18488 forbuffer txt fg bg)))
18489 linkfile (format "%s_%s.png" prefix hash)
18490 movefile (format "%s_%s.png" absprefix hash)))
18491 (setq link (concat block "[[file:" linkfile "]]" block))
18492 (if msg (message msg cnt))
18493 (goto-char beg)
18494 (unless checkdir ; Ensure the directory exists.
18495 (setq checkdir t)
18496 (or (file-directory-p todir) (make-directory todir t)))
18497 (unless (file-exists-p movefile)
18498 (org-create-formula-image
18499 txt movefile optnew forbuffer processing-type))
18500 (if overlays
18501 (progn
18502 (mapc (lambda (o)
18503 (if (eq (overlay-get o 'org-overlay-type)
18504 'org-latex-overlay)
18505 (delete-overlay o)))
18506 (overlays-in beg end))
18507 (setq ov (make-overlay beg end))
18508 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18509 (if (featurep 'xemacs)
18510 (progn
18511 (overlay-put ov 'invisible t)
18512 (overlay-put
18513 ov 'end-glyph
18514 (make-glyph (vector 'png :file movefile))))
18515 (overlay-put
18516 ov 'display
18517 (list 'image :type 'png :file movefile :ascent 'center)))
18518 (push ov org-latex-fragment-image-overlays)
18519 (goto-char end))
18520 (delete-region beg end)
18521 (insert (org-add-props link
18522 (list 'org-latex-src
18523 (replace-regexp-in-string
18524 "\"" "" txt)
18525 'org-latex-src-embed-type
18526 (if block-type 'paragraph 'character))))))
18527 ((eq processing-type 'mathml)
18528 ;; Process to MathML
18529 (unless (save-match-data (org-format-latex-mathml-available-p))
18530 (user-error "LaTeX to MathML converter not configured"))
18531 (setq txt (match-string n)
18532 beg (match-beginning n) end (match-end n)
18533 cnt (1+ cnt))
18534 (if msg (message msg cnt))
18535 (goto-char beg)
18536 (delete-region beg end)
18537 (insert (org-format-latex-as-mathml
18538 txt block-type prefix dir)))
18539 (t
18540 (error "Unknown conversion type %s for LaTeX fragments"
18541 processing-type)))))))))
18542
18543 (defun org-create-math-formula (latex-frag &optional mathml-file)
18544 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18545 Use `org-latex-to-mathml-convert-command'. If the conversion is
18546 sucessful, return the portion between \"<math...> </math>\"
18547 elements otherwise return nil. When MATHML-FILE is specified,
18548 write the results in to that file. When invoked as an
18549 interactive command, prompt for LATEX-FRAG, with initial value
18550 set to the current active region and echo the results for user
18551 inspection."
18552 (interactive (list (let ((frag (when (org-region-active-p)
18553 (buffer-substring-no-properties
18554 (region-beginning) (region-end)))))
18555 (read-string "LaTeX Fragment: " frag nil frag))))
18556 (unless latex-frag (error "Invalid LaTeX fragment"))
18557 (let* ((tmp-in-file (file-relative-name
18558 (make-temp-name (expand-file-name "ltxmathml-in"))))
18559 (ignore (write-region latex-frag nil tmp-in-file))
18560 (tmp-out-file (file-relative-name
18561 (make-temp-name (expand-file-name "ltxmathml-out"))))
18562 (cmd (format-spec
18563 org-latex-to-mathml-convert-command
18564 `((?j . ,(shell-quote-argument
18565 (expand-file-name org-latex-to-mathml-jar-file)))
18566 (?I . ,(shell-quote-argument tmp-in-file))
18567 (?o . ,(shell-quote-argument tmp-out-file)))))
18568 mathml shell-command-output)
18569 (when (org-called-interactively-p 'any)
18570 (unless (org-format-latex-mathml-available-p)
18571 (user-error "LaTeX to MathML converter not configured")))
18572 (message "Running %s" cmd)
18573 (setq shell-command-output (shell-command-to-string cmd))
18574 (setq mathml
18575 (when (file-readable-p tmp-out-file)
18576 (with-current-buffer (find-file-noselect tmp-out-file t)
18577 (goto-char (point-min))
18578 (when (re-search-forward
18579 (concat
18580 (regexp-quote
18581 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18582 "\\(.\\|\n\\)*"
18583 (regexp-quote "</math>")) nil t)
18584 (prog1 (match-string 0) (kill-buffer))))))
18585 (cond
18586 (mathml
18587 (setq mathml
18588 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18589 (when mathml-file
18590 (write-region mathml nil mathml-file))
18591 (when (org-called-interactively-p 'any)
18592 (message mathml)))
18593 ((message "LaTeX to MathML conversion failed")
18594 (message shell-command-output)))
18595 (delete-file tmp-in-file)
18596 (when (file-exists-p tmp-out-file)
18597 (delete-file tmp-out-file))
18598 mathml))
18599
18600 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18601 prefix &optional dir)
18602 "Use `org-create-math-formula' but check local cache first."
18603 (let* ((absprefix (expand-file-name prefix dir))
18604 (print-length nil) (print-level nil)
18605 (formula-id (concat
18606 "formula-"
18607 (sha1
18608 (prin1-to-string
18609 (list latex-frag
18610 org-latex-to-mathml-convert-command)))))
18611 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18612 (formula-cache-dir (file-name-directory formula-cache)))
18613
18614 (unless (file-directory-p formula-cache-dir)
18615 (make-directory formula-cache-dir t))
18616
18617 (unless (file-exists-p formula-cache)
18618 (org-create-math-formula latex-frag formula-cache))
18619
18620 (if (file-exists-p formula-cache)
18621 ;; Successful conversion. Return the link to MathML file.
18622 (org-add-props
18623 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18624 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18625 'org-latex-src-embed-type (if latex-frag-type
18626 'paragraph 'character)))
18627 ;; Failed conversion. Return the LaTeX fragment verbatim
18628 latex-frag)))
18629
18630 (defun org-create-formula-image (string tofile options buffer &optional type)
18631 "Create an image from LaTeX source using dvipng or convert.
18632 This function calls either `org-create-formula-image-with-dvipng'
18633 or `org-create-formula-image-with-imagemagick' depending on the
18634 value of `org-latex-create-formula-image-program' or on the value
18635 of the optional TYPE variable.
18636
18637 Note: ultimately these two function should be combined as they
18638 share a good deal of logic."
18639 (org-check-external-command
18640 "latex" "needed to convert LaTeX fragments to images")
18641 (funcall
18642 (case (or type org-latex-create-formula-image-program)
18643 ('dvipng
18644 (org-check-external-command
18645 "dvipng" "needed to convert LaTeX fragments to images")
18646 #'org-create-formula-image-with-dvipng)
18647 ('imagemagick
18648 (org-check-external-command
18649 "convert" "you need to install imagemagick")
18650 #'org-create-formula-image-with-imagemagick)
18651 (t (error
18652 "Invalid value of `org-latex-create-formula-image-program'")))
18653 string tofile options buffer))
18654
18655 (declare-function org-export-get-backend "ox" (name))
18656 (declare-function org-export--get-global-options "ox" (&optional backend))
18657 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18658 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18659 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18660 (defun org-create-formula--latex-header ()
18661 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18662 (let ((info (org-combine-plists (org-export--get-global-options
18663 (org-export-get-backend 'latex))
18664 (org-export--get-inbuffer-options
18665 (org-export-get-backend 'latex)))))
18666 (org-latex-guess-babel-language
18667 (org-latex-guess-inputenc
18668 (org-splice-latex-header
18669 org-format-latex-header
18670 org-latex-default-packages-alist
18671 org-latex-packages-alist t
18672 (plist-get info :latex-header)))
18673 info)))
18674
18675 ;; This function borrows from Ganesh Swami's latex2png.el
18676 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18677 "This calls dvipng."
18678 (require 'ox-latex)
18679 (let* ((tmpdir (if (featurep 'xemacs)
18680 (temp-directory)
18681 temporary-file-directory))
18682 (texfilebase (make-temp-name
18683 (expand-file-name "orgtex" tmpdir)))
18684 (texfile (concat texfilebase ".tex"))
18685 (dvifile (concat texfilebase ".dvi"))
18686 (pngfile (concat texfilebase ".png"))
18687 (fnh (if (featurep 'xemacs)
18688 (font-height (face-font 'default))
18689 (face-attribute 'default :height nil)))
18690 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18691 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18692 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18693 "Black"))
18694 (bg (or (plist-get options (if buffer :background :html-background))
18695 "Transparent")))
18696 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18697 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18698 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18699 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18700 (let ((latex-header (org-create-formula--latex-header)))
18701 (with-temp-file texfile
18702 (insert latex-header)
18703 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18704 (let ((dir default-directory))
18705 (condition-case nil
18706 (progn
18707 (cd tmpdir)
18708 (call-process "latex" nil nil nil texfile))
18709 (error nil))
18710 (cd dir))
18711 (if (not (file-exists-p dvifile))
18712 (progn (message "Failed to create dvi file from %s" texfile) nil)
18713 (condition-case nil
18714 (if (featurep 'xemacs)
18715 (call-process "dvipng" nil nil nil
18716 "-fg" fg "-bg" bg
18717 "-T" "tight"
18718 "-o" pngfile
18719 dvifile)
18720 (call-process "dvipng" nil nil nil
18721 "-fg" fg "-bg" bg
18722 "-D" dpi
18723 ;;"-x" scale "-y" scale
18724 "-T" "tight"
18725 "-o" pngfile
18726 dvifile))
18727 (error nil))
18728 (if (not (file-exists-p pngfile))
18729 (if org-format-latex-signal-error
18730 (error "Failed to create png file from %s" texfile)
18731 (message "Failed to create png file from %s" texfile)
18732 nil)
18733 ;; Use the requested file name and clean up
18734 (copy-file pngfile tofile 'replace)
18735 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18736 (if (file-exists-p (concat texfilebase e))
18737 (delete-file (concat texfilebase e))))
18738 pngfile))))
18739
18740 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18741 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18742 "This calls convert, which is included into imagemagick."
18743 (require 'ox-latex)
18744 (let* ((tmpdir (if (featurep 'xemacs)
18745 (temp-directory)
18746 temporary-file-directory))
18747 (texfilebase (make-temp-name
18748 (expand-file-name "orgtex" tmpdir)))
18749 (texfile (concat texfilebase ".tex"))
18750 (pdffile (concat texfilebase ".pdf"))
18751 (pngfile (concat texfilebase ".png"))
18752 (fnh (if (featurep 'xemacs)
18753 (font-height (face-font 'default))
18754 (face-attribute 'default :height nil)))
18755 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18756 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18757 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18758 "black"))
18759 (bg (or (plist-get options (if buffer :background :html-background))
18760 "white")))
18761 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18762 (setq fg (org-latex-color-format fg)))
18763 (if (eq bg 'default) (setq bg (org-latex-color :background))
18764 (setq bg (org-latex-color-format
18765 (if (string= bg "Transparent") "white" bg))))
18766 (let ((latex-header (org-create-formula--latex-header)))
18767 (with-temp-file texfile
18768 (insert latex-header)
18769 (insert "\n\\begin{document}\n"
18770 "\\definecolor{fg}{rgb}{" fg "}\n"
18771 "\\definecolor{bg}{rgb}{" bg "}\n"
18772 "\n\\pagecolor{bg}\n"
18773 "\n{\\color{fg}\n"
18774 string
18775 "\n}\n"
18776 "\n\\end{document}\n")))
18777 (org-latex-compile texfile t)
18778 (if (not (file-exists-p pdffile))
18779 (progn (message "Failed to create pdf file from %s" texfile) nil)
18780 (condition-case nil
18781 (if (featurep 'xemacs)
18782 (call-process "convert" nil nil nil
18783 "-density" "96"
18784 "-trim"
18785 "-antialias"
18786 pdffile
18787 "-quality" "100"
18788 ;; "-sharpen" "0x1.0"
18789 pngfile)
18790 (call-process "convert" nil nil nil
18791 "-density" dpi
18792 "-trim"
18793 "-antialias"
18794 pdffile
18795 "-quality" "100"
18796 ;; "-sharpen" "0x1.0"
18797 pngfile))
18798 (error nil))
18799 (if (not (file-exists-p pngfile))
18800 (if org-format-latex-signal-error
18801 (error "Failed to create png file from %s" texfile)
18802 (message "Failed to create png file from %s" texfile)
18803 nil)
18804 ;; Use the requested file name and clean up
18805 (copy-file pngfile tofile 'replace)
18806 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18807 (if (file-exists-p (concat texfilebase e))
18808 (delete-file (concat texfilebase e))))
18809 pngfile))))
18810
18811 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18812 "Fill a LaTeX header template TPL.
18813 In the template, the following place holders will be recognized:
18814
18815 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18816 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18817 [PACKAGES] \\usepackage statements for PKG
18818 [NO-PACKAGES] do not include PKG
18819 [EXTRA] the string EXTRA
18820 [NO-EXTRA] do not include EXTRA
18821
18822 For backward compatibility, if both the positive and the negative place
18823 holder is missing, the positive one (without the \"NO-\") will be
18824 assumed to be present at the end of the template.
18825 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18826 EXTRA is a string.
18827 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18828 (let (rpl (end ""))
18829 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18830 (setq rpl (if (or (match-end 1) (not def-pkg))
18831 "" (org-latex-packages-to-string def-pkg snippets-p t))
18832 tpl (replace-match rpl t t tpl))
18833 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18834
18835 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18836 (setq rpl (if (or (match-end 1) (not pkg))
18837 "" (org-latex-packages-to-string pkg snippets-p t))
18838 tpl (replace-match rpl t t tpl))
18839 (if pkg (setq end
18840 (concat end "\n"
18841 (org-latex-packages-to-string pkg snippets-p)))))
18842
18843 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18844 (setq rpl (if (or (match-end 1) (not extra))
18845 "" (concat extra "\n"))
18846 tpl (replace-match rpl t t tpl))
18847 (if (and extra (string-match "\\S-" extra))
18848 (setq end (concat end "\n" extra))))
18849
18850 (if (string-match "\\S-" end)
18851 (concat tpl "\n" end)
18852 tpl)))
18853
18854 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18855 "Turn an alist of packages into a string with the \\usepackage macros."
18856 (setq pkg (mapconcat (lambda(p)
18857 (cond
18858 ((stringp p) p)
18859 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18860 (format "%% Package %s omitted" (cadr p)))
18861 ((equal "" (car p))
18862 (format "\\usepackage{%s}" (cadr p)))
18863 (t
18864 (format "\\usepackage[%s]{%s}"
18865 (car p) (cadr p)))))
18866 pkg
18867 "\n"))
18868 (if newline (concat pkg "\n") pkg))
18869
18870 (defun org-dvipng-color (attr)
18871 "Return a RGB color specification for dvipng."
18872 (apply 'format "rgb %s %s %s"
18873 (mapcar 'org-normalize-color
18874 (if (featurep 'xemacs)
18875 (color-rgb-components
18876 (face-property 'default
18877 (cond ((eq attr :foreground) 'foreground)
18878 ((eq attr :background) 'background))))
18879 (color-values (face-attribute 'default attr nil))))))
18880
18881 (defun org-dvipng-color-format (color-name)
18882 "Convert COLOR-NAME to a RGB color value for dvipng."
18883 (apply 'format "rgb %s %s %s"
18884 (mapcar 'org-normalize-color
18885 (color-values color-name))))
18886
18887 (defun org-latex-color (attr)
18888 "Return a RGB color for the LaTeX color package."
18889 (apply 'format "%s,%s,%s"
18890 (mapcar 'org-normalize-color
18891 (if (featurep 'xemacs)
18892 (color-rgb-components
18893 (face-property 'default
18894 (cond ((eq attr :foreground) 'foreground)
18895 ((eq attr :background) 'background))))
18896 (color-values (face-attribute 'default attr nil))))))
18897
18898 (defun org-latex-color-format (color-name)
18899 "Convert COLOR-NAME to a RGB color value."
18900 (apply 'format "%s,%s,%s"
18901 (mapcar 'org-normalize-color
18902 (color-values color-name))))
18903
18904 (defun org-normalize-color (value)
18905 "Return string to be used as color value for an RGB component."
18906 (format "%g" (/ value 65535.0)))
18907
18908
18909 \f
18910 ;; Image display
18911
18912 (defvar org-inline-image-overlays nil)
18913 (make-variable-buffer-local 'org-inline-image-overlays)
18914
18915 (defun org-toggle-inline-images (&optional include-linked)
18916 "Toggle the display of inline images.
18917 INCLUDE-LINKED is passed to `org-display-inline-images'."
18918 (interactive "P")
18919 (if org-inline-image-overlays
18920 (progn
18921 (org-remove-inline-images)
18922 (message "Inline image display turned off"))
18923 (org-display-inline-images include-linked)
18924 (if (and (org-called-interactively-p)
18925 org-inline-image-overlays)
18926 (message "%d images displayed inline"
18927 (length org-inline-image-overlays))
18928 (message "No images to display inline"))))
18929
18930 (defun org-redisplay-inline-images ()
18931 "Refresh the display of inline images."
18932 (interactive)
18933 (if (not org-inline-image-overlays)
18934 (org-toggle-inline-images)
18935 (org-toggle-inline-images)
18936 (org-toggle-inline-images)))
18937
18938 (defun org-display-inline-images (&optional include-linked refresh beg end)
18939 "Display inline images.
18940 Normally only links without a description part are inlined, because this
18941 is how it will work for export. When INCLUDE-LINKED is set, also links
18942 with a description part will be inlined. This can be nice for a quick
18943 look at those images, but it does not reflect what exported files will look
18944 like.
18945 When REFRESH is set, refresh existing images between BEG and END.
18946 This will create new image displays only if necessary.
18947 BEG and END default to the buffer boundaries."
18948 (interactive "P")
18949 (when (display-graphic-p)
18950 (unless refresh
18951 (org-remove-inline-images)
18952 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18953 (save-excursion
18954 (save-restriction
18955 (widen)
18956 (setq beg (or beg (point-min)) end (or end (point-max)))
18957 (goto-char beg)
18958 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18959 (substring (org-image-file-name-regexp) 0 -2)
18960 "\\)\\]" (if include-linked "" "\\]")))
18961 (case-fold-search t)
18962 old file ov img type attrwidth width)
18963 (while (re-search-forward re end t)
18964 (setq old (get-char-property-and-overlay (match-beginning 1)
18965 'org-image-overlay)
18966 file (expand-file-name
18967 (concat (or (match-string 3) "") (match-string 4))))
18968 (when (image-type-available-p 'imagemagick)
18969 (setq attrwidth (if (or (listp org-image-actual-width)
18970 (null org-image-actual-width))
18971 (save-excursion
18972 (save-match-data
18973 (when (re-search-backward
18974 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18975 (save-excursion
18976 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18977 (string-to-number (match-string 1))))))
18978 width (cond ((eq org-image-actual-width t) nil)
18979 ((null org-image-actual-width) attrwidth)
18980 ((numberp org-image-actual-width)
18981 org-image-actual-width)
18982 ((listp org-image-actual-width)
18983 (or attrwidth (car org-image-actual-width))))
18984 type (if width 'imagemagick)))
18985 (when (file-exists-p file)
18986 (if (and (car-safe old) refresh)
18987 (image-refresh (overlay-get (cdr old) 'display))
18988 (setq img (save-match-data (create-image file type nil :width width)))
18989 (when img
18990 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18991 (overlay-put ov 'display img)
18992 (overlay-put ov 'face 'default)
18993 (overlay-put ov 'org-image-overlay t)
18994 (overlay-put ov 'modification-hooks
18995 (list 'org-display-inline-remove-overlay))
18996 (push ov org-inline-image-overlays))))))))))
18997
18998 (define-obsolete-function-alias
18999 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19000
19001 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19002 "Remove inline-display overlay if a corresponding region is modified."
19003 (let ((inhibit-modification-hooks t))
19004 (when (and ov after)
19005 (delete ov org-inline-image-overlays)
19006 (delete-overlay ov))))
19007
19008 (defun org-remove-inline-images ()
19009 "Remove inline display of images."
19010 (interactive)
19011 (mapc 'delete-overlay org-inline-image-overlays)
19012 (setq org-inline-image-overlays nil))
19013
19014 ;;;; Key bindings
19015
19016 ;; Outline functions from `outline-mode-prefix-map'
19017 ;; that can be remapped in Org:
19018 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19019 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19020 (define-key org-mode-map [remap outline-forward-same-level]
19021 'org-forward-heading-same-level)
19022 (define-key org-mode-map [remap outline-backward-same-level]
19023 'org-backward-heading-same-level)
19024 (define-key org-mode-map [remap show-branches]
19025 'org-kill-note-or-show-branches)
19026 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19027 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19028 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19029
19030 ;; Outline functions from `outline-mode-prefix-map' that can not
19031 ;; be remapped in Org:
19032 ;;
19033 ;; - the column "key binding" shows whether the Outline function is still
19034 ;; available in Org mode on the same key that it has been bound to in
19035 ;; Outline mode:
19036 ;; - "overridden": key used for a different functionality in Org mode
19037 ;; - else: key still bound to the same Outline function in Org mode
19038 ;;
19039 ;; | Outline function | key binding | Org replacement |
19040 ;; |------------------------------------+-------------+-----------------------|
19041 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19042 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19043 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19044 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19045 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19046 ;; | `show-entry' | overridden | no replacement |
19047 ;; | `show-children' | `C-c C-i' | visibility cycling |
19048 ;; | `show-branches' | `C-c C-k' | still same function |
19049 ;; | `show-subtree' | overridden | visibility cycling |
19050 ;; | `show-all' | overridden | no replacement |
19051 ;; | `hide-subtree' | overridden | visibility cycling |
19052 ;; | `hide-body' | overridden | no replacement |
19053 ;; | `hide-entry' | overridden | visibility cycling |
19054 ;; | `hide-leaves' | overridden | no replacement |
19055 ;; | `hide-sublevels' | overridden | no replacement |
19056 ;; | `hide-other' | overridden | no replacement |
19057
19058 ;; Make `C-c C-x' a prefix key
19059 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19060
19061 ;; TAB key with modifiers
19062 (org-defkey org-mode-map "\C-i" 'org-cycle)
19063 (org-defkey org-mode-map [(tab)] 'org-cycle)
19064 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19065 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19066 ;; The following line is necessary under Suse GNU/Linux
19067 (unless (featurep 'xemacs)
19068 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19069 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19070 (define-key org-mode-map [backtab] 'org-shifttab)
19071
19072 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19073 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19074 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19075
19076 ;; Cursor keys with modifiers
19077 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19078 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19079 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19080 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19081
19082 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19083 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19084 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19085 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19086
19087 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19088 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19089 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19090 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19091
19092 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19093 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19094 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19095 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19096
19097 ;; Babel keys
19098 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19099 (mapc (lambda (pair)
19100 (define-key org-babel-map (car pair) (cdr pair)))
19101 org-babel-key-bindings)
19102
19103 ;;; Extra keys for tty access.
19104 ;; We only set them when really needed because otherwise the
19105 ;; menus don't show the simple keys
19106
19107 (when (or org-use-extra-keys
19108 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19109 (not window-system))
19110 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19111 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19112 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19113 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19114 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19115 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19116 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19117 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19118 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19119 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19120 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19121 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19122 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19123 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19124 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19125 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19126 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19127 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19128 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19129 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19130 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19131 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19132 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19133 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19134 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19135 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19136 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19137 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19138
19139 ;; All the other keys
19140
19141 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19142 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19143 (if (boundp 'narrow-map)
19144 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19145 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19146 (if (boundp 'narrow-map)
19147 (org-defkey narrow-map "b" 'org-narrow-to-block)
19148 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19149 (if (boundp 'narrow-map)
19150 (org-defkey narrow-map "e" 'org-narrow-to-element)
19151 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19152 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19153 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19154 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19155 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19156 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19157 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19158 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19159 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19160 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19161 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19162 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19163 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19164 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19165 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19166 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19167 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19168 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19169 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19170 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19171 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19172 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19173 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19174 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19175 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19176 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19177 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19178 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19179 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19180 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19181 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19182 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19183 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19184 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19185 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19186 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19187 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19188 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19189 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19190 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19191 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19192 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19193 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19194 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19195 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19196 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19197 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19198 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19199 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19200 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19201 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19202 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19203 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19204 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19205 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19206 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19207 (org-defkey org-mode-map "\C-c^" 'org-sort)
19208 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19209 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19210 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19211 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19212 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19213 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19214 (org-defkey org-mode-map "\C-m" 'org-return)
19215 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19216 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19217 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19218 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19219 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19220 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19221 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19222 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19223 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19224 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19225 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19226 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19227 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19228 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19229 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19230 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19231 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19232 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19233 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19234 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19235 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19236 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19237 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19238
19239 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19240 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19241 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19242
19243 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19244 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19245 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19246 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19247 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19248 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19249 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19250 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19251 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19252 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19253 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19254 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19255 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19256 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19257 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19258 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19259 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19260 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19261 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19262 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19263 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19264 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19265 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19266
19267 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19268 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19269 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19270 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19271 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19272
19273 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19274
19275 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19276
19277 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19278 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19279
19280 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19281
19282
19283 (when (featurep 'xemacs)
19284 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19285
19286
19287 (defconst org-speed-commands-default
19288 '(
19289 ("Outline Navigation")
19290 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19291 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19292 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19293 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19294 ("F" . org-next-block)
19295 ("B" . org-previous-block)
19296 ("u" . (org-speed-move-safe 'outline-up-heading))
19297 ("j" . org-goto)
19298 ("g" . (org-refile t))
19299 ("Outline Visibility")
19300 ("c" . org-cycle)
19301 ("C" . org-shifttab)
19302 (" " . org-display-outline-path)
19303 ("s" . org-narrow-to-subtree)
19304 ("=" . org-columns)
19305 ("Outline Structure Editing")
19306 ("U" . org-shiftmetaup)
19307 ("D" . org-shiftmetadown)
19308 ("r" . org-metaright)
19309 ("l" . org-metaleft)
19310 ("R" . org-shiftmetaright)
19311 ("L" . org-shiftmetaleft)
19312 ("i" . (progn (forward-char 1) (call-interactively
19313 'org-insert-heading-respect-content)))
19314 ("^" . org-sort)
19315 ("w" . org-refile)
19316 ("a" . org-archive-subtree-default-with-confirmation)
19317 ("@" . org-mark-subtree)
19318 ("#" . org-toggle-comment)
19319 ("Clock Commands")
19320 ("I" . org-clock-in)
19321 ("O" . org-clock-out)
19322 ("Meta Data Editing")
19323 ("t" . org-todo)
19324 ("," . (org-priority))
19325 ("0" . (org-priority ?\ ))
19326 ("1" . (org-priority ?A))
19327 ("2" . (org-priority ?B))
19328 ("3" . (org-priority ?C))
19329 (":" . org-set-tags-command)
19330 ("e" . org-set-effort)
19331 ("E" . org-inc-effort)
19332 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19333 (org-entry-put (point) "APPT_WARNTIME" m)))
19334 ("Agenda Views etc")
19335 ("v" . org-agenda)
19336 ("/" . org-sparse-tree)
19337 ("Misc")
19338 ("o" . org-open-at-point)
19339 ("?" . org-speed-command-help)
19340 ("<" . (org-agenda-set-restriction-lock 'subtree))
19341 (">" . (org-agenda-remove-restriction-lock))
19342 )
19343 "The default speed commands.")
19344
19345 (defun org-print-speed-command (e)
19346 (if (> (length (car e)) 1)
19347 (progn
19348 (princ "\n")
19349 (princ (car e))
19350 (princ "\n")
19351 (princ (make-string (length (car e)) ?-))
19352 (princ "\n"))
19353 (princ (car e))
19354 (princ " ")
19355 (if (symbolp (cdr e))
19356 (princ (symbol-name (cdr e)))
19357 (prin1 (cdr e)))
19358 (princ "\n")))
19359
19360 (defun org-speed-command-help ()
19361 "Show the available speed commands."
19362 (interactive)
19363 (if (not org-use-speed-commands)
19364 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19365 (with-output-to-temp-buffer "*Help*"
19366 (princ "User-defined Speed commands\n===========================\n")
19367 (mapc 'org-print-speed-command org-speed-commands-user)
19368 (princ "\n")
19369 (princ "Built-in Speed commands\n=======================\n")
19370 (mapc 'org-print-speed-command org-speed-commands-default))
19371 (with-current-buffer "*Help*"
19372 (setq truncate-lines t))))
19373
19374 (defun org-speed-move-safe (cmd)
19375 "Execute CMD, but make sure that the cursor always ends up in a headline.
19376 If not, return to the original position and throw an error."
19377 (interactive)
19378 (let ((pos (point)))
19379 (call-interactively cmd)
19380 (unless (and (bolp) (org-at-heading-p))
19381 (goto-char pos)
19382 (error "Boundary reached while executing %s" cmd))))
19383
19384 (defvar org-self-insert-command-undo-counter 0)
19385
19386 (defvar org-table-auto-blank-field) ; defined in org-table.el
19387 (defvar org-speed-command nil)
19388
19389 (define-obsolete-function-alias
19390 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19391
19392 (defun org-speed-command-activate (keys)
19393 "Hook for activating single-letter speed commands.
19394 `org-speed-commands-default' specifies a minimal command set.
19395 Use `org-speed-commands-user' for further customization."
19396 (when (or (and (bolp) (looking-at org-outline-regexp))
19397 (and (functionp org-use-speed-commands)
19398 (funcall org-use-speed-commands)))
19399 (cdr (assoc keys (append org-speed-commands-user
19400 org-speed-commands-default)))))
19401
19402 (define-obsolete-function-alias
19403 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19404
19405 (defun org-babel-speed-command-activate (keys)
19406 "Hook for activating single-letter code block commands."
19407 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19408 (cdr (assoc keys org-babel-key-bindings))))
19409
19410 (defcustom org-speed-command-hook
19411 '(org-speed-command-default-hook org-babel-speed-command-hook)
19412 "Hook for activating speed commands at strategic locations.
19413 Hook functions are called in sequence until a valid handler is
19414 found.
19415
19416 Each hook takes a single argument, a user-pressed command key
19417 which is also a `self-insert-command' from the global map.
19418
19419 Within the hook, examine the cursor position and the command key
19420 and return nil or a valid handler as appropriate. Handler could
19421 be one of an interactive command, a function, or a form.
19422
19423 Set `org-use-speed-commands' to non-nil value to enable this
19424 hook. The default setting is `org-speed-command-activate'."
19425 :group 'org-structure
19426 :version "24.1"
19427 :type 'hook)
19428
19429 (defun org-self-insert-command (N)
19430 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19431 If the cursor is in a table looking at whitespace, the whitespace is
19432 overwritten, and the table is not marked as requiring realignment."
19433 (interactive "p")
19434 (org-check-before-invisible-edit 'insert)
19435 (cond
19436 ((and org-use-speed-commands
19437 (setq org-speed-command
19438 (run-hook-with-args-until-success
19439 'org-speed-command-hook (this-command-keys))))
19440 (cond
19441 ((commandp org-speed-command)
19442 (setq this-command org-speed-command)
19443 (call-interactively org-speed-command))
19444 ((functionp org-speed-command)
19445 (funcall org-speed-command))
19446 ((and org-speed-command (listp org-speed-command))
19447 (eval org-speed-command))
19448 (t (let (org-use-speed-commands)
19449 (call-interactively 'org-self-insert-command)))))
19450 ((and
19451 (org-table-p)
19452 (progn
19453 ;; check if we blank the field, and if that triggers align
19454 (and (featurep 'org-table) org-table-auto-blank-field
19455 (member last-command
19456 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19457 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19458 ;; got extra space, this field does not determine column width
19459 (let (org-table-may-need-update) (org-table-blank-field))
19460 ;; no extra space, this field may determine column width
19461 (org-table-blank-field)))
19462 t)
19463 (eq N 1)
19464 (looking-at "[^|\n]* |"))
19465 (let (org-table-may-need-update)
19466 (goto-char (1- (match-end 0)))
19467 (backward-delete-char 1)
19468 (goto-char (match-beginning 0))
19469 (self-insert-command N)))
19470 (t
19471 (setq org-table-may-need-update t)
19472 (self-insert-command N)
19473 (org-fix-tags-on-the-fly)
19474 (if org-self-insert-cluster-for-undo
19475 (if (not (eq last-command 'org-self-insert-command))
19476 (setq org-self-insert-command-undo-counter 1)
19477 (if (>= org-self-insert-command-undo-counter 20)
19478 (setq org-self-insert-command-undo-counter 1)
19479 (and (> org-self-insert-command-undo-counter 0)
19480 buffer-undo-list (listp buffer-undo-list)
19481 (not (cadr buffer-undo-list)) ; remove nil entry
19482 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19483 (setq org-self-insert-command-undo-counter
19484 (1+ org-self-insert-command-undo-counter))))))))
19485
19486 (defun org-check-before-invisible-edit (kind)
19487 "Check is editing if kind KIND would be dangerous with invisible text around.
19488 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19489 ;; First, try to get out of here as quickly as possible, to reduce overhead
19490 (if (and org-catch-invisible-edits
19491 (or (not (boundp 'visible-mode)) (not visible-mode))
19492 (or (get-char-property (point) 'invisible)
19493 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19494 ;; OK, we need to take a closer look
19495 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19496 (invisible-before-point (if (bobp) nil (get-char-property
19497 (1- (point)) 'invisible)))
19498 (border-and-ok-direction
19499 (or
19500 ;; Check if we are acting predictably before invisible text
19501 (and invisible-at-point (not invisible-before-point)
19502 (memq kind '(insert delete-backward)))
19503 ;; Check if we are acting predictably after invisible text
19504 ;; This works not well, and I have turned it off. It seems
19505 ;; better to always show and stop after invisible text.
19506 ;; (and (not invisible-at-point) invisible-before-point
19507 ;; (memq kind '(insert delete)))
19508 )))
19509 (when (or (memq invisible-at-point '(outline org-hide-block t))
19510 (memq invisible-before-point '(outline org-hide-block t)))
19511 (if (eq org-catch-invisible-edits 'error)
19512 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19513 (if (and org-custom-properties-overlays
19514 (y-or-n-p "Display invisible properties in this buffer? "))
19515 (org-toggle-custom-properties-visibility)
19516 ;; Make the area visible
19517 (save-excursion
19518 (if invisible-before-point
19519 (goto-char (previous-single-char-property-change
19520 (point) 'invisible)))
19521 (show-subtree))
19522 (cond
19523 ((eq org-catch-invisible-edits 'show)
19524 ;; That's it, we do the edit after showing
19525 (message
19526 "Unfolding invisible region around point before editing")
19527 (sit-for 1))
19528 ((and (eq org-catch-invisible-edits 'smart)
19529 border-and-ok-direction)
19530 (message "Unfolding invisible region around point before editing"))
19531 (t
19532 ;; Don't do the edit, make the user repeat it in full visibility
19533 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19534
19535 (defun org-fix-tags-on-the-fly ()
19536 (when (and (equal (char-after (point-at-bol)) ?*)
19537 (org-at-heading-p))
19538 (org-align-tags-here org-tags-column)))
19539
19540 (defun org-delete-backward-char (N)
19541 "Like `delete-backward-char', insert whitespace at field end in tables.
19542 When deleting backwards, in tables this function will insert whitespace in
19543 front of the next \"|\" separator, to keep the table aligned. The table will
19544 still be marked for re-alignment if the field did fill the entire column,
19545 because, in this case the deletion might narrow the column."
19546 (interactive "p")
19547 (save-match-data
19548 (org-check-before-invisible-edit 'delete-backward)
19549 (if (and (org-table-p)
19550 (eq N 1)
19551 (string-match "|" (buffer-substring (point-at-bol) (point)))
19552 (looking-at ".*?|"))
19553 (let ((pos (point))
19554 (noalign (looking-at "[^|\n\r]* |"))
19555 (c org-table-may-need-update))
19556 (backward-delete-char N)
19557 (if (not overwrite-mode)
19558 (progn
19559 (skip-chars-forward "^|")
19560 (insert " ")
19561 (goto-char (1- pos))))
19562 ;; noalign: if there were two spaces at the end, this field
19563 ;; does not determine the width of the column.
19564 (if noalign (setq org-table-may-need-update c)))
19565 (backward-delete-char N)
19566 (org-fix-tags-on-the-fly))))
19567
19568 (defun org-delete-char (N)
19569 "Like `delete-char', but insert whitespace at field end in tables.
19570 When deleting characters, in tables this function will insert whitespace in
19571 front of the next \"|\" separator, to keep the table aligned. The table will
19572 still be marked for re-alignment if the field did fill the entire column,
19573 because, in this case the deletion might narrow the column."
19574 (interactive "p")
19575 (save-match-data
19576 (org-check-before-invisible-edit 'delete)
19577 (if (and (org-table-p)
19578 (not (bolp))
19579 (not (= (char-after) ?|))
19580 (eq N 1))
19581 (if (looking-at ".*?|")
19582 (let ((pos (point))
19583 (noalign (looking-at "[^|\n\r]* |"))
19584 (c org-table-may-need-update))
19585 (replace-match
19586 (concat (substring (match-string 0) 1 -1) " |") nil t)
19587 (goto-char pos)
19588 ;; noalign: if there were two spaces at the end, this field
19589 ;; does not determine the width of the column.
19590 (if noalign (setq org-table-may-need-update c)))
19591 (delete-char N))
19592 (delete-char N)
19593 (org-fix-tags-on-the-fly))))
19594
19595 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19596 (put 'org-self-insert-command 'delete-selection
19597 (lambda ()
19598 (not (run-hook-with-args-until-success
19599 'self-insert-uses-region-functions))))
19600 (put 'orgtbl-self-insert-command 'delete-selection
19601 (lambda ()
19602 (not (run-hook-with-args-until-success
19603 'self-insert-uses-region-functions))))
19604 (put 'org-delete-char 'delete-selection 'supersede)
19605 (put 'org-delete-backward-char 'delete-selection 'supersede)
19606 (put 'org-yank 'delete-selection 'yank)
19607
19608 ;; Make `flyspell-mode' delay after some commands
19609 (put 'org-self-insert-command 'flyspell-delayed t)
19610 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19611 (put 'org-delete-char 'flyspell-delayed t)
19612 (put 'org-delete-backward-char 'flyspell-delayed t)
19613
19614 ;; Make pabbrev-mode expand after org-mode commands
19615 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19616 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19617
19618 (defun org-remap (map &rest commands)
19619 "In MAP, remap the functions given in COMMANDS.
19620 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19621 (let (new old)
19622 (while commands
19623 (setq old (pop commands) new (pop commands))
19624 (if (fboundp 'command-remapping)
19625 (org-defkey map (vector 'remap old) new)
19626 (substitute-key-definition old new map global-map)))))
19627
19628 (defun org-transpose-words ()
19629 "Transpose words for Org.
19630 This uses the `org-mode-transpose-word-syntax-table' syntax
19631 table, which interprets characters in `org-emphasis-alist' as
19632 word constituents."
19633 (interactive)
19634 (with-syntax-table org-mode-transpose-word-syntax-table
19635 (call-interactively 'transpose-words)))
19636 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19637
19638 (when (eq org-enable-table-editor 'optimized)
19639 ;; If the user wants maximum table support, we need to hijack
19640 ;; some standard editing functions
19641 (org-remap org-mode-map
19642 'self-insert-command 'org-self-insert-command
19643 'delete-char 'org-delete-char
19644 'delete-backward-char 'org-delete-backward-char)
19645 (org-defkey org-mode-map "|" 'org-force-self-insert))
19646
19647 (defvar org-ctrl-c-ctrl-c-hook nil
19648 "Hook for functions attaching themselves to `C-c C-c'.
19649
19650 This can be used to add additional functionality to the C-c C-c
19651 key which executes context-dependent commands. This hook is run
19652 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19653 run after the last test.
19654
19655 Each function will be called with no arguments. The function
19656 must check if the context is appropriate for it to act. If yes,
19657 it should do its thing and then return a non-nil value. If the
19658 context is wrong, just do nothing and return nil.")
19659
19660 (defvar org-ctrl-c-ctrl-c-final-hook nil
19661 "Hook for functions attaching themselves to `C-c C-c'.
19662
19663 This can be used to add additional functionality to the C-c C-c
19664 key which executes context-dependent commands. This hook is run
19665 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19666 before the first test.
19667
19668 Each function will be called with no arguments. The function
19669 must check if the context is appropriate for it to act. If yes,
19670 it should do its thing and then return a non-nil value. If the
19671 context is wrong, just do nothing and return nil.")
19672
19673 (defvar org-tab-first-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 as the first action when TAB is pressed, even before
19677 `org-cycle' messes around with the `outline-regexp' to cater for
19678 inline tasks and plain list item folding.
19679 If any function in this hook returns t, any other actions that
19680 would have been caused by TAB (such as table field motion or visibility
19681 cycling) will not occur.")
19682
19683 (defvar org-tab-after-check-for-table-hook nil
19684 "Hook for functions to attach themselves to TAB.
19685 See `org-ctrl-c-ctrl-c-hook' for more information.
19686 This hook runs after it has been established that the cursor is not in a
19687 table, but before checking if the cursor is in a headline or if global cycling
19688 should be done.
19689 If any function in this hook returns t, not other actions like visibility
19690 cycling will be done.")
19691
19692 (defvar org-tab-after-check-for-cycling-hook nil
19693 "Hook for functions to attach themselves to TAB.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.
19695 This hook runs after it has been established that not table field motion and
19696 not visibility should be done because of current context. This is probably
19697 the place where a package like yasnippets can hook in.")
19698
19699 (defvar org-tab-before-tab-emulation-hook nil
19700 "Hook for functions to attach themselves to TAB.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.
19702 This hook runs after every other options for TAB have been exhausted, but
19703 before indentation and \t insertion takes place.")
19704
19705 (defvar org-metaleft-hook nil
19706 "Hook for functions attaching themselves to `M-left'.
19707 See `org-ctrl-c-ctrl-c-hook' for more information.")
19708 (defvar org-metaright-hook nil
19709 "Hook for functions attaching themselves to `M-right'.
19710 See `org-ctrl-c-ctrl-c-hook' for more information.")
19711 (defvar org-metaup-hook nil
19712 "Hook for functions attaching themselves to `M-up'.
19713 See `org-ctrl-c-ctrl-c-hook' for more information.")
19714 (defvar org-metadown-hook nil
19715 "Hook for functions attaching themselves to `M-down'.
19716 See `org-ctrl-c-ctrl-c-hook' for more information.")
19717 (defvar org-shiftmetaleft-hook nil
19718 "Hook for functions attaching themselves to `M-S-left'.
19719 See `org-ctrl-c-ctrl-c-hook' for more information.")
19720 (defvar org-shiftmetaright-hook nil
19721 "Hook for functions attaching themselves to `M-S-right'.
19722 See `org-ctrl-c-ctrl-c-hook' for more information.")
19723 (defvar org-shiftmetaup-hook nil
19724 "Hook for functions attaching themselves to `M-S-up'.
19725 See `org-ctrl-c-ctrl-c-hook' for more information.")
19726 (defvar org-shiftmetadown-hook nil
19727 "Hook for functions attaching themselves to `M-S-down'.
19728 See `org-ctrl-c-ctrl-c-hook' for more information.")
19729 (defvar org-metareturn-hook nil
19730 "Hook for functions attaching themselves to `M-RET'.
19731 See `org-ctrl-c-ctrl-c-hook' for more information.")
19732 (defvar org-shiftup-hook nil
19733 "Hook for functions attaching themselves to `S-up'.
19734 See `org-ctrl-c-ctrl-c-hook' for more information.")
19735 (defvar org-shiftup-final-hook nil
19736 "Hook for functions attaching themselves to `S-up'.
19737 This one runs after all other options except shift-select have been excluded.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftdown-hook nil
19740 "Hook for functions attaching themselves to `S-down'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-shiftdown-final-hook nil
19743 "Hook for functions attaching themselves to `S-down'.
19744 This one runs after all other options except shift-select have been excluded.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.")
19746 (defvar org-shiftleft-hook nil
19747 "Hook for functions attaching themselves to `S-left'.
19748 See `org-ctrl-c-ctrl-c-hook' for more information.")
19749 (defvar org-shiftleft-final-hook nil
19750 "Hook for functions attaching themselves to `S-left'.
19751 This one runs after all other options except shift-select have been excluded.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-shiftright-hook nil
19754 "Hook for functions attaching themselves to `S-right'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-shiftright-final-hook nil
19757 "Hook for functions attaching themselves to `S-right'.
19758 This one runs after all other options except shift-select have been excluded.
19759 See `org-ctrl-c-ctrl-c-hook' for more information.")
19760
19761 (defun org-modifier-cursor-error ()
19762 "Throw an error, a modified cursor command was applied in wrong context."
19763 (user-error "This command is active in special context like tables, headlines or items"))
19764
19765 (defun org-shiftselect-error ()
19766 "Throw an error because Shift-Cursor command was applied in wrong context."
19767 (if (and (boundp 'shift-select-mode) shift-select-mode)
19768 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19769 (user-error "This command works only in special context like headlines or timestamps")))
19770
19771 (defun org-call-for-shift-select (cmd)
19772 (let ((this-command-keys-shift-translated t))
19773 (call-interactively cmd)))
19774
19775 (defun org-shifttab (&optional arg)
19776 "Global visibility cycling or move to previous table field.
19777 Call `org-table-previous-field' within a table.
19778 When ARG is nil, cycle globally through visibility states.
19779 When ARG is a numeric prefix, show contents of this level."
19780 (interactive "P")
19781 (cond
19782 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19783 ((integerp arg)
19784 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19785 (message "Content view to level: %d" arg)
19786 (org-content (prefix-numeric-value arg2))
19787 (org-cycle-show-empty-lines t)
19788 (setq org-cycle-global-status 'overview)))
19789 (t (call-interactively 'org-global-cycle))))
19790
19791 (defun org-shiftmetaleft ()
19792 "Promote subtree or delete table column.
19793 Calls `org-promote-subtree', `org-outdent-item-tree', or
19794 `org-table-delete-column', depending on context. See the
19795 individual commands for more information."
19796 (interactive)
19797 (cond
19798 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19799 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19800 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19801 ((if (not (org-region-active-p)) (org-at-item-p)
19802 (save-excursion (goto-char (region-beginning))
19803 (org-at-item-p)))
19804 (call-interactively 'org-outdent-item-tree))
19805 (t (org-modifier-cursor-error))))
19806
19807 (defun org-shiftmetaright ()
19808 "Demote subtree or insert table column.
19809 Calls `org-demote-subtree', `org-indent-item-tree', or
19810 `org-table-insert-column', depending on context. See the
19811 individual commands for more information."
19812 (interactive)
19813 (cond
19814 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19815 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19816 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19817 ((if (not (org-region-active-p)) (org-at-item-p)
19818 (save-excursion (goto-char (region-beginning))
19819 (org-at-item-p)))
19820 (call-interactively 'org-indent-item-tree))
19821 (t (org-modifier-cursor-error))))
19822
19823 (defun org-shiftmetaup (&optional arg)
19824 "Move subtree up or kill table row.
19825 Calls `org-move-subtree-up' or `org-table-kill-row' or
19826 `org-move-item-up' or `org-timestamp-up', depending on context.
19827 See the individual commands for more information."
19828 (interactive "P")
19829 (cond
19830 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19831 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19832 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19833 ((org-at-item-p) (call-interactively 'org-move-item-up))
19834 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19835 (call-interactively 'org-timestamp-up)))
19836 (t (call-interactively 'org-drag-line-backward))))
19837
19838 (defun org-shiftmetadown (&optional arg)
19839 "Move subtree down or insert table row.
19840 Calls `org-move-subtree-down' or `org-table-insert-row' or
19841 `org-move-item-down' or `org-timestamp-up', depending on context.
19842 See the individual commands for more information."
19843 (interactive "P")
19844 (cond
19845 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19846 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19847 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19848 ((org-at-item-p) (call-interactively 'org-move-item-down))
19849 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19850 (call-interactively 'org-timestamp-down)))
19851 (t (call-interactively 'org-drag-line-forward))))
19852
19853 (defsubst org-hidden-tree-error ()
19854 (user-error
19855 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19856
19857 (defun org-metaleft (&optional arg)
19858 "Promote heading or move table column to left.
19859 Calls `org-do-promote' or `org-table-move-column', depending on context.
19860 With no specific context, calls the Emacs default `backward-word'.
19861 See the individual commands for more information."
19862 (interactive "P")
19863 (cond
19864 ((run-hook-with-args-until-success 'org-metaleft-hook))
19865 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19866 ((org-with-limited-levels
19867 (or (org-at-heading-p)
19868 (and (org-region-active-p)
19869 (save-excursion
19870 (goto-char (region-beginning))
19871 (org-at-heading-p)))))
19872 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19873 (call-interactively 'org-do-promote))
19874 ;; At an inline task.
19875 ((org-at-heading-p)
19876 (call-interactively 'org-inlinetask-promote))
19877 ((or (org-at-item-p)
19878 (and (org-region-active-p)
19879 (save-excursion
19880 (goto-char (region-beginning))
19881 (org-at-item-p))))
19882 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19883 (call-interactively 'org-outdent-item))
19884 (t (call-interactively 'backward-word))))
19885
19886 (defun org-metaright (&optional arg)
19887 "Demote a subtree, a list item or move table column to right.
19888 In front of a drawer or a block keyword, indent it correctly.
19889 With no specific context, calls the Emacs default `forward-word'.
19890 See the individual commands for more information."
19891 (interactive "P")
19892 (cond
19893 ((run-hook-with-args-until-success 'org-metaright-hook))
19894 ((org-at-table-p) (call-interactively 'org-table-move-column))
19895 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19896 ((org-at-block-p) (call-interactively 'org-indent-block))
19897 ((org-with-limited-levels
19898 (or (org-at-heading-p)
19899 (and (org-region-active-p)
19900 (save-excursion
19901 (goto-char (region-beginning))
19902 (org-at-heading-p)))))
19903 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19904 (call-interactively 'org-do-demote))
19905 ;; At an inline task.
19906 ((org-at-heading-p)
19907 (call-interactively 'org-inlinetask-demote))
19908 ((or (org-at-item-p)
19909 (and (org-region-active-p)
19910 (save-excursion
19911 (goto-char (region-beginning))
19912 (org-at-item-p))))
19913 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19914 (call-interactively 'org-indent-item))
19915 (t (call-interactively 'forward-word))))
19916
19917 (defun org-check-for-hidden (what)
19918 "Check if there are hidden headlines/items in the current visual line.
19919 WHAT can be either `headlines' or `items'. If the current line is
19920 an outline or item heading and it has a folded subtree below it,
19921 this function returns t, nil otherwise."
19922 (let ((re (cond
19923 ((eq what 'headlines) org-outline-regexp-bol)
19924 ((eq what 'items) (org-item-beginning-re))
19925 (t (error "This should not happen"))))
19926 beg end)
19927 (save-excursion
19928 (catch 'exit
19929 (unless (org-region-active-p)
19930 (setq beg (point-at-bol))
19931 (beginning-of-line 2)
19932 (while (and (not (eobp)) ;; this is like `next-line'
19933 (get-char-property (1- (point)) 'invisible))
19934 (beginning-of-line 2))
19935 (setq end (point))
19936 (goto-char beg)
19937 (goto-char (point-at-eol))
19938 (setq end (max end (point)))
19939 (while (re-search-forward re end t)
19940 (if (get-char-property (match-beginning 0) 'invisible)
19941 (throw 'exit t))))
19942 nil))))
19943
19944 (defun org-metaup (&optional arg)
19945 "Move subtree up or move table row up.
19946 Calls `org-move-subtree-up' or `org-table-move-row' or
19947 `org-move-item-up', depending on context. See the individual commands
19948 for more information."
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-metaup-hook))
19952 ((org-region-active-p)
19953 (let* ((a (min (region-beginning) (region-end)))
19954 (b (1- (max (region-beginning) (region-end))))
19955 (c (save-excursion (goto-char a)
19956 (move-beginning-of-line 0)))
19957 (d (save-excursion (goto-char a)
19958 (move-end-of-line 0) (point))))
19959 (transpose-regions a b c d)
19960 (goto-char c)))
19961 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19962 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19963 ((org-at-item-p) (call-interactively 'org-move-item-up))
19964 (t (org-drag-element-backward))))
19965
19966 (defun org-metadown (&optional arg)
19967 "Move subtree down or move table row down.
19968 Calls `org-move-subtree-down' or `org-table-move-row' or
19969 `org-move-item-down', depending on context. See the individual
19970 commands for more information."
19971 (interactive "P")
19972 (cond
19973 ((run-hook-with-args-until-success 'org-metadown-hook))
19974 ((org-region-active-p)
19975 (let* ((a (min (region-beginning) (region-end)))
19976 (b (max (region-beginning) (region-end)))
19977 (c (save-excursion (goto-char b)
19978 (move-beginning-of-line 1)))
19979 (d (save-excursion (goto-char b)
19980 (move-end-of-line 1) (1+ (point)))))
19981 (transpose-regions a b c d)
19982 (goto-char d)))
19983 ((org-at-table-p) (call-interactively 'org-table-move-row))
19984 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19985 ((org-at-item-p) (call-interactively 'org-move-item-down))
19986 (t (org-drag-element-forward))))
19987
19988 (defun org-shiftup (&optional arg)
19989 "Increase item in timestamp or increase priority of current headline.
19990 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19991 depending on context. See the individual commands for more information."
19992 (interactive "P")
19993 (cond
19994 ((run-hook-with-args-until-success 'org-shiftup-hook))
19995 ((and org-support-shift-select (org-region-active-p))
19996 (org-call-for-shift-select 'previous-line))
19997 ((org-at-timestamp-p t)
19998 (call-interactively (if org-edit-timestamp-down-means-later
19999 'org-timestamp-down 'org-timestamp-up)))
20000 ((and (not (eq org-support-shift-select 'always))
20001 org-enable-priority-commands
20002 (org-at-heading-p))
20003 (call-interactively 'org-priority-up))
20004 ((and (not org-support-shift-select) (org-at-item-p))
20005 (call-interactively 'org-previous-item))
20006 ((org-clocktable-try-shift 'up arg))
20007 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20008 (org-support-shift-select
20009 (org-call-for-shift-select 'previous-line))
20010 (t (org-shiftselect-error))))
20011
20012 (defun org-shiftdown (&optional arg)
20013 "Decrease item in timestamp or decrease priority of current headline.
20014 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20015 depending on context. See the individual commands for more information."
20016 (interactive "P")
20017 (cond
20018 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20019 ((and org-support-shift-select (org-region-active-p))
20020 (org-call-for-shift-select 'next-line))
20021 ((org-at-timestamp-p t)
20022 (call-interactively (if org-edit-timestamp-down-means-later
20023 'org-timestamp-up 'org-timestamp-down)))
20024 ((and (not (eq org-support-shift-select 'always))
20025 org-enable-priority-commands
20026 (org-at-heading-p))
20027 (call-interactively 'org-priority-down))
20028 ((and (not org-support-shift-select) (org-at-item-p))
20029 (call-interactively 'org-next-item))
20030 ((org-clocktable-try-shift 'down arg))
20031 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20032 (org-support-shift-select
20033 (org-call-for-shift-select 'next-line))
20034 (t (org-shiftselect-error))))
20035
20036 (defun org-shiftright (&optional arg)
20037 "Cycle the thing at point or in the current line, depending on context.
20038 Depending on context, this does one of the following:
20039
20040 - switch a timestamp at point one day into the future
20041 - on a headline, switch to the next TODO keyword.
20042 - on an item, switch entire list to the next bullet type
20043 - on a property line, switch to the next allowed value
20044 - on a clocktable definition line, move time block into the future"
20045 (interactive "P")
20046 (cond
20047 ((run-hook-with-args-until-success 'org-shiftright-hook))
20048 ((and org-support-shift-select (org-region-active-p))
20049 (org-call-for-shift-select 'forward-char))
20050 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20051 ((and (not (eq org-support-shift-select 'always))
20052 (org-at-heading-p))
20053 (let ((org-inhibit-logging
20054 (not org-treat-S-cursor-todo-selection-as-state-change))
20055 (org-inhibit-blocking
20056 (not org-treat-S-cursor-todo-selection-as-state-change)))
20057 (org-call-with-arg 'org-todo 'right)))
20058 ((or (and org-support-shift-select
20059 (not (eq org-support-shift-select 'always))
20060 (org-at-item-bullet-p))
20061 (and (not org-support-shift-select) (org-at-item-p)))
20062 (org-call-with-arg 'org-cycle-list-bullet nil))
20063 ((and (not (eq org-support-shift-select 'always))
20064 (org-at-property-p))
20065 (call-interactively 'org-property-next-allowed-value))
20066 ((org-clocktable-try-shift 'right arg))
20067 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20068 (org-support-shift-select
20069 (org-call-for-shift-select 'forward-char))
20070 (t (org-shiftselect-error))))
20071
20072 (defun org-shiftleft (&optional arg)
20073 "Cycle the thing at point or in the current line, depending on context.
20074 Depending on context, this does one of the following:
20075
20076 - switch a timestamp at point one day into the past
20077 - on a headline, switch to the previous TODO keyword.
20078 - on an item, switch entire list to the previous bullet type
20079 - on a property line, switch to the previous allowed value
20080 - on a clocktable definition line, move time block into the past"
20081 (interactive "P")
20082 (cond
20083 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20084 ((and org-support-shift-select (org-region-active-p))
20085 (org-call-for-shift-select 'backward-char))
20086 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20087 ((and (not (eq org-support-shift-select 'always))
20088 (org-at-heading-p))
20089 (let ((org-inhibit-logging
20090 (not org-treat-S-cursor-todo-selection-as-state-change))
20091 (org-inhibit-blocking
20092 (not org-treat-S-cursor-todo-selection-as-state-change)))
20093 (org-call-with-arg 'org-todo 'left)))
20094 ((or (and org-support-shift-select
20095 (not (eq org-support-shift-select 'always))
20096 (org-at-item-bullet-p))
20097 (and (not org-support-shift-select) (org-at-item-p)))
20098 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20099 ((and (not (eq org-support-shift-select 'always))
20100 (org-at-property-p))
20101 (call-interactively 'org-property-previous-allowed-value))
20102 ((org-clocktable-try-shift 'left arg))
20103 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20104 (org-support-shift-select
20105 (org-call-for-shift-select 'backward-char))
20106 (t (org-shiftselect-error))))
20107
20108 (defun org-shiftcontrolright ()
20109 "Switch to next TODO set."
20110 (interactive)
20111 (cond
20112 ((and org-support-shift-select (org-region-active-p))
20113 (org-call-for-shift-select 'forward-word))
20114 ((and (not (eq org-support-shift-select 'always))
20115 (org-at-heading-p))
20116 (org-call-with-arg 'org-todo 'nextset))
20117 (org-support-shift-select
20118 (org-call-for-shift-select 'forward-word))
20119 (t (org-shiftselect-error))))
20120
20121 (defun org-shiftcontrolleft ()
20122 "Switch to previous TODO set."
20123 (interactive)
20124 (cond
20125 ((and org-support-shift-select (org-region-active-p))
20126 (org-call-for-shift-select 'backward-word))
20127 ((and (not (eq org-support-shift-select 'always))
20128 (org-at-heading-p))
20129 (org-call-with-arg 'org-todo 'previousset))
20130 (org-support-shift-select
20131 (org-call-for-shift-select 'backward-word))
20132 (t (org-shiftselect-error))))
20133
20134 (defun org-shiftcontrolup (&optional n)
20135 "Change timestamps synchronously up in CLOCK log lines.
20136 Optional argument N tells to change by that many units."
20137 (interactive "P")
20138 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20139 (let (org-support-shift-select)
20140 (org-clock-timestamps-up n))
20141 (user-error "Not at a clock log")))
20142
20143 (defun org-shiftcontroldown (&optional n)
20144 "Change timestamps synchronously down in CLOCK log lines.
20145 Optional argument N tells to change by that many units."
20146 (interactive "P")
20147 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20148 (let (org-support-shift-select)
20149 (org-clock-timestamps-down n))
20150 (user-error "Not at a clock log")))
20151
20152 (defun org-ctrl-c-ret ()
20153 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20154 (interactive)
20155 (cond
20156 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20157 (t (call-interactively 'org-insert-heading))))
20158
20159 (defun org-find-visible ()
20160 (let ((s (point)))
20161 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20162 (get-char-property s 'invisible)))
20163 s))
20164 (defun org-find-invisible ()
20165 (let ((s (point)))
20166 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20167 (not (get-char-property s 'invisible))))
20168 s))
20169
20170 (defun org-copy-visible (beg end)
20171 "Copy the visible parts of the region."
20172 (interactive "r")
20173 (let (snippets s)
20174 (save-excursion
20175 (save-restriction
20176 (narrow-to-region beg end)
20177 (setq s (goto-char (point-min)))
20178 (while (not (= (point) (point-max)))
20179 (goto-char (org-find-invisible))
20180 (push (buffer-substring s (point)) snippets)
20181 (setq s (goto-char (org-find-visible))))))
20182 (kill-new (apply 'concat (nreverse snippets)))))
20183
20184 (defun org-copy-special ()
20185 "Copy region in table or copy current subtree.
20186 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20187 See the individual commands for more information."
20188 (interactive)
20189 (call-interactively
20190 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20191
20192 (defun org-cut-special ()
20193 "Cut region in table or cut current subtree.
20194 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20195 See the individual commands for more information."
20196 (interactive)
20197 (call-interactively
20198 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20199
20200 (defun org-paste-special (arg)
20201 "Paste rectangular region into table, or past subtree relative to level.
20202 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20203 See the individual commands for more information."
20204 (interactive "P")
20205 (if (org-at-table-p)
20206 (org-table-paste-rectangle)
20207 (org-paste-subtree arg)))
20208
20209 (defsubst org-in-fixed-width-region-p ()
20210 "Is point in a fixed-width region?"
20211 (save-match-data
20212 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20213
20214 (defun org-edit-special (&optional arg)
20215 "Call a special editor for the element at point.
20216 When at a table, call the formula editor with `org-table-edit-formulas'.
20217 When in a source code block, call `org-edit-src-code'.
20218 When in a fixed-width region, call `org-edit-fixed-width-region'.
20219 When at an #+INCLUDE keyword, visit the included file.
20220 On a link, call `ffap' to visit the link at point.
20221 Otherwise, return a user error."
20222 (interactive "P")
20223 (let ((element (org-element-at-point)))
20224 (assert (not buffer-read-only) nil
20225 "Buffer is read-only: %s" (buffer-name))
20226 (case (org-element-type element)
20227 (src-block
20228 (if (not arg) (org-edit-src-code)
20229 (let* ((info (org-babel-get-src-block-info))
20230 (lang (nth 0 info))
20231 (params (nth 2 info))
20232 (session (cdr (assq :session params))))
20233 (if (not session) (org-edit-src-code)
20234 ;; At a src-block with a session and function called with
20235 ;; an ARG: switch to the buffer related to the inferior
20236 ;; process.
20237 (switch-to-buffer
20238 (funcall (intern (concat "org-babel-prep-session:" lang))
20239 session params))))))
20240 (keyword
20241 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20242 (find-file
20243 (org-remove-double-quotes
20244 (car (org-split-string (org-element-property :value element)))))
20245 (user-error "No special environment to edit here")))
20246 (table
20247 (if (eq (org-element-property :type element) 'table.el)
20248 (org-edit-src-code)
20249 (call-interactively 'org-table-edit-formulas)))
20250 ;; Only Org tables contain `table-row' type elements.
20251 (table-row (call-interactively 'org-table-edit-formulas))
20252 ((example-block export-block) (org-edit-src-code))
20253 (fixed-width (org-edit-fixed-width-region))
20254 (otherwise
20255 ;; No notable element at point. Though, we may be at a link,
20256 ;; which is an object. Thus, scan deeper.
20257 (if (eq (org-element-type (org-element-context element)) 'link)
20258 (call-interactively 'ffap)
20259 (user-error "No special environment to edit here"))))))
20260
20261 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20262 (defun org-ctrl-c-ctrl-c (&optional arg)
20263 "Set tags in headline, or update according to changed information at point.
20264
20265 This command does many different things, depending on context:
20266
20267 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20268 this is what we do.
20269
20270 - If the cursor is on a statistics cookie, update it.
20271
20272 - If the cursor is in a headline, prompt for tags and insert them
20273 into the current line, aligned to `org-tags-column'. When called
20274 with prefix arg, realign all tags in the current buffer.
20275
20276 - If the cursor is in one of the special #+KEYWORD lines, this
20277 triggers scanning the buffer for these lines and updating the
20278 information.
20279
20280 - If the cursor is inside a table, realign the table. This command
20281 works even if the automatic table editor has been turned off.
20282
20283 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20284 the entire table.
20285
20286 - If the cursor is at a footnote reference or definition, jump to
20287 the corresponding definition or references, respectively.
20288
20289 - If the cursor is a the beginning of a dynamic block, update it.
20290
20291 - If the current buffer is a capture buffer, close note and file it.
20292
20293 - If the cursor is on a <<<target>>>, update radio targets and
20294 corresponding links in this buffer.
20295
20296 - If the cursor is on a numbered item in a plain list, renumber the
20297 ordered list.
20298
20299 - If the cursor is on a checkbox, toggle it.
20300
20301 - If the cursor is on a code block, evaluate it. The variable
20302 `org-confirm-babel-evaluate' can be used to control prompting
20303 before code block evaluation, by default every code block
20304 evaluation requires confirmation. Code block evaluation can be
20305 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20306 (interactive "P")
20307 (cond
20308 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20309 org-occur-highlights
20310 org-latex-fragment-image-overlays)
20311 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20312 (org-remove-occur-highlights)
20313 (org-remove-latex-fragment-image-overlays)
20314 (message "Temporary highlights/overlays removed from current buffer"))
20315 ((and (local-variable-p 'org-finish-function (current-buffer))
20316 (fboundp org-finish-function))
20317 (funcall org-finish-function))
20318 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20319 (t
20320 (let* ((context (org-element-context)) (type (org-element-type context)))
20321 ;; Test if point is within a blank line.
20322 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20323 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20324 (user-error "C-c C-c can do nothing useful at this location"))
20325 (case type
20326 ;; When at a link, act according to the parent instead.
20327 (link (setq context (org-element-property :parent context))
20328 (setq type (org-element-type context)))
20329 ;; Unsupported object types: refer to the first supported
20330 ;; element or object containing it.
20331 ((bold code entity export-snippet inline-babel-call inline-src-block
20332 italic latex-fragment line-break macro strike-through subscript
20333 superscript underline verbatim)
20334 (while (and (setq context (org-element-property :parent context))
20335 (not (memq (setq type (org-element-type context))
20336 '(radio-target paragraph verse-block
20337 table-cell)))))))
20338 ;; For convenience: at the first line of a paragraph on the
20339 ;; same line as an item, apply function on that item instead.
20340 (when (eq type 'paragraph)
20341 (let ((parent (org-element-property :parent context)))
20342 (when (and (eq (org-element-type parent) 'item)
20343 (= (point-at-bol) (org-element-property :begin parent)))
20344 (setq context parent type 'item))))
20345 ;; Act according to type of element or object at point.
20346 (case type
20347 (clock (org-clock-update-time-maybe))
20348 (dynamic-block
20349 (save-excursion
20350 (goto-char (org-element-property :post-affiliated context))
20351 (org-update-dblock)))
20352 (footnote-definition
20353 (goto-char (org-element-property :post-affiliated context))
20354 (call-interactively 'org-footnote-action))
20355 (footnote-reference (call-interactively 'org-footnote-action))
20356 ((headline inlinetask)
20357 (save-excursion (goto-char (org-element-property :begin context))
20358 (call-interactively 'org-set-tags)))
20359 (item
20360 ;; At an item: a double C-u set checkbox to "[-]"
20361 ;; unconditionally, whereas a single one will toggle its
20362 ;; presence. Without a universal argument, if the item
20363 ;; has a checkbox, toggle it. Otherwise repair the list.
20364 (let* ((box (org-element-property :checkbox context))
20365 (struct (org-element-property :structure context))
20366 (old-struct (copy-tree struct))
20367 (parents (org-list-parents-alist struct))
20368 (prevs (org-list-prevs-alist struct))
20369 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20370 (org-list-set-checkbox
20371 (org-element-property :begin context) struct
20372 (cond ((equal arg '(16)) "[-]")
20373 ((and (not box) (equal arg '(4))) "[ ]")
20374 ((or (not box) (equal arg '(4))) nil)
20375 ((eq box 'on) "[ ]")
20376 (t "[X]")))
20377 ;; Mimic `org-list-write-struct' but with grabbing
20378 ;; a return value from `org-list-struct-fix-box'.
20379 (org-list-struct-fix-ind struct parents 2)
20380 (org-list-struct-fix-item-end struct)
20381 (org-list-struct-fix-bul struct prevs)
20382 (org-list-struct-fix-ind struct parents)
20383 (let ((block-item
20384 (org-list-struct-fix-box struct parents prevs orderedp)))
20385 (if (and box (equal struct old-struct))
20386 (if (equal arg '(16))
20387 (message "Checkboxes already reset")
20388 (user-error "Cannot toggle this checkbox: %s"
20389 (if (eq box 'on)
20390 "all subitems checked"
20391 "unchecked subitems")))
20392 (org-list-struct-apply-struct struct old-struct)
20393 (org-update-checkbox-count-maybe))
20394 (when block-item
20395 (message "Checkboxes were removed due to empty box at line %d"
20396 (org-current-line block-item))))))
20397 (keyword
20398 (let ((org-inhibit-startup-visibility-stuff t)
20399 (org-startup-align-all-tables nil))
20400 (when (boundp 'org-table-coordinate-overlays)
20401 (mapc 'delete-overlay org-table-coordinate-overlays)
20402 (setq org-table-coordinate-overlays nil))
20403 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20404 (message "Local setup has been refreshed"))
20405 (plain-list
20406 ;; At a plain list, with a double C-u argument, set
20407 ;; checkboxes of each item to "[-]", whereas a single one
20408 ;; will toggle their presence according to the state of the
20409 ;; first item in the list. Without an argument, repair the
20410 ;; list.
20411 (let* ((begin (org-element-property :contents-begin context))
20412 (beginm (move-marker (make-marker) begin))
20413 (struct (org-element-property :structure context))
20414 (old-struct (copy-tree struct))
20415 (first-box (save-excursion
20416 (goto-char begin)
20417 (looking-at org-list-full-item-re)
20418 (match-string-no-properties 3)))
20419 (new-box (cond ((equal arg '(16)) "[-]")
20420 ((equal arg '(4)) (unless first-box "[ ]"))
20421 ((equal first-box "[X]") "[ ]")
20422 (t "[X]"))))
20423 (cond
20424 (arg
20425 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20426 (org-list-get-all-items
20427 begin struct (org-list-prevs-alist struct))))
20428 ((and first-box (eq (point) begin))
20429 ;; For convenience, when point is at bol on the first
20430 ;; item of the list and no argument is provided, simply
20431 ;; toggle checkbox of that item, if any.
20432 (org-list-set-checkbox begin struct new-box)))
20433 (org-list-write-struct
20434 struct (org-list-parents-alist struct) old-struct)
20435 (org-update-checkbox-count-maybe)
20436 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20437 ((property-drawer node-property)
20438 (call-interactively 'org-property-action))
20439 ((radio-target target)
20440 (call-interactively 'org-update-radio-target-regexp))
20441 (statistics-cookie
20442 (call-interactively 'org-update-statistics-cookies))
20443 ((table table-cell table-row)
20444 ;; At a table, recalculate every field and align it. Also
20445 ;; send the table if necessary. If the table has
20446 ;; a `table.el' type, just give up. At a table row or
20447 ;; cell, maybe recalculate line but always align table.
20448 (if (eq (org-element-property :type context) 'table.el)
20449 (message "%s" "Use C-c ' to edit table.el tables")
20450 (let ((org-enable-table-editor t))
20451 (if (or (eq type 'table)
20452 ;; Check if point is at a TBLFM line.
20453 (and (eq type 'table-row)
20454 (= (point) (org-element-property :end context))))
20455 (save-excursion
20456 (if (org-at-TBLFM-p)
20457 (progn (require 'org-table)
20458 (org-table-calc-current-TBLFM))
20459 (goto-char (org-element-property :contents-begin context))
20460 (org-call-with-arg 'org-table-recalculate (or arg t))
20461 (orgtbl-send-table 'maybe)))
20462 (org-table-maybe-eval-formula)
20463 (cond (arg (call-interactively 'org-table-recalculate))
20464 ((org-table-maybe-recalculate-line))
20465 (t (org-table-align)))))))
20466 (timestamp (org-timestamp-change 0 'day))
20467 (otherwise
20468 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20469 (user-error
20470 "C-c C-c can do nothing useful at this location")))))))))
20471
20472 (defun org-mode-restart ()
20473 (interactive)
20474 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20475 (funcall major-mode)
20476 (hack-local-variables)
20477 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20478 (org-indent-mode -1)))
20479 (message "%s restarted" major-mode))
20480
20481 (defun org-kill-note-or-show-branches ()
20482 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20483 (interactive)
20484 (if (not org-finish-function)
20485 (progn
20486 (hide-subtree)
20487 (call-interactively 'show-branches))
20488 (let ((org-note-abort t))
20489 (funcall org-finish-function))))
20490
20491 (defun org-open-line (n)
20492 "Insert a new row in tables, call `open-line' elsewhere.
20493 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20494 (interactive "*p")
20495 (cond
20496 ((not org-special-ctrl-o)
20497 (open-line n))
20498 ((org-at-table-p)
20499 (org-table-insert-row))
20500 (t
20501 (open-line n))))
20502
20503 (defun org-return (&optional indent)
20504 "Goto next table row or insert a newline.
20505 Calls `org-table-next-row' or `newline', depending on context.
20506 See the individual commands for more information."
20507 (interactive)
20508 (let (org-ts-what)
20509 (cond
20510 ((or (bobp) (org-in-src-block-p))
20511 (if indent (newline-and-indent) (newline)))
20512 ((org-at-table-p)
20513 (org-table-justify-field-maybe)
20514 (call-interactively 'org-table-next-row))
20515 ;; when `newline-and-indent' is called within a list, make sure
20516 ;; text moved stays inside the item.
20517 ((and (org-in-item-p) indent)
20518 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20519 (progn
20520 (save-match-data (newline))
20521 (org-indent-line-to (length (match-string 0))))
20522 (let ((ind (org-get-indentation)))
20523 (newline)
20524 (if (org-looking-back org-list-end-re)
20525 (org-indent-line)
20526 (org-indent-line-to ind)))))
20527 ((and org-return-follows-link
20528 (org-at-timestamp-p t)
20529 (not (eq org-ts-what 'after)))
20530 (org-follow-timestamp-link))
20531 ((and org-return-follows-link
20532 (let ((tprop (get-text-property (point) 'face)))
20533 (or (eq tprop 'org-link)
20534 (and (listp tprop) (memq 'org-link tprop)))))
20535 (call-interactively 'org-open-at-point))
20536 ((and (org-at-heading-p)
20537 (looking-at
20538 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20539 (org-show-entry)
20540 (end-of-line 1)
20541 (newline))
20542 (t (if indent (newline-and-indent) (newline))))))
20543
20544 (defun org-return-indent ()
20545 "Goto next table row or insert a newline and indent.
20546 Calls `org-table-next-row' or `newline-and-indent', depending on
20547 context. See the individual commands for more information."
20548 (interactive)
20549 (org-return t))
20550
20551 (defun org-ctrl-c-star ()
20552 "Compute table, or change heading status of lines.
20553 Calls `org-table-recalculate' or `org-toggle-heading',
20554 depending on context."
20555 (interactive)
20556 (cond
20557 ((org-at-table-p)
20558 (call-interactively 'org-table-recalculate))
20559 (t
20560 ;; Convert all lines in region to list items
20561 (call-interactively 'org-toggle-heading))))
20562
20563 (defun org-ctrl-c-minus ()
20564 "Insert separator line in table or modify bullet status of line.
20565 Also turns a plain line or a region of lines into list items.
20566 Calls `org-table-insert-hline', `org-toggle-item', or
20567 `org-cycle-list-bullet', depending on context."
20568 (interactive)
20569 (cond
20570 ((org-at-table-p)
20571 (call-interactively 'org-table-insert-hline))
20572 ((org-region-active-p)
20573 (call-interactively 'org-toggle-item))
20574 ((org-in-item-p)
20575 (call-interactively 'org-cycle-list-bullet))
20576 (t
20577 (call-interactively 'org-toggle-item))))
20578
20579 (defun org-toggle-item (arg)
20580 "Convert headings or normal lines to items, items to normal lines.
20581 If there is no active region, only the current line is considered.
20582
20583 If the first non blank line in the region is a headline, convert
20584 all headlines to items, shifting text accordingly.
20585
20586 If it is an item, convert all items to normal lines.
20587
20588 If it is normal text, change region into a list of items.
20589 With a prefix argument ARG, change the region in a single item."
20590 (interactive "P")
20591 (let ((shift-text
20592 (function
20593 ;; Shift text in current section to IND, from point to END.
20594 ;; The function leaves point to END line.
20595 (lambda (ind end)
20596 (let ((min-i 1000) (end (copy-marker end)))
20597 ;; First determine the minimum indentation (MIN-I) of
20598 ;; the text.
20599 (save-excursion
20600 (catch 'exit
20601 (while (< (point) end)
20602 (let ((i (org-get-indentation)))
20603 (cond
20604 ;; Skip blank lines and inline tasks.
20605 ((looking-at "^[ \t]*$"))
20606 ((looking-at org-outline-regexp-bol))
20607 ;; We can't find less than 0 indentation.
20608 ((zerop i) (throw 'exit (setq min-i 0)))
20609 ((< i min-i) (setq min-i i))))
20610 (forward-line))))
20611 ;; Then indent each line so that a line indented to
20612 ;; MIN-I becomes indented to IND. Ignore blank lines
20613 ;; and inline tasks in the process.
20614 (let ((delta (- ind min-i)))
20615 (while (< (point) end)
20616 (unless (or (looking-at "^[ \t]*$")
20617 (looking-at org-outline-regexp-bol))
20618 (org-indent-line-to (+ (org-get-indentation) delta)))
20619 (forward-line)))))))
20620 (skip-blanks
20621 (function
20622 ;; Return beginning of first non-blank line, starting from
20623 ;; line at POS.
20624 (lambda (pos)
20625 (save-excursion
20626 (goto-char pos)
20627 (skip-chars-forward " \r\t\n")
20628 (point-at-bol)))))
20629 beg end)
20630 ;; Determine boundaries of changes.
20631 (if (org-region-active-p)
20632 (setq beg (funcall skip-blanks (region-beginning))
20633 end (copy-marker (region-end)))
20634 (setq beg (funcall skip-blanks (point-at-bol))
20635 end (copy-marker (point-at-eol))))
20636 ;; Depending on the starting line, choose an action on the text
20637 ;; between BEG and END.
20638 (org-with-limited-levels
20639 (save-excursion
20640 (goto-char beg)
20641 (cond
20642 ;; Case 1. Start at an item: de-itemize. Note that it only
20643 ;; happens when a region is active: `org-ctrl-c-minus'
20644 ;; would call `org-cycle-list-bullet' otherwise.
20645 ((org-at-item-p)
20646 (while (< (point) end)
20647 (when (org-at-item-p)
20648 (skip-chars-forward " \t")
20649 (delete-region (point) (match-end 0)))
20650 (forward-line)))
20651 ;; Case 2. Start at an heading: convert to items.
20652 ((org-at-heading-p)
20653 (let* ((bul (org-list-bullet-string "-"))
20654 (bul-len (length bul))
20655 ;; Indentation of the first heading. It should be
20656 ;; relative to the indentation of its parent, if any.
20657 (start-ind (save-excursion
20658 (cond
20659 ((not org-adapt-indentation) 0)
20660 ((not (outline-previous-heading)) 0)
20661 (t (length (match-string 0))))))
20662 ;; Level of first heading. Further headings will be
20663 ;; compared to it to determine hierarchy in the list.
20664 (ref-level (org-reduced-level (org-outline-level))))
20665 (while (< (point) end)
20666 (let* ((level (org-reduced-level (org-outline-level)))
20667 (delta (max 0 (- level ref-level))))
20668 ;; If current headline is less indented than the first
20669 ;; one, set it as reference, in order to preserve
20670 ;; subtrees.
20671 (when (< level ref-level) (setq ref-level level))
20672 (replace-match bul t t)
20673 (org-indent-line-to (+ start-ind (* delta bul-len)))
20674 ;; Ensure all text down to END (or SECTION-END) belongs
20675 ;; to the newly created item.
20676 (let ((section-end (save-excursion
20677 (or (outline-next-heading) (point)))))
20678 (forward-line)
20679 (funcall shift-text
20680 (+ start-ind (* (1+ delta) bul-len))
20681 (min end section-end)))))))
20682 ;; Case 3. Normal line with ARG: make the first line of region
20683 ;; an item, and shift indentation of others lines to
20684 ;; set them as item's body.
20685 (arg (let* ((bul (org-list-bullet-string "-"))
20686 (bul-len (length bul))
20687 (ref-ind (org-get-indentation)))
20688 (skip-chars-forward " \t")
20689 (insert bul)
20690 (forward-line)
20691 (while (< (point) end)
20692 ;; Ensure that lines less indented than first one
20693 ;; still get included in item body.
20694 (funcall shift-text
20695 (+ ref-ind bul-len)
20696 (min end (save-excursion (or (outline-next-heading)
20697 (point)))))
20698 (forward-line))))
20699 ;; Case 4. Normal line without ARG: turn each non-item line
20700 ;; into an item.
20701 (t
20702 (while (< (point) end)
20703 (unless (or (org-at-heading-p) (org-at-item-p))
20704 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20705 (replace-match
20706 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20707 (forward-line))))))))
20708
20709 (defun org-toggle-heading (&optional nstars)
20710 "Convert headings to normal text, or items or text to headings.
20711 If there is no active region, only convert the current line.
20712
20713 With a \\[universal-argument] prefix, convert the whole list at
20714 point into heading.
20715
20716 In a region:
20717
20718 - If the first non blank line is a headline, remove the stars
20719 from all headlines in the region.
20720
20721 - If it is a normal line, turn each and every normal line (i.e.,
20722 not an heading or an item) in the region into headings. If you
20723 want to convert only the first line of this region, use one
20724 universal prefix argument.
20725
20726 - If it is a plain list item, turn all plain list items into headings.
20727
20728 When converting a line into a heading, the number of stars is chosen
20729 such that the lines become children of the current entry. However,
20730 when a numeric prefix argument is given, its value determines the
20731 number of stars to add."
20732 (interactive "P")
20733 (let ((skip-blanks
20734 (function
20735 ;; Return beginning of first non-blank line, starting from
20736 ;; line at POS.
20737 (lambda (pos)
20738 (save-excursion
20739 (goto-char pos)
20740 (while (org-at-comment-p) (forward-line))
20741 (skip-chars-forward " \r\t\n")
20742 (point-at-bol)))))
20743 beg end toggled)
20744 ;; Determine boundaries of changes. If a universal prefix has
20745 ;; been given, put the list in a region. If region ends at a bol,
20746 ;; do not consider the last line to be in the region.
20747
20748 (when (and current-prefix-arg (org-at-item-p))
20749 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20750 (org-mark-element))
20751
20752 (if (org-region-active-p)
20753 (setq beg (funcall skip-blanks (region-beginning))
20754 end (copy-marker (save-excursion
20755 (goto-char (region-end))
20756 (if (bolp) (point) (point-at-eol)))))
20757 (setq beg (funcall skip-blanks (point-at-bol))
20758 end (copy-marker (point-at-eol))))
20759 ;; Ensure inline tasks don't count as headings.
20760 (org-with-limited-levels
20761 (save-excursion
20762 (goto-char beg)
20763 (cond
20764 ;; Case 1. Started at an heading: de-star headings.
20765 ((org-at-heading-p)
20766 (while (< (point) end)
20767 (when (org-at-heading-p t)
20768 (looking-at org-outline-regexp) (replace-match "")
20769 (setq toggled t))
20770 (forward-line)))
20771 ;; Case 2. Started at an item: change items into headlines.
20772 ;; One star will be added by `org-list-to-subtree'.
20773 ((org-at-item-p)
20774 (let* ((stars (make-string
20775 ;; subtract the star that will be added again by
20776 ;; `org-list-to-subtree'
20777 (if (numberp nstars) (1- nstars)
20778 (or (org-current-level) 0))
20779 ?*))
20780 (add-stars
20781 (cond (nstars "") ; stars from prefix only
20782 ((equal stars "") "") ; before first heading
20783 (org-odd-levels-only "*") ; inside heading, odd
20784 (t "")))) ; inside heading, oddeven
20785 (while (< (point) end)
20786 (when (org-at-item-p)
20787 ;; Pay attention to cases when region ends before list.
20788 (let* ((struct (org-list-struct))
20789 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20790 (save-restriction
20791 (narrow-to-region (point) list-end)
20792 (insert
20793 (org-list-to-subtree
20794 (org-list-parse-list t)
20795 `(:istart (concat ',stars ',add-stars (funcall get-stars depth))
20796 :icount (concat ',stars ',add-stars (funcall get-stars depth)))))))
20797 (setq toggled t))
20798 (forward-line))))
20799 ;; Case 3. Started at normal text: make every line an heading,
20800 ;; skipping headlines and items.
20801 (t (let* ((stars
20802 (make-string
20803 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20804 (add-stars
20805 (cond (nstars "") ; stars from prefix only
20806 ((equal stars "") "*") ; before first heading
20807 (org-odd-levels-only "**") ; inside heading, odd
20808 (t "*"))) ; inside heading, oddeven
20809 (rpl (concat stars add-stars " "))
20810 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20811 (while (< (point) (if (equal nstars '(4)) lend end))
20812 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20813 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20814 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20815 (forward-line)))))))
20816 (unless toggled (message "Cannot toggle heading from here"))))
20817
20818 (defun org-meta-return (&optional _arg)
20819 "Insert a new heading or wrap a region in a table.
20820 Calls `org-insert-heading' or `org-table-wrap-region', depending
20821 on context. See the individual commands for more information."
20822 (interactive)
20823 (org-check-before-invisible-edit 'insert)
20824 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20825 (let* ((element (org-element-at-point))
20826 (type (org-element-type element)))
20827 (when (eq type 'table-row)
20828 (setq element (org-element-property :parent element))
20829 (setq type 'table))
20830 (if (and (eq type 'table)
20831 (eq (org-element-property :type element) 'org)
20832 (>= (point) (org-element-property :contents-begin element))
20833 (< (point) (org-element-property :contents-end element)))
20834 (call-interactively 'org-table-wrap-region)
20835 (call-interactively 'org-insert-heading)))))
20836
20837 ;;; Menu entries
20838
20839 (defsubst org-in-subtree-not-table-p ()
20840 "Are we in a subtree and not in a table?"
20841 (and (not (org-before-first-heading-p))
20842 (not (org-at-table-p))))
20843
20844 ;; Define the Org-mode menus
20845 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20846 '("Tbl"
20847 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20848 ["Next Field" org-cycle (org-at-table-p)]
20849 ["Previous Field" org-shifttab (org-at-table-p)]
20850 ["Next Row" org-return (org-at-table-p)]
20851 "--"
20852 ["Blank Field" org-table-blank-field (org-at-table-p)]
20853 ["Edit Field" org-table-edit-field (org-at-table-p)]
20854 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20855 "--"
20856 ("Column"
20857 ["Move Column Left" org-metaleft (org-at-table-p)]
20858 ["Move Column Right" org-metaright (org-at-table-p)]
20859 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20860 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20861 ("Row"
20862 ["Move Row Up" org-metaup (org-at-table-p)]
20863 ["Move Row Down" org-metadown (org-at-table-p)]
20864 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20865 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20866 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20867 "--"
20868 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20869 ("Rectangle"
20870 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20871 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20872 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20873 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20874 "--"
20875 ("Calculate"
20876 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20877 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20878 ["Edit Formulas" org-edit-special (org-at-table-p)]
20879 "--"
20880 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20881 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20882 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20883 "--"
20884 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20885 "--"
20886 ["Sum Column/Rectangle" org-table-sum
20887 (or (org-at-table-p) (org-region-active-p))]
20888 ["Which Column?" org-table-current-column (org-at-table-p)])
20889 ["Debug Formulas"
20890 org-table-toggle-formula-debugger
20891 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20892 ["Show Col/Row Numbers"
20893 org-table-toggle-coordinate-overlays
20894 :style toggle
20895 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20896 "--"
20897 ["Create" org-table-create (and (not (org-at-table-p))
20898 org-enable-table-editor)]
20899 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20900 ["Import from File" org-table-import (not (org-at-table-p))]
20901 ["Export to File" org-table-export (org-at-table-p)]
20902 "--"
20903 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20904
20905 (easy-menu-define org-org-menu org-mode-map "Org menu"
20906 '("Org"
20907 ("Show/Hide"
20908 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20909 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20910 ["Sparse Tree..." org-sparse-tree t]
20911 ["Reveal Context" org-reveal t]
20912 ["Show All" show-all t]
20913 "--"
20914 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20915 "--"
20916 ["New Heading" org-insert-heading t]
20917 ("Navigate Headings"
20918 ["Up" outline-up-heading t]
20919 ["Next" outline-next-visible-heading t]
20920 ["Previous" outline-previous-visible-heading t]
20921 ["Next Same Level" outline-forward-same-level t]
20922 ["Previous Same Level" outline-backward-same-level t]
20923 "--"
20924 ["Jump" org-goto t])
20925 ("Edit Structure"
20926 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20927 "--"
20928 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20929 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20930 "--"
20931 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20932 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20933 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20934 "--"
20935 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20936 "--"
20937 ["Copy visible text" org-copy-visible t]
20938 "--"
20939 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20940 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20941 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20942 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20943 "--"
20944 ["Sort Region/Children" org-sort t]
20945 "--"
20946 ["Convert to odd levels" org-convert-to-odd-levels t]
20947 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20948 ("Editing"
20949 ["Emphasis..." org-emphasize t]
20950 ["Edit Source Example" org-edit-special t]
20951 "--"
20952 ["Footnote new/jump" org-footnote-action t]
20953 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20954 ("Archive"
20955 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20956 "--"
20957 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20958 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20959 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20960 )
20961 "--"
20962 ("Hyperlinks"
20963 ["Store Link (Global)" org-store-link t]
20964 ["Find existing link to here" org-occur-link-in-agenda-files t]
20965 ["Insert Link" org-insert-link t]
20966 ["Follow Link" org-open-at-point t]
20967 "--"
20968 ["Next link" org-next-link t]
20969 ["Previous link" org-previous-link t]
20970 "--"
20971 ["Descriptive Links"
20972 org-toggle-link-display
20973 :style radio
20974 :selected org-descriptive-links
20975 ]
20976 ["Literal Links"
20977 org-toggle-link-display
20978 :style radio
20979 :selected (not org-descriptive-links)])
20980 "--"
20981 ("TODO Lists"
20982 ["TODO/DONE/-" org-todo t]
20983 ("Select keyword"
20984 ["Next keyword" org-shiftright (org-at-heading-p)]
20985 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20986 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20987 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20988 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20989 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20990 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20991 "--"
20992 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20993 :selected org-enforce-todo-dependencies :style toggle :active t]
20994 "Settings for tree at point"
20995 ["Do Children sequentially" org-toggle-ordered-property :style radio
20996 :selected (org-entry-get nil "ORDERED")
20997 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20998 ["Do Children parallel" org-toggle-ordered-property :style radio
20999 :selected (not (org-entry-get nil "ORDERED"))
21000 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21001 "--"
21002 ["Set Priority" org-priority t]
21003 ["Priority Up" org-shiftup t]
21004 ["Priority Down" org-shiftdown t]
21005 "--"
21006 ["Get news from all feeds" org-feed-update-all t]
21007 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21008 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21009 ("TAGS and Properties"
21010 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21011 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21012 "--"
21013 ["Set property" org-set-property (not (org-before-first-heading-p))]
21014 ["Column view of properties" org-columns t]
21015 ["Insert Column View DBlock" org-insert-columns-dblock t])
21016 ("Dates and Scheduling"
21017 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21018 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21019 ("Change Date"
21020 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21021 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21022 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21023 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21024 ["Compute Time Range" org-evaluate-time-range t]
21025 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21026 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21027 "--"
21028 ["Custom time format" org-toggle-time-stamp-overlays
21029 :style radio :selected org-display-custom-times]
21030 "--"
21031 ["Goto Calendar" org-goto-calendar t]
21032 ["Date from Calendar" org-date-from-calendar t]
21033 "--"
21034 ["Start/Restart Timer" org-timer-start t]
21035 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21036 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21037 ["Insert Timer String" org-timer t]
21038 ["Insert Timer Item" org-timer-item t])
21039 ("Logging work"
21040 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21041 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21042 ["Clock out" org-clock-out t]
21043 ["Clock cancel" org-clock-cancel t]
21044 "--"
21045 ["Mark as default task" org-clock-mark-default-task t]
21046 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21047 ["Goto running clock" org-clock-goto t]
21048 "--"
21049 ["Display times" org-clock-display t]
21050 ["Create clock table" org-clock-report t]
21051 "--"
21052 ["Record DONE time"
21053 (progn (setq org-log-done (not org-log-done))
21054 (message "Switching to %s will %s record a timestamp"
21055 (car org-done-keywords)
21056 (if org-log-done "automatically" "not")))
21057 :style toggle :selected org-log-done])
21058 "--"
21059 ["Agenda Command..." org-agenda t]
21060 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21061 ("File List for Agenda")
21062 ("Special views current file"
21063 ["TODO Tree" org-show-todo-tree t]
21064 ["Check Deadlines" org-check-deadlines t]
21065 ["Timeline" org-timeline t]
21066 ["Tags/Property tree" org-match-sparse-tree t])
21067 "--"
21068 ["Export/Publish..." org-export-dispatch t]
21069 ("LaTeX"
21070 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21071 :selected org-cdlatex-mode]
21072 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21073 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21074 ["Modify math symbol" org-cdlatex-math-modify
21075 (org-inside-LaTeX-fragment-p)]
21076 ["Insert citation" org-reftex-citation t]
21077 "--"
21078 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21079 "--"
21080 ("MobileOrg"
21081 ["Push Files and Views" org-mobile-push t]
21082 ["Get Captured and Flagged" org-mobile-pull t]
21083 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21084 "--"
21085 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21086 "--"
21087 ("Documentation"
21088 ["Show Version" org-version t]
21089 ["Info Documentation" org-info t])
21090 ("Customize"
21091 ["Browse Org Group" org-customize t]
21092 "--"
21093 ["Expand This Menu" org-create-customize-menu
21094 (fboundp 'customize-menu-create)])
21095 ["Send bug report" org-submit-bug-report t]
21096 "--"
21097 ("Refresh/Reload"
21098 ["Refresh setup current buffer" org-mode-restart t]
21099 ["Reload Org (after update)" org-reload t]
21100 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21101 ))
21102
21103 (defun org-info (&optional node)
21104 "Read documentation for Org-mode in the info system.
21105 With optional NODE, go directly to that node."
21106 (interactive)
21107 (info (format "(org)%s" (or node ""))))
21108
21109 ;;;###autoload
21110 (defun org-submit-bug-report ()
21111 "Submit a bug report on Org-mode via mail.
21112
21113 Don't hesitate to report any problems or inaccurate documentation.
21114
21115 If you don't have setup sending mail from (X)Emacs, please copy the
21116 output buffer into your mail program, as it gives us important
21117 information about your Org-mode version and configuration."
21118 (interactive)
21119 (require 'reporter)
21120 (defvar reporter-prompt-for-summary-p)
21121 (org-load-modules-maybe)
21122 (org-require-autoloaded-modules)
21123 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21124 (reporter-submit-bug-report
21125 "emacs-orgmode@gnu.org"
21126 (org-version nil 'full)
21127 (let (list)
21128 (save-window-excursion
21129 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21130 (delete-other-windows)
21131 (erase-buffer)
21132 (insert "You are about to submit a bug report to the Org-mode mailing list.
21133
21134 We would like to add your full Org-mode and Outline configuration to the
21135 bug report. This greatly simplifies the work of the maintainer and
21136 other experts on the mailing list.
21137
21138 HOWEVER, some variables you have customized may contain private
21139 information. The names of customers, colleagues, or friends, might
21140 appear in the form of file names, tags, todo states, or search strings.
21141 If you answer yes to the prompt, you might want to check and remove
21142 such private information before sending the email.")
21143 (add-text-properties (point-min) (point-max) '(face org-warning))
21144 (when (yes-or-no-p "Include your Org-mode configuration ")
21145 (mapatoms
21146 (lambda (v)
21147 (and (boundp v)
21148 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21149 (or (and (symbol-value v)
21150 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21151 (and
21152 (get v 'custom-type) (get v 'standard-value)
21153 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21154 (push v list)))))
21155 (kill-buffer (get-buffer "*Warn about privacy*"))
21156 list))
21157 nil nil
21158 "Remember to cover the basics, that is, what you expected to happen and
21159 what in fact did happen. You don't know how to make a good report? See
21160
21161 http://orgmode.org/manual/Feedback.html#Feedback
21162
21163 Your bug report will be posted to the Org-mode mailing list.
21164 ------------------------------------------------------------------------")
21165 (save-excursion
21166 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21167 (replace-match "\\1Bug: \\3 [\\2]")))))
21168
21169
21170 (defun org-install-agenda-files-menu ()
21171 (let ((bl (buffer-list)))
21172 (save-excursion
21173 (while bl
21174 (set-buffer (pop bl))
21175 (if (derived-mode-p 'org-mode) (setq bl nil)))
21176 (when (derived-mode-p 'org-mode)
21177 (easy-menu-change
21178 '("Org") "File List for Agenda"
21179 (append
21180 (list
21181 ["Edit File List" (org-edit-agenda-file-list) t]
21182 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21183 ["Remove Current File from List" org-remove-file t]
21184 ["Cycle through agenda files" org-cycle-agenda-files t]
21185 ["Occur in all agenda files" org-occur-in-agenda-files t]
21186 "--")
21187 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21188
21189 ;;;; Documentation
21190
21191 (defun org-require-autoloaded-modules ()
21192 (interactive)
21193 (mapc 'require
21194 '(org-agenda org-archive org-attach org-clock org-colview org-id
21195 org-table org-timer)))
21196
21197 ;;;###autoload
21198 (defun org-reload (&optional uncompiled)
21199 "Reload all org lisp files.
21200 With prefix arg UNCOMPILED, load the uncompiled versions."
21201 (interactive "P")
21202 (require 'loadhist)
21203 (let* ((org-dir (org-find-library-dir "org"))
21204 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21205 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21206 (remove-re (mapconcat 'identity
21207 (mapcar (lambda (f) (concat "^" f "$"))
21208 (list (if (featurep 'xemacs)
21209 "org-colview"
21210 "org-colview-xemacs")
21211 "org" "org-loaddefs" "org-version"))
21212 "\\|"))
21213 (feats (delete-dups
21214 (mapcar 'file-name-sans-extension
21215 (mapcar 'file-name-nondirectory
21216 (delq nil
21217 (mapcar 'feature-file
21218 features))))))
21219 (lfeat (append
21220 (sort
21221 (setq feats
21222 (delq nil (mapcar
21223 (lambda (f)
21224 (if (and (string-match feature-re f)
21225 (not (string-match remove-re f)))
21226 f nil))
21227 feats)))
21228 'string-lessp)
21229 (list "org-version" "org")))
21230 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21231 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21232 load-uncore load-misses)
21233 (setq load-misses
21234 (delq 't
21235 (mapcar (lambda (f)
21236 (or (org-load-noerror-mustsuffix (concat org-dir f))
21237 (and (string= org-dir contrib-dir)
21238 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21239 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21240 (add-to-list 'load-uncore f 'append)
21241 't)
21242 f))
21243 lfeat)))
21244 (if load-uncore
21245 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21246 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21247 (if load-misses
21248 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21249 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21250 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21251
21252 ;;;###autoload
21253 (defun org-customize ()
21254 "Call the customize function with org as argument."
21255 (interactive)
21256 (org-load-modules-maybe)
21257 (org-require-autoloaded-modules)
21258 (customize-browse 'org))
21259
21260 (defun org-create-customize-menu ()
21261 "Create a full customization menu for Org-mode, insert it into the menu."
21262 (interactive)
21263 (org-load-modules-maybe)
21264 (org-require-autoloaded-modules)
21265 (if (fboundp 'customize-menu-create)
21266 (progn
21267 (easy-menu-change
21268 '("Org") "Customize"
21269 `(["Browse Org group" org-customize t]
21270 "--"
21271 ,(customize-menu-create 'org)
21272 ["Set" Custom-set t]
21273 ["Save" Custom-save t]
21274 ["Reset to Current" Custom-reset-current t]
21275 ["Reset to Saved" Custom-reset-saved t]
21276 ["Reset to Standard Settings" Custom-reset-standard t]))
21277 (message "\"Org\"-menu now contains full customization menu"))
21278 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21279
21280 ;;;; Miscellaneous stuff
21281
21282 ;;; Generally useful functions
21283
21284 (defun org-get-at-bol (property)
21285 "Get text property PROPERTY at beginning of line."
21286 (get-text-property (point-at-bol) property))
21287
21288 (defun org-find-text-property-in-string (prop s)
21289 "Return the first non-nil value of property PROP in string S."
21290 (or (get-text-property 0 prop s)
21291 (get-text-property (or (next-single-property-change 0 prop s) 0)
21292 prop s)))
21293
21294 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21295 "Display the given MESSAGE as a warning."
21296 (if (fboundp 'display-warning)
21297 (display-warning 'org message
21298 (if (featurep 'xemacs) 'warning :warning))
21299 (let ((buf (get-buffer-create "*Org warnings*")))
21300 (with-current-buffer buf
21301 (goto-char (point-max))
21302 (insert "Warning (Org): " message)
21303 (unless (bolp)
21304 (newline)))
21305 (display-buffer buf)
21306 (sit-for 0))))
21307
21308 (defun org-eval (form)
21309 "Eval FORM and return result."
21310 (condition-case error
21311 (eval form)
21312 (error (format "%%![Error: %s]" error))))
21313
21314 (defun org-in-clocktable-p ()
21315 "Check if the cursor is in a clocktable."
21316 (let ((pos (point)) start)
21317 (save-excursion
21318 (end-of-line 1)
21319 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21320 (setq start (match-beginning 0))
21321 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21322 (>= (match-end 0) pos)
21323 start))))
21324
21325 (defun org-in-commented-line ()
21326 "Is point in a line starting with `#'?"
21327 (equal (char-after (point-at-bol)) ?#))
21328
21329 (defun org-in-indented-comment-line ()
21330 "Is point in a line starting with `#' after some white space?"
21331 (save-excursion
21332 (save-match-data
21333 (goto-char (point-at-bol))
21334 (looking-at "[ \t]*#"))))
21335
21336 (defun org-in-verbatim-emphasis ()
21337 (save-match-data
21338 (and (org-in-regexp org-emph-re 2)
21339 (>= (point) (match-beginning 3))
21340 (<= (point) (match-end 4))
21341 (member (match-string 3) '("=" "~")))))
21342
21343 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21344 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21345 (if (and marker (marker-buffer marker)
21346 (buffer-live-p (marker-buffer marker)))
21347 (progn
21348 (org-pop-to-buffer-same-window (marker-buffer marker))
21349 (if (or (> marker (point-max)) (< marker (point-min)))
21350 (widen))
21351 (goto-char marker)
21352 (org-show-context 'org-goto))
21353 (if bookmark
21354 (bookmark-jump bookmark)
21355 (error "Cannot find location"))))
21356
21357 (defun org-quote-csv-field (s)
21358 "Quote field for inclusion in CSV material."
21359 (if (string-match "[\",]" s)
21360 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21361 s))
21362
21363 (defun org-force-self-insert (N)
21364 "Needed to enforce self-insert under remapping."
21365 (interactive "p")
21366 (self-insert-command N))
21367
21368 (defun org-string-width (s)
21369 "Compute width of string, ignoring invisible characters.
21370 This ignores character with invisibility property `org-link', and also
21371 characters with property `org-cwidth', because these will become invisible
21372 upon the next fontification round."
21373 (let (b l)
21374 (when (or (eq t buffer-invisibility-spec)
21375 (assq 'org-link buffer-invisibility-spec))
21376 (while (setq b (text-property-any 0 (length s)
21377 'invisible 'org-link s))
21378 (setq s (concat (substring s 0 b)
21379 (substring s (or (next-single-property-change
21380 b 'invisible s)
21381 (length s)))))))
21382 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21383 (setq s (concat (substring s 0 b)
21384 (substring s (or (next-single-property-change
21385 b 'org-cwidth s)
21386 (length s))))))
21387 (setq l (string-width s) b -1)
21388 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21389 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21390 l))
21391
21392 (defun org-shorten-string (s maxlength)
21393 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21394 If the string is shorter or has length MAXLENGTH, just return the
21395 original string. If it is longer, the functions finds a space in the
21396 string, breaks this string off at that locations and adds three dots
21397 as ellipsis. Including the ellipsis, the string will not be longer
21398 than MAXLENGTH. If finding a good breaking point in the string does
21399 not work, the string is just chopped off in the middle of a word
21400 if necessary."
21401 (if (<= (length s) maxlength)
21402 s
21403 (let* ((n (max (- maxlength 4) 1))
21404 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21405 (if (string-match re s)
21406 (concat (match-string 1 s) "...")
21407 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21408
21409 (defun org-get-indentation (&optional line)
21410 "Get the indentation of the current line, interpreting tabs.
21411 When LINE is given, assume it represents a line and compute its indentation."
21412 (if line
21413 (if (string-match "^ *" (org-remove-tabs line))
21414 (match-end 0))
21415 (save-excursion
21416 (beginning-of-line 1)
21417 (skip-chars-forward " \t")
21418 (current-column))))
21419
21420 (defun org-get-string-indentation (s)
21421 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21422 (let ((n -1) (i 0) (w tab-width) c)
21423 (catch 'exit
21424 (while (< (setq n (1+ n)) (length s))
21425 (setq c (aref s n))
21426 (cond ((= c ?\ ) (setq i (1+ i)))
21427 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21428 (t (throw 'exit t)))))
21429 i))
21430
21431 (defun org-remove-tabs (s &optional width)
21432 "Replace tabulators in S with spaces.
21433 Assumes that s is a single line, starting in column 0."
21434 (setq width (or width tab-width))
21435 (while (string-match "\t" s)
21436 (setq s (replace-match
21437 (make-string
21438 (- (* width (/ (+ (match-beginning 0) width) width))
21439 (match-beginning 0)) ?\ )
21440 t t s)))
21441 s)
21442
21443 (defun org-fix-indentation (line ind)
21444 "Fix indentation in LINE.
21445 IND is a cons cell with target and minimum indentation.
21446 If the current indentation in LINE is smaller than the minimum,
21447 leave it alone. If it is larger than ind, set it to the target."
21448 (let* ((l (org-remove-tabs line))
21449 (i (org-get-indentation l))
21450 (i1 (car ind)) (i2 (cdr ind)))
21451 (if (>= i i2) (setq l (substring line i2)))
21452 (if (> i1 0)
21453 (concat (make-string i1 ?\ ) l)
21454 l)))
21455
21456 (defun org-remove-indentation (code &optional n)
21457 "Remove the maximum common indentation from the lines in CODE.
21458 N may optionally be the number of spaces to remove."
21459 (with-temp-buffer
21460 (insert code)
21461 (org-do-remove-indentation n)
21462 (buffer-string)))
21463
21464 (defun org-do-remove-indentation (&optional n)
21465 "Remove the maximum common indentation from the buffer."
21466 (untabify (point-min) (point-max))
21467 (let ((min 10000) re)
21468 (if n
21469 (setq min n)
21470 (goto-char (point-min))
21471 (while (re-search-forward "^ *[^ \n]" nil t)
21472 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21473 (unless (or (= min 0) (= min 10000))
21474 (setq re (format "^ \\{%d\\}" min))
21475 (goto-char (point-min))
21476 (while (re-search-forward re nil t)
21477 (replace-match "")
21478 (end-of-line 1))
21479 min)))
21480
21481 (defun org-fill-template (template alist)
21482 "Find each %key of ALIST in TEMPLATE and replace it."
21483 (let ((case-fold-search nil))
21484 (dolist (entry (sort (copy-sequence alist)
21485 (lambda (a b) (< (length (car a)) (length (car b))))))
21486 (setq template
21487 (replace-regexp-in-string
21488 (concat "%" (regexp-quote (car entry)))
21489 (or (cdr entry) "") template t t)))
21490 template))
21491
21492 (defun org-base-buffer (buffer)
21493 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21494 (if (not buffer)
21495 buffer
21496 (or (buffer-base-buffer buffer)
21497 buffer)))
21498
21499 (defun org-trim (s)
21500 "Remove whitespace at beginning and end of string."
21501 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21502 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21503 s)
21504
21505 (defun org-wrap (string &optional width lines)
21506 "Wrap string to either a number of lines, or a width in characters.
21507 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21508 that costs. If there is a word longer than WIDTH, the text is actually
21509 wrapped to the length of that word.
21510 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21511 many lines, whatever width that takes.
21512 The return value is a list of lines, without newlines at the end."
21513 (let* ((words (org-split-string string "[ \t\n]+"))
21514 (maxword (apply 'max (mapcar 'org-string-width words)))
21515 w ll)
21516 (cond (width
21517 (org-do-wrap words (max maxword width)))
21518 (lines
21519 (setq w maxword)
21520 (setq ll (org-do-wrap words maxword))
21521 (if (<= (length ll) lines)
21522 ll
21523 (setq ll words)
21524 (while (> (length ll) lines)
21525 (setq w (1+ w))
21526 (setq ll (org-do-wrap words w)))
21527 ll))
21528 (t (error "Cannot wrap this")))))
21529
21530 (defun org-do-wrap (words width)
21531 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21532 (let (lines line)
21533 (while words
21534 (setq line (pop words))
21535 (while (and words (< (+ (length line) (length (car words))) width))
21536 (setq line (concat line " " (pop words))))
21537 (setq lines (push line lines)))
21538 (nreverse lines)))
21539
21540 (defun org-split-string (string &optional separators)
21541 "Splits STRING into substrings at SEPARATORS.
21542 No empty strings are returned if there are matches at the beginning
21543 and end of string."
21544 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21545 (start 0)
21546 notfirst
21547 (list nil))
21548 (while (and (string-match rexp string
21549 (if (and notfirst
21550 (= start (match-beginning 0))
21551 (< start (length string)))
21552 (1+ start) start))
21553 (< (match-beginning 0) (length string)))
21554 (setq notfirst t)
21555 (or (eq (match-beginning 0) 0)
21556 (and (eq (match-beginning 0) (match-end 0))
21557 (eq (match-beginning 0) start))
21558 (setq list
21559 (cons (substring string start (match-beginning 0))
21560 list)))
21561 (setq start (match-end 0)))
21562 (or (eq start (length string))
21563 (setq list
21564 (cons (substring string start)
21565 list)))
21566 (nreverse list)))
21567
21568 (defun org-quote-vert (s)
21569 "Replace \"|\" with \"\\vert\"."
21570 (while (string-match "|" s)
21571 (setq s (replace-match "\\vert" t t s)))
21572 s)
21573
21574 (defun org-uuidgen-p (s)
21575 "Is S an ID created by UUIDGEN?"
21576 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21577
21578 (defun org-in-src-block-p (&optional inside)
21579 "Whether point is in a code source block.
21580 When INSIDE is non-nil, don't consider we are within a src block
21581 when point is at #+BEGIN_SRC or #+END_SRC."
21582 (let ((case-fold-search t) ov)
21583 (or (and (setq ov (overlays-at (point)))
21584 (memq 'org-block-background
21585 (overlay-properties (car ov))))
21586 (and (not inside)
21587 (save-match-data
21588 (save-excursion
21589 (beginning-of-line)
21590 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21591
21592 (defun org-context ()
21593 "Return a list of contexts of the current cursor position.
21594 If several contexts apply, all are returned.
21595 Each context entry is a list with a symbol naming the context, and
21596 two positions indicating start and end of the context. Possible
21597 contexts are:
21598
21599 :headline anywhere in a headline
21600 :headline-stars on the leading stars in a headline
21601 :todo-keyword on a TODO keyword (including DONE) in a headline
21602 :tags on the TAGS in a headline
21603 :priority on the priority cookie in a headline
21604 :item on the first line of a plain list item
21605 :item-bullet on the bullet/number of a plain list item
21606 :checkbox on the checkbox in a plain list item
21607 :table in an org-mode table
21608 :table-special on a special filed in a table
21609 :table-table in a table.el table
21610 :clocktable in a clocktable
21611 :src-block in a source block
21612 :link on a hyperlink
21613 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21614 :target on a <<target>>
21615 :radio-target on a <<<radio-target>>>
21616 :latex-fragment on a LaTeX fragment
21617 :latex-preview on a LaTeX fragment with overlaid preview image
21618
21619 This function expects the position to be visible because it uses font-lock
21620 faces as a help to recognize the following contexts: :table-special, :link,
21621 and :keyword."
21622 (let* ((f (get-text-property (point) 'face))
21623 (faces (if (listp f) f (list f)))
21624 (case-fold-search t)
21625 (p (point)) clist o)
21626 ;; First the large context
21627 (cond
21628 ((org-at-heading-p t)
21629 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21630 (when (progn
21631 (beginning-of-line 1)
21632 (looking-at org-todo-line-tags-regexp))
21633 (push (org-point-in-group p 1 :headline-stars) clist)
21634 (push (org-point-in-group p 2 :todo-keyword) clist)
21635 (push (org-point-in-group p 4 :tags) clist))
21636 (goto-char p)
21637 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21638 (if (looking-at "\\[#[A-Z0-9]\\]")
21639 (push (org-point-in-group p 0 :priority) clist)))
21640
21641 ((org-at-item-p)
21642 (push (org-point-in-group p 2 :item-bullet) clist)
21643 (push (list :item (point-at-bol)
21644 (save-excursion (org-end-of-item) (point)))
21645 clist)
21646 (and (org-at-item-checkbox-p)
21647 (push (org-point-in-group p 0 :checkbox) clist)))
21648
21649 ((org-at-table-p)
21650 (push (list :table (org-table-begin) (org-table-end)) clist)
21651 (if (memq 'org-formula faces)
21652 (push (list :table-special
21653 (previous-single-property-change p 'face)
21654 (next-single-property-change p 'face)) clist)))
21655 ((org-at-table-p 'any)
21656 (push (list :table-table) clist)))
21657 (goto-char p)
21658
21659 (let ((case-fold-search t))
21660 ;; New the "medium" contexts: clocktables, source blocks
21661 (cond ((org-in-clocktable-p)
21662 (push (list :clocktable
21663 (and (or (looking-at "#\\+BEGIN: clocktable")
21664 (search-backward "#+BEGIN: clocktable" nil t))
21665 (match-beginning 0))
21666 (and (re-search-forward "#\\+END:?" nil t)
21667 (match-end 0))) clist))
21668 ((org-in-src-block-p)
21669 (push (list :src-block
21670 (and (or (looking-at "#\\+BEGIN_SRC")
21671 (search-backward "#+BEGIN_SRC" nil t))
21672 (match-beginning 0))
21673 (and (search-forward "#+END_SRC" nil t)
21674 (match-beginning 0))) clist))))
21675 (goto-char p)
21676
21677 ;; Now the small context
21678 (cond
21679 ((org-at-timestamp-p)
21680 (push (org-point-in-group p 0 :timestamp) clist))
21681 ((memq 'org-link faces)
21682 (push (list :link
21683 (previous-single-property-change p 'face)
21684 (next-single-property-change p 'face)) clist))
21685 ((memq 'org-special-keyword faces)
21686 (push (list :keyword
21687 (previous-single-property-change p 'face)
21688 (next-single-property-change p 'face)) clist))
21689 ((org-at-target-p)
21690 (push (org-point-in-group p 0 :target) clist)
21691 (goto-char (1- (match-beginning 0)))
21692 (if (looking-at org-radio-target-regexp)
21693 (push (org-point-in-group p 0 :radio-target) clist))
21694 (goto-char p))
21695 ((setq o (car (delq nil
21696 (mapcar
21697 (lambda (x)
21698 (if (memq x org-latex-fragment-image-overlays) x))
21699 (overlays-at (point))))))
21700 (push (list :latex-fragment
21701 (overlay-start o) (overlay-end o)) clist)
21702 (push (list :latex-preview
21703 (overlay-start o) (overlay-end o)) clist))
21704 ((org-inside-LaTeX-fragment-p)
21705 ;; FIXME: positions wrong.
21706 (push (list :latex-fragment (point) (point)) clist)))
21707
21708 (setq clist (nreverse (delq nil clist)))
21709 clist))
21710
21711 ;; FIXME: Compare with at-regexp-p Do we need both?
21712 (defun org-in-regexp (re &optional nlines visually)
21713 "Check if point is inside a match of regexp.
21714 Normally only the current line is checked, but you can include NLINES extra
21715 lines both before and after point into the search.
21716 If VISUALLY is set, require that the cursor is not after the match but
21717 really on, so that the block visually is on the match."
21718 (catch 'exit
21719 (let ((pos (point))
21720 (eol (point-at-eol (+ 1 (or nlines 0))))
21721 (inc (if visually 1 0)))
21722 (save-excursion
21723 (beginning-of-line (- 1 (or nlines 0)))
21724 (while (re-search-forward re eol t)
21725 (if (and (<= (match-beginning 0) pos)
21726 (>= (+ inc (match-end 0)) pos))
21727 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21728
21729 (defun org-at-regexp-p (regexp)
21730 "Is point inside a match of REGEXP in the current line?"
21731 (catch 'exit
21732 (save-excursion
21733 (let ((pos (point)) (end (point-at-eol)))
21734 (beginning-of-line 1)
21735 (while (re-search-forward regexp end t)
21736 (if (and (<= (match-beginning 0) pos)
21737 (>= (match-end 0) pos))
21738 (throw 'exit t)))
21739 nil))))
21740
21741 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21742 "Non-nil when point is between matches of START-RE and END-RE.
21743
21744 Also return a non-nil value when point is on one of the matches.
21745
21746 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21747 buffer positions. Default values are the positions of headlines
21748 surrounding the point.
21749
21750 The functions returns a cons cell whose car (resp. cdr) is the
21751 position before START-RE (resp. after END-RE)."
21752 (save-match-data
21753 (let ((pos (point))
21754 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21755 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21756 beg end)
21757 (save-excursion
21758 ;; Point is on a block when on START-RE or if START-RE can be
21759 ;; found before it...
21760 (and (or (org-at-regexp-p start-re)
21761 (re-search-backward start-re limit-up t))
21762 (setq beg (match-beginning 0))
21763 ;; ... and END-RE after it...
21764 (goto-char (match-end 0))
21765 (re-search-forward end-re limit-down t)
21766 (> (setq end (match-end 0)) pos)
21767 ;; ... without another START-RE in-between.
21768 (goto-char (match-beginning 0))
21769 (not (re-search-backward start-re (1+ beg) t))
21770 ;; Return value.
21771 (cons beg end))))))
21772
21773 (defun org-in-block-p (names)
21774 "Non-nil when point belongs to a block whose name belongs to NAMES.
21775
21776 NAMES is a list of strings containing names of blocks.
21777
21778 Return first block name matched, or nil. Beware that in case of
21779 nested blocks, the returned name may not belong to the closest
21780 block from point."
21781 (save-match-data
21782 (catch 'exit
21783 (let ((case-fold-search t)
21784 (lim-up (save-excursion (outline-previous-heading)))
21785 (lim-down (save-excursion (outline-next-heading))))
21786 (mapc (lambda (name)
21787 (let ((n (regexp-quote name)))
21788 (when (org-between-regexps-p
21789 (concat "^[ \t]*#\\+begin_" n)
21790 (concat "^[ \t]*#\\+end_" n)
21791 lim-up lim-down)
21792 (throw 'exit n))))
21793 names))
21794 nil)))
21795
21796 (defun org-in-drawer-p ()
21797 "Is point within a drawer?"
21798 (save-match-data
21799 (let ((case-fold-search t)
21800 (lim-up (save-excursion (outline-previous-heading)))
21801 (lim-down (save-excursion (outline-next-heading))))
21802 (org-between-regexps-p
21803 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21804 "^[ \t]*:end:.*$"
21805 lim-up lim-down))))
21806
21807 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21808 "Call `multi-occur' with buffers for all agenda files."
21809 (interactive "sOrg-files matching: ")
21810 (let* ((files (org-agenda-files))
21811 (tnames (mapcar #'file-truename files))
21812 (extra org-agenda-text-search-extra-files))
21813 (when (eq (car extra) 'agenda-archives)
21814 (setq extra (cdr extra))
21815 (setq files (org-add-archive-files files)))
21816 (dolist (f extra)
21817 (unless (member (file-truename f) tnames)
21818 (unless (member f files) (setq files (append files (list f))))
21819 (setq tnames (append tnames (list (file-truename f))))))
21820 (multi-occur
21821 (mapcar (lambda (x)
21822 (with-current-buffer
21823 ;; FIXME: Why not just (find-file-noselect x)?
21824 ;; Is it to avoid the "revert buffer" prompt?
21825 (or (get-file-buffer x) (find-file-noselect x))
21826 (widen)
21827 (current-buffer)))
21828 files)
21829 regexp)))
21830
21831 (if (boundp 'occur-mode-find-occurrence-hook)
21832 ;; Emacs 23
21833 (add-hook 'occur-mode-find-occurrence-hook
21834 (lambda ()
21835 (when (derived-mode-p 'org-mode)
21836 (org-reveal))))
21837 ;; Emacs 22
21838 (defadvice occur-mode-goto-occurrence
21839 (after org-occur-reveal activate)
21840 (and (derived-mode-p 'org-mode) (org-reveal)))
21841 (defadvice occur-mode-goto-occurrence-other-window
21842 (after org-occur-reveal activate)
21843 (and (derived-mode-p 'org-mode) (org-reveal)))
21844 (defadvice occur-mode-display-occurrence
21845 (after org-occur-reveal activate)
21846 (when (derived-mode-p 'org-mode)
21847 (let ((pos (occur-mode-find-occurrence)))
21848 (with-current-buffer (marker-buffer pos)
21849 (save-excursion
21850 (goto-char pos)
21851 (org-reveal)))))))
21852
21853 (defun org-occur-link-in-agenda-files ()
21854 "Create a link and search for it in the agendas.
21855 The link is not stored in `org-stored-links', it is just created
21856 for the search purpose."
21857 (interactive)
21858 (let ((link (condition-case nil
21859 (org-store-link nil)
21860 (error "Unable to create a link to here"))))
21861 (org-occur-in-agenda-files (regexp-quote link))))
21862
21863 (defun org-reverse-string (string)
21864 "Return the reverse of STRING."
21865 (apply 'string (reverse (string-to-list string))))
21866
21867 ;; defsubst org-uniquify must be defined before first use
21868
21869 (defun org-uniquify-alist (alist)
21870 "Merge elements of ALIST with the same key.
21871
21872 For example, in this alist:
21873
21874 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
21875 => \\='((a 1 3) (b 2))
21876
21877 merge (a 1) and (a 3) into (a 1 3).
21878
21879 The function returns the new ALIST."
21880 (let (rtn)
21881 (mapc
21882 (lambda (e)
21883 (let (n)
21884 (if (not (assoc (car e) rtn))
21885 (push e rtn)
21886 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21887 (setq rtn (assq-delete-all (car e) rtn))
21888 (push n rtn))))
21889 alist)
21890 rtn))
21891
21892 (defun org-delete-all (elts list)
21893 "Remove all elements in ELTS from LIST."
21894 (while elts
21895 (setq list (delete (pop elts) list)))
21896 list)
21897
21898 (defun org-count (cl-item cl-seq)
21899 "Count the number of occurrences of ITEM in SEQ.
21900 Taken from `count' in cl-seq.el with all keyword arguments removed."
21901 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21902 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21903 (while (< cl-start cl-end)
21904 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21905 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21906 (setq cl-start (1+ cl-start)))
21907 cl-count))
21908
21909 (defun org-remove-if (predicate seq)
21910 "Remove everything from SEQ that fulfills PREDICATE."
21911 (let (res e)
21912 (while seq
21913 (setq e (pop seq))
21914 (if (not (funcall predicate e)) (push e res)))
21915 (nreverse res)))
21916
21917 (defun org-remove-if-not (predicate seq)
21918 "Remove everything from SEQ that does not fulfill PREDICATE."
21919 (let (res e)
21920 (while seq
21921 (setq e (pop seq))
21922 (if (funcall predicate e) (push e res)))
21923 (nreverse res)))
21924
21925 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21926 "Reduce two-argument FUNCTION across SEQ.
21927 Taken from `reduce' in cl-seq.el with all keyword arguments but
21928 \":initial-value\" removed."
21929 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21930 (cadr (memq :initial-value cl-keys)))
21931 (cl-seq (pop cl-seq))
21932 (t (funcall cl-func)))))
21933 (while cl-seq
21934 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21935 cl-accum))
21936
21937 (defun org-every (pred seq)
21938 "Return true if PREDICATE is true of every element of SEQ.
21939 Adapted from `every' in cl.el."
21940 (catch 'org-every
21941 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21942 t))
21943
21944 (defun org-some (pred seq)
21945 "Return true if PREDICATE is true of any element of SEQ.
21946 Adapted from `some' in cl.el."
21947 (catch 'org-some
21948 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21949 nil))
21950
21951 (defun org-back-over-empty-lines ()
21952 "Move backwards over whitespace, to the beginning of the first empty line.
21953 Returns the number of empty lines passed."
21954 (let ((pos (point)))
21955 (if (cdr (assoc 'heading org-blank-before-new-entry))
21956 (skip-chars-backward " \t\n\r")
21957 (unless (eobp)
21958 (forward-line -1)))
21959 (beginning-of-line 2)
21960 (goto-char (min (point) pos))
21961 (count-lines (point) pos)))
21962
21963 (defun org-skip-whitespace ()
21964 (skip-chars-forward " \t\n\r"))
21965
21966 (defun org-point-in-group (point group &optional context)
21967 "Check if POINT is in match-group GROUP.
21968 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21969 match. If the match group does not exist or point is not inside it,
21970 return nil."
21971 (and (match-beginning group)
21972 (>= point (match-beginning group))
21973 (<= point (match-end group))
21974 (if context
21975 (list context (match-beginning group) (match-end group))
21976 t)))
21977
21978 (defun org-switch-to-buffer-other-window (&rest args)
21979 "Switch to buffer in a second window on the current frame.
21980 In particular, do not allow pop-up frames.
21981 Returns the newly created buffer."
21982 (org-no-popups
21983 (apply 'switch-to-buffer-other-window args)))
21984
21985 (defun org-combine-plists (&rest plists)
21986 "Create a single property list from all plists in PLISTS.
21987 The process starts by copying the first list, and then setting properties
21988 from the other lists. Settings in the last list are the most significant
21989 ones and overrule settings in the other lists."
21990 (let ((rtn (copy-sequence (pop plists)))
21991 p v ls)
21992 (while plists
21993 (setq ls (pop plists))
21994 (while ls
21995 (setq p (pop ls) v (pop ls))
21996 (setq rtn (plist-put rtn p v))))
21997 rtn))
21998
21999 (defun org-replace-escapes (string table)
22000 "Replace %-escapes in STRING with values in TABLE.
22001 TABLE is an association list with keys like \"%a\" and string values.
22002 The sequences in STRING may contain normal field width and padding information,
22003 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22004 so values can contain further %-escapes if they are define later in TABLE."
22005 (let ((tbl (copy-alist table))
22006 (case-fold-search nil)
22007 (pchg 0)
22008 e re rpl)
22009 (dolist (e tbl)
22010 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22011 (when (and (cdr e) (string-match re (cdr e)))
22012 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22013 (safe "SREF"))
22014 (add-text-properties 0 3 (list 'sref sref) safe)
22015 (setcdr e (replace-match safe t t (cdr e)))))
22016 (while (string-match re string)
22017 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22018 (cdr e)))
22019 (setq string (replace-match rpl t t string))))
22020 (while (setq pchg (next-property-change pchg string))
22021 (let ((sref (get-text-property pchg 'sref string)))
22022 (when (and sref (string-match "SREF" string pchg))
22023 (setq string (replace-match sref t t string)))))
22024 string))
22025
22026 (defun org-sublist (list start end)
22027 "Return a section of LIST, from START to END.
22028 Counting starts at 1."
22029 (let (rtn (c start))
22030 (setq list (nthcdr (1- start) list))
22031 (while (and list (<= c end))
22032 (push (pop list) rtn)
22033 (setq c (1+ c)))
22034 (nreverse rtn)))
22035
22036 (defun org-find-base-buffer-visiting (file)
22037 "Like `find-buffer-visiting' but always return the base buffer and
22038 not an indirect buffer."
22039 (let ((buf (or (get-file-buffer file)
22040 (find-buffer-visiting file))))
22041 (if buf
22042 (or (buffer-base-buffer buf) buf)
22043 nil)))
22044
22045 (defun org-image-file-name-regexp (&optional extensions)
22046 "Return regexp matching the file names of images.
22047 If EXTENSIONS is given, only match these."
22048 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22049 (image-file-name-regexp)
22050 (let ((image-file-name-extensions
22051 (or extensions
22052 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22053 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22054 (concat "\\."
22055 (regexp-opt (nconc (mapcar 'upcase
22056 image-file-name-extensions)
22057 image-file-name-extensions)
22058 t)
22059 "\\'"))))
22060
22061 (defun org-file-image-p (file &optional extensions)
22062 "Return non-nil if FILE is an image."
22063 (save-match-data
22064 (string-match (org-image-file-name-regexp extensions) file)))
22065
22066 (defun org-get-cursor-date (&optional with-time)
22067 "Return the date at cursor in as a time.
22068 This works in the calendar and in the agenda, anywhere else it just
22069 returns the current time.
22070 If WITH-TIME is non-nil, returns the time of the event at point (in
22071 the agenda) or the current time of the day."
22072 (let (date day defd tp hod mod)
22073 (when with-time
22074 (setq tp (get-text-property (point) 'time))
22075 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22076 (setq hod (string-to-number (match-string 1 tp))
22077 mod (string-to-number (match-string 2 tp))))
22078 (or tp (let ((now (decode-time)))
22079 (setq hod (nth 2 now)
22080 mod (nth 1 now)))))
22081 (cond
22082 ((eq major-mode 'calendar-mode)
22083 (setq date (calendar-cursor-to-date)
22084 defd (encode-time 0 (or mod 0) (or hod 0)
22085 (nth 1 date) (nth 0 date) (nth 2 date))))
22086 ((eq major-mode 'org-agenda-mode)
22087 (setq day (get-text-property (point) 'day))
22088 (if day
22089 (setq date (calendar-gregorian-from-absolute day)
22090 defd (encode-time 0 (or mod 0) (or hod 0)
22091 (nth 1 date) (nth 0 date) (nth 2 date))))))
22092 (or defd (current-time))))
22093
22094 (defun org-mark-subtree (&optional up)
22095 "Mark the current subtree.
22096 This puts point at the start of the current subtree, and mark at
22097 the end. If a numeric prefix UP is given, move up into the
22098 hierarchy of headlines by UP levels before marking the subtree."
22099 (interactive "P")
22100 (org-with-limited-levels
22101 (cond ((org-at-heading-p) (beginning-of-line))
22102 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22103 (t (outline-previous-visible-heading 1))))
22104 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22105 (if (org-called-interactively-p 'any)
22106 (call-interactively 'org-mark-element)
22107 (org-mark-element)))
22108
22109
22110 ;;; Indentation
22111
22112 (defun org-indent-line ()
22113 "Indent line depending on context."
22114 (interactive)
22115 (let* ((pos (point))
22116 (itemp (org-at-item-p))
22117 (case-fold-search t)
22118 (org-drawer-regexp (or org-drawer-regexp "\000"))
22119 (inline-task-p (and (featurep 'org-inlinetask)
22120 (org-inlinetask-in-task-p)))
22121 (inline-re (and inline-task-p
22122 (org-inlinetask-outline-regexp)))
22123 column)
22124 (if (and orgstruct-is-++ (eq pos (point)))
22125 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22126 (indent-according-to-mode))
22127 (beginning-of-line 1)
22128 (cond
22129 ;; Headings
22130 ((looking-at org-outline-regexp) (setq column 0))
22131 ;; Footnote definition
22132 ((looking-at org-footnote-definition-re) (setq column 0))
22133 ;; Literal examples
22134 ((looking-at "[ \t]*:\\( \\|$\\)")
22135 (setq column (org-get-indentation))) ; do nothing
22136 ;; Lists
22137 ((ignore-errors (goto-char (org-in-item-p)))
22138 (setq column (if itemp
22139 (org-get-indentation)
22140 (org-list-item-body-column (point))))
22141 (goto-char pos))
22142 ;; Drawers
22143 ((and (looking-at "[ \t]*:END:")
22144 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22145 (save-excursion
22146 (goto-char (1- (match-beginning 1)))
22147 (setq column (current-column))))
22148 ;; Special blocks
22149 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22150 (save-excursion
22151 (re-search-backward
22152 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22153 (setq column (org-get-indentation (match-string 0))))
22154 ((and (not (looking-at "[ \t]*#\\+begin_"))
22155 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22156 (save-excursion
22157 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22158 (setq column
22159 (cond ((equal (downcase (match-string 1)) "src")
22160 ;; src blocks: let `org-edit-src-exit' handle them
22161 (org-get-indentation))
22162 ((equal (downcase (match-string 1)) "example")
22163 (max (org-get-indentation)
22164 (org-get-indentation (match-string 0))))
22165 (t
22166 (org-get-indentation (match-string 0))))))
22167 ;; This line has nothing special, look at the previous relevant
22168 ;; line to compute indentation
22169 (t
22170 (beginning-of-line 0)
22171 (while (and (not (bobp))
22172 (not (looking-at org-table-line-regexp))
22173 (not (looking-at org-drawer-regexp))
22174 ;; When point started in an inline task, do not move
22175 ;; above task starting line.
22176 (not (and inline-task-p (looking-at inline-re)))
22177 ;; Skip drawers, blocks, empty lines, verbatim,
22178 ;; comments, tables, footnotes definitions, lists,
22179 ;; inline tasks.
22180 (or (and (looking-at "[ \t]*:END:")
22181 (re-search-backward org-drawer-regexp nil t))
22182 (and (looking-at "[ \t]*#\\+end_")
22183 (re-search-backward "[ \t]*#\\+begin_"nil t))
22184 (looking-at "[ \t]*[\n:#|]")
22185 (looking-at org-footnote-definition-re)
22186 (and (not inline-task-p)
22187 (featurep 'org-inlinetask)
22188 (org-inlinetask-in-task-p)
22189 (or (org-inlinetask-goto-beginning) t))))
22190 (beginning-of-line 0))
22191 (cond
22192 ;; There was a list item above.
22193 ((ignore-errors (goto-char (org-in-item-p)))
22194 (goto-char (org-list-get-top-point (org-list-struct)))
22195 (setq column (org-get-indentation)))
22196 ;; There was an heading above.
22197 ((looking-at "\\*+[ \t]+")
22198 (if (not org-adapt-indentation)
22199 (setq column 0)
22200 (goto-char (match-end 0))
22201 (setq column (current-column))))
22202 ;; A drawer had started and is unfinished
22203 ((looking-at org-drawer-regexp)
22204 (goto-char (1- (match-beginning 1)))
22205 (setq column (current-column)))
22206 ;; Else, nothing noticeable found: get indentation and go on.
22207 (t (setq column (org-get-indentation))))))
22208 ;; Now apply indentation and move cursor accordingly
22209 (goto-char pos)
22210 (if (<= (current-column) (current-indentation))
22211 (org-indent-line-to column)
22212 (save-excursion (org-indent-line-to column)))
22213 ;; Special polishing for properties, see `org-property-format'
22214 (setq column (current-column))
22215 (beginning-of-line 1)
22216 (if (looking-at org-property-re)
22217 (replace-match (concat (match-string 4)
22218 (format org-property-format
22219 (match-string 1) (match-string 3)))
22220 t t))
22221 (org-move-to-column column))))
22222
22223 (defun org-indent-drawer ()
22224 "Indent the drawer at point."
22225 (interactive)
22226 (let ((p (point))
22227 (e (and (save-excursion (re-search-forward ":END:" nil t))
22228 (match-end 0)))
22229 (folded
22230 (save-excursion
22231 (end-of-line)
22232 (when (overlays-at (point))
22233 (member 'invisible (overlay-properties
22234 (car (overlays-at (point)))))))))
22235 (when folded (org-cycle))
22236 (indent-for-tab-command)
22237 (while (and (move-beginning-of-line 2) (< (point) e))
22238 (indent-for-tab-command))
22239 (goto-char p)
22240 (when folded (org-cycle)))
22241 (message "Drawer at point indented"))
22242
22243 (defun org-indent-block ()
22244 "Indent the block at point."
22245 (interactive)
22246 (let ((p (point))
22247 (case-fold-search t)
22248 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22249 (match-end 0)))
22250 (folded
22251 (save-excursion
22252 (end-of-line)
22253 (when (overlays-at (point))
22254 (member 'invisible (overlay-properties
22255 (car (overlays-at (point)))))))))
22256 (when folded (org-cycle))
22257 (indent-for-tab-command)
22258 (while (and (move-beginning-of-line 2) (< (point) e))
22259 (indent-for-tab-command))
22260 (goto-char p)
22261 (when folded (org-cycle)))
22262 (message "Block at point indented"))
22263
22264 (defun org-indent-region (start end)
22265 "Indent region."
22266 (interactive "r")
22267 (save-excursion
22268 (let ((line-end (org-current-line end)))
22269 (goto-char start)
22270 (while (< (org-current-line) line-end)
22271 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22272 (t (call-interactively 'org-indent-line)))
22273 (move-beginning-of-line 2)))))
22274
22275
22276 ;;; Filling
22277
22278 ;; We use our own fill-paragraph and auto-fill functions.
22279
22280 ;; `org-fill-paragraph' relies on adaptive filling and context
22281 ;; checking. Appropriate `fill-prefix' is computed with
22282 ;; `org-adaptive-fill-function'.
22283
22284 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22285 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22286 ;; `org-adaptive-fill-function' value. Internally,
22287 ;; `org-comment-line-break-function' breaks the line.
22288
22289 ;; `org-setup-filling' installs filling and auto-filling related
22290 ;; variables during `org-mode' initialization.
22291
22292 (defvar org-element-paragraph-separate) ; org-element.el
22293 (defun org-setup-filling ()
22294 (require 'org-element)
22295 ;; Prevent auto-fill from inserting unwanted new items.
22296 (when (boundp 'fill-nobreak-predicate)
22297 (org-set-local
22298 'fill-nobreak-predicate
22299 (org-uniquify
22300 (append fill-nobreak-predicate
22301 '(org-fill-line-break-nobreak-p
22302 org-fill-paragraph-with-timestamp-nobreak-p)))))
22303 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22304 (org-set-local 'paragraph-start paragraph-ending)
22305 (org-set-local 'paragraph-separate paragraph-ending))
22306 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22307 (org-set-local 'auto-fill-inhibit-regexp nil)
22308 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22309 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22310 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22311
22312 (defun org-fill-line-break-nobreak-p ()
22313 "Non-nil when a new line at point would create an Org line break."
22314 (save-excursion
22315 (skip-chars-backward "[ \t]")
22316 (skip-chars-backward "\\\\")
22317 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22318
22319 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22320 "Non-nil when a new line at point would split a timestamp."
22321 (and (org-at-timestamp-p t)
22322 (not (looking-at org-ts-regexp-both))))
22323
22324 (declare-function message-in-body-p "message" ())
22325 (defvar orgtbl-line-start-regexp) ; From org-table.el
22326 (defun org-adaptive-fill-function ()
22327 "Compute a fill prefix for the current line.
22328 Return fill prefix, as a string, or nil if current line isn't
22329 meant to be filled. For convenience, if `adaptive-fill-regexp'
22330 matches in paragraphs or comments, use it."
22331 (catch 'exit
22332 (when (derived-mode-p 'message-mode)
22333 (save-excursion
22334 (beginning-of-line)
22335 (cond ((or (not (message-in-body-p))
22336 (looking-at orgtbl-line-start-regexp))
22337 (throw 'exit nil))
22338 ((looking-at message-cite-prefix-regexp)
22339 (throw 'exit (match-string-no-properties 0)))
22340 ((looking-at org-outline-regexp)
22341 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22342 (org-with-wide-buffer
22343 (let* ((p (line-beginning-position))
22344 (element (save-excursion
22345 (beginning-of-line)
22346 (or (ignore-errors (org-element-at-point))
22347 (user-error "An element cannot be parsed line %d"
22348 (line-number-at-pos (point))))))
22349 (type (org-element-type element))
22350 (post-affiliated (org-element-property :post-affiliated element)))
22351 (unless (and post-affiliated (< p post-affiliated))
22352 (case type
22353 (comment
22354 (save-excursion
22355 (beginning-of-line)
22356 (looking-at "[ \t]*")
22357 (concat (match-string 0) "# ")))
22358 (footnote-definition "")
22359 ((item plain-list)
22360 (make-string (org-list-item-body-column
22361 (or post-affiliated
22362 (org-element-property :begin element)))
22363 ? ))
22364 (paragraph
22365 ;; Fill prefix is usually the same as the current line,
22366 ;; unless the paragraph is at the beginning of an item.
22367 (let ((parent (org-element-property :parent element)))
22368 (save-excursion
22369 (beginning-of-line)
22370 (cond ((eq (org-element-type parent) 'item)
22371 (make-string (org-list-item-body-column
22372 (org-element-property :begin parent))
22373 ? ))
22374 ((and adaptive-fill-regexp
22375 ;; Locally disable
22376 ;; `adaptive-fill-function' to let
22377 ;; `fill-context-prefix' handle
22378 ;; `adaptive-fill-regexp' variable.
22379 (let (adaptive-fill-function)
22380 (fill-context-prefix
22381 post-affiliated
22382 (org-element-property :end element)))))
22383 ((looking-at "[ \t]+") (match-string 0))
22384 (t "")))))
22385 (comment-block
22386 ;; Only fill contents if P is within block boundaries.
22387 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22388 (forward-line)
22389 (point)))
22390 (cend (save-excursion
22391 (goto-char (org-element-property :end element))
22392 (skip-chars-backward " \r\t\n")
22393 (line-beginning-position))))
22394 (when (and (>= p cbeg) (< p cend))
22395 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22396 (match-string 0)
22397 ""))))))))))
22398
22399 (declare-function message-goto-body "message" ())
22400 (defvar message-cite-prefix-regexp) ; From message.el
22401 (defun org-fill-paragraph (&optional justify)
22402 "Fill element at point, when applicable.
22403
22404 This function only applies to comment blocks, comments, example
22405 blocks and paragraphs. Also, as a special case, re-align table
22406 when point is at one.
22407
22408 If JUSTIFY is non-nil (interactively, with prefix argument),
22409 justify as well. If `sentence-end-double-space' is non-nil, then
22410 period followed by one space does not end a sentence, so don't
22411 break a line there. The variable `fill-column' controls the
22412 width for filling.
22413
22414 For convenience, when point is at a plain list, an item or
22415 a footnote definition, try to fill the first paragraph within."
22416 (interactive)
22417 (if (and (derived-mode-p 'message-mode)
22418 (or (not (message-in-body-p))
22419 (save-excursion (move-beginning-of-line 1)
22420 (looking-at message-cite-prefix-regexp))))
22421 ;; First ensure filling is correct in message-mode.
22422 (let ((fill-paragraph-function
22423 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22424 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22425 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22426 (paragraph-separate
22427 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22428 (fill-paragraph nil))
22429 (with-syntax-table org-mode-transpose-word-syntax-table
22430 ;; Move to end of line in order to get the first paragraph
22431 ;; within a plain list or a footnote definition.
22432 (let ((element (save-excursion
22433 (end-of-line)
22434 (or (ignore-errors (org-element-at-point))
22435 (user-error "An element cannot be parsed line %d"
22436 (line-number-at-pos (point)))))))
22437 ;; First check if point is in a blank line at the beginning of
22438 ;; the buffer. In that case, ignore filling.
22439 (case (org-element-type element)
22440 ;; Use major mode filling function is src blocks.
22441 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22442 ;; Align Org tables, leave table.el tables as-is.
22443 (table-row (org-table-align) t)
22444 (table
22445 (when (eq (org-element-property :type element) 'org)
22446 (save-excursion
22447 (goto-char (org-element-property :post-affiliated element))
22448 (org-table-align)))
22449 t)
22450 (paragraph
22451 ;; Paragraphs may contain `line-break' type objects.
22452 (let ((beg (max (point-min)
22453 (org-element-property :contents-begin element)))
22454 (end (min (point-max)
22455 (org-element-property :contents-end element))))
22456 ;; Do nothing if point is at an affiliated keyword.
22457 (if (< (line-end-position) beg) t
22458 (when (derived-mode-p 'message-mode)
22459 ;; In `message-mode', do not fill following citation
22460 ;; in current paragraph nor text before message body.
22461 (let ((body-start (save-excursion (message-goto-body))))
22462 (when body-start (setq beg (max body-start beg))))
22463 (when (save-excursion
22464 (re-search-forward
22465 (concat "^" message-cite-prefix-regexp) end t))
22466 (setq end (match-beginning 0))))
22467 ;; Fill paragraph, taking line breaks into account.
22468 ;; For that, slice the paragraph using line breaks as
22469 ;; separators, and fill the parts in reverse order to
22470 ;; avoid messing with markers.
22471 (save-excursion
22472 (goto-char end)
22473 (mapc
22474 (lambda (pos)
22475 (fill-region-as-paragraph pos (point) justify)
22476 (goto-char pos))
22477 ;; Find the list of ending positions for line breaks
22478 ;; in the current paragraph. Add paragraph
22479 ;; beginning to include first slice.
22480 (nreverse
22481 (cons beg
22482 (org-element-map
22483 (org-element--parse-objects
22484 beg end nil (org-element-restriction 'paragraph))
22485 'line-break
22486 (lambda (lb) (org-element-property :end lb)))))))
22487 t)))
22488 ;; Contents of `comment-block' type elements should be
22489 ;; filled as plain text, but only if point is within block
22490 ;; markers.
22491 (comment-block
22492 (let* ((case-fold-search t)
22493 (beg (save-excursion
22494 (goto-char (org-element-property :begin element))
22495 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22496 (forward-line)
22497 (point)))
22498 (end (save-excursion
22499 (goto-char (org-element-property :end element))
22500 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22501 (line-beginning-position))))
22502 (if (or (< (point) beg) (> (point) end)) t
22503 (fill-region-as-paragraph
22504 (save-excursion (end-of-line)
22505 (re-search-backward "^[ \t]*$" beg 'move)
22506 (line-beginning-position))
22507 (save-excursion (beginning-of-line)
22508 (re-search-forward "^[ \t]*$" end 'move)
22509 (line-beginning-position))
22510 justify))))
22511 ;; Fill comments.
22512 (comment
22513 (let ((begin (org-element-property :post-affiliated element))
22514 (end (org-element-property :end element)))
22515 (when (and (>= (point) begin) (<= (point) end))
22516 (let ((begin (save-excursion
22517 (end-of-line)
22518 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22519 (progn (forward-line) (point))
22520 begin)))
22521 (end (save-excursion
22522 (end-of-line)
22523 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22524 (1- (line-beginning-position))
22525 (skip-chars-backward " \r\t\n")
22526 (line-end-position)))))
22527 ;; Do not fill comments when at a blank line.
22528 (when (> end begin)
22529 (let ((fill-prefix
22530 (save-excursion
22531 (beginning-of-line)
22532 (looking-at "[ \t]*#")
22533 (let ((comment-prefix (match-string 0)))
22534 (goto-char (match-end 0))
22535 (if (looking-at adaptive-fill-regexp)
22536 (concat comment-prefix (match-string 0))
22537 (concat comment-prefix " "))))))
22538 (save-excursion
22539 (fill-region-as-paragraph begin end justify))))))
22540 t))
22541 ;; Ignore every other element.
22542 (otherwise t))))))
22543
22544 (defun org-auto-fill-function ()
22545 "Auto-fill function."
22546 ;; Check if auto-filling is meaningful.
22547 (let ((fc (current-fill-column)))
22548 (when (and fc (> (current-column) fc))
22549 (let* ((fill-prefix (org-adaptive-fill-function))
22550 ;; Enforce empty fill prefix, if required. Otherwise, it
22551 ;; will be computed again.
22552 (adaptive-fill-mode (not (equal fill-prefix ""))))
22553 (when fill-prefix (do-auto-fill))))))
22554
22555 (defun org-comment-line-break-function (&optional soft)
22556 "Break line at point and indent, continuing comment if within one.
22557 The inserted newline is marked hard if variable
22558 `use-hard-newlines' is true, unless optional argument SOFT is
22559 non-nil."
22560 (if soft (insert-and-inherit ?\n) (newline 1))
22561 (save-excursion (forward-char -1) (delete-horizontal-space))
22562 (delete-horizontal-space)
22563 (indent-to-left-margin)
22564 (insert-before-markers-and-inherit fill-prefix))
22565
22566
22567 ;;; Comments
22568
22569 ;; Org comments syntax is quite complex. It requires the entire line
22570 ;; to be just a comment. Also, even with the right syntax at the
22571 ;; beginning of line, some some elements (i.e. verse-block or
22572 ;; example-block) don't accept comments. Usual Emacs comment commands
22573 ;; cannot cope with those requirements. Therefore, Org replaces them.
22574
22575 ;; Org still relies on `comment-dwim', but cannot trust
22576 ;; `comment-only-p'. So, `comment-region-function' and
22577 ;; `uncomment-region-function' both point
22578 ;; to`org-comment-or-uncomment-region'. Eventually,
22579 ;; `org-insert-comment' takes care of insertion of comments at the
22580 ;; beginning of line.
22581
22582 ;; `org-setup-comments-handling' install comments related variables
22583 ;; during `org-mode' initialization.
22584
22585 (defun org-setup-comments-handling ()
22586 (interactive)
22587 (org-set-local 'comment-use-syntax nil)
22588 (org-set-local 'comment-start "# ")
22589 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22590 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22591 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22592 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22593
22594 (defun org-insert-comment ()
22595 "Insert an empty comment above current line.
22596 If the line is empty, insert comment at its beginning."
22597 (beginning-of-line)
22598 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22599 (org-indent-line)
22600 (insert "# "))
22601
22602 (defvar comment-empty-lines) ; From newcomment.el.
22603 (defun org-comment-or-uncomment-region (beg end &rest _)
22604 "Comment or uncomment each non-blank line in the region.
22605 Uncomment each non-blank line between BEG and END if it only
22606 contains commented lines. Otherwise, comment them."
22607 (save-restriction
22608 ;; Restrict region
22609 (narrow-to-region (save-excursion (goto-char beg)
22610 (skip-chars-forward " \r\t\n" end)
22611 (line-beginning-position))
22612 (save-excursion (goto-char end)
22613 (skip-chars-backward " \r\t\n" beg)
22614 (line-end-position)))
22615 (let ((uncommentp
22616 ;; UNCOMMENTP is non-nil when every non blank line between
22617 ;; BEG and END is a comment.
22618 (save-excursion
22619 (goto-char (point-min))
22620 (while (and (not (eobp))
22621 (let ((element (org-element-at-point)))
22622 (and (eq (org-element-type element) 'comment)
22623 (goto-char (min (point-max)
22624 (org-element-property
22625 :end element)))))))
22626 (eobp))))
22627 (if uncommentp
22628 ;; Only blank lines and comments in region: uncomment it.
22629 (save-excursion
22630 (goto-char (point-min))
22631 (while (not (eobp))
22632 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22633 (replace-match "" nil nil nil 1))
22634 (forward-line)))
22635 ;; Comment each line in region.
22636 (let ((min-indent (point-max)))
22637 ;; First find the minimum indentation across all lines.
22638 (save-excursion
22639 (goto-char (point-min))
22640 (while (and (not (eobp)) (not (zerop min-indent)))
22641 (unless (looking-at "[ \t]*$")
22642 (setq min-indent (min min-indent (current-indentation))))
22643 (forward-line)))
22644 ;; Then loop over all lines.
22645 (save-excursion
22646 (goto-char (point-min))
22647 (while (not (eobp))
22648 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22649 ;; Don't get fooled by invisible text (e.g. link path)
22650 ;; when moving to column MIN-INDENT.
22651 (let ((buffer-invisibility-spec nil))
22652 (org-move-to-column min-indent t))
22653 (insert comment-start))
22654 (forward-line))))))))
22655
22656
22657 ;;; Planning
22658
22659 ;; This section contains tools to operate on timestamp objects, as
22660 ;; returned by, e.g. `org-element-context'.
22661
22662 (defun org-timestamp-has-time-p (timestamp)
22663 "Non-nil when TIMESTAMP has a time specified."
22664 (org-element-property :hour-start timestamp))
22665
22666 (defun org-timestamp-format (timestamp format &optional end utc)
22667 "Format a TIMESTAMP element into a string.
22668
22669 FORMAT is a format specifier to be passed to
22670 `format-time-string'.
22671
22672 When optional argument END is non-nil, use end of date-range or
22673 time-range, if possible.
22674
22675 When optional argument UTC is non-nil, time will be expressed as
22676 Universal Time."
22677 (format-time-string
22678 format
22679 (apply 'encode-time
22680 (cons 0
22681 (mapcar
22682 (lambda (prop) (or (org-element-property prop timestamp) 0))
22683 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22684 '(:minute-start :hour-start :day-start :month-start
22685 :year-start)))))
22686 utc))
22687
22688 (defun org-timestamp-split-range (timestamp &optional end)
22689 "Extract a timestamp object from a date or time range.
22690
22691 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22692 the end of the range. Otherwise, extract its start.
22693
22694 Return a new timestamp object sharing the same parent as
22695 TIMESTAMP."
22696 (let ((type (org-element-property :type timestamp)))
22697 (if (memq type '(active inactive diary)) timestamp
22698 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22699 ;; Set new type.
22700 (org-element-put-property
22701 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22702 ;; Copy start properties over end properties if END is
22703 ;; non-nil. Otherwise, copy end properties over `start' ones.
22704 (let ((p-alist '((:minute-start . :minute-end)
22705 (:hour-start . :hour-end)
22706 (:day-start . :day-end)
22707 (:month-start . :month-end)
22708 (:year-start . :year-end))))
22709 (dolist (p-cell p-alist)
22710 (org-element-put-property
22711 split-ts
22712 (funcall (if end 'car 'cdr) p-cell)
22713 (org-element-property
22714 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22715 ;; Eventually refresh `:raw-value'.
22716 (org-element-put-property split-ts :raw-value nil)
22717 (org-element-put-property
22718 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22719
22720 (defun org-timestamp-translate (timestamp &optional boundary)
22721 "Apply `org-translate-time' on a TIMESTAMP object.
22722 When optional argument BOUNDARY is non-nil, it is either the
22723 symbol `start' or `end'. In this case, only translate the
22724 starting or ending part of TIMESTAMP if it is a date or time
22725 range. Otherwise, translate both parts."
22726 (if (and (not boundary)
22727 (memq (org-element-property :type timestamp)
22728 '(active-range inactive-range)))
22729 (concat
22730 (org-translate-time
22731 (org-element-property :raw-value
22732 (org-timestamp-split-range timestamp)))
22733 "--"
22734 (org-translate-time
22735 (org-element-property :raw-value
22736 (org-timestamp-split-range timestamp t))))
22737 (org-translate-time
22738 (org-element-property
22739 :raw-value
22740 (if (not boundary) timestamp
22741 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22742
22743
22744
22745 ;;; Other stuff.
22746
22747 (defun org-toggle-fixed-width-section (arg)
22748 "Toggle the fixed-width export.
22749 If there is no active region, the QUOTE keyword at the current headline is
22750 inserted or removed. When present, it causes the text between this headline
22751 and the next to be exported as fixed-width text, and unmodified.
22752 If there is an active region, this command adds or removes a colon as the
22753 first character of this line. If the first character of a line is a colon,
22754 this line is also exported in fixed-width font."
22755 (interactive "P")
22756 (let* ((cc 0)
22757 (regionp (org-region-active-p))
22758 (beg (if regionp (region-beginning) (point)))
22759 (end (if regionp (region-end)))
22760 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22761 (case-fold-search nil)
22762 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22763 off)
22764 (if regionp
22765 (save-excursion
22766 (goto-char beg)
22767 (setq cc (current-column))
22768 (beginning-of-line 1)
22769 (setq off (looking-at re))
22770 (while (> nlines 0)
22771 (setq nlines (1- nlines))
22772 (beginning-of-line 1)
22773 (cond
22774 (arg
22775 (org-move-to-column cc t)
22776 (insert ": \n")
22777 (forward-line -1))
22778 ((and off (looking-at re))
22779 (replace-match "" t t nil 1))
22780 ((not off) (org-move-to-column cc t) (insert ": ")))
22781 (forward-line 1)))
22782 (save-excursion
22783 (org-back-to-heading)
22784 (cond
22785 ((looking-at (format org-heading-keyword-regexp-format
22786 org-quote-string))
22787 (goto-char (match-end 1))
22788 (looking-at (concat " +" org-quote-string))
22789 (replace-match "" t t)
22790 (when (eolp) (insert " ")))
22791 ((looking-at org-outline-regexp)
22792 (goto-char (match-end 0))
22793 (insert org-quote-string " ")))))))
22794
22795 (defvar reftex-docstruct-symbol)
22796 (defvar reftex-cite-format)
22797 (defvar org--rds)
22798
22799 (defun org-reftex-citation ()
22800 "Use reftex-citation to insert a citation into the buffer.
22801 This looks for a line like
22802
22803 #+BIBLIOGRAPHY: foo plain option:-d
22804
22805 and derives from it that foo.bib is the bibliography file relevant
22806 for this document. It then installs the necessary environment for RefTeX
22807 to work in this buffer and calls `reftex-citation' to insert a citation
22808 into the buffer.
22809
22810 Export of such citations to both LaTeX and HTML is handled by the contributed
22811 package ox-bibtex by Taru Karttunen."
22812 (interactive)
22813 (let ((reftex-docstruct-symbol 'org--rds)
22814 (reftex-cite-format "\\cite{%l}")
22815 org--rds bib)
22816 (save-excursion
22817 (save-restriction
22818 (widen)
22819 (let ((case-fold-search t)
22820 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22821 (if (not (save-excursion
22822 (or (re-search-forward re nil t)
22823 (re-search-backward re nil t))))
22824 (error "No bibliography defined in file")
22825 (setq bib (concat (match-string 1) ".bib")
22826 org--rds (list (list 'bib bib)))))))
22827 (call-interactively 'reftex-citation)))
22828
22829 ;;;; Functions extending outline functionality
22830
22831 (defun org-beginning-of-line (&optional arg)
22832 "Go to the beginning of the current line. If that is invisible, continue
22833 to a visible line beginning. This makes the function of C-a more intuitive.
22834 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22835 first attempt, and only move to after the tags when the cursor is already
22836 beyond the end of the headline."
22837 (interactive "P")
22838 (let ((pos (point))
22839 (special (if (consp org-special-ctrl-a/e)
22840 (car org-special-ctrl-a/e)
22841 org-special-ctrl-a/e))
22842 deactivate-mark refpos)
22843 (if (org-bound-and-true-p visual-line-mode)
22844 (beginning-of-visual-line 1)
22845 (beginning-of-line 1))
22846 (if (and arg (fboundp 'move-beginning-of-line))
22847 (call-interactively 'move-beginning-of-line)
22848 (if (bobp)
22849 nil
22850 (backward-char 1)
22851 (if (org-truely-invisible-p)
22852 (while (and (not (bobp)) (org-truely-invisible-p))
22853 (backward-char 1)
22854 (beginning-of-line 1))
22855 (forward-char 1))))
22856 (when special
22857 (cond
22858 ((and (looking-at org-complex-heading-regexp)
22859 (= (char-after (match-end 1)) ?\ ))
22860 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22861 (point-at-eol)))
22862 (goto-char
22863 (if (eq special t)
22864 (cond ((> pos refpos) refpos)
22865 ((= pos (point)) refpos)
22866 (t (point)))
22867 (cond ((> pos (point)) (point))
22868 ((not (eq last-command this-command)) (point))
22869 (t refpos)))))
22870 ((org-at-item-p)
22871 ;; Being at an item and not looking at an the item means point
22872 ;; was previously moved to beginning of a visual line, which
22873 ;; doesn't contain the item. Therefore, do nothing special,
22874 ;; just stay here.
22875 (when (looking-at org-list-full-item-re)
22876 ;; Set special position at first white space character after
22877 ;; bullet, and check-box, if any.
22878 (let ((after-bullet
22879 (let ((box (match-end 3)))
22880 (if (not box) (match-end 1)
22881 (let ((after (char-after box)))
22882 (if (and after (= after ? )) (1+ box) box))))))
22883 ;; Special case: Move point to special position when
22884 ;; currently after it or at beginning of line.
22885 (if (eq special t)
22886 (when (or (> pos after-bullet) (= (point) pos))
22887 (goto-char after-bullet))
22888 ;; Reversed case: Move point to special position when
22889 ;; point was already at beginning of line and command is
22890 ;; repeated.
22891 (when (and (= (point) pos) (eq last-command this-command))
22892 (goto-char after-bullet))))))))
22893 (org-no-warnings
22894 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22895 (setq disable-point-adjustment
22896 (or (not (invisible-p (point)))
22897 (not (invisible-p (max (point-min) (1- (point))))))))
22898
22899 (defun org-end-of-line (&optional arg)
22900 "Go to the end of the line.
22901 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22902 tags on the first attempt, and only move to after the tags when
22903 the cursor is already beyond the end of the headline."
22904 (interactive "P")
22905 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22906 org-special-ctrl-a/e))
22907 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22908 'end-of-visual-line)
22909 ((fboundp 'move-end-of-line) 'move-end-of-line)
22910 (t 'end-of-line)))
22911 deactivate-mark)
22912 (if (or (not special) arg) (call-interactively move-fun)
22913 (let* ((element (save-excursion (beginning-of-line)
22914 (org-element-at-point)))
22915 (type (org-element-type element)))
22916 (cond
22917 ((memq type '(headline inlinetask))
22918 (let ((pos (point)))
22919 (beginning-of-line 1)
22920 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22921 (if (eq special t)
22922 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22923 (goto-char (match-beginning 1))
22924 (goto-char (match-end 0)))
22925 (if (or (< pos (match-end 0))
22926 (not (eq this-command last-command)))
22927 (goto-char (match-end 0))
22928 (goto-char (match-beginning 1))))
22929 (call-interactively move-fun))))
22930 ((org-element-property :hiddenp element)
22931 ;; If element is hidden, `move-end-of-line' would put point
22932 ;; after it. Use `end-of-line' to stay on current line.
22933 (call-interactively 'end-of-line))
22934 (t (call-interactively move-fun)))))
22935 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22936 (setq disable-point-adjustment
22937 (or (not (invisible-p (point)))
22938 (not (invisible-p (max (point-min) (1- (point))))))))
22939
22940 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22941 (define-key org-mode-map "\C-e" 'org-end-of-line)
22942
22943 (defun org-backward-sentence (&optional _arg)
22944 "Go to beginning of sentence, or beginning of table field.
22945 This will call `backward-sentence' or `org-table-beginning-of-field',
22946 depending on context."
22947 (interactive)
22948 (cond
22949 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22950 (t (call-interactively 'backward-sentence))))
22951
22952 (defun org-forward-sentence (&optional _arg)
22953 "Go to end of sentence, or end of table field.
22954 This will call `forward-sentence' or `org-table-end-of-field',
22955 depending on context."
22956 (interactive)
22957 (cond
22958 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22959 (t (call-interactively 'forward-sentence))))
22960
22961 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22962 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22963
22964 (defun org-kill-line (&optional _arg)
22965 "Kill line, to tags or end of line."
22966 (interactive)
22967 (cond
22968 ((or (not org-special-ctrl-k)
22969 (bolp)
22970 (not (org-at-heading-p)))
22971 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22972 org-ctrl-k-protect-subtree)
22973 (if (or (eq org-ctrl-k-protect-subtree 'error)
22974 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22975 (user-error "C-k aborted as it would kill a hidden subtree")))
22976 (call-interactively
22977 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22978 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22979 (kill-region (point) (match-beginning 1))
22980 (org-set-tags nil t))
22981 (t (kill-region (point) (point-at-eol)))))
22982
22983 (define-key org-mode-map "\C-k" 'org-kill-line)
22984
22985 (defun org-yank (&optional arg)
22986 "Yank. If the kill is a subtree, treat it specially.
22987 This command will look at the current kill and check if is a single
22988 subtree, or a series of subtrees[1]. If it passes the test, and if the
22989 cursor is at the beginning of a line or after the stars of a currently
22990 empty headline, then the yank is handled specially. How exactly depends
22991 on the value of the following variables, both set by default.
22992
22993 org-yank-folded-subtrees
22994 When set, the subtree(s) will be folded after insertion, but only
22995 if doing so would now swallow text after the yanked text.
22996
22997 org-yank-adjusted-subtrees
22998 When set, the subtree will be promoted or demoted in order to
22999 fit into the local outline tree structure, which means that the level
23000 will be adjusted so that it becomes the smaller one of the two
23001 *visible* surrounding headings.
23002
23003 Any prefix to this command will cause `yank' to be called directly with
23004 no special treatment. In particular, a simple \\[universal-argument] prefix \
23005 will just
23006 plainly yank the text as it is.
23007
23008 [1] The test checks if the first non-white line is a heading
23009 and if there are no other headings with fewer stars."
23010 (interactive "P")
23011 (org-yank-generic 'yank arg))
23012
23013 (defun org-yank-generic (command arg)
23014 "Perform some yank-like command.
23015
23016 This function implements the behavior described in the `org-yank'
23017 documentation. However, it has been generalized to work for any
23018 interactive command with similar behavior."
23019
23020 ;; pretend to be command COMMAND
23021 (setq this-command command)
23022
23023 (if arg
23024 (call-interactively command)
23025
23026 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23027 (and (org-kill-is-subtree-p)
23028 (or (bolp)
23029 (and (looking-at "[ \t]*$")
23030 (string-match
23031 "\\`\\*+\\'"
23032 (buffer-substring (point-at-bol) (point)))))))
23033 swallowp)
23034 (cond
23035 ((and subtreep org-yank-folded-subtrees)
23036 (let ((beg (point))
23037 end)
23038 (if (and subtreep org-yank-adjusted-subtrees)
23039 (org-paste-subtree nil nil 'for-yank)
23040 (call-interactively command))
23041
23042 (setq end (point))
23043 (goto-char beg)
23044 (when (and (bolp) subtreep
23045 (not (setq swallowp
23046 (org-yank-folding-would-swallow-text beg end))))
23047 (org-with-limited-levels
23048 (or (looking-at org-outline-regexp)
23049 (re-search-forward org-outline-regexp-bol end t))
23050 (while (and (< (point) end) (looking-at org-outline-regexp))
23051 (hide-subtree)
23052 (org-cycle-show-empty-lines 'folded)
23053 (condition-case nil
23054 (outline-forward-same-level 1)
23055 (error (goto-char end))))))
23056 (when swallowp
23057 (message
23058 "Inserted text not folded because that would swallow text"))
23059
23060 (goto-char end)
23061 (skip-chars-forward " \t\n\r")
23062 (beginning-of-line 1)
23063 (push-mark beg 'nomsg)))
23064 ((and subtreep org-yank-adjusted-subtrees)
23065 (let ((beg (point-at-bol)))
23066 (org-paste-subtree nil nil 'for-yank)
23067 (push-mark beg 'nomsg)))
23068 (t
23069 (call-interactively command))))))
23070
23071 (defun org-yank-folding-would-swallow-text (beg end)
23072 "Would hide-subtree at BEG swallow any text after END?"
23073 (let (level)
23074 (org-with-limited-levels
23075 (save-excursion
23076 (goto-char beg)
23077 (when (or (looking-at org-outline-regexp)
23078 (re-search-forward org-outline-regexp-bol end t))
23079 (setq level (org-outline-level)))
23080 (goto-char end)
23081 (skip-chars-forward " \t\r\n\v\f")
23082 (if (or (eobp)
23083 (and (bolp) (looking-at org-outline-regexp)
23084 (<= (org-outline-level) level)))
23085 nil ; Nothing would be swallowed
23086 t))))) ; something would swallow
23087
23088 (define-key org-mode-map "\C-y" 'org-yank)
23089
23090 (defun org-truely-invisible-p ()
23091 "Check if point is at a character currently not visible.
23092 This version does not only check the character property, but also
23093 `visible-mode'."
23094 ;; Early versions of noutline don't have `outline-invisible-p'.
23095 (if (org-bound-and-true-p visible-mode)
23096 nil
23097 (outline-invisible-p)))
23098
23099 (defun org-invisible-p2 ()
23100 "Check if point is at a character currently not visible."
23101 (save-excursion
23102 (if (and (eolp) (not (bobp))) (backward-char 1))
23103 ;; Early versions of noutline don't have `outline-invisible-p'.
23104 (outline-invisible-p)))
23105
23106 (defun org-back-to-heading (&optional invisible-ok)
23107 "Call `outline-back-to-heading', but provide a better error message."
23108 (condition-case nil
23109 (outline-back-to-heading invisible-ok)
23110 (error (error "Before first headline at position %d in buffer %s"
23111 (point) (current-buffer)))))
23112
23113 (defun org-before-first-heading-p ()
23114 "Before first heading?"
23115 (save-excursion
23116 (end-of-line)
23117 (null (re-search-backward org-outline-regexp-bol nil t))))
23118
23119 (defun org-at-heading-p (&optional ignored)
23120 (outline-on-heading-p t))
23121 ;; Compatibility alias with Org versions < 7.8.03
23122 (defalias 'org-on-heading-p 'org-at-heading-p)
23123
23124 (defun org-at-comment-p nil
23125 "Is cursor in a line starting with a # character?"
23126 (save-excursion
23127 (beginning-of-line)
23128 (looking-at "^#")))
23129
23130 (defun org-at-drawer-p nil
23131 "Is cursor at a drawer keyword?"
23132 (save-excursion
23133 (move-beginning-of-line 1)
23134 (looking-at org-drawer-regexp)))
23135
23136 (defun org-at-block-p nil
23137 "Is cursor at a block keyword?"
23138 (save-excursion
23139 (move-beginning-of-line 1)
23140 (looking-at org-block-regexp)))
23141
23142 (defun org-point-at-end-of-empty-headline ()
23143 "If point is at the end of an empty headline, return t, else nil.
23144 If the heading only contains a TODO keyword, it is still still considered
23145 empty."
23146 (and (looking-at "[ \t]*$")
23147 (when org-todo-line-regexp
23148 (save-excursion
23149 (beginning-of-line 1)
23150 (let ((case-fold-search nil))
23151 (looking-at org-todo-line-regexp)
23152 (string= (match-string 3) ""))))))
23153
23154 (defun org-at-heading-or-item-p ()
23155 (or (org-at-heading-p) (org-at-item-p)))
23156
23157 (defun org-at-target-p ()
23158 (or (org-in-regexp org-radio-target-regexp)
23159 (org-in-regexp org-target-regexp)))
23160 ;; Compatibility alias with Org versions < 7.8.03
23161 (defalias 'org-on-target-p 'org-at-target-p)
23162
23163 (defun org-up-heading-all (arg)
23164 "Move to the heading line of which the present line is a subheading.
23165 This function considers both visible and invisible heading lines.
23166 With argument, move up ARG levels."
23167 (if (fboundp 'outline-up-heading-all)
23168 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23169 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23170
23171 (defun org-up-heading-safe ()
23172 "Move to the heading line of which the present line is a subheading.
23173 This version will not throw an error. It will return the level of the
23174 headline found, or nil if no higher level is found.
23175
23176 Also, this function will be a lot faster than `outline-up-heading',
23177 because it relies on stars being the outline starters. This can really
23178 make a significant difference in outlines with very many siblings."
23179 (let (start-level re)
23180 (org-back-to-heading t)
23181 (setq start-level (funcall outline-level))
23182 (if (equal start-level 1)
23183 nil
23184 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23185 (if (re-search-backward re nil t)
23186 (funcall outline-level)))))
23187
23188 (defun org-first-sibling-p ()
23189 "Is this heading the first child of its parents?"
23190 (interactive)
23191 (let ((re org-outline-regexp-bol)
23192 level l)
23193 (unless (org-at-heading-p t)
23194 (user-error "Not at a heading"))
23195 (setq level (funcall outline-level))
23196 (save-excursion
23197 (if (not (re-search-backward re nil t))
23198 t
23199 (setq l (funcall outline-level))
23200 (< l level)))))
23201
23202 (defun org-goto-sibling (&optional previous)
23203 "Goto the next sibling, even if it is invisible.
23204 When PREVIOUS is set, go to the previous sibling instead. Returns t
23205 when a sibling was found. When none is found, return nil and don't
23206 move point."
23207 (let ((fun (if previous 're-search-backward 're-search-forward))
23208 (pos (point))
23209 (re org-outline-regexp-bol)
23210 level l)
23211 (when (condition-case nil (org-back-to-heading t) (error nil))
23212 (setq level (funcall outline-level))
23213 (catch 'exit
23214 (or previous (forward-char 1))
23215 (while (funcall fun re nil t)
23216 (setq l (funcall outline-level))
23217 (when (< l level) (goto-char pos) (throw 'exit nil))
23218 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23219 (goto-char pos)
23220 nil))))
23221
23222 (defun org-show-siblings ()
23223 "Show all siblings of the current headline."
23224 (save-excursion
23225 (while (org-goto-sibling) (org-flag-heading nil)))
23226 (save-excursion
23227 (while (org-goto-sibling 'previous)
23228 (org-flag-heading nil))))
23229
23230 (defun org-goto-first-child ()
23231 "Goto the first child, even if it is invisible.
23232 Return t when a child was found. Otherwise don't move point and
23233 return nil."
23234 (let (level (pos (point)) (re org-outline-regexp-bol))
23235 (when (condition-case nil (org-back-to-heading t) (error nil))
23236 (setq level (outline-level))
23237 (forward-char 1)
23238 (if (and (re-search-forward re nil t) (> (outline-level) level))
23239 (progn (goto-char (match-beginning 0)) t)
23240 (goto-char pos) nil))))
23241
23242 (defun org-show-hidden-entry ()
23243 "Show an entry where even the heading is hidden."
23244 (save-excursion
23245 (org-show-entry)))
23246
23247 (defun org-flag-heading (flag &optional entry)
23248 "Flag the current heading. FLAG non-nil means make invisible.
23249 When ENTRY is non-nil, show the entire entry."
23250 (save-excursion
23251 (org-back-to-heading t)
23252 ;; Check if we should show the entire entry
23253 (if entry
23254 (progn
23255 (org-show-entry)
23256 (save-excursion
23257 (and (outline-next-heading)
23258 (org-flag-heading nil))))
23259 (outline-flag-region (max (point-min) (1- (point)))
23260 (save-excursion (outline-end-of-heading) (point))
23261 flag))))
23262
23263 (defun org-get-next-sibling ()
23264 "Move to next heading of the same level, and return point.
23265 If there is no such heading, return nil.
23266 This is like outline-next-sibling, but invisible headings are ok."
23267 (let ((level (funcall outline-level)))
23268 (outline-next-heading)
23269 (while (and (not (eobp)) (> (funcall outline-level) level))
23270 (outline-next-heading))
23271 (if (or (eobp) (< (funcall outline-level) level))
23272 nil
23273 (point))))
23274
23275 (defun org-get-last-sibling ()
23276 "Move to previous heading of the same level, and return point.
23277 If there is no such heading, return nil."
23278 (let ((opoint (point))
23279 (level (funcall outline-level)))
23280 (outline-previous-heading)
23281 (when (and (/= (point) opoint) (outline-on-heading-p t))
23282 (while (and (> (funcall outline-level) level)
23283 (not (bobp)))
23284 (outline-previous-heading))
23285 (if (< (funcall outline-level) level)
23286 nil
23287 (point)))))
23288
23289 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23290 "Goto to the end of a subtree."
23291 ;; This contains an exact copy of the original function, but it uses
23292 ;; `org-back-to-heading', to make it work also in invisible
23293 ;; trees. And is uses an invisible-ok argument.
23294 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23295 ;; Furthermore, when used inside Org, finding the end of a large subtree
23296 ;; with many children and grandchildren etc, this can be much faster
23297 ;; than the outline version.
23298 (org-back-to-heading invisible-ok)
23299 (let ((first t)
23300 (level (funcall outline-level)))
23301 (if (and (derived-mode-p 'org-mode) (< level 1000))
23302 ;; A true heading (not a plain list item), in Org-mode
23303 ;; This means we can easily find the end by looking
23304 ;; only for the right number of stars. Using a regexp to do
23305 ;; this is so much faster than using a Lisp loop.
23306 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23307 (forward-char 1)
23308 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23309 ;; something else, do it the slow way
23310 (while (and (not (eobp))
23311 (or first (> (funcall outline-level) level)))
23312 (setq first nil)
23313 (outline-next-heading)))
23314 (unless to-heading
23315 (if (memq (preceding-char) '(?\n ?\^M))
23316 (progn
23317 ;; Go to end of line before heading
23318 (forward-char -1)
23319 (if (memq (preceding-char) '(?\n ?\^M))
23320 ;; leave blank line before heading
23321 (forward-char -1))))))
23322 (point))
23323
23324 (defun org-end-of-meta-data-and-drawers ()
23325 "Jump to the first text after meta data and drawers in the current entry.
23326 This will move over empty lines, lines with planning time stamps,
23327 clocking lines, and drawers."
23328 (org-back-to-heading t)
23329 (let ((end (save-excursion (outline-next-heading) (point)))
23330 (re (concat "\\(" org-drawer-regexp "\\)"
23331 "\\|" "[ \t]*" org-keyword-time-regexp)))
23332 (forward-line 1)
23333 (while (re-search-forward re end t)
23334 (if (not (match-end 1))
23335 ;; empty or planning line
23336 (forward-line 1)
23337 ;; a drawer, find the end
23338 (re-search-forward "^[ \t]*:END:" end 'move)
23339 (forward-line 1)))
23340 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23341 (point)))
23342
23343 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23344 "Move forward to the ARG'th subheading at same level as this one.
23345 Stop at the first and last subheadings of a superior heading.
23346 Normally this only looks at visible headings, but when INVISIBLE-OK is
23347 non-nil it will also look at invisible ones."
23348 (interactive "p")
23349 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23350 (if (and arg (< arg 0))
23351 (goto-char (point-min))
23352 (outline-next-heading))
23353 (org-at-heading-p)
23354 (let ((level (- (match-end 0) (match-beginning 0) 1))
23355 (f (if (and arg (< arg 0))
23356 're-search-backward
23357 're-search-forward))
23358 (count (if arg (abs arg) 1))
23359 (result (point)))
23360 (while (and (prog1 (> count 0)
23361 (forward-char (if (and arg (< arg 0)) -1 1)))
23362 (funcall f org-outline-regexp-bol nil 'move))
23363 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23364 (cond ((< l level) (setq count 0))
23365 ((and (= l level)
23366 (or invisible-ok
23367 (progn
23368 (goto-char (line-beginning-position))
23369 (not (outline-invisible-p)))))
23370 (setq count (1- count))
23371 (when (eq l level)
23372 (setq result (point)))))))
23373 (goto-char result))
23374 (beginning-of-line 1)))
23375
23376 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23377 "Move backward to the ARG'th subheading at same level as this one.
23378 Stop at the first and last subheadings of a superior heading."
23379 (interactive "p")
23380 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23381
23382 (defun org-next-block (arg &optional backward block-regexp)
23383 "Jump to the next block.
23384 With a prefix argument ARG, jump forward ARG many source blocks.
23385 When BACKWARD is non-nil, jump to the previous block.
23386 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23387 (interactive "p")
23388 (let ((re (or block-regexp org-block-regexp))
23389 (re-search-fn (or (and backward 're-search-backward)
23390 're-search-forward)))
23391 (if (looking-at re) (forward-char 1))
23392 (condition-case nil
23393 (funcall re-search-fn re nil nil arg)
23394 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23395 (goto-char (match-beginning 0)) (org-show-context)))
23396
23397 (defun org-previous-block (arg &optional block-regexp)
23398 "Jump to the previous block.
23399 With a prefix argument ARG, jump backward ARG many source blocks.
23400 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23401 (interactive "p")
23402 (org-next-block arg t block-regexp))
23403
23404 (defun org-forward-paragraph ()
23405 "Move forward to beginning of next paragraph or equivalent.
23406
23407 The function moves point to the beginning of the next visible
23408 structural element, which can be a paragraph, a table, a list
23409 item, etc. It also provides some special moves for convenience:
23410
23411 - On an affiliated keyword, jump to the beginning of the
23412 relative element.
23413 - On an item or a footnote definition, move to the second
23414 element inside, if any.
23415 - On a table or a property drawer, jump after it.
23416 - On a verse or source block, stop after blank lines."
23417 (interactive)
23418 (when (eobp) (user-error "Cannot move further down"))
23419 (let* ((deactivate-mark nil)
23420 (element (org-element-at-point))
23421 (type (org-element-type element))
23422 (post-affiliated (org-element-property :post-affiliated element))
23423 (contents-begin (org-element-property :contents-begin element))
23424 (contents-end (org-element-property :contents-end element))
23425 (end (let ((end (org-element-property :end element)) (parent element))
23426 (while (and (setq parent (org-element-property :parent parent))
23427 (= (org-element-property :contents-end parent) end))
23428 (setq end (org-element-property :end parent)))
23429 end)))
23430 (cond ((not element)
23431 (skip-chars-forward " \r\t\n")
23432 (or (eobp) (beginning-of-line)))
23433 ;; On affiliated keywords, move to element's beginning.
23434 ((and post-affiliated (< (point) post-affiliated))
23435 (goto-char post-affiliated))
23436 ;; At a table row, move to the end of the table. Similarly,
23437 ;; at a node property, move to the end of the property
23438 ;; drawer.
23439 ((memq type '(node-property table-row))
23440 (goto-char (org-element-property
23441 :end (org-element-property :parent element))))
23442 ((memq type '(property-drawer table)) (goto-char end))
23443 ;; Consider blank lines as separators in verse and source
23444 ;; blocks to ease editing.
23445 ((memq type '(src-block verse-block))
23446 (when (eq type 'src-block)
23447 (setq contents-end
23448 (save-excursion (goto-char end)
23449 (skip-chars-backward " \r\t\n")
23450 (line-beginning-position))))
23451 (beginning-of-line)
23452 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23453 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23454 (goto-char end)
23455 (skip-chars-forward " \r\t\n")
23456 (if (= (point) contents-end) (goto-char end)
23457 (beginning-of-line))))
23458 ;; With no contents, just skip element.
23459 ((not contents-begin) (goto-char end))
23460 ;; If contents are invisible, skip the element altogether.
23461 ((outline-invisible-p (line-end-position))
23462 (case type
23463 (headline
23464 (org-with-limited-levels (outline-next-visible-heading 1)))
23465 ;; At a plain list, make sure we move to the next item
23466 ;; instead of skipping the whole list.
23467 (plain-list (forward-char)
23468 (org-forward-paragraph))
23469 (otherwise (goto-char end))))
23470 ((>= (point) contents-end) (goto-char end))
23471 ((>= (point) contents-begin)
23472 ;; This can only happen on paragraphs and plain lists.
23473 (case type
23474 (paragraph (goto-char end))
23475 ;; At a plain list, try to move to second element in
23476 ;; first item, if possible.
23477 (plain-list (end-of-line)
23478 (org-forward-paragraph))))
23479 ;; When contents start on the middle of a line (e.g. in
23480 ;; items and footnote definitions), try to reach first
23481 ;; element starting after current line.
23482 ((> (line-end-position) contents-begin)
23483 (end-of-line)
23484 (org-forward-paragraph))
23485 (t (goto-char contents-begin)))))
23486
23487 (defun org-backward-paragraph ()
23488 "Move backward to start of previous paragraph or equivalent.
23489
23490 The function moves point to the beginning of the current
23491 structural element, which can be a paragraph, a table, a list
23492 item, etc., or to the beginning of the previous visible one if
23493 point is already there. It also provides some special moves for
23494 convenience:
23495
23496 - On an affiliated keyword, jump to the first one.
23497 - On a table or a property drawer, move to its beginning.
23498 - On a verse or source block, stop before blank lines."
23499 (interactive)
23500 (when (bobp) (user-error "Cannot move further up"))
23501 (let* ((deactivate-mark nil)
23502 (element (org-element-at-point))
23503 (type (org-element-type element))
23504 (contents-begin (org-element-property :contents-begin element))
23505 (contents-end (org-element-property :contents-end element))
23506 (post-affiliated (org-element-property :post-affiliated element))
23507 (begin (org-element-property :begin element)))
23508 (cond
23509 ((not element) (goto-char (point-min)))
23510 ((= (point) begin)
23511 (backward-char)
23512 (org-backward-paragraph))
23513 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23514 ((memq type '(node-property table-row))
23515 (goto-char (org-element-property
23516 :post-affiliated (org-element-property :parent element))))
23517 ((memq type '(property-drawer table)) (goto-char begin))
23518 ((memq type '(src-block verse-block))
23519 (when (eq type 'src-block)
23520 (setq contents-begin
23521 (save-excursion (goto-char begin) (forward-line) (point))))
23522 (if (= (point) contents-begin) (goto-char post-affiliated)
23523 ;; Inside a verse block, see blank lines as paragraph
23524 ;; separators.
23525 (let ((origin (point)))
23526 (skip-chars-backward " \r\t\n" contents-begin)
23527 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23528 (skip-chars-forward " \r\t\n" origin)
23529 (if (= (point) origin) (goto-char contents-begin)
23530 (beginning-of-line))))))
23531 ((not contents-begin) (goto-char (or post-affiliated begin)))
23532 ((eq type 'paragraph)
23533 (goto-char contents-begin)
23534 ;; When at first paragraph in an item or a footnote definition,
23535 ;; move directly to beginning of line.
23536 (let ((parent-contents
23537 (org-element-property
23538 :contents-begin (org-element-property :parent element))))
23539 (when (and parent-contents (= parent-contents contents-begin))
23540 (beginning-of-line))))
23541 ;; At the end of a greater element, move to the beginning of the
23542 ;; last element within.
23543 ((>= (point) contents-end)
23544 (goto-char (1- contents-end))
23545 (org-backward-paragraph))
23546 (t (goto-char (or post-affiliated begin))))
23547 ;; Ensure we never leave point invisible.
23548 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23549
23550 (defun org-forward-element ()
23551 "Move forward by one element.
23552 Move to the next element at the same level, when possible."
23553 (interactive)
23554 (cond ((eobp) (user-error "Cannot move further down"))
23555 ((org-with-limited-levels (org-at-heading-p))
23556 (let ((origin (point)))
23557 (goto-char (org-end-of-subtree nil t))
23558 (unless (org-with-limited-levels (org-at-heading-p))
23559 (goto-char origin)
23560 (user-error "Cannot move further down"))))
23561 (t
23562 (let* ((elem (org-element-at-point))
23563 (end (org-element-property :end elem))
23564 (parent (org-element-property :parent elem)))
23565 (cond ((and parent (= (org-element-property :contents-end parent) end))
23566 (goto-char (org-element-property :end parent)))
23567 ((integer-or-marker-p end) (goto-char end))
23568 (t (message "No element at point")))))))
23569
23570 (defun org-backward-element ()
23571 "Move backward by one element.
23572 Move to the previous element at the same level, when possible."
23573 (interactive)
23574 (cond ((bobp) (user-error "Cannot move further up"))
23575 ((org-with-limited-levels (org-at-heading-p))
23576 ;; At a headline, move to the previous one, if any, or stay
23577 ;; here.
23578 (let ((origin (point)))
23579 (org-with-limited-levels (org-backward-heading-same-level 1))
23580 ;; When current headline has no sibling above, move to its
23581 ;; parent.
23582 (when (= (point) origin)
23583 (or (org-with-limited-levels (org-up-heading-safe))
23584 (progn (goto-char origin)
23585 (user-error "Cannot move further up"))))))
23586 (t
23587 (let* ((trail (org-element-at-point 'keep-trail))
23588 (elem (car trail))
23589 (prev-elem (nth 1 trail))
23590 (beg (org-element-property :begin elem)))
23591 (cond
23592 ;; Move to beginning of current element if point isn't
23593 ;; there already.
23594 ((null beg) (message "No element at point"))
23595 ((/= (point) beg) (goto-char beg))
23596 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23597 ((org-before-first-heading-p) (goto-char (point-min)))
23598 (t (org-back-to-heading)))))))
23599
23600 (defun org-up-element ()
23601 "Move to upper element."
23602 (interactive)
23603 (if (org-with-limited-levels (org-at-heading-p))
23604 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23605 (let* ((elem (org-element-at-point))
23606 (parent (org-element-property :parent elem)))
23607 (if parent (goto-char (org-element-property :begin parent))
23608 (if (org-with-limited-levels (org-before-first-heading-p))
23609 (user-error "No surrounding element")
23610 (org-with-limited-levels (org-back-to-heading)))))))
23611
23612 (defvar org-element-greater-elements)
23613 (defun org-down-element ()
23614 "Move to inner element."
23615 (interactive)
23616 (let ((element (org-element-at-point)))
23617 (cond
23618 ((memq (org-element-type element) '(plain-list table))
23619 (goto-char (org-element-property :contents-begin element))
23620 (forward-char))
23621 ((memq (org-element-type element) org-element-greater-elements)
23622 ;; If contents are hidden, first disclose them.
23623 (when (org-element-property :hiddenp element) (org-cycle))
23624 (goto-char (or (org-element-property :contents-begin element)
23625 (user-error "No content for this element"))))
23626 (t (user-error "No inner element")))))
23627
23628 (defun org-drag-element-backward ()
23629 "Move backward element at point."
23630 (interactive)
23631 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23632 (let* ((trail (org-element-at-point 'keep-trail))
23633 (elem (car trail))
23634 (prev-elem (nth 1 trail)))
23635 ;; Error out if no previous element or previous element is
23636 ;; a parent of the current one.
23637 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23638 (user-error "Cannot drag element backward")
23639 (let ((pos (point)))
23640 (org-element-swap-A-B prev-elem elem)
23641 (goto-char (+ (org-element-property :begin prev-elem)
23642 (- pos (org-element-property :begin elem)))))))))
23643
23644 (defun org-drag-element-forward ()
23645 "Move forward element at point."
23646 (interactive)
23647 (let* ((pos (point))
23648 (elem (org-element-at-point)))
23649 (when (= (point-max) (org-element-property :end elem))
23650 (user-error "Cannot drag element forward"))
23651 (goto-char (org-element-property :end elem))
23652 (let ((next-elem (org-element-at-point)))
23653 (when (or (org-element-nested-p elem next-elem)
23654 (and (eq (org-element-type next-elem) 'headline)
23655 (not (eq (org-element-type elem) 'headline))))
23656 (goto-char pos)
23657 (user-error "Cannot drag element forward"))
23658 ;; Compute new position of point: it's shifted by NEXT-ELEM
23659 ;; body's length (without final blanks) and by the length of
23660 ;; blanks between ELEM and NEXT-ELEM.
23661 (let ((size-next (- (save-excursion
23662 (goto-char (org-element-property :end next-elem))
23663 (skip-chars-backward " \r\t\n")
23664 (forward-line)
23665 ;; Small correction if buffer doesn't end
23666 ;; with a newline character.
23667 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23668 (org-element-property :begin next-elem)))
23669 (size-blank (- (org-element-property :end elem)
23670 (save-excursion
23671 (goto-char (org-element-property :end elem))
23672 (skip-chars-backward " \r\t\n")
23673 (forward-line)
23674 (point)))))
23675 (org-element-swap-A-B elem next-elem)
23676 (goto-char (+ pos size-next size-blank))))))
23677
23678 (defun org-drag-line-forward (arg)
23679 "Drag the line at point ARG lines forward."
23680 (interactive "p")
23681 (dotimes (n (abs arg))
23682 (let ((c (current-column)))
23683 (if (< 0 arg)
23684 (progn
23685 (beginning-of-line 2)
23686 (transpose-lines 1)
23687 (beginning-of-line 0))
23688 (transpose-lines 1)
23689 (beginning-of-line -1))
23690 (org-move-to-column c))))
23691
23692 (defun org-drag-line-backward (arg)
23693 "Drag the line at point ARG lines backward."
23694 (interactive "p")
23695 (org-drag-line-forward (- arg)))
23696
23697 (defun org-mark-element ()
23698 "Put point at beginning of this element, mark at end.
23699
23700 Interactively, if this command is repeated or (in Transient Mark
23701 mode) if the mark is active, it marks the next element after the
23702 ones already marked."
23703 (interactive)
23704 (let (deactivate-mark)
23705 (if (and (org-called-interactively-p 'any)
23706 (or (and (eq last-command this-command) (mark t))
23707 (and transient-mark-mode mark-active)))
23708 (set-mark
23709 (save-excursion
23710 (goto-char (mark))
23711 (goto-char (org-element-property :end (org-element-at-point)))))
23712 (let ((element (org-element-at-point)))
23713 (end-of-line)
23714 (push-mark (org-element-property :end element) t t)
23715 (goto-char (org-element-property :begin element))))))
23716
23717 (defun org-narrow-to-element ()
23718 "Narrow buffer to current element."
23719 (interactive)
23720 (let ((elem (org-element-at-point)))
23721 (cond
23722 ((eq (car elem) 'headline)
23723 (narrow-to-region
23724 (org-element-property :begin elem)
23725 (org-element-property :end elem)))
23726 ((memq (car elem) org-element-greater-elements)
23727 (narrow-to-region
23728 (org-element-property :contents-begin elem)
23729 (org-element-property :contents-end elem)))
23730 (t
23731 (narrow-to-region
23732 (org-element-property :begin elem)
23733 (org-element-property :end elem))))))
23734
23735 (defun org-transpose-element ()
23736 "Transpose current and previous elements, keeping blank lines between.
23737 Point is moved after both elements."
23738 (interactive)
23739 (org-skip-whitespace)
23740 (let ((end (org-element-property :end (org-element-at-point))))
23741 (org-drag-element-backward)
23742 (goto-char end)))
23743
23744 (defun org-unindent-buffer ()
23745 "Un-indent the visible part of the buffer.
23746 Relative indentation (between items, inside blocks, etc.) isn't
23747 modified."
23748 (interactive)
23749 (unless (eq major-mode 'org-mode)
23750 (user-error "Cannot un-indent a buffer not in Org mode"))
23751 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23752 unindent-tree ; For byte-compiler.
23753 (unindent-tree
23754 (function
23755 (lambda (contents)
23756 (mapc
23757 (lambda (element)
23758 (if (memq (org-element-type element) '(headline section))
23759 (funcall unindent-tree (org-element-contents element))
23760 (save-excursion
23761 (save-restriction
23762 (narrow-to-region
23763 (org-element-property :begin element)
23764 (org-element-property :end element))
23765 (org-do-remove-indentation)))))
23766 (reverse contents))))))
23767 (funcall unindent-tree (org-element-contents parse-tree))))
23768
23769 (defun org-show-subtree ()
23770 "Show everything after this heading at deeper levels."
23771 (interactive)
23772 (outline-flag-region
23773 (point)
23774 (save-excursion
23775 (org-end-of-subtree t t))
23776 nil))
23777
23778 (defun org-show-entry ()
23779 "Show the body directly following this heading.
23780 Show the heading too, if it is currently invisible."
23781 (interactive)
23782 (save-excursion
23783 (condition-case nil
23784 (progn
23785 (org-back-to-heading t)
23786 (outline-flag-region
23787 (max (point-min) (1- (point)))
23788 (save-excursion
23789 (if (re-search-forward
23790 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23791 (match-beginning 1)
23792 (point-max)))
23793 nil)
23794 (org-cycle-hide-drawers 'children))
23795 (error nil))))
23796
23797 (defun org-make-options-regexp (kwds &optional extra)
23798 "Make a regular expression for keyword lines."
23799 (concat
23800 "^#\\+\\("
23801 (mapconcat 'regexp-quote kwds "\\|")
23802 (if extra (concat "\\|" extra))
23803 "\\):[ \t]*\\(.*\\)"))
23804
23805 ;; Make isearch reveal the necessary context
23806 (defun org-isearch-end ()
23807 "Reveal context after isearch exits."
23808 (when isearch-success ; only if search was successful
23809 (if (featurep 'xemacs)
23810 ;; Under XEmacs, the hook is run in the correct place,
23811 ;; we directly show the context.
23812 (org-show-context 'isearch)
23813 ;; In Emacs the hook runs *before* restoring the overlays.
23814 ;; So we have to use a one-time post-command-hook to do this.
23815 ;; (Emacs 22 has a special variable, see function `org-mode')
23816 (unless (and (boundp 'isearch-mode-end-hook-quit)
23817 isearch-mode-end-hook-quit)
23818 ;; Only when the isearch was not quitted.
23819 (org-add-hook 'post-command-hook 'org-isearch-post-command
23820 'append 'local)))))
23821
23822 (defun org-isearch-post-command ()
23823 "Remove self from hook, and show context."
23824 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23825 (org-show-context 'isearch))
23826
23827
23828 ;;;; Integration with and fixes for other packages
23829
23830 ;;; Imenu support
23831
23832 (defvar org-imenu-markers nil
23833 "All markers currently used by Imenu.")
23834 (make-variable-buffer-local 'org-imenu-markers)
23835
23836 (defun org-imenu-new-marker (&optional pos)
23837 "Return a new marker for use by Imenu, and remember the marker."
23838 (let ((m (make-marker)))
23839 (move-marker m (or pos (point)))
23840 (push m org-imenu-markers)
23841 m))
23842
23843 (defun org-imenu-get-tree ()
23844 "Produce the index for Imenu."
23845 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23846 (setq org-imenu-markers nil)
23847 (let* ((n org-imenu-depth)
23848 (re (concat "^" (org-get-limited-outline-regexp)))
23849 (subs (make-vector (1+ n) nil))
23850 (last-level 0)
23851 m level head0 head)
23852 (save-excursion
23853 (save-restriction
23854 (widen)
23855 (goto-char (point-max))
23856 (while (re-search-backward re nil t)
23857 (setq level (org-reduced-level (funcall outline-level)))
23858 (when (and (<= level n)
23859 (looking-at org-complex-heading-regexp)
23860 (setq head0 (org-match-string-no-properties 4)))
23861 (setq head (org-link-display-format head0)
23862 m (org-imenu-new-marker))
23863 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23864 (if (>= level last-level)
23865 (push (cons head m) (aref subs level))
23866 (push (cons head (aref subs (1+ level))) (aref subs level))
23867 (loop for i from (1+ level) to n do (aset subs i nil)))
23868 (setq last-level level)))))
23869 (aref subs 1)))
23870
23871 (eval-after-load "imenu"
23872 '(progn
23873 (add-hook 'imenu-after-jump-hook
23874 (lambda ()
23875 (if (derived-mode-p 'org-mode)
23876 (org-show-context 'org-goto))))))
23877
23878 (defun org-link-display-format (link)
23879 "Replace a link with its the description.
23880 If there is no description, use the link target."
23881 (save-match-data
23882 (if (string-match org-bracket-link-analytic-regexp link)
23883 (replace-match (if (match-end 5)
23884 (match-string 5 link)
23885 (concat (match-string 1 link)
23886 (match-string 3 link)))
23887 nil t link)
23888 link)))
23889
23890 (defun org-toggle-link-display ()
23891 "Toggle the literal or descriptive display of links."
23892 (interactive)
23893 (if org-descriptive-links
23894 (progn (org-remove-from-invisibility-spec '(org-link))
23895 (org-restart-font-lock)
23896 (setq org-descriptive-links nil))
23897 (progn (add-to-invisibility-spec '(org-link))
23898 (org-restart-font-lock)
23899 (setq org-descriptive-links t))))
23900
23901 ;; Speedbar support
23902
23903 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23904 "Overlay marking the agenda restriction line in speedbar.")
23905 (overlay-put org-speedbar-restriction-lock-overlay
23906 'face 'org-agenda-restriction-lock)
23907 (overlay-put org-speedbar-restriction-lock-overlay
23908 'help-echo "Agendas are currently limited to this item.")
23909 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23910
23911 (defun org-speedbar-set-agenda-restriction ()
23912 "Restrict future agenda commands to the location at point in speedbar.
23913 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23914 (interactive)
23915 (require 'org-agenda)
23916 (let (p m tp np dir txt)
23917 (cond
23918 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23919 'org-imenu t))
23920 (setq m (get-text-property p 'org-imenu-marker))
23921 (with-current-buffer (marker-buffer m)
23922 (goto-char m)
23923 (org-agenda-set-restriction-lock 'subtree)))
23924 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23925 'speedbar-function 'speedbar-find-file))
23926 (setq tp (previous-single-property-change
23927 (1+ p) 'speedbar-function)
23928 np (next-single-property-change
23929 tp 'speedbar-function)
23930 dir (speedbar-line-directory)
23931 txt (buffer-substring-no-properties (or tp (point-min))
23932 (or np (point-max))))
23933 (with-current-buffer (find-file-noselect
23934 (let ((default-directory dir))
23935 (expand-file-name txt)))
23936 (unless (derived-mode-p 'org-mode)
23937 (user-error "Cannot restrict to non-Org-mode file"))
23938 (org-agenda-set-restriction-lock 'file)))
23939 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23940 (move-overlay org-speedbar-restriction-lock-overlay
23941 (point-at-bol) (point-at-eol))
23942 (setq current-prefix-arg nil)
23943 (org-agenda-maybe-redo)))
23944
23945 (defvar speedbar-file-key-map)
23946 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23947 (eval-after-load "speedbar"
23948 '(progn
23949 (speedbar-add-supported-extension ".org")
23950 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23951 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23952 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23953 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23954 (add-hook 'speedbar-visiting-tag-hook
23955 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23956
23957 ;;; Fixes and Hacks for problems with other packages
23958
23959 ;; Make flyspell not check words in links, to not mess up our keymap
23960 (defvar org-element-affiliated-keywords) ; From org-element.el
23961 (defvar org-element-block-name-alist) ; From org-element.el
23962 (defun org-mode-flyspell-verify ()
23963 "Don't let flyspell put overlays at active buttons, or on
23964 {todo,all-time,additional-option-like}-keywords."
23965 (require 'org-element) ; For `org-element-affiliated-keywords'
23966 (let ((pos (max (1- (point)) (point-min)))
23967 (word (thing-at-point 'word)))
23968 (and (not (get-text-property pos 'keymap))
23969 (not (get-text-property pos 'org-no-flyspell))
23970 (not (member word org-todo-keywords-1))
23971 (not (member word org-all-time-keywords))
23972 (not (member word org-options-keywords))
23973 (not (member word (mapcar 'car org-startup-options)))
23974 (not (member-ignore-case word org-element-affiliated-keywords))
23975 (not (member-ignore-case word (org-get-export-keywords)))
23976 (not (member-ignore-case
23977 word (mapcar 'car org-element-block-name-alist)))
23978 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23979 (not (org-in-src-block-p)))))
23980
23981 (defun org-remove-flyspell-overlays-in (beg end)
23982 "Remove flyspell overlays in region."
23983 (and (org-bound-and-true-p flyspell-mode)
23984 (fboundp 'flyspell-delete-region-overlays)
23985 (flyspell-delete-region-overlays beg end))
23986 (add-text-properties beg end '(org-no-flyspell t)))
23987
23988 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23989 (eval-after-load "bookmark"
23990 '(if (boundp 'bookmark-after-jump-hook)
23991 ;; We can use the hook
23992 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23993 ;; Hook not available, use advice
23994 (defadvice bookmark-jump (after org-make-visible activate)
23995 "Make the position visible."
23996 (org-bookmark-jump-unhide))))
23997
23998 ;; Make sure saveplace shows the location if it was hidden
23999 (eval-after-load "saveplace"
24000 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24001 "Make the position visible."
24002 (org-bookmark-jump-unhide)))
24003
24004 ;; Make sure ecb shows the location if it was hidden
24005 (eval-after-load "ecb"
24006 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24007 "Make hierarchy visible when jumping into location from ECB tree buffer."
24008 (if (derived-mode-p 'org-mode)
24009 (org-show-context))))
24010
24011 (defun org-bookmark-jump-unhide ()
24012 "Unhide the current position, to show the bookmark location."
24013 (and (derived-mode-p 'org-mode)
24014 (or (outline-invisible-p)
24015 (save-excursion (goto-char (max (point-min) (1- (point))))
24016 (outline-invisible-p)))
24017 (org-show-context 'bookmark-jump)))
24018
24019 ;; Make session.el ignore our circular variable
24020 (defvar session-globals-exclude)
24021 (eval-after-load "session"
24022 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24023
24024 ;;;; Finish up
24025
24026 (provide 'org)
24027
24028 (run-hooks 'org-load-hook)
24029
24030 ;;; org.el ends here