org-eww: Fix docstrings
[org-mode/org-tableheadings.git] / lisp / org.el
blob459e9a1bde168fccbef3a7bfa4a2c20ea4e9f634
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 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
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
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.
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.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
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 doc/ directory.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda"
118 (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-edit-field "org-table" (arg))
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function org-table-next-row "org-table" ())
166 (declare-function org-table-paste-rectangle "org-table" ())
167 (declare-function org-table-wrap-region "org-table" (arg))
168 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
169 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
170 (declare-function orgtbl-mode "org-table" (&optional arg))
172 (defsubst org-uniquify (list)
173 "Non-destructively remove duplicate elements from LIST."
174 (let ((res (copy-sequence list))) (delete-dups res)))
176 (defsubst org-get-at-bol (property)
177 "Get text property PROPERTY at the beginning of line."
178 (get-text-property (point-at-bol) property))
180 (defsubst org-trim (s &optional keep-lead)
181 "Remove whitespace at the beginning and the end of string S.
182 When optional argument KEEP-LEAD is non-nil, removing blank lines
183 at the beginning of the string does not affect leading indentation."
184 (replace-regexp-in-string
185 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
186 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org-mode FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the org-mode file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org-mode buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Emacs Lisp" emacs-lisp)
261 (const :tag "Forth" forth)
262 (const :tag "Fortran" fortran)
263 (const :tag "Gnuplot" gnuplot)
264 (const :tag "Haskell" haskell)
265 (const :tag "IO" io)
266 (const :tag "J" J)
267 (const :tag "Java" java)
268 (const :tag "Javascript" js)
269 (const :tag "LaTeX" latex)
270 (const :tag "Ledger" ledger)
271 (const :tag "Lilypond" lilypond)
272 (const :tag "Lisp" lisp)
273 (const :tag "Makefile" makefile)
274 (const :tag "Maxima" maxima)
275 (const :tag "Matlab" matlab)
276 (const :tag "Mscgen" mscgen)
277 (const :tag "Ocaml" ocaml)
278 (const :tag "Octave" octave)
279 (const :tag "Org" org)
280 (const :tag "Perl" perl)
281 (const :tag "Pico Lisp" picolisp)
282 (const :tag "PlantUML" plantuml)
283 (const :tag "Python" python)
284 (const :tag "Ruby" ruby)
285 (const :tag "Sass" sass)
286 (const :tag "Scala" scala)
287 (const :tag "Scheme" scheme)
288 (const :tag "Screen" screen)
289 (const :tag "Shell Script" shell)
290 (const :tag "Shen" shen)
291 (const :tag "Sql" sql)
292 (const :tag "Sqlite" sqlite)
293 (const :tag "Stan" stan)
294 (const :tag "ebnf2ps" ebnf2ps))
295 :value-type (boolean :tag "Activate" :value t)))
297 ;;;; Customization variables
298 (defcustom org-clone-delete-id nil
299 "Remove ID property of clones of a subtree.
300 When non-nil, clones of a subtree don't inherit the ID property.
301 Otherwise they inherit the ID property with a new unique
302 identifier."
303 :type 'boolean
304 :version "24.1"
305 :group 'org-id)
307 ;;; Version
308 (org-check-version)
310 ;;;###autoload
311 (defun org-version (&optional here full message)
312 "Show the org-mode version.
313 Interactively, or when MESSAGE is non-nil, show it in echo area.
314 With prefix argument, or when HERE is non-nil, insert it at point.
315 In non-interactive uses, a reduced version string is output unless
316 FULL is given."
317 (interactive (list current-prefix-arg t (not current-prefix-arg)))
318 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
319 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
320 (load-suffixes (list ".el"))
321 (org-install-dir
322 (ignore-errors (org-find-library-dir "org-loaddefs"))))
323 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
324 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
325 (let* ((load-suffixes save-load-suffixes)
326 (release (org-release))
327 (git-version (org-git-version))
328 (version (format "Org-mode version %s (%s @ %s)"
329 release
330 git-version
331 (if org-install-dir
332 (if (string= org-dir org-install-dir)
333 org-install-dir
334 (concat "mixed installation! "
335 org-install-dir
336 " and "
337 org-dir))
338 "org-loaddefs.el can not be found!")))
339 (version1 (if full version release)))
340 (when here (insert version1))
341 (when message (message "%s" version1))
342 version1)))
344 (defconst org-version (org-version))
347 ;;; Syntax Constants
349 ;;;; Block
351 (defconst org-block-regexp
352 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
353 "Regular expression for hiding blocks.")
355 (defconst org-dblock-start-re
356 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
357 "Matches the start line of a dynamic block, with parameters.")
359 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
360 "Matches the end of a dynamic block.")
362 ;;;; Clock and Planning
364 (defconst org-clock-string "CLOCK:"
365 "String used as prefix for timestamps clocking work hours on an item.")
367 (defvar org-closed-string "CLOSED:"
368 "String used as the prefix for timestamps logging closing a TODO entry.")
370 (defvar org-deadline-string "DEADLINE:"
371 "String to mark deadline entries.
372 A deadline is this string, followed by a time stamp. Should be a word,
373 terminated by a colon. You can insert a schedule keyword and
374 a timestamp with \\[org-deadline].")
376 (defvar org-scheduled-string "SCHEDULED:"
377 "String to mark scheduled TODO entries.
378 A schedule is this string, followed by a time stamp. Should be a word,
379 terminated by a colon. You can insert a schedule keyword and
380 a timestamp with \\[org-schedule].")
382 (defconst org-ds-keyword-length
383 (+ 2
384 (apply #'max
385 (mapcar #'length
386 (list org-deadline-string org-scheduled-string
387 org-clock-string org-closed-string))))
388 "Maximum length of the DEADLINE and SCHEDULED keywords.")
390 (defconst org-planning-line-re
391 (concat "^[ \t]*"
392 (regexp-opt
393 (list org-closed-string org-deadline-string org-scheduled-string)
395 "Matches a line with planning info.
396 Matched keyword is in group 1.")
398 (defconst org-clock-line-re
399 (concat "^[ \t]*" org-clock-string)
400 "Matches a line with clock info.")
402 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
403 "Matches the DEADLINE keyword.")
405 (defconst org-deadline-time-regexp
406 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
407 "Matches the DEADLINE keyword together with a time stamp.")
409 (defconst org-deadline-time-hour-regexp
410 (concat "\\<" org-deadline-string
411 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
412 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
414 (defconst org-deadline-line-regexp
415 (concat "\\<\\(" org-deadline-string "\\).*")
416 "Matches the DEADLINE keyword and the rest of the line.")
418 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
419 "Matches the SCHEDULED keyword.")
421 (defconst org-scheduled-time-regexp
422 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
423 "Matches the SCHEDULED keyword together with a time stamp.")
425 (defconst org-scheduled-time-hour-regexp
426 (concat "\\<" org-scheduled-string
427 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
428 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
430 (defconst org-closed-time-regexp
431 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
432 "Matches the CLOSED keyword together with a time stamp.")
434 (defconst org-keyword-time-regexp
435 (concat "\\<"
436 (regexp-opt
437 (list org-scheduled-string org-deadline-string org-closed-string
438 org-clock-string)
440 " *[[<]\\([^]>]+\\)[]>]")
441 "Matches any of the 4 keywords, together with the time stamp.")
443 (defconst org-keyword-time-not-clock-regexp
444 (concat
445 "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string) t)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 3 keywords, together with the time stamp.")
451 (defconst org-maybe-keyword-time-regexp
452 (concat "\\(\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 "\\)?"
458 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
459 "\\|"
460 "<%%([^\r\n>]*>\\)")
461 "Matches a timestamp, possibly preceded by a keyword.")
463 (defconst org-all-time-keywords
464 (mapcar (lambda (w) (substring w 0 -1))
465 (list org-scheduled-string org-deadline-string
466 org-clock-string org-closed-string))
467 "List of time keywords.")
469 ;;;; Drawer
471 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
472 "Matches first or last line of a hidden block.
473 Group 1 contains drawer's name or \"END\".")
475 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
476 "Regular expression matching the first line of a property drawer.")
478 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
479 "Regular expression matching the last line of a property drawer.")
481 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
482 "Regular expression matching the first line of a clock drawer.")
484 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a clock drawer.")
487 (defconst org-property-drawer-re
488 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
489 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
490 "[ \t]*:END:[ \t]*$")
491 "Matches an entire property drawer.")
493 (defconst org-clock-drawer-re
494 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
495 org-clock-drawer-end-re "\\)\n?")
496 "Matches an entire clock drawer.")
498 ;;;; Headline
500 (defconst org-heading-keyword-regexp-format
501 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
502 "Printf format for a regexp matching a headline with some keyword.
503 This regexp will match the headline of any node which has the
504 exact keyword that is put into the format. The keyword isn't in
505 any group by default, but the stars and the body are.")
507 (defconst org-heading-keyword-maybe-regexp-format
508 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
509 "Printf format for a regexp matching a headline, possibly with some keyword.
510 This regexp can match any headline with the specified keyword, or
511 without a keyword. The keyword isn't in any group by default,
512 but the stars and the body are.")
514 (defconst org-archive-tag "ARCHIVE"
515 "The tag that marks a subtree as archived.
516 An archived subtree does not open during visibility cycling, and does
517 not contribute to the agenda listings.")
519 (defconst org-comment-string "COMMENT"
520 "Entries starting with this keyword will never be exported.
521 An entry can be toggled between COMMENT and normal with
522 \\[org-toggle-comment].")
525 ;;;; LaTeX Environments and Fragments
527 (defconst org-latex-regexps
528 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
529 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
530 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
531 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
532 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
533 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
534 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
535 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
536 "Regular expressions for matching embedded LaTeX.")
538 ;;;; Node Property
540 (defconst org-effort-property "Effort"
541 "The property that is being used to keep track of effort estimates.
542 Effort estimates given in this property need to have the format H:MM.")
544 ;;;; Table
546 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
547 "Detect an org-type or table-type table.")
549 (defconst org-table-line-regexp "^[ \t]*|"
550 "Detect an org-type table line.")
552 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
553 "Detect an org-type table line.")
555 (defconst org-table-hline-regexp "^[ \t]*|-"
556 "Detect an org-type table hline.")
558 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
559 "Detect a table-type table hline.")
561 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
562 "Detect the first line outside a table when searching from within it.
563 This works for both table types.")
565 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
566 "Detect a #+TBLFM line.")
568 ;;;; Timestamp
570 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
571 "Regular expression for fast time stamp matching.")
573 (defconst org-ts-regexp-inactive
574 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
575 "Regular expression for fast inactive time stamp matching.")
577 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp0
581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
582 "Regular expression matching time strings for analysis.
583 This one does not require the space after the date, so it can be used
584 on a string that terminates immediately after the date.")
586 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.")
589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
590 "Regular expression matching time stamps, with groups.")
592 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
593 "Regular expression matching time stamps (also [..]), with groups.")
595 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
596 "Regular expression matching a time stamp range.")
598 (defconst org-tr-regexp-both
599 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
600 "Regular expression matching a time stamp range.")
602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
603 org-ts-regexp "\\)?")
604 "Regular expression matching a time stamp or time stamp range.")
606 (defconst org-tsr-regexp-both
607 (concat org-ts-regexp-both "\\(--?-?"
608 org-ts-regexp-both "\\)?")
609 "Regular expression matching a time stamp or time stamp range.
610 The time stamps may be either active or inactive.")
612 (defconst org-repeat-re
613 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
614 "Regular expression for specifying repeated events.
615 After a match, group 1 contains the repeat expression.")
617 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
618 "Formats for `format-time-string' which are used for time stamps.")
621 ;;; The custom variables
623 (defgroup org nil
624 "Outline-based notes management and organizer."
625 :tag "Org"
626 :group 'outlines
627 :group 'calendar)
629 (defcustom org-mode-hook nil
630 "Mode hook for Org-mode, run after the mode was turned on."
631 :group 'org
632 :type 'hook)
634 (defcustom org-load-hook nil
635 "Hook that is run after org.el has been loaded."
636 :group 'org
637 :type 'hook)
639 (defcustom org-log-buffer-setup-hook nil
640 "Hook that is run after an Org log buffer is created."
641 :group 'org
642 :version "24.1"
643 :type 'hook)
645 (defvar org-modules) ; defined below
646 (defvar org-modules-loaded nil
647 "Have the modules been loaded already?")
649 (defun org-load-modules-maybe (&optional force)
650 "Load all extensions listed in `org-modules'."
651 (when (or force (not org-modules-loaded))
652 (dolist (ext org-modules)
653 (condition-case nil (require ext)
654 (error (message "Problems while trying to load feature `%s'" ext))))
655 (setq org-modules-loaded t)))
657 (defun org-set-modules (var value)
658 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
659 (set var value)
660 (when (featurep 'org)
661 (org-load-modules-maybe 'force)
662 (org-element-cache-reset 'all)))
664 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
665 "Modules that should always be loaded together with org.el.
667 If a description starts with <C>, the file is not part of Emacs
668 and loading it will require that you have downloaded and properly
669 installed the Org mode distribution.
671 You can also use this system to load external packages (i.e. neither Org
672 core modules, nor modules from the CONTRIB directory). Just add symbols
673 to the end of the list. If the package is called org-xyz.el, then you need
674 to add the symbol `xyz', and the package must have a call to:
676 (provide \\='org-xyz)
678 For export specific modules, see also `org-export-backends'."
679 :group 'org
680 :set 'org-set-modules
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type
684 '(set :greedy t
685 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
686 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
687 (const :tag " crypt: Encryption of subtrees" org-crypt)
688 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
689 (const :tag " docview: Links to doc-view buffers" org-docview)
690 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
691 (const :tag " habit: Track your consistency with habits" org-habit)
692 (const :tag " id: Global IDs for identifying entries" org-id)
693 (const :tag " info: Links to Info nodes" org-info)
694 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
695 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
696 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
697 (const :tag " mouse: Additional mouse support" org-mouse)
698 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
699 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
700 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
702 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
703 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
704 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
705 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
706 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
707 (const :tag "C collector: Collect properties into tables" org-collector)
708 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
709 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
710 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
711 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
712 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
713 (const :tag "C eval: Include command output as text" org-eval)
714 (const :tag "C eww: Store link to url of eww" org-eww)
715 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
716 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
717 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
718 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
719 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
720 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
721 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
722 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
723 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
724 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
725 (const :tag "C mew: Links to Mew folders/messages" org-mew)
726 (const :tag "C mtags: Support for muse-like tags" org-mtags)
727 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
728 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
729 (const :tag "C registry: A registry for Org-mode links" org-registry)
730 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
731 (const :tag "C secretary: Team management with org-mode" org-secretary)
732 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
733 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
734 (const :tag "C track: Keep up with Org-mode development" org-track)
735 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
736 (const :tag "C vm: Links to VM folders/messages" org-vm)
737 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
738 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
739 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
741 (defvar org-export-registered-backends) ; From ox.el.
742 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
743 (declare-function org-export-backend-name "ox" (backend) t)
744 (defcustom org-export-backends '(ascii html icalendar latex odt)
745 "List of export back-ends that should be always available.
747 If a description starts with <C>, the file is not part of Emacs
748 and loading it will require that you have downloaded and properly
749 installed the Org mode distribution.
751 Unlike to `org-modules', libraries in this list will not be
752 loaded along with Org, but only once the export framework is
753 needed.
755 This variable needs to be set before org.el is loaded. If you
756 need to make a change while Emacs is running, use the customize
757 interface or run the following code, where VAL stands for the new
758 value of the variable, after updating it:
760 (progn
761 (setq org-export-registered-backends
762 (cl-remove-if-not
763 (lambda (backend)
764 (let ((name (org-export-backend-name backend)))
765 (or (memq name val)
766 (catch \\='parentp
767 (dolist (b val)
768 (and (org-export-derived-backend-p b name)
769 (throw \\='parentp t)))))))
770 org-export-registered-backends))
771 (let ((new-list (mapcar #\\='org-export-backend-name
772 org-export-registered-backends)))
773 (dolist (backend val)
774 (cond
775 ((not (load (format \"ox-%s\" backend) t t))
776 (message \"Problems while trying to load export back-end \\=`%s\\='\"
777 backend))
778 ((not (memq backend new-list)) (push backend new-list))))
779 (set-default \\='org-export-backends new-list)))
781 Adding a back-end to this list will also pull the back-end it
782 depends on, if any."
783 :group 'org
784 :group 'org-export
785 :version "25.1"
786 :package-version '(Org . "9.0")
787 :initialize 'custom-initialize-set
788 :set (lambda (var val)
789 (if (not (featurep 'ox)) (set-default var val)
790 ;; Any back-end not required anymore (not present in VAL and not
791 ;; a parent of any back-end in the new value) is removed from the
792 ;; list of registered back-ends.
793 (setq org-export-registered-backends
794 (cl-remove-if-not
795 (lambda (backend)
796 (let ((name (org-export-backend-name backend)))
797 (or (memq name val)
798 (catch 'parentp
799 (dolist (b val)
800 (and (org-export-derived-backend-p b name)
801 (throw 'parentp t)))))))
802 org-export-registered-backends))
803 ;; Now build NEW-LIST of both new back-ends and required
804 ;; parents.
805 (let ((new-list (mapcar #'org-export-backend-name
806 org-export-registered-backends)))
807 (dolist (backend val)
808 (cond
809 ((not (load (format "ox-%s" backend) t t))
810 (message "Problems while trying to load export back-end `%s'"
811 backend))
812 ((not (memq backend new-list)) (push backend new-list))))
813 ;; Set VAR to that list with fixed dependencies.
814 (set-default var new-list))))
815 :type '(set :greedy t
816 (const :tag " ascii Export buffer to ASCII format" ascii)
817 (const :tag " beamer Export buffer to Beamer presentation" beamer)
818 (const :tag " html Export buffer to HTML format" html)
819 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
820 (const :tag " latex Export buffer to LaTeX format" latex)
821 (const :tag " man Export buffer to MAN format" man)
822 (const :tag " md Export buffer to Markdown format" md)
823 (const :tag " odt Export buffer to ODT format" odt)
824 (const :tag " org Export buffer to Org format" org)
825 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
826 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
827 (const :tag "C deck Export buffer to deck.js presentations" deck)
828 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
829 (const :tag "C groff Export buffer to Groff format" groff)
830 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
831 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
832 (const :tag "C s5 Export buffer to s5 presentations" s5)
833 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
835 (eval-after-load 'ox
836 '(dolist (backend org-export-backends)
837 (condition-case nil (require (intern (format "ox-%s" backend)))
838 (error (message "Problems while trying to load export back-end `%s'"
839 backend)))))
841 (defcustom org-support-shift-select nil
842 "Non-nil means make shift-cursor commands select text when possible.
843 \\<org-mode-map>\
845 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
846 start selecting a region, or enlarge regions started in this way.
847 In Org-mode, in special contexts, these same keys are used for
848 other purposes, important enough to compete with shift selection.
849 Org tries to balance these needs by supporting `shift-select-mode'
850 outside these special contexts, under control of this variable.
852 The default of this variable is nil, to avoid confusing behavior. Shifted
853 cursor keys will then execute Org commands in the following contexts:
854 - on a headline, changing TODO state (left/right) and priority (up/down)
855 - on a time stamp, changing the time
856 - in a plain list item, changing the bullet type
857 - in a property definition line, switching between allowed values
858 - in the BEGIN line of a clock table (changing the time block).
859 Outside these contexts, the commands will throw an error.
861 When this variable is t and the cursor is not in a special
862 context, Org-mode will support shift-selection for making and
863 enlarging regions. To make this more effective, the bullet
864 cycling will no longer happen anywhere in an item line, but only
865 if the cursor is exactly on the bullet.
867 If you set this variable to the symbol `always', then the keys
868 will not be special in headlines, property lines, and item lines,
869 to make shift selection work there as well. If this is what you
870 want, you can use the following alternative commands:
871 `\\[org-todo]' and `\\[org-priority]' \
872 to change TODO state and priority,
873 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
874 can be used to switch TODO sets,
875 `\\[org-ctrl-c-minus]' to cycle item bullet types,
876 and properties can be edited by hand or in column view.
878 However, when the cursor is on a timestamp, shift-cursor commands
879 will still edit the time stamp - this is just too good to give up."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped.
942 The variable `org-startup-truncated' allows to configure
943 truncation for Org mode different to the other modes that use the
944 variable `truncate-lines' and as a shortcut instead of putting
945 the variable `truncate-lines' into the `org-mode-hook'. If one
946 wants to configure truncation for Org mode not statically but
947 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
948 the variable `truncate-lines' has to be used because in such a
949 case it is too late to set the variable `org-startup-truncated'."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
958 #+STARTUP: indent
959 #+STARTUP: noindent"
960 :group 'org-structure
961 :type '(choice
962 (const :tag "Not" nil)
963 (const :tag "Globally (slow on startup in large files)" t)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
990 :group 'org-startup
991 :version "24.4"
992 :package-version '(Org . "8.0")
993 :type '(choice
994 (const :tag "Always interpret" t)
995 (const :tag "Only with braces" {})
996 (const :tag "Never interpret" nil)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1003 #+STARTUP: beamer"
1004 :group 'org-startup
1005 :version "24.1"
1006 :type 'boolean)
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This is useful when the column width in tables is forced with <N> cookies
1011 in table fields. Such tables will look correct only after the first re-align.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-with-inline-images nil
1020 "Non-nil means show inline images when loading a new Org file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: inlineimages
1024 #+STARTUP: noinlineimages"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-with-latex-preview nil
1030 "Non-nil means preview LaTeX fragments when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: latexpreview
1035 #+STARTUP: nolatexpreview"
1036 :group 'org-startup
1037 :version "24.4"
1038 :package-version '(Org . "8.0")
1039 :type 'boolean)
1041 (defcustom org-insert-mode-line-in-empty-file nil
1042 "Non-nil means insert the first line setting Org-mode in empty files.
1043 When the function `org-mode' is called interactively in an empty file, this
1044 normally means that the file name does not automatically trigger Org-mode.
1045 To ensure that the file will always be in Org-mode in the future, a
1046 line enforcing Org-mode will be inserted into the buffer, if this option
1047 has been set."
1048 :group 'org-startup
1049 :type 'boolean)
1051 (defcustom org-replace-disputed-keys nil
1052 "Non-nil means use alternative key bindings for some keys.
1053 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1054 These keys are also used by other packages like shift-selection-mode'
1055 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1056 If you want to use Org-mode together with one of these other modes,
1057 or more generally if you would like to move some Org-mode commands to
1058 other keys, set this variable and configure the keys with the variable
1059 `org-disputed-keys'.
1061 This option is only relevant at load-time of Org-mode, and must be set
1062 *before* org.el is loaded. Changing it requires a restart of Emacs to
1063 become effective."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-use-extra-keys nil
1068 "Non-nil means use extra key sequence definitions for certain commands.
1069 This happens automatically if `window-system' is nil. This
1070 variable lets you do the same manually. You must set it before
1071 loading Org."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1077 (defcustom org-disputed-keys
1078 '(([(shift up)] . [(meta p)])
1079 ([(shift down)] . [(meta n)])
1080 ([(shift left)] . [(meta -)])
1081 ([(shift right)] . [(meta +)])
1082 ([(control shift right)] . [(meta shift +)])
1083 ([(control shift left)] . [(meta shift -)]))
1084 "Keys for which Org-mode and other modes compete.
1085 This is an alist, cars are the default keys, second element specifies
1086 the alternative to use when `org-replace-disputed-keys' is t.
1088 Keys can be specified in any syntax supported by `define-key'.
1089 The value of this option takes effect only at Org-mode's startup,
1090 therefore you'll have to restart Emacs to apply it after changing."
1091 :group 'org-startup
1092 :type 'alist)
1094 (defun org-key (key)
1095 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1096 Or return the original if not disputed."
1097 (when org-replace-disputed-keys
1098 (let* ((nkey (key-description key))
1099 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1100 org-disputed-keys)))
1101 (setq key (if x (cdr x) key))))
1102 key)
1104 (defun org-defkey (keymap key def)
1105 "Define a key, possibly translated, as returned by `org-key'."
1106 (define-key keymap (org-key key) def))
1108 (defcustom org-ellipsis nil
1109 "The ellipsis to use in the Org-mode outline.
1110 When nil, just use the standard three dots.
1111 When a string, use that string instead.
1112 When a face, use the standard 3 dots, but with the specified face.
1113 The change affects only Org-mode (which will then use its own display table).
1114 Changing this requires executing \\[org-mode] in a buffer to become
1115 effective."
1116 :group 'org-startup
1117 :type '(choice (const :tag "Default" nil)
1118 (face :tag "Face" :value org-warning)
1119 (string :tag "String" :value "...#")))
1121 (defvar org-display-table nil
1122 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1124 (defgroup org-keywords nil
1125 "Keywords in Org-mode."
1126 :tag "Org Keywords"
1127 :group 'org)
1129 (defcustom org-closed-keep-when-no-todo nil
1130 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1131 :group 'org-todo
1132 :group 'org-keywords
1133 :version "24.4"
1134 :package-version '(Org . "8.0")
1135 :type 'boolean)
1137 (defgroup org-structure nil
1138 "Options concerning the general structure of Org-mode files."
1139 :tag "Org Structure"
1140 :group 'org)
1142 (defgroup org-reveal-location nil
1143 "Options about how to make context of a location visible."
1144 :tag "Org Reveal Location"
1145 :group 'org-structure)
1147 (defcustom org-show-context-detail '((agenda . local)
1148 (bookmark-jump . lineage)
1149 (isearch . lineage)
1150 (default . ancestors))
1151 "Alist between context and visibility span when revealing a location.
1153 \\<org-mode-map>Some actions may move point into invisible
1154 locations. As a consequence, Org always expose a neighborhood
1155 around point. How much is shown depends on the initial action,
1156 or context. Valid contexts are
1158 agenda when exposing an entry from the agenda
1159 org-goto when using the command `org-goto' (\\[org-goto])
1160 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1161 tags-tree when constructing a sparse tree based on tags matches
1162 link-search when exposing search matches associated with a link
1163 mark-goto when exposing the jump goal of a mark
1164 bookmark-jump when exposing a bookmark location
1165 isearch when exiting from an incremental search
1166 default default for all contexts not set explicitly
1168 Allowed visibility spans are
1170 minimal show current headline; if point is not on headline,
1171 also show entry
1173 local show current headline, entry and next headline
1175 ancestors show current headline and its direct ancestors; if
1176 point is not on headline, also show entry
1178 lineage show current headline, its direct ancestors and all
1179 their children; if point is not on headline, also show
1180 entry and first child
1182 tree show current headline, its direct ancestors and all
1183 their children; if point is not on headline, also show
1184 entry and all children
1186 canonical show current headline, its direct ancestors along with
1187 their entries and children; if point is not located on
1188 the headline, also show current entry and all children
1190 As special cases, a nil or t value means show all contexts in
1191 `minimal' or `canonical' view, respectively.
1193 Some views can make displayed information very compact, but also
1194 make it harder to edit the location of the match. In such
1195 a case, use the command `org-reveal' (\\[org-reveal]) to show
1196 more context."
1197 :group 'org-reveal-location
1198 :version "25.2"
1199 :package-version '(Org . "9.0")
1200 :type '(choice
1201 (const :tag "Canonical" t)
1202 (const :tag "Minimal" nil)
1203 (repeat :greedy t :tag "Individual contexts"
1204 (cons
1205 (choice :tag "Context"
1206 (const agenda)
1207 (const org-goto)
1208 (const occur-tree)
1209 (const tags-tree)
1210 (const link-search)
1211 (const mark-goto)
1212 (const bookmark-jump)
1213 (const isearch)
1214 (const default))
1215 (choice :tag "Detail level"
1216 (const minimal)
1217 (const local)
1218 (const ancestors)
1219 (const lineage)
1220 (const tree)
1221 (const canonical))))))
1223 (defcustom org-indirect-buffer-display 'other-window
1224 "How should indirect tree buffers be displayed?
1225 This applies to indirect buffers created with the commands
1226 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1227 Valid values are:
1228 current-window Display in the current window
1229 other-window Just display in another window.
1230 dedicated-frame Create one new frame, and re-use it each time.
1231 new-frame Make a new frame each time. Note that in this case
1232 previously-made indirect buffers are kept, and you need to
1233 kill these buffers yourself."
1234 :group 'org-structure
1235 :group 'org-agenda-windows
1236 :type '(choice
1237 (const :tag "In current window" current-window)
1238 (const :tag "In current frame, other window" other-window)
1239 (const :tag "Each time a new frame" new-frame)
1240 (const :tag "One dedicated frame" dedicated-frame)))
1242 (defcustom org-use-speed-commands nil
1243 "Non-nil means activate single letter commands at beginning of a headline.
1244 This may also be a function to test for appropriate locations where speed
1245 commands should be active.
1247 For example, to activate speed commands when the point is on any
1248 star at the beginning of the headline, you can do this:
1250 (setq org-use-speed-commands
1251 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1252 :group 'org-structure
1253 :type '(choice
1254 (const :tag "Never" nil)
1255 (const :tag "At beginning of headline stars" t)
1256 (function)))
1258 (defcustom org-speed-commands-user nil
1259 "Alist of additional speed commands.
1260 This list will be checked before `org-speed-commands-default'
1261 when the variable `org-use-speed-commands' is non-nil
1262 and when the cursor is at the beginning of a headline.
1263 The car if each entry is a string with a single letter, which must
1264 be assigned to `self-insert-command' in the global map.
1265 The cdr is either a command to be called interactively, a function
1266 to be called, or a form to be evaluated.
1267 An entry that is just a list with a single string will be interpreted
1268 as a descriptive headline that will be added when listing the speed
1269 commands in the Help buffer using the `?' speed command."
1270 :group 'org-structure
1271 :type '(repeat :value ("k" . ignore)
1272 (choice :value ("k" . ignore)
1273 (list :tag "Descriptive Headline" (string :tag "Headline"))
1274 (cons :tag "Letter and Command"
1275 (string :tag "Command letter")
1276 (choice
1277 (function)
1278 (sexp))))))
1280 (defcustom org-bookmark-names-plist
1281 '(:last-capture "org-capture-last-stored"
1282 :last-refile "org-refile-last-stored"
1283 :last-capture-marker "org-capture-last-stored-marker")
1284 "Names for bookmarks automatically set by some Org commands.
1285 This can provide strings as names for a number of bookmarks Org sets
1286 automatically. The following keys are currently implemented:
1287 :last-capture
1288 :last-capture-marker
1289 :last-refile
1290 When a key does not show up in the property list, the corresponding bookmark
1291 is not set."
1292 :group 'org-structure
1293 :type 'plist)
1295 (defgroup org-cycle nil
1296 "Options concerning visibility cycling in Org-mode."
1297 :tag "Org Cycle"
1298 :group 'org-structure)
1300 (defcustom org-cycle-skip-children-state-if-no-children t
1301 "Non-nil means skip CHILDREN state in entries that don't have any."
1302 :group 'org-cycle
1303 :type 'boolean)
1305 (defcustom org-cycle-max-level nil
1306 "Maximum level which should still be subject to visibility cycling.
1307 Levels higher than this will, for cycling, be treated as text, not a headline.
1308 When `org-odd-levels-only' is set, a value of N in this variable actually
1309 means 2N-1 stars as the limiting headline.
1310 When nil, cycle all levels.
1311 Note that the limiting level of cycling is also influenced by
1312 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1313 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1314 than its value."
1315 :group 'org-cycle
1316 :type '(choice
1317 (const :tag "No limit" nil)
1318 (integer :tag "Maximum level")))
1320 (defcustom org-hide-block-startup nil
1321 "Non-nil means entering Org-mode will fold all blocks.
1322 This can also be set in on a per-file basis with
1324 #+STARTUP: hideblocks
1325 #+STARTUP: showblocks"
1326 :group 'org-startup
1327 :group 'org-cycle
1328 :type 'boolean)
1330 (defcustom org-cycle-global-at-bob nil
1331 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1332 This makes it possible to do global cycling without having to use S-TAB or
1333 \\[universal-argument] TAB. For this special case to work, the first line
1334 of the buffer must not be a headline -- it may be empty or some other text.
1335 When used in this way, `org-cycle-hook' is disabled temporarily to make
1336 sure the cursor stays at the beginning of the buffer. When this option is
1337 nil, don't do anything special at the beginning of the buffer."
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-level-after-item/entry-creation t
1342 "Non-nil means cycle entry level or item indentation in new empty entries.
1344 When the cursor is at the end of an empty headline, i.e., with only stars
1345 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1346 and then all possible ancestor states, before returning to the original state.
1347 This makes data entry extremely fast: M-RET to create a new headline,
1348 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1350 When the cursor is at the end of an empty plain list item, one TAB will
1351 make it a subitem, two or more tabs will back up to make this an item
1352 higher up in the item hierarchy."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-emulate-tab t
1357 "Where should `org-cycle' emulate TAB.
1358 nil Never
1359 white Only in completely white lines
1360 whitestart Only at the beginning of lines, before the first non-white char
1361 t Everywhere except in headlines
1362 exc-hl-bol Everywhere except at the start of a headline
1363 If TAB is used in a place where it does not emulate TAB, the current subtree
1364 visibility is cycled."
1365 :group 'org-cycle
1366 :type '(choice (const :tag "Never" nil)
1367 (const :tag "Only in completely white lines" white)
1368 (const :tag "Before first char in a line" whitestart)
1369 (const :tag "Everywhere except in headlines" t)
1370 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1372 (defcustom org-cycle-separator-lines 2
1373 "Number of empty lines needed to keep an empty line between collapsed trees.
1374 If you leave an empty line between the end of a subtree and the following
1375 headline, this empty line is hidden when the subtree is folded.
1376 Org-mode will leave (exactly) one empty line visible if the number of
1377 empty lines is equal or larger to the number given in this variable.
1378 So the default 2 means at least 2 empty lines after the end of a subtree
1379 are needed to produce free space between a collapsed subtree and the
1380 following headline.
1382 If the number is negative, and the number of empty lines is at least -N,
1383 all empty lines are shown.
1385 Special case: when 0, never leave empty lines in collapsed view."
1386 :group 'org-cycle
1387 :type 'integer)
1388 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1390 (defcustom org-pre-cycle-hook nil
1391 "Hook that is run before visibility cycling is happening.
1392 The function(s) in this hook must accept a single argument which indicates
1393 the new state that will be set right after running this hook. The
1394 argument is a symbol. Before a global state change, it can have the values
1395 `overview', `content', or `all'. Before a local state change, it can have
1396 the values `folded', `children', or `subtree'."
1397 :group 'org-cycle
1398 :type 'hook)
1400 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1401 org-cycle-hide-drawers
1402 org-cycle-show-empty-lines
1403 org-optimize-window-after-visibility-change)
1404 "Hook that is run after `org-cycle' has changed the buffer visibility.
1405 The function(s) in this hook must accept a single argument which indicates
1406 the new state that was set by the most recent `org-cycle' command. The
1407 argument is a symbol. After a global state change, it can have the values
1408 `overview', `contents', or `all'. After a local state change, it can have
1409 the values `folded', `children', or `subtree'."
1410 :group 'org-cycle
1411 :type 'hook
1412 :version "25.1"
1413 :package-version '(Org . "8.3"))
1415 (defgroup org-edit-structure nil
1416 "Options concerning structure editing in Org-mode."
1417 :tag "Org Edit Structure"
1418 :group 'org-structure)
1420 (defcustom org-odd-levels-only nil
1421 "Non-nil means skip even levels and only use odd levels for the outline.
1422 This has the effect that two stars are being added/taken away in
1423 promotion/demotion commands. It also influences how levels are
1424 handled by the exporters.
1425 Changing it requires restart of `font-lock-mode' to become effective
1426 for fontification also in regions already fontified.
1427 You may also set this on a per-file basis by adding one of the following
1428 lines to the buffer:
1430 #+STARTUP: odd
1431 #+STARTUP: oddeven"
1432 :group 'org-edit-structure
1433 :group 'org-appearance
1434 :type 'boolean)
1436 (defcustom org-adapt-indentation t
1437 "Non-nil means adapt indentation to outline node level.
1439 When this variable is set, Org assumes that you write outlines by
1440 indenting text in each node to align with the headline (after the
1441 stars). The following issues are influenced by this variable:
1443 - The indentation is increased by one space in a demotion
1444 command, and decreased by one in a promotion command. However,
1445 in the latter case, if shifting some line in the entry body
1446 would alter document structure (e.g., insert a new headline),
1447 indentation is not changed at all.
1449 - Property drawers and planning information is inserted indented
1450 when this variable is set. When nil, they will not be indented.
1452 - TAB indents a line relative to current level. The lines below
1453 a headline will be indented when this variable is set.
1455 Note that this is all about true indentation, by adding and
1456 removing space characters. See also `org-indent.el' which does
1457 level-dependent indentation in a virtual way, i.e. at display
1458 time in Emacs."
1459 :group 'org-edit-structure
1460 :type 'boolean)
1462 (defcustom org-special-ctrl-a/e nil
1463 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1465 When t, `C-a' will bring back the cursor to the beginning of the
1466 headline text, i.e. after the stars and after a possible TODO
1467 keyword. In an item, this will be the position after bullet and
1468 check-box, if any. When the cursor is already at that position,
1469 another `C-a' will bring it to the beginning of the line.
1471 `C-e' will jump to the end of the headline, ignoring the presence
1472 of tags in the headline. A second `C-e' will then jump to the
1473 true end of the line, after any tags. This also means that, when
1474 this variable is non-nil, `C-e' also will never jump beyond the
1475 end of the heading of a folded section, i.e. not after the
1476 ellipses.
1478 When set to the symbol `reversed', the first `C-a' or `C-e' works
1479 normally, going to the true line boundary first. Only a directly
1480 following, identical keypress will bring the cursor to the
1481 special positions.
1483 This may also be a cons cell where the behavior for `C-a' and
1484 `C-e' is set separately."
1485 :group 'org-edit-structure
1486 :type '(choice
1487 (const :tag "off" nil)
1488 (const :tag "on: after stars/bullet and before tags first" t)
1489 (const :tag "reversed: true line boundary first" reversed)
1490 (cons :tag "Set C-a and C-e separately"
1491 (choice :tag "Special C-a"
1492 (const :tag "off" nil)
1493 (const :tag "on: after stars/bullet first" t)
1494 (const :tag "reversed: before stars/bullet first" reversed))
1495 (choice :tag "Special C-e"
1496 (const :tag "off" nil)
1497 (const :tag "on: before tags first" t)
1498 (const :tag "reversed: after tags first" reversed)))))
1499 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1501 (defcustom org-special-ctrl-k nil
1502 "Non-nil means `C-k' will behave specially in headlines.
1503 When nil, `C-k' will call the default `kill-line' command.
1504 When t, the following will happen while the cursor is in the headline:
1506 - When the cursor is at the beginning of a headline, kill the entire
1507 line and possible the folded subtree below the line.
1508 - When in the middle of the headline text, kill the headline up to the tags.
1509 - When after the headline text, kill the tags."
1510 :group 'org-edit-structure
1511 :type 'boolean)
1513 (defcustom org-ctrl-k-protect-subtree nil
1514 "Non-nil means, do not delete a hidden subtree with C-k.
1515 When set to the symbol `error', simply throw an error when C-k is
1516 used to kill (part-of) a headline that has hidden text behind it.
1517 Any other non-nil value will result in a query to the user, if it is
1518 OK to kill that hidden subtree. When nil, kill without remorse."
1519 :group 'org-edit-structure
1520 :version "24.1"
1521 :type '(choice
1522 (const :tag "Do not protect hidden subtrees" nil)
1523 (const :tag "Protect hidden subtrees with a security query" t)
1524 (const :tag "Never kill a hidden subtree with C-k" error)))
1526 (defcustom org-special-ctrl-o t
1527 "Non-nil means, make `C-o' insert a row in tables."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-catch-invisible-edits nil
1532 "Check if in invisible region before inserting or deleting a character.
1533 Valid values are:
1535 nil Do not check, so just do invisible edits.
1536 error Throw an error and do nothing.
1537 show Make point visible, and do the requested edit.
1538 show-and-error Make point visible, then throw an error and abort the edit.
1539 smart Make point visible, and do insertion/deletion if it is
1540 adjacent to visible text and the change feels predictable.
1541 Never delete a previously invisible character or add in the
1542 middle or right after an invisible region. Basically, this
1543 allows insertion and backward-delete right before ellipses.
1544 FIXME: maybe in this case we should not even show?"
1545 :group 'org-edit-structure
1546 :version "24.1"
1547 :type '(choice
1548 (const :tag "Do not check" nil)
1549 (const :tag "Throw error when trying to edit" error)
1550 (const :tag "Unhide, but do not do the edit" show-and-error)
1551 (const :tag "Show invisible part and do the edit" show)
1552 (const :tag "Be smart and do the right thing" smart)))
1554 (defcustom org-yank-folded-subtrees t
1555 "Non-nil means when yanking subtrees, fold them.
1556 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1557 it starts with a heading and all other headings in it are either children
1558 or siblings, then fold all the subtrees. However, do this only if no
1559 text after the yank would be swallowed into a folded tree by this action."
1560 :group 'org-edit-structure
1561 :type 'boolean)
1563 (defcustom org-yank-adjusted-subtrees nil
1564 "Non-nil means when yanking subtrees, adjust the level.
1565 With this setting, `org-paste-subtree' is used to insert the subtree, see
1566 this function for details."
1567 :group 'org-edit-structure
1568 :type 'boolean)
1570 (defcustom org-M-RET-may-split-line '((default . t))
1571 "Non-nil means M-RET will split the line at the cursor position.
1572 When nil, it will go to the end of the line before making a
1573 new line.
1574 You may also set this option in a different way for different
1575 contexts. Valid contexts are:
1577 headline when creating a new headline
1578 item when creating a new item
1579 table in a table field
1580 default the value to be used for all contexts not explicitly
1581 customized"
1582 :group 'org-structure
1583 :group 'org-table
1584 :type '(choice
1585 (const :tag "Always" t)
1586 (const :tag "Never" nil)
1587 (repeat :greedy t :tag "Individual contexts"
1588 (cons
1589 (choice :tag "Context"
1590 (const headline)
1591 (const item)
1592 (const table)
1593 (const default))
1594 (boolean)))))
1597 (defcustom org-insert-heading-respect-content nil
1598 "Non-nil means insert new headings after the current subtree.
1599 When nil, the new heading is created directly after the current line.
1600 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1601 this variable on for the duration of the command."
1602 :group 'org-structure
1603 :type 'boolean)
1605 (defcustom org-blank-before-new-entry '((heading . auto)
1606 (plain-list-item . auto))
1607 "Should `org-insert-heading' leave a blank line before new heading/item?
1608 The value is an alist, with `heading' and `plain-list-item' as CAR,
1609 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1610 which case Org will look at the surrounding headings/items and try to
1611 make an intelligent decision whether to insert a blank line or not."
1612 :group 'org-edit-structure
1613 :type '(list
1614 (cons (const heading)
1615 (choice (const :tag "Never" nil)
1616 (const :tag "Always" t)
1617 (const :tag "Auto" auto)))
1618 (cons (const plain-list-item)
1619 (choice (const :tag "Never" nil)
1620 (const :tag "Always" t)
1621 (const :tag "Auto" auto)))))
1623 (defcustom org-insert-heading-hook nil
1624 "Hook being run after inserting a new heading."
1625 :group 'org-edit-structure
1626 :type 'hook)
1628 (defcustom org-enable-fixed-width-editor t
1629 "Non-nil means lines starting with \":\" are treated as fixed-width.
1630 This currently only means they are never auto-wrapped.
1631 When nil, such lines will be treated like ordinary lines."
1632 :group 'org-edit-structure
1633 :type 'boolean)
1635 (defcustom org-goto-auto-isearch t
1636 "Non-nil means typing characters in `org-goto' starts incremental search.
1637 When nil, you can use these keybindings to navigate the buffer:
1639 q Quit the org-goto interface
1640 n Go to the next visible heading
1641 p Go to the previous visible heading
1642 f Go one heading forward on same level
1643 b Go one heading backward on same level
1644 u Go one heading up"
1645 :group 'org-edit-structure
1646 :type 'boolean)
1648 (defgroup org-sparse-trees nil
1649 "Options concerning sparse trees in Org-mode."
1650 :tag "Org Sparse Trees"
1651 :group 'org-structure)
1653 (defcustom org-highlight-sparse-tree-matches t
1654 "Non-nil means highlight all matches that define a sparse tree.
1655 The highlights will automatically disappear the next time the buffer is
1656 changed by an edit command."
1657 :group 'org-sparse-trees
1658 :type 'boolean)
1660 (defcustom org-remove-highlights-with-change t
1661 "Non-nil means any change to the buffer will remove temporary highlights.
1662 \\<org-mode-map>\
1663 Such highlights are created by `org-occur' and `org-clock-display'.
1664 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1665 to get rid of the highlights.
1666 The highlights created by `org-toggle-latex-fragment' always need
1667 `\\[org-toggle-latex-fragment]' to be removed."
1668 :group 'org-sparse-trees
1669 :group 'org-time
1670 :type 'boolean)
1672 (defcustom org-occur-case-fold-search t
1673 "Non-nil means `org-occur' should be case-insensitive.
1674 If set to `smart' the search will be case-insensitive only if it
1675 doesn't specify any upper case character."
1676 :group 'org-sparse-trees
1677 :version "25.1"
1678 :type '(choice
1679 (const :tag "Case-sensitive" nil)
1680 (const :tag "Case-insensitive" t)
1681 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1683 (defcustom org-occur-hook '(org-first-headline-recenter)
1684 "Hook that is run after `org-occur' has constructed a sparse tree.
1685 This can be used to recenter the window to show as much of the structure
1686 as possible."
1687 :group 'org-sparse-trees
1688 :type 'hook)
1690 (defgroup org-imenu-and-speedbar nil
1691 "Options concerning imenu and speedbar in Org-mode."
1692 :tag "Org Imenu and Speedbar"
1693 :group 'org-structure)
1695 (defcustom org-imenu-depth 2
1696 "The maximum level for Imenu access to Org-mode headlines.
1697 This also applied for speedbar access."
1698 :group 'org-imenu-and-speedbar
1699 :type 'integer)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org-mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-enable-table-editor 'optimized
1707 "Non-nil means lines starting with \"|\" are handled by the table editor.
1708 When nil, such lines will be treated like ordinary lines.
1710 When equal to the symbol `optimized', the table editor will be optimized to
1711 do the following:
1712 - Automatic overwrite mode in front of whitespace in table fields.
1713 This makes the structure of the table stay in tact as long as the edited
1714 field does not exceed the column width.
1715 - Minimize the number of realigns. Normally, the table is aligned each time
1716 TAB or RET are pressed to move to another field. With optimization this
1717 happens only if changes to a field might have changed the column width.
1718 Optimization requires replacing the functions `self-insert-command',
1719 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1720 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1721 very good at guessing when a re-align will be necessary, but you can always
1722 force one with \\[org-ctrl-c-ctrl-c].
1724 If you would like to use the optimized version in Org-mode, but the
1725 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1727 This variable can be used to turn on and off the table editor during a session,
1728 but in order to toggle optimization, a restart is required.
1730 See also the variable `org-table-auto-blank-field'."
1731 :group 'org-table
1732 :type '(choice
1733 (const :tag "off" nil)
1734 (const :tag "on" t)
1735 (const :tag "on, optimized" optimized)))
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org-mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-parameters
1762 '(("doi" :follow org--open-doi-link)
1763 ("elisp" :follow org--open-elisp-link)
1764 ("file" :complete org-file-complete-link)
1765 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1766 ("help" :follow org--open-help-link)
1767 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1768 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1769 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1770 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1771 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1772 ("shell" :follow org--open-shell-link))
1773 "An alist of properties that defines all the links in Org mode.
1774 The key in each association is a string of the link type.
1775 Subsequent optional elements make up a p-list of link properties.
1777 :follow - A function that takes the link path as an argument.
1779 :export - A function that takes the link path, description and
1780 export-backend as arguments.
1782 :store - A function responsible for storing the link. See the
1783 function `org-store-link-functions'.
1785 :complete - A function that inserts a link with completion. The
1786 function takes one optional prefix arg.
1788 :face - A face for the link, or a function that returns a face.
1789 The function takes one argument which is the link path. The
1790 default face is `org-link'.
1792 :mouse-face - The mouse-face. The default is `highlight'.
1794 :display - `full' will not fold the link in descriptive
1795 display. Default is `org-link'.
1797 :help-echo - A string or function that takes (window object position)
1798 as arguments and returns a string.
1800 :keymap - A keymap that is active on the link. The default is
1801 `org-mouse-map'.
1803 :htmlize-link - A function for the htmlize-link. Defaults
1804 to (list :uri \"type:path\")
1806 :activate-func - A function to run at the end of font-lock
1807 activation. The function must accept (link-start link-end path bracketp)
1808 as arguments."
1809 :group 'org-link
1810 :type '(alist :tag "Link display parameters"
1811 :value-type plist))
1813 (defun org-link-get-parameter (type key)
1814 "Get TYPE link property for KEY.
1815 TYPE is a string and KEY is a plist keyword."
1816 (plist-get
1817 (cdr (assoc type org-link-parameters))
1818 key))
1820 (defun org-link-set-parameters (type &rest parameters)
1821 "Set link TYPE properties to PARAMETERS.
1822 PARAMETERS should be :key val pairs."
1823 (let ((data (assoc type org-link-parameters)))
1824 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1825 (push (cons type parameters) org-link-parameters)
1826 (org-make-link-regexps)
1827 (org-element-update-syntax))))
1829 (defun org-link-types ()
1830 "Return a list of known link types."
1831 (mapcar #'car org-link-parameters))
1833 (defcustom org-link-abbrev-alist nil
1834 "Alist of link abbreviations.
1835 The car of each element is a string, to be replaced at the start of a link.
1836 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1837 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1839 [[linkkey:tag][description]]
1841 The `linkkey' must be a word word, starting with a letter, followed
1842 by letters, numbers, `-' or `_'.
1844 If REPLACE is a string, the tag will simply be appended to create the link.
1845 If the string contains \"%s\", the tag will be inserted there. If the string
1846 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1847 at that point (see the function `url-hexify-string'). If the string contains
1848 the specifier \"%(my-function)\", then the custom function `my-function' will
1849 be invoked: this function takes the tag as its only argument and must return
1850 a string.
1852 REPLACE may also be a function that will be called with the tag as the
1853 only argument to create the link, which should be returned as a string.
1855 See the manual for examples."
1856 :group 'org-link
1857 :type '(repeat
1858 (cons
1859 (string :tag "Protocol")
1860 (choice
1861 (string :tag "Format")
1862 (function)))))
1864 (defcustom org-descriptive-links t
1865 "Non-nil means Org will display descriptive links.
1866 E.g. [[http://orgmode.org][Org website]] will be displayed as
1867 \"Org Website\", hiding the link itself and just displaying its
1868 description. When set to nil, Org will display the full links
1869 literally.
1871 You can interactively set the value of this variable by calling
1872 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1873 :group 'org-link
1874 :type 'boolean)
1876 (defcustom org-link-file-path-type 'adaptive
1877 "How the path name in file links should be stored.
1878 Valid values are:
1880 relative Relative to the current directory, i.e. the directory of the file
1881 into which the link is being inserted.
1882 absolute Absolute path, if possible with ~ for home directory.
1883 noabbrev Absolute path, no abbreviation of home directory.
1884 adaptive Use relative path for files in the current directory and sub-
1885 directories of it. For other files, use an absolute path."
1886 :group 'org-link
1887 :type '(choice
1888 (const relative)
1889 (const absolute)
1890 (const noabbrev)
1891 (const adaptive)))
1893 (defvaralias 'org-activate-links 'org-highlight-links)
1894 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1895 "Types of links that should be highlighted in Org-mode files.
1897 This is a list of symbols, each one of them leading to the
1898 highlighting of a certain link type.
1900 You can still open links that are not highlighted.
1902 In principle, it does not hurt to turn on highlighting for all
1903 link types. There may be a small gain when turning off unused
1904 link types. The types are:
1906 bracket The recommended [[link][description]] or [[link]] links with hiding.
1907 angle Links in angular brackets that may contain whitespace like
1908 <bbdb:Carsten Dominik>.
1909 plain Plain links in normal text, no whitespace, like http://google.com.
1910 radio Text that is matched by a radio target, see manual for details.
1911 tag Tag settings in a headline (link to tag search).
1912 date Time stamps (link to calendar).
1913 footnote Footnote labels.
1915 If you set this variable during an Emacs session, use `org-mode-restart'
1916 in the Org buffer so that the change takes effect."
1917 :group 'org-link
1918 :group 'org-appearance
1919 :type '(set :greedy t
1920 (const :tag "Double bracket links" bracket)
1921 (const :tag "Angular bracket links" angle)
1922 (const :tag "Plain text links" plain)
1923 (const :tag "Radio target matches" radio)
1924 (const :tag "Tags" tag)
1925 (const :tag "Timestamps" date)
1926 (const :tag "Footnotes" footnote)))
1928 (defcustom org-make-link-description-function nil
1929 "Function to use for generating link descriptions from links.
1930 When nil, the link location will be used. This function must take
1931 two parameters: the first one is the link, the second one is the
1932 description generated by `org-insert-link'. The function should
1933 return the description to use."
1934 :group 'org-link
1935 :type '(choice (const nil) (function)))
1937 (defgroup org-link-store nil
1938 "Options concerning storing links in Org-mode."
1939 :tag "Org Store Link"
1940 :group 'org-link)
1942 (defcustom org-url-hexify-p t
1943 "When non-nil, hexify URL when creating a link."
1944 :type 'boolean
1945 :version "24.3"
1946 :group 'org-link-store)
1948 (defcustom org-email-link-description-format "Email %c: %.30s"
1949 "Format of the description part of a link to an email or usenet message.
1950 The following %-escapes will be replaced by corresponding information:
1952 %F full \"From\" field
1953 %f name, taken from \"From\" field, address if no name
1954 %T full \"To\" field
1955 %t first name in \"To\" field, address if no name
1956 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1957 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1958 %s subject
1959 %d date
1960 %m message-id.
1962 You may use normal field width specification between the % and the letter.
1963 This is for example useful to limit the length of the subject.
1965 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1966 :group 'org-link-store
1967 :type 'string)
1969 (defcustom org-from-is-user-regexp
1970 (let (r1 r2)
1971 (when (and user-mail-address (not (string= user-mail-address "")))
1972 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1973 (when (and user-full-name (not (string= user-full-name "")))
1974 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1975 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1976 "Regexp matched against the \"From:\" header of an email or usenet message.
1977 It should match if the message is from the user him/herself."
1978 :group 'org-link-store
1979 :type 'regexp)
1981 (defcustom org-context-in-file-links t
1982 "Non-nil means file links from `org-store-link' contain context.
1983 A search string will be added to the file name with :: as separator and
1984 used to find the context when the link is activated by the command
1985 `org-open-at-point'. When this option is t, the entire active region
1986 will be placed in the search string of the file link. If set to a
1987 positive integer, only the first n lines of context will be stored.
1989 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1990 negates this setting for the duration of the command."
1991 :group 'org-link-store
1992 :type '(choice boolean integer))
1994 (defcustom org-keep-stored-link-after-insertion nil
1995 "Non-nil means keep link in list for entire session.
1997 The command `org-store-link' adds a link pointing to the current
1998 location to an internal list. These links accumulate during a session.
1999 The command `org-insert-link' can be used to insert links into any
2000 Org-mode file (offering completion for all stored links). When this
2001 option is nil, every link which has been inserted once using \\[org-insert-link]
2002 will be removed from the list, to make completing the unused links
2003 more efficient."
2004 :group 'org-link-store
2005 :type 'boolean)
2007 (defgroup org-link-follow nil
2008 "Options concerning following links in Org-mode."
2009 :tag "Org Follow Link"
2010 :group 'org-link)
2012 (defcustom org-link-translation-function nil
2013 "Function to translate links with different syntax to Org syntax.
2014 This can be used to translate links created for example by the Planner
2015 or emacs-wiki packages to Org syntax.
2016 The function must accept two parameters, a TYPE containing the link
2017 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2018 which is everything after the link protocol. It should return a cons
2019 with possibly modified values of type and path.
2020 Org contains a function for this, so if you set this variable to
2021 `org-translate-link-from-planner', you should be able follow many
2022 links created by planner."
2023 :group 'org-link-follow
2024 :type '(choice (const nil) (function)))
2026 (defcustom org-follow-link-hook nil
2027 "Hook that is run after a link has been followed."
2028 :group 'org-link-follow
2029 :type 'hook)
2031 (defcustom org-tab-follows-link nil
2032 "Non-nil means on links TAB will follow the link.
2033 Needs to be set before org.el is loaded.
2034 This really should not be used, it does not make sense, and the
2035 implementation is bad."
2036 :group 'org-link-follow
2037 :type 'boolean)
2039 (defcustom org-return-follows-link nil
2040 "Non-nil means on links RET will follow the link.
2041 In tables, the special behavior of RET has precedence."
2042 :group 'org-link-follow
2043 :type 'boolean)
2045 (defcustom org-mouse-1-follows-link
2046 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2047 "Non-nil means mouse-1 on a link will follow the link.
2048 A longer mouse click will still set point. Needs to be set
2049 before org.el is loaded."
2050 :group 'org-link-follow
2051 :version "24.4"
2052 :package-version '(Org . "8.3")
2053 :type '(choice
2054 (const :tag "A double click follows the link" double)
2055 (const :tag "Unconditionally follow the link with mouse-1" t)
2056 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2058 (defcustom org-mark-ring-length 4
2059 "Number of different positions to be recorded in the ring.
2060 Changing this requires a restart of Emacs to work correctly."
2061 :group 'org-link-follow
2062 :type 'integer)
2064 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2065 "Non-nil means internal links in Org files must exactly match a headline.
2066 When nil, the link search tries to match a phrase with all words
2067 in the search text."
2068 :group 'org-link-follow
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "Use fuzzy text search" nil)
2072 (const :tag "Match only exact headline" t)
2073 (const :tag "Match exact headline or query to create it"
2074 query-to-create)))
2076 (defcustom org-link-frame-setup
2077 '((vm . vm-visit-folder-other-frame)
2078 (vm-imap . vm-visit-imap-folder-other-frame)
2079 (gnus . org-gnus-no-new-news)
2080 (file . find-file-other-window)
2081 (wl . wl-other-frame))
2082 "Setup the frame configuration for following links.
2083 When following a link with Emacs, it may often be useful to display
2084 this link in another window or frame. This variable can be used to
2085 set this up for the different types of links.
2086 For VM, use any of
2087 `vm-visit-folder'
2088 `vm-visit-folder-other-window'
2089 `vm-visit-folder-other-frame'
2090 For Gnus, use any of
2091 `gnus'
2092 `gnus-other-frame'
2093 `org-gnus-no-new-news'
2094 For FILE, use any of
2095 `find-file'
2096 `find-file-other-window'
2097 `find-file-other-frame'
2098 For Wanderlust use any of
2099 `wl'
2100 `wl-other-frame'
2101 For the calendar, use the variable `calendar-setup'.
2102 For BBDB, it is currently only possible to display the matches in
2103 another window."
2104 :group 'org-link-follow
2105 :type '(list
2106 (cons (const vm)
2107 (choice
2108 (const vm-visit-folder)
2109 (const vm-visit-folder-other-window)
2110 (const vm-visit-folder-other-frame)))
2111 (cons (const vm-imap)
2112 (choice
2113 (const vm-visit-imap-folder)
2114 (const vm-visit-imap-folder-other-window)
2115 (const vm-visit-imap-folder-other-frame)))
2116 (cons (const gnus)
2117 (choice
2118 (const gnus)
2119 (const gnus-other-frame)
2120 (const org-gnus-no-new-news)))
2121 (cons (const file)
2122 (choice
2123 (const find-file)
2124 (const find-file-other-window)
2125 (const find-file-other-frame)))
2126 (cons (const wl)
2127 (choice
2128 (const wl)
2129 (const wl-other-frame)))))
2131 (defcustom org-display-internal-link-with-indirect-buffer nil
2132 "Non-nil means use indirect buffer to display infile links.
2133 Activating internal links (from one location in a file to another location
2134 in the same file) normally just jumps to the location. When the link is
2135 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2136 is displayed in
2137 another window. When this option is set, the other window actually displays
2138 an indirect buffer clone of the current buffer, to avoid any visibility
2139 changes to the current buffer."
2140 :group 'org-link-follow
2141 :type 'boolean)
2143 (defcustom org-open-non-existing-files nil
2144 "Non-nil means `org-open-file' will open non-existing files.
2145 When nil, an error will be generated.
2146 This variable applies only to external applications because they
2147 might choke on non-existing files. If the link is to a file that
2148 will be opened in Emacs, the variable is ignored."
2149 :group 'org-link-follow
2150 :type 'boolean)
2152 (defcustom org-open-directory-means-index-dot-org nil
2153 "Non-nil means a link to a directory really means to index.org.
2154 When nil, following a directory link will run dired or open a finder/explorer
2155 window on that directory."
2156 :group 'org-link-follow
2157 :type 'boolean)
2159 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2160 "Non-nil means ask for confirmation before executing shell links.
2161 Shell links can be dangerous: just think about a link
2163 [[shell:rm -rf ~/*][Google Search]]
2165 This link would show up in your Org-mode document as \"Google Search\",
2166 but really it would remove your entire home directory.
2167 Therefore we advise against setting this variable to nil.
2168 Just change it to `y-or-n-p' if you want to confirm with a
2169 single keystroke rather than having to type \"yes\"."
2170 :group 'org-link-follow
2171 :type '(choice
2172 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2173 (const :tag "with y-or-n (faster)" y-or-n-p)
2174 (const :tag "no confirmation (dangerous)" nil)))
2175 (put 'org-confirm-shell-link-function
2176 'safe-local-variable
2177 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2179 (defcustom org-confirm-shell-link-not-regexp ""
2180 "A regexp to skip confirmation for shell links."
2181 :group 'org-link-follow
2182 :version "24.1"
2183 :type 'regexp)
2185 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2186 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2187 Elisp links can be dangerous: just think about a link
2189 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2191 This link would show up in your Org-mode document as \"Google Search\",
2192 but really it would remove your entire home directory.
2193 Therefore we advise against setting this variable to nil.
2194 Just change it to `y-or-n-p' if you want to confirm with a
2195 single keystroke rather than having to type \"yes\"."
2196 :group 'org-link-follow
2197 :type '(choice
2198 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2199 (const :tag "with y-or-n (faster)" y-or-n-p)
2200 (const :tag "no confirmation (dangerous)" nil)))
2201 (put 'org-confirm-shell-link-function
2202 'safe-local-variable
2203 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2205 (defcustom org-confirm-elisp-link-not-regexp ""
2206 "A regexp to skip confirmation for Elisp links."
2207 :group 'org-link-follow
2208 :version "24.1"
2209 :type 'regexp)
2211 (defconst org-file-apps-defaults-gnu
2212 '((remote . emacs)
2213 (system . mailcap)
2214 (t . mailcap))
2215 "Default file applications on a UNIX or GNU/Linux system.
2216 See `org-file-apps'.")
2218 (defconst org-file-apps-defaults-macosx
2219 '((remote . emacs)
2220 (system . "open %s")
2221 ("ps.gz" . "gv %s")
2222 ("eps.gz" . "gv %s")
2223 ("dvi" . "xdvi %s")
2224 ("fig" . "xfig %s")
2225 (t . "open %s"))
2226 "Default file applications on a MacOS X system.
2227 The system \"open\" is known as a default, but we use X11 applications
2228 for some files for which the OS does not have a good default.
2229 See `org-file-apps'.")
2231 (defconst org-file-apps-defaults-windowsnt
2232 (list '(remote . emacs)
2233 (cons 'system (lambda (file _path)
2234 (with-no-warnings (w32-shell-execute "open" file))))
2235 (cons t (lambda (file _path)
2236 (with-no-warnings (w32-shell-execute "open" file)))))
2237 "Default file applications on a Windows NT system.
2238 The system \"open\" is used for most files.
2239 See `org-file-apps'.")
2241 (defcustom org-file-apps
2242 '((auto-mode . emacs)
2243 ("\\.mm\\'" . default)
2244 ("\\.x?html?\\'" . default)
2245 ("\\.pdf\\'" . default))
2246 "External applications for opening `file:path' items in a document.
2247 \\<org-mode-map>\
2249 Org mode uses system defaults for different file types, but
2250 you can use this variable to set the application for a given file
2251 extension. The entries in this list are cons cells where the car identifies
2252 files and the cdr the corresponding command.
2254 Possible values for the file identifier are:
2256 \"string\" A string as a file identifier can be interpreted in different
2257 ways, depending on its contents:
2259 - Alphanumeric characters only:
2260 Match links with this file extension.
2261 Example: (\"pdf\" . \"evince %s\")
2262 to open PDFs with evince.
2264 - Regular expression: Match links where the
2265 filename matches the regexp. If you want to
2266 use groups here, use shy groups.
2268 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2269 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2270 to open *.html and *.xhtml with firefox.
2272 - Regular expression which contains (non-shy) groups:
2273 Match links where the whole link, including \"::\", and
2274 anything after that, matches the regexp.
2275 In a custom command string, %1, %2, etc. are replaced with
2276 the parts of the link that were matched by the groups.
2277 For backwards compatibility, if a command string is given
2278 that does not use any of the group matches, this case is
2279 handled identically to the second one (i.e. match against
2280 file name only).
2281 In a custom function, you can access the group matches with
2282 \(match-string n link).
2284 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2285 \"evince -p %1 %s\")
2286 to open [[file:document.pdf::5]] with evince at page 5.
2288 `directory' Matches a directory
2289 `remote' Matches a remote file, accessible through tramp or efs.
2290 Remote files most likely should be visited through Emacs
2291 because external applications cannot handle such paths.
2292 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2293 so all files Emacs knows how to handle. Using this with
2294 command `emacs' will open most files in Emacs. Beware that this
2295 will also open html files inside Emacs, unless you add
2296 \(\"html\" . default) to the list as well.
2297 `system' The system command to open files, like `open' on Windows
2298 and Mac OS X, and mailcap under GNU/Linux. This is the command
2299 that will be selected if you call \\[org-open-at-point] with a double
2300 \\[universal-argument] \\[universal-argument] prefix.
2301 t Default for files not matched by any of the other options.
2303 Possible values for the command are:
2305 `emacs' The file will be visited by the current Emacs process.
2306 `default' Use the default application for this file type, which is the
2307 association for t in the list, most likely in the system-specific
2308 part. This can be used to overrule an unwanted setting in the
2309 system-specific variable.
2310 `system' Use the system command for opening files, like \"open\".
2311 This command is specified by the entry whose car is `system'.
2312 Most likely, the system-specific version of this variable
2313 does define this command, but you can overrule/replace it
2314 here.
2315 `mailcap' Use command specified in the mailcaps.
2316 string A command to be executed by a shell; %s will be replaced
2317 by the path to the file.
2318 function A Lisp function, which will be called with two arguments:
2319 the file path and the original link string, without the
2320 \"file:\" prefix.
2322 For more examples, see the system specific constants
2323 `org-file-apps-defaults-macosx'
2324 `org-file-apps-defaults-windowsnt'
2325 `org-file-apps-defaults-gnu'."
2326 :group 'org-link-follow
2327 :type '(repeat
2328 (cons (choice :value ""
2329 (string :tag "Extension")
2330 (const :tag "System command to open files" system)
2331 (const :tag "Default for unrecognized files" t)
2332 (const :tag "Remote file" remote)
2333 (const :tag "Links to a directory" directory)
2334 (const :tag "Any files that have Emacs modes"
2335 auto-mode))
2336 (choice :value ""
2337 (const :tag "Visit with Emacs" emacs)
2338 (const :tag "Use default" default)
2339 (const :tag "Use the system command" system)
2340 (string :tag "Command")
2341 (function :tag "Function")))))
2343 (defcustom org-doi-server-url "http://dx.doi.org/"
2344 "The URL of the DOI server."
2345 :type 'string
2346 :version "24.3"
2347 :group 'org-link-follow)
2349 (defgroup org-refile nil
2350 "Options concerning refiling entries in Org-mode."
2351 :tag "Org Refile"
2352 :group 'org)
2354 (defcustom org-directory "~/org"
2355 "Directory with Org files.
2356 This is just a default location to look for Org files. There is no need
2357 at all to put your files into this directory. It is used in the
2358 following situations:
2360 1. When a capture template specifies a target file that is not an
2361 absolute path. The path will then be interpreted relative to
2362 `org-directory'
2363 2. When the value of variable `org-agenda-files' is a single file, any
2364 relative paths in this file will be taken as relative to
2365 `org-directory'."
2366 :group 'org-refile
2367 :group 'org-capture
2368 :type 'directory)
2370 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2371 "Default target for storing notes.
2372 Used as a fall back file for org-capture.el, for templates that
2373 do not specify a target file."
2374 :group 'org-refile
2375 :group 'org-capture
2376 :type 'file)
2378 (defcustom org-goto-interface 'outline
2379 "The default interface to be used for `org-goto'.
2380 Allowed values are:
2381 outline The interface shows an outline of the relevant file
2382 and the correct heading is found by moving through
2383 the outline or by searching with incremental search.
2384 outline-path-completion Headlines in the current buffer are offered via
2385 completion. This is the interface also used by
2386 the refile command."
2387 :group 'org-refile
2388 :type '(choice
2389 (const :tag "Outline" outline)
2390 (const :tag "Outline-path-completion" outline-path-completion)))
2392 (defcustom org-goto-max-level 5
2393 "Maximum target level when running `org-goto' with refile interface."
2394 :group 'org-refile
2395 :type 'integer)
2397 (defcustom org-reverse-note-order nil
2398 "Non-nil means store new notes at the beginning of a file or entry.
2399 When nil, new notes will be filed to the end of a file or entry.
2400 This can also be a list with cons cells of regular expressions that
2401 are matched against file names, and values."
2402 :group 'org-capture
2403 :group 'org-refile
2404 :type '(choice
2405 (const :tag "Reverse always" t)
2406 (const :tag "Reverse never" nil)
2407 (repeat :tag "By file name regexp"
2408 (cons regexp boolean))))
2410 (defcustom org-log-refile nil
2411 "Information to record when a task is refiled.
2413 Possible values are:
2415 nil Don't add anything
2416 time Add a time stamp to the task
2417 note Prompt for a note and add it with template `org-log-note-headings'
2419 This option can also be set with on a per-file-basis with
2421 #+STARTUP: nologrefile
2422 #+STARTUP: logrefile
2423 #+STARTUP: lognoterefile
2425 You can have local logging settings for a subtree by setting the LOGGING
2426 property to one or more of these keywords.
2428 When bulk-refiling from the agenda, the value `note' is forbidden and
2429 will temporarily be changed to `time'."
2430 :group 'org-refile
2431 :group 'org-progress
2432 :version "24.1"
2433 :type '(choice
2434 (const :tag "No logging" nil)
2435 (const :tag "Record timestamp" time)
2436 (const :tag "Record timestamp with note." note)))
2438 (defcustom org-refile-targets nil
2439 "Targets for refiling entries with \\[org-refile].
2440 This is a list of cons cells. Each cell contains:
2441 - a specification of the files to be considered, either a list of files,
2442 or a symbol whose function or variable value will be used to retrieve
2443 a file name or a list of file names. If you use `org-agenda-files' for
2444 that, all agenda files will be scanned for targets. Nil means consider
2445 headings in the current buffer.
2446 - A specification of how to find candidate refile targets. This may be
2447 any of:
2448 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2449 This tag has to be present in all target headlines, inheritance will
2450 not be considered.
2451 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2452 todo keyword.
2453 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2454 headlines that are refiling targets.
2455 - a cons cell (:level . N). Any headline of level N is considered a target.
2456 Note that, when `org-odd-levels-only' is set, level corresponds to
2457 order in hierarchy, not to the number of stars.
2458 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2459 Note that, when `org-odd-levels-only' is set, level corresponds to
2460 order in hierarchy, not to the number of stars.
2462 Each element of this list generates a set of possible targets.
2463 The union of these sets is presented (with completion) to
2464 the user by `org-refile'.
2466 You can set the variable `org-refile-target-verify-function' to a function
2467 to verify each headline found by the simple criteria above.
2469 When this variable is nil, all top-level headlines in the current buffer
2470 are used, equivalent to the value `((nil . (:level . 1))'."
2471 :group 'org-refile
2472 :type '(repeat
2473 (cons
2474 (choice :value org-agenda-files
2475 (const :tag "All agenda files" org-agenda-files)
2476 (const :tag "Current buffer" nil)
2477 (function) (variable) (file))
2478 (choice :tag "Identify target headline by"
2479 (cons :tag "Specific tag" (const :value :tag) (string))
2480 (cons :tag "TODO keyword" (const :value :todo) (string))
2481 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2482 (cons :tag "Level number" (const :value :level) (integer))
2483 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2485 (defcustom org-refile-target-verify-function nil
2486 "Function to verify if the headline at point should be a refile target.
2487 The function will be called without arguments, with point at the
2488 beginning of the headline. It should return t and leave point
2489 where it is if the headline is a valid target for refiling.
2491 If the target should not be selected, the function must return nil.
2492 In addition to this, it may move point to a place from where the search
2493 should be continued. For example, the function may decide that the entire
2494 subtree of the current entry should be excluded and move point to the end
2495 of the subtree."
2496 :group 'org-refile
2497 :type '(choice
2498 (const nil)
2499 (function)))
2501 (defcustom org-refile-use-cache nil
2502 "Non-nil means cache refile targets to speed up the process.
2503 \\<org-mode-map>\
2504 The cache for a particular file will be updated automatically when
2505 the buffer has been killed, or when any of the marker used for flagging
2506 refile targets no longer points at a live buffer.
2507 If you have added new entries to a buffer that might themselves be targets,
2508 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2509 if you find that easier, \
2510 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2511 \\[org-refile]'."
2512 :group 'org-refile
2513 :version "24.1"
2514 :type 'boolean)
2516 (defcustom org-refile-use-outline-path nil
2517 "Non-nil means provide refile targets as paths.
2518 So a level 3 headline will be available as level1/level2/level3.
2520 When the value is `file', also include the file name (without directory)
2521 into the path. In this case, you can also stop the completion after
2522 the file name, to get entries inserted as top level in the file.
2524 When `full-file-path', include the full file path."
2525 :group 'org-refile
2526 :type '(choice
2527 (const :tag "Not" nil)
2528 (const :tag "Yes" t)
2529 (const :tag "Start with file name" file)
2530 (const :tag "Start with full file path" full-file-path)))
2532 (defcustom org-outline-path-complete-in-steps t
2533 "Non-nil means complete the outline path in hierarchical steps.
2534 When Org-mode uses the refile interface to select an outline path
2535 \(see variable `org-refile-use-outline-path'), the completion of
2536 the path can be done in a single go, or it can be done in steps down
2537 the headline hierarchy. Going in steps is probably the best if you
2538 do not use a special completion package like `ido' or `icicles'.
2539 However, when using these packages, going in one step can be very
2540 fast, while still showing the whole path to the entry."
2541 :group 'org-refile
2542 :type 'boolean)
2544 (defcustom org-refile-allow-creating-parent-nodes nil
2545 "Non-nil means allow the creation of new nodes as refile targets.
2546 New nodes are then created by adding \"/new node name\" to the completion
2547 of an existing node. When the value of this variable is `confirm',
2548 new node creation must be confirmed by the user (recommended).
2549 When nil, the completion must match an existing entry.
2551 Note that, if the new heading is not seen by the criteria
2552 listed in `org-refile-targets', multiple instances of the same
2553 heading would be created by trying again to file under the new
2554 heading."
2555 :group 'org-refile
2556 :type '(choice
2557 (const :tag "Never" nil)
2558 (const :tag "Always" t)
2559 (const :tag "Prompt for confirmation" confirm)))
2561 (defcustom org-refile-active-region-within-subtree nil
2562 "Non-nil means also refile active region within a subtree.
2564 By default `org-refile' doesn't allow refiling regions if they
2565 don't contain a set of subtrees, but it might be convenient to
2566 do so sometimes: in that case, the first line of the region is
2567 converted to a headline before refiling."
2568 :group 'org-refile
2569 :version "24.1"
2570 :type 'boolean)
2572 (defgroup org-todo nil
2573 "Options concerning TODO items in Org-mode."
2574 :tag "Org TODO"
2575 :group 'org)
2577 (defgroup org-progress nil
2578 "Options concerning Progress logging in Org-mode."
2579 :tag "Org Progress"
2580 :group 'org-time)
2582 (defvar org-todo-interpretation-widgets
2583 '((:tag "Sequence (cycling hits every state)" sequence)
2584 (:tag "Type (cycling directly to DONE)" type))
2585 "The available interpretation symbols for customizing `org-todo-keywords'.
2586 Interested libraries should add to this list.")
2588 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2589 "List of TODO entry keyword sequences and their interpretation.
2590 \\<org-mode-map>This is a list of sequences.
2592 Each sequence starts with a symbol, either `sequence' or `type',
2593 indicating if the keywords should be interpreted as a sequence of
2594 action steps, or as different types of TODO items. The first
2595 keywords are states requiring action - these states will select a headline
2596 for inclusion into the global TODO list Org-mode produces. If one of
2597 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2598 signify that no further action is necessary. If \"|\" is not found,
2599 the last keyword is treated as the only DONE state of the sequence.
2601 The command \\[org-todo] cycles an entry through these states, and one
2602 additional state where no keyword is present. For details about this
2603 cycling, see the manual.
2605 TODO keywords and interpretation can also be set on a per-file basis with
2606 the special #+SEQ_TODO and #+TYP_TODO lines.
2608 Each keyword can optionally specify a character for fast state selection
2609 \(in combination with the variable `org-use-fast-todo-selection')
2610 and specifiers for state change logging, using the same syntax that
2611 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2612 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2613 indicates to record a time stamp each time this state is selected.
2615 Each keyword may also specify if a timestamp or a note should be
2616 recorded when entering or leaving the state, by adding additional
2617 characters in the parenthesis after the keyword. This looks like this:
2618 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2619 record only the time of the state change. With X and Y being either
2620 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2621 Y when leaving the state if and only if the *target* state does not
2622 define X. You may omit any of the fast-selection key or X or /Y,
2623 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2625 For backward compatibility, this variable may also be just a list
2626 of keywords. In this case the interpretation (sequence or type) will be
2627 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2628 :group 'org-todo
2629 :group 'org-keywords
2630 :type '(choice
2631 (repeat :tag "Old syntax, just keywords"
2632 (string :tag "Keyword"))
2633 (repeat :tag "New syntax"
2634 (cons
2635 (choice
2636 :tag "Interpretation"
2637 ;;Quick and dirty way to see
2638 ;;`org-todo-interpretations'. This takes the
2639 ;;place of item arguments
2640 :convert-widget
2641 (lambda (widget)
2642 (widget-put widget
2643 :args (mapcar
2644 (lambda (x)
2645 (widget-convert
2646 (cons 'const x)))
2647 org-todo-interpretation-widgets))
2648 widget))
2649 (repeat
2650 (string :tag "Keyword"))))))
2652 (defvar-local org-todo-keywords-1 nil
2653 "All TODO and DONE keywords active in a buffer.")
2654 (defvar org-todo-keywords-for-agenda nil)
2655 (defvar org-done-keywords-for-agenda nil)
2656 (defvar org-todo-keyword-alist-for-agenda nil)
2657 (defvar org-tag-alist-for-agenda nil
2658 "Alist of all tags from all agenda files.")
2659 (defvar org-tag-groups-alist-for-agenda nil
2660 "Alist of all groups tags from all current agenda files.")
2661 (defvar-local org-tag-groups-alist nil)
2662 (defvar org-agenda-contributing-files nil)
2663 (defvar-local org-current-tag-alist nil
2664 "Alist of all tag groups in current buffer.
2665 This variable takes into consideration `org-tag-alist',
2666 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2667 (defvar-local org-not-done-keywords nil)
2668 (defvar-local org-done-keywords nil)
2669 (defvar-local org-todo-heads nil)
2670 (defvar-local org-todo-sets nil)
2671 (defvar-local org-todo-log-states nil)
2672 (defvar-local org-todo-kwd-alist nil)
2673 (defvar-local org-todo-key-alist nil)
2674 (defvar-local org-todo-key-trigger nil)
2676 (defcustom org-todo-interpretation 'sequence
2677 "Controls how TODO keywords are interpreted.
2678 This variable is in principle obsolete and is only used for
2679 backward compatibility, if the interpretation of todo keywords is
2680 not given already in `org-todo-keywords'. See that variable for
2681 more information."
2682 :group 'org-todo
2683 :group 'org-keywords
2684 :type '(choice (const sequence)
2685 (const type)))
2687 (defcustom org-use-fast-todo-selection t
2688 "\\<org-mode-map>\
2689 Non-nil means use the fast todo selection scheme with \\[org-todo].
2690 This variable describes if and under what circumstances the cycling
2691 mechanism for TODO keywords will be replaced by a single-key, direct
2692 selection scheme.
2694 When nil, fast selection is never used.
2696 When the symbol `prefix', it will be used when `org-todo' is called
2697 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2698 in an Org-mode buffer, and
2699 `\\[universal-argument] t' in an agenda buffer.
2701 When t, fast selection is used by default. In this case, the prefix
2702 argument forces cycling instead.
2704 In all cases, the special interface is only used if access keys have
2705 actually been assigned by the user, i.e. if keywords in the configuration
2706 are followed by a letter in parenthesis, like TODO(t)."
2707 :group 'org-todo
2708 :type '(choice
2709 (const :tag "Never" nil)
2710 (const :tag "By default" t)
2711 (const :tag "Only with C-u C-c C-t" prefix)))
2713 (defcustom org-provide-todo-statistics t
2714 "Non-nil means update todo statistics after insert and toggle.
2715 ALL-HEADLINES means update todo statistics by including headlines
2716 with no TODO keyword as well, counting them as not done.
2717 A list of TODO keywords means the same, but skip keywords that are
2718 not in this list.
2719 When set to a list of two lists, the first list contains keywords
2720 to consider as TODO keywords, the second list contains keywords
2721 to consider as DONE keywords.
2723 When this is set, todo statistics is updated in the parent of the
2724 current entry each time a todo state is changed."
2725 :group 'org-todo
2726 :type '(choice
2727 (const :tag "Yes, only for TODO entries" t)
2728 (const :tag "Yes, including all entries" all-headlines)
2729 (repeat :tag "Yes, for TODOs in this list"
2730 (string :tag "TODO keyword"))
2731 (list :tag "Yes, for TODOs and DONEs in these lists"
2732 (repeat (string :tag "TODO keyword"))
2733 (repeat (string :tag "DONE keyword")))
2734 (other :tag "No TODO statistics" nil)))
2736 (defcustom org-hierarchical-todo-statistics t
2737 "Non-nil means TODO statistics covers just direct children.
2738 When nil, all entries in the subtree are considered.
2739 This has only an effect if `org-provide-todo-statistics' is set.
2740 To set this to nil for only a single subtree, use a COOKIE_DATA
2741 property and include the word \"recursive\" into the value."
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-after-todo-state-change-hook nil
2746 "Hook which is run after the state of a TODO item was changed.
2747 The new state (a string with a TODO keyword, or nil) is available in the
2748 Lisp variable `org-state'."
2749 :group 'org-todo
2750 :type 'hook)
2752 (defvar org-blocker-hook nil
2753 "Hook for functions that are allowed to block a state change.
2755 Functions in this hook should not modify the buffer.
2756 Each function gets as its single argument a property list,
2757 see `org-trigger-hook' for more information about this list.
2759 If any of the functions in this hook returns nil, the state change
2760 is blocked.")
2762 (defvar org-trigger-hook nil
2763 "Hook for functions that are triggered by a state change.
2765 Each function gets as its single argument a property list with at
2766 least the following elements:
2768 (:type type-of-change :position pos-at-entry-start
2769 :from old-state :to new-state)
2771 Depending on the type, more properties may be present.
2773 This mechanism is currently implemented for:
2775 TODO state changes
2776 ------------------
2777 :type todo-state-change
2778 :from previous state (keyword as a string), or nil, or a symbol
2779 `todo' or `done', to indicate the general type of state.
2780 :to new state, like in :from")
2782 (defcustom org-enforce-todo-dependencies nil
2783 "Non-nil means undone TODO entries will block switching the parent to DONE.
2784 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2785 be blocked if any prior sibling is not yet done.
2786 Finally, if the parent is blocked because of ordered siblings of its own,
2787 the child will also be blocked."
2788 :set (lambda (var val)
2789 (set var val)
2790 (if val
2791 (add-hook 'org-blocker-hook
2792 'org-block-todo-from-children-or-siblings-or-parent)
2793 (remove-hook 'org-blocker-hook
2794 'org-block-todo-from-children-or-siblings-or-parent)))
2795 :group 'org-todo
2796 :type 'boolean)
2798 (defcustom org-enforce-todo-checkbox-dependencies nil
2799 "Non-nil means unchecked boxes will block switching the parent to DONE.
2800 When this is nil, checkboxes have no influence on switching TODO states.
2801 When non-nil, you first need to check off all check boxes before the TODO
2802 entry can be switched to DONE.
2803 This variable needs to be set before org.el is loaded, and you need to
2804 restart Emacs after a change to make the change effective. The only way
2805 to change is while Emacs is running is through the customize interface."
2806 :set (lambda (var val)
2807 (set var val)
2808 (if val
2809 (add-hook 'org-blocker-hook
2810 'org-block-todo-from-checkboxes)
2811 (remove-hook 'org-blocker-hook
2812 'org-block-todo-from-checkboxes)))
2813 :group 'org-todo
2814 :type 'boolean)
2816 (defcustom org-treat-insert-todo-heading-as-state-change nil
2817 "Non-nil means inserting a TODO heading is treated as state change.
2818 So when the command \\[org-insert-todo-heading] is used, state change
2819 logging will apply if appropriate. When nil, the new TODO item will
2820 be inserted directly, and no logging will take place."
2821 :group 'org-todo
2822 :type 'boolean)
2824 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2825 "Non-nil means switching TODO states with S-cursor counts as state change.
2826 This is the default behavior. However, setting this to nil allows a
2827 convenient way to select a TODO state and bypass any logging associated
2828 with that."
2829 :group 'org-todo
2830 :type 'boolean)
2832 (defcustom org-todo-state-tags-triggers nil
2833 "Tag changes that should be triggered by TODO state changes.
2834 This is a list. Each entry is
2836 (state-change (tag . flag) .......)
2838 State-change can be a string with a state, and empty string to indicate the
2839 state that has no TODO keyword, or it can be one of the symbols `todo'
2840 or `done', meaning any not-done or done state, respectively."
2841 :group 'org-todo
2842 :group 'org-tags
2843 :type '(repeat
2844 (cons (choice :tag "When changing to"
2845 (const :tag "Not-done state" todo)
2846 (const :tag "Done state" done)
2847 (string :tag "State"))
2848 (repeat
2849 (cons :tag "Tag action"
2850 (string :tag "Tag")
2851 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2853 (defcustom org-log-done nil
2854 "Information to record when a task moves to the DONE state.
2856 Possible values are:
2858 nil Don't add anything, just change the keyword
2859 time Add a time stamp to the task
2860 note Prompt for a note and add it with template `org-log-note-headings'
2862 This option can also be set with on a per-file-basis with
2864 #+STARTUP: nologdone
2865 #+STARTUP: logdone
2866 #+STARTUP: lognotedone
2868 You can have local logging settings for a subtree by setting the LOGGING
2869 property to one or more of these keywords."
2870 :group 'org-todo
2871 :group 'org-progress
2872 :type '(choice
2873 (const :tag "No logging" nil)
2874 (const :tag "Record CLOSED timestamp" time)
2875 (const :tag "Record CLOSED timestamp with note." note)))
2877 ;; Normalize old uses of org-log-done.
2878 (cond
2879 ((eq org-log-done t) (setq org-log-done 'time))
2880 ((and (listp org-log-done) (memq 'done org-log-done))
2881 (setq org-log-done 'note)))
2883 (defcustom org-log-reschedule nil
2884 "Information to record when the scheduling date of a tasks is modified.
2886 Possible values are:
2888 nil Don't add anything, just change the date
2889 time Add a time stamp to the task
2890 note Prompt for a note and add it with template `org-log-note-headings'
2892 This option can also be set with on a per-file-basis with
2894 #+STARTUP: nologreschedule
2895 #+STARTUP: logreschedule
2896 #+STARTUP: lognotereschedule"
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type '(choice
2900 (const :tag "No logging" nil)
2901 (const :tag "Record timestamp" time)
2902 (const :tag "Record timestamp with note." note)))
2904 (defcustom org-log-redeadline nil
2905 "Information to record when the deadline date of a tasks is modified.
2907 Possible values are:
2909 nil Don't add anything, just change the date
2910 time Add a time stamp to the task
2911 note Prompt for a note and add it with template `org-log-note-headings'
2913 This option can also be set with on a per-file-basis with
2915 #+STARTUP: nologredeadline
2916 #+STARTUP: logredeadline
2917 #+STARTUP: lognoteredeadline
2919 You can have local logging settings for a subtree by setting the LOGGING
2920 property to one or more of these keywords."
2921 :group 'org-todo
2922 :group 'org-progress
2923 :type '(choice
2924 (const :tag "No logging" nil)
2925 (const :tag "Record timestamp" time)
2926 (const :tag "Record timestamp with note." note)))
2928 (defcustom org-log-note-clock-out nil
2929 "Non-nil means record a note when clocking out of an item.
2930 This can also be configured on a per-file basis by adding one of
2931 the following lines anywhere in the buffer:
2933 #+STARTUP: lognoteclock-out
2934 #+STARTUP: nolognoteclock-out"
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type 'boolean)
2939 (defcustom org-log-done-with-time t
2940 "Non-nil means the CLOSED time stamp will contain date and time.
2941 When nil, only the date will be recorded."
2942 :group 'org-progress
2943 :type 'boolean)
2945 (defcustom org-log-note-headings
2946 '((done . "CLOSING NOTE %t")
2947 (state . "State %-12s from %-12S %t")
2948 (note . "Note taken on %t")
2949 (reschedule . "Rescheduled from %S on %t")
2950 (delschedule . "Not scheduled, was %S on %t")
2951 (redeadline . "New deadline from %S on %t")
2952 (deldeadline . "Removed deadline, was %S on %t")
2953 (refile . "Refiled on %t")
2954 (clock-out . ""))
2955 "Headings for notes added to entries.
2957 The value is an alist, with the car being a symbol indicating the
2958 note context, and the cdr is the heading to be used. The heading
2959 may also be the empty string. The following placeholders can be
2960 used:
2962 %t a time stamp.
2963 %T an active time stamp instead the default inactive one
2964 %d a short-format time stamp.
2965 %D an active short-format time stamp.
2966 %s the new TODO state or time stamp (inactive), in double quotes.
2967 %S the old TODO state or time stamp (inactive), in double quotes.
2968 %u the user name.
2969 %U full user name.
2971 In fact, it is not a good idea to change the `state' entry,
2972 because Agenda Log mode depends on the format of these entries."
2973 :group 'org-todo
2974 :group 'org-progress
2975 :type '(list :greedy t
2976 (cons (const :tag "Heading when closing an item" done) string)
2977 (cons (const :tag
2978 "Heading when changing todo state (todo sequence only)"
2979 state) string)
2980 (cons (const :tag "Heading when just taking a note" note) string)
2981 (cons (const :tag "Heading when rescheduling" reschedule) string)
2982 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2983 (cons (const :tag "Heading when changing deadline" redeadline) string)
2984 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2985 (cons (const :tag "Heading when refiling" refile) string)
2986 (cons (const :tag "Heading when clocking out" clock-out) string)))
2988 (unless (assq 'note org-log-note-headings)
2989 (push '(note . "%t") org-log-note-headings))
2991 (defcustom org-log-into-drawer nil
2992 "Non-nil means insert state change notes and time stamps into a drawer.
2993 When nil, state changes notes will be inserted after the headline and
2994 any scheduling and clock lines, but not inside a drawer.
2996 The value of this variable should be the name of the drawer to use.
2997 LOGBOOK is proposed as the default drawer for this purpose, you can
2998 also set this to a string to define the drawer of your choice.
3000 A value of t is also allowed, representing \"LOGBOOK\".
3002 A value of t or nil can also be set with on a per-file-basis with
3004 #+STARTUP: logdrawer
3005 #+STARTUP: nologdrawer
3007 If this variable is set, `org-log-state-notes-insert-after-drawers'
3008 will be ignored.
3010 You can set the property LOG_INTO_DRAWER to overrule this setting for
3011 a subtree.
3013 Do not check directly this variable in a Lisp program. Call
3014 function `org-log-into-drawer' instead."
3015 :group 'org-todo
3016 :group 'org-progress
3017 :type '(choice
3018 (const :tag "Not into a drawer" nil)
3019 (const :tag "LOGBOOK" t)
3020 (string :tag "Other")))
3022 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3024 (defun org-log-into-drawer ()
3025 "Name of the log drawer, as a string, or nil.
3026 This is the value of `org-log-into-drawer'. However, if the
3027 current entry has or inherits a LOG_INTO_DRAWER property, it will
3028 be used instead of the default value."
3029 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3030 (cond ((equal p "nil") nil)
3031 ((equal p "t") "LOGBOOK")
3032 ((stringp p) p)
3033 (p "LOGBOOK")
3034 ((stringp org-log-into-drawer) org-log-into-drawer)
3035 (org-log-into-drawer "LOGBOOK"))))
3037 (defcustom org-log-state-notes-insert-after-drawers nil
3038 "Non-nil means insert state change notes after any drawers in entry.
3039 Only the drawers that *immediately* follow the headline and the
3040 deadline/scheduled line are skipped.
3041 When nil, insert notes right after the heading and perhaps the line
3042 with deadline/scheduling if present.
3044 This variable will have no effect if `org-log-into-drawer' is
3045 set."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type 'boolean)
3050 (defcustom org-log-states-order-reversed t
3051 "Non-nil means the latest state note will be directly after heading.
3052 When nil, the state change notes will be ordered according to time.
3054 This option can also be set with on a per-file-basis with
3056 #+STARTUP: logstatesreversed
3057 #+STARTUP: nologstatesreversed"
3058 :group 'org-todo
3059 :group 'org-progress
3060 :type 'boolean)
3062 (defcustom org-todo-repeat-to-state nil
3063 "The TODO state to which a repeater should return the repeating task.
3064 By default this is the first task in a TODO sequence, or the previous state
3065 in a TODO_TYP set. But you can specify another task here.
3066 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3067 :group 'org-todo
3068 :version "24.1"
3069 :type '(choice (const :tag "Head of sequence" nil)
3070 (string :tag "Specific state")))
3072 (defcustom org-log-repeat 'time
3073 "Non-nil means record moving through the DONE state when triggering repeat.
3074 An auto-repeating task is immediately switched back to TODO when
3075 marked DONE. If you are not logging state changes (by adding \"@\"
3076 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3077 record a closing note, there will be no record of the task moving
3078 through DONE. This variable forces taking a note anyway.
3080 nil Don't force a record
3081 time Record a time stamp
3082 note Prompt for a note and add it with template `org-log-note-headings'
3084 This option can also be set with on a per-file-basis with
3086 #+STARTUP: nologrepeat
3087 #+STARTUP: logrepeat
3088 #+STARTUP: lognoterepeat
3090 You can have local logging settings for a subtree by setting the LOGGING
3091 property to one or more of these keywords."
3092 :group 'org-todo
3093 :group 'org-progress
3094 :type '(choice
3095 (const :tag "Don't force a record" nil)
3096 (const :tag "Force recording the DONE state" time)
3097 (const :tag "Force recording a note with the DONE state" note)))
3100 (defgroup org-priorities nil
3101 "Priorities in Org-mode."
3102 :tag "Org Priorities"
3103 :group 'org-todo)
3105 (defcustom org-enable-priority-commands t
3106 "Non-nil means priority commands are active.
3107 When nil, these commands will be disabled, so that you never accidentally
3108 set a priority."
3109 :group 'org-priorities
3110 :type 'boolean)
3112 (defcustom org-highest-priority ?A
3113 "The highest priority of TODO items. A character like ?A, ?B etc.
3114 Must have a smaller ASCII number than `org-lowest-priority'."
3115 :group 'org-priorities
3116 :type 'character)
3118 (defcustom org-lowest-priority ?C
3119 "The lowest priority of TODO items. A character like ?A, ?B etc.
3120 Must have a larger ASCII number than `org-highest-priority'."
3121 :group 'org-priorities
3122 :type 'character)
3124 (defcustom org-default-priority ?B
3125 "The default priority of TODO items.
3126 This is the priority an item gets if no explicit priority is given.
3127 When starting to cycle on an empty priority the first step in the cycle
3128 depends on `org-priority-start-cycle-with-default'. The resulting first
3129 step priority must not exceed the range from `org-highest-priority' to
3130 `org-lowest-priority' which means that `org-default-priority' has to be
3131 in this range exclusive or inclusive the range boundaries. Else the
3132 first step refuses to set the default and the second will fall back
3133 to (depending on the command used) the highest or lowest priority."
3134 :group 'org-priorities
3135 :type 'character)
3137 (defcustom org-priority-start-cycle-with-default t
3138 "Non-nil means start with default priority when starting to cycle.
3139 When this is nil, the first step in the cycle will be (depending on the
3140 command used) one higher or lower than the default priority.
3141 See also `org-default-priority'."
3142 :group 'org-priorities
3143 :type 'boolean)
3145 (defcustom org-get-priority-function nil
3146 "Function to extract the priority from a string.
3147 The string is normally the headline. If this is nil Org computes the
3148 priority from the priority cookie like [#A] in the headline. It returns
3149 an integer, increasing by 1000 for each priority level.
3150 The user can set a different function here, which should take a string
3151 as an argument and return the numeric priority."
3152 :group 'org-priorities
3153 :version "24.1"
3154 :type '(choice
3155 (const nil)
3156 (function)))
3158 (defgroup org-time nil
3159 "Options concerning time stamps and deadlines in Org-mode."
3160 :tag "Org Time"
3161 :group 'org)
3163 (defcustom org-time-stamp-rounding-minutes '(0 5)
3164 "Number of minutes to round time stamps to.
3165 \\<org-mode-map>\
3166 These are two values, the first applies when first creating a time stamp.
3167 The second applies when changing it with the commands `S-up' and `S-down'.
3168 When changing the time stamp, this means that it will change in steps
3169 of N minutes, as given by the second value.
3171 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3172 numbers should be factors of 60, so for example 5, 10, 15.
3174 When this is larger than 1, you can still force an exact time stamp by using
3175 a double prefix argument to a time stamp command like \
3176 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3177 and by using a prefix arg to `S-up/down' to specify the exact number
3178 of minutes to shift."
3179 :group 'org-time
3180 :get (lambda (var) ; Make sure both elements are there
3181 (if (integerp (default-value var))
3182 (list (default-value var) 5)
3183 (default-value var)))
3184 :type '(list
3185 (integer :tag "when inserting times")
3186 (integer :tag "when modifying times")))
3188 ;; Normalize old customizations of this variable.
3189 (when (integerp org-time-stamp-rounding-minutes)
3190 (setq org-time-stamp-rounding-minutes
3191 (list org-time-stamp-rounding-minutes
3192 org-time-stamp-rounding-minutes)))
3194 (defcustom org-display-custom-times nil
3195 "Non-nil means overlay custom formats over all time stamps.
3196 The formats are defined through the variable `org-time-stamp-custom-formats'.
3197 To turn this on on a per-file basis, insert anywhere in the file:
3198 #+STARTUP: customtime"
3199 :group 'org-time
3200 :set 'set-default
3201 :type 'sexp)
3202 (make-variable-buffer-local 'org-display-custom-times)
3204 (defcustom org-time-stamp-custom-formats
3205 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3206 "Custom formats for time stamps. See `format-time-string' for the syntax.
3207 These are overlaid over the default ISO format if the variable
3208 `org-display-custom-times' is set. Time like %H:%M should be at the
3209 end of the second format. The custom formats are also honored by export
3210 commands, if custom time display is turned on at the time of export."
3211 :group 'org-time
3212 :type 'sexp)
3214 (defun org-time-stamp-format (&optional long inactive)
3215 "Get the right format for a time string."
3216 (let ((f (if long (cdr org-time-stamp-formats)
3217 (car org-time-stamp-formats))))
3218 (if inactive
3219 (concat "[" (substring f 1 -1) "]")
3220 f)))
3222 (defcustom org-time-clocksum-format
3223 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3224 "The format string used when creating CLOCKSUM lines.
3225 This is also used when Org mode generates a time duration.
3227 The value can be a single format string containing two
3228 %-sequences, which will be filled with the number of hours and
3229 minutes in that order.
3231 Alternatively, the value can be a plist associating any of the
3232 keys :years, :months, :weeks, :days, :hours or :minutes with
3233 format strings. The time duration is formatted using only the
3234 time components that are needed and concatenating the results.
3235 If a time unit in absent, it falls back to the next smallest
3236 unit.
3238 The keys :require-years, :require-months, :require-days,
3239 :require-weeks, :require-hours, :require-minutes are also
3240 meaningful. A non-nil value for these keys indicates that the
3241 corresponding time component should always be included, even if
3242 its value is 0.
3245 For example,
3247 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3248 :require-minutes t)
3250 means durations longer than a day will be expressed in days,
3251 hours and minutes, and durations less than a day will always be
3252 expressed in hours and minutes (even for durations less than an
3253 hour).
3255 The value
3257 (:days \"%dd\" :minutes \"%dm\")
3259 means durations longer than a day will be expressed in days and
3260 minutes, and durations less than a day will be expressed entirely
3261 in minutes (even for durations longer than an hour)."
3262 :group 'org-time
3263 :group 'org-clock
3264 :version "24.4"
3265 :package-version '(Org . "8.0")
3266 :type '(choice (string :tag "Format string")
3267 (set :tag "Plist"
3268 (group :inline t (const :tag "Years" :years)
3269 (string :tag "Format string"))
3270 (group :inline t
3271 (const :tag "Always show years" :require-years)
3272 (const t))
3273 (group :inline t (const :tag "Months" :months)
3274 (string :tag "Format string"))
3275 (group :inline t
3276 (const :tag "Always show months" :require-months)
3277 (const t))
3278 (group :inline t (const :tag "Weeks" :weeks)
3279 (string :tag "Format string"))
3280 (group :inline t
3281 (const :tag "Always show weeks" :require-weeks)
3282 (const t))
3283 (group :inline t (const :tag "Days" :days)
3284 (string :tag "Format string"))
3285 (group :inline t
3286 (const :tag "Always show days" :require-days)
3287 (const t))
3288 (group :inline t (const :tag "Hours" :hours)
3289 (string :tag "Format string"))
3290 (group :inline t
3291 (const :tag "Always show hours" :require-hours)
3292 (const t))
3293 (group :inline t (const :tag "Minutes" :minutes)
3294 (string :tag "Format string"))
3295 (group :inline t
3296 (const :tag "Always show minutes" :require-minutes)
3297 (const t)))))
3299 (defcustom org-time-clocksum-use-fractional nil
3300 "When non-nil, \\[org-clock-display] uses fractional times.
3301 See `org-time-clocksum-format' for more on time clock formats."
3302 :group 'org-time
3303 :group 'org-clock
3304 :version "24.3"
3305 :type 'boolean)
3307 (defcustom org-time-clocksum-use-effort-durations nil
3308 "When non-nil, \\[org-clock-display] uses effort durations.
3309 E.g. by default, one day is considered to be a 8 hours effort,
3310 so a task that has been clocked for 16 hours will be displayed
3311 as during 2 days in the clock display or in the clocktable.
3313 See `org-effort-durations' on how to set effort durations
3314 and `org-time-clocksum-format' for more on time clock formats."
3315 :group 'org-time
3316 :group 'org-clock
3317 :version "24.4"
3318 :package-version '(Org . "8.0")
3319 :type 'boolean)
3321 (defcustom org-time-clocksum-fractional-format "%.2f"
3322 "The format string used when creating CLOCKSUM lines,
3323 or when Org mode generates a time duration, if
3324 `org-time-clocksum-use-fractional' is enabled.
3326 The value can be a single format string containing one
3327 %-sequence, which will be filled with the number of hours as
3328 a float.
3330 Alternatively, the value can be a plist associating any of the
3331 keys :years, :months, :weeks, :days, :hours or :minutes with
3332 a format string. The time duration is formatted using the
3333 largest time unit which gives a non-zero integer part. If all
3334 specified formats have zero integer part, the smallest time unit
3335 is used."
3336 :group 'org-time
3337 :type '(choice (string :tag "Format string")
3338 (set (group :inline t (const :tag "Years" :years)
3339 (string :tag "Format string"))
3340 (group :inline t (const :tag "Months" :months)
3341 (string :tag "Format string"))
3342 (group :inline t (const :tag "Weeks" :weeks)
3343 (string :tag "Format string"))
3344 (group :inline t (const :tag "Days" :days)
3345 (string :tag "Format string"))
3346 (group :inline t (const :tag "Hours" :hours)
3347 (string :tag "Format string"))
3348 (group :inline t (const :tag "Minutes" :minutes)
3349 (string :tag "Format string")))))
3351 (defcustom org-deadline-warning-days 14
3352 "Number of days before expiration during which a deadline becomes active.
3353 This variable governs the display in sparse trees and in the agenda.
3354 When 0 or negative, it means use this number (the absolute value of it)
3355 even if a deadline has a different individual lead time specified.
3357 Custom commands can set this variable in the options section."
3358 :group 'org-time
3359 :group 'org-agenda-daily/weekly
3360 :type 'integer)
3362 (defcustom org-scheduled-delay-days 0
3363 "Number of days before a scheduled item becomes active.
3364 This variable governs the display in sparse trees and in the agenda.
3365 The default value (i.e. 0) means: don't delay scheduled item.
3366 When negative, it means use this number (the absolute value of it)
3367 even if a scheduled item has a different individual delay time
3368 specified.
3370 Custom commands can set this variable in the options section."
3371 :group 'org-time
3372 :group 'org-agenda-daily/weekly
3373 :version "24.4"
3374 :package-version '(Org . "8.0")
3375 :type 'integer)
3377 (defcustom org-read-date-prefer-future t
3378 "Non-nil means assume future for incomplete date input from user.
3379 This affects the following situations:
3380 1. The user gives a month but not a year.
3381 For example, if it is April and you enter \"feb 2\", this will be read
3382 as Feb 2, *next* year. \"May 5\", however, will be this year.
3383 2. The user gives a day, but no month.
3384 For example, if today is the 15th, and you enter \"3\", Org-mode will
3385 read this as the third of *next* month. However, if you enter \"17\",
3386 it will be considered as *this* month.
3388 If you set this variable to the symbol `time', then also the following
3389 will work:
3391 3. If the user gives a time.
3392 If the time is before now, it will be interpreted as tomorrow.
3394 Currently none of this works for ISO week specifications.
3396 When this option is nil, the current day, month and year will always be
3397 used as defaults.
3399 See also `org-agenda-jump-prefer-future'."
3400 :group 'org-time
3401 :type '(choice
3402 (const :tag "Never" nil)
3403 (const :tag "Check month and day" t)
3404 (const :tag "Check month, day, and time" time)))
3406 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3407 "Should the agenda jump command prefer the future for incomplete dates?
3408 The default is to do the same as configured in `org-read-date-prefer-future'.
3409 But you can also set a deviating value here.
3410 This may t or nil, or the symbol `org-read-date-prefer-future'."
3411 :group 'org-agenda
3412 :group 'org-time
3413 :version "24.1"
3414 :type '(choice
3415 (const :tag "Use org-read-date-prefer-future"
3416 org-read-date-prefer-future)
3417 (const :tag "Never" nil)
3418 (const :tag "Always" t)))
3420 (defcustom org-read-date-force-compatible-dates t
3421 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3423 Depending on the system Emacs is running on, certain dates cannot
3424 be represented with the type used internally to represent time.
3425 Dates between 1970-1-1 and 2038-1-1 can always be represented
3426 correctly. Some systems allow for earlier dates, some for later,
3427 some for both. One way to find out it to insert any date into an
3428 Org buffer, putting the cursor on the year and hitting S-up and
3429 S-down to test the range.
3431 When this variable is set to t, the date/time prompt will not let
3432 you specify dates outside the 1970-2037 range, so it is certain that
3433 these dates will work in whatever version of Emacs you are
3434 running, and also that you can move a file from one Emacs implementation
3435 to another. WHenever Org is forcing the year for you, it will display
3436 a message and beep.
3438 When this variable is nil, Org will check if the date is
3439 representable in the specific Emacs implementation you are using.
3440 If not, it will force a year, usually the current year, and beep
3441 to remind you. Currently this setting is not recommended because
3442 the likelihood that you will open your Org files in an Emacs that
3443 has limited date range is not negligible.
3445 A workaround for this problem is to use diary sexp dates for time
3446 stamps outside of this range."
3447 :group 'org-time
3448 :version "24.1"
3449 :type 'boolean)
3451 (defcustom org-read-date-display-live t
3452 "Non-nil means display current interpretation of date prompt live.
3453 This display will be in an overlay, in the minibuffer."
3454 :group 'org-time
3455 :type 'boolean)
3457 (defcustom org-read-date-popup-calendar t
3458 "Non-nil means pop up a calendar when prompting for a date.
3459 In the calendar, the date can be selected with mouse-1. However, the
3460 minibuffer will also be active, and you can simply enter the date as well.
3461 When nil, only the minibuffer will be available."
3462 :group 'org-time
3463 :type 'boolean)
3464 (defvaralias 'org-popup-calendar-for-date-prompt
3465 'org-read-date-popup-calendar)
3467 (defcustom org-extend-today-until 0
3468 "The hour when your day really ends. Must be an integer.
3469 This has influence for the following applications:
3470 - When switching the agenda to \"today\". It it is still earlier than
3471 the time given here, the day recognized as TODAY is actually yesterday.
3472 - When a date is read from the user and it is still before the time given
3473 here, the current date and time will be assumed to be yesterday, 23:59.
3474 Also, timestamps inserted in capture templates follow this rule.
3476 IMPORTANT: This is a feature whose implementation is and likely will
3477 remain incomplete. Really, it is only here because past midnight seems to
3478 be the favorite working time of John Wiegley :-)"
3479 :group 'org-time
3480 :type 'integer)
3482 (defcustom org-use-effective-time nil
3483 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3484 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3485 \"effective time\" of any timestamps between midnight and 8am will be
3486 23:59 of the previous day."
3487 :group 'org-time
3488 :version "24.1"
3489 :type 'boolean)
3491 (defcustom org-use-last-clock-out-time-as-effective-time nil
3492 "When non-nil, use the last clock out time for `org-todo'.
3493 Note that this option has precedence over the combined use of
3494 `org-use-effective-time' and `org-extend-today-until'."
3495 :group 'org-time
3496 :version "24.4"
3497 :package-version '(Org . "8.0")
3498 :type 'boolean)
3500 (defcustom org-edit-timestamp-down-means-later nil
3501 "Non-nil means S-down will increase the time in a time stamp.
3502 When nil, S-up will increase."
3503 :group 'org-time
3504 :type 'boolean)
3506 (defcustom org-calendar-follow-timestamp-change t
3507 "Non-nil means make the calendar window follow timestamp changes.
3508 When a timestamp is modified and the calendar window is visible, it will be
3509 moved to the new date."
3510 :group 'org-time
3511 :type 'boolean)
3513 (defgroup org-tags nil
3514 "Options concerning tags in Org-mode."
3515 :tag "Org Tags"
3516 :group 'org)
3518 (defcustom org-tag-alist nil
3519 "Default tags available in Org files.
3521 The value of this variable is an alist. Associations either:
3523 (TAG)
3524 (TAG . SELECT)
3525 (SPECIAL)
3527 where TAG is a tag as a string, SELECT is a character, used to
3528 select that tag through the fast tag selection interface, and
3529 SPECIAL is one of the following keywords: `:startgroup',
3530 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3531 `:newline'. These keywords are used to define a hierarchy of
3532 tags. See manual for details.
3534 When this variable is nil, Org mode bases tag input on what is
3535 already in the buffer. The value can be overridden locally by
3536 using a TAGS keyword, e.g.,
3538 #+TAGS: tag1 tag2
3540 See also `org-tag-persistent-alist' to sidestep this behavior."
3541 :group 'org-tags
3542 :type '(repeat
3543 (choice
3544 (cons (string :tag "Tag name")
3545 (character :tag "Access char"))
3546 (const :tag "Start radio group" (:startgroup))
3547 (const :tag "Start tag group, non distinct" (:startgrouptag))
3548 (const :tag "Group tags delimiter" (:grouptags))
3549 (const :tag "End radio group" (:endgroup))
3550 (const :tag "End tag group, non distinct" (:endgrouptag))
3551 (const :tag "New line" (:newline)))))
3553 (defcustom org-tag-persistent-alist nil
3554 "Tags always available in Org files.
3556 The value of this variable is an alist. Associations either:
3558 (TAG)
3559 (TAG . SELECT)
3560 (SPECIAL)
3562 where TAG is a tag as a string, SELECT is a character, used to
3563 select that tag through the fast tag selection interface, and
3564 SPECIAL is one of the following keywords: `:startgroup',
3565 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3566 `:newline'. These keywords are used to define a hierarchy of
3567 tags. See manual for details.
3569 Unlike to `org-tag-alist', tags defined in this variable do not
3570 depend on a local TAGS keyword. Instead, to disable these tags
3571 on a per-file basis, insert anywhere in the file:
3573 #+STARTUP: noptag"
3574 :group 'org-tags
3575 :type '(repeat
3576 (choice
3577 (cons (string :tag "Tag name")
3578 (character :tag "Access char"))
3579 (const :tag "Start radio group" (:startgroup))
3580 (const :tag "Start tag group, non distinct" (:startgrouptag))
3581 (const :tag "Group tags delimiter" (:grouptags))
3582 (const :tag "End radio group" (:endgroup))
3583 (const :tag "End tag group, non distinct" (:endgrouptag))
3584 (const :tag "New line" (:newline)))))
3586 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3587 "If non-nil, always offer completion for all tags of all agenda files.
3588 Instead of customizing this variable directly, you might want to
3589 set it locally for capture buffers, because there no list of
3590 tags in that file can be created dynamically (there are none).
3592 (add-hook \\='org-capture-mode-hook
3593 (lambda ()
3594 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3595 :group 'org-tags
3596 :version "24.1"
3597 :type 'boolean)
3599 (defvar org-file-tags nil
3600 "List of tags that can be inherited by all entries in the file.
3601 The tags will be inherited if the variable `org-use-tag-inheritance'
3602 says they should be.
3603 This variable is populated from #+FILETAGS lines.")
3605 (defcustom org-use-fast-tag-selection 'auto
3606 "Non-nil means use fast tag selection scheme.
3607 This is a special interface to select and deselect tags with single keys.
3608 When nil, fast selection is never used.
3609 When the symbol `auto', fast selection is used if and only if selection
3610 characters for tags have been configured, either through the variable
3611 `org-tag-alist' or through a #+TAGS line in the buffer.
3612 When t, fast selection is always used and selection keys are assigned
3613 automatically if necessary."
3614 :group 'org-tags
3615 :type '(choice
3616 (const :tag "Always" t)
3617 (const :tag "Never" nil)
3618 (const :tag "When selection characters are configured" auto)))
3620 (defcustom org-fast-tag-selection-single-key nil
3621 "Non-nil means fast tag selection exits after first change.
3622 When nil, you have to press RET to exit it.
3623 During fast tag selection, you can toggle this flag with `C-c'.
3624 This variable can also have the value `expert'. In this case, the window
3625 displaying the tags menu is not even shown, until you press C-c again."
3626 :group 'org-tags
3627 :type '(choice
3628 (const :tag "No" nil)
3629 (const :tag "Yes" t)
3630 (const :tag "Expert" expert)))
3632 (defvar org-fast-tag-selection-include-todo nil
3633 "Non-nil means fast tags selection interface will also offer TODO states.
3634 This is an undocumented feature, you should not rely on it.")
3636 (defcustom org-tags-column -77
3637 "The column to which tags should be indented in a headline.
3638 If this number is positive, it specifies the column. If it is negative,
3639 it means that the tags should be flushright to that column. For example,
3640 -80 works well for a normal 80 character screen.
3641 When 0, place tags directly after headline text, with only one space in
3642 between."
3643 :group 'org-tags
3644 :type 'integer)
3646 (defcustom org-auto-align-tags t
3647 "Non-nil keeps tags aligned when modifying headlines.
3648 Some operations (i.e. demoting) change the length of a headline and
3649 therefore shift the tags around. With this option turned on, after
3650 each such operation the tags are again aligned to `org-tags-column'."
3651 :group 'org-tags
3652 :type 'boolean)
3654 (defcustom org-use-tag-inheritance t
3655 "Non-nil means tags in levels apply also for sublevels.
3656 When nil, only the tags directly given in a specific line apply there.
3657 This may also be a list of tags that should be inherited, or a regexp that
3658 matches tags that should be inherited. Additional control is possible
3659 with the variable `org-tags-exclude-from-inheritance' which gives an
3660 explicit list of tags to be excluded from inheritance, even if the value of
3661 `org-use-tag-inheritance' would select it for inheritance.
3663 If this option is t, a match early-on in a tree can lead to a large
3664 number of matches in the subtree when constructing the agenda or creating
3665 a sparse tree. If you only want to see the first match in a tree during
3666 a search, check out the variable `org-tags-match-list-sublevels'."
3667 :group 'org-tags
3668 :type '(choice
3669 (const :tag "Not" nil)
3670 (const :tag "Always" t)
3671 (repeat :tag "Specific tags" (string :tag "Tag"))
3672 (regexp :tag "Tags matched by regexp")))
3674 (defcustom org-tags-exclude-from-inheritance nil
3675 "List of tags that should never be inherited.
3676 This is a way to exclude a few tags from inheritance. For way to do
3677 the opposite, to actively allow inheritance for selected tags,
3678 see the variable `org-use-tag-inheritance'."
3679 :group 'org-tags
3680 :type '(repeat (string :tag "Tag")))
3682 (defun org-tag-inherit-p (tag)
3683 "Check if TAG is one that should be inherited."
3684 (cond
3685 ((member tag org-tags-exclude-from-inheritance) nil)
3686 ((eq org-use-tag-inheritance t) t)
3687 ((not org-use-tag-inheritance) nil)
3688 ((stringp org-use-tag-inheritance)
3689 (string-match org-use-tag-inheritance tag))
3690 ((listp org-use-tag-inheritance)
3691 (member tag org-use-tag-inheritance))
3692 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3694 (defcustom org-tags-match-list-sublevels t
3695 "Non-nil means list also sublevels of headlines matching a search.
3696 This variable applies to tags/property searches, and also to stuck
3697 projects because this search is based on a tags match as well.
3699 When set to the symbol `indented', sublevels are indented with
3700 leading dots.
3702 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3703 the sublevels of a headline matching a tag search often also match
3704 the same search. Listing all of them can create very long lists.
3705 Setting this variable to nil causes subtrees of a match to be skipped.
3707 This variable is semi-obsolete and probably should always be true. It
3708 is better to limit inheritance to certain tags using the variables
3709 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3710 :group 'org-tags
3711 :type '(choice
3712 (const :tag "No, don't list them" nil)
3713 (const :tag "Yes, do list them" t)
3714 (const :tag "List them, indented with leading dots" indented)))
3716 (defcustom org-tags-sort-function nil
3717 "When set, tags are sorted using this function as a comparator."
3718 :group 'org-tags
3719 :type '(choice
3720 (const :tag "No sorting" nil)
3721 (const :tag "Alphabetical" string<)
3722 (const :tag "Reverse alphabetical" string>)
3723 (function :tag "Custom function" nil)))
3725 (defvar org-tags-history nil
3726 "History of minibuffer reads for tags.")
3727 (defvar org-last-tags-completion-table nil
3728 "The last used completion table for tags.")
3729 (defvar org-after-tags-change-hook nil
3730 "Hook that is run after the tags in a line have changed.")
3732 (defgroup org-properties nil
3733 "Options concerning properties in Org-mode."
3734 :tag "Org Properties"
3735 :group 'org)
3737 (defcustom org-property-format "%-10s %s"
3738 "How property key/value pairs should be formatted by `indent-line'.
3739 When `indent-line' hits a property definition, it will format the line
3740 according to this format, mainly to make sure that the values are
3741 lined-up with respect to each other."
3742 :group 'org-properties
3743 :type 'string)
3745 (defcustom org-properties-postprocess-alist nil
3746 "Alist of properties and functions to adjust inserted values.
3747 Elements of this alist must be of the form
3749 ([string] [function])
3751 where [string] must be a property name and [function] must be a
3752 lambda expression: this lambda expression must take one argument,
3753 the value to adjust, and return the new value as a string.
3755 For example, this element will allow the property \"Remaining\"
3756 to be updated wrt the relation between the \"Effort\" property
3757 and the clock summary:
3759 ((\"Remaining\" (lambda(value)
3760 (let ((clocksum (org-clock-sum-current-item))
3761 (effort (org-duration-string-to-minutes
3762 (org-entry-get (point) \"Effort\"))))
3763 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3764 :group 'org-properties
3765 :version "24.1"
3766 :type '(alist :key-type (string :tag "Property")
3767 :value-type (function :tag "Function")))
3769 (defcustom org-use-property-inheritance nil
3770 "Non-nil means properties apply also for sublevels.
3772 This setting is chiefly used during property searches. Turning it on can
3773 cause significant overhead when doing a search, which is why it is not
3774 on by default.
3776 When nil, only the properties directly given in the current entry count.
3777 When t, every property is inherited. The value may also be a list of
3778 properties that should have inheritance, or a regular expression matching
3779 properties that should be inherited.
3781 However, note that some special properties use inheritance under special
3782 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3783 and the properties ending in \"_ALL\" when they are used as descriptor
3784 for valid values of a property.
3786 Note for programmers:
3787 When querying an entry with `org-entry-get', you can control if inheritance
3788 should be used. By default, `org-entry-get' looks only at the local
3789 properties. You can request inheritance by setting the inherit argument
3790 to t (to force inheritance) or to `selective' (to respect the setting
3791 in this variable)."
3792 :group 'org-properties
3793 :type '(choice
3794 (const :tag "Not" nil)
3795 (const :tag "Always" t)
3796 (repeat :tag "Specific properties" (string :tag "Property"))
3797 (regexp :tag "Properties matched by regexp")))
3799 (defun org-property-inherit-p (property)
3800 "Check if PROPERTY is one that should be inherited."
3801 (cond
3802 ((eq org-use-property-inheritance t) t)
3803 ((not org-use-property-inheritance) nil)
3804 ((stringp org-use-property-inheritance)
3805 (string-match org-use-property-inheritance property))
3806 ((listp org-use-property-inheritance)
3807 (member property org-use-property-inheritance))
3808 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3810 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3811 "The default column format, if no other format has been defined.
3812 This variable can be set on the per-file basis by inserting a line
3814 #+COLUMNS: %25ITEM ....."
3815 :group 'org-properties
3816 :type 'string)
3818 (defcustom org-columns-ellipses ".."
3819 "The ellipses to be used when a field in column view is truncated.
3820 When this is the empty string, as many characters as possible are shown,
3821 but then there will be no visual indication that the field has been truncated.
3822 When this is a string of length N, the last N characters of a truncated
3823 field are replaced by this string. If the column is narrower than the
3824 ellipses string, only part of the ellipses string will be shown."
3825 :group 'org-properties
3826 :type 'string)
3828 (defconst org-global-properties-fixed
3829 '(("VISIBILITY_ALL" . "folded children content all")
3830 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3831 "List of property/value pairs that can be inherited by any entry.
3833 These are fixed values, for the preset properties. The user variable
3834 that can be used to add to this list is `org-global-properties'.
3836 The entries in this list are cons cells where the car is a property
3837 name and cdr is a string with the value. If the value represents
3838 multiple items like an \"_ALL\" property, separate the items by
3839 spaces.")
3841 (defcustom org-global-properties nil
3842 "List of property/value pairs that can be inherited by any entry.
3844 This list will be combined with the constant `org-global-properties-fixed'.
3846 The entries in this list are cons cells where the car is a property
3847 name and cdr is a string with the value.
3849 You can set buffer-local values for the same purpose in the variable
3850 `org-file-properties' this by adding lines like
3852 #+PROPERTY: NAME VALUE"
3853 :group 'org-properties
3854 :type '(repeat
3855 (cons (string :tag "Property")
3856 (string :tag "Value"))))
3858 (defvar-local org-file-properties nil
3859 "List of property/value pairs that can be inherited by any entry.
3860 Valid for the current buffer.
3861 This variable is populated from #+PROPERTY lines.")
3863 (defgroup org-agenda nil
3864 "Options concerning agenda views in Org-mode."
3865 :tag "Org Agenda"
3866 :group 'org)
3868 (defvar-local org-category nil
3869 "Variable used by org files to set a category for agenda display.
3870 Such files should use a file variable to set it, for example
3872 # -*- mode: org; org-category: \"ELisp\"
3874 or contain a special line
3876 #+CATEGORY: ELisp
3878 If the file does not specify a category, then file's base name
3879 is used instead.")
3880 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3882 (defcustom org-agenda-files nil
3883 "The files to be used for agenda display.
3884 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3885 \\[org-remove-file]. You can also use customize to edit the list.
3887 If an entry is a directory, all files in that directory that are matched by
3888 `org-agenda-file-regexp' will be part of the file list.
3890 If the value of the variable is not a list but a single file name, then
3891 the list of agenda files is actually stored and maintained in that file, one
3892 agenda file per line. In this file paths can be given relative to
3893 `org-directory'. Tilde expansion and environment variable substitution
3894 are also made."
3895 :group 'org-agenda
3896 :type '(choice
3897 (repeat :tag "List of files and directories" file)
3898 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3900 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3901 "Regular expression to match files for `org-agenda-files'.
3902 If any element in the list in that variable contains a directory instead
3903 of a normal file, all files in that directory that are matched by this
3904 regular expression will be included."
3905 :group 'org-agenda
3906 :type 'regexp)
3908 (defcustom org-agenda-text-search-extra-files nil
3909 "List of extra files to be searched by text search commands.
3910 These files will be searched in addition to the agenda files by the
3911 commands `org-search-view' (`\\[org-agenda] s') \
3912 and `org-occur-in-agenda-files'.
3913 Note that these files will only be searched for text search commands,
3914 not for the other agenda views like todo lists, tag searches or the weekly
3915 agenda. This variable is intended to list notes and possibly archive files
3916 that should also be searched by these two commands.
3917 In fact, if the first element in the list is the symbol `agenda-archives',
3918 then all archive files of all agenda files will be added to the search
3919 scope."
3920 :group 'org-agenda
3921 :type '(set :greedy t
3922 (const :tag "Agenda Archives" agenda-archives)
3923 (repeat :inline t (file))))
3925 (defvaralias 'org-agenda-multi-occur-extra-files
3926 'org-agenda-text-search-extra-files)
3928 (defcustom org-agenda-skip-unavailable-files nil
3929 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3930 A nil value means to remove them, after a query, from the list."
3931 :group 'org-agenda
3932 :type 'boolean)
3934 (defcustom org-calendar-to-agenda-key [?c]
3935 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3936 The command `org-calendar-goto-agenda' will be bound to this key. The
3937 default is the character `c' because then `c' can be used to switch back and
3938 forth between agenda and calendar."
3939 :group 'org-agenda
3940 :type 'sexp)
3942 (defcustom org-calendar-insert-diary-entry-key [?i]
3943 "The key to be installed in `calendar-mode-map' for adding diary entries.
3944 This option is irrelevant until `org-agenda-diary-file' has been configured
3945 to point to an Org-mode file. When that is the case, the command
3946 `org-agenda-diary-entry' will be bound to the key given here, by default
3947 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3948 if you want to continue doing this, you need to change this to a different
3949 key."
3950 :group 'org-agenda
3951 :type 'sexp)
3953 (defcustom org-agenda-diary-file 'diary-file
3954 "File to which to add new entries with the `i' key in agenda and calendar.
3955 When this is the symbol `diary-file', the functionality in the Emacs
3956 calendar will be used to add entries to the `diary-file'. But when this
3957 points to a file, `org-agenda-diary-entry' will be used instead."
3958 :group 'org-agenda
3959 :type '(choice
3960 (const :tag "The standard Emacs diary file" diary-file)
3961 (file :tag "Special Org file diary entries")))
3963 (eval-after-load "calendar"
3964 '(progn
3965 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3966 'org-calendar-goto-agenda)
3967 (add-hook 'calendar-mode-hook
3968 (lambda ()
3969 (unless (eq org-agenda-diary-file 'diary-file)
3970 (define-key calendar-mode-map
3971 org-calendar-insert-diary-entry-key
3972 'org-agenda-diary-entry))))))
3974 (defgroup org-latex nil
3975 "Options for embedding LaTeX code into Org-mode."
3976 :tag "Org LaTeX"
3977 :group 'org)
3979 (defcustom org-format-latex-options
3980 '(:foreground default :background default :scale 1.0
3981 :html-foreground "Black" :html-background "Transparent"
3982 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3983 "Options for creating images from LaTeX fragments.
3984 This is a property list with the following properties:
3985 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3986 `default' means use the foreground of the default face.
3987 `auto' means use the foreground from the text face.
3988 :background the background color, or \"Transparent\".
3989 `default' means use the background of the default face.
3990 `auto' means use the background from the text face.
3991 :scale a scaling factor for the size of the images, to get more pixels
3992 :html-foreground, :html-background, :html-scale
3993 the same numbers for HTML export.
3994 :matchers a list indicating which matchers should be used to
3995 find LaTeX fragments. Valid members of this list are:
3996 \"begin\" find environments
3997 \"$1\" find single characters surrounded by $.$
3998 \"$\" find math expressions surrounded by $...$
3999 \"$$\" find math expressions surrounded by $$....$$
4000 \"\\(\" find math expressions surrounded by \\(...\\)
4001 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4002 :group 'org-latex
4003 :type 'plist)
4005 (defcustom org-format-latex-signal-error t
4006 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4007 When nil, just push out a message."
4008 :group 'org-latex
4009 :version "24.1"
4010 :type 'boolean)
4012 (defcustom org-latex-to-mathml-jar-file nil
4013 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4014 Use this to specify additional executable file say a jar file.
4016 When using MathToWeb as the converter, specify the full-path to
4017 your mathtoweb.jar file."
4018 :group 'org-latex
4019 :version "24.1"
4020 :type '(choice
4021 (const :tag "None" nil)
4022 (file :tag "JAR file" :must-match t)))
4024 (defcustom org-latex-to-mathml-convert-command nil
4025 "Command to convert LaTeX fragments to MathML.
4026 Replace format-specifiers in the command as noted below and use
4027 `shell-command' to convert LaTeX to MathML.
4028 %j: Executable file in fully expanded form as specified by
4029 `org-latex-to-mathml-jar-file'.
4030 %I: Input LaTeX file in fully expanded form.
4031 %i: The latex fragment to be converted.
4032 %o: Output MathML file.
4034 This command is used by `org-create-math-formula'.
4036 When using MathToWeb as the converter, set this option to
4037 \"java -jar %j -unicode -force -df %o %I\".
4039 When using LaTeXML set this option to
4040 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type '(choice
4044 (const :tag "None" nil)
4045 (string :tag "\nShell command")))
4047 (defcustom org-preview-latex-default-process 'dvipng
4048 "The default process to convert LaTeX fragments to image files.
4049 All available processes and theirs documents can be found in
4050 `org-preview-latex-process-alist', which see."
4051 :group 'org-latex
4052 :version "25.2"
4053 :package-version '(Org . "9.0")
4054 :type 'symbol)
4056 (defcustom org-preview-latex-process-alist
4057 '((dvipng
4058 :programs ("latex" "dvipng" "gs")
4059 :description "dvi > png"
4060 :message "you need to install the programs: latex, dvipng and ghostscript."
4061 :image-input-type "dvi"
4062 :image-output-type "png"
4063 :image-size-adjust (1.0 . 1.0)
4064 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4065 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4066 (dvisvgm
4067 :programs ("latex" "dvisvgm" "gs")
4068 :description "dvi > svg"
4069 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4070 :use-xcolor t
4071 :image-input-type "dvi"
4072 :image-output-type "svg"
4073 :image-size-adjust (1.7 . 1.5)
4074 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4075 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4076 (imagemagick
4077 :programs ("latex" "convert" "gs")
4078 :description "pdf > png"
4079 :message
4080 "you need to install the programs: latex, imagemagick and ghostscript."
4081 :use-xcolor t
4082 :image-input-type "pdf"
4083 :image-output-type "png"
4084 :image-size-adjust (1.0 . 1.0)
4085 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4086 :image-converter
4087 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4088 "Definitions of external processes for LaTeX previewing.
4089 Org mode can use some external commands to generate TeX snippet's images for
4090 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4091 `org-create-formula-image' how to call them.
4093 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4094 PROPERTIES accepts the following attributes:
4096 :programs list of strings, required programs.
4097 :description string, describe the process.
4098 :message string, message it when required programs cannot be found.
4099 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4100 :image-output-type string, output file type of image converter (e.g., \"png\").
4101 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4102 deal with background and foreground color of image.
4103 Otherwise, dvipng style background and foregroud color
4104 format are generated. You may then refer to them in
4105 command options with \"%F\" and \"%B\".
4106 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4107 image size showed in buffer and the cdr element is for
4108 HTML file. This option is only useful for process
4109 developers, users should use variable
4110 `org-format-latex-options' instead.
4111 :post-clean list of strings, files matched are to be cleaned up once
4112 the image is generated. When nil, the files with \".dvi\",
4113 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4114 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4115 be cleaned up.
4116 :latex-header list of strings, the LaTeX header of the snippet file.
4117 When nil, the fallback value is used instead, which is
4118 controlled by `org-format-latex-header',
4119 `org-latex-default-packages-alist' and
4120 `org-latex-packages-alist', which see.
4121 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4122 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4123 replaced with values defined below.
4124 :image-converter list of image converter commands strings. Each of them is
4125 given to the shell and supports any of the following
4126 place-holders defined below.
4128 Place-holders used by `:image-converter' and `:latex-compiler':
4130 %f input file name.
4131 %b base name of input file.
4132 %o base directory of input file.
4134 Place-holders only used by `:image-converter':
4136 %F foreground of image
4137 %B background of image
4138 %D dpi, which is used to adjust image size by some processing commands.
4139 %S the image size scale ratio, which is used to adjust image size by some
4140 processing commands."
4141 :group 'org-latex
4142 :version "25.2"
4143 :package-version '(Org . "9.0")
4144 :type '(alist :tag "LaTeX to image backends"
4145 :value-type (plist)))
4147 (defcustom org-preview-latex-image-directory "ltximg/"
4148 "Path to store latex preview images.
4149 A relative path here creates many directories relative to the
4150 processed org files paths. An absolute path puts all preview
4151 images at the same place."
4152 :group 'org-latex
4153 :version "25.1"
4154 :package-version '(Org . "9.0")
4155 :type 'string)
4157 (defun org-format-latex-mathml-available-p ()
4158 "Return t if `org-latex-to-mathml-convert-command' is usable."
4159 (save-match-data
4160 (when (and (boundp 'org-latex-to-mathml-convert-command)
4161 org-latex-to-mathml-convert-command)
4162 (let ((executable (car (split-string
4163 org-latex-to-mathml-convert-command))))
4164 (when (executable-find executable)
4165 (if (string-match
4166 "%j" org-latex-to-mathml-convert-command)
4167 (file-readable-p org-latex-to-mathml-jar-file)
4168 t))))))
4170 (defcustom org-format-latex-header "\\documentclass{article}
4171 \\usepackage[usenames]{color}
4172 \[PACKAGES]
4173 \[DEFAULT-PACKAGES]
4174 \\pagestyle{empty} % do not remove
4175 % The settings below are copied from fullpage.sty
4176 \\setlength{\\textwidth}{\\paperwidth}
4177 \\addtolength{\\textwidth}{-3cm}
4178 \\setlength{\\oddsidemargin}{1.5cm}
4179 \\addtolength{\\oddsidemargin}{-2.54cm}
4180 \\setlength{\\evensidemargin}{\\oddsidemargin}
4181 \\setlength{\\textheight}{\\paperheight}
4182 \\addtolength{\\textheight}{-\\headheight}
4183 \\addtolength{\\textheight}{-\\headsep}
4184 \\addtolength{\\textheight}{-\\footskip}
4185 \\addtolength{\\textheight}{-3cm}
4186 \\setlength{\\topmargin}{1.5cm}
4187 \\addtolength{\\topmargin}{-2.54cm}"
4188 "The document header used for processing LaTeX fragments.
4189 It is imperative that this header make sure that no page number
4190 appears on the page. The package defined in the variables
4191 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4192 will either replace the placeholder \"[PACKAGES]\" in this
4193 header, or they will be appended."
4194 :group 'org-latex
4195 :type 'string)
4197 (defun org-set-packages-alist (var val)
4198 "Set the packages alist and make sure it has 3 elements per entry."
4199 (set var (mapcar (lambda (x)
4200 (if (and (consp x) (= (length x) 2))
4201 (list (car x) (nth 1 x) t)
4203 val)))
4205 (defun org-get-packages-alist (var)
4206 "Get the packages alist and make sure it has 3 elements per entry."
4207 (mapcar (lambda (x)
4208 (if (and (consp x) (= (length x) 2))
4209 (list (car x) (nth 1 x) t)
4211 (default-value var)))
4213 (defcustom org-latex-default-packages-alist
4214 '(("AUTO" "inputenc" t ("pdflatex"))
4215 ("T1" "fontenc" t ("pdflatex"))
4216 ("" "graphicx" t)
4217 ("" "grffile" t)
4218 ("" "longtable" nil)
4219 ("" "wrapfig" nil)
4220 ("" "rotating" nil)
4221 ("normalem" "ulem" t)
4222 ("" "amsmath" t)
4223 ("" "textcomp" t)
4224 ("" "amssymb" t)
4225 ("" "capt-of" nil)
4226 ("" "hyperref" nil))
4227 "Alist of default packages to be inserted in the header.
4229 Change this only if one of the packages here causes an
4230 incompatibility with another package you are using.
4232 The packages in this list are needed by one part or another of
4233 Org mode to function properly:
4235 - inputenc, fontenc: for basic font and character selection
4236 - graphicx: for including images
4237 - grffile: allow periods and spaces in graphics file names
4238 - longtable: For multipage tables
4239 - wrapfig: for figure placement
4240 - rotating: for sideways figures and tables
4241 - ulem: for underline and strike-through
4242 - amsmath: for subscript and superscript and math environments
4243 - textcomp, amssymb: for various symbols used
4244 for interpreting the entities in `org-entities'. You can skip
4245 some of these packages if you don't use any of their symbols.
4246 - capt-of: for captions outside of floats
4247 - hyperref: for cross references
4249 Therefore you should not modify this variable unless you know
4250 what you are doing. The one reason to change it anyway is that
4251 you might be loading some other package that conflicts with one
4252 of the default packages. Each element is either a cell or
4253 a string.
4255 A cell is of the format
4257 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4259 If SNIPPET-FLAG is non-nil, the package also needs to be included
4260 when compiling LaTeX snippets into images for inclusion into
4261 non-LaTeX output. COMPILERS is a list of compilers that should
4262 include the package, see `org-latex-compiler'. If the document
4263 compiler is not in the list, and the list is non-nil, the package
4264 will not be inserted in the final document.
4266 A string will be inserted as-is in the header of the document."
4267 :group 'org-latex
4268 :group 'org-export-latex
4269 :set 'org-set-packages-alist
4270 :get 'org-get-packages-alist
4271 :version "25.1"
4272 :package-version '(Org . "8.3")
4273 :type '(repeat
4274 (choice
4275 (list :tag "options/package pair"
4276 (string :tag "options")
4277 (string :tag "package")
4278 (boolean :tag "Snippet"))
4279 (string :tag "A line of LaTeX"))))
4281 (defcustom org-latex-packages-alist nil
4282 "Alist of packages to be inserted in every LaTeX header.
4284 These will be inserted after `org-latex-default-packages-alist'.
4285 Each element is either a cell or a string.
4287 A cell is of the format:
4289 (\"options\" \"package\" SNIPPET-FLAG)
4291 SNIPPET-FLAG, when non-nil, indicates that this package is also
4292 needed when turning LaTeX snippets into images for inclusion into
4293 non-LaTeX output.
4295 A string will be inserted as-is in the header of the document.
4297 Make sure that you only list packages here which:
4299 - you want in every file;
4300 - do not conflict with the setup in `org-format-latex-header';
4301 - do not conflict with the default packages in
4302 `org-latex-default-packages-alist'."
4303 :group 'org-latex
4304 :group 'org-export-latex
4305 :set 'org-set-packages-alist
4306 :get 'org-get-packages-alist
4307 :type '(repeat
4308 (choice
4309 (list :tag "options/package pair"
4310 (string :tag "options")
4311 (string :tag "package")
4312 (boolean :tag "Snippet"))
4313 (string :tag "A line of LaTeX"))))
4315 (defgroup org-appearance nil
4316 "Settings for Org-mode appearance."
4317 :tag "Org Appearance"
4318 :group 'org)
4320 (defcustom org-level-color-stars-only nil
4321 "Non-nil means fontify only the stars in each headline.
4322 When nil, the entire headline is fontified.
4323 Changing it requires restart of `font-lock-mode' to become effective
4324 also in regions already fontified."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-hide-leading-stars nil
4329 "Non-nil means hide the first N-1 stars in a headline.
4330 This works by using the face `org-hide' for these stars. This
4331 face is white for a light background, and black for a dark
4332 background. You may have to customize the face `org-hide' to
4333 make this work.
4334 Changing it requires restart of `font-lock-mode' to become effective
4335 also in regions already fontified.
4336 You may also set this on a per-file basis by adding one of the following
4337 lines to the buffer:
4339 #+STARTUP: hidestars
4340 #+STARTUP: showstars"
4341 :group 'org-appearance
4342 :type 'boolean)
4344 (defcustom org-hidden-keywords nil
4345 "List of symbols corresponding to keywords to be hidden the org buffer.
4346 For example, a value \\='(title) for this list will make the document's title
4347 appear in the buffer without the initial #+TITLE: keyword."
4348 :group 'org-appearance
4349 :version "24.1"
4350 :type '(set (const :tag "#+AUTHOR" author)
4351 (const :tag "#+DATE" date)
4352 (const :tag "#+EMAIL" email)
4353 (const :tag "#+TITLE" title)))
4355 (defcustom org-custom-properties nil
4356 "List of properties (as strings) with a special meaning.
4357 The default use of these custom properties is to let the user
4358 hide them with `org-toggle-custom-properties-visibility'."
4359 :group 'org-properties
4360 :group 'org-appearance
4361 :version "24.3"
4362 :type '(repeat (string :tag "Property Name")))
4364 (defcustom org-fontify-done-headline nil
4365 "Non-nil means change the face of a headline if it is marked DONE.
4366 Normally, only the TODO/DONE keyword indicates the state of a headline.
4367 When this is non-nil, the headline after the keyword is set to the
4368 `org-headline-done' as an additional indication."
4369 :group 'org-appearance
4370 :type 'boolean)
4372 (defcustom org-fontify-emphasized-text t
4373 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4374 Changing this variable requires a restart of Emacs to take effect."
4375 :group 'org-appearance
4376 :type 'boolean)
4378 (defcustom org-fontify-whole-heading-line nil
4379 "Non-nil means fontify the whole line for headings.
4380 This is useful when setting a background color for the
4381 org-level-* faces."
4382 :group 'org-appearance
4383 :type 'boolean)
4385 (defcustom org-highlight-latex-and-related nil
4386 "Non-nil means highlight LaTeX related syntax in the buffer.
4387 When non nil, the value should be a list containing any of the
4388 following symbols:
4389 `latex' Highlight LaTeX snippets and environments.
4390 `script' Highlight subscript and superscript.
4391 `entities' Highlight entities."
4392 :group 'org-appearance
4393 :version "24.4"
4394 :package-version '(Org . "8.0")
4395 :type '(choice
4396 (const :tag "No highlighting" nil)
4397 (set :greedy t :tag "Highlight"
4398 (const :tag "LaTeX snippets and environments" latex)
4399 (const :tag "Subscript and superscript" script)
4400 (const :tag "Entities" entities))))
4402 (defcustom org-hide-emphasis-markers nil
4403 "Non-nil mean font-lock should hide the emphasis marker characters."
4404 :group 'org-appearance
4405 :type 'boolean)
4407 (defcustom org-hide-macro-markers nil
4408 "Non-nil mean font-lock should hide the brackets marking macro calls."
4409 :group 'org-appearance
4410 :type 'boolean)
4412 (defcustom org-pretty-entities nil
4413 "Non-nil means show entities as UTF8 characters.
4414 When nil, the \\name form remains in the buffer."
4415 :group 'org-appearance
4416 :version "24.1"
4417 :type 'boolean)
4419 (defcustom org-pretty-entities-include-sub-superscripts t
4420 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4421 :group 'org-appearance
4422 :version "24.1"
4423 :type 'boolean)
4425 (defvar org-emph-re nil
4426 "Regular expression for matching emphasis.
4427 After a match, the match groups contain these elements:
4428 0 The match of the full regular expression, including the characters
4429 before and after the proper match
4430 1 The character before the proper match, or empty at beginning of line
4431 2 The proper match, including the leading and trailing markers
4432 3 The leading marker like * or /, indicating the type of highlighting
4433 4 The text between the emphasis markers, not including the markers
4434 5 The character after the match, empty at the end of a line")
4435 (defvar org-verbatim-re nil
4436 "Regular expression for matching verbatim text.")
4437 (defvar org-emphasis-regexp-components) ; defined just below
4438 (defvar org-emphasis-alist) ; defined just below
4439 (defun org-set-emph-re (var val)
4440 "Set variable and compute the emphasis regular expression."
4441 (set var val)
4442 (when (and (boundp 'org-emphasis-alist)
4443 (boundp 'org-emphasis-regexp-components)
4444 org-emphasis-alist org-emphasis-regexp-components)
4445 (let* ((e org-emphasis-regexp-components)
4446 (pre (car e))
4447 (post (nth 1 e))
4448 (border (nth 2 e))
4449 (body (nth 3 e))
4450 (nl (nth 4 e))
4451 (body1 (concat body "*?"))
4452 (markers (mapconcat 'car org-emphasis-alist ""))
4453 (vmarkers (mapconcat
4454 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4455 org-emphasis-alist "")))
4456 ;; make sure special characters appear at the right position in the class
4457 (if (string-match "\\^" markers)
4458 (setq markers (concat (replace-match "" t t markers) "^")))
4459 (if (string-match "-" markers)
4460 (setq markers (concat (replace-match "" t t markers) "-")))
4461 (if (string-match "\\^" vmarkers)
4462 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4463 (if (string-match "-" vmarkers)
4464 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4465 (if (> nl 0)
4466 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4467 (int-to-string nl) "\\}")))
4468 ;; Make the regexp
4469 (setq org-emph-re
4470 (concat "\\([" pre "]\\|^\\)"
4471 "\\("
4472 "\\([" markers "]\\)"
4473 "\\("
4474 "[^" border "]\\|"
4475 "[^" border "]"
4476 body1
4477 "[^" border "]"
4478 "\\)"
4479 "\\3\\)"
4480 "\\([" post "]\\|$\\)"))
4481 (setq org-verbatim-re
4482 (concat "\\([" pre "]\\|^\\)"
4483 "\\("
4484 "\\([" vmarkers "]\\)"
4485 "\\("
4486 "[^" border "]\\|"
4487 "[^" border "]"
4488 body1
4489 "[^" border "]"
4490 "\\)"
4491 "\\3\\)"
4492 "\\([" post "]\\|$\\)")))))
4494 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4495 ;; set this option proved cumbersome. See this message/thread:
4496 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4497 (defvar org-emphasis-regexp-components
4498 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4499 "Components used to build the regular expression for emphasis.
4500 This is a list with five entries. Terminology: In an emphasis string
4501 like \" *strong word* \", we call the initial space PREMATCH, the final
4502 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4503 and \"trong wor\" is the body. The different components in this variable
4504 specify what is allowed/forbidden in each part:
4506 pre Chars allowed as prematch. Beginning of line will be allowed too.
4507 post Chars allowed as postmatch. End of line will be allowed too.
4508 border The chars *forbidden* as border characters.
4509 body-regexp A regexp like \".\" to match a body character. Don't use
4510 non-shy groups here, and don't allow newline here.
4511 newline The maximum number of newlines allowed in an emphasis exp.
4513 You need to reload Org or to restart Emacs after customizing this.")
4515 (defcustom org-emphasis-alist
4516 '(("*" bold)
4517 ("/" italic)
4518 ("_" underline)
4519 ("=" org-verbatim verbatim)
4520 ("~" org-code verbatim)
4521 ("+" (:strike-through t)))
4522 "Alist of characters and faces to emphasize text.
4523 Text starting and ending with a special character will be emphasized,
4524 for example *bold*, _underlined_ and /italic/. This variable sets the
4525 marker characters and the face to be used by font-lock for highlighting
4526 in Org-mode Emacs buffers.
4528 You need to reload Org or to restart Emacs after customizing this."
4529 :group 'org-appearance
4530 :set 'org-set-emph-re
4531 :version "24.4"
4532 :package-version '(Org . "8.0")
4533 :type '(repeat
4534 (list
4535 (string :tag "Marker character")
4536 (choice
4537 (face :tag "Font-lock-face")
4538 (plist :tag "Face property list"))
4539 (option (const verbatim)))))
4541 (defvar org-protecting-blocks '("src" "example" "export")
4542 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4543 This is needed for font-lock setup.")
4545 ;;; Functions and variables from their packages
4546 ;; Declared here to avoid compiler warnings
4547 (defvar mark-active)
4549 ;; Various packages
4550 (declare-function calc-eval "calc" (str &optional separator &rest args))
4551 (declare-function calendar-forward-day "cal-move" (arg))
4552 (declare-function calendar-goto-date "cal-move" (date))
4553 (declare-function calendar-goto-today "cal-move" ())
4554 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4555 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4556 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4557 (declare-function cdlatex-tab "ext:cdlatex" ())
4558 (declare-function dired-get-filename
4559 "dired"
4560 (&optional localp no-error-if-not-filep))
4561 (declare-function iswitchb-read-buffer
4562 "iswitchb"
4563 (prompt &optional
4564 default require-match _predicate start matches-set))
4565 (declare-function org-agenda-change-all-lines
4566 "org-agenda"
4567 (newhead hdmarker &optional fixface just-this))
4568 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4569 "org-agenda"
4570 (&optional end))
4571 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4572 (declare-function org-agenda-format-item
4573 "org-agenda"
4574 (extra txt &optional level category tags dotime
4575 remove-re habitp))
4576 (declare-function org-agenda-maybe-redo "org-agenda" ())
4577 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4578 (declare-function org-agenda-save-markers-for-cut-and-paste
4579 "org-agenda"
4580 (beg end))
4581 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4582 (declare-function org-agenda-skip "org-agenda" ())
4583 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4584 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4585 (declare-function org-indent-mode "org-indent" (&optional arg))
4586 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4587 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4588 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4589 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4590 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4591 (declare-function parse-time-string "parse-time" (string))
4592 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4593 (declare-function table--at-cell-p
4594 "table"
4595 (position &optional object at-column))
4597 (defvar align-mode-rules-list)
4598 (defvar calc-embedded-close-formula)
4599 (defvar calc-embedded-open-formula)
4600 (defvar calc-embedded-open-mode)
4601 (defvar font-lock-unfontify-region-function)
4602 (defvar iswitchb-temp-buflist)
4603 (defvar org-agenda-tags-todo-honor-ignore-options)
4604 (defvar remember-data-file)
4605 (defvar texmathp-why)
4607 ;;;###autoload
4608 (defun turn-on-orgtbl ()
4609 "Unconditionally turn on `orgtbl-mode'."
4610 (require 'org-table)
4611 (orgtbl-mode 1))
4613 (defun org-at-table-p (&optional table-type)
4614 "Non-nil if the cursor is inside an Org table.
4615 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4616 If `org-enable-table-editor' is nil, return nil unconditionally."
4617 (and
4618 org-enable-table-editor
4619 (save-excursion
4620 (beginning-of-line)
4621 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4622 (or (not (derived-mode-p 'org-mode))
4623 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4624 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4626 (defun org-at-table.el-p ()
4627 "Non-nil when point is at a table.el table."
4628 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4629 (let ((element (org-element-at-point)))
4630 (and (eq (org-element-type element) 'table)
4631 (eq (org-element-property :type element) 'table.el)))))
4633 (defun org-table-recognize-table.el ()
4634 "If there is a table.el table nearby, recognize it and move into it."
4635 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4636 (beginning-of-line)
4637 (unless (or (looking-at org-table-dataline-regexp)
4638 (not (looking-at org-table1-hline-regexp)))
4639 (forward-line)
4640 (when (looking-at org-table-any-border-regexp)
4641 (forward-line -2)))
4642 (if (re-search-forward "|" (org-table-end t) t)
4643 (progn
4644 (require 'table)
4645 (if (table--at-cell-p (point)) t
4646 (message "recognizing table.el table...")
4647 (table-recognize-table)
4648 (message "recognizing table.el table...done")))
4649 (error "This should not happen"))))
4650 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4651 (make-obsolete 'org-table-recognize-table.el
4652 "please notify the org mailing list if you use this function."
4653 "Org 9.0")
4655 (defun org-at-table-hline-p ()
4656 "Non-nil when point is inside a hline in a table.
4657 Assume point is already in a table. If `org-enable-table-editor'
4658 is nil, return nil unconditionally."
4659 (and org-enable-table-editor
4660 (save-excursion
4661 (beginning-of-line)
4662 (looking-at org-table-hline-regexp))))
4664 (defun org-table-map-tables (function &optional quietly)
4665 "Apply FUNCTION to the start of all tables in the buffer."
4666 (save-excursion
4667 (save-restriction
4668 (widen)
4669 (goto-char (point-min))
4670 (while (re-search-forward org-table-any-line-regexp nil t)
4671 (unless quietly
4672 (message "Mapping tables: %d%%"
4673 (floor (* 100.0 (point)) (buffer-size))))
4674 (beginning-of-line 1)
4675 (when (and (looking-at org-table-line-regexp)
4676 ;; Exclude tables in src/example/verbatim/clocktable blocks
4677 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4678 (save-excursion (funcall function))
4679 (or (looking-at org-table-line-regexp)
4680 (forward-char 1)))
4681 (re-search-forward org-table-any-border-regexp nil 1))))
4682 (unless quietly (message "Mapping tables: done")))
4684 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4685 (declare-function org-clock-update-mode-line "org-clock" ())
4686 (declare-function org-resolve-clocks "org-clock"
4687 (&optional also-non-dangling-p prompt last-valid))
4689 (defun org-at-TBLFM-p (&optional pos)
4690 "Non-nil when point (or POS) is in #+TBLFM line."
4691 (save-excursion
4692 (goto-char (or pos (point)))
4693 (beginning-of-line)
4694 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4695 (eq (org-element-type (org-element-at-point)) 'table))))
4697 (defvar org-clock-start-time)
4698 (defvar org-clock-marker (make-marker)
4699 "Marker recording the last clock-in.")
4700 (defvar org-clock-hd-marker (make-marker)
4701 "Marker recording the last clock-in, but the headline position.")
4702 (defvar org-clock-heading ""
4703 "The heading of the current clock entry.")
4704 (defun org-clock-is-active ()
4705 "Return the buffer where the clock is currently running.
4706 Return nil if no clock is running."
4707 (marker-buffer org-clock-marker))
4709 (defun org-check-running-clock ()
4710 "Check if the current buffer contains the running clock.
4711 If yes, offer to stop it and to save the buffer with the changes."
4712 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4713 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4714 (buffer-name))))
4715 (org-clock-out)
4716 (when (y-or-n-p "Save changed buffer?")
4717 (save-buffer))))
4719 (defun org-clocktable-try-shift (dir n)
4720 "Check if this line starts a clock table, if yes, shift the time block."
4721 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4722 (org-clocktable-shift dir n)))
4724 ;;;###autoload
4725 (defun org-clock-persistence-insinuate ()
4726 "Set up hooks for clock persistence."
4727 (require 'org-clock)
4728 (add-hook 'org-mode-hook 'org-clock-load)
4729 (add-hook 'kill-emacs-hook 'org-clock-save))
4731 (defgroup org-archive nil
4732 "Options concerning archiving in Org-mode."
4733 :tag "Org Archive"
4734 :group 'org-structure)
4736 (defcustom org-archive-location "%s_archive::"
4737 "The location where subtrees should be archived.
4739 The value of this variable is a string, consisting of two parts,
4740 separated by a double-colon. The first part is a filename and
4741 the second part is a headline.
4743 When the filename is omitted, archiving happens in the same file.
4744 %s in the filename will be replaced by the current file
4745 name (without the directory part). Archiving to a different file
4746 is useful to keep archived entries from contributing to the
4747 Org-mode Agenda.
4749 The archived entries will be filed as subtrees of the specified
4750 headline. When the headline is omitted, the subtrees are simply
4751 filed away at the end of the file, as top-level entries. Also in
4752 the heading you can use %s to represent the file name, this can be
4753 useful when using the same archive for a number of different files.
4755 Here are a few examples:
4756 \"%s_archive::\"
4757 If the current file is Projects.org, archive in file
4758 Projects.org_archive, as top-level trees. This is the default.
4760 \"::* Archived Tasks\"
4761 Archive in the current file, under the top-level headline
4762 \"* Archived Tasks\".
4764 \"~/org/archive.org::\"
4765 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4767 \"~/org/archive.org::* From %s\"
4768 Archive in file ~/org/archive.org (absolute path), under headlines
4769 \"From FILENAME\" where file name is the current file name.
4771 \"~/org/datetree.org::datetree/* Finished Tasks\"
4772 The \"datetree/\" string is special, signifying to archive
4773 items to the datetree. Items are placed in either the CLOSED
4774 date of the item, or the current date if there is no CLOSED date.
4775 The heading will be a subentry to the current date. There doesn't
4776 need to be a heading, but there always needs to be a slash after
4777 datetree. For example, to store archived items directly in the
4778 datetree, use \"~/org/datetree.org::datetree/\".
4780 \"basement::** Finished Tasks\"
4781 Archive in file ./basement (relative path), as level 3 trees
4782 below the level 2 heading \"** Finished Tasks\".
4784 You may set this option on a per-file basis by adding to the buffer a
4785 line like
4787 #+ARCHIVE: basement::** Finished Tasks
4789 You may also define it locally for a subtree by setting an ARCHIVE property
4790 in the entry. If such a property is found in an entry, or anywhere up
4791 the hierarchy, it will be used."
4792 :group 'org-archive
4793 :type 'string)
4795 (defcustom org-agenda-skip-archived-trees t
4796 "Non-nil means the agenda will skip any items located in archived trees.
4797 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4798 variable is no longer recommended, you should leave it at the value t.
4799 Instead, use the key `v' to cycle the archives-mode in the agenda."
4800 :group 'org-archive
4801 :group 'org-agenda-skip
4802 :type 'boolean)
4804 (defcustom org-columns-skip-archived-trees t
4805 "Non-nil means ignore archived trees when creating column view."
4806 :group 'org-archive
4807 :group 'org-properties
4808 :type 'boolean)
4810 (defcustom org-cycle-open-archived-trees nil
4811 "Non-nil means `org-cycle' will open archived trees.
4812 An archived tree is a tree marked with the tag ARCHIVE.
4813 When nil, archived trees will stay folded. You can still open them with
4814 normal outline commands like `show-all', but not with the cycling commands."
4815 :group 'org-archive
4816 :group 'org-cycle
4817 :type 'boolean)
4819 (defcustom org-sparse-tree-open-archived-trees nil
4820 "Non-nil means sparse tree construction shows matches in archived trees.
4821 When nil, matches in these trees are highlighted, but the trees are kept in
4822 collapsed state."
4823 :group 'org-archive
4824 :group 'org-sparse-trees
4825 :type 'boolean)
4827 (defcustom org-sparse-tree-default-date-type nil
4828 "The default date type when building a sparse tree.
4829 When this is nil, a date is a scheduled or a deadline timestamp.
4830 Otherwise, these types are allowed:
4832 all: all timestamps
4833 active: only active timestamps (<...>)
4834 inactive: only inactive timestamps ([...])
4835 scheduled: only scheduled timestamps
4836 deadline: only deadline timestamps"
4837 :type '(choice (const :tag "Scheduled or deadline" nil)
4838 (const :tag "All timestamps" all)
4839 (const :tag "Only active timestamps" active)
4840 (const :tag "Only inactive timestamps" inactive)
4841 (const :tag "Only scheduled timestamps" scheduled)
4842 (const :tag "Only deadline timestamps" deadline)
4843 (const :tag "Only closed timestamps" closed))
4844 :version "25.1"
4845 :package-version '(Org . "8.3")
4846 :group 'org-sparse-trees)
4848 (defun org-cycle-hide-archived-subtrees (state)
4849 "Re-hide all archived subtrees after a visibility state change."
4850 (when (and (not org-cycle-open-archived-trees)
4851 (not (memq state '(overview folded))))
4852 (save-excursion
4853 (let* ((globalp (memq state '(contents all)))
4854 (beg (if globalp (point-min) (point)))
4855 (end (if globalp (point-max) (org-end-of-subtree t))))
4856 (org-hide-archived-subtrees beg end)
4857 (goto-char beg)
4858 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4859 (message "%s" (substitute-command-keys
4860 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4862 (defun org-force-cycle-archived ()
4863 "Cycle subtree even if it is archived."
4864 (interactive)
4865 (setq this-command 'org-cycle)
4866 (let ((org-cycle-open-archived-trees t))
4867 (call-interactively 'org-cycle)))
4869 (defun org-hide-archived-subtrees (beg end)
4870 "Re-hide all archived subtrees after a visibility state change."
4871 (org-with-wide-buffer
4872 (let ((case-fold-search nil)
4873 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4874 (goto-char beg)
4875 ;; Include headline point is currently on.
4876 (beginning-of-line)
4877 (while (and (< (point) end) (re-search-forward re end t))
4878 (when (member org-archive-tag (org-get-tags))
4879 (org-flag-subtree t)
4880 (org-end-of-subtree t))))))
4882 (declare-function outline-end-of-heading "outline" ())
4883 (declare-function outline-flag-region "outline" (from to flag))
4884 (defun org-flag-subtree (flag)
4885 (save-excursion
4886 (org-back-to-heading t)
4887 (outline-end-of-heading)
4888 (outline-flag-region (point)
4889 (progn (org-end-of-subtree t) (point))
4890 flag)))
4892 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4894 ;; Declare Column View Code
4896 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4897 (declare-function org-columns-compute "org-colview" (property))
4899 ;; Declare ID code
4901 (declare-function org-id-store-link "org-id")
4902 (declare-function org-id-locations-load "org-id")
4903 (declare-function org-id-locations-save "org-id")
4904 (defvar org-id-track-globally)
4906 ;;; Variables for pre-computed regular expressions, all buffer local
4908 (defvar-local org-todo-regexp nil
4909 "Matches any of the TODO state keywords.")
4910 (defvar-local org-not-done-regexp nil
4911 "Matches any of the TODO state keywords except the last one.")
4912 (defvar-local org-not-done-heading-regexp nil
4913 "Matches a TODO headline that is not done.")
4914 (defvar-local org-todo-line-regexp nil
4915 "Matches a headline and puts TODO state into group 2 if present.")
4916 (defvar-local org-complex-heading-regexp nil
4917 "Matches a headline and puts everything into groups:
4918 group 1: the stars
4919 group 2: The todo keyword, maybe
4920 group 3: Priority cookie
4921 group 4: True headline
4922 group 5: Tags")
4923 (defvar-local org-complex-heading-regexp-format nil
4924 "Printf format to make regexp to match an exact headline.
4925 This regexp will match the headline of any node which has the
4926 exact headline text that is put into the format, but may have any
4927 TODO state, priority and tags.")
4928 (defvar-local org-todo-line-tags-regexp nil
4929 "Matches a headline and puts TODO state into group 2 if present.
4930 Also put tags into group 4 if tags are present.")
4932 (defconst org-plain-time-of-day-regexp
4933 (concat
4934 "\\(\\<[012]?[0-9]"
4935 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4936 "\\(--?"
4937 "\\(\\<[012]?[0-9]"
4938 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4939 "\\)?")
4940 "Regular expression to match a plain time or time range.
4941 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4942 groups carry important information:
4943 0 the full match
4944 1 the first time, range or not
4945 8 the second time, if it is a range.")
4947 (defconst org-plain-time-extension-regexp
4948 (concat
4949 "\\(\\<[012]?[0-9]"
4950 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4951 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4952 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4953 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4954 groups carry important information:
4955 0 the full match
4956 7 hours of duration
4957 9 minutes of duration")
4959 (defconst org-stamp-time-of-day-regexp
4960 (concat
4961 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4962 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4963 "\\(--?"
4964 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4965 "Regular expression to match a timestamp time or time range.
4966 After a match, the following groups carry important information:
4967 0 the full match
4968 1 date plus weekday, for back referencing to make sure both times are on the same day
4969 2 the first time, range or not
4970 4 the second time, if it is a range.")
4972 (defconst org-startup-options
4973 '(("fold" org-startup-folded t)
4974 ("overview" org-startup-folded t)
4975 ("nofold" org-startup-folded nil)
4976 ("showall" org-startup-folded nil)
4977 ("showeverything" org-startup-folded showeverything)
4978 ("content" org-startup-folded content)
4979 ("indent" org-startup-indented t)
4980 ("noindent" org-startup-indented nil)
4981 ("hidestars" org-hide-leading-stars t)
4982 ("showstars" org-hide-leading-stars nil)
4983 ("odd" org-odd-levels-only t)
4984 ("oddeven" org-odd-levels-only nil)
4985 ("align" org-startup-align-all-tables t)
4986 ("noalign" org-startup-align-all-tables nil)
4987 ("inlineimages" org-startup-with-inline-images t)
4988 ("noinlineimages" org-startup-with-inline-images nil)
4989 ("latexpreview" org-startup-with-latex-preview t)
4990 ("nolatexpreview" org-startup-with-latex-preview nil)
4991 ("customtime" org-display-custom-times t)
4992 ("logdone" org-log-done time)
4993 ("lognotedone" org-log-done note)
4994 ("nologdone" org-log-done nil)
4995 ("lognoteclock-out" org-log-note-clock-out t)
4996 ("nolognoteclock-out" org-log-note-clock-out nil)
4997 ("logrepeat" org-log-repeat state)
4998 ("lognoterepeat" org-log-repeat note)
4999 ("logdrawer" org-log-into-drawer t)
5000 ("nologdrawer" org-log-into-drawer nil)
5001 ("logstatesreversed" org-log-states-order-reversed t)
5002 ("nologstatesreversed" org-log-states-order-reversed nil)
5003 ("nologrepeat" org-log-repeat nil)
5004 ("logreschedule" org-log-reschedule time)
5005 ("lognotereschedule" org-log-reschedule note)
5006 ("nologreschedule" org-log-reschedule nil)
5007 ("logredeadline" org-log-redeadline time)
5008 ("lognoteredeadline" org-log-redeadline note)
5009 ("nologredeadline" org-log-redeadline nil)
5010 ("logrefile" org-log-refile time)
5011 ("lognoterefile" org-log-refile note)
5012 ("nologrefile" org-log-refile nil)
5013 ("fninline" org-footnote-define-inline t)
5014 ("nofninline" org-footnote-define-inline nil)
5015 ("fnlocal" org-footnote-section nil)
5016 ("fnauto" org-footnote-auto-label t)
5017 ("fnprompt" org-footnote-auto-label nil)
5018 ("fnconfirm" org-footnote-auto-label confirm)
5019 ("fnplain" org-footnote-auto-label plain)
5020 ("fnadjust" org-footnote-auto-adjust t)
5021 ("nofnadjust" org-footnote-auto-adjust nil)
5022 ("constcgs" constants-unit-system cgs)
5023 ("constSI" constants-unit-system SI)
5024 ("noptag" org-tag-persistent-alist nil)
5025 ("hideblocks" org-hide-block-startup t)
5026 ("nohideblocks" org-hide-block-startup nil)
5027 ("beamer" org-startup-with-beamer-mode t)
5028 ("entitiespretty" org-pretty-entities t)
5029 ("entitiesplain" org-pretty-entities nil))
5030 "Variable associated with STARTUP options for org-mode.
5031 Each element is a list of three items: the startup options (as written
5032 in the #+STARTUP line), the corresponding variable, and the value to set
5033 this variable to if the option is found. An optional forth element PUSH
5034 means to push this value onto the list in the variable.")
5036 (defcustom org-group-tags t
5037 "When non-nil (the default), use group tags.
5038 This can be turned on/off through `org-toggle-tags-groups'."
5039 :group 'org-tags
5040 :group 'org-startup
5041 :type 'boolean)
5043 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5045 (defun org-toggle-tags-groups ()
5046 "Toggle support for group tags.
5047 Support for group tags is controlled by the option
5048 `org-group-tags', which is non-nil by default."
5049 (interactive)
5050 (setq org-group-tags (not org-group-tags))
5051 (cond ((and (derived-mode-p 'org-agenda-mode)
5052 org-group-tags)
5053 (org-agenda-redo))
5054 ((derived-mode-p 'org-mode)
5055 (let ((org-inhibit-startup t)) (org-mode))))
5056 (message "Groups tags support has been turned %s"
5057 (if org-group-tags "on" "off")))
5059 (defun org-set-regexps-and-options (&optional tags-only)
5060 "Precompute regular expressions used in the current buffer.
5061 When optional argument TAGS-ONLY is non-nil, only compute tags
5062 related expressions."
5063 (when (derived-mode-p 'org-mode)
5064 (let ((alist (org--setup-collect-keywords
5065 (org-make-options-regexp
5066 (append '("FILETAGS" "TAGS" "SETUPFILE")
5067 (and (not tags-only)
5068 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5069 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5070 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5071 ;; Startup options. Get this early since it does change
5072 ;; behavior for other options (e.g., tags).
5073 (let ((startup (cdr (assq 'startup alist))))
5074 (dolist (option startup)
5075 (let ((entry (assoc-string option org-startup-options t)))
5076 (when entry
5077 (let ((var (nth 1 entry))
5078 (val (nth 2 entry)))
5079 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5080 (unless (listp (symbol-value var))
5081 (set (make-local-variable var) nil))
5082 (add-to-list var val)))))))
5083 (setq-local org-file-tags
5084 (mapcar #'org-add-prop-inherited
5085 (cdr (assq 'filetags alist))))
5086 (setq org-current-tag-alist
5087 (append org-tag-persistent-alist
5088 (let ((tags (cdr (assq 'tags alist))))
5089 (if tags (org-tag-string-to-alist tags)
5090 org-tag-alist))))
5091 (setq org-tag-groups-alist
5092 (org-tag-alist-to-groups org-current-tag-alist))
5093 (unless tags-only
5094 ;; File properties.
5095 (setq-local org-file-properties (cdr (assq 'property alist)))
5096 ;; Archive location.
5097 (let ((archive (cdr (assq 'archive alist))))
5098 (when archive (setq-local org-archive-location archive)))
5099 ;; Category.
5100 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5101 (when cat
5102 (setq-local org-category (intern cat))
5103 (setq-local org-file-properties
5104 (org--update-property-plist
5105 "CATEGORY" cat org-file-properties))))
5106 ;; Columns.
5107 (let ((column (cdr (assq 'columns alist))))
5108 (when column (setq-local org-columns-default-format column)))
5109 ;; Constants.
5110 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5111 ;; Link abbreviations.
5112 (let ((links (cdr (assq 'link alist))))
5113 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5114 ;; Priorities.
5115 (let ((priorities (cdr (assq 'priorities alist))))
5116 (when priorities
5117 (setq-local org-highest-priority (nth 0 priorities))
5118 (setq-local org-lowest-priority (nth 1 priorities))
5119 (setq-local org-default-priority (nth 2 priorities))))
5120 ;; Scripts.
5121 (let ((scripts (assq 'scripts alist)))
5122 (when scripts
5123 (setq-local org-use-sub-superscripts (cdr scripts))))
5124 ;; TODO keywords.
5125 (setq-local org-todo-kwd-alist nil)
5126 (setq-local org-todo-key-alist nil)
5127 (setq-local org-todo-key-trigger nil)
5128 (setq-local org-todo-keywords-1 nil)
5129 (setq-local org-done-keywords nil)
5130 (setq-local org-todo-heads nil)
5131 (setq-local org-todo-sets nil)
5132 (setq-local org-todo-log-states nil)
5133 (let ((todo-sequences
5134 (or (nreverse (cdr (assq 'todo alist)))
5135 (let ((d (default-value 'org-todo-keywords)))
5136 (if (not (stringp (car d))) d
5137 ;; XXX: Backward compatibility code.
5138 (list (cons org-todo-interpretation d)))))))
5139 (dolist (sequence todo-sequences)
5140 (let* ((sequence (or (run-hook-with-args-until-success
5141 'org-todo-setup-filter-hook sequence)
5142 sequence))
5143 (sequence-type (car sequence))
5144 (keywords (cdr sequence))
5145 (sep (member "|" keywords))
5146 names alist)
5147 (dolist (k (remove "|" keywords))
5148 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5150 (error "Invalid TODO keyword %s" k))
5151 (let ((name (match-string 1 k))
5152 (key (match-string 2 k))
5153 (log (org-extract-log-state-settings k)))
5154 (push name names)
5155 (push (cons name (and key (string-to-char key))) alist)
5156 (when log (push log org-todo-log-states))))
5157 (let* ((names (nreverse names))
5158 (done (if sep (org-remove-keyword-keys (cdr sep))
5159 (last names)))
5160 (head (car names))
5161 (tail (list sequence-type head (car done) (org-last done))))
5162 (add-to-list 'org-todo-heads head 'append)
5163 (push names org-todo-sets)
5164 (setq org-done-keywords (append org-done-keywords done nil))
5165 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5166 (setq org-todo-key-alist
5167 (append org-todo-key-alist
5168 (and alist
5169 (append '((:startgroup))
5170 (nreverse alist)
5171 '((:endgroup))))))
5172 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5173 (setq org-todo-sets (nreverse org-todo-sets)
5174 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5175 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5176 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5177 ;; Compute the regular expressions and other local variables.
5178 ;; Using `org-outline-regexp-bol' would complicate them much,
5179 ;; because of the fixed white space at the end of that string.
5180 (unless org-done-keywords
5181 (setq org-done-keywords
5182 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5183 (setq org-not-done-keywords
5184 (org-delete-all org-done-keywords
5185 (copy-sequence org-todo-keywords-1))
5186 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5187 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5188 org-not-done-heading-regexp
5189 (format org-heading-keyword-regexp-format org-not-done-regexp)
5190 org-todo-line-regexp
5191 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5192 org-complex-heading-regexp
5193 (concat "^\\(\\*+\\)"
5194 "\\(?: +" org-todo-regexp "\\)?"
5195 "\\(?: +\\(\\[#.\\]\\)\\)?"
5196 "\\(?: +\\(.*?\\)\\)??"
5197 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5198 "[ \t]*$")
5199 org-complex-heading-regexp-format
5200 (concat "^\\(\\*+\\)"
5201 "\\(?: +" org-todo-regexp "\\)?"
5202 "\\(?: +\\(\\[#.\\]\\)\\)?"
5203 "\\(?: +"
5204 ;; Stats cookies can be stuck to body.
5205 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5206 "\\(%s\\)"
5207 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5208 "\\)"
5209 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5210 "[ \t]*$")
5211 org-todo-line-tags-regexp
5212 (concat "^\\(\\*+\\)"
5213 "\\(?: +" org-todo-regexp "\\)?"
5214 "\\(?: +\\(.*?\\)\\)??"
5215 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5216 "[ \t]*$"))
5217 (org-compute-latex-and-related-regexp)))))
5219 (defun org--setup-collect-keywords (regexp &optional files alist)
5220 "Return setup keywords values as an alist.
5222 REGEXP matches a subset of setup keywords. FILES is a list of
5223 file names already visited. It is used to avoid circular setup
5224 files. ALIST, when non-nil, is the alist computed so far.
5226 Return value contains the following keys: `archive', `category',
5227 `columns', `constants', `filetags', `link', `priorities',
5228 `property', `scripts', `startup', `tags' and `todo'."
5229 (org-with-wide-buffer
5230 (goto-char (point-min))
5231 (let ((case-fold-search t))
5232 (while (re-search-forward regexp nil t)
5233 (let ((element (org-element-at-point)))
5234 (when (eq (org-element-type element) 'keyword)
5235 (let ((key (org-element-property :key element))
5236 (value (org-element-property :value element)))
5237 (cond
5238 ((equal key "ARCHIVE")
5239 (when (org-string-nw-p value)
5240 (push (cons 'archive value) alist)))
5241 ((equal key "CATEGORY") (push (cons 'category value) alist))
5242 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5243 ((equal key "CONSTANTS")
5244 (let* ((constants (assq 'constants alist))
5245 (store (cdr constants)))
5246 (dolist (pair (org-split-string value))
5247 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5248 pair)
5249 (let* ((name (match-string 1 pair))
5250 (value (match-string 2 pair))
5251 (old (assoc name store)))
5252 (if old (setcdr old value)
5253 (push (cons name value) store)))))
5254 (if constants (setcdr constants store)
5255 (push (cons 'constants store) alist))))
5256 ((equal key "FILETAGS")
5257 (when (org-string-nw-p value)
5258 (let ((old (assq 'filetags alist))
5259 (new (apply #'nconc
5260 (mapcar (lambda (x) (org-split-string x ":"))
5261 (org-split-string value)))))
5262 (if old (setcdr old (append new (cdr old)))
5263 (push (cons 'filetags new) alist)))))
5264 ((equal key "LINK")
5265 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5266 (let ((links (assq 'link alist))
5267 (pair (cons (match-string-no-properties 1 value)
5268 (match-string-no-properties 2 value))))
5269 (if links (push pair (cdr links))
5270 (push (list 'link pair) alist)))))
5271 ((equal key "OPTIONS")
5272 (when (and (org-string-nw-p value)
5273 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5274 (push (cons 'scripts (read (match-string 1 value))) alist)))
5275 ((equal key "PRIORITIES")
5276 (push (cons 'priorities
5277 (let ((prio (org-split-string value)))
5278 (if (< (length prio) 3) '(?A ?C ?B)
5279 (mapcar #'string-to-char prio))))
5280 alist))
5281 ((equal key "PROPERTY")
5282 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5283 (let* ((property (assq 'property alist))
5284 (value (org--update-property-plist
5285 (match-string-no-properties 1 value)
5286 (match-string-no-properties 2 value)
5287 (cdr property))))
5288 (if property (setcdr property value)
5289 (push (cons 'property value) alist)))))
5290 ((equal key "STARTUP")
5291 (let ((startup (assq 'startup alist)))
5292 (if startup
5293 (setcdr startup
5294 (append (cdr startup) (org-split-string value)))
5295 (push (cons 'startup (org-split-string value)) alist))))
5296 ((equal key "TAGS")
5297 (let ((tag-cell (assq 'tags alist)))
5298 (if tag-cell
5299 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5300 (push (cons 'tags value) alist))))
5301 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5302 (let ((todo (assq 'todo alist))
5303 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5304 (org-split-string value))))
5305 (if todo (push value (cdr todo))
5306 (push (list 'todo value) alist))))
5307 ((equal key "SETUPFILE")
5308 (unless buffer-read-only ; Do not check in Gnus messages.
5309 (let ((f (and (org-string-nw-p value)
5310 (expand-file-name
5311 (org-remove-double-quotes value)))))
5312 (when (and f (file-readable-p f) (not (member f files)))
5313 (with-temp-buffer
5314 (setq default-directory (file-name-directory f))
5315 (insert-file-contents f)
5316 (setq alist
5317 ;; Fake Org mode to benefit from cache
5318 ;; without recurring needlessly.
5319 (let ((major-mode 'org-mode))
5320 (org--setup-collect-keywords
5321 regexp (cons f files) alist)))))))))))))))
5322 alist)
5324 (defun org-tag-string-to-alist (s)
5325 "Return tag alist associated to string S.
5326 S is a value for TAGS keyword or produced with
5327 `org-tag-alist-to-string'. Return value is an alist suitable for
5328 `org-tag-alist' or `org-tag-persistent-alist'."
5329 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5330 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5331 "\\|{.+?}\\)" ; regular expression
5332 "\\(?:(\\(.\\))\\)?\\'"))
5333 alist group-flag)
5334 (dolist (tokens lines (cdr (nreverse alist)))
5335 (push '(:newline) alist)
5336 (while tokens
5337 (let ((token (pop tokens)))
5338 (pcase token
5339 ("{"
5340 (push '(:startgroup) alist)
5341 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5342 ("}"
5343 (push '(:endgroup) alist)
5344 (setq group-flag nil))
5345 ("["
5346 (push '(:startgrouptag) alist)
5347 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5348 ("]"
5349 (push '(:endgrouptag) alist)
5350 (setq group-flag nil))
5351 (":"
5352 (push '(:grouptags) alist))
5353 ((guard (string-match tag-re token))
5354 (let ((tag (match-string 1 token))
5355 (key (and (match-beginning 2)
5356 (string-to-char (match-string 2 token)))))
5357 ;; Push all tags in groups, no matter if they already
5358 ;; appear somewhere else in the list.
5359 (when (or group-flag (not (assoc tag alist)))
5360 (push (cons tag key) alist))))))))))
5362 (defun org-tag-alist-to-string (alist &optional skip-key)
5363 "Return tag string associated to ALIST.
5365 ALIST is an alist, as defined in `org-tag-alist' or
5366 `org-tag-persistent-alist', or produced with
5367 `org-tag-string-to-alist'.
5369 Return value is a string suitable as a value for \"TAGS\"
5370 keyword.
5372 When optional argument SKIP-KEY is non-nil, skip selection keys
5373 next to tags."
5374 (mapconcat (lambda (token)
5375 (pcase token
5376 (`(:startgroup) "{")
5377 (`(:endgroup) "}")
5378 (`(:startgrouptag) "[")
5379 (`(:endgrouptag) "]")
5380 (`(:grouptags) ":")
5381 (`(:newline) "\\n")
5382 ((and
5383 (guard (not skip-key))
5384 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5385 (format "%s(%c)" tag key))
5386 (`(,(and tag (pred stringp)) . ,_) tag)
5387 (_ (user-error "Invalid tag token: %S" token))))
5388 alist
5389 " "))
5391 (defun org-tag-alist-to-groups (alist)
5392 "Return group alist from tag ALIST.
5393 ALIST is an alist, as defined in `org-tag-alist' or
5394 `org-tag-persistent-alist', or produced with
5395 `org-tag-string-to-alist'. Return value is an alist following
5396 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5397 a string, summarizing TAGS, as a list of strings."
5398 (let (groups group-status current-group)
5399 (dolist (token alist (nreverse groups))
5400 (pcase token
5401 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5402 (`(,(or :endgroup :endgrouptag))
5403 (when (eq group-status 'append)
5404 (push (nreverse current-group) groups))
5405 (setq group-status nil))
5406 (`(:grouptags) (setq group-status 'append))
5407 ((and `(,tag . ,_) (guard group-status))
5408 (if (eq group-status 'append) (push tag current-group)
5409 (setq current-group (list tag))))
5410 (_ nil)))))
5412 (defun org-file-contents (file &optional noerror)
5413 "Return the contents of FILE, as a string."
5414 (if (and file (file-readable-p file))
5415 (with-temp-buffer
5416 (insert-file-contents file)
5417 (buffer-string))
5418 (funcall (if noerror 'message 'error)
5419 "Cannot read file \"%s\"%s"
5420 file
5421 (let ((from (buffer-file-name (buffer-base-buffer))))
5422 (if from (concat " (referenced in file \"" from "\")") "")))))
5424 (defun org-extract-log-state-settings (x)
5425 "Extract the log state setting from a TODO keyword string.
5426 This will extract info from a string like \"WAIT(w@/!)\"."
5427 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5428 (let ((kw (match-string 1 x))
5429 (log1 (and (match-end 3) (match-string 3 x)))
5430 (log2 (and (match-end 4) (match-string 4 x))))
5431 (and (or log1 log2)
5432 (list kw
5433 (and log1 (if (equal log1 "!") 'time 'note))
5434 (and log2 (if (equal log2 "!") 'time 'note)))))))
5436 (defun org-remove-keyword-keys (list)
5437 "Remove a pair of parenthesis at the end of each string in LIST."
5438 (mapcar (lambda (x)
5439 (if (string-match "(.*)$" x)
5440 (substring x 0 (match-beginning 0))
5442 list))
5444 (defun org-assign-fast-keys (alist)
5445 "Assign fast keys to a keyword-key alist.
5446 Respect keys that are already there."
5447 (let (new e (alt ?0))
5448 (while (setq e (pop alist))
5449 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5450 (cdr e)) ;; Key already assigned.
5451 (push e new)
5452 (let ((clist (string-to-list (downcase (car e))))
5453 (used (append new alist)))
5454 (when (= (car clist) ?@)
5455 (pop clist))
5456 (while (and clist (rassoc (car clist) used))
5457 (pop clist))
5458 (unless clist
5459 (while (rassoc alt used)
5460 (cl-incf alt)))
5461 (push (cons (car e) (or (car clist) alt)) new))))
5462 (nreverse new)))
5464 ;;; Some variables used in various places
5466 (defvar org-window-configuration nil
5467 "Used in various places to store a window configuration.")
5468 (defvar org-selected-window nil
5469 "Used in various places to store a window configuration.")
5470 (defvar org-finish-function nil
5471 "Function to be called when `C-c C-c' is used.
5472 This is for getting out of special buffers like capture.")
5473 (defvar org-last-state)
5475 ;; Defined somewhere in this file, but used before definition.
5476 (defvar org-entities) ;; defined in org-entities.el
5477 (defvar org-struct-menu)
5478 (defvar org-org-menu)
5479 (defvar org-tbl-menu)
5481 ;;;; Define the Org-mode
5483 ;; We use a before-change function to check if a table might need
5484 ;; an update.
5485 (defvar org-table-may-need-update t
5486 "Indicates that a table might need an update.
5487 This variable is set by `org-before-change-function'.
5488 `org-table-align' sets it back to nil.")
5489 (defun org-before-change-function (_beg _end)
5490 "Every change indicates that a table might need an update."
5491 (setq org-table-may-need-update t))
5492 (defvar org-mode-map)
5493 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5494 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5495 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5496 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5497 (defvar org-table-buffer-is-an nil)
5499 (defvar bidi-paragraph-direction)
5500 (defvar buffer-face-mode-face)
5502 (require 'outline)
5504 ;; Other stuff we need.
5505 (require 'time-date)
5506 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5507 (require 'easymenu)
5508 (autoload 'easy-menu-add "easymenu")
5509 (require 'overlay)
5511 ;; (require 'org-macs) moved higher up in the file before it is first used
5512 (require 'org-entities)
5513 ;; (require 'org-compat) moved higher up in the file before it is first used
5514 (require 'org-faces)
5515 (require 'org-list)
5516 (require 'org-pcomplete)
5517 (require 'org-src)
5518 (require 'org-footnote)
5519 (require 'org-macro)
5521 ;; babel
5522 (require 'ob)
5524 ;;;###autoload
5525 (define-derived-mode org-mode outline-mode "Org"
5526 "Outline-based notes management and organizer, alias
5527 \"Carsten's outline-mode for keeping track of everything.\"
5529 Org-mode develops organizational tasks around a NOTES file which
5530 contains information about projects as plain text. Org-mode is
5531 implemented on top of outline-mode, which is ideal to keep the content
5532 of large files well structured. It supports ToDo items, deadlines and
5533 time stamps, which magically appear in the diary listing of the Emacs
5534 calendar. Tables are easily created with a built-in table editor.
5535 Plain text URL-like links connect to websites, emails (VM), Usenet
5536 messages (Gnus), BBDB entries, and any files related to the project.
5537 For printing and sharing of notes, an Org-mode file (or a part of it)
5538 can be exported as a structured ASCII or HTML file.
5540 The following commands are available:
5542 \\{org-mode-map}"
5544 ;; Get rid of Outline menus, they are not needed
5545 ;; Need to do this here because define-derived-mode sets up
5546 ;; the keymap so late. Still, it is a waste to call this each time
5547 ;; we switch another buffer into Org mode.
5548 (define-key org-mode-map [menu-bar headings] 'undefined)
5549 (define-key org-mode-map [menu-bar hide] 'undefined)
5550 (define-key org-mode-map [menu-bar show] 'undefined)
5552 (org-load-modules-maybe)
5553 (org-install-agenda-files-menu)
5554 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5555 (add-to-invisibility-spec '(org-cwidth))
5556 (add-to-invisibility-spec '(org-hide-block . t))
5557 (setq-local outline-regexp org-outline-regexp)
5558 (setq-local outline-level 'org-outline-level)
5559 (setq bidi-paragraph-direction 'left-to-right)
5560 (when (and org-ellipsis
5561 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5562 (fboundp 'make-glyph-code))
5563 (unless org-display-table
5564 (setq org-display-table (make-display-table)))
5565 (set-display-table-slot
5566 org-display-table 4
5567 (vconcat (mapcar
5568 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5569 org-ellipsis)))
5570 (if (stringp org-ellipsis) org-ellipsis "..."))))
5571 (setq buffer-display-table org-display-table))
5572 (org-set-regexps-and-options)
5573 (org-set-font-lock-defaults)
5574 (when (and org-tag-faces (not org-tags-special-faces-re))
5575 ;; tag faces set outside customize.... force initialization.
5576 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5577 ;; Calc embedded
5578 (setq-local calc-embedded-open-mode "# ")
5579 ;; Modify a few syntax entries
5580 (modify-syntax-entry ?@ "w")
5581 (modify-syntax-entry ?\" "\"")
5582 (modify-syntax-entry ?\\ "_")
5583 (modify-syntax-entry ?~ "_")
5584 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5585 ;; Activate before-change-function
5586 (setq-local org-table-may-need-update t)
5587 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5588 ;; Check for running clock before killing a buffer
5589 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5590 ;; Initialize macros templates.
5591 (org-macro-initialize-templates)
5592 ;; Initialize radio targets.
5593 (org-update-radio-target-regexp)
5594 ;; Indentation.
5595 (setq-local indent-line-function 'org-indent-line)
5596 (setq-local indent-region-function 'org-indent-region)
5597 ;; Filling and auto-filling.
5598 (org-setup-filling)
5599 ;; Comments.
5600 (org-setup-comments-handling)
5601 ;; Initialize cache.
5602 (org-element-cache-reset)
5603 ;; Beginning/end of defun
5604 (setq-local beginning-of-defun-function 'org-backward-element)
5605 (setq-local end-of-defun-function
5606 (lambda ()
5607 (if (not (org-at-heading-p))
5608 (org-forward-element)
5609 (org-forward-element)
5610 (forward-char -1))))
5611 ;; Next error for sparse trees
5612 (setq-local next-error-function 'org-occur-next-match)
5613 ;; Make sure dependence stuff works reliably, even for users who set it
5614 ;; too late :-(
5615 (if org-enforce-todo-dependencies
5616 (add-hook 'org-blocker-hook
5617 'org-block-todo-from-children-or-siblings-or-parent)
5618 (remove-hook 'org-blocker-hook
5619 'org-block-todo-from-children-or-siblings-or-parent))
5620 (if org-enforce-todo-checkbox-dependencies
5621 (add-hook 'org-blocker-hook
5622 'org-block-todo-from-checkboxes)
5623 (remove-hook 'org-blocker-hook
5624 'org-block-todo-from-checkboxes))
5626 ;; Align options lines
5627 (setq-local
5628 align-mode-rules-list
5629 '((org-in-buffer-settings
5630 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5631 (modes . '(org-mode)))))
5633 ;; Imenu
5634 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5636 ;; Make isearch reveal context
5637 (setq-local outline-isearch-open-invisible-function
5638 (lambda (&rest _) (org-show-context 'isearch)))
5640 ;; Setup the pcomplete hooks
5641 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5642 (setq-local pcomplete-command-name-function 'org-command-at-point)
5643 (setq-local pcomplete-default-completion-function 'ignore)
5644 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5645 (setq-local pcomplete-termination-string "")
5646 (setq-local buffer-face-mode-face 'org-default)
5648 ;; If empty file that did not turn on Org mode automatically, make
5649 ;; it to.
5650 (when (and org-insert-mode-line-in-empty-file
5651 (called-interactively-p 'any)
5652 (= (point-min) (point-max)))
5653 (insert "# -*- mode: org -*-\n\n"))
5654 (unless org-inhibit-startup
5655 (org-unmodified
5656 (when org-startup-with-beamer-mode (org-beamer-mode))
5657 (when org-startup-align-all-tables
5658 (org-table-map-tables #'org-table-align t))
5659 (when org-startup-with-inline-images (org-display-inline-images))
5660 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5661 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5662 (when org-startup-truncated (setq truncate-lines t))
5663 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5664 (org-refresh-effort-properties)))
5665 ;; Try to set `org-hide' face correctly.
5666 (let ((foreground (org-find-invisible-foreground)))
5667 (when foreground
5668 (set-face-foreground 'org-hide foreground))))
5670 ;; Update `customize-package-emacs-version-alist'
5671 (add-to-list 'customize-package-emacs-version-alist
5672 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5673 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5674 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5676 (defvar org-mode-transpose-word-syntax-table
5677 (let ((st (make-syntax-table text-mode-syntax-table)))
5678 (dolist (c org-emphasis-alist st)
5679 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5681 (when (fboundp 'abbrev-table-put)
5682 (abbrev-table-put org-mode-abbrev-table
5683 :parents (list text-mode-abbrev-table)))
5685 (defun org-find-invisible-foreground ()
5686 (let ((candidates (remove
5687 "unspecified-bg"
5688 (nconc
5689 (list (face-background 'default)
5690 (face-background 'org-default))
5691 (mapcar
5692 (lambda (alist)
5693 (when (boundp alist)
5694 (cdr (assoc 'background-color (symbol-value alist)))))
5695 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5696 (list (face-foreground 'org-hide))))))
5697 (car (remove nil candidates))))
5699 (defun org-current-time (&optional rounding-minutes past)
5700 "Current time, possibly rounded to ROUNDING-MINUTES.
5701 When ROUNDING-MINUTES is not an integer, fall back on the car of
5702 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5703 the rounding returns a past time."
5704 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5705 (car org-time-stamp-rounding-minutes)))
5706 (time (decode-time)) res)
5707 (if (< r 1)
5708 (current-time)
5709 (setq res
5710 (apply 'encode-time
5711 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5712 (nthcdr 2 time))))
5713 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5714 (seconds-to-time (- (float-time res) (* r 60)))
5715 res))))
5717 (defun org-today ()
5718 "Return today date, considering `org-extend-today-until'."
5719 (time-to-days
5720 (time-subtract (current-time)
5721 (list 0 (* 3600 org-extend-today-until) 0))))
5723 ;;;; Font-Lock stuff, including the activators
5725 (defvar org-mouse-map (make-sparse-keymap))
5726 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5727 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5728 (when org-mouse-1-follows-link
5729 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5730 (when org-tab-follows-link
5731 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5732 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5734 (require 'font-lock)
5736 (defconst org-non-link-chars "]\t\n\r<>")
5737 (defvar org-link-types-re nil
5738 "Matches a link that has a url-like prefix like \"http:\"")
5739 (defvar org-link-re-with-space nil
5740 "Matches a link with spaces, optional angular brackets around it.")
5741 (defvar org-link-re-with-space2 nil
5742 "Matches a link with spaces, optional angular brackets around it.")
5743 (defvar org-link-re-with-space3 nil
5744 "Matches a link with spaces, only for internal part in bracket links.")
5745 (defvar org-angle-link-re nil
5746 "Matches link with angular brackets, spaces are allowed.")
5747 (defvar org-plain-link-re nil
5748 "Matches plain link, without spaces.")
5749 (defvar org-bracket-link-regexp nil
5750 "Matches a link in double brackets.")
5751 (defvar org-bracket-link-analytic-regexp nil
5752 "Regular expression used to analyze links.
5753 Here is what the match groups contain after a match:
5754 1: http:
5755 2: http
5756 3: path
5757 4: [desc]
5758 5: desc")
5759 (defvar org-bracket-link-analytic-regexp++ nil
5760 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5761 (defvar org-any-link-re nil
5762 "Regular expression matching any link.")
5764 (defconst org-match-sexp-depth 3
5765 "Number of stacked braces for sub/superscript matching.")
5767 (defun org-create-multibrace-regexp (left right n)
5768 "Create a regular expression which will match a balanced sexp.
5769 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5770 as single character strings.
5771 The regexp returned will match the entire expression including the
5772 delimiters. It will also define a single group which contains the
5773 match except for the outermost delimiters. The maximum depth of
5774 stacked delimiters is N. Escaping delimiters is not possible."
5775 (let* ((nothing (concat "[^" left right "]*?"))
5776 (or "\\|")
5777 (re nothing)
5778 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5779 (while (> n 1)
5780 (setq n (1- n)
5781 re (concat re or next)
5782 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5783 (concat left "\\(" re "\\)" right)))
5785 (defconst org-match-substring-regexp
5786 (concat
5787 "\\(\\S-\\)\\([_^]\\)\\("
5788 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5789 "\\|"
5790 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5791 "\\|"
5792 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5793 "The regular expression matching a sub- or superscript.")
5795 (defconst org-match-substring-with-braces-regexp
5796 (concat
5797 "\\(\\S-\\)\\([_^]\\)"
5798 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5799 "The regular expression matching a sub- or superscript, forcing braces.")
5801 (defun org-make-link-regexps ()
5802 "Update the link regular expressions.
5803 This should be called after the variable `org-link-parameters' has changed."
5804 (let ((types-re (regexp-opt (org-link-types) t)))
5805 (setq org-link-types-re
5806 (concat "\\`" types-re ":")
5807 org-link-re-with-space
5808 (concat "<?" types-re ":"
5809 "\\([^" org-non-link-chars " ]"
5810 "[^" org-non-link-chars "]*"
5811 "[^" org-non-link-chars " ]\\)>?")
5812 org-link-re-with-space2
5813 (concat "<?" types-re ":"
5814 "\\([^" org-non-link-chars " ]"
5815 "[^\t\n\r]*"
5816 "[^" org-non-link-chars " ]\\)>?")
5817 org-link-re-with-space3
5818 (concat "<?" types-re ":"
5819 "\\([^" org-non-link-chars " ]"
5820 "[^\t\n\r]*\\)")
5821 org-angle-link-re
5822 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5823 types-re)
5824 org-plain-link-re
5825 (concat
5826 "\\<" types-re ":"
5827 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5828 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5829 org-bracket-link-regexp
5830 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5831 org-bracket-link-analytic-regexp
5832 (concat
5833 "\\[\\["
5834 "\\(" types-re ":\\)?"
5835 "\\([^]]+\\)"
5836 "\\]"
5837 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5838 "\\]")
5839 org-bracket-link-analytic-regexp++
5840 (concat
5841 "\\[\\["
5842 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5843 "\\([^]]+\\)"
5844 "\\]"
5845 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5846 "\\]")
5847 org-any-link-re
5848 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5849 org-angle-link-re "\\)\\|\\("
5850 org-plain-link-re "\\)"))))
5852 (org-make-link-regexps)
5854 (defvar org-emph-face nil)
5856 (defun org-do-emphasis-faces (limit)
5857 "Run through the buffer and emphasize strings."
5858 (let (rtn a)
5859 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5860 (let* ((border (char-after (match-beginning 3)))
5861 (bre (regexp-quote (char-to-string border))))
5862 (when (and (not (= border (char-after (match-beginning 4))))
5863 (not (string-match-p (concat bre ".*" bre)
5864 (replace-regexp-in-string
5865 "\n" " "
5866 (substring (match-string 2) 1 -1)))))
5867 (setq rtn t)
5868 (setq a (assoc (match-string 3) org-emphasis-alist))
5869 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5870 'face
5871 (nth 1 a))
5872 (and (nth 2 a)
5873 (org-remove-flyspell-overlays-in
5874 (match-beginning 0) (match-end 0)))
5875 (add-text-properties (match-beginning 2) (match-end 2)
5876 '(font-lock-multiline t org-emphasis t))
5877 (when org-hide-emphasis-markers
5878 (add-text-properties (match-end 4) (match-beginning 5)
5879 '(invisible org-link))
5880 (add-text-properties (match-beginning 3) (match-end 3)
5881 '(invisible org-link)))))
5882 (goto-char (1+ (match-beginning 0))))
5883 rtn))
5885 (defun org-emphasize (&optional char)
5886 "Insert or change an emphasis, i.e. a font like bold or italic.
5887 If there is an active region, change that region to a new emphasis.
5888 If there is no region, just insert the marker characters and position
5889 the cursor between them.
5890 CHAR should be the marker character. If it is a space, it means to
5891 remove the emphasis of the selected region.
5892 If CHAR is not given (for example in an interactive call) it will be
5893 prompted for."
5894 (interactive)
5895 (let ((erc org-emphasis-regexp-components)
5896 (string "") beg end move s)
5897 (if (org-region-active-p)
5898 (setq beg (region-beginning)
5899 end (region-end)
5900 string (buffer-substring beg end))
5901 (setq move t))
5903 (unless char
5904 (message "Emphasis marker or tag: [%s]"
5905 (mapconcat #'car org-emphasis-alist ""))
5906 (setq char (read-char-exclusive)))
5907 (if (equal char ?\s)
5908 (setq s ""
5909 move nil)
5910 (unless (assoc (char-to-string char) org-emphasis-alist)
5911 (user-error "No such emphasis marker: \"%c\"" char))
5912 (setq s (char-to-string char)))
5913 (while (and (> (length string) 1)
5914 (equal (substring string 0 1) (substring string -1))
5915 (assoc (substring string 0 1) org-emphasis-alist))
5916 (setq string (substring string 1 -1)))
5917 (setq string (concat s string s))
5918 (when beg (delete-region beg end))
5919 (unless (or (bolp)
5920 (string-match (concat "[" (nth 0 erc) "\n]")
5921 (char-to-string (char-before (point)))))
5922 (insert " "))
5923 (unless (or (eobp)
5924 (string-match (concat "[" (nth 1 erc) "\n]")
5925 (char-to-string (char-after (point)))))
5926 (insert " ") (backward-char 1))
5927 (insert string)
5928 (and move (backward-char 1))))
5930 (defconst org-nonsticky-props
5931 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5933 (defsubst org-rear-nonsticky-at (pos)
5934 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5936 (defun org-activate-plain-links (limit)
5937 "Add link properties for plain links."
5938 (when (and (re-search-forward org-plain-link-re limit t)
5939 (not (org-in-src-block-p)))
5941 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5942 'face))
5943 (link (match-string-no-properties 0))
5944 (type (match-string-no-properties 1))
5945 (path (match-string-no-properties 2))
5946 (link-start (match-beginning 0))
5947 (link-end (match-end 0))
5948 (link-face (org-link-get-parameter type :face))
5949 (help-echo (org-link-get-parameter type :help-echo))
5950 (htmlize-link (org-link-get-parameter type :htmlize-link))
5951 (activate-func (org-link-get-parameter type :activate-func)))
5952 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5953 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5954 (add-text-properties (match-beginning 0) (match-end 0)
5955 (list
5956 'mouse-face (or (org-link-get-parameter type :mouse-face)
5957 'highlight)
5958 'face (cond
5959 ;; A function that returns a face
5960 ((functionp link-face)
5961 (funcall link-face path))
5962 ;; a face
5963 ((facep link-face)
5964 link-face)
5965 ;; An anonymous face
5966 ((consp link-face)
5967 link-face)
5968 ;; default
5970 'org-link))
5971 'help-echo (cond
5972 ((stringp help-echo)
5973 help-echo)
5974 ((functionp help-echo)
5975 help-echo)
5977 (concat "LINK: "
5978 (save-match-data
5979 (org-link-unescape link)))))
5980 'htmlize-link (cond
5981 ((functionp htmlize-link)
5982 (funcall htmlize-link path))
5984 `(:uri ,link)))
5985 'keymap (or (org-link-get-parameter type :keymap)
5986 org-mouse-map)
5987 'org-link-start (match-beginning 0)))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when activate-func
5990 (funcall activate-func link-start link-end path nil))
5991 t))))
5993 (defun org-activate-code (limit)
5994 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (remove-text-properties (match-beginning 0) (match-end 0)
5997 '(display t invisible t intangible t))
6000 (defcustom org-src-fontify-natively t
6001 "When non-nil, fontify code in code blocks.
6002 See also the `org-block' face."
6003 :type 'boolean
6004 :version "24.4"
6005 :package-version '(Org . "8.3")
6006 :group 'org-appearance
6007 :group 'org-babel)
6009 (defcustom org-allow-promoting-top-level-subtree nil
6010 "When non-nil, allow promoting a top level subtree.
6011 The leading star of the top level headline will be replaced
6012 by a #."
6013 :type 'boolean
6014 :version "24.1"
6015 :group 'org-appearance)
6017 (defun org-fontify-meta-lines-and-blocks (limit)
6018 (condition-case nil
6019 (org-fontify-meta-lines-and-blocks-1 limit)
6020 (error (message "org-mode fontification error in %S at %d"
6021 (current-buffer)
6022 (line-number-at-pos)))))
6024 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6025 "Fontify #+ lines and blocks."
6026 (let ((case-fold-search t))
6027 (when (re-search-forward
6028 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6029 limit t)
6030 (let ((beg (match-beginning 0))
6031 (block-start (match-end 0))
6032 (block-end nil)
6033 (lang (match-string 7))
6034 (beg1 (line-beginning-position 2))
6035 (dc1 (downcase (match-string 2)))
6036 (dc3 (downcase (match-string 3)))
6037 end end1 quoting block-type)
6038 (cond
6039 ((and (match-end 4) (equal dc3 "+begin"))
6040 ;; Truly a block
6041 (setq block-type (downcase (match-string 5))
6042 quoting (member block-type org-protecting-blocks))
6043 (when (re-search-forward
6044 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6045 nil t) ;; on purpose, we look further than LIMIT
6046 (setq end (min (point-max) (match-end 0))
6047 end1 (min (point-max) (1- (match-beginning 0))))
6048 (setq block-end (match-beginning 0))
6049 (when quoting
6050 (org-remove-flyspell-overlays-in beg1 end1)
6051 (remove-text-properties beg end
6052 '(display t invisible t intangible t)))
6053 (add-text-properties
6054 beg end '(font-lock-fontified t font-lock-multiline t))
6055 (add-text-properties beg beg1 '(face org-meta-line))
6056 (org-remove-flyspell-overlays-in beg beg1)
6057 (add-text-properties ; For end_src
6058 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6059 (org-remove-flyspell-overlays-in end1 end)
6060 (cond
6061 ((and lang (not (string= lang "")) org-src-fontify-natively)
6062 (org-src-font-lock-fontify-block lang block-start block-end)
6063 (add-text-properties beg1 block-end '(src-block t)))
6064 (quoting
6065 (add-text-properties beg1 (min (point-max) (1+ end1))
6066 (list 'face
6067 (list :inherit
6068 (let ((face-name
6069 (intern (format "org-block-%s" lang))))
6070 (append (and (facep face-name) (list face-name))
6071 '(org-block))))))) ; end of source block
6072 ((not org-fontify-quote-and-verse-blocks))
6073 ((string= block-type "quote")
6074 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6075 ((string= block-type "verse")
6076 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6077 (add-text-properties beg beg1 '(face org-block-begin-line))
6078 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6079 '(face org-block-end-line))
6081 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6082 (org-remove-flyspell-overlays-in
6083 (match-beginning 0)
6084 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6085 (add-text-properties
6086 beg (match-end 3)
6087 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6088 '(font-lock-fontified t invisible t)
6089 '(font-lock-fontified t face org-document-info-keyword)))
6090 (add-text-properties
6091 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6092 (if (string-equal dc1 "+title:")
6093 '(font-lock-fontified t face org-document-title)
6094 '(font-lock-fontified t face org-document-info))))
6095 ((equal dc1 "+caption:")
6096 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6097 (remove-text-properties (match-beginning 0) (match-end 0)
6098 '(display t invisible t intangible t))
6099 (add-text-properties (match-beginning 1) (match-end 3)
6100 '(font-lock-fontified t face org-meta-line))
6101 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6102 '(font-lock-fontified t face org-block))
6104 ((member dc3 '(" " ""))
6105 (org-remove-flyspell-overlays-in beg (match-end 0))
6106 (add-text-properties
6107 beg (match-end 0)
6108 '(font-lock-fontified t face font-lock-comment-face)))
6109 (t ;; just any other in-buffer setting, but not indented
6110 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6111 (remove-text-properties (match-beginning 0) (match-end 0)
6112 '(display t invisible t intangible t))
6113 (add-text-properties beg (match-end 0)
6114 '(font-lock-fontified t face org-meta-line))
6115 t))))))
6117 (defun org-fontify-drawers (limit)
6118 "Fontify drawers."
6119 (when (re-search-forward org-drawer-regexp limit t)
6120 (add-text-properties
6121 (match-beginning 0) (match-end 0)
6122 '(font-lock-fontified t face org-special-keyword))
6123 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6126 (defun org-fontify-macros (limit)
6127 "Fontify macros."
6128 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6129 (add-text-properties
6130 (match-beginning 0) (match-end 0)
6131 '(font-lock-fontified t face org-macro))
6132 (when org-hide-macro-markers
6133 (add-text-properties (match-end 2) (match-beginning 2)
6134 '(invisible t))
6135 (add-text-properties (match-beginning 1) (match-end 1)
6136 '(invisible t)))
6137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6140 (defun org-activate-angle-links (limit)
6141 "Add text properties for angle links."
6142 (when (and (re-search-forward org-angle-link-re limit t)
6143 (not (org-in-src-block-p)))
6144 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6145 (add-text-properties (match-beginning 0) (match-end 0)
6146 (list 'mouse-face 'highlight
6147 'keymap org-mouse-map
6148 'font-lock-multiline t))
6149 (org-rear-nonsticky-at (match-end 0))
6152 (defun org-activate-footnote-links (limit)
6153 "Add text properties for footnotes."
6154 (let ((fn (org-footnote-next-reference-or-definition limit)))
6155 (when fn
6156 (let* ((beg (nth 1 fn))
6157 (end (nth 2 fn))
6158 (label (car fn))
6159 (referencep (/= (line-beginning-position) beg)))
6160 (when (and referencep (nth 3 fn))
6161 (save-excursion
6162 (goto-char beg)
6163 (search-forward (or label "fn:"))
6164 (org-remove-flyspell-overlays-in beg (match-end 0))))
6165 (add-text-properties beg end
6166 (list 'mouse-face 'highlight
6167 'keymap org-mouse-map
6168 'help-echo
6169 (if referencep "Footnote reference"
6170 "Footnote definition")
6171 'font-lock-fontified t
6172 'font-lock-multiline t
6173 'face 'org-footnote))))))
6175 (defun org-activate-bracket-links (limit)
6176 "Add text properties for bracketed links."
6177 (when (and (re-search-forward org-bracket-link-regexp limit t)
6178 (not (org-in-src-block-p)))
6179 (let* ((hl (match-string-no-properties 1))
6180 (type (save-match-data
6181 (and (string-match org-plain-link-re hl)
6182 (match-string-no-properties 1 hl))))
6183 (path (save-match-data
6184 (and (string-match org-plain-link-re hl)
6185 (match-string-no-properties 2 hl))))
6186 (link-start (match-beginning 0))
6187 (link-end (match-end 0))
6188 (bracketp t)
6189 (help-echo (org-link-get-parameter type :help-echo))
6190 (help (cond
6191 ((stringp help-echo)
6192 help-echo)
6193 ((functionp help-echo)
6194 help-echo)
6196 (concat "LINK: "
6197 (save-match-data
6198 (org-link-unescape hl))))))
6199 (link-face (org-link-get-parameter type :face))
6200 (face (cond
6201 ;; A function that returns a face
6202 ((functionp link-face)
6203 (funcall link-face path))
6204 ;; a face
6205 ((facep link-face)
6206 link-face)
6207 ;; An anonymous face
6208 ((consp link-face)
6209 link-face)
6210 ;; default
6212 'org-link)))
6213 (keymap (or (org-link-get-parameter type :keymap)
6214 org-mouse-map))
6215 (mouse-face (or (org-link-get-parameter type :mouse-face)
6216 'highlight))
6217 (htmlize (org-link-get-parameter type :htmlize-link))
6218 (htmlize-link (cond
6219 ((functionp htmlize)
6220 (funcall htmlize))
6222 `(:uri ,(format "%s:%s" type path)))))
6223 (activate-func (org-link-get-parameter type :activate-func))
6224 ;; invisible part
6225 (ip (list 'invisible (or
6226 (org-link-get-parameter type :display)
6227 'org-link)
6228 'face face
6229 'keymap keymap
6230 'mouse-face mouse-face
6231 'font-lock-multiline t
6232 'help-echo help
6233 'htmlize-link htmlize-link))
6234 ;; visible part
6235 (vp (list 'keymap keymap
6236 'face face
6237 'mouse-face mouse-face
6238 'font-lock-multiline t
6239 'help-echo help
6240 'htmlize-link htmlize-link)))
6241 ;; We need to remove the invisible property here. Table narrowing
6242 ;; may have made some of this invisible.
6243 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6244 (remove-text-properties (match-beginning 0) (match-end 0)
6245 '(invisible nil))
6246 (if (match-end 3)
6247 (progn
6248 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6249 (org-rear-nonsticky-at (match-beginning 3))
6250 (add-text-properties (match-beginning 3) (match-end 3) vp)
6251 (org-rear-nonsticky-at (match-end 3))
6252 (add-text-properties (match-end 3) (match-end 0) ip)
6253 (org-rear-nonsticky-at (match-end 0)))
6254 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6255 (org-rear-nonsticky-at (match-beginning 1))
6256 (add-text-properties (match-beginning 1) (match-end 1) vp)
6257 (org-rear-nonsticky-at (match-end 1))
6258 (add-text-properties (match-end 1) (match-end 0) ip)
6259 (org-rear-nonsticky-at (match-end 0)))
6260 (when activate-func
6261 (funcall activate-func link-start link-end path bracketp))
6262 t)))
6264 (defun org-activate-dates (limit)
6265 "Add text properties for dates."
6266 (when (and (re-search-forward org-tsr-regexp-both limit t)
6267 (not (equal (char-before (match-beginning 0)) 91)))
6268 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6269 (add-text-properties (match-beginning 0) (match-end 0)
6270 (list 'mouse-face 'highlight
6271 'keymap org-mouse-map))
6272 (org-rear-nonsticky-at (match-end 0))
6273 (when org-display-custom-times
6274 (if (match-end 3)
6275 (org-display-custom-time (match-beginning 3) (match-end 3))
6276 (org-display-custom-time (match-beginning 1) (match-end 1))))
6279 (defvar-local org-target-link-regexp nil
6280 "Regular expression matching radio targets in plain text.")
6282 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6283 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6284 border border border))
6285 "Regular expression matching a link target.")
6287 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6288 "Regular expression matching a radio target.")
6290 (defconst org-any-target-regexp
6291 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6292 "Regular expression matching any target.")
6294 (defun org-activate-target-links (limit)
6295 "Add text properties for target matches."
6296 (when org-target-link-regexp
6297 (let ((case-fold-search t))
6298 (when (re-search-forward org-target-link-regexp limit t)
6299 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6300 (add-text-properties (match-beginning 1) (match-end 1)
6301 (list 'mouse-face 'highlight
6302 'keymap org-mouse-map
6303 'help-echo "Radio target link"
6304 'org-linked-text t))
6305 (org-rear-nonsticky-at (match-end 1))
6306 t))))
6308 (defun org-update-radio-target-regexp ()
6309 "Find all radio targets in this file and update the regular expression.
6310 Also refresh fontification if needed."
6311 (interactive)
6312 (let ((old-regexp org-target-link-regexp)
6313 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6314 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6315 (targets
6316 (org-with-wide-buffer
6317 (goto-char (point-min))
6318 (let (rtn)
6319 (while (re-search-forward org-radio-target-regexp nil t)
6320 ;; Make sure point is really within the object.
6321 (backward-char)
6322 (let ((obj (org-element-context)))
6323 (when (eq (org-element-type obj) 'radio-target)
6324 (cl-pushnew (org-element-property :value obj) rtn
6325 :test #'equal))))
6326 rtn))))
6327 (setq org-target-link-regexp
6328 (and targets
6329 (concat before-re
6330 (mapconcat
6331 (lambda (x)
6332 (replace-regexp-in-string
6333 " +" "\\s-+" (regexp-quote x) t t))
6334 targets
6335 "\\|")
6336 after-re)))
6337 (unless (equal old-regexp org-target-link-regexp)
6338 ;; Clean-up cache.
6339 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6340 ((not org-target-link-regexp) old-regexp)
6342 (concat before-re
6343 (mapconcat
6344 (lambda (re)
6345 (substring re (length before-re)
6346 (- (length after-re))))
6347 (list old-regexp org-target-link-regexp)
6348 "\\|")
6349 after-re)))))
6350 (org-with-wide-buffer
6351 (goto-char (point-min))
6352 (while (re-search-forward regexp nil t)
6353 (org-element-cache-refresh (match-beginning 1)))))
6354 ;; Re fontify buffer.
6355 (when (memq 'radio org-highlight-links)
6356 (org-restart-font-lock)))))
6358 (defun org-hide-wide-columns (limit)
6359 (let (s e)
6360 (setq s (text-property-any (point) (or limit (point-max))
6361 'org-cwidth t))
6362 (when s
6363 (setq e (next-single-property-change s 'org-cwidth))
6364 (add-text-properties s e '(invisible org-cwidth))
6365 (goto-char e)
6366 t)))
6368 (defvar org-latex-and-related-regexp nil
6369 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6371 (defun org-compute-latex-and-related-regexp ()
6372 "Compute regular expression for LaTeX, entities and sub/superscript.
6373 Result depends on variable `org-highlight-latex-and-related'."
6374 (setq-local
6375 org-latex-and-related-regexp
6376 (let* ((re-sub
6377 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6378 ((eq org-use-sub-superscripts '{})
6379 (list org-match-substring-with-braces-regexp))
6380 (org-use-sub-superscripts (list org-match-substring-regexp))))
6381 (re-latex
6382 (when (memq 'latex org-highlight-latex-and-related)
6383 (let ((matchers (plist-get org-format-latex-options :matchers)))
6384 (delq nil
6385 (mapcar (lambda (x)
6386 (and (member (car x) matchers) (nth 1 x)))
6387 org-latex-regexps)))))
6388 (re-entities
6389 (when (memq 'entities org-highlight-latex-and-related)
6390 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6391 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6393 (defun org-do-latex-and-related (limit)
6394 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6395 LIMIT bounds the search for syntax to highlight. Stop at first
6396 highlighted object, if any. Return t if some highlighting was
6397 done, nil otherwise."
6398 (when (org-string-nw-p org-latex-and-related-regexp)
6399 (catch 'found
6400 (while (re-search-forward org-latex-and-related-regexp limit t)
6401 (unless
6402 (cl-some
6403 (lambda (f)
6404 (memq f '(org-code org-verbatim underline org-special-keyword)))
6405 (save-excursion
6406 (goto-char (1+ (match-beginning 0)))
6407 (face-at-point nil t)))
6408 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6409 '(?_ ?^))
6411 0)))
6412 (font-lock-prepend-text-property
6413 (+ offset (match-beginning 0)) (match-end 0)
6414 'face 'org-latex-and-related)
6415 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6416 '(font-lock-multiline t)))
6417 (throw 'found t)))
6418 nil)))
6420 (defun org-restart-font-lock ()
6421 "Restart `font-lock-mode', to force refontification."
6422 (when (and (boundp 'font-lock-mode) font-lock-mode)
6423 (font-lock-mode -1)
6424 (font-lock-mode 1)))
6426 (defun org-activate-tags (limit)
6427 (when (re-search-forward
6428 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6429 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6430 (add-text-properties (match-beginning 1) (match-end 1)
6431 (list 'mouse-face 'highlight
6432 'keymap org-mouse-map))
6433 (org-rear-nonsticky-at (match-end 1))
6436 (defun org-outline-level ()
6437 "Compute the outline level of the heading at point.
6439 If this is called at a normal headline, the level is the number
6440 of stars. Use `org-reduced-level' to remove the effect of
6441 `org-odd-levels'. Unlike to `org-current-level', this function
6442 takes into consideration inlinetasks."
6443 (org-with-wide-buffer
6444 (end-of-line)
6445 (if (re-search-backward org-outline-regexp-bol nil t)
6446 (1- (- (match-end 0) (match-beginning 0)))
6447 0)))
6449 (defvar org-font-lock-keywords nil)
6451 (defsubst org-re-property (property &optional literal allow-null value)
6452 "Return a regexp matching a PROPERTY line.
6454 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6455 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6456 non-nil, match properties even without a value.
6458 Match group 3 is set to the value when it exists. If there is no
6459 value and ALLOW-NULL is non-nil, it is set to the empty string.
6461 With optional argument VALUE, match only property lines with
6462 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6463 unless LITERAL is non-nil."
6464 (concat
6465 "^\\(?4:[ \t]*\\)"
6466 (format "\\(?1::\\(?2:%s\\):\\)"
6467 (if literal property (regexp-quote property)))
6468 (cond (value
6469 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6470 (if literal value (regexp-quote value))))
6471 (allow-null
6472 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6474 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6476 (defconst org-property-re
6477 (org-re-property "\\S-+" 'literal t)
6478 "Regular expression matching a property line.
6479 There are four matching groups:
6480 1: :PROPKEY: including the leading and trailing colon,
6481 2: PROPKEY without the leading and trailing colon,
6482 3: PROPVAL without leading or trailing spaces,
6483 4: the indentation of the current line,
6484 5: trailing whitespace.")
6486 (defvar org-font-lock-hook nil
6487 "Functions to be called for special font lock stuff.")
6489 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6491 (defvar org-font-lock-set-keywords-hook nil
6492 "Functions that can manipulate `org-font-lock-extra-keywords'.
6493 This is called after `org-font-lock-extra-keywords' is defined, but before
6494 it is installed to be used by font lock. This can be useful if something
6495 needs to be inserted at a specific position in the font-lock sequence.")
6497 (defun org-font-lock-hook (limit)
6498 "Run `org-font-lock-hook' within LIMIT."
6499 (run-hook-with-args 'org-font-lock-hook limit))
6501 (defun org-set-font-lock-defaults ()
6502 "Set font lock defaults for the current buffer."
6503 (let* ((em org-fontify-emphasized-text)
6504 (lk org-highlight-links)
6505 (org-font-lock-extra-keywords
6506 (list
6507 ;; Call the hook
6508 '(org-font-lock-hook)
6509 ;; Headlines
6510 `(,(if org-fontify-whole-heading-line
6511 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6512 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6513 (1 (org-get-level-face 1))
6514 (2 (org-get-level-face 2))
6515 (3 (org-get-level-face 3)))
6516 ;; Table lines
6517 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6518 (1 'org-table t))
6519 ;; Table internals
6520 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6521 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6522 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6523 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6524 ;; Drawers
6525 '(org-fontify-drawers)
6526 ;; Properties
6527 (list org-property-re
6528 '(1 'org-special-keyword t)
6529 '(3 'org-property-value t))
6530 ;; Links
6531 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6532 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6533 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6534 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6535 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6536 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6537 (when (memq 'footnote lk) '(org-activate-footnote-links))
6538 ;; Targets.
6539 (list org-any-target-regexp '(0 'org-target t))
6540 ;; Diary sexps.
6541 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6542 ;; Macro
6543 '(org-fontify-macros)
6544 '(org-hide-wide-columns (0 nil append))
6545 ;; TODO keyword
6546 (list (format org-heading-keyword-regexp-format
6547 org-todo-regexp)
6548 '(2 (org-get-todo-face 2) t))
6549 ;; DONE
6550 (if org-fontify-done-headline
6551 (list (format org-heading-keyword-regexp-format
6552 (concat
6553 "\\(?:"
6554 (mapconcat 'regexp-quote org-done-keywords "\\|")
6555 "\\)"))
6556 '(2 'org-headline-done t))
6557 nil)
6558 ;; Priorities
6559 '(org-font-lock-add-priority-faces)
6560 ;; Tags
6561 '(org-font-lock-add-tag-faces)
6562 ;; Tags groups
6563 (when (and org-group-tags org-tag-groups-alist)
6564 (list (concat org-outline-regexp-bol ".+\\(:"
6565 (regexp-opt (mapcar 'car org-tag-groups-alist))
6566 ":\\).*$")
6567 '(1 'org-tag-group prepend)))
6568 ;; Special keywords
6569 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6570 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6571 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6572 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6573 ;; Emphasis
6574 (when em '(org-do-emphasis-faces))
6575 ;; Checkboxes
6576 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6577 1 'org-checkbox prepend)
6578 (when (cdr (assq 'checkbox org-list-automatic-rules))
6579 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6580 (0 (org-get-checkbox-statistics-face) t)))
6581 ;; Description list items
6582 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6583 1 'org-list-dt prepend)
6584 ;; ARCHIVEd headings
6585 (list (concat
6586 org-outline-regexp-bol
6587 "\\(.*:" org-archive-tag ":.*\\)")
6588 '(1 'org-archived prepend))
6589 ;; Specials
6590 '(org-do-latex-and-related)
6591 '(org-fontify-entities)
6592 '(org-raise-scripts)
6593 ;; Code
6594 '(org-activate-code (1 'org-code t))
6595 ;; COMMENT
6596 (list (format
6597 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6598 org-todo-regexp
6599 org-comment-string)
6600 '(9 'org-special-keyword t))
6601 ;; Blocks and meta lines
6602 '(org-fontify-meta-lines-and-blocks))))
6603 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6604 (run-hooks 'org-font-lock-set-keywords-hook)
6605 ;; Now set the full font-lock-keywords
6606 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6607 (setq-local font-lock-defaults
6608 '(org-font-lock-keywords t nil nil backward-paragraph))
6609 (kill-local-variable 'font-lock-keywords)
6610 nil))
6612 (defun org-toggle-pretty-entities ()
6613 "Toggle the composition display of entities as UTF8 characters."
6614 (interactive)
6615 (setq-local org-pretty-entities (not org-pretty-entities))
6616 (org-restart-font-lock)
6617 (if org-pretty-entities
6618 (message "Entities are now displayed as UTF8 characters")
6619 (save-restriction
6620 (widen)
6621 (decompose-region (point-min) (point-max))
6622 (message "Entities are now displayed as plain text"))))
6624 (defvar-local org-custom-properties-overlays nil
6625 "List of overlays used for custom properties.")
6627 (defun org-toggle-custom-properties-visibility ()
6628 "Display or hide properties in `org-custom-properties'."
6629 (interactive)
6630 (if org-custom-properties-overlays
6631 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6632 (setq org-custom-properties-overlays nil))
6633 (when org-custom-properties
6634 (org-with-wide-buffer
6635 (goto-char (point-min))
6636 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6637 (while (re-search-forward regexp nil t)
6638 (let ((end (cdr (save-match-data (org-get-property-block)))))
6639 (when (and end (< (point) end))
6640 ;; Hide first custom property in current drawer.
6641 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6642 (overlay-put o 'invisible t)
6643 (overlay-put o 'org-custom-property t)
6644 (push o org-custom-properties-overlays))
6645 ;; Hide additional custom properties in the same drawer.
6646 (while (re-search-forward regexp end t)
6647 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6648 (overlay-put o 'invisible t)
6649 (overlay-put o 'org-custom-property t)
6650 (push o org-custom-properties-overlays)))))
6651 ;; Each entry is limited to a single property drawer.
6652 (outline-next-heading)))))))
6654 (defun org-fontify-entities (limit)
6655 "Find an entity to fontify."
6656 (let (ee)
6657 (when org-pretty-entities
6658 (catch 'match
6659 ;; "\_ "-family is left out on purpose. Only the first one,
6660 ;; i.e., "\_ ", could be fontified anyway, and it would be
6661 ;; confusing when adding a second white space character.
6662 (while (re-search-forward
6663 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6664 limit t)
6665 (when (and (not (org-at-comment-p))
6666 (setq ee (org-entity-get (match-string 1)))
6667 (= (length (nth 6 ee)) 1))
6668 (let* ((end (if (equal (match-string 2) "{}")
6669 (match-end 2)
6670 (match-end 1))))
6671 (add-text-properties
6672 (match-beginning 0) end
6673 (list 'font-lock-fontified t))
6674 (compose-region (match-beginning 0) end
6675 (nth 6 ee) nil)
6676 (backward-char 1)
6677 (throw 'match t))))
6678 nil))))
6680 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6681 "Fontify string S like in Org-mode."
6682 (with-temp-buffer
6683 (insert s)
6684 (let ((org-odd-levels-only odd-levels))
6685 (org-mode)
6686 (org-font-lock-ensure)
6687 (buffer-string))))
6689 (defvar org-m nil)
6690 (defvar org-l nil)
6691 (defvar org-f nil)
6692 (defun org-get-level-face (n)
6693 "Get the right face for match N in font-lock matching of headlines."
6694 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6695 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6696 (if org-cycle-level-faces
6697 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6698 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6699 (cond
6700 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6701 ((eq n 2) org-f)
6702 (t (unless org-level-color-stars-only org-f))))
6704 (defun org-face-from-face-or-color (context inherit face-or-color)
6705 "Create a face list that inherits INHERIT, but sets the foreground color.
6706 When FACE-OR-COLOR is not a string, just return it."
6707 (if (stringp face-or-color)
6708 (list :inherit inherit
6709 (cdr (assoc context org-faces-easy-properties))
6710 face-or-color)
6711 face-or-color))
6713 (defun org-get-todo-face (kwd)
6714 "Get the right face for a TODO keyword KWD.
6715 If KWD is a number, get the corresponding match group."
6716 (when (numberp kwd) (setq kwd (match-string kwd)))
6717 (or (org-face-from-face-or-color
6718 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6719 (and (member kwd org-done-keywords) 'org-done)
6720 'org-todo))
6722 (defun org-get-priority-face (priority)
6723 "Get the right face for PRIORITY.
6724 PRIORITY is a character."
6725 (or (org-face-from-face-or-color
6726 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6727 'org-priority))
6729 (defun org-get-tag-face (tag)
6730 "Get the right face for TAG.
6731 If TAG is a number, get the corresponding match group."
6732 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6733 (or (org-face-from-face-or-color
6734 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6735 'org-tag)))
6737 (defun org-font-lock-add-priority-faces (limit)
6738 "Add the special priority faces."
6739 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6740 (add-text-properties
6741 (match-beginning 1) (match-end 1)
6742 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6743 'font-lock-fontified t))))
6745 (defun org-font-lock-add-tag-faces (limit)
6746 "Add the special tag faces."
6747 (when (and org-tag-faces org-tags-special-faces-re)
6748 (while (re-search-forward org-tags-special-faces-re limit t)
6749 (add-text-properties (match-beginning 1) (match-end 1)
6750 (list 'face (org-get-tag-face 1)
6751 'font-lock-fontified t))
6752 (backward-char 1))))
6754 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6755 "Remove fontification and activation overlays from links."
6756 (font-lock-default-unfontify-region beg end)
6757 (let* ((buffer-undo-list t)
6758 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6759 (inhibit-modification-hooks t)
6760 deactivate-mark buffer-file-name buffer-file-truename)
6761 (decompose-region beg end)
6762 (remove-text-properties beg end
6763 '(mouse-face t keymap t org-linked-text t
6764 invisible t intangible t
6765 org-emphasis t))
6766 (org-remove-font-lock-display-properties beg end)))
6768 (defconst org-script-display '(((raise -0.3) (height 0.7))
6769 ((raise 0.3) (height 0.7))
6770 ((raise -0.5))
6771 ((raise 0.5)))
6772 "Display properties for showing superscripts and subscripts.")
6774 (defun org-remove-font-lock-display-properties (beg end)
6775 "Remove specific display properties that have been added by font lock.
6776 The will remove the raise properties that are used to show superscripts
6777 and subscripts."
6778 (let (next prop)
6779 (while (< beg end)
6780 (setq next (next-single-property-change beg 'display nil end)
6781 prop (get-text-property beg 'display))
6782 (when (member prop org-script-display)
6783 (put-text-property beg next 'display nil))
6784 (setq beg next))))
6786 (defun org-raise-scripts (limit)
6787 "Add raise properties to sub/superscripts."
6788 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6789 (re-search-forward
6790 (if (eq org-use-sub-superscripts t)
6791 org-match-substring-regexp
6792 org-match-substring-with-braces-regexp)
6793 limit t))
6794 (let* ((pos (point)) table-p comment-p
6795 (mpos (match-beginning 3))
6796 (emph-p (get-text-property mpos 'org-emphasis))
6797 (link-p (get-text-property mpos 'mouse-face))
6798 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6799 (goto-char (point-at-bol))
6800 (setq table-p (looking-at-p org-table-dataline-regexp)
6801 comment-p (looking-at-p "^[ \t]*#[ +]"))
6802 (goto-char pos)
6803 ;; Handle a_b^c
6804 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6805 (unless (or comment-p emph-p link-p keyw-p)
6806 (put-text-property (match-beginning 3) (match-end 0)
6807 'display
6808 (if (equal (char-after (match-beginning 2)) ?^)
6809 (nth (if table-p 3 1) org-script-display)
6810 (nth (if table-p 2 0) org-script-display)))
6811 (add-text-properties (match-beginning 2) (match-end 2)
6812 (list 'invisible t
6813 'org-dwidth t 'org-dwidth-n 1))
6814 (if (and (eq (char-after (match-beginning 3)) ?{)
6815 (eq (char-before (match-end 3)) ?}))
6816 (progn
6817 (add-text-properties
6818 (match-beginning 3) (1+ (match-beginning 3))
6819 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6820 (add-text-properties
6821 (1- (match-end 3)) (match-end 3)
6822 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6823 t)))
6825 ;;;; Visibility cycling, including org-goto and indirect buffer
6827 ;;; Cycling
6829 (defvar-local org-cycle-global-status nil)
6830 (put 'org-cycle-global-status 'org-state t)
6831 (defvar-local org-cycle-subtree-status nil)
6832 (put 'org-cycle-subtree-status 'org-state t)
6834 (defvar org-inlinetask-min-level)
6836 (defun org-unlogged-message (&rest args)
6837 "Display a message, but avoid logging it in the *Messages* buffer."
6838 (let ((message-log-max nil))
6839 (apply 'message args)))
6841 ;;;###autoload
6842 (defun org-cycle (&optional arg)
6843 "TAB-action and visibility cycling for Org-mode.
6845 This is the command invoked in Org-mode by the TAB key. Its main purpose
6846 is outline visibility cycling, but it also invokes other actions
6847 in special contexts.
6849 - When this function is called with a prefix argument, rotate the entire
6850 buffer through 3 states (global cycling)
6851 1. OVERVIEW: Show only top-level headlines.
6852 2. CONTENTS: Show all headlines of all levels, but no body text.
6853 3. SHOW ALL: Show everything.
6854 With a double \\[universal-argument] prefix argument, \
6855 switch to the startup visibility,
6856 determined by the variable `org-startup-folded', and by any VISIBILITY
6857 properties in the buffer.
6858 With a triple \\[universal-argument] prefix argument, \
6859 show the entire buffer, including any drawers.
6861 - When inside a table, re-align the table and move to the next field.
6863 - When point is at the beginning of a headline, rotate the subtree started
6864 by this line through 3 different states (local cycling)
6865 1. FOLDED: Only the main headline is shown.
6866 2. CHILDREN: The main headline and the direct children are shown.
6867 From this state, you can move to one of the children
6868 and zoom in further.
6869 3. SUBTREE: Show the entire subtree, including body text.
6870 If there is no subtree, switch directly from CHILDREN to FOLDED.
6872 - When point is at the beginning of an empty headline and the variable
6873 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6874 of the headline by demoting and promoting it to likely levels. This
6875 speeds up creation document structure by pressing TAB once or several
6876 times right after creating a new headline.
6878 - When there is a numeric prefix, go up to a heading with level ARG, do
6879 a `show-subtree' and return to the previous cursor position. If ARG
6880 is negative, go up that many levels.
6882 - When point is not at the beginning of a headline, execute the global
6883 binding for TAB, which is re-indenting the line. See the option
6884 `org-cycle-emulate-tab' for details.
6886 - Special case: if point is at the beginning of the buffer and there is
6887 no headline in line 1, this function will act as if called with prefix arg
6888 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6889 But only if also the variable `org-cycle-global-at-bob' is t."
6890 (interactive "P")
6891 (org-load-modules-maybe)
6892 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6893 (and org-cycle-level-after-item/entry-creation
6894 (or (org-cycle-level)
6895 (org-cycle-item-indentation))))
6896 (let* ((limit-level
6897 (or org-cycle-max-level
6898 (and (boundp 'org-inlinetask-min-level)
6899 org-inlinetask-min-level
6900 (1- org-inlinetask-min-level))))
6901 (nstars (and limit-level
6902 (if org-odd-levels-only
6903 (and limit-level (1- (* limit-level 2)))
6904 limit-level)))
6905 (org-outline-regexp
6906 (if (not (derived-mode-p 'org-mode))
6907 outline-regexp
6908 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6909 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6910 (not (looking-at org-outline-regexp))))
6911 (org-cycle-hook
6912 (if bob-special
6913 (delq 'org-optimize-window-after-visibility-change
6914 (copy-sequence org-cycle-hook))
6915 org-cycle-hook))
6916 (pos (point)))
6918 (when (or bob-special (equal arg '(4)))
6919 ;; special case: use global cycling
6920 (setq arg t))
6922 (cond
6924 ((equal arg '(16))
6925 (setq last-command 'dummy)
6926 (org-set-startup-visibility)
6927 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6929 ((equal arg '(64))
6930 (outline-show-all)
6931 (org-unlogged-message "Entire buffer visible, including drawers"))
6933 ;; Try cdlatex TAB completion
6934 ((org-try-cdlatex-tab))
6936 ;; Table: enter it or move to the next field.
6937 ((org-at-table-p 'any)
6938 (if (org-at-table.el-p)
6939 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6940 Use \\[org-edit-special] to edit table.el tables"))
6941 (if arg (org-table-edit-field t)
6942 (org-table-justify-field-maybe)
6943 (call-interactively 'org-table-next-field))))
6945 ((run-hook-with-args-until-success
6946 'org-tab-after-check-for-table-hook))
6948 ;; Global cycling: delegate to `org-cycle-internal-global'.
6949 ((eq arg t) (org-cycle-internal-global))
6951 ;; Drawers: delegate to `org-flag-drawer'.
6952 ((save-excursion
6953 (beginning-of-line 1)
6954 (looking-at org-drawer-regexp))
6955 (org-flag-drawer ; toggle block visibility
6956 (not (get-char-property (match-end 0) 'invisible))))
6958 ;; Show-subtree, ARG levels up from here.
6959 ((integerp arg)
6960 (save-excursion
6961 (org-back-to-heading)
6962 (outline-up-heading (if (< arg 0) (- arg)
6963 (- (funcall outline-level) arg)))
6964 (org-show-subtree)))
6966 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6967 ((and (featurep 'org-inlinetask)
6968 (org-inlinetask-at-task-p)
6969 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6970 (org-inlinetask-toggle-visibility))
6972 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6973 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6974 (save-excursion (move-beginning-of-line 1)
6975 (looking-at org-outline-regexp)))
6976 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6977 (org-cycle-internal-local))
6979 ;; From there: TAB emulation and template completion.
6980 (buffer-read-only (org-back-to-heading))
6982 ((run-hook-with-args-until-success
6983 'org-tab-after-check-for-cycling-hook))
6985 ((org-try-structure-completion))
6987 ((run-hook-with-args-until-success
6988 'org-tab-before-tab-emulation-hook))
6990 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6991 (or (not (bolp))
6992 (not (looking-at org-outline-regexp))))
6993 (call-interactively (global-key-binding "\t")))
6995 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6996 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6997 (or (and (eq org-cycle-emulate-tab 'white)
6998 (= (match-end 0) (point-at-eol)))
6999 (and (eq org-cycle-emulate-tab 'whitestart)
7000 (>= (match-end 0) pos))))
7002 (eq org-cycle-emulate-tab t))
7003 (call-interactively (global-key-binding "\t")))
7005 (t (save-excursion
7006 (org-back-to-heading)
7007 (org-cycle)))))))
7009 (defun org-cycle-internal-global ()
7010 "Do the global cycling action."
7011 ;; Hack to avoid display of messages for .org attachments in Gnus
7012 (let ((ga (string-match "\\*fontification" (buffer-name))))
7013 (cond
7014 ((and (eq last-command this-command)
7015 (eq org-cycle-global-status 'overview))
7016 ;; We just created the overview - now do table of contents
7017 ;; This can be slow in very large buffers, so indicate action
7018 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7019 (unless ga (org-unlogged-message "CONTENTS..."))
7020 (org-content)
7021 (unless ga (org-unlogged-message "CONTENTS...done"))
7022 (setq org-cycle-global-status 'contents)
7023 (run-hook-with-args 'org-cycle-hook 'contents))
7025 ((and (eq last-command this-command)
7026 (eq org-cycle-global-status 'contents))
7027 ;; We just showed the table of contents - now show everything
7028 (run-hook-with-args 'org-pre-cycle-hook 'all)
7029 (outline-show-all)
7030 (unless ga (org-unlogged-message "SHOW ALL"))
7031 (setq org-cycle-global-status 'all)
7032 (run-hook-with-args 'org-cycle-hook 'all))
7035 ;; Default action: go to overview
7036 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7037 (org-overview)
7038 (unless ga (org-unlogged-message "OVERVIEW"))
7039 (setq org-cycle-global-status 'overview)
7040 (run-hook-with-args 'org-cycle-hook 'overview)))))
7042 (defvar org-called-with-limited-levels nil
7043 "Non-nil when `org-with-limited-levels' is currently active.")
7045 (defun org-cycle-internal-local ()
7046 "Do the local cycling action."
7047 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7048 ;; First, determine end of headline (EOH), end of subtree or item
7049 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7050 (save-excursion
7051 (if (org-at-item-p)
7052 (progn
7053 (beginning-of-line)
7054 (setq struct (org-list-struct))
7055 (setq eoh (point-at-eol))
7056 (setq eos (org-list-get-item-end-before-blank (point) struct))
7057 (setq has-children (org-list-has-child-p (point) struct)))
7058 (org-back-to-heading)
7059 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7060 (setq eos (save-excursion (org-end-of-subtree t t)
7061 (when (bolp) (backward-char)) (point)))
7062 (setq has-children
7063 (or (save-excursion
7064 (let ((level (funcall outline-level)))
7065 (outline-next-heading)
7066 (and (org-at-heading-p t)
7067 (> (funcall outline-level) level))))
7068 (save-excursion
7069 (org-list-search-forward (org-item-beginning-re) eos t)))))
7070 ;; Determine end invisible part of buffer (EOL)
7071 (beginning-of-line 2)
7072 (while (and (not (eobp)) ;This is like `next-line'.
7073 (get-char-property (1- (point)) 'invisible))
7074 (goto-char (next-single-char-property-change (point) 'invisible))
7075 (and (eolp) (beginning-of-line 2)))
7076 (setq eol (point)))
7077 ;; Find out what to do next and set `this-command'
7078 (cond
7079 ((= eos eoh)
7080 ;; Nothing is hidden behind this heading
7081 (unless (org-before-first-heading-p)
7082 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7083 (org-unlogged-message "EMPTY ENTRY")
7084 (setq org-cycle-subtree-status nil)
7085 (save-excursion
7086 (goto-char eos)
7087 (outline-next-heading)
7088 (when (outline-invisible-p) (org-flag-heading nil))))
7089 ((and (or (>= eol eos)
7090 (not (string-match "\\S-" (buffer-substring eol eos))))
7091 (or has-children
7092 (not (setq children-skipped
7093 org-cycle-skip-children-state-if-no-children))))
7094 ;; Entire subtree is hidden in one line: children view
7095 (unless (org-before-first-heading-p)
7096 (run-hook-with-args 'org-pre-cycle-hook 'children))
7097 (if (org-at-item-p)
7098 (org-list-set-item-visibility (point-at-bol) struct 'children)
7099 (org-show-entry)
7100 (org-with-limited-levels (org-show-children))
7101 ;; FIXME: This slows down the func way too much.
7102 ;; How keep drawers hidden in subtree anyway?
7103 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7104 ;; (org-cycle-hide-drawers 'subtree))
7106 ;; Fold every list in subtree to top-level items.
7107 (when (eq org-cycle-include-plain-lists 'integrate)
7108 (save-excursion
7109 (org-back-to-heading)
7110 (while (org-list-search-forward (org-item-beginning-re) eos t)
7111 (beginning-of-line 1)
7112 (let* ((struct (org-list-struct))
7113 (prevs (org-list-prevs-alist struct))
7114 (end (org-list-get-bottom-point struct)))
7115 (dolist (e (org-list-get-all-items (point) struct prevs))
7116 (org-list-set-item-visibility e struct 'folded))
7117 (goto-char (if (< end eos) end eos)))))))
7118 (org-unlogged-message "CHILDREN")
7119 (save-excursion
7120 (goto-char eos)
7121 (outline-next-heading)
7122 (when (outline-invisible-p) (org-flag-heading nil)))
7123 (setq org-cycle-subtree-status 'children)
7124 (unless (org-before-first-heading-p)
7125 (run-hook-with-args 'org-cycle-hook 'children)))
7126 ((or children-skipped
7127 (and (eq last-command this-command)
7128 (eq org-cycle-subtree-status 'children)))
7129 ;; We just showed the children, or no children are there,
7130 ;; now show everything.
7131 (unless (org-before-first-heading-p)
7132 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7133 (outline-flag-region eoh eos nil)
7134 (org-unlogged-message
7135 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7136 (setq org-cycle-subtree-status 'subtree)
7137 (unless (org-before-first-heading-p)
7138 (run-hook-with-args 'org-cycle-hook 'subtree)))
7140 ;; Default action: hide the subtree.
7141 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7142 (outline-flag-region eoh eos t)
7143 (org-unlogged-message "FOLDED")
7144 (setq org-cycle-subtree-status 'folded)
7145 (unless (org-before-first-heading-p)
7146 (run-hook-with-args 'org-cycle-hook 'folded))))))
7148 ;;;###autoload
7149 (defun org-global-cycle (&optional arg)
7150 "Cycle the global visibility. For details see `org-cycle'.
7151 With \\[universal-argument] prefix arg, switch to startup visibility.
7152 With a numeric prefix, show all headlines up to that level."
7153 (interactive "P")
7154 (let ((org-cycle-include-plain-lists
7155 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7156 (cond
7157 ((integerp arg)
7158 (outline-show-all)
7159 (outline-hide-sublevels arg)
7160 (setq org-cycle-global-status 'contents))
7161 ((equal arg '(4))
7162 (org-set-startup-visibility)
7163 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7165 (org-cycle '(4))))))
7167 (defun org-set-startup-visibility ()
7168 "Set the visibility required by startup options and properties."
7169 (cond
7170 ((eq org-startup-folded t)
7171 (org-overview))
7172 ((eq org-startup-folded 'content)
7173 (org-content))
7174 ((or (eq org-startup-folded 'showeverything)
7175 (eq org-startup-folded nil))
7176 (outline-show-all)))
7177 (unless (eq org-startup-folded 'showeverything)
7178 (when org-hide-block-startup (org-hide-block-all))
7179 (org-set-visibility-according-to-property 'no-cleanup)
7180 (org-cycle-hide-archived-subtrees 'all)
7181 (org-cycle-hide-drawers 'all)
7182 (org-cycle-show-empty-lines t)))
7184 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7185 "Switch subtree visibilities according to :VISIBILITY: property."
7186 (interactive)
7187 (org-with-wide-buffer
7188 (goto-char (point-min))
7189 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7190 (if (not (org-at-property-p)) (outline-next-heading)
7191 (let ((state (match-string 3)))
7192 (save-excursion
7193 (org-back-to-heading t)
7194 (outline-hide-subtree)
7195 (org-reveal)
7196 (cond
7197 ((equal state "folded")
7198 (outline-hide-subtree))
7199 ((equal state "children")
7200 (org-show-hidden-entry)
7201 (org-show-children))
7202 ((equal state "content")
7203 (save-excursion
7204 (save-restriction
7205 (org-narrow-to-subtree)
7206 (org-content))))
7207 ((member state '("all" "showall"))
7208 (outline-show-subtree)))))))
7209 (unless no-cleanup
7210 (org-cycle-hide-archived-subtrees 'all)
7211 (org-cycle-hide-drawers 'all)
7212 (org-cycle-show-empty-lines 'all))))
7214 ;; This function uses outline-regexp instead of the more fundamental
7215 ;; org-outline-regexp so that org-cycle-global works outside of Org
7216 ;; buffers, where outline-regexp is needed.
7217 (defun org-overview ()
7218 "Switch to overview mode, showing only top-level headlines.
7219 This shows all headlines with a level equal or greater than the level
7220 of the first headline in the buffer. This is important, because if the
7221 first headline is not level one, then (hide-sublevels 1) gives confusing
7222 results."
7223 (interactive)
7224 (save-excursion
7225 (let ((level
7226 (save-excursion
7227 (goto-char (point-min))
7228 (when (re-search-forward (concat "^" outline-regexp) nil t)
7229 (goto-char (match-beginning 0))
7230 (funcall outline-level)))))
7231 (and level (outline-hide-sublevels level)))))
7233 (defun org-content (&optional arg)
7234 "Show all headlines in the buffer, like a table of contents.
7235 With numerical argument N, show content up to level N."
7236 (interactive "P")
7237 (org-overview)
7238 (save-excursion
7239 ;; Visit all headings and show their offspring
7240 (and (integerp arg) (org-overview))
7241 (goto-char (point-max))
7242 (catch 'exit
7243 (while (and (progn (condition-case nil
7244 (outline-previous-visible-heading 1)
7245 (error (goto-char (point-min))))
7247 (looking-at org-outline-regexp))
7248 (if (integerp arg)
7249 (org-show-children (1- arg))
7250 (outline-show-branches))
7251 (when (bobp) (throw 'exit nil))))))
7253 (defun org-optimize-window-after-visibility-change (state)
7254 "Adjust the window after a change in outline visibility.
7255 This function is the default value of the hook `org-cycle-hook'."
7256 (when (get-buffer-window (current-buffer))
7257 (cond
7258 ((eq state 'content) nil)
7259 ((eq state 'all) nil)
7260 ((eq state 'folded) nil)
7261 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7262 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7264 (defun org-remove-empty-overlays-at (pos)
7265 "Remove outline overlays that do not contain non-white stuff."
7266 (dolist (o (overlays-at pos))
7267 (and (eq 'outline (overlay-get o 'invisible))
7268 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7269 (overlay-end o))))
7270 (delete-overlay o))))
7272 (defun org-clean-visibility-after-subtree-move ()
7273 "Fix visibility issues after moving a subtree."
7274 ;; First, find a reasonable region to look at:
7275 ;; Start two siblings above, end three below
7276 (let* ((beg (save-excursion
7277 (and (org-get-last-sibling)
7278 (org-get-last-sibling))
7279 (point)))
7280 (end (save-excursion
7281 (and (org-get-next-sibling)
7282 (org-get-next-sibling)
7283 (org-get-next-sibling))
7284 (if (org-at-heading-p)
7285 (point-at-eol)
7286 (point))))
7287 (level (looking-at "\\*+"))
7288 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7289 (save-excursion
7290 (save-restriction
7291 (narrow-to-region beg end)
7292 (when re
7293 ;; Properly fold already folded siblings
7294 (goto-char (point-min))
7295 (while (re-search-forward re nil t)
7296 (when (and (not (outline-invisible-p))
7297 (save-excursion
7298 (goto-char (point-at-eol)) (outline-invisible-p)))
7299 (outline-hide-entry))))
7300 (org-cycle-show-empty-lines 'overview)
7301 (org-cycle-hide-drawers 'overview)))))
7303 (defun org-cycle-show-empty-lines (state)
7304 "Show empty lines above all visible headlines.
7305 The region to be covered depends on STATE when called through
7306 `org-cycle-hook'. Lisp program can use t for STATE to get the
7307 entire buffer covered. Note that an empty line is only shown if there
7308 are at least `org-cycle-separator-lines' empty lines before the headline."
7309 (when (/= org-cycle-separator-lines 0)
7310 (save-excursion
7311 (let* ((n (abs org-cycle-separator-lines))
7312 (re (cond
7313 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7314 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7315 (t (let ((ns (number-to-string (- n 2))))
7316 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7317 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7318 beg end)
7319 (cond
7320 ((memq state '(overview contents t))
7321 (setq beg (point-min) end (point-max)))
7322 ((memq state '(children folded))
7323 (setq beg (point)
7324 end (progn (org-end-of-subtree t t)
7325 (line-beginning-position 2)))))
7326 (when beg
7327 (goto-char beg)
7328 (while (re-search-forward re end t)
7329 (unless (get-char-property (match-end 1) 'invisible)
7330 (let ((e (match-end 1))
7331 (b (if (>= org-cycle-separator-lines 0)
7332 (match-beginning 1)
7333 (save-excursion
7334 (goto-char (match-beginning 0))
7335 (skip-chars-backward " \t\n")
7336 (line-end-position)))))
7337 (outline-flag-region b e nil))))))))
7338 ;; Never hide empty lines at the end of the file.
7339 (save-excursion
7340 (goto-char (point-max))
7341 (outline-previous-heading)
7342 (outline-end-of-heading)
7343 (when (and (looking-at "[ \t\n]+")
7344 (= (match-end 0) (point-max)))
7345 (outline-flag-region (point) (match-end 0) nil))))
7347 (defun org-show-empty-lines-in-parent ()
7348 "Move to the parent and re-show empty lines before visible headlines."
7349 (save-excursion
7350 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7351 (org-cycle-show-empty-lines context))))
7353 (defun org-files-list ()
7354 "Return `org-agenda-files' list, plus all open org-mode files.
7355 This is useful for operations that need to scan all of a user's
7356 open and agenda-wise Org files."
7357 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7358 (dolist (buf (buffer-list))
7359 (with-current-buffer buf
7360 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7361 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7362 files))
7364 (defsubst org-entry-beginning-position ()
7365 "Return the beginning position of the current entry."
7366 (save-excursion (org-back-to-heading t) (point)))
7368 (defsubst org-entry-end-position ()
7369 "Return the end position of the current entry."
7370 (save-excursion (outline-next-heading) (point)))
7372 (defun org-cycle-hide-drawers (state &optional exceptions)
7373 "Re-hide all drawers after a visibility state change.
7374 When non-nil, optional argument EXCEPTIONS is a list of strings
7375 specifying which drawers should not be hidden."
7376 (when (and (derived-mode-p 'org-mode)
7377 (not (memq state '(overview folded contents))))
7378 (save-excursion
7379 (let* ((globalp (memq state '(contents all)))
7380 (beg (if globalp (point-min) (point)))
7381 (end (if globalp (point-max)
7382 (if (eq state 'children)
7383 (save-excursion (outline-next-heading) (point))
7384 (org-end-of-subtree t)))))
7385 (goto-char beg)
7386 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7387 (unless (member-ignore-case (match-string 1) exceptions)
7388 (let ((drawer (org-element-at-point)))
7389 (when (memq (org-element-type drawer) '(drawer property-drawer))
7390 (org-flag-drawer t drawer)
7391 ;; Make sure to skip drawer entirely or we might flag
7392 ;; it another time when matching its ending line with
7393 ;; `org-drawer-regexp'.
7394 (goto-char (org-element-property :end drawer))))))))))
7396 (defun org-flag-drawer (flag &optional element)
7397 "When FLAG is non-nil, hide the drawer we are at.
7398 Otherwise make it visible. When optional argument ELEMENT is
7399 a parsed drawer, as returned by `org-element-at-point', hide or
7400 show that drawer instead."
7401 (let ((drawer (or element
7402 (and (save-excursion
7403 (beginning-of-line)
7404 (looking-at-p org-drawer-regexp))
7405 (org-element-at-point)))))
7406 (when (memq (org-element-type drawer) '(drawer property-drawer))
7407 (let ((post (org-element-property :post-affiliated drawer)))
7408 (save-excursion
7409 (outline-flag-region
7410 (progn (goto-char post) (line-end-position))
7411 (progn (goto-char (org-element-property :end drawer))
7412 (skip-chars-backward " \r\t\n")
7413 (line-end-position))
7414 flag))
7415 ;; When the drawer is hidden away, make sure point lies in
7416 ;; a visible part of the buffer.
7417 (when (and flag (> (line-beginning-position) post))
7418 (goto-char post))))))
7420 (defun org-subtree-end-visible-p ()
7421 "Is the end of the current subtree visible?"
7422 (pos-visible-in-window-p
7423 (save-excursion (org-end-of-subtree t) (point))))
7425 (defun org-first-headline-recenter ()
7426 "Move cursor to the first headline and recenter the headline."
7427 (let ((window (get-buffer-window)))
7428 (when window
7429 (goto-char (point-min))
7430 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7431 (set-window-start window (line-beginning-position))))))
7433 ;;; Saving and restoring visibility
7435 (defun org-outline-overlay-data (&optional use-markers)
7436 "Return a list of the locations of all outline overlays.
7437 These are overlays with the `invisible' property value `outline'.
7438 The return value is a list of cons cells, with start and stop
7439 positions for each overlay.
7440 If USE-MARKERS is set, return the positions as markers."
7441 (let (beg end)
7442 (save-excursion
7443 (save-restriction
7444 (widen)
7445 (delq nil
7446 (mapcar (lambda (o)
7447 (when (eq (overlay-get o 'invisible) 'outline)
7448 (setq beg (overlay-start o)
7449 end (overlay-end o))
7450 (and beg end (> end beg)
7451 (if use-markers
7452 (cons (copy-marker beg)
7453 (copy-marker end t))
7454 (cons beg end)))))
7455 (overlays-in (point-min) (point-max))))))))
7457 (defun org-set-outline-overlay-data (data)
7458 "Create visibility overlays for all positions in DATA.
7459 DATA should have been made by `org-outline-overlay-data'."
7460 (org-with-wide-buffer
7461 (outline-show-all)
7462 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7464 ;;; Folding of blocks
7466 (defvar-local org-hide-block-overlays nil
7467 "Overlays hiding blocks.")
7469 (defun org-block-map (function &optional start end)
7470 "Call FUNCTION at the head of all source blocks in the current buffer.
7471 Optional arguments START and END can be used to limit the range."
7472 (let ((start (or start (point-min)))
7473 (end (or end (point-max))))
7474 (save-excursion
7475 (goto-char start)
7476 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7477 (save-excursion
7478 (save-match-data
7479 (goto-char (match-beginning 0))
7480 (funcall function)))))))
7482 (defun org-hide-block-toggle-all ()
7483 "Toggle the visibility of all blocks in the current buffer."
7484 (org-block-map 'org-hide-block-toggle))
7486 (defun org-hide-block-all ()
7487 "Fold all blocks in the current buffer."
7488 (interactive)
7489 (org-show-block-all)
7490 (org-block-map 'org-hide-block-toggle-maybe))
7492 (defun org-show-block-all ()
7493 "Unfold all blocks in the current buffer."
7494 (interactive)
7495 (mapc #'delete-overlay org-hide-block-overlays)
7496 (setq org-hide-block-overlays nil))
7498 (defun org-hide-block-toggle-maybe ()
7499 "Toggle visibility of block at point.
7500 Unlike to `org-hide-block-toggle', this function does not throw
7501 an error. Return a non-nil value when toggling is successful."
7502 (interactive)
7503 (ignore-errors (org-hide-block-toggle)))
7505 (defun org-hide-block-toggle (&optional force)
7506 "Toggle the visibility of the current block.
7507 When optional argument FORCE is `off', make block visible. If it
7508 is non-nil, hide it unconditionally. Throw an error when not at
7509 a block. Return a non-nil value when toggling is successful."
7510 (interactive)
7511 (let ((element (org-element-at-point)))
7512 (unless (memq (org-element-type element)
7513 '(center-block comment-block dynamic-block example-block
7514 export-block quote-block special-block
7515 src-block verse-block))
7516 (user-error "Not at a block"))
7517 (let* ((start (save-excursion
7518 (goto-char (org-element-property :post-affiliated element))
7519 (line-end-position)))
7520 (end (save-excursion
7521 (goto-char (org-element-property :end element))
7522 (skip-chars-backward " \r\t\n")
7523 (line-end-position)))
7524 (overlays (overlays-at start)))
7525 (cond
7526 ;; Do nothing when not before or at the block opening line or
7527 ;; at the block closing line.
7528 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7529 ((and (not (eq force 'off))
7530 (not (memq t (mapcar
7531 (lambda (o)
7532 (eq (overlay-get o 'invisible) 'org-hide-block))
7533 overlays))))
7534 (let ((ov (make-overlay start end)))
7535 (overlay-put ov 'invisible 'org-hide-block)
7536 ;; Make the block accessible to `isearch'.
7537 (overlay-put
7538 ov 'isearch-open-invisible
7539 (lambda (ov)
7540 (when (memq ov org-hide-block-overlays)
7541 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7542 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7543 (delete-overlay ov))))
7544 (push ov org-hide-block-overlays)
7545 ;; When the block is hidden away, make sure point is left in
7546 ;; a visible part of the buffer.
7547 (when (> (line-beginning-position) start)
7548 (goto-char start)
7549 (beginning-of-line))
7550 ;; Signal successful toggling.
7552 ((or (not force) (eq force 'off))
7553 (dolist (ov overlays t)
7554 (when (memq ov org-hide-block-overlays)
7555 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7556 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7557 (delete-overlay ov))))))))
7559 ;; org-tab-after-check-for-cycling-hook
7560 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7561 ;; Remove overlays when changing major mode
7562 (add-hook 'org-mode-hook
7563 (lambda () (add-hook 'change-major-mode-hook
7564 'org-show-block-all 'append 'local)))
7566 ;;; Org-goto
7568 (defvar org-goto-window-configuration nil)
7569 (defvar org-goto-marker nil)
7570 (defvar org-goto-map)
7571 (defun org-goto-map ()
7572 "Set the keymap `org-goto'."
7573 (setq org-goto-map
7574 (let ((map (make-sparse-keymap)))
7575 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7576 mouse-drag-region universal-argument org-occur)))
7577 (dolist (cmd cmds)
7578 (substitute-key-definition cmd cmd map global-map)))
7579 (suppress-keymap map)
7580 (org-defkey map "\C-m" 'org-goto-ret)
7581 (org-defkey map [(return)] 'org-goto-ret)
7582 (org-defkey map [(left)] 'org-goto-left)
7583 (org-defkey map [(right)] 'org-goto-right)
7584 (org-defkey map [(control ?g)] 'org-goto-quit)
7585 (org-defkey map "\C-i" 'org-cycle)
7586 (org-defkey map [(tab)] 'org-cycle)
7587 (org-defkey map [(down)] 'outline-next-visible-heading)
7588 (org-defkey map [(up)] 'outline-previous-visible-heading)
7589 (if org-goto-auto-isearch
7590 (if (fboundp 'define-key-after)
7591 (define-key-after map [t] 'org-goto-local-auto-isearch)
7592 nil)
7593 (org-defkey map "q" 'org-goto-quit)
7594 (org-defkey map "n" 'outline-next-visible-heading)
7595 (org-defkey map "p" 'outline-previous-visible-heading)
7596 (org-defkey map "f" 'outline-forward-same-level)
7597 (org-defkey map "b" 'outline-backward-same-level)
7598 (org-defkey map "u" 'outline-up-heading))
7599 (org-defkey map "/" 'org-occur)
7600 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7601 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7602 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7603 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7604 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7605 map)))
7607 (defconst org-goto-help
7608 "Browse buffer copy, to find location or copy text.%s
7609 RET=jump to location C-g=quit and return to previous location
7610 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7612 (defvar org-goto-start-pos) ; dynamically scoped parameter
7614 (defun org-goto (&optional alternative-interface)
7615 "Look up a different location in the current file, keeping current visibility.
7617 When you want look-up or go to a different location in a
7618 document, the fastest way is often to fold the entire buffer and
7619 then dive into the tree. This method has the disadvantage, that
7620 the previous location will be folded, which may not be what you
7621 want.
7623 This command works around this by showing a copy of the current
7624 buffer in an indirect buffer, in overview mode. You can dive
7625 into the tree in that copy, use org-occur and incremental search
7626 to find a location. When pressing RET or `Q', the command
7627 returns to the original buffer in which the visibility is still
7628 unchanged. After RET it will also jump to the location selected
7629 in the indirect buffer and expose the headline hierarchy above.
7631 With a prefix argument, use the alternative interface: e.g., if
7632 `org-goto-interface' is `outline' use `outline-path-completion'."
7633 (interactive "P")
7634 (org-goto-map)
7635 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7636 (org-refile-use-outline-path t)
7637 (org-refile-target-verify-function nil)
7638 (interface
7639 (if (not alternative-interface)
7640 org-goto-interface
7641 (if (eq org-goto-interface 'outline)
7642 'outline-path-completion
7643 'outline)))
7644 (org-goto-start-pos (point))
7645 (selected-point
7646 (if (eq interface 'outline)
7647 (car (org-get-location (current-buffer) org-goto-help))
7648 (let ((pa (org-refile-get-location "Goto")))
7649 (org-refile-check-position pa)
7650 (nth 3 pa)))))
7651 (if selected-point
7652 (progn
7653 (org-mark-ring-push org-goto-start-pos)
7654 (goto-char selected-point)
7655 (when (or (outline-invisible-p) (org-invisible-p2))
7656 (org-show-context 'org-goto)))
7657 (message "Quit"))))
7659 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7660 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7661 (defvar org-goto-local-auto-isearch-map) ; defined below
7663 (defun org-get-location (_buf help)
7664 "Let the user select a location in current buffer.
7665 This function uses a recursive edit. It returns the selected position
7666 or nil."
7667 (org-no-popups
7668 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7669 (isearch-hide-immediately nil)
7670 (isearch-search-fun-function
7671 (lambda () 'org-goto-local-search-headings))
7672 (org-goto-selected-point org-goto-exit-command))
7673 (save-excursion
7674 (save-window-excursion
7675 (delete-other-windows)
7676 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7677 (pop-to-buffer-same-window
7678 (condition-case nil
7679 (make-indirect-buffer (current-buffer) "*org-goto*")
7680 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7681 (with-output-to-temp-buffer "*Org Help*"
7682 (princ (format help (if org-goto-auto-isearch
7683 " Just type for auto-isearch."
7684 " n/p/f/b/u to navigate, q to quit."))))
7685 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7686 (setq buffer-read-only nil)
7687 (let ((org-startup-truncated t)
7688 (org-startup-folded nil)
7689 (org-startup-align-all-tables nil))
7690 (org-mode)
7691 (org-overview))
7692 (setq buffer-read-only t)
7693 (if (and (boundp 'org-goto-start-pos)
7694 (integer-or-marker-p org-goto-start-pos))
7695 (progn (goto-char org-goto-start-pos)
7696 (when (outline-invisible-p)
7697 (org-show-set-visibility 'lineage)))
7698 (goto-char (point-min)))
7699 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7700 (message "Select location and press RET")
7701 (use-local-map org-goto-map)
7702 (recursive-edit)))
7703 (kill-buffer "*org-goto*")
7704 (cons org-goto-selected-point org-goto-exit-command))))
7706 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7707 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7708 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7709 (if (fboundp 'isearch-other-control-char)
7710 (progn
7711 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7712 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7713 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7714 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7715 (define-key org-goto-local-auto-isearch-map [return] nil))
7717 (defun org-goto-local-search-headings (string bound noerror)
7718 "Search and make sure that any matches are in headlines."
7719 (catch 'return
7720 (while (if isearch-forward
7721 (search-forward string bound noerror)
7722 (search-backward string bound noerror))
7723 (when (save-match-data
7724 (and (save-excursion
7725 (beginning-of-line)
7726 (looking-at org-complex-heading-regexp))
7727 (or (not (match-beginning 5))
7728 (< (point) (match-beginning 5)))))
7729 (throw 'return (point))))))
7731 (defun org-goto-local-auto-isearch ()
7732 "Start isearch."
7733 (interactive)
7734 (goto-char (point-min))
7735 (let ((keys (this-command-keys)))
7736 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7737 (isearch-mode t)
7738 (isearch-process-search-char (string-to-char keys)))))
7740 (defun org-goto-ret (&optional _arg)
7741 "Finish `org-goto' by going to the new location."
7742 (interactive "P")
7743 (setq org-goto-selected-point (point))
7744 (setq org-goto-exit-command 'return)
7745 (throw 'exit nil))
7747 (defun org-goto-left ()
7748 "Finish `org-goto' by going to the new location."
7749 (interactive)
7750 (if (org-at-heading-p)
7751 (progn
7752 (beginning-of-line 1)
7753 (setq org-goto-selected-point (point)
7754 org-goto-exit-command 'left)
7755 (throw 'exit nil))
7756 (user-error "Not on a heading")))
7758 (defun org-goto-right ()
7759 "Finish `org-goto' by going to the new location."
7760 (interactive)
7761 (if (org-at-heading-p)
7762 (progn
7763 (setq org-goto-selected-point (point)
7764 org-goto-exit-command 'right)
7765 (throw 'exit nil))
7766 (user-error "Not on a heading")))
7768 (defun org-goto-quit ()
7769 "Finish `org-goto' without cursor motion."
7770 (interactive)
7771 (setq org-goto-selected-point nil)
7772 (setq org-goto-exit-command 'quit)
7773 (throw 'exit nil))
7775 ;;; Indirect buffer display of subtrees
7777 (defvar org-indirect-dedicated-frame nil
7778 "This is the frame being used for indirect tree display.")
7779 (defvar org-last-indirect-buffer nil)
7781 (defun org-tree-to-indirect-buffer (&optional arg)
7782 "Create indirect buffer and narrow it to current subtree.
7783 With a numerical prefix ARG, go up to this level and then take that tree.
7784 If ARG is negative, go up that many levels.
7786 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7787 indirect buffer previously made with this command, to avoid proliferation of
7788 indirect buffers. However, when you call the command with a \
7789 \\[universal-argument] prefix, or
7790 when `org-indirect-buffer-display' is `new-frame', the last buffer
7791 is kept so that you can work with several indirect buffers at the same time.
7792 If `org-indirect-buffer-display' is `dedicated-frame', the \
7793 \\[universal-argument] prefix also
7794 requests that a new frame be made for the new buffer, so that the dedicated
7795 frame is not changed."
7796 (interactive "P")
7797 (let ((cbuf (current-buffer))
7798 (cwin (selected-window))
7799 (pos (point))
7800 beg end level heading ibuf)
7801 (save-excursion
7802 (org-back-to-heading t)
7803 (when (numberp arg)
7804 (setq level (org-outline-level))
7805 (when (< arg 0) (setq arg (+ level arg)))
7806 (while (> (setq level (org-outline-level)) arg)
7807 (org-up-heading-safe)))
7808 (setq beg (point)
7809 heading (org-get-heading 'no-tags))
7810 (org-end-of-subtree t t)
7811 (when (org-at-heading-p) (backward-char 1))
7812 (setq end (point)))
7813 (when (and (buffer-live-p org-last-indirect-buffer)
7814 (not (eq org-indirect-buffer-display 'new-frame))
7815 (not arg))
7816 (kill-buffer org-last-indirect-buffer))
7817 (setq ibuf (org-get-indirect-buffer cbuf heading)
7818 org-last-indirect-buffer ibuf)
7819 (cond
7820 ((or (eq org-indirect-buffer-display 'new-frame)
7821 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7822 (select-frame (make-frame))
7823 (delete-other-windows)
7824 (pop-to-buffer-same-window ibuf)
7825 (org-set-frame-title heading))
7826 ((eq org-indirect-buffer-display 'dedicated-frame)
7827 (raise-frame
7828 (select-frame (or (and org-indirect-dedicated-frame
7829 (frame-live-p org-indirect-dedicated-frame)
7830 org-indirect-dedicated-frame)
7831 (setq org-indirect-dedicated-frame (make-frame)))))
7832 (delete-other-windows)
7833 (pop-to-buffer-same-window ibuf)
7834 (org-set-frame-title (concat "Indirect: " heading)))
7835 ((eq org-indirect-buffer-display 'current-window)
7836 (pop-to-buffer-same-window ibuf))
7837 ((eq org-indirect-buffer-display 'other-window)
7838 (pop-to-buffer ibuf))
7839 (t (error "Invalid value")))
7840 (narrow-to-region beg end)
7841 (outline-show-all)
7842 (goto-char pos)
7843 (run-hook-with-args 'org-cycle-hook 'all)
7844 (and (window-live-p cwin) (select-window cwin))))
7846 (defun org-get-indirect-buffer (&optional buffer heading)
7847 (setq buffer (or buffer (current-buffer)))
7848 (let ((n 1) (base (buffer-name buffer)) bname)
7849 (while (buffer-live-p
7850 (get-buffer
7851 (setq bname
7852 (concat base "-"
7853 (if heading (concat heading "-" (number-to-string n))
7854 (number-to-string n))))))
7855 (setq n (1+ n)))
7856 (condition-case nil
7857 (make-indirect-buffer buffer bname 'clone)
7858 (error (make-indirect-buffer buffer bname)))))
7860 (defun org-set-frame-title (title)
7861 "Set the title of the current frame to the string TITLE."
7862 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7864 ;;;; Structure editing
7866 ;;; Inserting headlines
7868 (defun org--line-empty-p (n)
7869 "Is the Nth next line empty?
7871 Counts the current line as N = 1 and the previous line as N = 0;
7872 see `beginning-of-line'."
7873 (save-excursion
7874 (and (not (bobp))
7875 (or (beginning-of-line n) t)
7876 (save-match-data
7877 (looking-at "[ \t]*$")))))
7879 (defun org-previous-line-empty-p ()
7880 "Is the previous line a blank line?
7881 When NEXT is non-nil, check the next line instead."
7882 (org--line-empty-p 0))
7884 (defun org-next-line-empty-p ()
7885 "Is the previous line a blank line?
7886 When NEXT is non-nil, check the next line instead."
7887 (org--line-empty-p 2))
7889 (defun org-insert-heading (&optional arg invisible-ok top)
7890 "Insert a new heading or an item with the same depth at point.
7892 If point is at the beginning of a heading or a list item, insert
7893 a new heading or a new item above the current one. If point is
7894 at the beginning of a normal line, turn the line into a heading.
7896 If point is in the middle of a headline or a list item, split the
7897 headline or the item and create a new headline/item with the text
7898 in the current line after point \(see `org-M-RET-may-split-line'
7899 on how to modify this behavior).
7901 With one universal prefix argument, set the user option
7902 `org-insert-heading-respect-content' to t for the duration of
7903 the command. This modifies the behavior described above in this
7904 ways: on list items and at the beginning of normal lines, force
7905 the insertion of a heading after the current subtree.
7907 With two universal prefix arguments, insert the heading at the
7908 end of the grandparent subtree. For example, if point is within
7909 a 2nd-level heading, then it will insert a 2nd-level heading at
7910 the end of the 1st-level parent heading.
7912 If point is at the beginning of a headline, insert a sibling
7913 before the current headline. If point is not at the beginning,
7914 split the line and create a new headline with the text in the
7915 current line after point \(see `org-M-RET-may-split-line' on how
7916 to modify this behavior).
7918 If point is at the beginning of a normal line, turn this line
7919 into a heading.
7921 When INVISIBLE-OK is set, stop at invisible headlines when going
7922 back. This is important for non-interactive uses of the
7923 command.
7925 When optional argument TOP is non-nil, insert a level 1 heading,
7926 unconditionally."
7927 (interactive "P")
7928 (let ((itemp (and (not top) (org-in-item-p)))
7929 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7930 (respect-content (or org-insert-heading-respect-content
7931 (equal arg '(4))))
7932 (initial-content ""))
7934 (cond
7936 ((or (= (buffer-size) 0)
7937 (and (not (save-excursion
7938 (and (ignore-errors (org-back-to-heading invisible-ok))
7939 (org-at-heading-p))))
7940 (or arg (not itemp))))
7941 ;; At beginning of buffer or so high up that only a heading
7942 ;; makes sense.
7943 (cond ((and (bolp) (not respect-content)) (insert "* "))
7944 ((not respect-content)
7945 (unless may-split (end-of-line))
7946 (insert "\n* "))
7947 ((re-search-forward org-outline-regexp-bol nil t)
7948 (beginning-of-line)
7949 (insert "* \n")
7950 (backward-char))
7951 (t (goto-char (point-max))
7952 (insert "\n* ")))
7953 (run-hooks 'org-insert-heading-hook))
7955 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7958 ;; Maybe move at the end of the subtree
7959 (when (equal arg '(16))
7960 (org-up-heading-safe)
7961 (org-end-of-subtree t))
7962 ;; Insert a heading
7963 (save-restriction
7964 (widen)
7965 (let* ((level nil)
7966 (on-heading (org-at-heading-p))
7967 (empty-line-p (if on-heading
7968 (org-previous-line-empty-p)
7969 ;; We will decide later
7970 nil))
7971 ;; Get a level string to fall back on.
7972 (fix-level
7973 (if (org-before-first-heading-p) "*"
7974 (save-excursion
7975 (org-back-to-heading t)
7976 (when (org-previous-line-empty-p) (setq empty-line-p t))
7977 (looking-at org-outline-regexp)
7978 (make-string (1- (length (match-string 0))) ?*))))
7979 (stars
7980 (save-excursion
7981 (condition-case nil
7982 (if top "* "
7983 (org-back-to-heading invisible-ok)
7984 (when (and (not on-heading)
7985 (featurep 'org-inlinetask)
7986 (integerp org-inlinetask-min-level)
7987 (>= (length (match-string 0))
7988 org-inlinetask-min-level))
7989 ;; Find a heading level before the inline
7990 ;; task.
7991 (while (and (setq level (org-up-heading-safe))
7992 (>= level org-inlinetask-min-level)))
7993 (if (org-at-heading-p)
7994 (org-back-to-heading invisible-ok)
7995 (error "This should not happen")))
7996 (unless (and (save-excursion
7997 (save-match-data
7998 (org-backward-heading-same-level
7999 1 invisible-ok))
8000 (= (point) (match-beginning 0)))
8001 (not (org-next-line-empty-p)))
8002 (setq empty-line-p (or empty-line-p
8003 (org-previous-line-empty-p))))
8004 (match-string 0))
8005 (error (or fix-level "* ")))))
8006 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8007 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8009 ;; If we insert after content, move there and clean up
8010 ;; whitespace.
8011 (when (and respect-content
8012 (not (looking-at-p org-outline-regexp-bol)))
8013 (if (not (org-before-first-heading-p))
8014 (org-end-of-subtree nil t)
8015 (re-search-forward org-outline-regexp-bol)
8016 (beginning-of-line 0))
8017 (skip-chars-backward " \r\t\n")
8018 (and (not (looking-back "^\\*+" (line-beginning-position)))
8019 (looking-at "[ \t]+") (replace-match ""))
8020 (unless (eobp) (forward-char 1))
8021 (when (looking-at "^\\*")
8022 (unless (bobp) (backward-char 1))
8023 (insert "\n")))
8025 ;; If we are splitting, grab the text that should be moved
8026 ;; to the new headline.
8027 (when may-split
8028 (if (org-at-heading-p)
8029 ;; This is a heading: split intelligently (keeping
8030 ;; tags).
8031 (let ((pos (point)))
8032 (beginning-of-line)
8033 (unless (looking-at org-complex-heading-regexp)
8034 (error "This should not happen"))
8035 (when (and (match-beginning 4)
8036 (> pos (match-beginning 4))
8037 (< pos (match-end 4)))
8038 (setq initial-content (buffer-substring pos (match-end 4)))
8039 (goto-char pos)
8040 (delete-region (point) (match-end 4))
8041 (if (looking-at "[ \t]*$")
8042 (replace-match "")
8043 (insert (make-string (length initial-content) ?\s)))
8044 (setq initial-content (org-trim initial-content)))
8045 (goto-char pos))
8046 ;; A normal line.
8047 (setq initial-content
8048 (org-trim
8049 (delete-and-extract-region (point) (line-end-position))))))
8051 ;; If we are at the beginning of the line, insert before it.
8052 ;; Otherwise, after it.
8053 (cond
8054 ((and (bolp) (looking-at "[ \t]*$")))
8055 ((bolp) (save-excursion (insert "\n")))
8056 (t (end-of-line)
8057 (insert "\n")))
8059 ;; Insert the new heading
8060 (insert stars)
8061 (just-one-space)
8062 (insert initial-content)
8063 (unless (and blank (org-previous-line-empty-p))
8064 (org-N-empty-lines-before-current (if blank 1 0)))
8065 ;; Adjust visibility, which may be messed up if we removed
8066 ;; blank lines while previous entry was hidden.
8067 (let ((bol (line-beginning-position)))
8068 (dolist (o (overlays-at (1- bol)))
8069 (when (and (eq (overlay-get o 'invisible) 'outline)
8070 (eq (overlay-end o) bol))
8071 (move-overlay o (overlay-start o) (1- bol)))))
8072 (run-hooks 'org-insert-heading-hook)))))))
8074 (defun org-N-empty-lines-before-current (N)
8075 "Make the number of empty lines before current exactly N.
8076 So this will delete or add empty lines."
8077 (save-excursion
8078 (beginning-of-line)
8079 (let ((p (point)))
8080 (skip-chars-backward " \r\t\n")
8081 (unless (bolp) (forward-line))
8082 (delete-region (point) p))
8083 (when (> N 0) (insert (make-string N ?\n)))))
8085 (defun org-get-heading (&optional no-tags no-todo)
8086 "Return the heading of the current entry, without the stars.
8087 When NO-TAGS is non-nil, don't include tags.
8088 When NO-TODO is non-nil, don't include TODO keywords."
8089 (save-excursion
8090 (org-back-to-heading t)
8091 (let ((case-fold-search nil))
8092 (cond
8093 ((and no-tags no-todo)
8094 (looking-at org-complex-heading-regexp)
8095 ;; Return value has to be a string, but match group 4 is
8096 ;; optional.
8097 (or (match-string 4) ""))
8098 (no-tags
8099 (looking-at (concat org-outline-regexp
8100 "\\(.*?\\)"
8101 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8102 (match-string 1))
8103 (no-todo
8104 (looking-at org-todo-line-regexp)
8105 (match-string 3))
8106 (t (looking-at org-heading-regexp)
8107 (match-string 2))))))
8109 (defvar orgstruct-mode) ; defined below
8111 (defun org-heading-components ()
8112 "Return the components of the current heading.
8113 This is a list with the following elements:
8114 - the level as an integer
8115 - the reduced level, different if `org-odd-levels-only' is set.
8116 - the TODO keyword, or nil
8117 - the priority character, like ?A, or nil if no priority is given
8118 - the headline text itself, or the tags string if no headline text
8119 - the tags string, or nil."
8120 (save-excursion
8121 (org-back-to-heading t)
8122 (when (let (case-fold-search)
8123 (looking-at
8124 (if orgstruct-mode
8125 org-heading-regexp
8126 org-complex-heading-regexp)))
8127 (if orgstruct-mode
8128 (list (length (match-string 1))
8129 (org-reduced-level (length (match-string 1)))
8132 (match-string 2)
8133 nil)
8134 (list (length (match-string 1))
8135 (org-reduced-level (length (match-string 1)))
8136 (match-string-no-properties 2)
8137 (and (match-end 3) (aref (match-string 3) 2))
8138 (match-string-no-properties 4)
8139 (match-string-no-properties 5))))))
8141 (defun org-get-entry ()
8142 "Get the entry text, after heading, entire subtree."
8143 (save-excursion
8144 (org-back-to-heading t)
8145 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8147 (defun org-edit-headline (&optional heading)
8148 "Edit the current headline.
8149 Set it to HEADING when provided."
8150 (interactive)
8151 (org-with-wide-buffer
8152 (org-back-to-heading t)
8153 (when (looking-at org-complex-heading-regexp)
8154 (let* ((old (match-string-no-properties 4))
8155 (new (save-match-data
8156 (org-trim (or heading (read-string "Edit: " old))))))
8157 (unless (equal old new)
8158 (if old (replace-match new t t nil 4)
8159 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8160 (insert " " new))
8161 (org-set-tags nil t)
8162 (when (looking-at "[ \t]*$") (replace-match "")))))))
8164 (defun org-insert-heading-after-current ()
8165 "Insert a new heading with same level as current, after current subtree."
8166 (interactive)
8167 (org-back-to-heading)
8168 (org-insert-heading)
8169 (org-move-subtree-down)
8170 (end-of-line 1))
8172 (defun org-insert-heading-respect-content (&optional invisible-ok)
8173 "Insert heading with `org-insert-heading-respect-content' set to t."
8174 (interactive)
8175 (org-insert-heading '(4) invisible-ok))
8177 (defun org-insert-todo-heading-respect-content (&optional force-state)
8178 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8179 (interactive)
8180 (org-insert-todo-heading force-state '(4)))
8182 (defun org-insert-todo-heading (arg &optional force-heading)
8183 "Insert a new heading with the same level and TODO state as current heading.
8184 If the heading has no TODO state, or if the state is DONE, use the first
8185 state (TODO by default). Also with one prefix arg, force first state. With
8186 two prefix args, force inserting at the end of the parent subtree."
8187 (interactive "P")
8188 (when (or force-heading (not (org-insert-item 'checkbox)))
8189 (org-insert-heading (or (and (equal arg '(16)) '(16))
8190 force-heading))
8191 (save-excursion
8192 (org-back-to-heading)
8193 (outline-previous-heading)
8194 (looking-at org-todo-line-regexp))
8195 (let*
8196 ((new-mark-x
8197 (if (or (equal arg '(4))
8198 (not (match-beginning 2))
8199 (member (match-string 2) org-done-keywords))
8200 (car org-todo-keywords-1)
8201 (match-string 2)))
8202 (new-mark
8204 (run-hook-with-args-until-success
8205 'org-todo-get-default-hook new-mark-x nil)
8206 new-mark-x)))
8207 (beginning-of-line 1)
8208 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8209 (if org-treat-insert-todo-heading-as-state-change
8210 (org-todo new-mark)
8211 (insert new-mark " "))))
8212 (when org-provide-todo-statistics
8213 (org-update-parent-todo-statistics))))
8215 (defun org-insert-subheading (arg)
8216 "Insert a new subheading and demote it.
8217 Works for outline headings and for plain lists alike."
8218 (interactive "P")
8219 (org-insert-heading arg)
8220 (cond
8221 ((org-at-heading-p) (org-do-demote))
8222 ((org-at-item-p) (org-indent-item))))
8224 (defun org-insert-todo-subheading (arg)
8225 "Insert a new subheading with TODO keyword or checkbox and demote it.
8226 Works for outline headings and for plain lists alike."
8227 (interactive "P")
8228 (org-insert-todo-heading arg)
8229 (cond
8230 ((org-at-heading-p) (org-do-demote))
8231 ((org-at-item-p) (org-indent-item))))
8233 ;;; Promotion and Demotion
8235 (defvar org-after-demote-entry-hook nil
8236 "Hook run after an entry has been demoted.
8237 The cursor will be at the beginning of the entry.
8238 When a subtree is being demoted, the hook will be called for each node.")
8240 (defvar org-after-promote-entry-hook nil
8241 "Hook run after an entry has been promoted.
8242 The cursor will be at the beginning of the entry.
8243 When a subtree is being promoted, the hook will be called for each node.")
8245 (defun org-promote-subtree ()
8246 "Promote the entire subtree.
8247 See also `org-promote'."
8248 (interactive)
8249 (save-excursion
8250 (org-with-limited-levels (org-map-tree 'org-promote)))
8251 (org-fix-position-after-promote))
8253 (defun org-demote-subtree ()
8254 "Demote the entire subtree.
8255 See `org-demote' and `org-promote'."
8256 (interactive)
8257 (save-excursion
8258 (org-with-limited-levels (org-map-tree 'org-demote)))
8259 (org-fix-position-after-promote))
8261 (defun org-do-promote ()
8262 "Promote the current heading higher up the tree.
8263 If the region is active in `transient-mark-mode', promote all
8264 headings in the region."
8265 (interactive)
8266 (save-excursion
8267 (if (org-region-active-p)
8268 (org-map-region 'org-promote (region-beginning) (region-end))
8269 (org-promote)))
8270 (org-fix-position-after-promote))
8272 (defun org-do-demote ()
8273 "Demote the current heading lower down the tree.
8274 If the region is active in `transient-mark-mode', demote all
8275 headings in the region."
8276 (interactive)
8277 (save-excursion
8278 (if (org-region-active-p)
8279 (org-map-region 'org-demote (region-beginning) (region-end))
8280 (org-demote)))
8281 (org-fix-position-after-promote))
8283 (defun org-fix-position-after-promote ()
8284 "Fix cursor position and indentation after demoting/promoting."
8285 (let ((pos (point)))
8286 (when (save-excursion
8287 (beginning-of-line 1)
8288 (looking-at org-todo-line-regexp)
8289 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8290 (cond ((eobp) (insert " "))
8291 ((eolp) (insert " "))
8292 ((equal (char-after) ?\ ) (forward-char 1))))))
8294 (defun org-current-level ()
8295 "Return the level of the current entry, or nil if before the first headline.
8296 The level is the number of stars at the beginning of the
8297 headline. Use `org-reduced-level' to remove the effect of
8298 `org-odd-levels'. Unlike to `org-outline-level', this function
8299 ignores inlinetasks."
8300 (let ((level (org-with-limited-levels (org-outline-level))))
8301 (and (> level 0) level)))
8303 (defun org-get-previous-line-level ()
8304 "Return the outline depth of the last headline before the current line.
8305 Returns 0 for the first headline in the buffer, and nil if before the
8306 first headline."
8307 (and (org-current-level)
8308 (or (and (/= (line-beginning-position) (point-min))
8309 (save-excursion (beginning-of-line 0) (org-current-level)))
8310 0)))
8312 (defun org-reduced-level (l)
8313 "Compute the effective level of a heading.
8314 This takes into account the setting of `org-odd-levels-only'."
8315 (cond
8316 ((zerop l) 0)
8317 (org-odd-levels-only (1+ (floor (/ l 2))))
8318 (t l)))
8320 (defun org-level-increment ()
8321 "Return the number of stars that will be added or removed at a
8322 time to headlines when structure editing, based on the value of
8323 `org-odd-levels-only'."
8324 (if org-odd-levels-only 2 1))
8326 (defun org-get-valid-level (level &optional change)
8327 "Rectify a level change under the influence of `org-odd-levels-only'
8328 LEVEL is a current level, CHANGE is by how much the level should be
8329 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8330 even level numbers will become the next higher odd number."
8331 (if org-odd-levels-only
8332 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8333 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8334 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8335 (max 1 (+ level (or change 0)))))
8337 (defun org-promote ()
8338 "Promote the current heading higher up the tree."
8339 (org-with-wide-buffer
8340 (org-back-to-heading t)
8341 (let* ((after-change-functions (remq 'flyspell-after-change-function
8342 after-change-functions))
8343 (level (save-match-data (funcall outline-level)))
8344 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8345 (diff (abs (- level (length up-head) -1))))
8346 (cond
8347 ((and (= level 1) org-allow-promoting-top-level-subtree)
8348 (replace-match "# " nil t))
8349 ((= level 1)
8350 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8351 (t (replace-match up-head nil t)))
8352 (unless (= level 1)
8353 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8354 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8355 (run-hooks 'org-after-promote-entry-hook))))
8357 (defun org-demote ()
8358 "Demote the current heading lower down the tree."
8359 (org-with-wide-buffer
8360 (org-back-to-heading t)
8361 (let* ((after-change-functions (remq 'flyspell-after-change-function
8362 after-change-functions))
8363 (level (save-match-data (funcall outline-level)))
8364 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8365 (diff (abs (- level (length down-head) -1))))
8366 (replace-match down-head nil t)
8367 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8368 (when org-adapt-indentation (org-fixup-indentation diff))
8369 (run-hooks 'org-after-demote-entry-hook))))
8371 (defun org-cycle-level ()
8372 "Cycle the level of an empty headline through possible states.
8373 This goes first to child, then to parent, level, then up the hierarchy.
8374 After top level, it switches back to sibling level."
8375 (interactive)
8376 (let ((org-adapt-indentation nil))
8377 (when (org-point-at-end-of-empty-headline)
8378 (setq this-command 'org-cycle-level) ; Only needed for caching
8379 (let ((cur-level (org-current-level))
8380 (prev-level (org-get-previous-line-level)))
8381 (cond
8382 ;; If first headline in file, promote to top-level.
8383 ((= prev-level 0)
8384 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8385 do (org-do-promote)))
8386 ;; If same level as prev, demote one.
8387 ((= prev-level cur-level)
8388 (org-do-demote))
8389 ;; If parent is top-level, promote to top level if not already.
8390 ((= prev-level 1)
8391 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8392 do (org-do-promote)))
8393 ;; If top-level, return to prev-level.
8394 ((= cur-level 1)
8395 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8396 do (org-do-demote)))
8397 ;; If less than prev-level, promote one.
8398 ((< cur-level prev-level)
8399 (org-do-promote))
8400 ;; If deeper than prev-level, promote until higher than
8401 ;; prev-level.
8402 ((> cur-level prev-level)
8403 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8404 do (org-do-promote))))
8405 t))))
8407 (defun org-map-tree (fun)
8408 "Call FUN for every heading underneath the current one."
8409 (org-back-to-heading t)
8410 (let ((level (funcall outline-level)))
8411 (save-excursion
8412 (funcall fun)
8413 (while (and (progn
8414 (outline-next-heading)
8415 (> (funcall outline-level) level))
8416 (not (eobp)))
8417 (funcall fun)))))
8419 (defun org-map-region (fun beg end)
8420 "Call FUN for every heading between BEG and END."
8421 (let ((org-ignore-region t))
8422 (save-excursion
8423 (setq end (copy-marker end))
8424 (goto-char beg)
8425 (when (and (re-search-forward org-outline-regexp-bol nil t)
8426 (< (point) end))
8427 (funcall fun))
8428 (while (and (progn
8429 (outline-next-heading)
8430 (< (point) end))
8431 (not (eobp)))
8432 (funcall fun)))))
8434 (defun org-fixup-indentation (diff)
8435 "Change the indentation in the current entry by DIFF.
8437 DIFF is an integer. Indentation is done according to the
8438 following rules:
8440 - Planning information and property drawers are always indented
8441 according to the new level of the headline;
8443 - Footnote definitions and their contents are ignored;
8445 - Inlinetasks' boundaries are not shifted;
8447 - Empty lines are ignored;
8449 - Other lines' indentation are shifted by DIFF columns, unless
8450 it would introduce a structural change in the document, in
8451 which case no shifting is done at all.
8453 Assume point is at a heading or an inlinetask beginning."
8454 (org-with-wide-buffer
8455 (narrow-to-region (line-beginning-position)
8456 (save-excursion
8457 (if (org-with-limited-levels (org-at-heading-p))
8458 (org-with-limited-levels (outline-next-heading))
8459 (org-inlinetask-goto-end))
8460 (point)))
8461 (forward-line)
8462 ;; Indent properly planning info and property drawer.
8463 (when (looking-at-p org-planning-line-re)
8464 (org-indent-line)
8465 (forward-line))
8466 (when (looking-at org-property-drawer-re)
8467 (goto-char (match-end 0))
8468 (forward-line)
8469 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8470 (catch 'no-shift
8471 (when (zerop diff) (throw 'no-shift nil))
8472 ;; If DIFF is negative, first check if a shift is possible at all
8473 ;; (e.g., it doesn't break structure). This can only happen if
8474 ;; some contents are not properly indented.
8475 (let ((case-fold-search t))
8476 (when (< diff 0)
8477 (let ((diff (- diff))
8478 (forbidden-re (concat org-outline-regexp
8479 "\\|"
8480 (substring org-footnote-definition-re 1))))
8481 (save-excursion
8482 (while (not (eobp))
8483 (cond
8484 ((looking-at-p "[ \t]*$") (forward-line))
8485 ((and (looking-at-p org-footnote-definition-re)
8486 (let ((e (org-element-at-point)))
8487 (and (eq (org-element-type e) 'footnote-definition)
8488 (goto-char (org-element-property :end e))))))
8489 ((looking-at-p org-outline-regexp) (forward-line))
8490 ;; Give up if shifting would move before column 0 or
8491 ;; if it would introduce a headline or a footnote
8492 ;; definition.
8494 (skip-chars-forward " \t")
8495 (let ((ind (current-column)))
8496 (when (or (< ind diff)
8497 (and (= ind diff) (looking-at-p forbidden-re)))
8498 (throw 'no-shift nil)))
8499 ;; Ignore contents of example blocks and source
8500 ;; blocks if their indentation is meant to be
8501 ;; preserved. Jump to block's closing line.
8502 (beginning-of-line)
8503 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8504 (let ((e (org-element-at-point)))
8505 (and (memq (org-element-type e)
8506 '(example-block src-block))
8507 (or org-src-preserve-indentation
8508 (org-element-property :preserve-indent e))
8509 (goto-char (org-element-property :end e))
8510 (progn (skip-chars-backward " \r\t\n")
8511 (beginning-of-line)
8512 t))))
8513 (forward-line))))))))
8514 ;; Shift lines but footnote definitions, inlinetasks boundaries
8515 ;; by DIFF. Also skip contents of source or example blocks
8516 ;; when indentation is meant to be preserved.
8517 (while (not (eobp))
8518 (cond
8519 ((and (looking-at-p org-footnote-definition-re)
8520 (let ((e (org-element-at-point)))
8521 (and (eq (org-element-type e) 'footnote-definition)
8522 (goto-char (org-element-property :end e))))))
8523 ((looking-at-p org-outline-regexp) (forward-line))
8524 ((looking-at-p "[ \t]*$") (forward-line))
8526 (indent-line-to (+ (org-get-indentation) diff))
8527 (beginning-of-line)
8528 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8529 (let ((e (org-element-at-point)))
8530 (and (memq (org-element-type e)
8531 '(example-block src-block))
8532 (or org-src-preserve-indentation
8533 (org-element-property :preserve-indent e))
8534 (goto-char (org-element-property :end e))
8535 (progn (skip-chars-backward " \r\t\n")
8536 (beginning-of-line)
8537 t))))
8538 (forward-line)))))))))
8540 (defun org-convert-to-odd-levels ()
8541 "Convert an org-mode file with all levels allowed to one with odd levels.
8542 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8543 level 5 etc."
8544 (interactive)
8545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8546 (let ((outline-level 'org-outline-level)
8547 (org-odd-levels-only nil) n)
8548 (save-excursion
8549 (goto-char (point-min))
8550 (while (re-search-forward "^\\*\\*+ " nil t)
8551 (setq n (- (length (match-string 0)) 2))
8552 (while (>= (setq n (1- n)) 0)
8553 (org-demote))
8554 (end-of-line 1))))))
8556 (defun org-convert-to-oddeven-levels ()
8557 "Convert an org-mode file with only odd levels to one with odd/even levels.
8558 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8559 file contains a section with an even level, conversion would
8560 destroy the structure of the file. An error is signaled in this
8561 case."
8562 (interactive)
8563 (goto-char (point-min))
8564 ;; First check if there are no even levels
8565 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8566 (org-show-set-visibility 'canonical)
8567 (error "Not all levels are odd in this file. Conversion not possible"))
8568 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8569 (let ((outline-regexp org-outline-regexp)
8570 (outline-level 'org-outline-level)
8571 (org-odd-levels-only nil) n)
8572 (save-excursion
8573 (goto-char (point-min))
8574 (while (re-search-forward "^\\*\\*+ " nil t)
8575 (setq n (/ (1- (length (match-string 0))) 2))
8576 (while (>= (setq n (1- n)) 0)
8577 (org-promote))
8578 (end-of-line 1))))))
8580 (defun org-tr-level (n)
8581 "Make N odd if required."
8582 (if org-odd-levels-only (1+ (/ n 2)) n))
8584 ;;; Vertical tree motion, cutting and pasting of subtrees
8586 (defun org-move-subtree-up (&optional arg)
8587 "Move the current subtree up past ARG headlines of the same level."
8588 (interactive "p")
8589 (org-move-subtree-down (- (prefix-numeric-value arg))))
8591 (defun org-move-subtree-down (&optional arg)
8592 "Move the current subtree down past ARG headlines of the same level."
8593 (interactive "p")
8594 (setq arg (prefix-numeric-value arg))
8595 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8596 'org-get-last-sibling))
8597 (ins-point (make-marker))
8598 (cnt (abs arg))
8599 (col (current-column))
8600 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8601 ;; Select the tree
8602 (org-back-to-heading)
8603 (setq beg0 (point))
8604 (save-excursion
8605 (setq ne-beg (org-back-over-empty-lines))
8606 (setq beg (point)))
8607 (save-match-data
8608 (save-excursion (outline-end-of-heading)
8609 (setq folded (outline-invisible-p)))
8610 (progn (org-end-of-subtree nil t)
8611 (unless (eobp) (backward-char))))
8612 (outline-next-heading)
8613 (setq ne-end (org-back-over-empty-lines))
8614 (setq end (point))
8615 (goto-char beg0)
8616 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8617 ;; include less whitespace
8618 (save-excursion
8619 (goto-char beg)
8620 (forward-line (- ne-beg ne-end))
8621 (setq beg (point))))
8622 ;; Find insertion point, with error handling
8623 (while (> cnt 0)
8624 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8625 (progn (goto-char beg0)
8626 (user-error "Cannot move past superior level or buffer limit")))
8627 (setq cnt (1- cnt)))
8628 (when (> arg 0)
8629 ;; Moving forward - still need to move over subtree
8630 (org-end-of-subtree t t)
8631 (save-excursion
8632 (org-back-over-empty-lines)
8633 (or (bolp) (newline))))
8634 (setq ne-ins (org-back-over-empty-lines))
8635 (move-marker ins-point (point))
8636 (setq txt (buffer-substring beg end))
8637 (org-save-markers-in-region beg end)
8638 (delete-region beg end)
8639 (org-remove-empty-overlays-at beg)
8640 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8641 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8642 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8643 (let ((bbb (point)))
8644 (insert-before-markers txt)
8645 (org-reinstall-markers-in-region bbb)
8646 (move-marker ins-point bbb))
8647 (or (bolp) (insert "\n"))
8648 (setq ins-end (point))
8649 (goto-char ins-point)
8650 (org-skip-whitespace)
8651 (when (and (< arg 0)
8652 (org-first-sibling-p)
8653 (> ne-ins ne-beg))
8654 ;; Move whitespace back to beginning
8655 (save-excursion
8656 (goto-char ins-end)
8657 (let ((kill-whole-line t))
8658 (kill-line (- ne-ins ne-beg)) (point)))
8659 (insert (make-string (- ne-ins ne-beg) ?\n)))
8660 (move-marker ins-point nil)
8661 (if folded
8662 (outline-hide-subtree)
8663 (org-show-entry)
8664 (org-show-children)
8665 (org-cycle-hide-drawers 'children))
8666 (org-clean-visibility-after-subtree-move)
8667 ;; move back to the initial column we were at
8668 (move-to-column col)))
8670 (defvar org-subtree-clip ""
8671 "Clipboard for cut and paste of subtrees.
8672 This is actually only a copy of the kill, because we use the normal kill
8673 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8675 (defvar org-subtree-clip-folded nil
8676 "Was the last copied subtree folded?
8677 This is used to fold the tree back after pasting.")
8679 (defun org-cut-subtree (&optional n)
8680 "Cut the current subtree into the clipboard.
8681 With prefix arg N, cut this many sequential subtrees.
8682 This is a short-hand for marking the subtree and then cutting it."
8683 (interactive "p")
8684 (org-copy-subtree n 'cut))
8686 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8687 "Copy the current subtree it in the clipboard.
8688 With prefix arg N, copy this many sequential subtrees.
8689 This is a short-hand for marking the subtree and then copying it.
8690 If CUT is non-nil, actually cut the subtree.
8691 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8692 of some markers in the region, even if CUT is non-nil. This is
8693 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8694 (interactive "p")
8695 (let (beg end folded (beg0 (point)))
8696 (if (called-interactively-p 'any)
8697 (org-back-to-heading nil) ; take what looks like a subtree
8698 (org-back-to-heading t)) ; take what is really there
8699 (setq beg (point))
8700 (skip-chars-forward " \t\r\n")
8701 (save-match-data
8702 (if nosubtrees
8703 (outline-next-heading)
8704 (save-excursion (outline-end-of-heading)
8705 (setq folded (outline-invisible-p)))
8706 (ignore-errors (org-forward-heading-same-level (1- n) t))
8707 (org-end-of-subtree t t)))
8708 ;; Include the end of an inlinetask
8709 (when (and (featurep 'org-inlinetask)
8710 (looking-at-p (concat (org-inlinetask-outline-regexp)
8711 "END[ \t]*$")))
8712 (end-of-line))
8713 (setq end (point))
8714 (goto-char beg0)
8715 (when (> end beg)
8716 (setq org-subtree-clip-folded folded)
8717 (when (or cut force-store-markers)
8718 (org-save-markers-in-region beg end))
8719 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8720 (setq org-subtree-clip (current-kill 0))
8721 (message "%s: Subtree(s) with %d characters"
8722 (if cut "Cut" "Copied")
8723 (length org-subtree-clip)))))
8725 (defun org-paste-subtree (&optional level tree for-yank remove)
8726 "Paste the clipboard as a subtree, with modification of headline level.
8727 The entire subtree is promoted or demoted in order to match a new headline
8728 level.
8730 If the cursor is at the beginning of a headline, the same level as
8731 that headline is used to paste the tree.
8733 If not, the new level is derived from the *visible* headings
8734 before and after the insertion point, and taken to be the inferior headline
8735 level of the two. So if the previous visible heading is level 3 and the
8736 next is level 4 (or vice versa), level 4 will be used for insertion.
8737 This makes sure that the subtree remains an independent subtree and does
8738 not swallow low level entries.
8740 You can also force a different level, either by using a numeric prefix
8741 argument, or by inserting the heading marker by hand. For example, if the
8742 cursor is after \"*****\", then the tree will be shifted to level 5.
8744 If optional TREE is given, use this text instead of the kill ring.
8746 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8747 move back over whitespace before inserting, and move point to the end of
8748 the inserted text when done.
8750 When REMOVE is non-nil, remove the subtree from the clipboard."
8751 (interactive "P")
8752 (setq tree (or tree (and kill-ring (current-kill 0))))
8753 (unless (org-kill-is-subtree-p tree)
8754 (user-error "%s"
8755 (substitute-command-keys
8756 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8757 (org-with-limited-levels
8758 (let* ((visp (not (outline-invisible-p)))
8759 (txt tree)
8760 (^re_ "\\(\\*+\\)[ \t]*")
8761 (old-level (if (string-match org-outline-regexp-bol txt)
8762 (- (match-end 0) (match-beginning 0) 1)
8763 -1))
8764 (force-level (cond (level (prefix-numeric-value level))
8765 ((and (looking-at "[ \t]*$")
8766 (string-match
8767 "^\\*+$" (buffer-substring
8768 (point-at-bol) (point))))
8769 (- (match-end 0) (match-beginning 0)))
8770 ((and (bolp)
8771 (looking-at org-outline-regexp))
8772 (- (match-end 0) (point) 1))))
8773 (previous-level (save-excursion
8774 (condition-case nil
8775 (progn
8776 (outline-previous-visible-heading 1)
8777 (if (looking-at ^re_)
8778 (- (match-end 0) (match-beginning 0) 1)
8780 (error 1))))
8781 (next-level (save-excursion
8782 (condition-case nil
8783 (progn
8784 (or (looking-at org-outline-regexp)
8785 (outline-next-visible-heading 1))
8786 (if (looking-at ^re_)
8787 (- (match-end 0) (match-beginning 0) 1)
8789 (error 1))))
8790 (new-level (or force-level (max previous-level next-level)))
8791 (shift (if (or (= old-level -1)
8792 (= new-level -1)
8793 (= old-level new-level))
8795 (- new-level old-level)))
8796 (delta (if (> shift 0) -1 1))
8797 (func (if (> shift 0) 'org-demote 'org-promote))
8798 (org-odd-levels-only nil)
8799 beg end newend)
8800 ;; Remove the forced level indicator
8801 (when force-level
8802 (delete-region (point-at-bol) (point)))
8803 ;; Paste
8804 (beginning-of-line (if (bolp) 1 2))
8805 (setq beg (point))
8806 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8807 (insert-before-markers txt)
8808 (unless (string-match "\n\\'" txt) (insert "\n"))
8809 (setq newend (point))
8810 (org-reinstall-markers-in-region beg)
8811 (setq end (point))
8812 (goto-char beg)
8813 (skip-chars-forward " \t\n\r")
8814 (setq beg (point))
8815 (when (and (outline-invisible-p) visp)
8816 (save-excursion (outline-show-heading)))
8817 ;; Shift if necessary
8818 (unless (= shift 0)
8819 (save-restriction
8820 (narrow-to-region beg end)
8821 (while (not (= shift 0))
8822 (org-map-region func (point-min) (point-max))
8823 (setq shift (+ delta shift)))
8824 (goto-char (point-min))
8825 (setq newend (point-max))))
8826 (when (or (called-interactively-p 'interactive) for-yank)
8827 (message "Clipboard pasted as level %d subtree" new-level))
8828 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8829 kill-ring
8830 (eq org-subtree-clip (current-kill 0))
8831 org-subtree-clip-folded)
8832 ;; The tree was folded before it was killed/copied
8833 (outline-hide-subtree))
8834 (and for-yank (goto-char newend))
8835 (and remove (setq kill-ring (cdr kill-ring))))))
8837 (defun org-kill-is-subtree-p (&optional txt)
8838 "Check if the current kill is an outline subtree, or a set of trees.
8839 Returns nil if kill does not start with a headline, or if the first
8840 headline level is not the largest headline level in the tree.
8841 So this will actually accept several entries of equal levels as well,
8842 which is OK for `org-paste-subtree'.
8843 If optional TXT is given, check this string instead of the current kill."
8844 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8845 (re (org-get-limited-outline-regexp))
8846 (^re (concat "^" re))
8847 (start-level (and kill
8848 (string-match
8849 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8850 kill)
8851 (- (match-end 2) (match-beginning 2) 1)))
8852 (start (1+ (or (match-beginning 2) -1))))
8853 (if (not start-level)
8854 (progn
8855 nil) ;; does not even start with a heading
8856 (catch 'exit
8857 (while (setq start (string-match ^re kill (1+ start)))
8858 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8859 (throw 'exit nil)))
8860 t))))
8862 (defvar org-markers-to-move nil
8863 "Markers that should be moved with a cut-and-paste operation.
8864 Those markers are stored together with their positions relative to
8865 the start of the region.")
8867 (defun org-save-markers-in-region (beg end)
8868 "Check markers in region.
8869 If these markers are between BEG and END, record their position relative
8870 to BEG, so that after moving the block of text, we can put the markers back
8871 into place.
8872 This function gets called just before an entry or tree gets cut from the
8873 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8874 called immediately, to move the markers with the entries."
8875 (setq org-markers-to-move nil)
8876 (when (featurep 'org-clock)
8877 (org-clock-save-markers-for-cut-and-paste beg end))
8878 (when (featurep 'org-agenda)
8879 (org-agenda-save-markers-for-cut-and-paste beg end)))
8881 (defun org-check-and-save-marker (marker beg end)
8882 "Check if MARKER is between BEG and END.
8883 If yes, remember the marker and the distance to BEG."
8884 (when (and (marker-buffer marker)
8885 (equal (marker-buffer marker) (current-buffer))
8886 (>= marker beg) (< marker end))
8887 (push (cons marker (- marker beg)) org-markers-to-move)))
8889 (defun org-reinstall-markers-in-region (beg)
8890 "Move all remembered markers to their position relative to BEG."
8891 (dolist (x org-markers-to-move)
8892 (move-marker (car x) (+ beg (cdr x))))
8893 (setq org-markers-to-move nil))
8895 (defun org-narrow-to-subtree ()
8896 "Narrow buffer to the current subtree."
8897 (interactive)
8898 (save-excursion
8899 (save-match-data
8900 (org-with-limited-levels
8901 (narrow-to-region
8902 (progn (org-back-to-heading t) (point))
8903 (progn (org-end-of-subtree t t)
8904 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8905 (point)))))))
8907 (defun org-narrow-to-block ()
8908 "Narrow buffer to the current block."
8909 (interactive)
8910 (let* ((case-fold-search t)
8911 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8912 "^[ \t]*#\\+end_.*")))
8913 (if blockp
8914 (narrow-to-region (car blockp) (cdr blockp))
8915 (user-error "Not in a block"))))
8917 (defun org-clone-subtree-with-time-shift (n &optional shift)
8918 "Clone the task (subtree) at point N times.
8919 The clones will be inserted as siblings.
8921 In interactive use, the user will be prompted for the number of
8922 clones to be produced. If the entry has a timestamp, the user
8923 will also be prompted for a time shift, which may be a repeater
8924 as used in time stamps, for example `+3d'. To disable this,
8925 you can call the function with a universal prefix argument.
8927 When a valid repeater is given and the entry contains any time
8928 stamps, the clones will become a sequence in time, with time
8929 stamps in the subtree shifted for each clone produced. If SHIFT
8930 is nil or the empty string, time stamps will be left alone. The
8931 ID property of the original subtree is removed.
8933 If the original subtree did contain time stamps with a repeater,
8934 the following will happen:
8935 - the repeater will be removed in each clone
8936 - an additional clone will be produced, with the current, unshifted
8937 date(s) in the entry.
8938 - the original entry will be placed *after* all the clones, with
8939 repeater intact.
8940 - the start days in the repeater in the original entry will be shifted
8941 to past the last clone.
8942 In this way you can spell out a number of instances of a repeating task,
8943 and still retain the repeater to cover future instances of the task.
8945 As described above, N+1 clones are produced when the original
8946 subtree has a repeater. Setting N to 0, then, can be used to
8947 remove the repeater from a subtree and create a shifted clone
8948 with the original repeater."
8949 (interactive "nNumber of clones to produce: ")
8950 (let ((shift
8951 (or shift
8952 (if (and (not (equal current-prefix-arg '(4)))
8953 (save-excursion
8954 (re-search-forward org-ts-regexp-both
8955 (save-excursion
8956 (org-end-of-subtree t)
8957 (point)) t)))
8958 (read-from-minibuffer
8959 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8960 ""))) ;; No time shift
8961 (n-no-remove -1)
8962 (drawer-re org-drawer-regexp)
8963 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8964 beg end template task idprop
8965 shift-n shift-what doshift nmin nmax)
8966 (unless (wholenump n)
8967 (user-error "Invalid number of replications %s" n))
8968 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8969 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8970 shift)))
8971 (user-error "Invalid shift specification %s" shift))
8972 (when doshift
8973 (setq shift-n (string-to-number (match-string 1 shift))
8974 shift-what (cdr (assoc (match-string 2 shift)
8975 '(("d" . day) ("w" . week)
8976 ("m" . month) ("y" . year))))))
8977 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8978 (setq nmin 1 nmax n)
8979 (org-back-to-heading t)
8980 (setq beg (point))
8981 (setq idprop (org-entry-get nil "ID"))
8982 (org-end-of-subtree t t)
8983 (or (bolp) (insert "\n"))
8984 (setq end (point))
8985 (setq template (buffer-substring beg end))
8986 (when (and doshift
8987 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8988 (delete-region beg end)
8989 (setq end beg)
8990 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8991 (goto-char end)
8992 (cl-loop for n from nmin to nmax do
8993 ;; prepare clone
8994 (with-temp-buffer
8995 (insert template)
8996 (org-mode)
8997 (goto-char (point-min))
8998 (org-show-subtree)
8999 (and idprop (if org-clone-delete-id
9000 (org-entry-delete nil "ID")
9001 (org-id-get-create t)))
9002 (unless (= n 0)
9003 (while (re-search-forward org-clock-re nil t)
9004 (kill-whole-line))
9005 (goto-char (point-min))
9006 (while (re-search-forward drawer-re nil t)
9007 (org-remove-empty-drawer-at (point))))
9008 (goto-char (point-min))
9009 (when doshift
9010 (while (re-search-forward org-ts-regexp-both nil t)
9011 (org-timestamp-change (* n shift-n) shift-what))
9012 (unless (= n n-no-remove)
9013 (goto-char (point-min))
9014 (while (re-search-forward org-ts-regexp nil t)
9015 (save-excursion
9016 (goto-char (match-beginning 0))
9017 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9018 (delete-region (match-beginning 1) (match-end 1)))))))
9019 (setq task (buffer-string)))
9020 (insert task))
9021 (goto-char beg)))
9023 ;;; Outline Sorting
9025 (defun org-sort (with-case)
9026 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9027 Optional argument WITH-CASE means sort case-sensitively."
9028 (interactive "P")
9029 (cond
9030 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9031 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9033 (org-call-with-arg 'org-sort-entries with-case))))
9035 (defun org-sort-remove-invisible (s)
9036 "Remove invisible links from string S."
9037 (remove-text-properties 0 (length s) org-rm-props s)
9038 (while (string-match org-bracket-link-regexp s)
9039 (setq s (replace-match (if (match-end 2)
9040 (match-string 3 s)
9041 (match-string 1 s))
9042 t t s)))
9043 (let ((st (format " %s " s)))
9044 (while (string-match org-emph-re st)
9045 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9046 (setq s (substring st 1 -1)))
9049 (defvar org-priority-regexp) ; defined later in the file
9051 (defvar org-after-sorting-entries-or-items-hook nil
9052 "Hook that is run after a bunch of entries or items have been sorted.
9053 When children are sorted, the cursor is in the parent line when this
9054 hook gets called. When a region or a plain list is sorted, the cursor
9055 will be in the first entry of the sorted region/list.")
9057 (defun org-sort-entries
9058 (&optional with-case sorting-type getkey-func compare-func property)
9059 "Sort entries on a certain level of an outline tree.
9060 If there is an active region, the entries in the region are sorted.
9061 Else, if the cursor is before the first entry, sort the top-level items.
9062 Else, the children of the entry at point are sorted.
9064 Sorting can be alphabetically, numerically, by date/time as given by
9065 a time stamp, by a property, by priority order, or by a custom function.
9067 The command prompts for the sorting type unless it has been given to the
9068 function through the SORTING-TYPE argument, which needs to be a character,
9069 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9070 the precise meaning of each character:
9072 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9073 c By creation time, which is assumed to be the first inactive time stamp
9074 at the beginning of a line.
9075 d By deadline date/time.
9076 k By clocking time.
9077 n Numerically, by converting the beginning of the entry/item to a number.
9078 o By order of TODO keywords.
9079 p By priority according to the cookie.
9080 r By the value of a property.
9081 s By scheduled date/time.
9082 t By date/time, either the first active time stamp in the entry, or, if
9083 none exist, by the first inactive one.
9085 Capital letters will reverse the sort order.
9087 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9088 called with point at the beginning of the record. It must return either
9089 a string or a number that should serve as the sorting key for that record.
9091 Comparing entries ignores case by default. However, with an optional argument
9092 WITH-CASE, the sorting considers case as well.
9094 Sorting is done against the visible part of the headlines, it ignores hidden
9095 links.
9097 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9098 (interactive "P")
9099 (let ((case-func (if with-case 'identity 'downcase))
9100 (cmstr
9101 ;; The clock marker is lost when using `sort-subr', let's
9102 ;; store the clocking string.
9103 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9104 (save-excursion
9105 (goto-char org-clock-marker)
9106 (buffer-substring-no-properties (line-beginning-position)
9107 (point)))))
9108 start beg end stars re re2
9109 txt what tmp)
9110 ;; Find beginning and end of region to sort
9111 (cond
9112 ((org-region-active-p)
9113 ;; we will sort the region
9114 (setq end (region-end)
9115 what "region")
9116 (goto-char (region-beginning))
9117 (unless (org-at-heading-p) (outline-next-heading))
9118 (setq start (point)))
9119 ((or (org-at-heading-p)
9120 (ignore-errors (progn (org-back-to-heading) t)))
9121 ;; we will sort the children of the current headline
9122 (org-back-to-heading)
9123 (setq start (point)
9124 end (progn (org-end-of-subtree t t)
9125 (or (bolp) (insert "\n"))
9126 (when (>= (org-back-over-empty-lines) 1)
9127 (forward-line 1))
9128 (point))
9129 what "children")
9130 (goto-char start)
9131 (outline-show-subtree)
9132 (outline-next-heading))
9134 ;; we will sort the top-level entries in this file
9135 (goto-char (point-min))
9136 (or (org-at-heading-p) (outline-next-heading))
9137 (setq start (point))
9138 (goto-char (point-max))
9139 (beginning-of-line 1)
9140 (when (looking-at ".*?\\S-")
9141 ;; File ends in a non-white line
9142 (end-of-line 1)
9143 (insert "\n"))
9144 (setq end (point-max))
9145 (setq what "top-level")
9146 (goto-char start)
9147 (outline-show-all)))
9149 (setq beg (point))
9150 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9152 (looking-at "\\(\\*+\\)")
9153 (setq stars (match-string 1)
9154 re (concat "^" (regexp-quote stars) " +")
9155 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9156 txt (buffer-substring beg end))
9157 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9158 (when (and (not (equal stars "*")) (string-match re2 txt))
9159 (user-error "Region to sort contains a level above the first entry"))
9161 (unless sorting-type
9162 (message
9163 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9164 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9165 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9166 what)
9167 (setq sorting-type (read-char-exclusive))
9169 (unless getkey-func
9170 (and (= (downcase sorting-type) ?f)
9171 (setq getkey-func
9172 (completing-read "Sort using function: "
9173 obarray 'fboundp t nil nil))
9174 (setq getkey-func (intern getkey-func))))
9176 (and (= (downcase sorting-type) ?r)
9177 (not property)
9178 (setq property
9179 (completing-read "Property: "
9180 (mapcar #'list (org-buffer-property-keys t))
9181 nil t))))
9183 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9184 (message "Sorting entries...")
9186 (save-restriction
9187 (narrow-to-region start end)
9188 (let ((dcst (downcase sorting-type))
9189 (case-fold-search nil)
9190 (now (current-time)))
9191 (sort-subr
9192 (/= dcst sorting-type)
9193 ;; This function moves to the beginning character of the "record" to
9194 ;; be sorted.
9195 (lambda nil
9196 (if (re-search-forward re nil t)
9197 (goto-char (match-beginning 0))
9198 (goto-char (point-max))))
9199 ;; This function moves to the last character of the "record" being
9200 ;; sorted.
9201 (lambda nil
9202 (save-match-data
9203 (condition-case nil
9204 (outline-forward-same-level 1)
9205 (error
9206 (goto-char (point-max))))))
9207 ;; This function returns the value that gets sorted against.
9208 (lambda nil
9209 (cond
9210 ((= dcst ?n)
9211 (if (looking-at org-complex-heading-regexp)
9212 (string-to-number (org-sort-remove-invisible (match-string 4)))
9213 nil))
9214 ((= dcst ?a)
9215 (if (looking-at org-complex-heading-regexp)
9216 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9217 nil))
9218 ((= dcst ?k)
9219 (or (get-text-property (point) :org-clock-minutes) 0))
9220 ((= dcst ?t)
9221 (let ((end (save-excursion (outline-next-heading) (point))))
9222 (if (or (re-search-forward org-ts-regexp end t)
9223 (re-search-forward org-ts-regexp-both end t))
9224 (org-time-string-to-seconds (match-string 0))
9225 (float-time now))))
9226 ((= dcst ?c)
9227 (let ((end (save-excursion (outline-next-heading) (point))))
9228 (if (re-search-forward
9229 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9230 end t)
9231 (org-time-string-to-seconds (match-string 0))
9232 (float-time now))))
9233 ((= dcst ?s)
9234 (let ((end (save-excursion (outline-next-heading) (point))))
9235 (if (re-search-forward org-scheduled-time-regexp end t)
9236 (org-time-string-to-seconds (match-string 1))
9237 (float-time now))))
9238 ((= dcst ?d)
9239 (let ((end (save-excursion (outline-next-heading) (point))))
9240 (if (re-search-forward org-deadline-time-regexp end t)
9241 (org-time-string-to-seconds (match-string 1))
9242 (float-time now))))
9243 ((= dcst ?p)
9244 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9245 (string-to-char (match-string 2))
9246 org-default-priority))
9247 ((= dcst ?r)
9248 (or (org-entry-get nil property) ""))
9249 ((= dcst ?o)
9250 (when (looking-at org-complex-heading-regexp)
9251 (let* ((m (match-string 2))
9252 (s (if (member m org-done-keywords) '- '+)))
9253 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9254 ((= dcst ?f)
9255 (if getkey-func
9256 (progn
9257 (setq tmp (funcall getkey-func))
9258 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9259 tmp)
9260 (error "Invalid key function `%s'" getkey-func)))
9261 (t (error "Invalid sorting type `%c'" sorting-type))))
9263 (cond
9264 ((= dcst ?a) 'string<)
9265 ((= dcst ?f) compare-func)
9266 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9267 (run-hooks 'org-after-sorting-entries-or-items-hook)
9268 ;; Reset the clock marker if needed
9269 (when cmstr
9270 (save-excursion
9271 (goto-char start)
9272 (search-forward cmstr nil t)
9273 (move-marker org-clock-marker (point))))
9274 (message "Sorting entries...done")))
9276 ;;; The orgstruct minor mode
9278 ;; Define a minor mode which can be used in other modes in order to
9279 ;; integrate the org-mode structure editing commands.
9281 ;; This is really a hack, because the org-mode structure commands use
9282 ;; keys which normally belong to the major mode. Here is how it
9283 ;; works: The minor mode defines all the keys necessary to operate the
9284 ;; structure commands, but wraps the commands into a function which
9285 ;; tests if the cursor is currently at a headline or a plain list
9286 ;; item. If that is the case, the structure command is used,
9287 ;; temporarily setting many Org-mode variables like regular
9288 ;; expressions for filling etc. However, when any of those keys is
9289 ;; used at a different location, function uses `key-binding' to look
9290 ;; up if the key has an associated command in another currently active
9291 ;; keymap (minor modes, major mode, global), and executes that
9292 ;; command. There might be problems if any of the keys is otherwise
9293 ;; used as a prefix key.
9295 (defcustom orgstruct-heading-prefix-regexp ""
9296 "Regexp that matches the custom prefix of Org headlines in
9297 orgstruct(++)-mode."
9298 :group 'org
9299 :version "24.4"
9300 :package-version '(Org . "8.3")
9301 :type 'regexp)
9302 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9304 (defcustom orgstruct-setup-hook nil
9305 "Hook run after orgstruct-mode-map is filled."
9306 :group 'org
9307 :version "24.4"
9308 :package-version '(Org . "8.0")
9309 :type 'hook)
9311 (defvar orgstruct-initialized nil)
9313 (defvar org-local-vars nil
9314 "List of local variables, for use by `orgstruct-mode'.")
9316 ;;;###autoload
9317 (define-minor-mode orgstruct-mode
9318 "Toggle the minor mode `orgstruct-mode'.
9319 This mode is for using Org-mode structure commands in other
9320 modes. The following keys behave as if Org-mode were active, if
9321 the cursor is on a headline, or on a plain list item (both as
9322 defined by Org-mode)."
9323 nil " OrgStruct" (make-sparse-keymap)
9324 (funcall (if orgstruct-mode
9325 'add-to-invisibility-spec
9326 'remove-from-invisibility-spec)
9327 '(outline . t))
9328 (when orgstruct-mode
9329 (org-load-modules-maybe)
9330 (unless orgstruct-initialized
9331 (orgstruct-setup)
9332 (setq orgstruct-initialized t))))
9334 ;;;###autoload
9335 (defun turn-on-orgstruct ()
9336 "Unconditionally turn on `orgstruct-mode'."
9337 (orgstruct-mode 1))
9339 (defvar-local orgstruct-is-++ nil
9340 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9341 (defvar-local org-fb-vars nil)
9342 (defun orgstruct++-mode (&optional arg)
9343 "Toggle `orgstruct-mode', the enhanced version of it.
9344 In addition to setting orgstruct-mode, this also exports all
9345 indentation and autofilling variables from org-mode into the
9346 buffer. It will also recognize item context in multiline items."
9347 (interactive "P")
9348 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9349 (if (< arg 1)
9350 (progn (orgstruct-mode -1)
9351 (dolist (v org-fb-vars)
9352 (set (make-local-variable (car v))
9353 (if (eq (car-safe (cadr v)) 'quote)
9354 (cl-cadadr v)
9355 (nth 1 v)))))
9356 (orgstruct-mode 1)
9357 (setq org-fb-vars nil)
9358 (unless org-local-vars
9359 (setq org-local-vars (org-get-local-variables)))
9360 (let (var val)
9361 (dolist (x org-local-vars)
9362 (when (string-match
9363 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9364 \\|fill-prefix\\|indent-\\)"
9365 (symbol-name (car x)))
9366 (setq var (car x) val (nth 1 x))
9367 (push (list var `(quote ,(eval var))) org-fb-vars)
9368 (set (make-local-variable var)
9369 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9370 (setq-local orgstruct-is-++ t))))
9372 ;;;###autoload
9373 (defun turn-on-orgstruct++ ()
9374 "Unconditionally turn on `orgstruct++-mode'."
9375 (orgstruct++-mode 1))
9377 (defun orgstruct-error ()
9378 "Error when there is no default binding for a structure key."
9379 (interactive)
9380 (funcall (if (fboundp 'user-error)
9381 'user-error
9382 'error)
9383 "This key has no function outside structure elements"))
9385 (defun orgstruct-setup ()
9386 "Setup orgstruct keymap."
9387 (dolist (cell '((org-demote . t)
9388 (org-metaleft . t)
9389 (org-metaright . t)
9390 (org-promote . t)
9391 (org-shiftmetaleft . t)
9392 (org-shiftmetaright . t)
9393 org-backward-element
9394 org-backward-heading-same-level
9395 org-ctrl-c-ret
9396 org-ctrl-c-minus
9397 org-ctrl-c-star
9398 org-cycle
9399 org-force-cycle-archived
9400 org-forward-heading-same-level
9401 org-insert-heading
9402 org-insert-heading-respect-content
9403 org-kill-note-or-show-branches
9404 org-mark-subtree
9405 org-meta-return
9406 org-metadown
9407 org-metaup
9408 org-narrow-to-subtree
9409 org-promote-subtree
9410 org-reveal
9411 org-shiftdown
9412 org-shiftleft
9413 org-shiftmetadown
9414 org-shiftmetaup
9415 org-shiftright
9416 org-shifttab
9417 org-shifttab
9418 org-shiftup
9419 org-show-children
9420 org-show-subtree
9421 org-sort
9422 org-up-element
9423 outline-demote
9424 outline-next-visible-heading
9425 outline-previous-visible-heading
9426 outline-promote
9427 outline-up-heading))
9428 (let ((f (or (car-safe cell) cell))
9429 (disable-when-heading-prefix (cdr-safe cell)))
9430 (when (fboundp f)
9431 (let ((new-bindings))
9432 (dolist (binding (nconc (where-is-internal f org-mode-map)
9433 (where-is-internal f outline-mode-map)))
9434 (push binding new-bindings)
9435 ;; TODO use local-function-key-map
9436 (dolist (rep '(("<tab>" . "TAB")
9437 ("<return>" . "RET")
9438 ("<escape>" . "ESC")
9439 ("<delete>" . "DEL")))
9440 (setq binding (read-kbd-macro
9441 (let ((case-fold-search))
9442 (replace-regexp-in-string
9443 (regexp-quote (cdr rep))
9444 (car rep)
9445 (key-description binding)))))
9446 (cl-pushnew binding new-bindings :test 'equal)))
9447 (dolist (binding new-bindings)
9448 (let ((key (lookup-key orgstruct-mode-map binding)))
9449 (when (or (not key) (numberp key))
9450 (ignore-errors
9451 (org-defkey orgstruct-mode-map
9452 binding
9453 (orgstruct-make-binding
9454 f binding disable-when-heading-prefix))))))))))
9455 (run-hooks 'orgstruct-setup-hook))
9457 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9458 "Create a function for binding in the structure minor mode.
9459 FUN is the command to call inside a table. KEY is the key that
9460 should be checked in for a command to execute outside of tables.
9461 Non-nil `disable-when-heading-prefix' means to disable the command
9462 if `orgstruct-heading-prefix-regexp' is not empty."
9463 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9464 (let ((nname name)
9465 (i 0))
9466 (while (fboundp (intern nname))
9467 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9468 (setq name (intern nname)))
9469 (eval
9470 (let ((bindings '((org-heading-regexp
9471 (concat "^"
9472 orgstruct-heading-prefix-regexp
9473 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9474 (org-outline-regexp
9475 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9476 (org-outline-regexp-bol
9477 (concat "^" org-outline-regexp))
9478 (outline-regexp org-outline-regexp)
9479 (outline-heading-end-regexp "\n")
9480 (outline-level 'org-outline-level)
9481 (outline-heading-alist))))
9482 `(defun ,name (arg)
9483 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9484 "Outside of structure, run the binding of `"
9485 (key-description key) "'."
9486 (when disable-when-heading-prefix
9487 (concat
9488 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9489 "back to the default binding due to limitations of Org's implementation of\n"
9490 "`" (symbol-name fun) "'.")))
9491 (interactive "p")
9492 (let* ((disable
9493 ,(and disable-when-heading-prefix
9494 '(not (string= orgstruct-heading-prefix-regexp ""))))
9495 (fallback
9496 (or disable
9497 (not
9498 (let* ,bindings
9499 (org-context-p 'headline 'item
9500 ,(when (memq fun
9501 '(org-insert-heading
9502 org-insert-heading-respect-content
9503 org-meta-return))
9504 '(when orgstruct-is-++
9505 'item-body))))))))
9506 (if fallback
9507 (let* ((orgstruct-mode)
9508 (binding
9509 (let ((key ,key))
9510 (catch 'exit
9511 (dolist
9512 (rep
9513 '(nil
9514 ("<\\([^>]*\\)tab>" . "\\1TAB")
9515 ("<\\([^>]*\\)return>" . "\\1RET")
9516 ("<\\([^>]*\\)escape>" . "\\1ESC")
9517 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9518 nil)
9519 (when rep
9520 (setq key (read-kbd-macro
9521 (let ((case-fold-search))
9522 (replace-regexp-in-string
9523 (car rep)
9524 (cdr rep)
9525 (key-description key))))))
9526 (when (key-binding key)
9527 (throw 'exit (key-binding key))))))))
9528 (if (keymapp binding)
9529 (org-set-transient-map binding)
9530 (let ((func (or binding
9531 (unless disable
9532 'orgstruct-error))))
9533 (when func
9534 (call-interactively func)))))
9535 (org-run-like-in-org-mode
9536 (lambda ()
9537 (interactive)
9538 (let* ,bindings
9539 (call-interactively ',fun)))))))))
9540 name))
9542 (defun org-contextualize-keys (alist contexts)
9543 "Return valid elements in ALIST depending on CONTEXTS.
9545 `org-agenda-custom-commands' or `org-capture-templates' are the
9546 values used for ALIST, and `org-agenda-custom-commands-contexts'
9547 or `org-capture-templates-contexts' are the associated contexts
9548 definitions."
9549 (let ((contexts
9550 ;; normalize contexts
9551 (mapcar
9552 (lambda(c) (cond ((listp (cadr c))
9553 (list (car c) (car c) (nth 1 c)))
9554 ((string= "" (cadr c))
9555 (list (car c) (car c) (nth 2 c)))
9556 (t c)))
9557 contexts))
9558 (a alist) r s)
9559 ;; loop over all commands or templates
9560 (dolist (c a)
9561 (let (vrules repl)
9562 (cond
9563 ((not (assoc (car c) contexts))
9564 (push c r))
9565 ((and (assoc (car c) contexts)
9566 (setq vrules (org-contextualize-validate-key
9567 (car c) contexts)))
9568 (mapc (lambda (vr)
9569 (unless (equal (car vr) (cadr vr))
9570 (setq repl vr)))
9571 vrules)
9572 (if (not repl) (push c r)
9573 (push (cadr repl) s)
9574 (push
9575 (cons (car c)
9576 (cdr (or (assoc (cadr repl) alist)
9577 (error "Undefined key `%s' as contextual replacement for `%s'"
9578 (cadr repl) (car c)))))
9579 r))))))
9580 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9581 (delq
9583 (delete-dups
9584 (mapcar (lambda (x)
9585 (let ((tpl (car x)))
9586 (unless (delq
9588 (mapcar (lambda (y)
9589 (equal y tpl))
9591 x)))
9592 (reverse r))))))
9594 (defun org-contextualize-validate-key (key contexts)
9595 "Check CONTEXTS for agenda or capture KEY."
9596 (let (res)
9597 (dolist (r contexts)
9598 (dolist (rr (car (last r)))
9599 (when
9600 (and (equal key (car r))
9601 (if (functionp rr) (funcall rr)
9602 (or (and (eq (car rr) 'in-file)
9603 (buffer-file-name)
9604 (string-match (cdr rr) (buffer-file-name)))
9605 (and (eq (car rr) 'in-mode)
9606 (string-match (cdr rr) (symbol-name major-mode)))
9607 (and (eq (car rr) 'in-buffer)
9608 (string-match (cdr rr) (buffer-name)))
9609 (when (and (eq (car rr) 'not-in-file)
9610 (buffer-file-name))
9611 (not (string-match (cdr rr) (buffer-file-name))))
9612 (when (eq (car rr) 'not-in-mode)
9613 (not (string-match (cdr rr) (symbol-name major-mode))))
9614 (when (eq (car rr) 'not-in-buffer)
9615 (not (string-match (cdr rr) (buffer-name)))))))
9616 (push r res))))
9617 (delete-dups (delq nil res))))
9619 (defun org-context-p (&rest contexts)
9620 "Check if local context is any of CONTEXTS.
9621 Possible values in the list of contexts are `table', `headline', and `item'."
9622 (let ((pos (point)))
9623 (goto-char (point-at-bol))
9624 (prog1 (or (and (memq 'table contexts)
9625 (looking-at "[ \t]*|"))
9626 (and (memq 'headline contexts)
9627 (looking-at org-outline-regexp))
9628 (and (memq 'item contexts)
9629 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9630 (and (memq 'item-body contexts)
9631 (org-in-item-p)))
9632 (goto-char pos))))
9634 (defconst org-unique-local-variables
9635 '(org-element--cache
9636 org-element--cache-objects
9637 org-element--cache-sync-keys
9638 org-element--cache-sync-requests
9639 org-element--cache-sync-timer)
9640 "List of local variables that cannot be transferred to another buffer.")
9642 (defun org-get-local-variables ()
9643 "Return a list of all local variables in an Org mode buffer."
9644 (delq nil
9645 (mapcar
9646 (lambda (x)
9647 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9648 (name (car binding)))
9649 (and (not (get name 'org-state))
9650 (not (memq name org-unique-local-variables))
9651 (string-match-p
9652 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9653 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9654 (symbol-name name))
9655 binding)))
9656 (with-temp-buffer
9657 (org-mode)
9658 (buffer-local-variables)))))
9660 (defun org-clone-local-variables (from-buffer &optional regexp)
9661 "Clone local variables from FROM-BUFFER.
9662 Optional argument REGEXP selects variables to clone."
9663 (dolist (pair (buffer-local-variables from-buffer))
9664 (let ((name (car pair)))
9665 (when (and (symbolp name)
9666 (not (memq name org-unique-local-variables))
9667 (or (null regexp) (string-match regexp (symbol-name name))))
9668 (set (make-local-variable name) (cdr pair))))))
9670 ;;;###autoload
9671 (defun org-run-like-in-org-mode (cmd)
9672 "Run a command, pretending that the current buffer is in Org-mode.
9673 This will temporarily bind local variables that are typically bound in
9674 Org-mode to the values they have in Org-mode, and then interactively
9675 call CMD."
9676 (org-load-modules-maybe)
9677 (unless org-local-vars
9678 (setq org-local-vars (org-get-local-variables)))
9679 (let (binds)
9680 (dolist (var org-local-vars)
9681 (when (or (not (boundp (car var)))
9682 (eq (symbol-value (car var))
9683 (default-value (car var))))
9684 (push (list (car var) `(quote ,(cadr var))) binds)))
9685 (eval `(let ,binds
9686 (call-interactively (quote ,cmd))))))
9688 (defun org-get-category (&optional pos force-refresh)
9689 "Get the category applying to position POS."
9690 (save-match-data
9691 (when force-refresh (org-refresh-category-properties))
9692 (let ((pos (or pos (point))))
9693 (or (get-text-property pos 'org-category)
9694 (progn (org-refresh-category-properties)
9695 (get-text-property pos 'org-category))))))
9697 ;;; Refresh properties
9699 (defun org-refresh-properties (dprop tprop)
9700 "Refresh buffer text properties.
9701 DPROP is the drawer property and TPROP is either the
9702 corresponding text property to set, or an alist with each element
9703 being a text property (as a symbol) and a function to apply to
9704 the value of the drawer property."
9705 (let ((case-fold-search t)
9706 (inhibit-read-only t))
9707 (org-with-silent-modifications
9708 (save-excursion
9709 (save-restriction
9710 (widen)
9711 (goto-char (point-min))
9712 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9713 (org-refresh-property tprop (match-string-no-properties 1))))))))
9715 (defun org-refresh-property (tprop p)
9716 "Refresh the buffer text property TPROP from the drawer property P.
9717 The refresh happens only for the current tree (not subtree)."
9718 (unless (org-before-first-heading-p)
9719 (save-excursion
9720 (org-back-to-heading t)
9721 (if (symbolp tprop)
9722 ;; TPROP is a text property symbol
9723 (put-text-property
9724 (point) (or (outline-next-heading) (point-max)) tprop p)
9725 ;; TPROP is an alist with (properties . function) elements
9726 (dolist (al tprop)
9727 (save-excursion
9728 (put-text-property
9729 (line-beginning-position) (or (outline-next-heading) (point-max))
9730 (car al)
9731 (funcall (cdr al) p))))))))
9733 (defun org-refresh-category-properties ()
9734 "Refresh category text properties in the buffer."
9735 (let ((case-fold-search t)
9736 (inhibit-read-only t)
9737 (default-category
9738 (cond ((null org-category)
9739 (if buffer-file-name
9740 (file-name-sans-extension
9741 (file-name-nondirectory buffer-file-name))
9742 "???"))
9743 ((symbolp org-category) (symbol-name org-category))
9744 (t org-category))))
9745 (org-with-silent-modifications
9746 (org-with-wide-buffer
9747 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9748 ;; This is the default category for the buffer. If none is
9749 ;; found, fall-back to `org-category' or buffer file name.
9750 (put-text-property
9751 (point-min) (point-max)
9752 'org-category
9753 (catch 'buffer-category
9754 (goto-char (point-max))
9755 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9756 (let ((element (org-element-at-point)))
9757 (when (eq (org-element-type element) 'keyword)
9758 (throw 'buffer-category
9759 (org-element-property :value element)))))
9760 default-category))
9761 ;; Set sub-tree specific categories.
9762 (goto-char (point-min))
9763 (let ((regexp (org-re-property "CATEGORY")))
9764 (while (re-search-forward regexp nil t)
9765 (let ((value (match-string-no-properties 3)))
9766 (when (org-at-property-p)
9767 (put-text-property
9768 (save-excursion (org-back-to-heading t) (point))
9769 (save-excursion (org-end-of-subtree t t) (point))
9770 'org-category
9771 value)))))))))
9773 (defun org-refresh-stats-properties ()
9774 "Refresh stats text properties in the buffer."
9775 (let (stats)
9776 (org-with-silent-modifications
9777 (save-excursion
9778 (save-restriction
9779 (widen)
9780 (goto-char (point-min))
9781 (while (re-search-forward
9782 (concat org-outline-regexp-bol ".*"
9783 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9784 nil t)
9785 (setq stats (cond ((equal (match-string 3) "0") 0)
9786 ((match-string 2)
9787 (/ (* (string-to-number (match-string 2)) 100)
9788 (string-to-number (match-string 3))))
9789 (t (string-to-number (match-string 1)))))
9790 (org-back-to-heading t)
9791 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9792 'org-stats stats)))))))
9794 (defun org-refresh-effort-properties ()
9795 "Refresh effort properties"
9796 (org-refresh-properties
9797 org-effort-property
9798 '((effort . identity)
9799 (effort-minutes . org-duration-string-to-minutes))))
9801 ;;;; Link Stuff
9803 ;;; Link abbreviations
9805 (defun org-link-expand-abbrev (link)
9806 "Apply replacements as defined in `org-link-abbrev-alist'."
9807 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9808 (let* ((key (match-string 1 link))
9809 (as (or (assoc key org-link-abbrev-alist-local)
9810 (assoc key org-link-abbrev-alist)))
9811 (tag (and (match-end 2) (match-string 3 link)))
9812 rpl)
9813 (if (not as)
9814 link
9815 (setq rpl (cdr as))
9816 (cond
9817 ((symbolp rpl) (funcall rpl tag))
9818 ((string-match "%(\\([^)]+\\))" rpl)
9819 (replace-match
9820 (save-match-data
9821 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9822 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9823 ((string-match "%h" rpl)
9824 (replace-match (url-hexify-string (or tag "")) t t rpl))
9825 (t (concat rpl tag)))))
9826 link))
9828 ;;; Storing and inserting links
9830 (defvar org-insert-link-history nil
9831 "Minibuffer history for links inserted with `org-insert-link'.")
9833 (defvar org-stored-links nil
9834 "Contains the links stored with `org-store-link'.")
9836 (defvar org-store-link-plist nil
9837 "Plist with info about the most recently link created with `org-store-link'.")
9839 (defun org-store-link-functions ()
9840 "Return a list of functions that are called to create and store a link.
9841 The functions defined in the :store property of
9842 `org-link-parameters'.
9844 Each function will be called in turn until one returns a non-nil
9845 value. Each function should check if it is responsible for
9846 creating this link (for example by looking at the major mode).
9847 If not, it must exit and return nil. If yes, it should return
9848 a non-nil value after calling `org-store-link-props' with a list
9849 of properties and values. Special properties are:
9851 :type The link prefix, like \"http\". This must be given.
9852 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9853 This is obligatory as well.
9854 :description Optional default description for the second pair
9855 of brackets in an Org mode link. The user can still change
9856 this when inserting this link into an Org mode buffer.
9858 In addition to these, any additional properties can be specified
9859 and then used in capture templates."
9860 (cl-loop for link in org-link-parameters
9861 with store-func
9862 do (setq store-func (org-link-get-parameter (car link) :store))
9863 if store-func
9864 collect store-func))
9866 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9867 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9869 ;;;###autoload
9870 (defun org-store-link (arg)
9871 "\\<org-mode-map>Store an org-link to the current location.
9872 This link is added to `org-stored-links' and can later be inserted
9873 into an Org buffer with \\[org-insert-link].
9875 For some link types, a prefix ARG is interpreted.
9876 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9877 For file links, ARG negates `org-context-in-file-links'.
9879 A double prefix ARG force skipping storing functions that are not
9880 part of Org's core.
9882 A triple prefix ARG force storing a link for each line in the
9883 active region."
9884 (interactive "P")
9885 (org-load-modules-maybe)
9886 (if (and (equal arg '(64)) (org-region-active-p))
9887 (save-excursion
9888 (let ((end (region-end)))
9889 (goto-char (region-beginning))
9890 (set-mark (point))
9891 (while (< (point-at-eol) end)
9892 (move-end-of-line 1) (activate-mark)
9893 (let (current-prefix-arg)
9894 (call-interactively 'org-store-link))
9895 (move-beginning-of-line 2)
9896 (set-mark (point)))))
9897 (org-with-limited-levels
9898 (setq org-store-link-plist nil)
9899 (let (link cpltxt desc description search
9900 txt custom-id agenda-link sfuns sfunsn)
9901 (cond
9903 ;; Store a link using an external link type
9904 ((and (not (equal arg '(16)))
9905 (setq sfuns
9906 (delq
9907 nil (mapcar (lambda (f)
9908 (let (fs) (if (funcall f) (push f fs))))
9909 (org-store-link-functions)))
9910 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9911 (or (and (cdr sfuns)
9912 (funcall (intern
9913 (completing-read
9914 "Which function for creating the link? "
9915 sfunsn nil t (car sfunsn)))))
9916 (funcall (caar sfuns)))
9917 (setq link (plist-get org-store-link-plist :link)
9918 desc (or (plist-get org-store-link-plist
9919 :description)
9920 link))))
9922 ;; Store a link from a source code buffer.
9923 ((org-src-edit-buffer-p)
9924 (cond
9925 ((save-excursion
9926 (beginning-of-line)
9927 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9928 "[ \t]*$")))
9929 (setq link (format "(%s)" (match-string-no-properties 1))))
9930 ((called-interactively-p 'any)
9931 (let (label)
9932 (while (or (not label)
9933 (org-with-wide-buffer
9934 (goto-char (point-min))
9935 (re-search-forward
9936 (regexp-quote (format org-coderef-label-format label))
9937 nil t)))
9938 (when label (message "Label exists already") (sit-for 2))
9939 (setq label (read-string "Code line label: " label)))
9940 (end-of-line)
9941 (setq link (format org-coderef-label-format label))
9942 (let ((gc (- 79 (length link))))
9943 (if (< (current-column) gc) (org-move-to-column gc t)
9944 (insert " ")))
9945 (insert link)
9946 (setq link (concat "(" label ")") desc nil)))
9947 (t (setq link nil))))
9949 ;; We are in the agenda, link to referenced location
9950 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9951 (let ((m (or (get-text-property (point) 'org-hd-marker)
9952 (get-text-property (point) 'org-marker))))
9953 (when m
9954 (org-with-point-at m
9955 (setq agenda-link
9956 (if (called-interactively-p 'any)
9957 (call-interactively 'org-store-link)
9958 (org-store-link nil)))))))
9960 ((eq major-mode 'calendar-mode)
9961 (let ((cd (calendar-cursor-to-date)))
9962 (setq link
9963 (format-time-string
9964 (car org-time-stamp-formats)
9965 (apply 'encode-time
9966 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9967 nil nil nil))))
9968 (org-store-link-props :type "calendar" :date cd)))
9970 ((eq major-mode 'help-mode)
9971 (setq link (concat "help:" (save-excursion
9972 (goto-char (point-min))
9973 (looking-at "^[^ ]+")
9974 (match-string 0))))
9975 (org-store-link-props :type "help"))
9977 ((eq major-mode 'w3-mode)
9978 (setq cpltxt (if (and (buffer-name)
9979 (not (string-match "Untitled" (buffer-name))))
9980 (buffer-name)
9981 (url-view-url t))
9982 link (url-view-url t))
9983 (org-store-link-props :type "w3" :url (url-view-url t)))
9985 ((eq major-mode 'image-mode)
9986 (setq cpltxt (concat "file:"
9987 (abbreviate-file-name buffer-file-name))
9988 link cpltxt)
9989 (org-store-link-props :type "image" :file buffer-file-name))
9991 ;; In dired, store a link to the file of the current line
9992 ((derived-mode-p 'dired-mode)
9993 (let ((file (dired-get-filename nil t)))
9994 (setq file (if file
9995 (abbreviate-file-name
9996 (expand-file-name (dired-get-filename nil t)))
9997 ;; otherwise, no file so use current directory.
9998 default-directory))
9999 (setq cpltxt (concat "file:" file)
10000 link cpltxt)))
10002 ((setq search (run-hook-with-args-until-success
10003 'org-create-file-search-functions))
10004 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10005 "::" search))
10006 (setq cpltxt (or description link)))
10008 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10009 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10010 (cond
10011 ;; Store a link using the target at point
10012 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10013 (setq cpltxt
10014 (concat "file:"
10015 (abbreviate-file-name
10016 (buffer-file-name (buffer-base-buffer)))
10017 "::" (match-string 1))
10018 link cpltxt))
10019 ((and (featurep 'org-id)
10020 (or (eq org-id-link-to-org-use-id t)
10021 (and (called-interactively-p 'any)
10022 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10023 (and (eq org-id-link-to-org-use-id
10024 'create-if-interactive-and-no-custom-id)
10025 (not custom-id))))
10026 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10027 ;; Store a link using the ID at point
10028 (setq link (condition-case nil
10029 (prog1 (org-id-store-link)
10030 (setq desc (or (plist-get org-store-link-plist
10031 :description)
10032 "")))
10033 (error
10034 ;; Probably before first headline, link only to file
10035 (concat "file:"
10036 (abbreviate-file-name
10037 (buffer-file-name (buffer-base-buffer))))))))
10039 ;; Just link to current headline
10040 (setq cpltxt (concat "file:"
10041 (abbreviate-file-name
10042 (buffer-file-name (buffer-base-buffer)))))
10043 ;; Add a context search string
10044 (when (org-xor org-context-in-file-links arg)
10045 (let* ((element (org-element-at-point))
10046 (name (org-element-property :name element)))
10047 (setq txt (cond
10048 ((org-at-heading-p) nil)
10049 (name)
10050 ((org-region-active-p)
10051 (buffer-substring (region-beginning) (region-end)))))
10052 (when (or (null txt) (string-match "\\S-" txt))
10053 (setq cpltxt
10054 (concat cpltxt "::"
10055 (condition-case nil
10056 (org-make-org-heading-search-string txt)
10057 (error "")))
10058 desc (or name
10059 (nth 4 (ignore-errors (org-heading-components)))
10060 "NONE")))))
10061 (when (string-match "::\\'" cpltxt)
10062 (setq cpltxt (substring cpltxt 0 -2)))
10063 (setq link cpltxt))))
10065 ((buffer-file-name (buffer-base-buffer))
10066 ;; Just link to this file here.
10067 (setq cpltxt (concat "file:"
10068 (abbreviate-file-name
10069 (buffer-file-name (buffer-base-buffer)))))
10070 ;; Add a context string.
10071 (when (org-xor org-context-in-file-links arg)
10072 (setq txt (if (org-region-active-p)
10073 (buffer-substring (region-beginning) (region-end))
10074 (buffer-substring (point-at-bol) (point-at-eol))))
10075 ;; Only use search option if there is some text.
10076 (when (string-match "\\S-" txt)
10077 (setq cpltxt
10078 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10079 desc "NONE")))
10080 (setq link cpltxt))
10082 ((called-interactively-p 'interactive)
10083 (user-error "No method for storing a link from this buffer"))
10085 (t (setq link nil)))
10087 ;; We're done setting link and desc, clean up
10088 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10089 (setq link (or link cpltxt)
10090 desc (or desc cpltxt))
10091 (cond ((not desc))
10092 ((equal desc "NONE") (setq desc nil))
10093 (t (setq desc
10094 (replace-regexp-in-string
10095 org-bracket-link-analytic-regexp
10096 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10097 desc))))
10098 ;; Return the link
10099 (if (not (and (or (called-interactively-p 'any)
10100 executing-kbd-macro)
10101 link))
10102 (or agenda-link (and link (org-make-link-string link desc)))
10103 (push (list link desc) org-stored-links)
10104 (message "Stored: %s" (or desc link))
10105 (when custom-id
10106 (setq link (concat "file:" (abbreviate-file-name
10107 (buffer-file-name)) "::#" custom-id))
10108 (push (list link desc) org-stored-links))
10109 (car org-stored-links))))))
10111 (defun org-store-link-props (&rest plist)
10112 "Store link properties, extract names, addresses and dates."
10113 (let ((x (plist-get plist :from)))
10114 (when x
10115 (let ((adr (mail-extract-address-components x)))
10116 (setq plist (plist-put plist :fromname (car adr)))
10117 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10118 (let ((x (plist-get plist :to)))
10119 (when x
10120 (let ((adr (mail-extract-address-components x)))
10121 (setq plist (plist-put plist :toname (car adr)))
10122 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10123 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10124 (when x
10125 (setq plist (plist-put plist :date-timestamp
10126 (format-time-string
10127 (org-time-stamp-format t) x)))
10128 (setq plist (plist-put plist :date-timestamp-inactive
10129 (format-time-string
10130 (org-time-stamp-format t t) x)))))
10131 (let ((from (plist-get plist :from))
10132 (to (plist-get plist :to)))
10133 (when (and from to org-from-is-user-regexp)
10134 (setq plist
10135 (plist-put plist :fromto
10136 (if (string-match org-from-is-user-regexp from)
10137 (concat "to %t")
10138 (concat "from %f"))))))
10139 (setq org-store-link-plist plist))
10141 (defun org-add-link-props (&rest plist)
10142 "Add these properties to the link property list."
10143 (let (key value)
10144 (while plist
10145 (setq key (pop plist) value (pop plist))
10146 (setq org-store-link-plist
10147 (plist-put org-store-link-plist key value)))))
10149 (defun org-email-link-description (&optional fmt)
10150 "Return the description part of an email link.
10151 This takes information from `org-store-link-plist' and formats it
10152 according to FMT (default from `org-email-link-description-format')."
10153 (setq fmt (or fmt org-email-link-description-format))
10154 (let* ((p org-store-link-plist)
10155 (to (plist-get p :toaddress))
10156 (from (plist-get p :fromaddress))
10157 (table
10158 (list
10159 (cons "%c" (plist-get p :fromto))
10160 (cons "%F" (plist-get p :from))
10161 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10162 (cons "%T" (plist-get p :to))
10163 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10164 (cons "%s" (plist-get p :subject))
10165 (cons "%d" (plist-get p :date))
10166 (cons "%m" (plist-get p :message-id)))))
10167 (when (string-match "%c" fmt)
10168 ;; Check if the user wrote this message
10169 (if (and org-from-is-user-regexp from to
10170 (save-match-data (string-match org-from-is-user-regexp from)))
10171 (setq fmt (replace-match "to %t" t t fmt))
10172 (setq fmt (replace-match "from %f" t t fmt))))
10173 (org-replace-escapes fmt table)))
10175 (defun org-make-org-heading-search-string (&optional string)
10176 "Make search string for the current headline or STRING."
10177 (let ((s (or string
10178 (and (derived-mode-p 'org-mode)
10179 (save-excursion
10180 (org-back-to-heading t)
10181 (org-element-property :raw-value (org-element-at-point))))))
10182 (lines org-context-in-file-links))
10183 (or string (setq s (concat "*" s))) ; Add * for headlines
10184 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10185 (when (and string (integerp lines) (> lines 0))
10186 (let ((slines (org-split-string s "\n")))
10187 (when (< lines (length slines))
10188 (setq s (mapconcat
10189 'identity
10190 (reverse (nthcdr (- (length slines) lines)
10191 (reverse slines))) "\n")))))
10192 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10194 (defun org-make-link-string (link &optional description)
10195 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10196 (unless (org-string-nw-p link) (error "Empty link"))
10197 (let ((uri (cond ((string-match org-link-types-re link)
10198 (concat (match-string 1 link)
10199 (org-link-escape (substring link (match-end 1)))))
10200 ;; For readability, url-encode internal links only
10201 ;; when absolutely needed (i.e, when they contain
10202 ;; square brackets). File links however, are
10203 ;; encoded since, e.g., spaces are significant.
10204 ((or (file-name-absolute-p link)
10205 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10206 (org-link-escape link))
10207 (t link)))
10208 (description
10209 (and (org-string-nw-p description)
10210 ;; Remove brackets from description, as they are fatal.
10211 (replace-regexp-in-string
10212 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10213 (org-trim description)))))
10214 (format "[[%s]%s]"
10216 (if description (format "[%s]" description) ""))))
10218 (defconst org-link-escape-chars
10219 ;;%20 %5B %5D %25
10220 '(?\s ?\[ ?\] ?%)
10221 "List of characters that should be escaped in a link when stored to Org.
10222 This is the list that is used for internal purposes.")
10224 (defun org-link-escape (text &optional table merge)
10225 "Return percent escaped representation of TEXT.
10226 TEXT is a string with the text to escape.
10227 Optional argument TABLE is a list with characters that should be
10228 escaped. When nil, `org-link-escape-chars' is used.
10229 If optional argument MERGE is set, merge TABLE into
10230 `org-link-escape-chars'."
10231 (let ((characters-to-encode
10232 (cond ((null table) org-link-escape-chars)
10233 (merge (append org-link-escape-chars table))
10234 (t table))))
10235 (mapconcat
10236 (lambda (c)
10237 (if (or (memq c characters-to-encode)
10238 (and org-url-hexify-p (or (< c 32) (> c 126))))
10239 (mapconcat (lambda (e) (format "%%%.2X" e))
10240 (or (encode-coding-char c 'utf-8)
10241 (error "Unable to percent escape character: %c" c))
10243 (char-to-string c)))
10244 text "")))
10246 (defun org-link-unescape (str)
10247 "Unhex hexified Unicode parts in string STR.
10248 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10249 reciprocal of `org-link-escape', which see."
10250 (if (org-string-nw-p str)
10251 (replace-regexp-in-string
10252 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10253 str))
10255 (defun org-link-unescape-compound (hex)
10256 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10257 Note: this function also decodes single byte encodings like
10258 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10259 (save-match-data
10260 (let* ((bytes (cdr (split-string hex "%")))
10261 (ret "")
10262 (eat 0)
10263 (sum 0))
10264 (while bytes
10265 (let* ((val (string-to-number (pop bytes) 16))
10266 (shift-xor
10267 (if (= 0 eat)
10268 (cond
10269 ((>= val 252) (cons 6 252))
10270 ((>= val 248) (cons 5 248))
10271 ((>= val 240) (cons 4 240))
10272 ((>= val 224) (cons 3 224))
10273 ((>= val 192) (cons 2 192))
10274 (t (cons 0 0)))
10275 (cons 6 128))))
10276 (when (>= val 192) (setq eat (car shift-xor)))
10277 (setq val (logxor val (cdr shift-xor)))
10278 (setq sum (+ (lsh sum (car shift-xor)) val))
10279 (when (> eat 0) (setq eat (- eat 1)))
10280 (cond
10281 ((= 0 eat) ;multi byte
10282 (setq ret (concat ret (char-to-string sum)))
10283 (setq sum 0))
10284 ((not bytes) ; single byte(s)
10285 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10286 ret)))
10288 (defun org-link-unescape-single-byte-sequence (hex)
10289 "Unhexify hex-encoded single byte character sequences."
10290 (mapconcat (lambda (byte)
10291 (char-to-string (string-to-number byte 16)))
10292 (cdr (split-string hex "%")) ""))
10294 (defun org-xor (a b)
10295 "Exclusive or."
10296 (if a (not b) b))
10298 (defun org-fixup-message-id-for-http (s)
10299 "Replace special characters in a message id, so it can be used in an http query."
10300 (when (string-match "%" s)
10301 (setq s (mapconcat (lambda (c)
10302 (if (eq c ?%)
10303 "%25"
10304 (char-to-string c)))
10305 s "")))
10306 (while (string-match "<" s)
10307 (setq s (replace-match "%3C" t t s)))
10308 (while (string-match ">" s)
10309 (setq s (replace-match "%3E" t t s)))
10310 (while (string-match "@" s)
10311 (setq s (replace-match "%40" t t s)))
10314 (defun org-link-prettify (link)
10315 "Return a human-readable representation of LINK.
10316 The car of LINK must be a raw link.
10317 The cdr of LINK must be either a link description or nil."
10318 (let ((desc (or (cadr link) "<no description>")))
10319 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10320 "<" (car link) ">")))
10322 ;;;###autoload
10323 (defun org-insert-link-global ()
10324 "Insert a link like Org-mode does.
10325 This command can be called in any mode to insert a link in Org-mode syntax."
10326 (interactive)
10327 (org-load-modules-maybe)
10328 (org-run-like-in-org-mode 'org-insert-link))
10330 (defun org-insert-all-links (arg &optional pre post)
10331 "Insert all links in `org-stored-links'.
10332 When a universal prefix, do not delete the links from `org-stored-links'.
10333 When `ARG' is a number, insert the last N link(s).
10334 `PRE' and `POST' are optional arguments to define a string to
10335 prepend or to append."
10336 (interactive "P")
10337 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10338 (links (copy-sequence org-stored-links))
10339 (pr (or pre "- "))
10340 (po (or post "\n"))
10341 (cnt 1) l)
10342 (if (null org-stored-links)
10343 (message "No link to insert")
10344 (while (and (or (listp arg) (>= arg cnt))
10345 (setq l (if (listp arg)
10346 (pop links)
10347 (pop org-stored-links))))
10348 (setq cnt (1+ cnt))
10349 (insert pr)
10350 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10351 (insert po)))))
10353 (defun org-insert-last-stored-link (arg)
10354 "Insert the last link stored in `org-stored-links'."
10355 (interactive "p")
10356 (org-insert-all-links arg "" "\n"))
10358 (defun org-link-fontify-links-to-this-file ()
10359 "Fontify links to the current file in `org-stored-links'."
10360 (let ((f (buffer-file-name)) a b)
10361 (setq a (mapcar (lambda(l)
10362 (let ((ll (car l)))
10363 (when (and (string-match "^file:\\(.+\\)::" ll)
10364 (equal f (expand-file-name (match-string 1 ll))))
10365 ll)))
10366 org-stored-links))
10367 (when (featurep 'org-id)
10368 (setq b (mapcar (lambda(l)
10369 (let ((ll (car l)))
10370 (when (and (string-match "^id:\\(.+\\)$" ll)
10371 (equal f (expand-file-name
10372 (or (org-id-find-id-file
10373 (match-string 1 ll)) ""))))
10374 ll)))
10375 org-stored-links)))
10376 (mapcar (lambda(l)
10377 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10378 (delq nil (append a b)))))
10380 (defvar org--links-history nil)
10381 (defun org-insert-link (&optional complete-file link-location default-description)
10382 "Insert a link. At the prompt, enter the link.
10384 Completion can be used to insert any of the link protocol prefixes like
10385 http or ftp in use.
10387 The history can be used to select a link previously stored with
10388 `org-store-link'. When the empty string is entered (i.e. if you just
10389 press RET at the prompt), the link defaults to the most recently
10390 stored link. As SPC triggers completion in the minibuffer, you need to
10391 use M-SPC or C-q SPC to force the insertion of a space character.
10393 You will also be prompted for a description, and if one is given, it will
10394 be displayed in the buffer instead of the link.
10396 If there is already a link at point, this command will allow you to edit link
10397 and description parts.
10399 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10400 be selected using completion. The path to the file will be relative to the
10401 current directory if the file is in the current directory or a subdirectory.
10402 Otherwise, the link will be the absolute path as completed in the minibuffer
10403 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10404 option `org-link-file-path-type'.
10406 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10407 the current directory or below.
10409 With three \\[universal-argument] prefixes, negate the meaning of
10410 `org-keep-stored-link-after-insertion'.
10412 If `org-make-link-description-function' is non-nil, this function will be
10413 called with the link target, and the result will be the default
10414 link description.
10416 If the LINK-LOCATION parameter is non-nil, this value will be
10417 used as the link location instead of reading one interactively.
10419 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10420 be used as the default description."
10421 (interactive "P")
10422 (let* ((wcf (current-window-configuration))
10423 (origbuf (current-buffer))
10424 (region (when (org-region-active-p)
10425 (buffer-substring (region-beginning) (region-end))))
10426 (remove (and region (list (region-beginning) (region-end))))
10427 (desc region)
10428 (link link-location)
10429 (abbrevs org-link-abbrev-alist-local)
10430 entry all-prefixes auto-desc)
10431 (cond
10432 (link-location) ; specified by arg, just use it.
10433 ((org-in-regexp org-bracket-link-regexp 1)
10434 ;; We do have a link at point, and we are going to edit it.
10435 (setq remove (list (match-beginning 0) (match-end 0)))
10436 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10437 (setq link (read-string "Link: "
10438 (org-link-unescape
10439 (match-string-no-properties 1)))))
10440 ((or (org-in-regexp org-angle-link-re)
10441 (org-in-regexp org-plain-link-re))
10442 ;; Convert to bracket link
10443 (setq remove (list (match-beginning 0) (match-end 0))
10444 link (read-string "Link: "
10445 (org-remove-angle-brackets (match-string 0)))))
10446 ((member complete-file '((4) (16)))
10447 ;; Completing read for file names.
10448 (setq link (org-file-complete-link complete-file)))
10450 ;; Read link, with completion for stored links.
10451 (org-link-fontify-links-to-this-file)
10452 (org-switch-to-buffer-other-window "*Org Links*")
10453 (with-current-buffer "*Org Links*"
10454 (erase-buffer)
10455 (insert "Insert a link.
10456 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10457 (when org-stored-links
10458 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10459 (insert (mapconcat 'org-link-prettify
10460 (reverse org-stored-links) "\n")))
10461 (goto-char (point-min)))
10462 (let ((cw (selected-window)))
10463 (select-window (get-buffer-window "*Org Links*" 'visible))
10464 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10465 (unless (pos-visible-in-window-p (point-max))
10466 (org-fit-window-to-buffer))
10467 (and (window-live-p cw) (select-window cw)))
10468 (setq all-prefixes (append (mapcar 'car abbrevs)
10469 (mapcar 'car org-link-abbrev-alist)
10470 (org-link-types)))
10471 (unwind-protect
10472 ;; Fake a link history, containing the stored links.
10473 (let ((org--links-history
10474 (append (mapcar #'car org-stored-links)
10475 org-insert-link-history)))
10476 (setq link
10477 (org-completing-read
10478 "Link: "
10479 (append
10480 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10481 (mapcar #'car org-stored-links))
10482 nil nil nil
10483 'org--links-history
10484 (caar org-stored-links)))
10485 (unless (org-string-nw-p link) (user-error "No link selected"))
10486 (dolist (l org-stored-links)
10487 (when (equal link (cadr l))
10488 (setq link (car l))
10489 (setq auto-desc t)))
10490 (when (or (member link all-prefixes)
10491 (and (equal ":" (substring link -1))
10492 (member (substring link 0 -1) all-prefixes)
10493 (setq link (substring link 0 -1))))
10494 (setq link (with-current-buffer origbuf
10495 (org-link-try-special-completion link)))))
10496 (set-window-configuration wcf)
10497 (kill-buffer "*Org Links*"))
10498 (setq entry (assoc link org-stored-links))
10499 (or entry (push link org-insert-link-history))
10500 (setq desc (or desc (nth 1 entry)))))
10502 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10503 (not org-keep-stored-link-after-insertion))
10504 (setq org-stored-links (delq (assoc link org-stored-links)
10505 org-stored-links)))
10507 (when (and (string-match org-plain-link-re link)
10508 (not (string-match org-ts-regexp link)))
10509 ;; URL-like link, normalize the use of angular brackets.
10510 (setq link (org-remove-angle-brackets link)))
10512 ;; Check if we are linking to the current file with a search
10513 ;; option If yes, simplify the link by using only the search
10514 ;; option.
10515 (when (and buffer-file-name
10516 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10517 (let* ((path (match-string 1 link))
10518 (case-fold-search nil)
10519 (search (match-string 2 link)))
10520 (save-match-data
10521 (when (equal (file-truename buffer-file-name) (file-truename path))
10522 ;; We are linking to this same file, with a search option
10523 (setq link search)))))
10525 ;; Check if we can/should use a relative path. If yes, simplify the link
10526 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10527 (let* ((type (match-string 1 link))
10528 (path (match-string 2 link))
10529 (origpath path)
10530 (case-fold-search nil))
10531 (cond
10532 ((or (eq org-link-file-path-type 'absolute)
10533 (equal complete-file '(16)))
10534 (setq path (abbreviate-file-name (expand-file-name path))))
10535 ((eq org-link-file-path-type 'noabbrev)
10536 (setq path (expand-file-name path)))
10537 ((eq org-link-file-path-type 'relative)
10538 (setq path (file-relative-name path)))
10540 (save-match-data
10541 (if (string-match (concat "^" (regexp-quote
10542 (expand-file-name
10543 (file-name-as-directory
10544 default-directory))))
10545 (expand-file-name path))
10546 ;; We are linking a file with relative path name.
10547 (setq path (substring (expand-file-name path)
10548 (match-end 0)))
10549 (setq path (abbreviate-file-name (expand-file-name path)))))))
10550 (setq link (concat type path))
10551 (when (equal desc origpath)
10552 (setq desc path))))
10554 (if org-make-link-description-function
10555 (setq desc
10556 (or (condition-case nil
10557 (funcall org-make-link-description-function link desc)
10558 (error (progn (message "Can't get link description from `%s'"
10559 (symbol-name org-make-link-description-function))
10560 (sit-for 2) nil)))
10561 (read-string "Description: " default-description)))
10562 (if default-description (setq desc default-description)
10563 (setq desc (or (and auto-desc desc)
10564 (read-string "Description: " desc)))))
10566 (unless (string-match "\\S-" desc) (setq desc nil))
10567 (when remove (apply 'delete-region remove))
10568 (insert (org-make-link-string link desc))
10569 ;; Redisplay so as the new link has proper invisible characters.
10570 (sit-for 0)))
10572 (defun org-link-try-special-completion (type)
10573 "If there is completion support for link type TYPE, offer it."
10574 (let ((fun (org-link-get-parameter type :complete)))
10575 (if (functionp fun)
10576 (funcall fun)
10577 (read-string "Link (no completion support): " (concat type ":")))))
10579 (defun org-file-complete-link (&optional arg)
10580 "Create a file link using completion."
10581 (let ((file (read-file-name "File: "))
10582 (pwd (file-name-as-directory (expand-file-name ".")))
10583 (pwd1 (file-name-as-directory (abbreviate-file-name
10584 (expand-file-name ".")))))
10585 (cond ((equal arg '(16))
10586 (concat "file:"
10587 (abbreviate-file-name (expand-file-name file))))
10588 ((string-match
10589 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10590 (concat "file:" (match-string 1 file)))
10591 ((string-match
10592 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10593 (expand-file-name file))
10594 (concat "file:"
10595 (match-string 1 (expand-file-name file))))
10596 (t (concat "file:" file)))))
10598 (defun org-completing-read (&rest args)
10599 "Completing-read with SPACE being a normal character."
10600 (let ((enable-recursive-minibuffers t)
10601 (minibuffer-local-completion-map
10602 (copy-keymap minibuffer-local-completion-map)))
10603 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10604 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10605 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10606 'org-time-stamp-inactive)
10607 (apply #'completing-read args)))
10609 ;;; Opening/following a link
10611 (defvar org-link-search-failed nil)
10613 (defvar org-open-link-functions nil
10614 "Hook for functions finding a plain text link.
10615 These functions must take a single argument, the link content.
10616 They will be called for links that look like [[link text][description]]
10617 when LINK TEXT does not have a protocol like \"http:\" and does not look
10618 like a filename (e.g. \"./blue.png\").
10620 These functions will be called *before* Org attempts to resolve the
10621 link by doing text searches in the current buffer - so if you want a
10622 link \"[[target]]\" to still find \"<<target>>\", your function should
10623 handle this as a special case.
10625 When the function does handle the link, it must return a non-nil value.
10626 If it decides that it is not responsible for this link, it must return
10627 nil to indicate that that Org-mode can continue with other options
10628 like exact and fuzzy text search.")
10630 (defun org-next-link (&optional search-backward)
10631 "Move forward to the next link.
10632 If the link is in hidden text, expose it."
10633 (interactive "P")
10634 (when (and org-link-search-failed (eq this-command last-command))
10635 (goto-char (point-min))
10636 (message "Link search wrapped back to beginning of buffer"))
10637 (setq org-link-search-failed nil)
10638 (let* ((pos (point))
10639 (ct (org-context))
10640 (a (assoc :link ct))
10641 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10642 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10643 ((looking-at org-any-link-re)
10644 ;; Don't stay stuck at link without an org-link face
10645 (forward-char (if search-backward -1 1))))
10646 (if (funcall srch-fun org-any-link-re nil t)
10647 (progn
10648 (goto-char (match-beginning 0))
10649 (when (outline-invisible-p) (org-show-context)))
10650 (goto-char pos)
10651 (setq org-link-search-failed t)
10652 (message "No further link found"))))
10654 (defun org-previous-link ()
10655 "Move backward to the previous link.
10656 If the link is in hidden text, expose it."
10657 (interactive)
10658 (funcall 'org-next-link t))
10660 (defun org-translate-link (s)
10661 "Translate a link string if a translation function has been defined."
10662 (with-temp-buffer
10663 (insert (org-trim s))
10664 (org-trim (org-element-interpret-data (org-element-context)))))
10666 (defun org-translate-link-from-planner (type path)
10667 "Translate a link from Emacs Planner syntax so that Org can follow it.
10668 This is still an experimental function, your mileage may vary."
10669 (cond
10670 ((member type '("http" "https" "news" "ftp"))
10671 ;; standard Internet links are the same.
10672 nil)
10673 ((and (equal type "irc") (string-match "^//" path))
10674 ;; Planner has two / at the beginning of an irc link, we have 1.
10675 ;; We should have zero, actually....
10676 (setq path (substring path 1)))
10677 ((and (equal type "lisp") (string-match "^/" path))
10678 ;; Planner has a slash, we do not.
10679 (setq type "elisp" path (substring path 1)))
10680 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10681 ;; A typical message link. Planner has the id after the final slash,
10682 ;; we separate it with a hash mark
10683 (setq path (concat (match-string 1 path) "#"
10684 (org-remove-angle-brackets (match-string 2 path))))))
10685 (cons type path))
10687 (defun org-find-file-at-mouse (ev)
10688 "Open file link or URL at mouse."
10689 (interactive "e")
10690 (mouse-set-point ev)
10691 (org-open-at-point 'in-emacs))
10693 (defun org-open-at-mouse (ev)
10694 "Open file link or URL at mouse.
10695 See the docstring of `org-open-file' for details."
10696 (interactive "e")
10697 (mouse-set-point ev)
10698 (when (eq major-mode 'org-agenda-mode)
10699 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10700 (org-open-at-point))
10702 (defvar org-window-config-before-follow-link nil
10703 "The window configuration before following a link.
10704 This is saved in case the need arises to restore it.")
10706 ;;;###autoload
10707 (defun org-open-at-point-global ()
10708 "Follow a link or time-stamp like Org mode does.
10709 This command can be called in any mode to follow an external link
10710 or a time-stamp that has Org mode syntax. Its behavior is
10711 undefined when called on internal links (e.g., fuzzy links).
10712 Raise an error when there is nothing to follow. "
10713 (interactive)
10714 (cond ((org-in-regexp org-any-link-re)
10715 (org-open-link-from-string (match-string-no-properties 0)))
10716 ((or (org-in-regexp org-ts-regexp-both nil t)
10717 (org-in-regexp org-tsr-regexp-both nil t))
10718 (org-follow-timestamp-link))
10719 (t (user-error "No link found"))))
10721 ;;;###autoload
10722 (defun org-open-link-from-string (s &optional arg reference-buffer)
10723 "Open a link in the string S, as if it was in Org-mode."
10724 (interactive "sLink: \nP")
10725 (let ((reference-buffer (or reference-buffer (current-buffer))))
10726 (with-temp-buffer
10727 (let ((org-inhibit-startup (not reference-buffer)))
10728 (org-mode)
10729 (insert s)
10730 (goto-char (point-min))
10731 (when reference-buffer
10732 (setq org-link-abbrev-alist-local
10733 (with-current-buffer reference-buffer
10734 org-link-abbrev-alist-local)))
10735 (org-open-at-point arg reference-buffer)))))
10737 (defvar org-open-at-point-functions nil
10738 "Hook that is run when following a link at point.
10740 Functions in this hook must return t if they identify and follow
10741 a link at point. If they don't find anything interesting at point,
10742 they must return nil.")
10744 (defvar org-link-search-inhibit-query nil)
10745 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10746 (defun org--open-doi-link (path)
10747 "Open a \"doi\" type link.
10748 PATH is a the path to search for, as a string."
10749 (browse-url (url-encode-url (concat org-doi-server-url path))))
10751 (defun org--open-elisp-link (path)
10752 "Open a \"elisp\" type link.
10753 PATH is the sexp to evaluate, as a string."
10754 (let ((cmd path))
10755 (if (or (and (org-string-nw-p
10756 org-confirm-elisp-link-not-regexp)
10757 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10758 (not org-confirm-elisp-link-function)
10759 (funcall org-confirm-elisp-link-function
10760 (format "Execute \"%s\" as elisp? "
10761 (org-add-props cmd nil 'face 'org-warning))))
10762 (message "%s => %s" cmd
10763 (if (eq (string-to-char cmd) ?\()
10764 (eval (read cmd))
10765 (call-interactively (read cmd))))
10766 (user-error "Abort"))))
10768 (defun org--open-help-link (path)
10769 "Open a \"help\" type link.
10770 PATH is a symbol name, as a string."
10771 (pcase (intern path)
10772 ((and (pred fboundp) variable) (describe-function variable))
10773 ((and (pred boundp) function) (describe-variable function))
10774 (name (user-error "Unknown function or variable: %s" name))))
10776 (defun org--open-shell-link (path)
10777 "Open a \"shell\" type link.
10778 PATH is the command to execute, as a string."
10779 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10780 (cmd path))
10781 (if (or (and (org-string-nw-p
10782 org-confirm-shell-link-not-regexp)
10783 (string-match
10784 org-confirm-shell-link-not-regexp cmd))
10785 (not org-confirm-shell-link-function)
10786 (funcall org-confirm-shell-link-function
10787 (format "Execute \"%s\" in shell? "
10788 (org-add-props cmd nil
10789 'face 'org-warning))))
10790 (progn
10791 (message "Executing %s" cmd)
10792 (shell-command cmd buf)
10793 (when (featurep 'midnight)
10794 (setq clean-buffer-list-kill-buffer-names
10795 (cons (buffer-name buf)
10796 clean-buffer-list-kill-buffer-names))))
10797 (user-error "Abort"))))
10799 (defun org-open-at-point (&optional arg reference-buffer)
10800 "Open link, timestamp, footnote or tags at point.
10802 When point is on a link, follow it. Normally, files will be
10803 opened by an appropriate application. If the optional prefix
10804 argument ARG is non-nil, Emacs will visit the file. With
10805 a double prefix argument, try to open outside of Emacs, in the
10806 application the system uses for this file type.
10808 When point is on a timestamp, open the agenda at the day
10809 specified.
10811 When point is a footnote definition, move to the first reference
10812 found. If it is on a reference, move to the associated
10813 definition.
10815 When point is on a headline, display a list of every link in the
10816 entry, so it is possible to pick one, or all, of them. If point
10817 is on a tag, call `org-tags-view' instead.
10819 When optional argument REFERENCE-BUFFER is non-nil, it should
10820 specify a buffer from where the link search should happen. This
10821 is used internally by `org-open-link-from-string'.
10823 On top of syntactically correct links, this function will open
10824 the link at point in comments or comment blocks and the first
10825 link in a property drawer line."
10826 (interactive "P")
10827 ;; On a code block, open block's results.
10828 (unless (call-interactively 'org-babel-open-src-block-result)
10829 (org-load-modules-maybe)
10830 (setq org-window-config-before-follow-link (current-window-configuration))
10831 (org-remove-occur-highlights nil nil t)
10832 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10833 (let* ((context
10834 ;; Only consider supported types, even if they are not
10835 ;; the closest one.
10836 (org-element-lineage
10837 (org-element-context)
10838 '(clock comment comment-block footnote-definition
10839 footnote-reference headline inlinetask keyword link
10840 node-property timestamp)
10842 (type (org-element-type context))
10843 (value (org-element-property :value context)))
10844 (cond
10845 ((not context) (user-error "No link found"))
10846 ;; Exception: open timestamps and links in properties
10847 ;; drawers, keywords and comments.
10848 ((memq type '(comment comment-block keyword node-property))
10849 (call-interactively #'org-open-at-point-global))
10850 ;; On a headline or an inlinetask, but not on a timestamp,
10851 ;; a link, a footnote reference or on tags.
10852 ((and (memq type '(headline inlinetask))
10853 ;; Not on tags.
10854 (progn (save-excursion (beginning-of-line)
10855 (looking-at org-complex-heading-regexp))
10856 (or (not (match-beginning 5))
10857 (< (point) (match-beginning 5)))))
10858 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10859 (links (car data))
10860 (links-end (cdr data)))
10861 (if links
10862 (dolist (link (if (stringp links) (list links) links))
10863 (search-forward link nil links-end)
10864 (goto-char (match-beginning 0))
10865 (org-open-at-point))
10866 (require 'org-attach)
10867 (org-attach-reveal 'if-exists))))
10868 ;; On a clock line, make sure point is on the timestamp
10869 ;; before opening it.
10870 ((and (eq type 'clock)
10871 value
10872 (>= (point) (org-element-property :begin value))
10873 (<= (point) (org-element-property :end value)))
10874 (org-follow-timestamp-link))
10875 ;; Do nothing on white spaces after an object.
10876 ((>= (point)
10877 (save-excursion
10878 (goto-char (org-element-property :end context))
10879 (skip-chars-backward " \t")
10880 (point)))
10881 (user-error "No link found"))
10882 ((eq type 'timestamp) (org-follow-timestamp-link))
10883 ;; On tags within a headline or an inlinetask.
10884 ((and (memq type '(headline inlinetask))
10885 (progn (save-excursion (beginning-of-line)
10886 (looking-at org-complex-heading-regexp))
10887 (and (match-beginning 5)
10888 (>= (point) (match-beginning 5)))))
10889 (org-tags-view arg (substring (match-string 5) 0 -1)))
10890 ((eq type 'link)
10891 ;; When link is located within the description of another
10892 ;; link (e.g., an inline image), always open the parent
10893 ;; link.
10894 (let* ((link (let ((up (org-element-property :parent context)))
10895 (if (eq (org-element-type up) 'link) up context)))
10896 (type (org-element-property :type link))
10897 (path (org-link-unescape (org-element-property :path link))))
10898 ;; Switch back to REFERENCE-BUFFER needed when called in
10899 ;; a temporary buffer through `org-open-link-from-string'.
10900 (with-current-buffer (or reference-buffer (current-buffer))
10901 (cond
10902 ((equal type "file")
10903 (if (string-match "[*?{]" (file-name-nondirectory path))
10904 (dired path)
10905 ;; Look into `org-link-parameters' in order to find
10906 ;; a DEDICATED-FUNCTION to open file. The function
10907 ;; will be applied on raw link instead of parsed
10908 ;; link due to the limitation in `org-add-link-type'
10909 ;; ("open" function called with a single argument).
10910 ;; If no such function is found, fallback to
10911 ;; `org-open-file'.
10912 (let* ((option (org-element-property :search-option link))
10913 (app (org-element-property :application link))
10914 (dedicated-function
10915 (org-link-get-parameter
10916 (if app (concat type "+" app) type)
10917 :follow)))
10918 (if dedicated-function
10919 (funcall dedicated-function
10920 (concat path
10921 (and option (concat "::" option))))
10922 (apply #'org-open-file
10923 path
10924 (cond (arg)
10925 ((equal app "emacs") 'emacs)
10926 ((equal app "sys") 'system))
10927 (cond ((not option) nil)
10928 ((string-match-p "\\`[0-9]+\\'" option)
10929 (list (string-to-number option)))
10930 (t (list nil
10931 (org-link-unescape option)))))))))
10932 ((functionp (org-link-get-parameter type :follow))
10933 (funcall (org-link-get-parameter type :follow) path))
10934 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10935 (unless (run-hook-with-args-until-success
10936 'org-open-link-functions path)
10937 (if (not arg) (org-mark-ring-push)
10938 (switch-to-buffer-other-window
10939 (org-get-buffer-for-internal-link (current-buffer))))
10940 (let ((destination
10941 (org-with-wide-buffer
10942 (if (equal type "radio")
10943 (org-search-radio-target
10944 (org-element-property :path link))
10945 (org-link-search
10946 (if (member type '("custom-id" "coderef"))
10947 (org-element-property :raw-link link)
10948 path)
10949 ;; Prevent fuzzy links from matching
10950 ;; themselves.
10951 (and (equal type "fuzzy")
10952 (+ 2 (org-element-property :begin link)))))
10953 (point))))
10954 (unless (and (<= (point-min) destination)
10955 (>= (point-max) destination))
10956 (widen))
10957 (goto-char destination))))
10958 (t (browse-url-at-point))))))
10959 ;; On a footnote reference or at a footnote definition's label.
10960 ((or (eq type 'footnote-reference)
10961 (and (eq type 'footnote-definition)
10962 (save-excursion
10963 ;; Do not validate action when point is on the
10964 ;; spaces right after the footnote label, in
10965 ;; order to be on par with behaviour on links.
10966 (skip-chars-forward " \t")
10967 (let ((begin
10968 (org-element-property :contents-begin context)))
10969 (if begin (< (point) begin)
10970 (= (org-element-property :post-affiliated context)
10971 (line-beginning-position)))))))
10972 (org-footnote-action))
10973 (t (user-error "No link found")))))
10974 (run-hook-with-args 'org-follow-link-hook)))
10976 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10977 "Offer links in the current entry and return the selected link.
10978 If there is only one link, return it.
10979 If NTH is an integer, return the NTH link found.
10980 If ZERO is a string, check also this string for a link, and if
10981 there is one, return it."
10982 (with-current-buffer buffer
10983 (save-excursion
10984 (save-restriction
10985 (widen)
10986 (goto-char marker)
10987 (let ((cnt ?0)
10988 have-zero end links link c)
10989 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10990 (push (match-string 0 zero) links)
10991 (setq cnt (1- cnt) have-zero t))
10992 (save-excursion
10993 (org-back-to-heading t)
10994 (setq end (save-excursion (outline-next-heading) (point)))
10995 (while (re-search-forward org-any-link-re end t)
10996 (push (match-string 0) links))
10997 (setq links (org-uniquify (reverse links))))
10998 (cond
10999 ((null links)
11000 (message "No links"))
11001 ((equal (length links) 1)
11002 (setq link (car links)))
11003 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11004 (setq link (nth (if have-zero nth (1- nth)) links)))
11005 (t ; we have to select a link
11006 (save-excursion
11007 (save-window-excursion
11008 (delete-other-windows)
11009 (with-output-to-temp-buffer "*Select Link*"
11010 (dolist (l links)
11011 (cond
11012 ((not (string-match org-bracket-link-regexp l))
11013 (princ (format "[%c] %s\n" (cl-incf cnt)
11014 (org-remove-angle-brackets l))))
11015 ((match-end 3)
11016 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11017 (match-string 3 l) (match-string 1 l))))
11018 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11019 (match-string 1 l)))))))
11020 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11021 (message "Select link to open, RET to open all:")
11022 (setq c (read-char-exclusive))
11023 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11024 (when (equal c ?q) (user-error "Abort"))
11025 (if (equal c ?\C-m)
11026 (setq link links)
11027 (setq nth (- c ?0))
11028 (when have-zero (setq nth (1+ nth)))
11029 (unless (and (integerp nth) (>= (length links) nth))
11030 (user-error "Invalid link selection"))
11031 (setq link (nth (1- nth) links)))))
11032 (cons link end))))))
11034 ;; TODO: These functions are deprecated since `org-open-at-point'
11035 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11036 (defun org-open-file-with-system (path)
11037 "Open file at PATH using the system way of opening it."
11038 (org-open-file path 'system))
11039 (defun org-open-file-with-emacs (path)
11040 "Open file at PATH in Emacs."
11041 (org-open-file path 'emacs))
11044 ;;; File search
11046 (defvar org-create-file-search-functions nil
11047 "List of functions to construct the right search string for a file link.
11048 These functions are called in turn with point at the location to
11049 which the link should point.
11051 A function in the hook should first test if it would like to
11052 handle this file type, for example by checking the `major-mode'
11053 or the file extension. If it decides not to handle this file, it
11054 should just return nil to give other functions a chance. If it
11055 does handle the file, it must return the search string to be used
11056 when following the link. The search string will be part of the
11057 file link, given after a double colon, and `org-open-at-point'
11058 will automatically search for it. If special measures must be
11059 taken to make the search successful, another function should be
11060 added to the companion hook `org-execute-file-search-functions',
11061 which see.
11063 A function in this hook may also use `setq' to set the variable
11064 `description' to provide a suggestion for the descriptive text to
11065 be used for this link when it gets inserted into an Org-mode
11066 buffer with \\[org-insert-link].")
11068 (defvar org-execute-file-search-functions nil
11069 "List of functions to execute a file search triggered by a link.
11071 Functions added to this hook must accept a single argument, the
11072 search string that was part of the file link, the part after the
11073 double colon. The function must first check if it would like to
11074 handle this search, for example by checking the `major-mode' or
11075 the file extension. If it decides not to handle this search, it
11076 should just return nil to give other functions a chance. If it
11077 does handle the search, it must return a non-nil value to keep
11078 other functions from trying.
11080 Each function can access the current prefix argument through the
11081 variable `current-prefix-arg'. Note that a single prefix is used
11082 to force opening a link in Emacs, so it may be good to only use a
11083 numeric or double prefix to guide the search function.
11085 In case this is needed, a function in this hook can also restore
11086 the window configuration before `org-open-at-point' was called using:
11088 \(set-window-configuration org-window-config-before-follow-link)")
11090 (defun org-search-radio-target (target)
11091 "Search a radio target matching TARGET in current buffer.
11092 White spaces are not significant."
11093 (let ((re (format "<<<%s>>>"
11094 (mapconcat #'regexp-quote
11095 (org-split-string target "[ \t\n]+")
11096 "[ \t]+\\(?:\n[ \t]*\\)?")))
11097 (origin (point)))
11098 (goto-char (point-min))
11099 (catch :radio-match
11100 (while (re-search-forward re nil t)
11101 (backward-char)
11102 (let ((object (org-element-context)))
11103 (when (eq (org-element-type object) 'radio-target)
11104 (goto-char (org-element-property :begin object))
11105 (org-show-context 'link-search)
11106 (throw :radio-match nil))))
11107 (goto-char origin)
11108 (user-error "No match for radio target: %s" target))))
11110 (defun org-link-search (s &optional avoid-pos stealth)
11111 "Search for a search string S.
11113 If S starts with \"#\", it triggers a custom ID search.
11115 If S is enclosed within parenthesis, it initiates a coderef
11116 search.
11118 If S is surrounded by forward slashes, it is interpreted as
11119 a regular expression. In Org mode files, this will create an
11120 `org-occur' sparse tree. In ordinary files, `occur' will be used
11121 to list matches. If the current buffer is in `dired-mode', grep
11122 will be used to search in all files.
11124 When AVOID-POS is given, ignore matches near that position.
11126 When optional argument STEALTH is non-nil, do not modify
11127 visibility around point, thus ignoring `org-show-context-detail'
11128 variable.
11130 Search is case-insensitive and ignores white spaces. Return type
11131 of matched result, with is either `dedicated' or `fuzzy'."
11132 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11133 (let* ((case-fold-search t)
11134 (origin (point))
11135 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11136 (words (org-split-string s "[ \t\n]+"))
11137 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11138 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11139 type)
11140 (cond
11141 ;; Check if there are any special search functions.
11142 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11143 ((eq (string-to-char s) ?#)
11144 ;; Look for a custom ID S if S starts with "#".
11145 (let* ((id (substring normalized 1))
11146 (match (org-find-property "CUSTOM_ID" id)))
11147 (if match (progn (goto-char match) (setf type 'dedicated))
11148 (error "No match for custom ID: %s" id))))
11149 ((string-match "\\`(\\(.*\\))\\'" normalized)
11150 ;; Look for coderef targets if S is enclosed within parenthesis.
11151 (let ((coderef (match-string-no-properties 1 normalized))
11152 (re (substring s-single-re 1 -1)))
11153 (goto-char (point-min))
11154 (catch :coderef-match
11155 (while (re-search-forward re nil t)
11156 (let ((element (org-element-at-point)))
11157 (when (and (memq (org-element-type element)
11158 '(example-block src-block))
11159 ;; Build proper regexp according to current
11160 ;; block's label format.
11161 (let ((label-fmt
11162 (regexp-quote
11163 (or (org-element-property :label-fmt element)
11164 org-coderef-label-format))))
11165 (save-excursion
11166 (beginning-of-line)
11167 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11168 (format label-fmt coderef))))))
11169 (setq type 'dedicated)
11170 (goto-char (match-beginning 1))
11171 (throw :coderef-match nil))))
11172 (goto-char origin)
11173 (error "No match for coderef: %s" coderef))))
11174 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11175 ;; Look for a regular expression.
11176 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11177 (match-string 1 s)))
11178 ;; Fuzzy links.
11180 (let ((starred (eq (string-to-char normalized) ?*)))
11181 (cond
11182 ;; Look for targets, only if not in a headline search.
11183 ((and (not starred)
11184 (let ((target (format "<<%s>>" s-multi-re)))
11185 (catch :target-match
11186 (goto-char (point-min))
11187 (while (re-search-forward target nil t)
11188 (backward-char)
11189 (let ((context (org-element-context)))
11190 (when (eq (org-element-type context) 'target)
11191 (setq type 'dedicated)
11192 (goto-char (org-element-property :begin context))
11193 (throw :target-match t))))
11194 nil))))
11195 ;; Look for elements named after S, only if not in a headline
11196 ;; search.
11197 ((and (not starred)
11198 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11199 (catch :name-match
11200 (goto-char (point-min))
11201 (while (re-search-forward name nil t)
11202 (let ((element (org-element-at-point)))
11203 (when (equal (org-split-string
11204 (org-element-property :name element)
11205 "[ \t]+")
11206 words)
11207 (setq type 'dedicated)
11208 (beginning-of-line)
11209 (throw :name-match t))))
11210 nil))))
11211 ;; Regular text search. Prefer headlines in Org mode
11212 ;; buffers.
11213 ((and (derived-mode-p 'org-mode)
11214 (let* ((wspace "[ \t]")
11215 (wspaceopt (concat wspace "*"))
11216 (cookie (concat "\\(?:"
11217 wspaceopt
11218 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11219 wspaceopt
11220 "\\)"))
11221 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11222 (re (concat
11223 org-outline-regexp-bol
11224 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11225 "\\(?:\\[#.\\][ \t]+\\)?"
11226 "\\(?:" org-comment-string "[ \t]+\\)?"
11227 sep "?"
11228 (let ((title (mapconcat #'regexp-quote
11229 words
11230 sep)))
11231 (if starred (substring title 1) title))
11232 sep "?"
11233 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11234 "[ \t]*$")))
11235 (goto-char (point-min))
11236 (re-search-forward re nil t)))
11237 (goto-char (match-beginning 0))
11238 (setq type 'dedicated))
11239 ;; Offer to create non-existent headline depending on
11240 ;; `org-link-search-must-match-exact-headline'.
11241 ((and (derived-mode-p 'org-mode)
11242 (not org-link-search-inhibit-query)
11243 (eq org-link-search-must-match-exact-headline 'query-to-create)
11244 (yes-or-no-p "No match - create this as a new heading? "))
11245 (goto-char (point-max))
11246 (unless (bolp) (newline))
11247 (org-insert-heading nil t t)
11248 (insert s "\n")
11249 (beginning-of-line 0))
11250 ;; Only headlines are looked after. No need to process
11251 ;; further: throw an error.
11252 ((and (derived-mode-p 'org-mode)
11253 (or starred org-link-search-must-match-exact-headline))
11254 (goto-char origin)
11255 (error "No match for fuzzy expression: %s" normalized))
11256 ;; Regular text search.
11257 ((catch :fuzzy-match
11258 (goto-char (point-min))
11259 (while (re-search-forward s-multi-re nil t)
11260 ;; Skip match if it contains AVOID-POS or it is included
11261 ;; in a link with a description but outside the
11262 ;; description.
11263 (unless (or (and avoid-pos
11264 (<= (match-beginning 0) avoid-pos)
11265 (> (match-end 0) avoid-pos))
11266 (and (save-match-data
11267 (org-in-regexp org-bracket-link-regexp))
11268 (match-beginning 3)
11269 (or (> (match-beginning 3) (point))
11270 (<= (match-end 3) (point)))
11271 (org-element-lineage
11272 (save-match-data (org-element-context))
11273 '(link) t)))
11274 (goto-char (match-beginning 0))
11275 (setq type 'fuzzy)
11276 (throw :fuzzy-match t)))
11277 nil))
11278 ;; All failed. Throw an error.
11279 (t (goto-char origin)
11280 (error "No match for fuzzy expression: %s" normalized))))))
11281 ;; Disclose surroundings of match, if appropriate.
11282 (when (and (derived-mode-p 'org-mode) (not stealth))
11283 (org-show-context 'link-search))
11284 type))
11286 (defun org-get-buffer-for-internal-link (buffer)
11287 "Return a buffer to be used for displaying the link target of internal links."
11288 (cond
11289 ((not org-display-internal-link-with-indirect-buffer)
11290 buffer)
11291 ((string-match "(Clone)$" (buffer-name buffer))
11292 (message "Buffer is already a clone, not making another one")
11293 ;; we also do not modify visibility in this case
11294 buffer)
11295 (t ; make a new indirect buffer for displaying the link
11296 (let* ((bn (buffer-name buffer))
11297 (ibn (concat bn "(Clone)"))
11298 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11299 (with-current-buffer ib (org-overview))
11300 ib))))
11302 (defun org-do-occur (regexp &optional cleanup)
11303 "Call the Emacs command `occur'.
11304 If CLEANUP is non-nil, remove the printout of the regular expression
11305 in the *Occur* buffer. This is useful if the regex is long and not useful
11306 to read."
11307 (occur regexp)
11308 (when cleanup
11309 (let ((cwin (selected-window)) win beg end)
11310 (when (setq win (get-buffer-window "*Occur*"))
11311 (select-window win))
11312 (goto-char (point-min))
11313 (when (re-search-forward "match[a-z]+" nil t)
11314 (setq beg (match-end 0))
11315 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11316 (setq end (1- (match-beginning 0)))))
11317 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11318 (goto-char (point-min))
11319 (select-window cwin))))
11321 ;;; The mark ring for links jumps
11323 (defvar org-mark-ring nil
11324 "Mark ring for positions before jumps in Org-mode.")
11325 (defvar org-mark-ring-last-goto nil
11326 "Last position in the mark ring used to go back.")
11327 ;; Fill and close the ring
11328 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11329 (dotimes (_ org-mark-ring-length)
11330 (push (make-marker) org-mark-ring))
11331 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11332 org-mark-ring)
11334 (defun org-mark-ring-push (&optional pos buffer)
11335 "Put the current position or POS into the mark ring and rotate it."
11336 (interactive)
11337 (setq pos (or pos (point)))
11338 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11339 (move-marker (car org-mark-ring)
11340 (or pos (point))
11341 (or buffer (current-buffer)))
11342 (message "%s"
11343 (substitute-command-keys
11344 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11346 (defun org-mark-ring-goto (&optional n)
11347 "Jump to the previous position in the mark ring.
11348 With prefix arg N, jump back that many stored positions. When
11349 called several times in succession, walk through the entire ring.
11350 Org-mode commands jumping to a different position in the current file,
11351 or to another Org-mode file, automatically push the old position
11352 onto the ring."
11353 (interactive "p")
11354 (let (p m)
11355 (if (eq last-command this-command)
11356 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11357 (setq p org-mark-ring))
11358 (setq org-mark-ring-last-goto p)
11359 (setq m (car p))
11360 (pop-to-buffer-same-window (marker-buffer m))
11361 (goto-char m)
11362 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11364 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11365 ;;; Emacs 24.4+
11366 (defun org-remove-angle-brackets (s)
11367 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11368 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11370 (defun org-add-angle-brackets (s)
11371 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11372 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11374 (defun org-remove-double-quotes (s)
11375 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11376 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11379 ;;; Following specific links
11381 (defvar org-agenda-buffer-tmp-name)
11382 (defvar org-agenda-start-on-weekday)
11383 (defun org-follow-timestamp-link ()
11384 "Open an agenda view for the time-stamp date/range at point."
11385 (cond
11386 ((org-at-date-range-p t)
11387 (let ((org-agenda-start-on-weekday)
11388 (t1 (match-string 1))
11389 (t2 (match-string 2)) tt1 tt2)
11390 (setq tt1 (time-to-days (org-time-string-to-time t1))
11391 tt2 (time-to-days (org-time-string-to-time t2)))
11392 (let ((org-agenda-buffer-tmp-name
11393 (format "*Org Agenda(a:%s)"
11394 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11395 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11396 ((org-at-timestamp-p t)
11397 (let ((org-agenda-buffer-tmp-name
11398 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11399 (org-agenda-list nil (time-to-days (org-time-string-to-time
11400 (substring (match-string 1) 0 10)))
11401 1)))
11402 (t (error "This should not happen"))))
11405 ;;; Following file links
11406 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11407 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11408 (declare-function mailcap-mime-info
11409 "mailcap" (string &optional request no-decode))
11410 (defvar org-wait nil)
11411 (defun org-open-file (path &optional in-emacs line search)
11412 "Open the file at PATH.
11413 First, this expands any special file name abbreviations. Then the
11414 configuration variable `org-file-apps' is checked if it contains an
11415 entry for this file type, and if yes, the corresponding command is launched.
11417 If no application is found, Emacs simply visits the file.
11419 With optional prefix argument IN-EMACS, Emacs will visit the file.
11420 With a double \\[universal-argument] \\[universal-argument] \
11421 prefix arg, Org tries to avoid opening in Emacs
11422 and to use an external application to visit the file.
11424 Optional LINE specifies a line to go to, optional SEARCH a string
11425 to search for. If LINE or SEARCH is given, the file will be
11426 opened in Emacs, unless an entry from org-file-apps that makes
11427 use of groups in a regexp matches.
11429 If you want to change the way frames are used when following a
11430 link, please customize `org-link-frame-setup'.
11432 If the file does not exist, an error is thrown."
11433 (let* ((file (if (equal path "")
11434 buffer-file-name
11435 (substitute-in-file-name (expand-file-name path))))
11436 (file-apps (append org-file-apps (org-default-apps)))
11437 (apps (cl-remove-if
11438 'org-file-apps-entry-match-against-dlink-p file-apps))
11439 (apps-dlink (cl-remove-if-not
11440 'org-file-apps-entry-match-against-dlink-p file-apps))
11441 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11442 (dirp (unless remp (file-directory-p file)))
11443 (file (if (and dirp org-open-directory-means-index-dot-org)
11444 (concat (file-name-as-directory file) "index.org")
11445 file))
11446 (a-m-a-p (assq 'auto-mode apps))
11447 (dfile (downcase file))
11448 ;; Reconstruct the original link from the PATH, LINE and
11449 ;; SEARCH args.
11450 (link (cond (line (concat file "::" (number-to-string line)))
11451 (search (concat file "::" search))
11452 (t file)))
11453 (dlink (downcase link))
11454 (old-buffer (current-buffer))
11455 (old-pos (point))
11456 (old-mode major-mode)
11457 (ext
11458 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11459 (match-string 1 dfile)))
11460 cmd link-match-data)
11461 (cond
11462 ((member in-emacs '((16) system))
11463 (setq cmd (cdr (assq 'system apps))))
11464 (in-emacs (setq cmd 'emacs))
11466 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11467 (and dirp (cdr (assq 'directory apps)))
11468 ;; First, try matching against apps-dlink if we
11469 ;; get a match here, store the match data for
11470 ;; later.
11471 (let ((match (assoc-default dlink apps-dlink
11472 'string-match)))
11473 (if match
11474 (progn (setq link-match-data (match-data))
11475 match)
11476 (progn (setq in-emacs (or in-emacs line search))
11477 nil))) ; if we have no match in apps-dlink,
11478 ; always open the file in emacs if line or search
11479 ; is given (for backwards compatibility)
11480 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11481 'string-match)
11482 (cdr (assoc ext apps))
11483 (cdr (assq t apps))))))
11484 (when (eq cmd 'system)
11485 (setq cmd (cdr (assoc 'system apps))))
11486 (when (eq cmd 'default)
11487 (setq cmd (cdr (assoc t apps))))
11488 (when (eq cmd 'mailcap)
11489 (require 'mailcap)
11490 (mailcap-parse-mailcaps)
11491 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11492 (command (mailcap-mime-info mime-type)))
11493 (if (stringp command)
11494 (setq cmd command)
11495 (setq cmd 'emacs))))
11496 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11497 (not (file-exists-p file))
11498 (not org-open-non-existing-files))
11499 (user-error "No such file: %s" file))
11500 (cond
11501 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11502 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11503 (while (string-match "['\"]%s['\"]" cmd)
11504 (setq cmd (replace-match "%s" t t cmd)))
11505 (while (string-match "%s" cmd)
11506 (setq cmd (replace-match
11507 (save-match-data
11508 (shell-quote-argument
11509 (convert-standard-filename file)))
11510 t t cmd)))
11512 ;; Replace "%1", "%2" etc. in command with group matches from regex
11513 (save-match-data
11514 (let ((match-index 1)
11515 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11516 (set-match-data link-match-data)
11517 (while (<= match-index number-of-groups)
11518 (let ((regex (concat "%" (number-to-string match-index)))
11519 (replace-with (match-string match-index dlink)))
11520 (while (string-match regex cmd)
11521 (setq cmd (replace-match replace-with t t cmd))))
11522 (setq match-index (+ match-index 1)))))
11524 (save-window-excursion
11525 (message "Running %s...done" cmd)
11526 (start-process-shell-command cmd nil cmd)
11527 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11528 ((or (stringp cmd)
11529 (eq cmd 'emacs))
11530 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11531 (widen)
11532 (cond (line (org-goto-line line)
11533 (when (derived-mode-p 'org-mode) (org-reveal)))
11534 (search (org-link-search search))))
11535 ((functionp cmd)
11536 (save-match-data
11537 (set-match-data link-match-data)
11538 (condition-case nil
11539 (funcall cmd file link)
11540 ;; FIXME: Remove this check when most default installations
11541 ;; of Emacs have at least Org 9.0.
11542 ((debug wrong-number-of-arguments wrong-type-argument
11543 invalid-function)
11544 (user-error "Please see Org News for version 9.0 about \
11545 `org-file-apps'--Lisp error: %S" cmd)))))
11546 ((consp cmd)
11547 ;; FIXME: Remove this check when most default installations of
11548 ;; Emacs have at least Org 9.0.
11549 ;; Heads-up instead of silently fall back to
11550 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11551 ;; with sexp instead of a function for `cmd'.
11552 (user-error "Please see Org News for version 9.0 about \
11553 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11554 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11555 (and (derived-mode-p 'org-mode)
11556 (eq old-mode 'org-mode)
11557 (or (not (eq old-buffer (current-buffer)))
11558 (not (eq old-pos (point))))
11559 (org-mark-ring-push old-pos old-buffer))))
11561 (defun org-file-apps-entry-match-against-dlink-p (entry)
11562 "This function returns non-nil if `entry' uses a regular
11563 expression which should be matched against the whole link by
11564 org-open-file.
11566 It assumes that is the case when the entry uses a regular
11567 expression which has at least one grouping construct and the
11568 action is either a lisp form or a command string containing
11569 `%1', i.e. using at least one subexpression match as a
11570 parameter."
11571 (let ((selector (car entry))
11572 (action (cdr entry)))
11573 (if (stringp selector)
11574 (and (> (regexp-opt-depth selector) 0)
11575 (or (and (stringp action)
11576 (string-match "%[0-9]" action))
11577 (consp action)))
11578 nil)))
11580 (defun org-default-apps ()
11581 "Return the default applications for this operating system."
11582 (cond
11583 ((eq system-type 'darwin)
11584 org-file-apps-defaults-macosx)
11585 ((eq system-type 'windows-nt)
11586 org-file-apps-defaults-windowsnt)
11587 (t org-file-apps-defaults-gnu)))
11589 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11590 "Convert extensions to regular expressions in the cars of LIST.
11591 Also, weed out any non-string entries, because the return value is used
11592 only for regexp matching.
11593 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11594 point to the symbol `emacs', indicating that the file should
11595 be opened in Emacs."
11596 (append
11597 (delq nil
11598 (mapcar (lambda (x)
11599 (unless (not (stringp (car x)))
11600 (if (string-match "\\W" (car x))
11602 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11603 list))
11604 (when add-auto-mode
11605 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11607 (defvar ange-ftp-name-format)
11608 (defun org-file-remote-p (file)
11609 "Test whether FILE specifies a location on a remote system.
11610 Return non-nil if the location is indeed remote.
11612 For example, the filename \"/user@host:/foo\" specifies a location
11613 on the system \"/user@host:\"."
11614 (cond ((fboundp 'file-remote-p)
11615 (file-remote-p file))
11616 ((fboundp 'tramp-handle-file-remote-p)
11617 (tramp-handle-file-remote-p file))
11618 ((and (boundp 'ange-ftp-name-format)
11619 (string-match (car ange-ftp-name-format) file))
11620 t)))
11623 ;;;; Refiling
11625 (defun org-get-org-file ()
11626 "Read a filename, with default directory `org-directory'."
11627 (let ((default (or org-default-notes-file remember-data-file)))
11628 (read-file-name (format "File name [%s]: " default)
11629 (file-name-as-directory org-directory)
11630 default)))
11632 (defun org-notes-order-reversed-p ()
11633 "Check if the current file should receive notes in reversed order."
11634 (cond
11635 ((not org-reverse-note-order) nil)
11636 ((eq t org-reverse-note-order) t)
11637 ((not (listp org-reverse-note-order)) nil)
11638 (t (catch 'exit
11639 (dolist (entry org-reverse-note-order)
11640 (when (string-match (car entry) buffer-file-name)
11641 (throw 'exit (cdr entry))))))))
11643 (defvar org-refile-target-table nil
11644 "The list of refile targets, created by `org-refile'.")
11646 (defvar org-agenda-new-buffers nil
11647 "Buffers created to visit agenda files.")
11649 (defvar org-refile-cache nil
11650 "Cache for refile targets.")
11652 (defvar org-refile-markers nil
11653 "All the markers used for caching refile locations.")
11655 (defun org-refile-marker (pos)
11656 "Get a new refile marker, but only if caching is in use."
11657 (if (not org-refile-use-cache)
11659 (let ((m (make-marker)))
11660 (move-marker m pos)
11661 (push m org-refile-markers)
11662 m)))
11664 (defun org-refile-cache-clear ()
11665 "Clear the refile cache and disable all the markers."
11666 (dolist (m org-refile-markers) (move-marker m nil))
11667 (setq org-refile-markers nil)
11668 (setq org-refile-cache nil)
11669 (message "Refile cache has been cleared"))
11671 (defun org-refile-cache-check-set (set)
11672 "Check if all the markers in the cache still have live buffers."
11673 (let (marker)
11674 (catch 'exit
11675 (while (and set (setq marker (nth 3 (pop set))))
11676 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11677 (when (and marker (null (marker-buffer marker)))
11678 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11679 (sit-for 3)
11680 (throw 'exit nil)))
11681 t)))
11683 (defun org-refile-cache-put (set &rest identifiers)
11684 "Push the refile targets SET into the cache, under IDENTIFIERS."
11685 (let* ((key (sha1 (prin1-to-string identifiers)))
11686 (entry (assoc key org-refile-cache)))
11687 (if entry
11688 (setcdr entry set)
11689 (push (cons key set) org-refile-cache))))
11691 (defun org-refile-cache-get (&rest identifiers)
11692 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11693 (cond
11694 ((not org-refile-cache) nil)
11695 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11697 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11698 org-refile-cache))))
11699 (and set (org-refile-cache-check-set set) set)))))
11701 (defvar org-outline-path-cache nil
11702 "Alist between buffer positions and outline paths.
11703 It value is an alist (POSITION . PATH) where POSITION is the
11704 buffer position at the beginning of an entry and PATH is a list
11705 of strings describing the outline path for that entry, in reverse
11706 order.")
11708 (defun org-refile-get-targets (&optional default-buffer)
11709 "Produce a table with refile targets."
11710 (let ((case-fold-search nil)
11711 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11712 (entries (or org-refile-targets '((nil . (:level . 1)))))
11713 targets tgs files desc descre)
11714 (message "Getting targets...")
11715 (with-current-buffer (or default-buffer (current-buffer))
11716 (dolist (entry entries)
11717 (setq files (car entry) desc (cdr entry))
11718 (cond
11719 ((null files) (setq files (list (current-buffer))))
11720 ((eq files 'org-agenda-files)
11721 (setq files (org-agenda-files 'unrestricted)))
11722 ((and (symbolp files) (fboundp files))
11723 (setq files (funcall files)))
11724 ((and (symbolp files) (boundp files))
11725 (setq files (symbol-value files))))
11726 (when (stringp files) (setq files (list files)))
11727 (cond
11728 ((eq (car desc) :tag)
11729 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11730 ((eq (car desc) :todo)
11731 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11732 ((eq (car desc) :regexp)
11733 (setq descre (cdr desc)))
11734 ((eq (car desc) :level)
11735 (setq descre (concat "^\\*\\{" (number-to-string
11736 (if org-odd-levels-only
11737 (1- (* 2 (cdr desc)))
11738 (cdr desc)))
11739 "\\}[ \t]")))
11740 ((eq (car desc) :maxlevel)
11741 (setq descre (concat "^\\*\\{1," (number-to-string
11742 (if org-odd-levels-only
11743 (1- (* 2 (cdr desc)))
11744 (cdr desc)))
11745 "\\}[ \t]")))
11746 (t (error "Bad refiling target description %s" desc)))
11747 (dolist (f files)
11748 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11750 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11751 (progn
11752 (when (bufferp f)
11753 (setq f (buffer-file-name (buffer-base-buffer f))))
11754 (setq f (and f (expand-file-name f)))
11755 (when (eq org-refile-use-outline-path 'file)
11756 (push (list (file-name-nondirectory f) f nil nil) tgs))
11757 (org-with-wide-buffer
11758 (goto-char (point-min))
11759 (setq org-outline-path-cache nil)
11760 (while (re-search-forward descre nil t)
11761 (beginning-of-line)
11762 (looking-at org-complex-heading-regexp)
11763 (let ((begin (point))
11764 (heading (match-string-no-properties 4)))
11765 (unless (or (and
11766 org-refile-target-verify-function
11767 (not
11768 (funcall org-refile-target-verify-function)))
11769 (not heading))
11770 (let ((re (format org-complex-heading-regexp-format
11771 (regexp-quote heading)))
11772 (target
11773 (if (not org-refile-use-outline-path) heading
11774 (mapconcat
11775 #'org-protect-slash
11776 (append
11777 (pcase org-refile-use-outline-path
11778 (`file (list (file-name-nondirectory
11779 (buffer-file-name
11780 (buffer-base-buffer)))))
11781 (`full-file-path
11782 (list (buffer-file-name
11783 (buffer-base-buffer))))
11784 (_ nil))
11785 (org-get-outline-path t t))
11786 "/"))))
11787 (push (list target f re (org-refile-marker (point)))
11788 tgs)))
11789 (when (= (point) begin)
11790 ;; Verification function has not moved point.
11791 (end-of-line)))))))
11792 (when org-refile-use-cache
11793 (org-refile-cache-put tgs (buffer-file-name) descre))
11794 (setq targets (append tgs targets))))))
11795 (message "Getting targets...done")
11796 (nreverse targets)))
11798 (defun org-protect-slash (s)
11799 (while (string-match "/" s)
11800 (setq s (replace-match "\\" t t s)))
11803 (defun org--get-outline-path-1 (&optional use-cache)
11804 "Return outline path to current headline.
11806 Outline path is a list of strings, in reverse order. When
11807 optional argument USE-CACHE is non-nil, make use of a cache. See
11808 `org-get-outline-path' for details.
11810 Assume buffer is widened and point is on a headline."
11811 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11812 (let ((p (point))
11813 (heading (progn
11814 (looking-at org-complex-heading-regexp)
11815 (if (not (match-end 4)) ""
11816 ;; Remove statistics cookies.
11817 (org-trim
11818 (org-link-display-format
11819 (replace-regexp-in-string
11820 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11821 (match-string-no-properties 4))))))))
11822 (if (org-up-heading-safe)
11823 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11824 (when use-cache
11825 (push (cons p path) org-outline-path-cache))
11826 path)
11827 ;; This is a new root node. Since we assume we are moving
11828 ;; forward, we can drop previous cache so as to limit number
11829 ;; of associations there.
11830 (let ((path (list heading)))
11831 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11832 path)))))
11834 (defun org-get-outline-path (&optional with-self use-cache)
11835 "Return the outline path to the current entry.
11837 An outline path is a list of ancestors for current headline, as
11838 a list of strings. Statistics cookies are removed and links are
11839 replaced with their description, if any, or their path otherwise.
11841 When optional argument WITH-SELF is non-nil, the path also
11842 includes the current headline.
11844 When optional argument USE-CACHE is non-nil, cache outline paths
11845 between calls to this function so as to avoid backtracking. This
11846 argument is useful when planning to find more than one outline
11847 path in the same document. In that case, there are two
11848 conditions to satisfy:
11849 - `org-outline-path-cache' is set to nil before starting the
11850 process;
11851 - outline paths are computed by increasing buffer positions."
11852 (org-with-wide-buffer
11853 (and (or (and with-self (org-back-to-heading t))
11854 (org-up-heading-safe))
11855 (reverse (org--get-outline-path-1 use-cache)))))
11857 (defun org-format-outline-path (path &optional width prefix separator)
11858 "Format the outline path PATH for display.
11859 WIDTH is the maximum number of characters that is available.
11860 PREFIX is a prefix to be included in the returned string,
11861 such as the file name.
11862 SEPARATOR is inserted between the different parts of the path,
11863 the default is \"/\"."
11864 (setq width (or width 79))
11865 (setq path (delq nil path))
11866 (unless (> width 0)
11867 (user-error "Argument `width' must be positive"))
11868 (setq separator (or separator "/"))
11869 (let* ((org-odd-levels-only nil)
11870 (fpath (concat
11871 prefix (and prefix path separator)
11872 (mapconcat
11873 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11874 (cl-loop for head in path
11875 for n from 0
11876 collect (org-add-props
11877 head nil 'face
11878 (nth (% n org-n-level-faces) org-level-faces)))
11879 separator))))
11880 (when (> (length fpath) width)
11881 (if (< width 7)
11882 ;; It's unlikely that `width' will be this small, but don't
11883 ;; waste characters by adding ".." if it is.
11884 (setq fpath (substring fpath 0 width))
11885 (setf (substring fpath (- width 2)) "..")))
11886 fpath))
11888 (defun org-display-outline-path (&optional file current separator just-return-string)
11889 "Display the current outline path in the echo area.
11891 If FILE is non-nil, prepend the output with the file name.
11892 If CURRENT is non-nil, append the current heading to the output.
11893 SEPARATOR is passed through to `org-format-outline-path'. It separates
11894 the different parts of the path and defaults to \"/\".
11895 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11896 (interactive "P")
11897 (let* (case-fold-search
11898 (bfn (buffer-file-name (buffer-base-buffer)))
11899 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11900 res)
11901 (when current (setq path (append path
11902 (save-excursion
11903 (org-back-to-heading t)
11904 (when (looking-at org-complex-heading-regexp)
11905 (list (match-string 4)))))))
11906 (setq res
11907 (org-format-outline-path
11908 path
11909 (1- (frame-width))
11910 (and file bfn (concat (file-name-nondirectory bfn) separator))
11911 separator))
11912 (if just-return-string
11913 (org-no-properties res)
11914 (org-unlogged-message "%s" res))))
11916 (defvar org-refile-history nil
11917 "History for refiling operations.")
11919 (defvar org-after-refile-insert-hook nil
11920 "Hook run after `org-refile' has inserted its stuff at the new location.
11921 Note that this is still *before* the stuff will be removed from
11922 the *old* location.")
11924 (defvar org-capture-last-stored-marker)
11925 (defvar org-refile-keep nil
11926 "Non-nil means `org-refile' will copy instead of refile.")
11928 (defun org-copy ()
11929 "Like `org-refile', but copy."
11930 (interactive)
11931 (let ((org-refile-keep t))
11932 (funcall 'org-refile nil nil nil "Copy")))
11934 (defun org-refile (&optional arg default-buffer rfloc msg)
11935 "Move the entry or entries at point to another heading.
11936 The list of target headings is compiled using the information in
11937 `org-refile-targets', which see.
11939 At the target location, the entry is filed as a subitem of the
11940 target heading. Depending on `org-reverse-note-order', the new
11941 subitem will either be the first or the last subitem.
11943 If there is an active region, all entries in that region will be
11944 refiled. However, the region must fulfill the requirement that
11945 the first heading sets the top-level of the moved text.
11947 With prefix arg ARG, the command will only visit the target
11948 location and not actually move anything.
11950 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11951 refiling operation has put the subtree.
11953 With a numeric prefix argument of `2', refile to the running clock.
11955 With a numeric prefix argument of `3', emulate `org-refile-keep'
11956 being set to t and copy to the target location, don't move it.
11957 Beware that keeping refiled entries may result in duplicated ID
11958 properties.
11960 RFLOC can be a refile location obtained in a different way.
11962 MSG is a string to replace \"Refile\" in the default prompt with
11963 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11965 See also `org-refile-use-outline-path'.
11967 If you are using target caching (see `org-refile-use-cache'), you
11968 have to clear the target cache in order to find new targets.
11969 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11970 prefix argument (`C-u C-u C-u C-c C-w')."
11971 (interactive "P")
11972 (if (member arg '(0 (64)))
11973 (org-refile-cache-clear)
11974 (let* ((actionmsg (cond (msg msg)
11975 ((equal arg 3) "Refile (and keep)")
11976 (t "Refile")))
11977 (regionp (org-region-active-p))
11978 (region-start (and regionp (region-beginning)))
11979 (region-end (and regionp (region-end)))
11980 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11981 pos it nbuf file level reversed)
11982 (setq last-command nil)
11983 (when regionp
11984 (goto-char region-start)
11985 (or (bolp) (goto-char (point-at-bol)))
11986 (setq region-start (point))
11987 (unless (or (org-kill-is-subtree-p
11988 (buffer-substring region-start region-end))
11989 (prog1 org-refile-active-region-within-subtree
11990 (let ((s (point-at-eol)))
11991 (org-toggle-heading)
11992 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11993 (user-error "The region is not a (sequence of) subtree(s)")))
11994 (if (equal arg '(16))
11995 (org-refile-goto-last-stored)
11996 (when (or
11997 (and (equal arg 2)
11998 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11999 (prog1
12000 (setq it (list (or org-clock-heading "running clock")
12001 (buffer-file-name
12002 (marker-buffer org-clock-hd-marker))
12004 (marker-position org-clock-hd-marker)))
12005 (setq arg nil)))
12006 (setq it
12007 (or rfloc
12008 (let (heading-text)
12009 (save-excursion
12010 (unless (and arg (listp arg))
12011 (org-back-to-heading t)
12012 (setq heading-text
12013 (replace-regexp-in-string
12014 org-bracket-link-regexp
12015 "\\3"
12016 (or (nth 4 (org-heading-components))
12017 ""))))
12018 (org-refile-get-location
12019 (cond ((and arg (listp arg)) "Goto")
12020 (regionp (concat actionmsg " region to"))
12021 (t (concat actionmsg " subtree \""
12022 heading-text "\" to")))
12023 default-buffer
12024 (and (not (equal '(4) arg))
12025 org-refile-allow-creating-parent-nodes)))))))
12026 (setq file (nth 1 it)
12027 pos (nth 3 it))
12028 (when (and (not arg)
12030 (equal (buffer-file-name) file)
12031 (if regionp
12032 (and (>= pos region-start)
12033 (<= pos region-end))
12034 (and (>= pos (point))
12035 (< pos (save-excursion
12036 (org-end-of-subtree t t))))))
12037 (error "Cannot refile to position inside the tree or region"))
12038 (setq nbuf (or (find-buffer-visiting file)
12039 (find-file-noselect file)))
12040 (if (and arg (not (equal arg 3)))
12041 (progn
12042 (pop-to-buffer-same-window nbuf)
12043 (goto-char pos)
12044 (org-show-context 'org-goto))
12045 (if regionp
12046 (progn
12047 (org-kill-new (buffer-substring region-start region-end))
12048 (org-save-markers-in-region region-start region-end))
12049 (org-copy-subtree 1 nil t))
12050 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12051 (find-file-noselect file)))
12052 (setq reversed (org-notes-order-reversed-p))
12053 (save-excursion
12054 (save-restriction
12055 (widen)
12056 (if pos
12057 (progn
12058 (goto-char pos)
12059 (looking-at org-outline-regexp)
12060 (setq level (org-get-valid-level (funcall outline-level) 1))
12061 (goto-char
12062 (if reversed
12063 (or (outline-next-heading) (point-max))
12064 (or (save-excursion (org-get-next-sibling))
12065 (org-end-of-subtree t t)
12066 (point-max)))))
12067 (setq level 1)
12068 (if (not reversed)
12069 (goto-char (point-max))
12070 (goto-char (point-min))
12071 (or (outline-next-heading) (goto-char (point-max)))))
12072 (unless (bolp) (newline))
12073 (org-paste-subtree level nil nil t)
12074 (when org-log-refile
12075 (org-add-log-setup 'refile nil nil org-log-refile)
12076 (unless (eq org-log-refile 'note)
12077 (save-excursion (org-add-log-note))))
12078 (and org-auto-align-tags
12079 (let ((org-loop-over-headlines-in-active-region nil))
12080 (org-set-tags nil t)))
12081 (let ((bookmark-name (plist-get org-bookmark-names-plist
12082 :last-refile)))
12083 (when bookmark-name
12084 (with-demoted-errors
12085 (bookmark-set bookmark-name))))
12086 ;; If we are refiling for capture, make sure that the
12087 ;; last-capture pointers point here
12088 (when (bound-and-true-p org-capture-is-refiling)
12089 (let ((bookmark-name (plist-get org-bookmark-names-plist
12090 :last-capture-marker)))
12091 (when bookmark-name
12092 (with-demoted-errors
12093 (bookmark-set bookmark-name))))
12094 (move-marker org-capture-last-stored-marker (point)))
12095 (when (fboundp 'deactivate-mark) (deactivate-mark))
12096 (run-hooks 'org-after-refile-insert-hook))))
12097 (unless org-refile-keep
12098 (if regionp
12099 (delete-region (point) (+ (point) (- region-end region-start)))
12100 (delete-region
12101 (and (org-back-to-heading t) (point))
12102 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12103 (when (featurep 'org-inlinetask)
12104 (org-inlinetask-remove-END-maybe))
12105 (setq org-markers-to-move nil)
12106 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12108 (defun org-refile-goto-last-stored ()
12109 "Go to the location where the last refile was stored."
12110 (interactive)
12111 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12112 (message "This is the location of the last refile"))
12114 (defun org-refile--get-location (refloc tbl)
12115 "When user refile to REFLOC, find the associated target in TBL.
12116 Also check `org-refile-target-table'."
12117 (car (delq
12119 (mapcar
12120 (lambda (r) (or (assoc r tbl)
12121 (assoc r org-refile-target-table)))
12122 (list (replace-regexp-in-string "/$" "" refloc)
12123 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12125 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12126 "Prompt the user for a refile location, using PROMPT.
12127 PROMPT should not be suffixed with a colon and a space, because
12128 this function appends the default value from
12129 `org-refile-history' automatically, if that is not empty."
12130 (let ((org-refile-targets org-refile-targets)
12131 (org-refile-use-outline-path org-refile-use-outline-path))
12132 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12133 (unless org-refile-target-table
12134 (user-error "No refile targets"))
12135 (let* ((cbuf (current-buffer))
12136 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12137 (cfunc (if (and org-refile-use-outline-path
12138 org-outline-path-complete-in-steps)
12139 #'org-olpath-completing-read
12140 #'completing-read))
12141 (extra (if org-refile-use-outline-path "/" ""))
12142 (cbnex (concat (buffer-name) extra))
12143 (filename (and cfn (expand-file-name cfn)))
12144 (tbl (mapcar
12145 (lambda (x)
12146 (if (and (not (member org-refile-use-outline-path
12147 '(file full-file-path)))
12148 (not (equal filename (nth 1 x))))
12149 (cons (concat (car x) extra " ("
12150 (file-name-nondirectory (nth 1 x)) ")")
12151 (cdr x))
12152 (cons (concat (car x) extra) (cdr x))))
12153 org-refile-target-table))
12154 (completion-ignore-case t)
12155 cdef
12156 (prompt (concat prompt
12157 (or (and (car org-refile-history)
12158 (concat " (default " (car org-refile-history) ")"))
12159 (and (assoc cbnex tbl) (setq cdef cbnex)
12160 (concat " (default " cbnex ")"))) ": "))
12161 pa answ parent-target child parent old-hist)
12162 (setq old-hist org-refile-history)
12163 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12164 nil 'org-refile-history (or cdef (car org-refile-history))))
12165 (if (setq pa (org-refile--get-location answ tbl))
12166 (progn
12167 (org-refile-check-position pa)
12168 (when (or (not org-refile-history)
12169 (not (eq old-hist org-refile-history))
12170 (not (equal (car pa) (car org-refile-history))))
12171 (setq org-refile-history
12172 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12173 org-refile-history
12174 (cdr org-refile-history))))
12175 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12176 (pop org-refile-history)))
12178 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12179 (progn
12180 (setq parent (match-string 1 answ)
12181 child (match-string 2 answ))
12182 (setq parent-target (org-refile--get-location parent tbl))
12183 (when (and parent-target
12184 (or (eq new-nodes t)
12185 (and (eq new-nodes 'confirm)
12186 (y-or-n-p (format "Create new node \"%s\"? "
12187 child)))))
12188 (org-refile-new-child parent-target child)))
12189 (user-error "Invalid target location")))))
12191 (declare-function org-string-nw-p "org-macs" (s))
12192 (defun org-refile-check-position (refile-pointer)
12193 "Check if the refile pointer matches the headline to which it points."
12194 (let* ((file (nth 1 refile-pointer))
12195 (re (nth 2 refile-pointer))
12196 (pos (nth 3 refile-pointer))
12197 buffer)
12198 (if (and (not (markerp pos)) (not file))
12199 (user-error "Please indicate a target file in the refile path")
12200 (when (org-string-nw-p re)
12201 (setq buffer (if (markerp pos)
12202 (marker-buffer pos)
12203 (or (find-buffer-visiting file)
12204 (find-file-noselect file))))
12205 (with-current-buffer buffer
12206 (save-excursion
12207 (save-restriction
12208 (widen)
12209 (goto-char pos)
12210 (beginning-of-line 1)
12211 (unless (looking-at-p re)
12212 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12214 (defun org-refile-new-child (parent-target child)
12215 "Use refile target PARENT-TARGET to add new CHILD below it."
12216 (unless parent-target
12217 (error "Cannot find parent for new node"))
12218 (let ((file (nth 1 parent-target))
12219 (pos (nth 3 parent-target))
12220 level)
12221 (with-current-buffer (or (find-buffer-visiting file)
12222 (find-file-noselect file))
12223 (save-excursion
12224 (save-restriction
12225 (widen)
12226 (if pos
12227 (goto-char pos)
12228 (goto-char (point-max))
12229 (unless (bolp) (newline)))
12230 (when (looking-at org-outline-regexp)
12231 (setq level (funcall outline-level))
12232 (org-end-of-subtree t t))
12233 (org-back-over-empty-lines)
12234 (insert "\n" (make-string
12235 (if pos (org-get-valid-level level 1) 1) ?*)
12236 " " child "\n")
12237 (beginning-of-line 0)
12238 (list (concat (car parent-target) "/" child) file "" (point)))))))
12240 (defun org-olpath-completing-read (prompt collection &rest args)
12241 "Read an outline path like a file name."
12242 (let ((thetable collection))
12243 (apply #'completing-read
12244 prompt
12245 (lambda (string predicate &optional flag)
12246 (cond
12247 ((eq flag nil) (try-completion string thetable))
12248 ((eq flag t)
12249 (let ((l (length string)))
12250 (mapcar (lambda (x)
12251 (let ((r (substring x l))
12252 (f (if (string-match " ([^)]*)$" x)
12253 (match-string 0 x)
12254 "")))
12255 (if (string-match "/" r)
12256 (concat string (substring r 0 (match-end 0)) f)
12257 x)))
12258 (all-completions string thetable predicate))))
12259 ;; Exact match?
12260 ((eq flag 'lambda) (assoc string thetable))))
12261 args)))
12263 ;;;; Dynamic blocks
12265 (defun org-find-dblock (name)
12266 "Find the first dynamic block with name NAME in the buffer.
12267 If not found, stay at current position and return nil."
12268 (let ((case-fold-search t) pos)
12269 (save-excursion
12270 (goto-char (point-min))
12271 (setq pos (and (re-search-forward
12272 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12273 (match-beginning 0))))
12274 (when pos (goto-char pos))
12275 pos))
12277 (defun org-create-dblock (plist)
12278 "Create a dynamic block section, with parameters taken from PLIST.
12279 PLIST must contain a :name entry which is used as the name of the block."
12280 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12281 (end-of-line 1)
12282 (newline))
12283 (let ((col (current-column))
12284 (name (plist-get plist :name)))
12285 (insert "#+BEGIN: " name)
12286 (while plist
12287 (if (eq (car plist) :name)
12288 (setq plist (cddr plist))
12289 (insert " " (prin1-to-string (pop plist)))))
12290 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12291 (beginning-of-line -2)))
12293 (defun org-prepare-dblock ()
12294 "Prepare dynamic block for refresh.
12295 This empties the block, puts the cursor at the insert position and returns
12296 the property list including an extra property :name with the block name."
12297 (unless (looking-at org-dblock-start-re)
12298 (user-error "Not at a dynamic block"))
12299 (let* ((begdel (1+ (match-end 0)))
12300 (name (org-no-properties (match-string 1)))
12301 (params (append (list :name name)
12302 (read (concat "(" (match-string 3) ")")))))
12303 (save-excursion
12304 (beginning-of-line 1)
12305 (skip-chars-forward " \t")
12306 (setq params (plist-put params :indentation-column (current-column))))
12307 (unless (re-search-forward org-dblock-end-re nil t)
12308 (error "Dynamic block not terminated"))
12309 (setq params
12310 (append params
12311 (list :content (buffer-substring
12312 begdel (match-beginning 0)))))
12313 (delete-region begdel (match-beginning 0))
12314 (goto-char begdel)
12315 (open-line 1)
12316 params))
12318 (defun org-map-dblocks (&optional command)
12319 "Apply COMMAND to all dynamic blocks in the current buffer.
12320 If COMMAND is not given, use `org-update-dblock'."
12321 (let ((cmd (or command 'org-update-dblock)))
12322 (save-excursion
12323 (goto-char (point-min))
12324 (while (re-search-forward org-dblock-start-re nil t)
12325 (goto-char (match-beginning 0))
12326 (save-excursion
12327 (condition-case nil
12328 (funcall cmd)
12329 (error (message "Error during update of dynamic block"))))
12330 (unless (re-search-forward org-dblock-end-re nil t)
12331 (error "Dynamic block not terminated"))))))
12333 (defun org-dblock-update (&optional arg)
12334 "User command for updating dynamic blocks.
12335 Update the dynamic block at point. With prefix ARG, update all dynamic
12336 blocks in the buffer."
12337 (interactive "P")
12338 (if arg
12339 (org-update-all-dblocks)
12340 (or (looking-at org-dblock-start-re)
12341 (org-beginning-of-dblock))
12342 (org-update-dblock)))
12344 (defun org-update-dblock ()
12345 "Update the dynamic block at point.
12346 This means to empty the block, parse for parameters and then call
12347 the correct writing function."
12348 (interactive)
12349 (save-excursion
12350 (let* ((win (selected-window))
12351 (pos (point))
12352 (line (org-current-line))
12353 (params (org-prepare-dblock))
12354 (name (plist-get params :name))
12355 (indent (plist-get params :indentation-column))
12356 (cmd (intern (concat "org-dblock-write:" name))))
12357 (message "Updating dynamic block `%s' at line %d..." name line)
12358 (funcall cmd params)
12359 (message "Updating dynamic block `%s' at line %d...done" name line)
12360 (goto-char pos)
12361 (when (and indent (> indent 0))
12362 (setq indent (make-string indent ?\ ))
12363 (save-excursion
12364 (select-window win)
12365 (org-beginning-of-dblock)
12366 (forward-line 1)
12367 (while (not (looking-at org-dblock-end-re))
12368 (insert indent)
12369 (beginning-of-line 2))
12370 (when (looking-at org-dblock-end-re)
12371 (and (looking-at "[ \t]+")
12372 (replace-match ""))
12373 (insert indent)))))))
12375 (defun org-beginning-of-dblock ()
12376 "Find the beginning of the dynamic block at point.
12377 Error if there is no such block at point."
12378 (let ((pos (point))
12379 beg)
12380 (end-of-line 1)
12381 (if (and (re-search-backward org-dblock-start-re nil t)
12382 (setq beg (match-beginning 0))
12383 (re-search-forward org-dblock-end-re nil t)
12384 (> (match-end 0) pos))
12385 (goto-char beg)
12386 (goto-char pos)
12387 (error "Not in a dynamic block"))))
12389 (defun org-update-all-dblocks ()
12390 "Update all dynamic blocks in the buffer.
12391 This function can be used in a hook."
12392 (interactive)
12393 (when (derived-mode-p 'org-mode)
12394 (org-map-dblocks 'org-update-dblock)))
12397 ;;;; Completion
12399 (declare-function org-export-backend-options "ox" (cl-x) t)
12400 (defun org-get-export-keywords ()
12401 "Return a list of all currently understood export keywords.
12402 Export keywords include options, block names, attributes and
12403 keywords relative to each registered export back-end."
12404 (let (keywords)
12405 (dolist (backend
12406 (bound-and-true-p org-export-registered-backends)
12407 (delq nil keywords))
12408 ;; Back-end name (for keywords, like #+LATEX:)
12409 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12410 (dolist (option-entry (org-export-backend-options backend))
12411 ;; Back-end options.
12412 (push (nth 1 option-entry) keywords)))))
12414 (defconst org-options-keywords
12415 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12416 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12417 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12418 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12419 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12421 (defcustom org-structure-template-alist
12422 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12423 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12424 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12425 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12426 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12427 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12428 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12429 ("L" "#+LaTeX: ")
12430 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12431 ("H" "#+HTML: ")
12432 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12433 ("A" "#+ASCII: ")
12434 ("i" "#+INDEX: ?")
12435 ("I" "#+INCLUDE: %file ?"))
12436 "Structure completion elements.
12437 This is a list of abbreviation keys and values. The value gets inserted
12438 if you type `<' followed by the key and then press the completion key,
12439 usually `TAB'. %file will be replaced by a file name after prompting
12440 for the file using completion. The cursor will be placed at the position
12441 of the `?' in the template.
12442 There are two templates for each key, the first uses the original Org syntax,
12443 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12444 the default when the /org-mtags.el/ module has been loaded. See also the
12445 variable `org-mtags-prefer-muse-templates'."
12446 :group 'org-completion
12447 :type '(repeat
12448 (list
12449 (string :tag "Key")
12450 (string :tag "Template")))
12451 :version "25.1"
12452 :package-version '(Org . "8.3"))
12454 (defun org-try-structure-completion ()
12455 "Try to complete a structure template before point.
12456 This looks for strings like \"<e\" on an otherwise empty line and
12457 expands them."
12458 (let ((l (buffer-substring (point-at-bol) (point)))
12460 (when (and (looking-at "[ \t]*$")
12461 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12462 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12463 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12464 (match-beginning 1)) a)
12465 t)))
12467 (defun org-complete-expand-structure-template (start cell)
12468 "Expand a structure template."
12469 (let ((rpl (nth 1 cell))
12470 (ind ""))
12471 (delete-region start (point))
12472 (when (string-match "\\`[ \t]*#\\+" rpl)
12473 (cond
12474 ((bolp))
12475 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12476 (setq ind (buffer-substring (point-at-bol) (point))))
12477 (t (newline))))
12478 (setq start (point))
12479 (when (string-match "%file" rpl)
12480 (setq rpl (replace-match
12481 (concat
12482 "\""
12483 (save-match-data
12484 (abbreviate-file-name (read-file-name "Include file: ")))
12485 "\"")
12486 t t rpl)))
12487 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12488 (concat "\n" ind)))
12489 (insert rpl)
12490 (when (re-search-backward "\\?" start t) (delete-char 1))))
12492 ;;;; TODO, DEADLINE, Comments
12494 (defun org-toggle-comment ()
12495 "Change the COMMENT state of an entry."
12496 (interactive)
12497 (save-excursion
12498 (org-back-to-heading)
12499 (looking-at org-complex-heading-regexp)
12500 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12501 (skip-chars-forward " \t")
12502 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12503 (if (org-in-commented-heading-p t)
12504 (delete-region (point)
12505 (progn (search-forward " " (line-end-position) 'move)
12506 (skip-chars-forward " \t")
12507 (point)))
12508 (insert org-comment-string)
12509 (unless (eolp) (insert " ")))))
12511 (defvar org-last-todo-state-is-todo nil
12512 "This is non-nil when the last TODO state change led to a TODO state.
12513 If the last change removed the TODO tag or switched to DONE, then
12514 this is nil.")
12516 (defvar org-setting-tags nil) ; dynamically skipped
12518 (defvar org-todo-setup-filter-hook nil
12519 "Hook for functions that pre-filter todo specs.
12520 Each function takes a todo spec and returns either nil or the spec
12521 transformed into canonical form." )
12523 (defvar org-todo-get-default-hook nil
12524 "Hook for functions that get a default item for todo.
12525 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12526 nil or a string to be used for the todo mark." )
12528 (defvar org-agenda-headline-snapshot-before-repeat)
12530 (defun org-current-effective-time ()
12531 "Return current time adjusted for `org-extend-today-until' variable."
12532 (let* ((ct (org-current-time))
12533 (dct (decode-time ct))
12534 (ct1
12535 (cond
12536 (org-use-last-clock-out-time-as-effective-time
12537 (or (org-clock-get-last-clock-out-time) ct))
12538 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12539 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12540 (t ct))))
12541 ct1))
12543 (defun org-todo-yesterday (&optional arg)
12544 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12545 (interactive "P")
12546 (if (eq major-mode 'org-agenda-mode)
12547 (apply 'org-agenda-todo-yesterday arg)
12548 (let* ((org-use-effective-time t)
12549 (hour (nth 2 (decode-time (org-current-time))))
12550 (org-extend-today-until (1+ hour)))
12551 (org-todo arg))))
12553 (defvar org-block-entry-blocking ""
12554 "First entry preventing the TODO state change.")
12556 (defun org-cancel-repeater ()
12557 "Cancel a repeater by setting its numeric value to zero."
12558 (interactive)
12559 (save-excursion
12560 (org-back-to-heading t)
12561 (let ((bound1 (point))
12562 (bound0 (save-excursion (outline-next-heading) (point))))
12563 (when (and (re-search-forward
12564 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12565 org-deadline-time-regexp "\\)\\|\\("
12566 org-ts-regexp "\\)")
12567 bound0 t)
12568 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12569 bound1 t))
12570 (replace-match "0" t nil nil 1)))))
12572 (defvar org-state) ;; dynamically scoped into this function
12573 (defun org-todo (&optional arg)
12574 "Change the TODO state of an item.
12575 The state of an item is given by a keyword at the start of the heading,
12576 like
12577 *** TODO Write paper
12578 *** DONE Call mom
12580 The different keywords are specified in the variable `org-todo-keywords'.
12581 By default the available states are \"TODO\" and \"DONE\".
12582 So for this example: when the item starts with TODO, it is changed to DONE.
12583 When it starts with DONE, the DONE is removed. And when neither TODO nor
12584 DONE are present, add TODO at the beginning of the heading.
12586 With \\[universal-argument] prefix arg, use completion to determine the new \
12587 state.
12588 With numeric prefix arg, switch to that state.
12589 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12590 keywords (nextset).
12591 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12592 With a numeric prefix arg of 0, inhibit note taking for the change.
12593 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12595 When called through ELisp, arg is also interpreted in the following way:
12596 `none' -> empty state
12597 \"\"(empty string) -> switch to empty state
12598 `done' -> switch to DONE
12599 `nextset' -> switch to the next set of keywords
12600 `previousset' -> switch to the previous set of keywords
12601 \"WAITING\" -> switch to the specified keyword, but only if it
12602 really is a member of `org-todo-keywords'."
12603 (interactive "P")
12604 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12605 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12606 'region-start-level 'region))
12607 org-loop-over-headlines-in-active-region)
12608 (org-map-entries
12609 `(org-todo ,arg)
12610 org-loop-over-headlines-in-active-region
12611 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12612 (when (equal arg '(16)) (setq arg 'nextset))
12613 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12614 (let ((org-blocker-hook org-blocker-hook)
12615 commentp
12616 case-fold-search)
12617 (when (equal arg '(64))
12618 (setq arg nil org-blocker-hook nil))
12619 (when (and org-blocker-hook
12620 (or org-inhibit-blocking
12621 (org-entry-get nil "NOBLOCKING")))
12622 (setq org-blocker-hook nil))
12623 (save-excursion
12624 (catch 'exit
12625 (org-back-to-heading t)
12626 (when (org-in-commented-heading-p t)
12627 (org-toggle-comment)
12628 (setq commentp t))
12629 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12630 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12631 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12632 (let* ((match-data (match-data))
12633 (startpos (point-at-bol))
12634 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12635 (org-log-done org-log-done)
12636 (org-log-repeat org-log-repeat)
12637 (org-todo-log-states org-todo-log-states)
12638 (org-inhibit-logging
12639 (if (equal arg 0)
12640 (progn (setq arg nil) 'note) org-inhibit-logging))
12641 (this (match-string 1))
12642 (hl-pos (match-beginning 0))
12643 (head (org-get-todo-sequence-head this))
12644 (ass (assoc head org-todo-kwd-alist))
12645 (interpret (nth 1 ass))
12646 (done-word (nth 3 ass))
12647 (final-done-word (nth 4 ass))
12648 (org-last-state (or this ""))
12649 (completion-ignore-case t)
12650 (member (member this org-todo-keywords-1))
12651 (tail (cdr member))
12652 (org-state (cond
12653 ((and org-todo-key-trigger
12654 (or (and (equal arg '(4))
12655 (eq org-use-fast-todo-selection 'prefix))
12656 (and (not arg) org-use-fast-todo-selection
12657 (not (eq org-use-fast-todo-selection
12658 'prefix)))))
12659 ;; Use fast selection
12660 (org-fast-todo-selection))
12661 ((and (equal arg '(4))
12662 (or (not org-use-fast-todo-selection)
12663 (not org-todo-key-trigger)))
12664 ;; Read a state with completion
12665 (completing-read
12666 "State: " (mapcar #'list org-todo-keywords-1)
12667 nil t))
12668 ((eq arg 'right)
12669 (if this
12670 (if tail (car tail) nil)
12671 (car org-todo-keywords-1)))
12672 ((eq arg 'left)
12673 (unless (equal member org-todo-keywords-1)
12674 (if this
12675 (nth (- (length org-todo-keywords-1)
12676 (length tail) 2)
12677 org-todo-keywords-1)
12678 (org-last org-todo-keywords-1))))
12679 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12680 (setq arg nil))) ; hack to fall back to cycling
12681 (arg
12682 ;; user or caller requests a specific state
12683 (cond
12684 ((equal arg "") nil)
12685 ((eq arg 'none) nil)
12686 ((eq arg 'done) (or done-word (car org-done-keywords)))
12687 ((eq arg 'nextset)
12688 (or (car (cdr (member head org-todo-heads)))
12689 (car org-todo-heads)))
12690 ((eq arg 'previousset)
12691 (let ((org-todo-heads (reverse org-todo-heads)))
12692 (or (car (cdr (member head org-todo-heads)))
12693 (car org-todo-heads))))
12694 ((car (member arg org-todo-keywords-1)))
12695 ((stringp arg)
12696 (user-error "State `%s' not valid in this file" arg))
12697 ((nth (1- (prefix-numeric-value arg))
12698 org-todo-keywords-1))))
12699 ((null member) (or head (car org-todo-keywords-1)))
12700 ((equal this final-done-word) nil) ;; -> make empty
12701 ((null tail) nil) ;; -> first entry
12702 ((memq interpret '(type priority))
12703 (if (eq this-command last-command)
12704 (car tail)
12705 (if (> (length tail) 0)
12706 (or done-word (car org-done-keywords))
12707 nil)))
12709 (car tail))))
12710 (org-state (or
12711 (run-hook-with-args-until-success
12712 'org-todo-get-default-hook org-state org-last-state)
12713 org-state))
12714 (next (if org-state (concat " " org-state " ") " "))
12715 (change-plist (list :type 'todo-state-change :from this :to org-state
12716 :position startpos))
12717 dolog now-done-p)
12718 (when org-blocker-hook
12719 (setq org-last-todo-state-is-todo
12720 (not (member this org-done-keywords)))
12721 (unless (save-excursion
12722 (save-match-data
12723 (org-with-wide-buffer
12724 (run-hook-with-args-until-failure
12725 'org-blocker-hook change-plist))))
12726 (if (called-interactively-p 'interactive)
12727 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12728 this org-state org-block-entry-blocking)
12729 ;; fail silently
12730 (message "TODO state change from %s to %s blocked (by \"%s\")"
12731 this org-state org-block-entry-blocking)
12732 (throw 'exit nil))))
12733 (store-match-data match-data)
12734 (replace-match next t t)
12735 (cond ((equal this org-state)
12736 (message "TODO state was already %s" (org-trim next)))
12737 ((pos-visible-in-window-p hl-pos)
12738 (message "TODO state changed to %s" (org-trim next))))
12739 (unless head
12740 (setq head (org-get-todo-sequence-head org-state)
12741 ass (assoc head org-todo-kwd-alist)
12742 interpret (nth 1 ass)
12743 done-word (nth 3 ass)
12744 final-done-word (nth 4 ass)))
12745 (when (memq arg '(nextset previousset))
12746 (message "Keyword-Set %d/%d: %s"
12747 (- (length org-todo-sets) -1
12748 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12749 (length org-todo-sets)
12750 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12751 (setq org-last-todo-state-is-todo
12752 (not (member org-state org-done-keywords)))
12753 (setq now-done-p (and (member org-state org-done-keywords)
12754 (not (member this org-done-keywords))))
12755 (and logging (org-local-logging logging))
12756 (when (and (or org-todo-log-states org-log-done)
12757 (not (eq org-inhibit-logging t))
12758 (not (memq arg '(nextset previousset))))
12759 ;; we need to look at recording a time and note
12760 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12761 (nth 2 (assoc this org-todo-log-states))))
12762 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12763 (setq dolog 'time))
12764 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12765 (and org-state
12766 (member org-state org-not-done-keywords)
12767 (not (member this org-not-done-keywords))))
12768 ;; This is now a todo state and was not one before
12769 ;; If there was a CLOSED time stamp, get rid of it.
12770 (org-add-planning-info nil nil 'closed))
12771 (when (and now-done-p org-log-done)
12772 ;; It is now done, and it was not done before
12773 (org-add-planning-info 'closed (org-current-effective-time))
12774 (when (and (not dolog) (eq 'note org-log-done))
12775 (org-add-log-setup 'done org-state this 'note)))
12776 (when (and org-state dolog)
12777 ;; This is a non-nil state, and we need to log it
12778 (org-add-log-setup 'state org-state this dolog)))
12779 ;; Fixup tag positioning
12780 (org-todo-trigger-tag-changes org-state)
12781 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12782 (when org-provide-todo-statistics
12783 (org-update-parent-todo-statistics))
12784 (run-hooks 'org-after-todo-state-change-hook)
12785 (when (and arg (not (member org-state org-done-keywords)))
12786 (setq head (org-get-todo-sequence-head org-state)))
12787 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12788 ;; Do we need to trigger a repeat?
12789 (when now-done-p
12790 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12791 ;; This is for the agenda, take a snapshot of the headline.
12792 (save-match-data
12793 (setq org-agenda-headline-snapshot-before-repeat
12794 (org-get-heading))))
12795 (org-auto-repeat-maybe org-state))
12796 ;; Fixup cursor location if close to the keyword
12797 (when (and (outline-on-heading-p)
12798 (not (bolp))
12799 (save-excursion (beginning-of-line 1)
12800 (looking-at org-todo-line-regexp))
12801 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12802 (goto-char (or (match-end 2) (match-end 1)))
12803 (and (looking-at " ") (just-one-space)))
12804 (when org-trigger-hook
12805 (save-excursion
12806 (run-hook-with-args 'org-trigger-hook change-plist)))
12807 (when commentp (org-toggle-comment))))))))
12809 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12810 "Block turning an entry into a TODO, using the hierarchy.
12811 This checks whether the current task should be blocked from state
12812 changes. Such blocking occurs when:
12814 1. The task has children which are not all in a completed state.
12816 2. A task has a parent with the property :ORDERED:, and there
12817 are siblings prior to the current task with incomplete
12818 status.
12820 3. The parent of the task is blocked because it has siblings that should
12821 be done first, or is child of a block grandparent TODO entry."
12823 (if (not org-enforce-todo-dependencies)
12824 t ; if locally turned off don't block
12825 (catch 'dont-block
12826 ;; If this is not a todo state change, or if this entry is already DONE,
12827 ;; do not block
12828 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12829 (member (plist-get change-plist :from)
12830 (cons 'done org-done-keywords))
12831 (member (plist-get change-plist :to)
12832 (cons 'todo org-not-done-keywords))
12833 (not (plist-get change-plist :to)))
12834 (throw 'dont-block t))
12835 ;; If this task has children, and any are undone, it's blocked
12836 (save-excursion
12837 (org-back-to-heading t)
12838 (let ((this-level (funcall outline-level)))
12839 (outline-next-heading)
12840 (let ((child-level (funcall outline-level)))
12841 (while (and (not (eobp))
12842 (> child-level this-level))
12843 ;; this todo has children, check whether they are all
12844 ;; completed
12845 (when (and (not (org-entry-is-done-p))
12846 (org-entry-is-todo-p))
12847 (setq org-block-entry-blocking (org-get-heading))
12848 (throw 'dont-block nil))
12849 (outline-next-heading)
12850 (setq child-level (funcall outline-level))))))
12851 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12852 ;; any previous siblings are undone, it's blocked
12853 (save-excursion
12854 (org-back-to-heading t)
12855 (let* ((pos (point))
12856 (parent-pos (and (org-up-heading-safe) (point))))
12857 (unless parent-pos (throw 'dont-block t)) ; no parent
12858 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12859 (forward-line 1)
12860 (re-search-forward org-not-done-heading-regexp pos t))
12861 (setq org-block-entry-blocking (match-string 0))
12862 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12863 ;; Search further up the hierarchy, to see if an ancestor is blocked
12864 (while t
12865 (goto-char parent-pos)
12866 (unless (looking-at org-not-done-heading-regexp)
12867 (throw 'dont-block t)) ; do not block, parent is not a TODO
12868 (setq pos (point))
12869 (setq parent-pos (and (org-up-heading-safe) (point)))
12870 (unless parent-pos (throw 'dont-block t)) ; no parent
12871 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12872 (forward-line 1)
12873 (re-search-forward org-not-done-heading-regexp pos t)
12874 (setq org-block-entry-blocking (org-get-heading)))
12875 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12877 (defcustom org-track-ordered-property-with-tag nil
12878 "Should the ORDERED property also be shown as a tag?
12879 The ORDERED property decides if an entry should require subtasks to be
12880 completed in sequence. Since a property is not very visible, setting
12881 this option means that toggling the ORDERED property with the command
12882 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12883 not relevant for the behavior, but it makes things more visible.
12885 Note that toggling the tag with tags commands will not change the property
12886 and therefore not influence behavior!
12888 This can be t, meaning the tag ORDERED should be used, It can also be a
12889 string to select a different tag for this task."
12890 :group 'org-todo
12891 :type '(choice
12892 (const :tag "No tracking" nil)
12893 (const :tag "Track with ORDERED tag" t)
12894 (string :tag "Use other tag")))
12896 (defun org-toggle-ordered-property ()
12897 "Toggle the ORDERED property of the current entry.
12898 For better visibility, you can track the value of this property with a tag.
12899 See variable `org-track-ordered-property-with-tag'."
12900 (interactive)
12901 (let* ((t1 org-track-ordered-property-with-tag)
12902 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12903 (save-excursion
12904 (org-back-to-heading)
12905 (if (org-entry-get nil "ORDERED")
12906 (progn
12907 (org-delete-property "ORDERED")
12908 (and tag (org-toggle-tag tag 'off))
12909 (message "Subtasks can be completed in arbitrary order"))
12910 (org-entry-put nil "ORDERED" "t")
12911 (and tag (org-toggle-tag tag 'on))
12912 (message "Subtasks must be completed in sequence")))))
12914 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12915 (defun org-block-todo-from-checkboxes (change-plist)
12916 "Block turning an entry into a TODO, using checkboxes.
12917 This checks whether the current task should be blocked from state
12918 changes because there are unchecked boxes in this entry."
12919 (if (not org-enforce-todo-checkbox-dependencies)
12920 t ; if locally turned off don't block
12921 (catch 'dont-block
12922 ;; If this is not a todo state change, or if this entry is already DONE,
12923 ;; do not block
12924 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12925 (member (plist-get change-plist :from)
12926 (cons 'done org-done-keywords))
12927 (member (plist-get change-plist :to)
12928 (cons 'todo org-not-done-keywords))
12929 (not (plist-get change-plist :to)))
12930 (throw 'dont-block t))
12931 ;; If this task has checkboxes that are not checked, it's blocked
12932 (save-excursion
12933 (org-back-to-heading t)
12934 (let ((beg (point)) end)
12935 (outline-next-heading)
12936 (setq end (point))
12937 (goto-char beg)
12938 (when (org-list-search-forward
12939 (concat (org-item-beginning-re)
12940 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12941 "\\[[- ]\\]")
12942 end t)
12943 (when (boundp 'org-blocked-by-checkboxes)
12944 (setq org-blocked-by-checkboxes t))
12945 (throw 'dont-block nil))))
12946 t))) ; do not block
12948 (defun org-entry-blocked-p ()
12949 "Non-nil if entry at point is blocked."
12950 (and (not (org-entry-get nil "NOBLOCKING"))
12951 (member (org-entry-get nil "TODO") org-not-done-keywords)
12952 (not (run-hook-with-args-until-failure
12953 'org-blocker-hook
12954 (list :type 'todo-state-change
12955 :position (point)
12956 :from 'todo
12957 :to 'done)))))
12959 (defun org-update-statistics-cookies (all)
12960 "Update the statistics cookie, either from TODO or from checkboxes.
12961 This should be called with the cursor in a line with a statistics cookie."
12962 (interactive "P")
12963 (if all
12964 (progn
12965 (org-update-checkbox-count 'all)
12966 (org-map-entries 'org-update-parent-todo-statistics))
12967 (if (not (org-at-heading-p))
12968 (org-update-checkbox-count)
12969 (let ((pos (point-marker))
12970 end l1 l2)
12971 (ignore-errors (org-back-to-heading t))
12972 (if (not (org-at-heading-p))
12973 (org-update-checkbox-count)
12974 (setq l1 (org-outline-level))
12975 (setq end (save-excursion
12976 (outline-next-heading)
12977 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12978 (point)))
12979 (if (and (save-excursion
12980 (re-search-forward
12981 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12982 (not (save-excursion (re-search-forward
12983 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12984 (org-update-checkbox-count)
12985 (if (and l2 (> l2 l1))
12986 (progn
12987 (goto-char end)
12988 (org-update-parent-todo-statistics))
12989 (goto-char pos)
12990 (beginning-of-line 1)
12991 (while (re-search-forward
12992 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12993 (point-at-eol) t)
12994 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12995 (goto-char pos)
12996 (move-marker pos nil)))))
12998 (defvar org-entry-property-inherited-from) ;; defined below
12999 (defun org-update-parent-todo-statistics ()
13000 "Update any statistics cookie in the parent of the current headline.
13001 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13002 the entire subtree and this will travel up the hierarchy and update
13003 statistics everywhere."
13004 (let* ((prop (save-excursion (org-up-heading-safe)
13005 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13006 (recursive (or (not org-hierarchical-todo-statistics)
13007 (and prop (string-match "\\<recursive\\>" prop))))
13008 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13010 (first t)
13011 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13012 level ltoggle l1 new ndel
13013 (cnt-all 0) (cnt-done 0) is-percent kwd
13014 checkbox-beg ov ovs ove cookie-present)
13015 (catch 'exit
13016 (save-excursion
13017 (beginning-of-line 1)
13018 (setq ltoggle (funcall outline-level))
13019 ;; Three situations are to consider:
13021 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13022 ;; to the top-level ancestor on the headline;
13024 ;; 2. If parent has "recursive" property, repeat up to the
13025 ;; headline setting that property, taking inheritance into
13026 ;; account;
13028 ;; 3. Else, move up to direct parent and proceed only once.
13029 (while (and (setq level (org-up-heading-safe))
13030 (or recursive first)
13031 (>= (point) lim))
13032 (setq first nil cookie-present nil)
13033 (unless (and level
13034 (not (string-match
13035 "\\<checkbox\\>"
13036 (downcase (or (org-entry-get nil "COOKIE_DATA")
13037 "")))))
13038 (throw 'exit nil))
13039 (while (re-search-forward box-re (point-at-eol) t)
13040 (setq cnt-all 0 cnt-done 0 cookie-present t)
13041 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13042 (save-match-data
13043 (unless (outline-next-heading) (throw 'exit nil))
13044 (while (and (looking-at org-complex-heading-regexp)
13045 (> (setq l1 (length (match-string 1))) level))
13046 (setq kwd (and (or recursive (= l1 ltoggle))
13047 (match-string 2)))
13048 (if (or (eq org-provide-todo-statistics 'all-headlines)
13049 (and (eq org-provide-todo-statistics t)
13050 (or (member kwd org-done-keywords)))
13051 (and (listp org-provide-todo-statistics)
13052 (stringp (car org-provide-todo-statistics))
13053 (or (member kwd org-provide-todo-statistics)
13054 (member kwd org-done-keywords)))
13055 (and (listp org-provide-todo-statistics)
13056 (listp (car org-provide-todo-statistics))
13057 (or (member kwd (car org-provide-todo-statistics))
13058 (and (member kwd org-done-keywords)
13059 (member kwd (cadr org-provide-todo-statistics))))))
13060 (setq cnt-all (1+ cnt-all))
13061 (and (eq org-provide-todo-statistics t)
13063 (setq cnt-all (1+ cnt-all))))
13064 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13065 (member kwd org-done-keywords))
13066 (and (listp org-provide-todo-statistics)
13067 (listp (car org-provide-todo-statistics))
13068 (member kwd org-done-keywords)
13069 (member kwd (cadr org-provide-todo-statistics)))
13070 (and (listp org-provide-todo-statistics)
13071 (stringp (car org-provide-todo-statistics))
13072 (member kwd org-done-keywords)))
13073 (setq cnt-done (1+ cnt-done)))
13074 (outline-next-heading)))
13075 (setq new
13076 (if is-percent
13077 (format "[%d%%]" (floor (* 100.0 cnt-done)
13078 (max 1 cnt-all)))
13079 (format "[%d/%d]" cnt-done cnt-all))
13080 ndel (- (match-end 0) checkbox-beg))
13081 ;; handle overlays when updating cookie from column view
13082 (when (setq ov (car (overlays-at checkbox-beg)))
13083 (setq ovs (overlay-start ov) ove (overlay-end ov))
13084 (delete-overlay ov))
13085 (goto-char checkbox-beg)
13086 (insert new)
13087 (delete-region (point) (+ (point) ndel))
13088 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13089 (when ov (move-overlay ov ovs ove)))
13090 (when cookie-present
13091 (run-hook-with-args 'org-after-todo-statistics-hook
13092 cnt-done (- cnt-all cnt-done))))))
13093 (run-hooks 'org-todo-statistics-hook)))
13095 (defvar org-after-todo-statistics-hook nil
13096 "Hook that is called after a TODO statistics cookie has been updated.
13097 Each function is called with two arguments: the number of not-done entries
13098 and the number of done entries.
13100 For example, the following function, when added to this hook, will switch
13101 an entry to DONE when all children are done, and back to TODO when new
13102 entries are set to a TODO status. Note that this hook is only called
13103 when there is a statistics cookie in the headline!
13105 \(defun org-summary-todo (n-done n-not-done)
13106 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13107 \(let (org-log-done org-log-states) ; turn off logging
13108 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13111 (defvar org-todo-statistics-hook nil
13112 "Hook that is run whenever Org thinks TODO statistics should be updated.
13113 This hook runs even if there is no statistics cookie present, in which case
13114 `org-after-todo-statistics-hook' would not run.")
13116 (defun org-todo-trigger-tag-changes (state)
13117 "Apply the changes defined in `org-todo-state-tags-triggers'."
13118 (let ((l org-todo-state-tags-triggers)
13119 changes)
13120 (when (or (not state) (equal state ""))
13121 (setq changes (append changes (cdr (assoc "" l)))))
13122 (when (and (stringp state) (> (length state) 0))
13123 (setq changes (append changes (cdr (assoc state l)))))
13124 (when (member state org-not-done-keywords)
13125 (setq changes (append changes (cdr (assoc 'todo l)))))
13126 (when (member state org-done-keywords)
13127 (setq changes (append changes (cdr (assoc 'done l)))))
13128 (dolist (c changes)
13129 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13131 (defun org-local-logging (value)
13132 "Get logging settings from a property VALUE."
13133 ;; Directly set the variables, they are already local.
13134 (setq org-log-done nil
13135 org-log-repeat nil
13136 org-todo-log-states nil)
13137 (dolist (w (org-split-string value))
13138 (let (a)
13139 (cond
13140 ((setq a (assoc w org-startup-options))
13141 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13142 (set (nth 1 a) (nth 2 a))))
13143 ((setq a (org-extract-log-state-settings w))
13144 (and (member (car a) org-todo-keywords-1)
13145 (push a org-todo-log-states)))))))
13147 (defun org-get-todo-sequence-head (kwd)
13148 "Return the head of the TODO sequence to which KWD belongs.
13149 If KWD is not set, check if there is a text property remembering the
13150 right sequence."
13151 (let (p)
13152 (cond
13153 ((not kwd)
13154 (or (get-text-property (point-at-bol) 'org-todo-head)
13155 (progn
13156 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13157 nil (point-at-eol)))
13158 (get-text-property p 'org-todo-head))))
13159 ((not (member kwd org-todo-keywords-1))
13160 (car org-todo-keywords-1))
13161 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13163 (defun org-fast-todo-selection ()
13164 "Fast TODO keyword selection with single keys.
13165 Returns the new TODO keyword, or nil if no state change should occur."
13166 (let* ((fulltable org-todo-key-alist)
13167 (done-keywords org-done-keywords) ;; needed for the faces.
13168 (maxlen (apply 'max (mapcar
13169 (lambda (x)
13170 (if (stringp (car x)) (string-width (car x)) 0))
13171 fulltable)))
13172 (expert nil)
13173 (fwidth (+ maxlen 3 1 3))
13174 (ncol (/ (- (window-width) 4) fwidth))
13175 tg cnt e c tbl
13176 groups ingroup)
13177 (save-excursion
13178 (save-window-excursion
13179 (if expert
13180 (set-buffer (get-buffer-create " *Org todo*"))
13181 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13182 (erase-buffer)
13183 (setq-local org-done-keywords done-keywords)
13184 (setq tbl fulltable cnt 0)
13185 (while (setq e (pop tbl))
13186 (cond
13187 ((equal e '(:startgroup))
13188 (push '() groups) (setq ingroup t)
13189 (unless (= cnt 0)
13190 (setq cnt 0)
13191 (insert "\n"))
13192 (insert "{ "))
13193 ((equal e '(:endgroup))
13194 (setq ingroup nil cnt 0)
13195 (insert "}\n"))
13196 ((equal e '(:newline))
13197 (unless (= cnt 0)
13198 (setq cnt 0)
13199 (insert "\n")
13200 (setq e (car tbl))
13201 (while (equal (car tbl) '(:newline))
13202 (insert "\n")
13203 (setq tbl (cdr tbl)))))
13205 (setq tg (car e) c (cdr e))
13206 (when ingroup (push tg (car groups)))
13207 (setq tg (org-add-props tg nil 'face
13208 (org-get-todo-face tg)))
13209 (when (and (= cnt 0) (not ingroup)) (insert " "))
13210 (insert "[" c "] " tg (make-string
13211 (- fwidth 4 (length tg)) ?\ ))
13212 (when (= (setq cnt (1+ cnt)) ncol)
13213 (insert "\n")
13214 (when ingroup (insert " "))
13215 (setq cnt 0)))))
13216 (insert "\n")
13217 (goto-char (point-min))
13218 (unless expert (org-fit-window-to-buffer))
13219 (message "[a-z..]:Set [SPC]:clear")
13220 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13221 (cond
13222 ((or (= c ?\C-g)
13223 (and (= c ?q) (not (rassoc c fulltable))))
13224 (setq quit-flag t))
13225 ((= c ?\ ) nil)
13226 ((setq e (rassoc c fulltable) tg (car e))
13228 (t (setq quit-flag t)))))))
13230 (defun org-entry-is-todo-p ()
13231 (member (org-get-todo-state) org-not-done-keywords))
13233 (defun org-entry-is-done-p ()
13234 (member (org-get-todo-state) org-done-keywords))
13236 (defun org-get-todo-state ()
13237 "Return the TODO keyword of the current subtree."
13238 (save-excursion
13239 (org-back-to-heading t)
13240 (and (looking-at org-todo-line-regexp)
13241 (match-end 2)
13242 (match-string 2))))
13244 (defun org-at-date-range-p (&optional inactive-ok)
13245 "Non-nil if point is inside a date range.
13247 When optional argument INACTIVE-OK is non-nil, also consider
13248 inactive time ranges.
13250 When this function returns a non-nil value, match data is set
13251 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13252 on INACTIVE-OK."
13253 (interactive)
13254 (save-excursion
13255 (catch 'exit
13256 (let ((pos (point)))
13257 (skip-chars-backward "^[<\r\n")
13258 (skip-chars-backward "<[")
13259 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13260 (>= (match-end 0) pos)
13261 (throw 'exit t))
13262 (skip-chars-backward "^<[\r\n")
13263 (skip-chars-backward "<[")
13264 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13265 (>= (match-end 0) pos)
13266 (throw 'exit t)))
13267 nil)))
13269 (defun org-get-repeat (&optional tagline)
13270 "Check if there is a deadline/schedule with repeater in this entry."
13271 (save-match-data
13272 (save-excursion
13273 (org-back-to-heading t)
13274 (and (re-search-forward (if tagline
13275 (concat tagline "\\s-*" org-repeat-re)
13276 org-repeat-re)
13277 (org-entry-end-position) t)
13278 (match-string-no-properties 1)))))
13280 (defvar org-last-changed-timestamp)
13281 (defvar org-last-inserted-timestamp)
13282 (defvar org-log-post-message)
13283 (defvar org-log-note-purpose)
13284 (defvar org-log-note-how nil)
13285 (defvar org-log-note-extra)
13286 (defun org-auto-repeat-maybe (done-word)
13287 "Check if the current headline contains a repeated time-stamp.
13289 If yes, set TODO state back to what it was and change the base date
13290 of repeating deadline/scheduled time stamps to new date.
13292 This function is run automatically after each state change to a DONE state."
13293 (let* ((repeat (org-get-repeat))
13294 (aa (assoc org-last-state org-todo-kwd-alist))
13295 (interpret (nth 1 aa))
13296 (head (nth 2 aa))
13297 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13298 (msg "Entry repeats: ")
13299 (org-log-done nil)
13300 (org-todo-log-states nil))
13301 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13302 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13303 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13304 org-todo-repeat-to-state)))
13305 (unless (and to-state (member to-state org-todo-keywords-1))
13306 (setq to-state (if (eq interpret 'type) org-last-state head)))
13307 (org-todo to-state))
13308 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13309 (org-entry-put nil "LAST_REPEAT" (format-time-string
13310 (org-time-stamp-format t t))))
13311 (when org-log-repeat
13312 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13313 (memq 'org-add-log-note post-command-hook))
13314 ;; We are already setup for some record.
13315 (when (eq org-log-repeat 'note)
13316 ;; Make sure we take a note, not only a time stamp.
13317 (setq org-log-note-how 'note))
13318 ;; Set up for taking a record.
13319 (org-add-log-setup 'state
13320 (or done-word (car org-done-keywords))
13321 org-last-state
13322 org-log-repeat)))
13323 (org-back-to-heading t)
13324 (org-add-planning-info nil nil 'closed)
13325 (let ((end (save-excursion (outline-next-heading) (point))))
13326 (while (re-search-forward org-ts-regexp end t)
13327 (when (save-match-data
13328 (or (org-at-planning-p)
13329 (org-at-property-p)
13330 (eq (org-element-type (save-excursion
13331 (backward-char)
13332 (org-element-context)))
13333 'timestamp)))
13334 (let ((type (cond ((match-end 1) org-scheduled-string)
13335 ((match-end 3) org-deadline-string)
13336 (t "Plain:")))
13337 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13338 (cond
13339 ((not
13340 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13341 ;; Time-stamps without a repeater are usually skipped.
13342 ;; However, a SCHEDULED time-stamp without one is
13343 ;; removed, as it is considered as no longer relevant.
13344 (when (equal type org-scheduled-string)
13345 (org-remove-timestamp-with-keyword type)))
13347 (let ((n (string-to-number (match-string 2 ts)))
13348 (what (match-string 3 ts)))
13349 (when (equal what "w") (setq n (* n 7) what "d"))
13350 (when (and (equal what "h")
13351 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13352 ts)))
13353 (user-error
13354 "Cannot repeat in Repeat in %d hour(s) because no hour \
13355 has been set"
13357 ;; Preparation, see if we need to modify the start
13358 ;; date for the change.
13359 (when (match-end 1)
13360 (let ((time (save-match-data (org-time-string-to-time ts))))
13361 (cond
13362 ((equal (match-string 1 ts) ".")
13363 ;; Shift starting date to today
13364 (org-timestamp-change
13365 (- (org-today) (time-to-days time))
13366 'day))
13367 ((equal (match-string 1 ts) "+")
13368 (let ((nshiftmax 10)
13369 (nshift 0))
13370 (while (or (= nshift 0)
13371 (not (time-less-p (current-time) time)))
13372 (when (= (cl-incf nshift) nshiftmax)
13373 (or (y-or-n-p
13374 (format "%d repeater intervals were not \
13375 enough to shift date past today. Continue? "
13376 nshift))
13377 (user-error "Abort")))
13378 (org-timestamp-change n (cdr (assoc what whata)))
13379 (org-at-timestamp-p t)
13380 (setq ts (match-string 1))
13381 (setq time
13382 (save-match-data
13383 (org-time-string-to-time ts)))))
13384 (org-timestamp-change (- n) (cdr (assoc what whata)))
13385 ;; Rematch, so that we have everything in
13386 ;; place for the real shift.
13387 (org-at-timestamp-p t)
13388 (setq ts (match-string 1))
13389 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13390 ts)))))
13391 (save-excursion
13392 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13393 (setq msg
13394 (concat
13395 msg type " " org-last-changed-timestamp " ")))))))))
13396 (setq org-log-post-message msg)
13397 (message "%s" msg))))
13399 (defun org-show-todo-tree (arg)
13400 "Make a compact tree which shows all headlines marked with TODO.
13401 The tree will show the lines where the regexp matches, and all higher
13402 headlines above the match.
13403 With a \\[universal-argument] prefix, prompt for a regexp to match.
13404 With a numeric prefix N, construct a sparse tree for the Nth element
13405 of `org-todo-keywords-1'."
13406 (interactive "P")
13407 (let ((case-fold-search nil)
13408 (kwd-re
13409 (cond ((null arg) org-not-done-regexp)
13410 ((equal arg '(4))
13411 (let ((kwd
13412 (completing-read "Keyword (or KWD1|KWD2|...): "
13413 (mapcar #'list org-todo-keywords-1))))
13414 (concat "\\("
13415 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13416 "\\)\\>")))
13417 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13418 (regexp-quote (nth (1- (prefix-numeric-value arg))
13419 org-todo-keywords-1)))
13420 (t (user-error "Invalid prefix argument: %s" arg)))))
13421 (message "%d TODO entries found"
13422 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13424 (defun org-deadline (arg &optional time)
13425 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13426 With one universal prefix argument, remove any deadline from the item.
13427 With two universal prefix arguments, prompt for a warning delay.
13428 With argument TIME, set the deadline at the corresponding date. TIME
13429 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13430 (interactive "P")
13431 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13432 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13433 'region-start-level 'region))
13434 org-loop-over-headlines-in-active-region)
13435 (org-map-entries
13436 `(org-deadline ',arg ,time)
13437 org-loop-over-headlines-in-active-region
13438 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13439 (let* ((old-date (org-entry-get nil "DEADLINE"))
13440 (old-date-time (when old-date (org-time-string-to-time old-date)))
13441 (repeater (and old-date
13442 (string-match
13443 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13444 old-date)
13445 (match-string 1 old-date))))
13446 (cond
13447 ((equal arg '(4))
13448 (when (and old-date org-log-redeadline)
13449 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13450 (org-remove-timestamp-with-keyword org-deadline-string)
13451 (message "Item no longer has a deadline."))
13452 ((equal arg '(16))
13453 (save-excursion
13454 (org-back-to-heading t)
13455 (if (re-search-forward
13456 org-deadline-time-regexp
13457 (save-excursion (outline-next-heading) (point)) t)
13458 (let* ((rpl0 (match-string 1))
13459 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13460 (replace-match
13461 (concat org-deadline-string
13462 " <" rpl
13463 (format " -%dd"
13464 (abs
13465 (- (time-to-days
13466 (save-match-data
13467 (org-read-date nil t nil "Warn starting from" old-date-time)))
13468 (time-to-days old-date-time))))
13469 ">") t t))
13470 (user-error "No deadline information to update"))))
13472 (org-add-planning-info 'deadline time 'closed)
13473 (when (and old-date
13474 org-log-redeadline
13475 (not (equal old-date org-last-inserted-timestamp)))
13476 (org-add-log-setup
13477 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13478 (when repeater
13479 (save-excursion
13480 (org-back-to-heading t)
13481 (when (re-search-forward (concat org-deadline-string " "
13482 org-last-inserted-timestamp)
13483 (save-excursion
13484 (outline-next-heading) (point)) t)
13485 (goto-char (1- (match-end 0)))
13486 (insert " " repeater)
13487 (setq org-last-inserted-timestamp
13488 (concat (substring org-last-inserted-timestamp 0 -1)
13489 " " repeater
13490 (substring org-last-inserted-timestamp -1))))))
13491 (message "Deadline on %s" org-last-inserted-timestamp))))))
13493 (defun org-schedule (arg &optional time)
13494 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13495 With one universal prefix argument, remove any scheduling date from the item.
13496 With two universal prefix arguments, prompt for a delay cookie.
13497 With argument TIME, scheduled at the corresponding date. TIME can
13498 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13499 (interactive "P")
13500 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13501 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13502 'region-start-level 'region))
13503 org-loop-over-headlines-in-active-region)
13504 (org-map-entries
13505 `(org-schedule ',arg ,time)
13506 org-loop-over-headlines-in-active-region
13507 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13508 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13509 (old-date-time (when old-date (org-time-string-to-time old-date)))
13510 (repeater (and old-date
13511 (string-match
13512 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13513 old-date)
13514 (match-string 1 old-date))))
13515 (cond
13516 ((equal arg '(4))
13517 (progn
13518 (when (and old-date org-log-reschedule)
13519 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13520 (org-remove-timestamp-with-keyword org-scheduled-string)
13521 (message "Item is no longer scheduled.")))
13522 ((equal arg '(16))
13523 (save-excursion
13524 (org-back-to-heading t)
13525 (if (re-search-forward
13526 org-scheduled-time-regexp
13527 (save-excursion (outline-next-heading) (point)) t)
13528 (let* ((rpl0 (match-string 1))
13529 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13530 (replace-match
13531 (concat org-scheduled-string
13532 " <" rpl
13533 (format " -%dd"
13534 (abs
13535 (- (time-to-days
13536 (save-match-data
13537 (org-read-date nil t nil "Delay until" old-date-time)))
13538 (time-to-days old-date-time))))
13539 ">") t t))
13540 (user-error "No scheduled information to update"))))
13542 (org-add-planning-info 'scheduled time 'closed)
13543 (when (and old-date
13544 org-log-reschedule
13545 (not (equal old-date org-last-inserted-timestamp)))
13546 (org-add-log-setup
13547 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13548 (when repeater
13549 (save-excursion
13550 (org-back-to-heading t)
13551 (when (re-search-forward (concat org-scheduled-string " "
13552 org-last-inserted-timestamp)
13553 (save-excursion
13554 (outline-next-heading) (point)) t)
13555 (goto-char (1- (match-end 0)))
13556 (insert " " repeater)
13557 (setq org-last-inserted-timestamp
13558 (concat (substring org-last-inserted-timestamp 0 -1)
13559 " " repeater
13560 (substring org-last-inserted-timestamp -1))))))
13561 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13563 (defun org-get-scheduled-time (pom &optional inherit)
13564 "Get the scheduled time as a time tuple, of a format suitable
13565 for calling org-schedule with, or if there is no scheduling,
13566 returns nil."
13567 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13568 (when time
13569 (apply 'encode-time (org-parse-time-string time)))))
13571 (defun org-get-deadline-time (pom &optional inherit)
13572 "Get the deadline as a time tuple, of a format suitable for
13573 calling org-deadline with, or if there is no scheduling, returns
13574 nil."
13575 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13576 (when time
13577 (apply 'encode-time (org-parse-time-string time)))))
13579 (defun org-remove-timestamp-with-keyword (keyword)
13580 "Remove all time stamps with KEYWORD in the current entry."
13581 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13582 beg)
13583 (save-excursion
13584 (org-back-to-heading t)
13585 (setq beg (point))
13586 (outline-next-heading)
13587 (while (re-search-backward re beg t)
13588 (replace-match "")
13589 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13590 (equal (char-before) ?\ ))
13591 (backward-delete-char 1)
13592 (when (string-match "^[ \t]*$" (buffer-substring
13593 (point-at-bol) (point-at-eol)))
13594 (delete-region (point-at-bol)
13595 (min (point-max) (1+ (point-at-eol))))))))))
13597 (defvar org-time-was-given) ; dynamically scoped parameter
13598 (defvar org-end-time-was-given) ; dynamically scoped parameter
13600 (defun org-at-planning-p ()
13601 "Non-nil when point is on a planning info line."
13602 ;; This is as accurate and faster than `org-element-at-point' since
13603 ;; planning info location is fixed in the section.
13604 (org-with-wide-buffer
13605 (beginning-of-line)
13606 (and (looking-at-p org-planning-line-re)
13607 (eq (point)
13608 (ignore-errors
13609 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13610 (org-back-to-heading t)
13611 (org-with-limited-levels (org-back-to-heading t)))
13612 (line-beginning-position 2))))))
13614 (defun org-add-planning-info (what &optional time &rest remove)
13615 "Insert new timestamp with keyword in the planning line.
13616 WHAT indicates what kind of time stamp to add. It is a symbol
13617 among `closed', `deadline', `scheduled' and nil. TIME indicates
13618 the time to use. If none is given, the user is prompted for
13619 a date. REMOVE indicates what kind of entries to remove. An old
13620 WHAT entry will also be removed."
13621 (let (org-time-was-given org-end-time-was-given default-time default-input)
13622 (catch 'exit
13623 (when (and (memq what '(scheduled deadline))
13624 (or (not time)
13625 (and (stringp time)
13626 (string-match "^[-+]+[0-9]" time))))
13627 ;; Try to get a default date/time from existing timestamp
13628 (save-excursion
13629 (org-back-to-heading t)
13630 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13631 (when (re-search-forward (if (eq what 'scheduled)
13632 org-scheduled-time-regexp
13633 org-deadline-time-regexp)
13634 end t)
13635 (setq ts (match-string 1)
13636 default-time (apply 'encode-time (org-parse-time-string ts))
13637 default-input (and ts (org-get-compact-tod ts)))))))
13638 (when what
13639 (setq time
13640 (if (stringp time)
13641 ;; This is a string (relative or absolute), set
13642 ;; proper date.
13643 (apply #'encode-time
13644 (org-read-date-analyze
13645 time default-time (decode-time default-time)))
13646 ;; If necessary, get the time from the user
13647 (or time (org-read-date nil 'to-time nil nil
13648 default-time default-input)))))
13650 (org-with-wide-buffer
13651 (org-back-to-heading t)
13652 (forward-line)
13653 (unless (bolp) (insert "\n"))
13654 (cond ((looking-at-p org-planning-line-re)
13655 ;; Move to current indentation.
13656 (skip-chars-forward " \t")
13657 ;; Check if we have to remove something.
13658 (dolist (type (if what (cons what remove) remove))
13659 (save-excursion
13660 (when (re-search-forward
13661 (cl-case type
13662 (closed org-closed-time-regexp)
13663 (deadline org-deadline-time-regexp)
13664 (scheduled org-scheduled-time-regexp)
13665 (otherwise
13666 (error "Invalid planning type: %s" type)))
13667 (line-end-position) t)
13668 ;; Delete until next keyword or end of line.
13669 (delete-region
13670 (match-beginning 0)
13671 (if (re-search-forward org-keyword-time-not-clock-regexp
13672 (line-end-position)
13674 (match-beginning 0)
13675 (line-end-position))))))
13676 ;; If there is nothing more to add and no more keyword
13677 ;; is left, remove the line completely.
13678 (if (and (looking-at-p "[ \t]*$") (not what))
13679 (delete-region (line-beginning-position)
13680 (line-beginning-position 2))
13681 ;; If we removed last keyword, do not leave trailing
13682 ;; white space at the end of line.
13683 (let ((p (point)))
13684 (save-excursion
13685 (end-of-line)
13686 (unless (= (skip-chars-backward " \t" p) 0)
13687 (delete-region (point) (line-end-position)))))))
13688 ((not what) (throw 'exit nil)) ; Nothing to do.
13689 (t (insert-before-markers "\n")
13690 (backward-char 1)
13691 (when org-adapt-indentation
13692 (indent-to-column (1+ (org-outline-level))))))
13693 (when what
13694 ;; Insert planning keyword.
13695 (insert (cl-case what
13696 (closed org-closed-string)
13697 (deadline org-deadline-string)
13698 (scheduled org-scheduled-string)
13699 (otherwise (error "Invalid planning type: %s" what)))
13700 " ")
13701 ;; Insert associated timestamp.
13702 (let ((ts (org-insert-time-stamp
13703 time
13704 (or org-time-was-given
13705 (and (eq what 'closed) org-log-done-with-time))
13706 (eq what 'closed)
13707 nil nil (list org-end-time-was-given))))
13708 (unless (eolp) (insert " "))
13709 ts))))))
13711 (defvar org-log-note-marker (make-marker)
13712 "Marker pointing at the entry where the note is to be inserted.")
13713 (defvar org-log-note-purpose nil)
13714 (defvar org-log-note-state nil)
13715 (defvar org-log-note-previous-state nil)
13716 (defvar org-log-note-extra nil)
13717 (defvar org-log-note-window-configuration nil)
13718 (defvar org-log-note-return-to (make-marker))
13719 (defvar org-log-note-effective-time nil
13720 "Remembered current time so that dynamically scoped
13721 `org-extend-today-until' affects timestamps in state change log")
13723 (defvar org-log-post-message nil
13724 "Message to be displayed after a log note has been stored.
13725 The auto-repeater uses this.")
13727 (defun org-add-note ()
13728 "Add a note to the current entry.
13729 This is done in the same way as adding a state change note."
13730 (interactive)
13731 (org-add-log-setup 'note))
13733 (defun org-log-beginning (&optional create)
13734 "Return expected start of log notes in current entry.
13735 When optional argument CREATE is non-nil, the function creates
13736 a drawer to store notes, if necessary. Returned position ignores
13737 narrowing."
13738 (org-with-wide-buffer
13739 (let ((drawer (org-log-into-drawer)))
13740 (cond
13741 (drawer
13742 (org-end-of-meta-data)
13743 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13744 (end (if (org-at-heading-p) (point)
13745 (save-excursion (outline-next-heading) (point))))
13746 (case-fold-search t))
13747 (catch 'exit
13748 ;; Try to find existing drawer.
13749 (while (re-search-forward regexp end t)
13750 (let ((element (org-element-at-point)))
13751 (when (eq (org-element-type element) 'drawer)
13752 (let ((cend (org-element-property :contents-end element)))
13753 (when (and (not org-log-states-order-reversed) cend)
13754 (goto-char cend)))
13755 (throw 'exit nil))))
13756 ;; No drawer found. Create one, if permitted.
13757 (when create
13758 (unless (bolp) (insert "\n"))
13759 (let ((beg (point)))
13760 (insert ":" drawer ":\n:END:\n")
13761 (org-indent-region beg (point)))
13762 (end-of-line -1)))))
13764 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13765 (skip-chars-forward " \t\n")
13766 (beginning-of-line)
13767 (unless org-log-states-order-reversed
13768 (org-skip-over-state-notes)
13769 (skip-chars-backward " \t\n")
13770 (forward-line)))))
13771 (if (bolp) (point) (line-beginning-position 2))))
13773 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13774 "Set up the post command hook to take a note.
13775 If this is about to TODO state change, the new state is expected in STATE.
13776 HOW is an indicator what kind of note should be created.
13777 EXTRA is additional text that will be inserted into the notes buffer."
13778 (move-marker org-log-note-marker (point))
13779 (setq org-log-note-purpose purpose
13780 org-log-note-state state
13781 org-log-note-previous-state prev-state
13782 org-log-note-how how
13783 org-log-note-extra extra
13784 org-log-note-effective-time (org-current-effective-time))
13785 (add-hook 'post-command-hook 'org-add-log-note 'append))
13787 (defun org-skip-over-state-notes ()
13788 "Skip past the list of State notes in an entry."
13789 (when (ignore-errors (goto-char (org-in-item-p)))
13790 (let* ((struct (org-list-struct))
13791 (prevs (org-list-prevs-alist struct))
13792 (regexp
13793 (concat "[ \t]*- +"
13794 (replace-regexp-in-string
13795 " +" " +"
13796 (org-replace-escapes
13797 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13798 `(("%d" . ,org-ts-regexp-inactive)
13799 ("%D" . ,org-ts-regexp)
13800 ("%s" . "\"\\S-+\"")
13801 ("%S" . "\"\\S-+\"")
13802 ("%t" . ,org-ts-regexp-inactive)
13803 ("%T" . ,org-ts-regexp)
13804 ("%u" . ".*?")
13805 ("%U" . ".*?")))))))
13806 (while (looking-at-p regexp)
13807 (goto-char (or (org-list-get-next-item (point) struct prevs)
13808 (org-list-get-item-end (point) struct)))))))
13810 (defun org-add-log-note (&optional _purpose)
13811 "Pop up a window for taking a note, and add this note later."
13812 (remove-hook 'post-command-hook 'org-add-log-note)
13813 (setq org-log-note-window-configuration (current-window-configuration))
13814 (delete-other-windows)
13815 (move-marker org-log-note-return-to (point))
13816 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13817 (goto-char org-log-note-marker)
13818 (org-switch-to-buffer-other-window "*Org Note*")
13819 (erase-buffer)
13820 (if (memq org-log-note-how '(time state))
13821 (let (current-prefix-arg) (org-store-log-note))
13822 (let ((org-inhibit-startup t)) (org-mode))
13823 (insert (format "# Insert note for %s.
13824 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13825 (cond
13826 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13827 ((eq org-log-note-purpose 'done) "closed todo item")
13828 ((eq org-log-note-purpose 'state)
13829 (format "state change from \"%s\" to \"%s\""
13830 (or org-log-note-previous-state "")
13831 (or org-log-note-state "")))
13832 ((eq org-log-note-purpose 'reschedule)
13833 "rescheduling")
13834 ((eq org-log-note-purpose 'delschedule)
13835 "no longer scheduled")
13836 ((eq org-log-note-purpose 'redeadline)
13837 "changing deadline")
13838 ((eq org-log-note-purpose 'deldeadline)
13839 "removing deadline")
13840 ((eq org-log-note-purpose 'refile)
13841 "refiling")
13842 ((eq org-log-note-purpose 'note)
13843 "this entry")
13844 (t (error "This should not happen")))))
13845 (when org-log-note-extra (insert org-log-note-extra))
13846 (setq-local org-finish-function 'org-store-log-note)
13847 (run-hooks 'org-log-buffer-setup-hook)))
13849 (defvar org-note-abort nil) ; dynamically scoped
13850 (defun org-store-log-note ()
13851 "Finish taking a log note, and insert it to where it belongs."
13852 (let ((txt (prog1 (buffer-string)
13853 (kill-buffer)))
13854 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13855 lines)
13856 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13857 (setq txt (replace-match "" t t txt)))
13858 (when (string-match "\\s-+\\'" txt)
13859 (setq txt (replace-match "" t t txt)))
13860 (setq lines (org-split-string txt "\n"))
13861 (when (org-string-nw-p note)
13862 (setq note
13863 (org-replace-escapes
13864 note
13865 (list (cons "%u" (user-login-name))
13866 (cons "%U" user-full-name)
13867 (cons "%t" (format-time-string
13868 (org-time-stamp-format 'long 'inactive)
13869 org-log-note-effective-time))
13870 (cons "%T" (format-time-string
13871 (org-time-stamp-format 'long nil)
13872 org-log-note-effective-time))
13873 (cons "%d" (format-time-string
13874 (org-time-stamp-format nil 'inactive)
13875 org-log-note-effective-time))
13876 (cons "%D" (format-time-string
13877 (org-time-stamp-format nil nil)
13878 org-log-note-effective-time))
13879 (cons "%s" (cond
13880 ((not org-log-note-state) "")
13881 ((string-match-p org-ts-regexp
13882 org-log-note-state)
13883 (format "\"[%s]\""
13884 (substring org-log-note-state 1 -1)))
13885 (t (format "\"%s\"" org-log-note-state))))
13886 (cons "%S"
13887 (cond
13888 ((not org-log-note-previous-state) "")
13889 ((string-match-p org-ts-regexp
13890 org-log-note-previous-state)
13891 (format "\"[%s]\""
13892 (substring
13893 org-log-note-previous-state 1 -1)))
13894 (t (format "\"%s\""
13895 org-log-note-previous-state)))))))
13896 (when lines (setq note (concat note " \\\\")))
13897 (push note lines))
13898 (when (and lines (not (or current-prefix-arg org-note-abort)))
13899 (with-current-buffer (marker-buffer org-log-note-marker)
13900 (org-with-wide-buffer
13901 ;; Find location for the new note.
13902 (goto-char org-log-note-marker)
13903 (set-marker org-log-note-marker nil)
13904 (goto-char (org-log-beginning t))
13905 ;; Make sure point is at the beginning of an empty line.
13906 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13907 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13908 ;; In an existing list, add a new item at the top level.
13909 ;; Otherwise, indent line like a regular one.
13910 (let ((itemp (org-in-item-p)))
13911 (if itemp
13912 (indent-line-to
13913 (let ((struct (save-excursion
13914 (goto-char itemp) (org-list-struct))))
13915 (org-list-get-ind (org-list-get-top-point struct) struct)))
13916 (org-indent-line)))
13917 (insert (org-list-bullet-string "-") (pop lines))
13918 (let ((ind (org-list-item-body-column (line-beginning-position))))
13919 (dolist (line lines)
13920 (insert "\n")
13921 (indent-line-to ind)
13922 (insert line)))
13923 (message "Note stored")
13924 (org-back-to-heading t)
13925 (org-cycle-hide-drawers 'children))
13926 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13927 ;; from within `org-add-log-note' because `buffer-undo-list'
13928 ;; is then modified outside of `org-with-remote-undo'.
13929 (when (eq this-command 'org-agenda-todo)
13930 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13931 ;; Don't add undo information when called from `org-agenda-todo'.
13932 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13933 (set-window-configuration org-log-note-window-configuration)
13934 (with-current-buffer (marker-buffer org-log-note-return-to)
13935 (goto-char org-log-note-return-to))
13936 (move-marker org-log-note-return-to nil)
13937 (when org-log-post-message (message "%s" org-log-post-message))))
13939 (defun org-remove-empty-drawer-at (pos)
13940 "Remove an empty drawer at position POS.
13941 POS may also be a marker."
13942 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13943 (org-with-wide-buffer
13944 (goto-char pos)
13945 (let ((drawer (org-element-at-point)))
13946 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13947 (not (org-element-property :contents-begin drawer)))
13948 (delete-region (org-element-property :begin drawer)
13949 (progn (goto-char (org-element-property :end drawer))
13950 (skip-chars-backward " \r\t\n")
13951 (forward-line)
13952 (point))))))))
13954 (defvar org-ts-type nil)
13955 (defun org-sparse-tree (&optional arg type)
13956 "Create a sparse tree, prompt for the details.
13957 This command can create sparse trees. You first need to select the type
13958 of match used to create the tree:
13960 t Show all TODO entries.
13961 T Show entries with a specific TODO keyword.
13962 m Show entries selected by a tags/property match.
13963 p Enter a property name and its value (both with completion on existing
13964 names/values) and show entries with that property.
13965 r Show entries matching a regular expression (`/' can be used as well).
13966 b Show deadlines and scheduled items before a date.
13967 a Show deadlines and scheduled items after a date.
13968 d Show deadlines due within `org-deadline-warning-days'.
13969 D Show deadlines and scheduled items between a date range."
13970 (interactive "P")
13971 (setq type (or type org-sparse-tree-default-date-type))
13972 (setq org-ts-type type)
13973 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13974 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13975 \[c]ycle through date types: %s"
13976 (cl-case type
13977 (all "all timestamps")
13978 (scheduled "only scheduled")
13979 (deadline "only deadline")
13980 (active "only active timestamps")
13981 (inactive "only inactive timestamps")
13982 (closed "with a closed time-stamp")
13983 (otherwise "scheduled/deadline")))
13984 (let ((answer (read-char-exclusive)))
13985 (cl-case answer
13987 (org-sparse-tree
13989 (cadr
13990 (memq type '(nil all scheduled deadline active inactive closed)))))
13991 (?d (call-interactively 'org-check-deadlines))
13992 (?b (call-interactively 'org-check-before-date))
13993 (?a (call-interactively 'org-check-after-date))
13994 (?D (call-interactively 'org-check-dates-range))
13995 (?t (call-interactively 'org-show-todo-tree))
13996 (?T (org-show-todo-tree '(4)))
13997 (?m (call-interactively 'org-match-sparse-tree))
13998 ((?p ?P)
13999 (let* ((kwd (completing-read
14000 "Property: " (mapcar #'list (org-buffer-property-keys))))
14001 (value (completing-read
14002 "Value: " (mapcar #'list (org-property-values kwd)))))
14003 (unless (string-match "\\`{.*}\\'" value)
14004 (setq value (concat "\"" value "\"")))
14005 (org-match-sparse-tree arg (concat kwd "=" value))))
14006 ((?r ?R ?/) (call-interactively 'org-occur))
14007 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14009 (defvar-local org-occur-highlights nil
14010 "List of overlays used for occur matches.")
14011 (defvar-local org-occur-parameters nil
14012 "Parameters of the active org-occur calls.
14013 This is a list, each call to org-occur pushes as cons cell,
14014 containing the regular expression and the callback, onto the list.
14015 The list can contain several entries if `org-occur' has been called
14016 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14017 will only contain one set of parameters. When the highlights are
14018 removed (for example with `C-c C-c', or with the next edit (depending
14019 on `org-remove-highlights-with-change'), this variable is emptied
14020 as well.")
14022 (defun org-occur (regexp &optional keep-previous callback)
14023 "Make a compact tree which shows all matches of REGEXP.
14025 The tree will show the lines where the regexp matches, and any other context
14026 defined in `org-show-context-detail', which see.
14028 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14029 done by a previous call to `org-occur' will be kept, to allow stacking of
14030 calls to this command.
14032 Optional argument CALLBACK can be a function of no argument. In this case,
14033 it is called with point at the end of the match, match data being set
14034 accordingly. Current match is shown only if the return value is non-nil.
14035 The function must neither move point nor alter narrowing."
14036 (interactive "sRegexp: \nP")
14037 (when (equal regexp "")
14038 (user-error "Regexp cannot be empty"))
14039 (unless keep-previous
14040 (org-remove-occur-highlights nil nil t))
14041 (push (cons regexp callback) org-occur-parameters)
14042 (let ((cnt 0))
14043 (save-excursion
14044 (goto-char (point-min))
14045 (when (or (not keep-previous) ; do not want to keep
14046 (not org-occur-highlights)) ; no previous matches
14047 ;; hide everything
14048 (org-overview))
14049 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14050 (isearch-no-upper-case-p regexp t)
14051 org-occur-case-fold-search)))
14052 (while (re-search-forward regexp nil t)
14053 (when (or (not callback)
14054 (save-match-data (funcall callback)))
14055 (setq cnt (1+ cnt))
14056 (when org-highlight-sparse-tree-matches
14057 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14058 (org-show-context 'occur-tree)))))
14059 (when org-remove-highlights-with-change
14060 (add-hook 'before-change-functions 'org-remove-occur-highlights
14061 nil 'local))
14062 (unless org-sparse-tree-open-archived-trees
14063 (org-hide-archived-subtrees (point-min) (point-max)))
14064 (run-hooks 'org-occur-hook)
14065 (when (called-interactively-p 'interactive)
14066 (message "%d match(es) for regexp %s" cnt regexp))
14067 cnt))
14069 (defun org-occur-next-match (&optional n _reset)
14070 "Function for `next-error-function' to find sparse tree matches.
14071 N is the number of matches to move, when negative move backwards.
14072 This function always goes back to the starting point when no
14073 match is found."
14074 (let* ((limit (if (< n 0) (point-min) (point-max)))
14075 (search-func (if (< n 0)
14076 'previous-single-char-property-change
14077 'next-single-char-property-change))
14078 (n (abs n))
14079 (pos (point))
14081 (catch 'exit
14082 (while (setq p1 (funcall search-func (point) 'org-type))
14083 (when (equal p1 limit)
14084 (goto-char pos)
14085 (user-error "No more matches"))
14086 (when (equal (get-char-property p1 'org-type) 'org-occur)
14087 (setq n (1- n))
14088 (when (= n 0)
14089 (goto-char p1)
14090 (throw 'exit (point))))
14091 (goto-char p1))
14092 (goto-char p1)
14093 (user-error "No more matches"))))
14095 (defun org-show-context (&optional key)
14096 "Make sure point and context are visible.
14097 Optional argument KEY, when non-nil, is a symbol. See
14098 `org-show-context-detail' for allowed values and how much is to
14099 be shown."
14100 (org-show-set-visibility
14101 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14102 ((cdr (assq key org-show-context-detail)))
14103 (t (cdr (assq 'default org-show-context-detail))))))
14105 (defun org-show-set-visibility (detail)
14106 "Set visibility around point according to DETAIL.
14107 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14108 `tree', `canonical' or t. See `org-show-context-detail' for more
14109 information."
14110 ;; Show current heading and possibly its entry, following headline
14111 ;; or all children.
14112 (if (and (org-at-heading-p) (not (eq detail 'local)))
14113 (org-flag-heading nil)
14114 (org-show-entry)
14115 ;; If point is hidden within a drawer or a block, make sure to
14116 ;; expose it.
14117 (dolist (o (overlays-at (point)))
14118 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14119 (delete-overlay o)))
14120 (unless (org-before-first-heading-p)
14121 (org-with-limited-levels
14122 (cl-case detail
14123 ((tree canonical t) (org-show-children))
14124 ((nil minimal ancestors))
14125 (t (save-excursion
14126 (outline-next-heading)
14127 (org-flag-heading nil)))))))
14128 ;; Show all siblings.
14129 (when (eq detail 'lineage) (org-show-siblings))
14130 ;; Show ancestors, possibly with their children.
14131 (when (memq detail '(ancestors lineage tree canonical t))
14132 (save-excursion
14133 (while (org-up-heading-safe)
14134 (org-flag-heading nil)
14135 (when (memq detail '(canonical t)) (org-show-entry))
14136 (when (memq detail '(tree canonical t)) (org-show-children))))))
14138 (defvar org-reveal-start-hook nil
14139 "Hook run before revealing a location.")
14141 (defun org-reveal (&optional siblings)
14142 "Show current entry, hierarchy above it, and the following headline.
14144 This can be used to show a consistent set of context around
14145 locations exposed with `org-show-context'.
14147 With optional argument SIBLINGS, on each level of the hierarchy all
14148 siblings are shown. This repairs the tree structure to what it would
14149 look like when opened with hierarchical calls to `org-cycle'.
14151 With double optional argument \\[universal-argument] \\[universal-argument], \
14152 go to the parent and show the
14153 entire tree."
14154 (interactive "P")
14155 (run-hooks 'org-reveal-start-hook)
14156 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14157 ((equal siblings '(16))
14158 (save-excursion
14159 (when (org-up-heading-safe)
14160 (org-show-subtree)
14161 (run-hook-with-args 'org-cycle-hook 'subtree))))
14162 (t (org-show-set-visibility 'lineage))))
14164 (defun org-highlight-new-match (beg end)
14165 "Highlight from BEG to END and mark the highlight is an occur headline."
14166 (let ((ov (make-overlay beg end)))
14167 (overlay-put ov 'face 'secondary-selection)
14168 (overlay-put ov 'org-type 'org-occur)
14169 (push ov org-occur-highlights)))
14171 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14172 "Remove the occur highlights from the buffer.
14173 BEG and END are ignored. If NOREMOVE is nil, remove this function
14174 from the `before-change-functions' in the current buffer."
14175 (interactive)
14176 (unless org-inhibit-highlight-removal
14177 (mapc #'delete-overlay org-occur-highlights)
14178 (setq org-occur-highlights nil)
14179 (setq org-occur-parameters nil)
14180 (unless noremove
14181 (remove-hook 'before-change-functions
14182 'org-remove-occur-highlights 'local))))
14184 ;;;; Priorities
14186 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14187 "Regular expression matching the priority indicator.")
14189 (defvar org-remove-priority-next-time nil)
14191 (defun org-priority-up ()
14192 "Increase the priority of the current item."
14193 (interactive)
14194 (org-priority 'up))
14196 (defun org-priority-down ()
14197 "Decrease the priority of the current item."
14198 (interactive)
14199 (org-priority 'down))
14201 (defun org-priority (&optional action _show)
14202 "Change the priority of an item.
14203 ACTION can be `set', `up', `down', or a character."
14204 (interactive "P")
14205 (if (equal action '(4))
14206 (org-show-priority)
14207 (unless org-enable-priority-commands
14208 (user-error "Priority commands are disabled"))
14209 (setq action (or action 'set))
14210 (let (current new news have remove)
14211 (save-excursion
14212 (org-back-to-heading t)
14213 (when (looking-at org-priority-regexp)
14214 (setq current (string-to-char (match-string 2))
14215 have t))
14216 (cond
14217 ((eq action 'remove)
14218 (setq remove t new ?\ ))
14219 ((or (eq action 'set)
14220 (integerp action))
14221 (if (not (eq action 'set))
14222 (setq new action)
14223 (message "Priority %c-%c, SPC to remove: "
14224 org-highest-priority org-lowest-priority)
14225 (save-match-data
14226 (setq new (read-char-exclusive))))
14227 (when (and (= (upcase org-highest-priority) org-highest-priority)
14228 (= (upcase org-lowest-priority) org-lowest-priority))
14229 (setq new (upcase new)))
14230 (cond ((equal new ?\ ) (setq remove t))
14231 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14232 (user-error "Priority must be between `%c' and `%c'"
14233 org-highest-priority org-lowest-priority))))
14234 ((eq action 'up)
14235 (setq new (if have
14236 (1- current) ; normal cycling
14237 ;; last priority was empty
14238 (if (eq last-command this-command)
14239 org-lowest-priority ; wrap around empty to lowest
14240 ;; default
14241 (if org-priority-start-cycle-with-default
14242 org-default-priority
14243 (1- org-default-priority))))))
14244 ((eq action 'down)
14245 (setq new (if have
14246 (1+ current) ; normal cycling
14247 ;; last priority was empty
14248 (if (eq last-command this-command)
14249 org-highest-priority ; wrap around empty to highest
14250 ;; default
14251 (if org-priority-start-cycle-with-default
14252 org-default-priority
14253 (1+ org-default-priority))))))
14254 (t (user-error "Invalid action")))
14255 (when (or (< (upcase new) org-highest-priority)
14256 (> (upcase new) org-lowest-priority))
14257 (if (and (memq action '(up down))
14258 (not have) (not (eq last-command this-command)))
14259 ;; `new' is from default priority
14260 (error
14261 "The default can not be set, see `org-default-priority' why")
14262 ;; normal cycling: `new' is beyond highest/lowest priority
14263 ;; and is wrapped around to the empty priority
14264 (setq remove t)))
14265 (setq news (format "%c" new))
14266 (if have
14267 (if remove
14268 (replace-match "" t t nil 1)
14269 (replace-match news t t nil 2))
14270 (if remove
14271 (user-error "No priority cookie found in line")
14272 (let ((case-fold-search nil))
14273 (looking-at org-todo-line-regexp))
14274 (if (match-end 2)
14275 (progn
14276 (goto-char (match-end 2))
14277 (insert " [#" news "]"))
14278 (goto-char (match-beginning 3))
14279 (insert "[#" news "] "))))
14280 (org-set-tags nil 'align))
14281 (if remove
14282 (message "Priority removed")
14283 (message "Priority of current item set to %s" news)))))
14285 (defun org-show-priority ()
14286 "Show the priority of the current item.
14287 This priority is composed of the main priority given with the [#A] cookies,
14288 and by additional input from the age of a schedules or deadline entry."
14289 (interactive)
14290 (let ((pri (if (eq major-mode 'org-agenda-mode)
14291 (org-get-at-bol 'priority)
14292 (save-excursion
14293 (save-match-data
14294 (beginning-of-line)
14295 (and (looking-at org-heading-regexp)
14296 (org-get-priority (match-string 0))))))))
14297 (message "Priority is %d" (if pri pri -1000))))
14299 (defun org-get-priority (s)
14300 "Find priority cookie and return priority."
14301 (save-match-data
14302 (if (functionp org-get-priority-function)
14303 (funcall org-get-priority-function)
14304 (if (not (string-match org-priority-regexp s))
14305 (* 1000 (- org-lowest-priority org-default-priority))
14306 (* 1000 (- org-lowest-priority
14307 (string-to-char (match-string 2 s))))))))
14309 ;;;; Tags
14311 (defvar org-agenda-archives-mode)
14312 (defvar org-map-continue-from nil
14313 "Position from where mapping should continue.
14314 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14316 (defvar org-scanner-tags nil
14317 "The current tag list while the tags scanner is running.")
14319 (defvar org-trust-scanner-tags nil
14320 "Should `org-get-tags-at' use the tags for the scanner.
14321 This is for internal dynamical scoping only.
14322 When this is non-nil, the function `org-get-tags-at' will return the value
14323 of `org-scanner-tags' instead of building the list by itself. This
14324 can lead to large speed-ups when the tags scanner is used in a file with
14325 many entries, and when the list of tags is retrieved, for example to
14326 obtain a list of properties. Building the tags list for each entry in such
14327 a file becomes an N^2 operation - but with this variable set, it scales
14328 as N.")
14330 (defvar org--matcher-tags-todo-only nil)
14332 (defun org-scan-tags (action matcher todo-only &optional start-level)
14333 "Scan headline tags with inheritance and produce output ACTION.
14335 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14336 or `agenda' to produce an entry list for an agenda view. It can also be
14337 a Lisp form or a function that should be called at each matched headline, in
14338 this case the return value is a list of all return values from these calls.
14340 MATCHER is a function accepting three arguments, returning
14341 a non-nil value whenever a given set of tags qualifies a headline
14342 for inclusion. See `org-make-tags-matcher' for more information.
14343 As a special case, it can also be set to t (respectively nil) in
14344 order to match all (respectively none) headline.
14346 When TODO-ONLY is non-nil, only lines with a not-done TODO
14347 keyword are included in the output.
14349 START-LEVEL can be a string with asterisks, reducing the scope to
14350 headlines matching this string."
14351 (require 'org-agenda)
14352 (let* ((re (concat "^"
14353 (if start-level
14354 ;; Get the correct level to match
14355 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14356 org-outline-regexp)
14357 " *\\(\\<\\("
14358 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14359 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14360 (props (list 'face 'default
14361 'done-face 'org-agenda-done
14362 'undone-face 'default
14363 'mouse-face 'highlight
14364 'org-not-done-regexp org-not-done-regexp
14365 'org-todo-regexp org-todo-regexp
14366 'org-complex-heading-regexp org-complex-heading-regexp
14367 'help-echo
14368 (format "mouse-2 or RET jump to org file %s"
14369 (abbreviate-file-name
14370 (or (buffer-file-name (buffer-base-buffer))
14371 (buffer-name (buffer-base-buffer)))))))
14372 (org-map-continue-from nil)
14373 lspos tags tags-list
14374 (tags-alist (list (cons 0 org-file-tags)))
14375 (llast 0) rtn rtn1 level category i txt
14376 todo marker entry priority
14377 ts-date ts-date-type ts-date-pair)
14378 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14379 (setq action (list 'lambda nil action)))
14380 (save-excursion
14381 (goto-char (point-min))
14382 (when (eq action 'sparse-tree)
14383 (org-overview)
14384 (org-remove-occur-highlights))
14385 (while (let (case-fold-search)
14386 (re-search-forward re nil t))
14387 (setq org-map-continue-from nil)
14388 (catch :skip
14389 (setq todo
14390 ;; TODO: is the 1-2 difference a bug?
14391 (when (match-end 1) (match-string-no-properties 2))
14392 tags (when (match-end 4) (match-string-no-properties 4)))
14393 (goto-char (setq lspos (match-beginning 0)))
14394 (setq level (org-reduced-level (org-outline-level))
14395 category (org-get-category))
14396 (when (eq action 'agenda)
14397 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14398 ts-date (car ts-date-pair)
14399 ts-date-type (cdr ts-date-pair)))
14400 (setq i llast llast level)
14401 ;; remove tag lists from same and sublevels
14402 (while (>= i level)
14403 (when (setq entry (assoc i tags-alist))
14404 (setq tags-alist (delete entry tags-alist)))
14405 (setq i (1- i)))
14406 ;; add the next tags
14407 (when tags
14408 (setq tags (org-split-string tags ":")
14409 tags-alist
14410 (cons (cons level tags) tags-alist)))
14411 ;; compile tags for current headline
14412 (setq tags-list
14413 (if org-use-tag-inheritance
14414 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14415 tags)
14416 org-scanner-tags tags-list)
14417 (when org-use-tag-inheritance
14418 (setcdr (car tags-alist)
14419 (mapcar (lambda (x)
14420 (setq x (copy-sequence x))
14421 (org-add-prop-inherited x))
14422 (cdar tags-alist))))
14423 (when (and tags org-use-tag-inheritance
14424 (or (not (eq t org-use-tag-inheritance))
14425 org-tags-exclude-from-inheritance))
14426 ;; Selective inheritance, remove uninherited ones.
14427 (setcdr (car tags-alist)
14428 (org-remove-uninherited-tags (cdar tags-alist))))
14429 (when (and
14431 ;; eval matcher only when the todo condition is OK
14432 (and (or (not todo-only) (member todo org-not-done-keywords))
14433 (if (functionp matcher)
14434 (let ((case-fold-search t) (org-trust-scanner-tags t))
14435 (funcall matcher todo tags-list level))
14436 matcher))
14438 ;; Call the skipper, but return t if it does not
14439 ;; skip, so that the `and' form continues evaluating.
14440 (progn
14441 (unless (eq action 'sparse-tree) (org-agenda-skip))
14444 ;; Check if timestamps are deselecting this entry
14445 (or (not todo-only)
14446 (and (member todo org-not-done-keywords)
14447 (or (not org-agenda-tags-todo-honor-ignore-options)
14448 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14450 ;; select this headline
14451 (cond
14452 ((eq action 'sparse-tree)
14453 (and org-highlight-sparse-tree-matches
14454 (org-get-heading) (match-end 0)
14455 (org-highlight-new-match
14456 (match-beginning 1) (match-end 1)))
14457 (org-show-context 'tags-tree))
14458 ((eq action 'agenda)
14459 (setq txt (org-agenda-format-item
14461 (concat
14462 (if (eq org-tags-match-list-sublevels 'indented)
14463 (make-string (1- level) ?.) "")
14464 (org-get-heading))
14465 (make-string level ?\s)
14466 category
14467 tags-list)
14468 priority (org-get-priority txt))
14469 (goto-char lspos)
14470 (setq marker (org-agenda-new-marker))
14471 (org-add-props txt props
14472 'org-marker marker 'org-hd-marker marker 'org-category category
14473 'todo-state todo
14474 'ts-date ts-date
14475 'priority priority
14476 'type (concat "tagsmatch" ts-date-type))
14477 (push txt rtn))
14478 ((functionp action)
14479 (setq org-map-continue-from nil)
14480 (save-excursion
14481 (setq rtn1 (funcall action))
14482 (push rtn1 rtn)))
14483 (t (user-error "Invalid action")))
14485 ;; if we are to skip sublevels, jump to end of subtree
14486 (unless org-tags-match-list-sublevels
14487 (org-end-of-subtree t)
14488 (backward-char 1))))
14489 ;; Get the correct position from where to continue
14490 (if org-map-continue-from
14491 (goto-char org-map-continue-from)
14492 (and (= (point) lspos) (end-of-line 1)))))
14493 (when (and (eq action 'sparse-tree)
14494 (not org-sparse-tree-open-archived-trees))
14495 (org-hide-archived-subtrees (point-min) (point-max)))
14496 (nreverse rtn)))
14498 (defun org-remove-uninherited-tags (tags)
14499 "Remove all tags that are not inherited from the list TAGS."
14500 (cond
14501 ((eq org-use-tag-inheritance t)
14502 (if org-tags-exclude-from-inheritance
14503 (org-delete-all org-tags-exclude-from-inheritance tags)
14504 tags))
14505 ((not org-use-tag-inheritance) nil)
14506 ((stringp org-use-tag-inheritance)
14507 (delq nil (mapcar
14508 (lambda (x)
14509 (if (and (string-match org-use-tag-inheritance x)
14510 (not (member x org-tags-exclude-from-inheritance)))
14511 x nil))
14512 tags)))
14513 ((listp org-use-tag-inheritance)
14514 (delq nil (mapcar
14515 (lambda (x)
14516 (if (member x org-use-tag-inheritance) x nil))
14517 tags)))))
14519 (defun org-match-sparse-tree (&optional todo-only match)
14520 "Create a sparse tree according to tags string MATCH.
14521 MATCH can contain positive and negative selection of tags, like
14522 \"+WORK+URGENT-WITHBOSS\".
14523 If optional argument TODO-ONLY is non-nil, only select lines that are
14524 also TODO lines."
14525 (interactive "P")
14526 (org-agenda-prepare-buffers (list (current-buffer)))
14527 (let ((org--matcher-tags-todo-only todo-only))
14528 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14529 org--matcher-tags-todo-only)))
14531 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14533 (defvar org-cached-props nil)
14534 (defun org-cached-entry-get (pom property)
14535 (if (or (eq t org-use-property-inheritance)
14536 (and (stringp org-use-property-inheritance)
14537 (let ((case-fold-search t))
14538 (string-match-p org-use-property-inheritance property)))
14539 (and (listp org-use-property-inheritance)
14540 (member-ignore-case property org-use-property-inheritance)))
14541 ;; Caching is not possible, check it directly.
14542 (org-entry-get pom property 'inherit)
14543 ;; Get all properties, so we can do complicated checks easily.
14544 (cdr (assoc-string property
14545 (or org-cached-props
14546 (setq org-cached-props (org-entry-properties pom)))
14547 t))))
14549 (defun org-global-tags-completion-table (&optional files)
14550 "Return the list of all tags in all agenda buffer/files.
14551 Optional FILES argument is a list of files which can be used
14552 instead of the agenda files."
14553 (save-excursion
14554 (org-uniquify
14555 (delq nil
14556 (apply #'append
14557 (mapcar
14558 (lambda (file)
14559 (set-buffer (find-file-noselect file))
14560 (mapcar (lambda (x)
14561 (and (stringp (car-safe x))
14562 (list (car-safe x))))
14563 (or org-current-tag-alist (org-get-buffer-tags))))
14564 (if (car-safe files) files
14565 (org-agenda-files))))))))
14567 (defun org-make-tags-matcher (match)
14568 "Create the TAGS/TODO matcher form for the selection string MATCH.
14570 Returns a cons of the selection string MATCH and a function
14571 implementing the matcher.
14573 The matcher is to be called at an Org entry, with point on the
14574 headline, and returns non-nil if the entry matches the selection
14575 string MATCH. It must be called with three arguments: the TODO
14576 keyword at the entry (or nil if none), the list of all tags at
14577 the entry including inherited ones and the reduced level of the
14578 headline. Additionally, the category of the entry, if any, must
14579 be specified as the text property `org-category' on the headline.
14581 This function sets the variable `org--matcher-tags-todo-only' to
14582 a non-nil value if the matcher restricts matching to TODO
14583 entries, otherwise it is not touched.
14585 See also `org-scan-tags'."
14586 (unless match
14587 ;; Get a new match request, with completion against the global
14588 ;; tags table and the local tags in current buffer.
14589 (let ((org-last-tags-completion-table
14590 (org-uniquify
14591 (delq nil (append (org-get-buffer-tags)
14592 (org-global-tags-completion-table))))))
14593 (setq match
14594 (completing-read
14595 "Match: "
14596 'org-tags-completion-function nil nil nil 'org-tags-history))))
14598 (let ((match0 match)
14599 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14600 (start 0)
14601 tagsmatch todomatch tagsmatcher todomatcher)
14603 ;; Expand group tags.
14604 (setq match (org-tags-expand match))
14606 ;; Check if there is a TODO part of this match, which would be the
14607 ;; part after a "/". To make sure that this slash is not part of
14608 ;; a property value to be matched against, we also check that
14609 ;; there is no / after that slash. First, find the last slash.
14610 (let ((s 0))
14611 (while (string-match "/+" match s)
14612 (setq start (match-beginning 0))
14613 (setq s (match-end 0))))
14614 (if (and (string-match "/+" match start)
14615 (not (string-match-p "\"" match start)))
14616 ;; Match contains also a TODO-matching request.
14617 (progn
14618 (setq tagsmatch (substring match 0 (match-beginning 0)))
14619 (setq todomatch (substring match (match-end 0)))
14620 (when (string-match "\\`!" todomatch)
14621 (setq org--matcher-tags-todo-only t)
14622 (setq todomatch (substring todomatch 1)))
14623 (when (string-match "\\`\\s-*\\'" todomatch)
14624 (setq todomatch nil)))
14625 ;; Only matching tags.
14626 (setq tagsmatch match)
14627 (setq todomatch nil))
14629 ;; Make the tags matcher.
14630 (when (org-string-nw-p tagsmatch)
14631 (let ((orlist nil)
14632 (orterms (org-split-string tagsmatch "|"))
14633 term)
14634 (while (setq term (pop orterms))
14635 (while (and (equal (substring term -1) "\\") orterms)
14636 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14637 (while (string-match re term)
14638 (let* ((rest (substring term (match-end 0)))
14639 (minus (and (match-end 1)
14640 (equal (match-string 1 term) "-")))
14641 (tag (save-match-data
14642 (replace-regexp-in-string
14643 "\\\\-" "-" (match-string 2 term))))
14644 (regexp (eq (string-to-char tag) ?{))
14645 (levelp (match-end 4))
14646 (propp (match-end 5))
14648 (cond
14649 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14650 (levelp
14651 `(,(org-op-to-function (match-string 3 term))
14652 level
14653 ,(string-to-number (match-string 4 term))))
14654 (propp
14655 (let* ((gv (pcase (upcase (match-string 5 term))
14656 ("CATEGORY"
14657 '(get-text-property (point) 'org-category))
14658 ("TODO" 'todo)
14659 (p `(org-cached-entry-get nil ,p))))
14660 (pv (match-string 7 term))
14661 (regexp (eq (string-to-char pv) ?{))
14662 (strp (eq (string-to-char pv) ?\"))
14663 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14664 (po (org-op-to-function (match-string 6 term)
14665 (if timep 'time strp))))
14666 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14667 (when timep (setq pv (org-matcher-time pv)))
14668 (cond ((and regexp (eq po 'org<>))
14669 `(not (string-match ,pv (or ,gv ""))))
14670 (regexp `(string-match ,pv (or ,gv "")))
14671 (strp `(,po (or ,gv "") ,pv))
14673 `(,po
14674 (string-to-number (or ,gv ""))
14675 ,(string-to-number pv))))))
14676 (t `(member ,tag tags-list)))))
14677 (push (if minus `(not ,mm) mm) tagsmatcher)
14678 (setq term rest)))
14679 (push `(and ,@tagsmatcher) orlist)
14680 (setq tagsmatcher nil))
14681 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14683 ;; Make the TODO matcher.
14684 (when (org-string-nw-p todomatch)
14685 (let ((orlist nil))
14686 (dolist (term (org-split-string todomatch "|"))
14687 (while (string-match re term)
14688 (let* ((minus (and (match-end 1)
14689 (equal (match-string 1 term) "-")))
14690 (kwd (match-string 2 term))
14691 (regexp (eq (string-to-char kwd) ?{))
14692 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14693 `(equal todo ,kwd))))
14694 (push (if minus `(not ,mm) mm) todomatcher))
14695 (setq term (substring term (match-end 0))))
14696 (push (if (> (length todomatcher) 1)
14697 (cons 'and todomatcher)
14698 (car todomatcher))
14699 orlist)
14700 (setq todomatcher nil))
14701 (setq todomatcher (cons 'or orlist))))
14703 ;; Return the string and function of the matcher. If no
14704 ;; tags-specific or todo-specific matcher exists, match
14705 ;; everything.
14706 (let ((matcher (if (and tagsmatcher todomatcher)
14707 `(and ,tagsmatcher ,todomatcher)
14708 (or tagsmatcher todomatcher t))))
14709 (when org--matcher-tags-todo-only
14710 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14711 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14713 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14714 "Expand group tags in MATCH.
14716 This replaces every group tag in MATCH with a regexp tag search.
14717 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14718 will be replaced like this:
14720 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14721 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14722 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14724 Replacing by a regexp preserves the structure of the match.
14725 E.g., this expansion
14727 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14729 will match anything tagged with \"Lab\" and \"Home\", or tagged
14730 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14732 A group tag in MATCH can contain regular expressions of its own.
14733 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14734 will be replaced like this:
14736 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14738 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14739 assumed to be a single group tag, and the function will return
14740 the list of tags in this group.
14742 When DOWNCASE is non-nil, expand downcased TAGS."
14743 (if org-group-tags
14744 (let* ((case-fold-search t)
14745 (stable org-mode-syntax-table)
14746 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14747 (taggroups (if downcased
14748 (mapcar (lambda (tg) (mapcar #'downcase tg))
14749 taggroups)
14750 taggroups))
14751 (taggroups-keys (mapcar #'car taggroups))
14752 (return-match (if downcased (downcase match) match))
14753 (count 0)
14754 (work-already-expanded tags-already-expanded)
14755 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14756 ;; @ and _ are allowed as word-components in tags.
14757 (modify-syntax-entry ?@ "w" stable)
14758 (modify-syntax-entry ?_ "w" stable)
14759 ;; Temporarily replace regexp-expressions in the match-expression.
14760 (while (string-match "{.+?}" return-match)
14761 (cl-incf count)
14762 (push (match-string 0 return-match) regexps-in-match)
14763 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14764 (while (and taggroups-keys
14765 (with-syntax-table stable
14766 (string-match
14767 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14768 (regexp-opt taggroups-keys) "\\>\\)")
14769 return-match)))
14770 (let* ((dir (match-string 1 return-match))
14771 (tag (match-string 2 return-match))
14772 (tag (if downcased (downcase tag) tag)))
14773 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14774 (member tag work-already-expanded))
14775 (setq tags-in-group (assoc tag taggroups))
14776 (push tag work-already-expanded)
14777 ;; Recursively expand each tag in the group, if the tag hasn't
14778 ;; already been expanded. Restore the match-data after all recursive calls.
14779 (save-match-data
14780 (let (tags-expanded)
14781 (dolist (x (cdr tags-in-group))
14782 (if (and (member x taggroups-keys)
14783 (not (member x work-already-expanded)))
14784 (setq tags-expanded
14785 (delete-dups
14786 (append
14787 (org-tags-expand x t downcased
14788 work-already-expanded)
14789 tags-expanded)))
14790 (setq tags-expanded
14791 (append (list x) tags-expanded)))
14792 (setq work-already-expanded
14793 (delete-dups
14794 (append tags-expanded
14795 work-already-expanded))))
14796 (setq tags-in-group
14797 (delete-dups (cons (car tags-in-group)
14798 tags-expanded)))))
14799 ;; Filter tag-regexps from tags.
14800 (setq regexp-in-group-escaped
14801 (delq nil (mapcar (lambda (x)
14802 (if (stringp x)
14803 (and (equal "{" (substring x 0 1))
14804 (equal "}" (substring x -1))
14807 tags-in-group))
14808 regexp-in-group
14809 (mapcar (lambda (x)
14810 (substring x 1 -1))
14811 regexp-in-group-escaped)
14812 tags-in-group
14813 (delq nil (mapcar (lambda (x)
14814 (if (stringp x)
14815 (and (not (equal "{" (substring x 0 1)))
14816 (not (equal "}" (substring x -1)))
14819 tags-in-group)))
14820 ;; If single-as-list, do no more in the while-loop.
14821 (if (not single-as-list)
14822 (progn
14823 (when regexp-in-group
14824 (setq regexp-in-group
14825 (concat "\\|"
14826 (mapconcat 'identity regexp-in-group
14827 "\\|"))))
14828 (setq tags-in-group
14829 (concat dir
14830 "{\\<"
14831 (regexp-opt tags-in-group)
14832 "\\>"
14833 regexp-in-group
14834 "}"))
14835 (when (stringp tags-in-group)
14836 (org-add-props tags-in-group '(grouptag t)))
14837 (setq return-match
14838 (replace-match tags-in-group t t return-match)))
14839 (setq tags-in-group
14840 (append regexp-in-group-escaped tags-in-group))))
14841 (setq taggroups-keys (delete tag taggroups-keys))))
14842 ;; Add the regular expressions back into the match-expression again.
14843 (while regexps-in-match
14844 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14845 (pop regexps-in-match)
14846 return-match t t))
14847 (cl-decf count))
14848 (if single-as-list
14849 (if tags-in-group tags-in-group (list return-match))
14850 return-match))
14851 (if single-as-list
14852 (list (if downcased (downcase match) match))
14853 match)))
14855 (defun org-op-to-function (op &optional stringp)
14856 "Turn an operator into the appropriate function."
14857 (setq op
14858 (cond
14859 ((equal op "<" ) '(< string< org-time<))
14860 ((equal op ">" ) '(> org-string> org-time>))
14861 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14862 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14863 ((member op '("=" "==")) '(= string= org-time=))
14864 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14865 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14867 (defun org<> (a b) (not (= a b)))
14868 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14869 (defun org-string>= (a b) (not (string< a b)))
14870 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14871 (defun org-string<> (a b) (not (string= a b)))
14872 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14873 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14874 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14875 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14876 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14877 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14878 (defun org-2ft (s)
14879 "Convert S to a floating point time.
14880 If S is already a number, just return it. If it is a string, parse
14881 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14882 (cond
14883 ((numberp s) s)
14884 ((stringp s)
14885 (condition-case nil
14886 (float-time (apply 'encode-time (org-parse-time-string s)))
14887 (error 0.)))
14888 (t 0.)))
14890 (defun org-time-today ()
14891 "Time in seconds today at 0:00.
14892 Returns the float number of seconds since the beginning of the
14893 epoch to the beginning of today (00:00)."
14894 (float-time (apply 'encode-time
14895 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14897 (defun org-matcher-time (s)
14898 "Interpret a time comparison value."
14899 (save-match-data
14900 (cond
14901 ((string= s "<now>") (float-time))
14902 ((string= s "<today>") (org-time-today))
14903 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14904 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14905 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14906 (+ (org-time-today)
14907 (* (string-to-number (match-string 1 s))
14908 (cdr (assoc (match-string 2 s)
14909 '(("d" . 86400.0) ("w" . 604800.0)
14910 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14911 (t (org-2ft s)))))
14913 (defun org-match-any-p (re list)
14914 "Does re match any element of list?"
14915 (setq list (mapcar (lambda (x) (string-match re x)) list))
14916 (delq nil list))
14918 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14919 (defvar org-tags-overlay (make-overlay 1 1))
14920 (delete-overlay org-tags-overlay)
14922 (defun org-get-local-tags-at (&optional pos)
14923 "Get a list of tags defined in the current headline."
14924 (org-get-tags-at pos 'local))
14926 (defun org-get-local-tags ()
14927 "Get a list of tags defined in the current headline."
14928 (org-get-tags-at nil 'local))
14930 (defun org-get-tags-at (&optional pos local)
14931 "Get a list of all headline tags applicable at POS.
14932 POS defaults to point. If tags are inherited, the list contains
14933 the targets in the same sequence as the headlines appear, i.e.
14934 the tags of the current headline come last.
14935 When LOCAL is non-nil, only return tags from the current headline,
14936 ignore inherited ones."
14937 (interactive)
14938 (if (and org-trust-scanner-tags
14939 (or (not pos) (equal pos (point)))
14940 (not local))
14941 org-scanner-tags
14942 (let (tags ltags lastpos parent)
14943 (save-excursion
14944 (save-restriction
14945 (widen)
14946 (goto-char (or pos (point)))
14947 (save-match-data
14948 (catch 'done
14949 (condition-case nil
14950 (progn
14951 (org-back-to-heading t)
14952 (while (not (equal lastpos (point)))
14953 (setq lastpos (point))
14954 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14955 (setq ltags (org-split-string
14956 (match-string-no-properties 1) ":"))
14957 (when parent
14958 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14959 (setq tags (append
14960 (if parent
14961 (org-remove-uninherited-tags ltags)
14962 ltags)
14963 tags)))
14964 (or org-use-tag-inheritance (throw 'done t))
14965 (when local (throw 'done t))
14966 (or (org-up-heading-safe) (error nil))
14967 (setq parent t)))
14968 (error nil)))))
14969 (if local
14970 tags
14971 (reverse (delete-dups
14972 (reverse (append
14973 (org-remove-uninherited-tags
14974 org-file-tags)
14975 tags)))))))))
14977 (defun org-add-prop-inherited (s)
14978 (add-text-properties 0 (length s) '(inherited t) s)
14981 (defun org-toggle-tag (tag &optional onoff)
14982 "Toggle the tag TAG for the current line.
14983 If ONOFF is `on' or `off', don't toggle but set to this state."
14984 (let (res current)
14985 (save-excursion
14986 (org-back-to-heading t)
14987 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14988 (point-at-eol) t)
14989 (progn
14990 (setq current (match-string 1))
14991 (replace-match ""))
14992 (setq current ""))
14993 (setq current (nreverse (org-split-string current ":")))
14994 (cond
14995 ((eq onoff 'on)
14996 (setq res t)
14997 (or (member tag current) (push tag current)))
14998 ((eq onoff 'off)
14999 (or (not (member tag current)) (setq current (delete tag current))))
15000 (t (if (member tag current)
15001 (setq current (delete tag current))
15002 (setq res t)
15003 (push tag current))))
15004 (end-of-line 1)
15005 (if current
15006 (progn
15007 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15008 (org-set-tags nil t))
15009 (delete-horizontal-space))
15010 (run-hooks 'org-after-tags-change-hook))
15011 res))
15013 (defun org-align-tags-here (to-col)
15014 ;; Assumes that this is a headline
15015 "Align tags on the current headline to TO-COL."
15016 (let ((pos (point)) (col (current-column)) ncol tags-l p)
15017 (beginning-of-line 1)
15018 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15019 (< pos (match-beginning 2)))
15020 (progn
15021 (setq tags-l (string-width (match-string 2)))
15022 (goto-char (match-beginning 1))
15023 (insert " ")
15024 (delete-region (point) (1+ (match-beginning 2)))
15025 (setq ncol (max (current-column)
15026 (1+ col)
15027 (if (> to-col 0)
15028 to-col
15029 (- (abs to-col) tags-l))))
15030 (setq p (point))
15031 (insert (make-string (- ncol (current-column)) ?\ ))
15032 (setq ncol (current-column))
15033 (when indent-tabs-mode (tabify p (point-at-eol)))
15034 (org-move-to-column (min ncol col)))
15035 (goto-char pos))))
15037 (defun org-set-tags-command (&optional arg just-align)
15038 "Call the set-tags command for the current entry."
15039 (interactive "P")
15040 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15041 (org-set-tags arg just-align)
15042 (save-excursion
15043 (unless (and (org-region-active-p)
15044 org-loop-over-headlines-in-active-region)
15045 (org-back-to-heading t))
15046 (org-set-tags arg just-align))))
15048 (defun org-set-tags-to (data)
15049 "Set the tags of the current entry to DATA, replacing the current tags.
15050 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15051 If DATA is nil or the empty string, any tags will be removed."
15052 (interactive "sTags: ")
15053 (setq data
15054 (cond
15055 ((eq data nil) "")
15056 ((equal data "") "")
15057 ((stringp data)
15058 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15059 ":"))
15060 ((listp data)
15061 (concat ":" (mapconcat 'identity data ":") ":"))))
15062 (when data
15063 (save-excursion
15064 (org-back-to-heading t)
15065 (when (looking-at org-complex-heading-regexp)
15066 (if (match-end 5)
15067 (progn
15068 (goto-char (match-beginning 5))
15069 (insert data)
15070 (delete-region (point) (point-at-eol))
15071 (org-set-tags nil 'align))
15072 (goto-char (point-at-eol))
15073 (insert " " data)
15074 (org-set-tags nil 'align)))
15075 (beginning-of-line 1)
15076 (when (looking-at ".*?\\([ \t]+\\)$")
15077 (delete-region (match-beginning 1) (match-end 1))))))
15079 (defun org-align-all-tags ()
15080 "Align the tags in all headings."
15081 (interactive)
15082 (save-excursion
15083 (or (ignore-errors (org-back-to-heading t))
15084 (outline-next-heading))
15085 (if (org-at-heading-p)
15086 (org-set-tags t)
15087 (message "No headings"))))
15089 (defvar org-indent-indentation-per-level)
15090 (defun org-set-tags (&optional arg just-align)
15091 "Set the tags for the current headline.
15092 With prefix ARG, realign all tags in headings in the current buffer.
15093 When JUST-ALIGN is non-nil, only align tags."
15094 (interactive "P")
15095 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15096 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15097 'region-start-level
15098 'region))
15099 org-loop-over-headlines-in-active-region)
15100 (org-map-entries
15101 ;; We don't use ARG and JUST-ALIGN here because these args
15102 ;; are not useful when looping over headlines.
15103 #'org-set-tags
15104 org-loop-over-headlines-in-active-region
15106 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15107 (let ((org-setting-tags t))
15108 (if arg
15109 (save-excursion
15110 (goto-char (point-min))
15111 (while (re-search-forward org-outline-regexp-bol nil t)
15112 (org-set-tags nil t)
15113 (end-of-line))
15114 (message "All tags realigned to column %d" org-tags-column))
15115 (let* ((current (org-get-tags-string))
15116 (col (current-column))
15117 (tags
15118 (if just-align current
15119 ;; Get a new set of tags from the user.
15120 (save-excursion
15121 (let* ((seen)
15122 (table
15123 (setq
15124 org-last-tags-completion-table
15125 ;; Uniquify tags in alists, yet preserve
15126 ;; structure (i.e., keywords).
15127 (delq nil
15128 (mapcar
15129 (lambda (pair)
15130 (let ((head (car pair)))
15131 (cond ((symbolp head) pair)
15132 ((member head seen) nil)
15133 (t (push head seen)
15134 pair))))
15135 (append
15136 (or org-current-tag-alist
15137 (org-get-buffer-tags))
15138 (and
15139 org-complete-tags-always-offer-all-agenda-tags
15140 (org-global-tags-completion-table
15141 (org-agenda-files))))))))
15142 (current-tags (org-split-string current ":"))
15143 (inherited-tags
15144 (nreverse (nthcdr (length current-tags)
15145 (nreverse (org-get-tags-at))))))
15146 (replace-regexp-in-string
15147 "\\([-+&]+\\|,\\)"
15149 (if (or (eq t org-use-fast-tag-selection)
15150 (and org-use-fast-tag-selection
15151 (delq nil (mapcar #'cdr table))))
15152 (org-fast-tag-selection
15153 current-tags inherited-tags table
15154 (and org-fast-tag-selection-include-todo
15155 org-todo-key-alist))
15156 (let ((org-add-colon-after-tag-completion
15157 (< 1 (length table))))
15158 (org-trim
15159 (completing-read
15160 "Tags: "
15161 #'org-tags-completion-function
15162 nil nil current 'org-tags-history))))))))))
15164 (when org-tags-sort-function
15165 (setq tags
15166 (mapconcat
15167 #'identity
15168 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15169 org-tags-sort-function)
15170 ":")))
15172 (if (not (org-string-nw-p tags)) (setq tags "")
15173 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15174 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15176 ;; Insert new tags at the correct column
15177 (beginning-of-line)
15178 (let ((level (if (looking-at org-outline-regexp)
15179 (- (match-end 0) (point) 1)
15180 1)))
15181 (cond
15182 ((and (equal current "") (equal tags "")))
15183 ((re-search-forward
15184 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15185 (line-end-position)
15187 (if (equal tags "") (replace-match "" t t)
15188 (goto-char (match-beginning 0))
15189 (let* ((c0 (current-column))
15190 ;; Compute offset for the case of org-indent-mode
15191 ;; active.
15192 (di (if (bound-and-true-p org-indent-mode)
15193 (* (1- org-indent-indentation-per-level)
15194 (1- level))
15196 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15197 (tc (+ org-tags-column
15198 (if (> org-tags-column 0) (- di) di)))
15199 (c1 (max (1+ c0)
15200 (if (> tc 0) tc
15201 (- (- tc) (string-width tags)))))
15202 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15203 (replace-match rpl t t)
15204 (when indent-tabs-mode (tabify p0 (point))))))
15205 (t (error "Tags alignment failed"))))
15206 (org-move-to-column col))
15207 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15209 (defun org-change-tag-in-region (beg end tag off)
15210 "Add or remove TAG for each entry in the region.
15211 This works in the agenda, and also in an org-mode buffer."
15212 (interactive
15213 (list (region-beginning) (region-end)
15214 (let ((org-last-tags-completion-table
15215 (if (derived-mode-p 'org-mode)
15216 (org-uniquify
15217 (delq nil (append (org-get-buffer-tags)
15218 (org-global-tags-completion-table))))
15219 (org-global-tags-completion-table))))
15220 (completing-read
15221 "Tag: " 'org-tags-completion-function nil nil nil
15222 'org-tags-history))
15223 (progn
15224 (message "[s]et or [r]emove? ")
15225 (equal (read-char-exclusive) ?r))))
15226 (when (fboundp 'deactivate-mark) (deactivate-mark))
15227 (let ((agendap (equal major-mode 'org-agenda-mode))
15228 l1 l2 m buf pos newhead (cnt 0))
15229 (goto-char end)
15230 (setq l2 (1- (org-current-line)))
15231 (goto-char beg)
15232 (setq l1 (org-current-line))
15233 (cl-loop for l from l1 to l2 do
15234 (org-goto-line l)
15235 (setq m (get-text-property (point) 'org-hd-marker))
15236 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15237 (and agendap m))
15238 (setq buf (if agendap (marker-buffer m) (current-buffer))
15239 pos (if agendap m (point)))
15240 (with-current-buffer buf
15241 (save-excursion
15242 (save-restriction
15243 (goto-char pos)
15244 (setq cnt (1+ cnt))
15245 (org-toggle-tag tag (if off 'off 'on))
15246 (setq newhead (org-get-heading)))))
15247 (and agendap (org-agenda-change-all-lines newhead m))))
15248 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15250 (defun org-tags-completion-function (string _predicate &optional flag)
15251 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15252 (confirm (lambda (x) (stringp (car x)))))
15253 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15254 (setq s1 (match-string 1 string)
15255 s2 (match-string 2 string))
15256 (setq s1 "" s2 string))
15257 (cond
15258 ((eq flag nil)
15259 ;; try completion
15260 (setq rtn (try-completion s2 ctable confirm))
15261 (when (stringp rtn)
15262 (setq rtn
15263 (concat s1 s2 (substring rtn (length s2))
15264 (if (and org-add-colon-after-tag-completion
15265 (assoc rtn ctable))
15266 ":" ""))))
15267 rtn)
15268 ((eq flag t)
15269 ;; all-completions
15270 (all-completions s2 ctable confirm))
15271 ((eq flag 'lambda)
15272 ;; exact match?
15273 (assoc s2 ctable)))))
15275 (defun org-fast-tag-insert (kwd tags face &optional end)
15276 "Insert KDW, and the TAGS, the latter with face FACE.
15277 Also insert END."
15278 (insert (format "%-12s" (concat kwd ":"))
15279 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15280 (or end "")))
15282 (defun org-fast-tag-show-exit (flag)
15283 (save-excursion
15284 (org-goto-line 3)
15285 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15286 (replace-match ""))
15287 (when flag
15288 (end-of-line 1)
15289 (org-move-to-column (- (window-width) 19) t)
15290 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15292 (defun org-set-current-tags-overlay (current prefix)
15293 "Add an overlay to CURRENT tag with PREFIX."
15294 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15295 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15296 (org-overlay-display org-tags-overlay (concat prefix s))))
15298 (defvar org-last-tag-selection-key nil)
15299 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15300 "Fast tag selection with single keys.
15301 CURRENT is the current list of tags in the headline, INHERITED is the
15302 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15303 possibly with grouping information. TODO-TABLE is a similar table with
15304 TODO keywords, should these have keys assigned to them.
15305 If the keys are nil, a-z are automatically assigned.
15306 Returns the new tags string, or nil to not change the current settings."
15307 (let* ((fulltable (append table todo-table))
15308 (maxlen (apply 'max (mapcar
15309 (lambda (x)
15310 (if (stringp (car x)) (string-width (car x)) 0))
15311 fulltable)))
15312 (buf (current-buffer))
15313 (expert (eq org-fast-tag-selection-single-key 'expert))
15314 (buffer-tags nil)
15315 (fwidth (+ maxlen 3 1 3))
15316 (ncol (/ (- (window-width) 4) fwidth))
15317 (i-face 'org-done)
15318 (c-face 'org-todo)
15319 tg cnt e c char c1 c2 ntable tbl rtn
15320 ov-start ov-end ov-prefix
15321 (exit-after-next org-fast-tag-selection-single-key)
15322 (done-keywords org-done-keywords)
15323 groups ingroup intaggroup)
15324 (save-excursion
15325 (beginning-of-line 1)
15326 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15327 (setq ov-start (match-beginning 1)
15328 ov-end (match-end 1)
15329 ov-prefix "")
15330 (setq ov-start (1- (point-at-eol))
15331 ov-end (1+ ov-start))
15332 (skip-chars-forward "^\n\r")
15333 (setq ov-prefix
15334 (concat
15335 (buffer-substring (1- (point)) (point))
15336 (if (> (current-column) org-tags-column)
15338 (make-string (- org-tags-column (current-column)) ?\ ))))))
15339 (move-overlay org-tags-overlay ov-start ov-end)
15340 (save-window-excursion
15341 (if expert
15342 (set-buffer (get-buffer-create " *Org tags*"))
15343 (delete-other-windows)
15344 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15345 (org-switch-to-buffer-other-window " *Org tags*"))
15346 (erase-buffer)
15347 (setq-local org-done-keywords done-keywords)
15348 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15349 (org-fast-tag-insert "Current" current c-face "\n\n")
15350 (org-fast-tag-show-exit exit-after-next)
15351 (org-set-current-tags-overlay current ov-prefix)
15352 (setq tbl fulltable char ?a cnt 0)
15353 (while (setq e (pop tbl))
15354 (cond
15355 ((eq (car e) :startgroup)
15356 (push '() groups) (setq ingroup t)
15357 (unless (zerop cnt)
15358 (setq cnt 0)
15359 (insert "\n"))
15360 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15361 ((eq (car e) :endgroup)
15362 (setq ingroup nil cnt 0)
15363 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15364 ((eq (car e) :startgrouptag)
15365 (setq intaggroup t)
15366 (unless (zerop cnt)
15367 (setq cnt 0)
15368 (insert "\n"))
15369 (insert "[ "))
15370 ((eq (car e) :endgrouptag)
15371 (setq intaggroup nil cnt 0)
15372 (insert "]\n"))
15373 ((equal e '(:newline))
15374 (unless (zerop cnt)
15375 (setq cnt 0)
15376 (insert "\n")
15377 (setq e (car tbl))
15378 (while (equal (car tbl) '(:newline))
15379 (insert "\n")
15380 (setq tbl (cdr tbl)))))
15381 ((equal e '(:grouptags)) (insert " : "))
15383 (setq tg (copy-sequence (car e)) c2 nil)
15384 (if (cdr e)
15385 (setq c (cdr e))
15386 ;; automatically assign a character.
15387 (setq c1 (string-to-char
15388 (downcase (substring
15389 tg (if (= (string-to-char tg) ?@) 1 0)))))
15390 (if (or (rassoc c1 ntable) (rassoc c1 table))
15391 (while (or (rassoc char ntable) (rassoc char table))
15392 (setq char (1+ char)))
15393 (setq c2 c1))
15394 (setq c (or c2 char)))
15395 (when ingroup (push tg (car groups)))
15396 (setq tg (org-add-props tg nil 'face
15397 (cond
15398 ((not (assoc tg table))
15399 (org-get-todo-face tg))
15400 ((member tg current) c-face)
15401 ((member tg inherited) i-face))))
15402 (when (equal (caar tbl) :grouptags)
15403 (org-add-props tg nil 'face 'org-tag-group))
15404 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15405 (insert "[" c "] " tg (make-string
15406 (- fwidth 4 (length tg)) ?\ ))
15407 (push (cons tg c) ntable)
15408 (when (= (cl-incf cnt) ncol)
15409 (insert "\n")
15410 (when (or ingroup intaggroup) (insert " "))
15411 (setq cnt 0)))))
15412 (setq ntable (nreverse ntable))
15413 (insert "\n")
15414 (goto-char (point-min))
15415 (unless expert (org-fit-window-to-buffer))
15416 (setq rtn
15417 (catch 'exit
15418 (while t
15419 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15420 (if (not groups) "no " "")
15421 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15422 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15423 (setq org-last-tag-selection-key c)
15424 (cond
15425 ((= c ?\r) (throw 'exit t))
15426 ((= c ?!)
15427 (setq groups (not groups))
15428 (goto-char (point-min))
15429 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15430 ((= c ?\C-c)
15431 (if (not expert)
15432 (org-fast-tag-show-exit
15433 (setq exit-after-next (not exit-after-next)))
15434 (setq expert nil)
15435 (delete-other-windows)
15436 (set-window-buffer (split-window-vertically) " *Org tags*")
15437 (org-switch-to-buffer-other-window " *Org tags*")
15438 (org-fit-window-to-buffer)))
15439 ((or (= c ?\C-g)
15440 (and (= c ?q) (not (rassoc c ntable))))
15441 (delete-overlay org-tags-overlay)
15442 (setq quit-flag t))
15443 ((= c ?\ )
15444 (setq current nil)
15445 (when exit-after-next (setq exit-after-next 'now)))
15446 ((= c ?\t)
15447 (condition-case nil
15448 (setq tg (completing-read
15449 "Tag: "
15450 (or buffer-tags
15451 (with-current-buffer buf
15452 (setq buffer-tags
15453 (org-get-buffer-tags))))))
15454 (quit (setq tg "")))
15455 (when (string-match "\\S-" tg)
15456 (cl-pushnew (list tg) buffer-tags :test #'equal)
15457 (if (member tg current)
15458 (setq current (delete tg current))
15459 (push tg current)))
15460 (when exit-after-next (setq exit-after-next 'now)))
15461 ((setq e (rassoc c todo-table) tg (car e))
15462 (with-current-buffer buf
15463 (save-excursion (org-todo tg)))
15464 (when exit-after-next (setq exit-after-next 'now)))
15465 ((setq e (rassoc c ntable) tg (car e))
15466 (if (member tg current)
15467 (setq current (delete tg current))
15468 (cl-loop for g in groups do
15469 (when (member tg g)
15470 (dolist (x g) (setq current (delete x current)))))
15471 (push tg current))
15472 (when exit-after-next (setq exit-after-next 'now))))
15474 ;; Create a sorted list
15475 (setq current
15476 (sort current
15477 (lambda (a b)
15478 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15479 (when (eq exit-after-next 'now) (throw 'exit t))
15480 (goto-char (point-min))
15481 (beginning-of-line 2)
15482 (delete-region (point) (point-at-eol))
15483 (org-fast-tag-insert "Current" current c-face)
15484 (org-set-current-tags-overlay current ov-prefix)
15485 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15486 (setq tg (match-string 1))
15487 (add-text-properties
15488 (match-beginning 1) (match-end 1)
15489 (list 'face
15490 (cond
15491 ((member tg current) c-face)
15492 ((member tg inherited) i-face)
15493 (t (get-text-property (match-beginning 1) 'face))))))
15494 (goto-char (point-min)))))
15495 (delete-overlay org-tags-overlay)
15496 (if rtn
15497 (mapconcat 'identity current ":")
15498 nil))))
15500 (defun org-get-tags-string ()
15501 "Get the TAGS string in the current headline."
15502 (unless (org-at-heading-p t)
15503 (user-error "Not on a heading"))
15504 (save-excursion
15505 (beginning-of-line 1)
15506 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15507 (match-string-no-properties 1)
15508 "")))
15510 (defun org-get-tags ()
15511 "Get the list of tags specified in the current headline."
15512 (org-split-string (org-get-tags-string) ":"))
15514 (defun org-get-buffer-tags ()
15515 "Get a table of all tags used in the buffer, for completion."
15516 (org-with-wide-buffer
15517 (goto-char (point-min))
15518 (let ((tag-re (concat org-outline-regexp-bol
15519 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15520 tags)
15521 (while (re-search-forward tag-re nil t)
15522 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15523 (push tag tags)))
15524 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15526 ;;;; The mapping API
15528 (defvar org-agenda-skip-comment-trees)
15529 (defvar org-agenda-skip-function)
15530 (defun org-map-entries (func &optional match scope &rest skip)
15531 "Call FUNC at each headline selected by MATCH in SCOPE.
15533 FUNC is a function or a lisp form. The function will be called without
15534 arguments, with the cursor positioned at the beginning of the headline.
15535 The return values of all calls to the function will be collected and
15536 returned as a list.
15538 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15539 does not need to preserve point. After evaluation, the cursor will be
15540 moved to the end of the line (presumably of the headline of the
15541 processed entry) and search continues from there. Under some
15542 circumstances, this may not produce the wanted results. For example,
15543 if you have removed (e.g. archived) the current (sub)tree it could
15544 mean that the next entry will be skipped entirely. In such cases, you
15545 can specify the position from where search should continue by making
15546 FUNC set the variable `org-map-continue-from' to the desired buffer
15547 position.
15549 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15550 Only headlines that are matched by this query will be considered during
15551 the iteration. When MATCH is nil or t, all headlines will be
15552 visited by the iteration.
15554 SCOPE determines the scope of this command. It can be any of:
15556 nil The current buffer, respecting the restriction if any
15557 tree The subtree started with the entry at point
15558 region The entries within the active region, if any
15559 region-start-level
15560 The entries within the active region, but only those at
15561 the same level than the first one.
15562 file The current buffer, without restriction
15563 file-with-archives
15564 The current buffer, and any archives associated with it
15565 agenda All agenda files
15566 agenda-with-archives
15567 All agenda files with any archive files associated with them
15568 \(file1 file2 ...)
15569 If this is a list, all files in the list will be scanned
15571 The remaining args are treated as settings for the skipping facilities of
15572 the scanner. The following items can be given here:
15574 archive skip trees with the archive tag
15575 comment skip trees with the COMMENT keyword
15576 function or Emacs Lisp form:
15577 will be used as value for `org-agenda-skip-function', so
15578 whenever the function returns a position, FUNC will not be
15579 called for that entry and search will continue from the
15580 position returned
15582 If your function needs to retrieve the tags including inherited tags
15583 at the *current* entry, you can use the value of the variable
15584 `org-scanner-tags' which will be much faster than getting the value
15585 with `org-get-tags-at'. If your function gets properties with
15586 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15587 to t around the call to `org-entry-properties' to get the same speedup.
15588 Note that if your function moves around to retrieve tags and properties at
15589 a *different* entry, you cannot use these techniques."
15590 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15591 (not (org-region-active-p)))
15592 (let* ((org-agenda-archives-mode nil) ; just to make sure
15593 (org-agenda-skip-archived-trees (memq 'archive skip))
15594 (org-agenda-skip-comment-trees (memq 'comment skip))
15595 (org-agenda-skip-function
15596 (car (org-delete-all '(comment archive) skip)))
15597 (org-tags-match-list-sublevels t)
15598 (start-level (eq scope 'region-start-level))
15599 matcher res
15600 org-todo-keywords-for-agenda
15601 org-done-keywords-for-agenda
15602 org-todo-keyword-alist-for-agenda
15603 org-tag-alist-for-agenda
15604 org--matcher-tags-todo-only)
15606 (cond
15607 ((eq match t) (setq matcher t))
15608 ((eq match nil) (setq matcher t))
15609 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15611 (save-excursion
15612 (save-restriction
15613 (cond ((eq scope 'tree)
15614 (org-back-to-heading t)
15615 (org-narrow-to-subtree)
15616 (setq scope nil))
15617 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15618 (org-region-active-p))
15619 ;; If needed, set start-level to a string like "2"
15620 (when start-level
15621 (save-excursion
15622 (goto-char (region-beginning))
15623 (unless (org-at-heading-p) (outline-next-heading))
15624 (setq start-level (org-current-level))))
15625 (narrow-to-region (region-beginning)
15626 (save-excursion
15627 (goto-char (region-end))
15628 (unless (and (bolp) (org-at-heading-p))
15629 (outline-next-heading))
15630 (point)))
15631 (setq scope nil)))
15633 (if (not scope)
15634 (progn
15635 (org-agenda-prepare-buffers
15636 (and buffer-file-name (list buffer-file-name)))
15637 (setq res
15638 (org-scan-tags
15639 func matcher org--matcher-tags-todo-only start-level)))
15640 ;; Get the right scope
15641 (cond
15642 ((and scope (listp scope) (symbolp (car scope)))
15643 (setq scope (eval scope)))
15644 ((eq scope 'agenda)
15645 (setq scope (org-agenda-files t)))
15646 ((eq scope 'agenda-with-archives)
15647 (setq scope (org-agenda-files t))
15648 (setq scope (org-add-archive-files scope)))
15649 ((eq scope 'file)
15650 (setq scope (and buffer-file-name (list buffer-file-name))))
15651 ((eq scope 'file-with-archives)
15652 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15653 (org-agenda-prepare-buffers scope)
15654 (dolist (file scope)
15655 (with-current-buffer (org-find-base-buffer-visiting file)
15656 (save-excursion
15657 (save-restriction
15658 (widen)
15659 (goto-char (point-min))
15660 (setq res
15661 (append
15663 (org-scan-tags
15664 func matcher org--matcher-tags-todo-only))))))))))
15665 res)))
15667 ;;; Properties API
15669 (defconst org-special-properties
15670 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15671 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15672 "The special properties valid in Org mode.
15673 These are properties that are not defined in the property drawer,
15674 but in some other way.")
15676 (defconst org-default-properties
15677 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15678 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15679 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15680 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15681 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15682 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15683 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15684 "Some properties that are used by Org mode for various purposes.
15685 Being in this list makes sure that they are offered for completion.")
15687 (defun org--valid-property-p (property)
15688 "Non nil when string PROPERTY is a valid property name."
15689 (not
15690 (or (equal property "")
15691 (string-match-p "\\s-" property))))
15693 (defun org--update-property-plist (key val props)
15694 "Associate KEY to VAL in alist PROPS.
15695 Modifications are made by side-effect. Return new alist."
15696 (let* ((appending (string= (substring key -1) "+"))
15697 (key (if appending (substring key 0 -1) key))
15698 (old (assoc-string key props t)))
15699 (if (not old) (cons (cons key val) props)
15700 (setcdr old (if appending (concat (cdr old) " " val) val))
15701 props)))
15703 (defun org-get-property-block (&optional beg force)
15704 "Return the (beg . end) range of the body of the property drawer.
15705 BEG is the beginning of the current subtree, or of the part
15706 before the first headline. If it is not given, it will be found.
15707 If the drawer does not exist, create it if FORCE is non-nil, or
15708 return nil."
15709 (org-with-wide-buffer
15710 (when beg (goto-char beg))
15711 (unless (org-before-first-heading-p)
15712 (let ((beg (cond (beg)
15713 ((or (not (featurep 'org-inlinetask))
15714 (org-inlinetask-in-task-p))
15715 (org-back-to-heading t))
15716 (t (org-with-limited-levels (org-back-to-heading t))))))
15717 (forward-line)
15718 (when (looking-at-p org-planning-line-re) (forward-line))
15719 (cond ((looking-at org-property-drawer-re)
15720 (forward-line)
15721 (cons (point) (progn (goto-char (match-end 0))
15722 (line-beginning-position))))
15723 (force
15724 (goto-char beg)
15725 (org-insert-property-drawer)
15726 (let ((pos (save-excursion (search-forward ":END:")
15727 (line-beginning-position))))
15728 (cons pos pos))))))))
15730 (defun org-at-property-p ()
15731 "Non-nil when point is inside a property drawer.
15732 See `org-property-re' for match data, if applicable."
15733 (save-excursion
15734 (beginning-of-line)
15735 (and (looking-at org-property-re)
15736 (let ((property-drawer (save-match-data (org-get-property-block))))
15737 (and property-drawer
15738 (>= (point) (car property-drawer))
15739 (< (point) (cdr property-drawer)))))))
15741 (defun org-property-action ()
15742 "Do an action on properties."
15743 (interactive)
15744 (unless (org-at-property-p) (user-error "Not at a property"))
15745 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15746 (let ((c (read-char-exclusive)))
15747 (cl-case c
15748 (?s (call-interactively #'org-set-property))
15749 (?d (call-interactively #'org-delete-property))
15750 (?D (call-interactively #'org-delete-property-globally))
15751 (?c (call-interactively #'org-compute-property-at-point))
15752 (otherwise (user-error "No such property action %c" c)))))
15754 (defun org-inc-effort ()
15755 "Increment the value of the effort property in the current entry."
15756 (interactive)
15757 (org-set-effort nil t))
15759 (defvar org-clock-effort) ; Defined in org-clock.el.
15760 (defvar org-clock-current-task) ; Defined in org-clock.el.
15761 (defun org-set-effort (&optional value increment)
15762 "Set the effort property of the current entry.
15763 With numerical prefix arg, use the nth allowed value, 0 stands for the
15764 10th allowed value.
15766 When INCREMENT is non-nil, set the property to the next allowed value."
15767 (interactive "P")
15768 (when (equal value 0) (setq value 10))
15769 (let* ((completion-ignore-case t)
15770 (prop org-effort-property)
15771 (cur (org-entry-get nil prop))
15772 (allowed (org-property-get-allowed-values nil prop 'table))
15773 (existing (mapcar 'list (org-property-values prop)))
15774 (heading (nth 4 (org-heading-components)))
15776 (val (cond
15777 ((stringp value) value)
15778 ((and allowed (integerp value))
15779 (or (car (nth (1- value) allowed))
15780 (car (org-last allowed))))
15781 ((and allowed increment)
15782 (or (cl-caadr (member (list cur) allowed))
15783 (user-error "Allowed effort values are not set")))
15784 (allowed
15785 (message "Select 1-9,0, [RET%s]: %s"
15786 (if cur (concat "=" cur) "")
15787 (mapconcat 'car allowed " "))
15788 (setq rpl (read-char-exclusive))
15789 (if (equal rpl ?\r)
15791 (setq rpl (- rpl ?0))
15792 (when (equal rpl 0) (setq rpl 10))
15793 (if (and (> rpl 0) (<= rpl (length allowed)))
15794 (car (nth (1- rpl) allowed))
15795 (org-completing-read "Effort: " allowed nil))))
15797 (org-completing-read
15798 (concat "Effort" (and cur (string-match "\\S-" cur)
15799 (concat " [" cur "]"))
15800 ": ")
15801 existing nil nil "" nil cur)))))
15802 (unless (equal (org-entry-get nil prop) val)
15803 (org-entry-put nil prop val))
15804 (org-refresh-property
15805 '((effort . identity)
15806 (effort-minutes . org-duration-string-to-minutes))
15807 val)
15808 (when (equal heading (bound-and-true-p org-clock-current-task))
15809 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15810 (org-clock-update-mode-line))
15811 (message "%s is now %s" prop val)))
15813 (defun org-entry-properties (&optional pom which)
15814 "Get all properties of the current entry.
15816 When POM is a buffer position, get all properties from the entry
15817 there instead.
15819 This includes the TODO keyword, the tags, time strings for
15820 deadline, scheduled, and clocking, and any additional properties
15821 defined in the entry.
15823 If WHICH is nil or `all', get all properties. If WHICH is
15824 `special' or `standard', only get that subclass. If WHICH is
15825 a string, only get that property.
15827 Return value is an alist. Keys are properties, as upcased
15828 strings."
15829 (org-with-point-at pom
15830 (when (and (derived-mode-p 'org-mode)
15831 (ignore-errors (org-back-to-heading t)))
15832 (catch 'exit
15833 (let* ((beg (point))
15834 (specific (and (stringp which) (upcase which)))
15835 (which (cond ((not specific) which)
15836 ((member specific org-special-properties) 'special)
15837 (t 'standard)))
15838 props)
15839 ;; Get the special properties, like TODO and TAGS.
15840 (when (memq which '(nil all special))
15841 (when (or (not specific) (string= specific "CLOCKSUM"))
15842 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15843 (when clocksum
15844 (push (cons "CLOCKSUM"
15845 (org-minutes-to-clocksum-string clocksum))
15846 props)))
15847 (when specific (throw 'exit props)))
15848 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15849 (let ((clocksumt (get-text-property (point)
15850 :org-clock-minutes-today)))
15851 (when clocksumt
15852 (push (cons "CLOCKSUM_T"
15853 (org-minutes-to-clocksum-string clocksumt))
15854 props)))
15855 (when specific (throw 'exit props)))
15856 (when (or (not specific) (string= specific "ITEM"))
15857 (when (looking-at org-complex-heading-regexp)
15858 (push (cons "ITEM"
15859 (let ((title (match-string-no-properties 4)))
15860 (if (org-string-nw-p title)
15861 (org-remove-tabs title)
15862 "")))
15863 props))
15864 (when specific (throw 'exit props)))
15865 (when (or (not specific) (string= specific "TODO"))
15866 (let ((case-fold-search nil))
15867 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15868 (push (cons "TODO" (match-string-no-properties 2)) props)))
15869 (when specific (throw 'exit props)))
15870 (when (or (not specific) (string= specific "PRIORITY"))
15871 (push (cons "PRIORITY"
15872 (if (looking-at org-priority-regexp)
15873 (match-string-no-properties 2)
15874 (char-to-string org-default-priority)))
15875 props)
15876 (when specific (throw 'exit props)))
15877 (when (or (not specific) (string= specific "FILE"))
15878 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15879 props)
15880 (when specific (throw 'exit props)))
15881 (when (or (not specific) (string= specific "TAGS"))
15882 (let ((value (org-string-nw-p (org-get-tags-string))))
15883 (when value (push (cons "TAGS" value) props)))
15884 (when specific (throw 'exit props)))
15885 (when (or (not specific) (string= specific "ALLTAGS"))
15886 (let ((value (org-get-tags-at)))
15887 (when value
15888 (push (cons "ALLTAGS"
15889 (format ":%s:" (mapconcat #'identity value ":")))
15890 props)))
15891 (when specific (throw 'exit props)))
15892 (when (or (not specific) (string= specific "BLOCKED"))
15893 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15894 (when specific (throw 'exit props)))
15895 (when (or (not specific)
15896 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15897 (forward-line)
15898 (when (looking-at-p org-planning-line-re)
15899 (end-of-line)
15900 (let ((bol (line-beginning-position))
15901 ;; Backward compatibility: time keywords used to
15902 ;; be configurable (before 8.3). Make sure we
15903 ;; get the correct keyword.
15904 (key-assoc `(("CLOSED" . ,org-closed-string)
15905 ("DEADLINE" . ,org-deadline-string)
15906 ("SCHEDULED" . ,org-scheduled-string))))
15907 (dolist (pair (if specific (list (assoc specific key-assoc))
15908 key-assoc))
15909 (save-excursion
15910 (when (search-backward (cdr pair) bol t)
15911 (goto-char (match-end 0))
15912 (skip-chars-forward " \t")
15913 (and (looking-at org-ts-regexp-both)
15914 (push (cons (car pair)
15915 (match-string-no-properties 0))
15916 props)))))))
15917 (when specific (throw 'exit props)))
15918 (when (or (not specific)
15919 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15920 (let ((find-ts
15921 (lambda (end ts)
15922 ;; Fix next time-stamp before END. TS is the
15923 ;; list of time-stamps found so far.
15924 (let ((ts ts)
15925 (regexp (cond
15926 ((string= specific "TIMESTAMP")
15927 org-ts-regexp)
15928 ((string= specific "TIMESTAMP_IA")
15929 org-ts-regexp-inactive)
15930 ((assoc "TIMESTAMP_IA" ts)
15931 org-ts-regexp)
15932 ((assoc "TIMESTAMP" ts)
15933 org-ts-regexp-inactive)
15934 (t org-ts-regexp-both))))
15935 (catch 'next
15936 (while (re-search-forward regexp end t)
15937 (backward-char)
15938 (let ((object (org-element-context)))
15939 ;; Accept to match timestamps in node
15940 ;; properties, too.
15941 (when (memq (org-element-type object)
15942 '(node-property timestamp))
15943 (let ((type
15944 (org-element-property :type object)))
15945 (cond
15946 ((and (memq type '(active active-range))
15947 (not (equal specific "TIMESTAMP_IA")))
15948 (unless (assoc "TIMESTAMP" ts)
15949 (push (cons "TIMESTAMP"
15950 (org-element-property
15951 :raw-value object))
15953 (when specific (throw 'exit ts))))
15954 ((and (memq type '(inactive inactive-range))
15955 (not (string= specific "TIMESTAMP")))
15956 (unless (assoc "TIMESTAMP_IA" ts)
15957 (push (cons "TIMESTAMP_IA"
15958 (org-element-property
15959 :raw-value object))
15961 (when specific (throw 'exit ts))))))
15962 ;; Both timestamp types are found,
15963 ;; move to next part.
15964 (when (= (length ts) 2) (throw 'next ts)))))
15965 ts)))))
15966 (goto-char beg)
15967 ;; First look for timestamps within headline.
15968 (let ((ts (funcall find-ts (line-end-position) nil)))
15969 (if (= (length ts) 2) (setq props (nconc ts props))
15970 (forward-line)
15971 ;; Then find timestamps in the section, skipping
15972 ;; planning line.
15973 (when (looking-at-p org-planning-line-re)
15974 (forward-line))
15975 (let ((end (save-excursion (outline-next-heading))))
15976 (setq props (nconc (funcall find-ts end ts) props))))))))
15977 ;; Get the standard properties, like :PROP:.
15978 (when (memq which '(nil all standard))
15979 ;; If we are looking after a specific property, delegate
15980 ;; to `org-entry-get', which is faster. However, make an
15981 ;; exception for "CATEGORY", since it can be also set
15982 ;; through keywords (i.e. #+CATEGORY).
15983 (if (and specific (not (equal specific "CATEGORY")))
15984 (let ((value (org-entry-get beg specific nil t)))
15985 (throw 'exit (and value (list (cons specific value)))))
15986 (let ((range (org-get-property-block beg)))
15987 (when range
15988 (let ((end (cdr range)) seen-base)
15989 (goto-char (car range))
15990 ;; Unlike to `org--update-property-plist', we
15991 ;; handle the case where base values is found
15992 ;; after its extension. We also forbid standard
15993 ;; properties to be named as special properties.
15994 (while (re-search-forward org-property-re end t)
15995 (let* ((key (upcase (match-string-no-properties 2)))
15996 (extendp (string-match-p "\\+\\'" key))
15997 (key-base (if extendp (substring key 0 -1) key))
15998 (value (match-string-no-properties 3)))
15999 (cond
16000 ((member-ignore-case key-base org-special-properties))
16001 (extendp
16002 (setq props
16003 (org--update-property-plist key value props)))
16004 ((member key seen-base))
16005 (t (push key seen-base)
16006 (let ((p (assoc-string key props t)))
16007 (if p (setcdr p (concat value " " (cdr p)))
16008 (push (cons key value) props))))))))))))
16009 (unless (assoc "CATEGORY" props)
16010 (push (cons "CATEGORY" (org-get-category beg)) props)
16011 (when (string= specific "CATEGORY") (throw 'exit props)))
16012 ;; Return value.
16013 props)))))
16015 (defun org-property--local-values (property literal-nil)
16016 "Return value for PROPERTY in current entry.
16017 Value is a list whose car is the base value for PROPERTY and cdr
16018 a list of accumulated values. Return nil if neither is found in
16019 the entry. Also return nil when PROPERTY is set to \"nil\",
16020 unless LITERAL-NIL is non-nil."
16021 (let ((range (org-get-property-block)))
16022 (when range
16023 (goto-char (car range))
16024 (let* ((case-fold-search t)
16025 (end (cdr range))
16026 (value
16027 ;; Base value.
16028 (save-excursion
16029 (let ((v (and (re-search-forward
16030 (org-re-property property nil t) end t)
16031 (match-string-no-properties 3))))
16032 (list (if literal-nil v (org-not-nil v)))))))
16033 ;; Find additional values.
16034 (let* ((property+ (org-re-property (concat property "+") nil t)))
16035 (while (re-search-forward property+ end t)
16036 (push (match-string-no-properties 3) value)))
16037 ;; Return final values.
16038 (and (not (equal value '(nil))) (nreverse value))))))
16040 (defun org-entry-get (pom property &optional inherit literal-nil)
16041 "Get value of PROPERTY for entry or content at point-or-marker POM.
16043 If INHERIT is non-nil and the entry does not have the property,
16044 then also check higher levels of the hierarchy. If INHERIT is
16045 the symbol `selective', use inheritance only if the setting in
16046 `org-use-property-inheritance' selects PROPERTY for inheritance.
16048 If the property is present but empty, the return value is the
16049 empty string. If the property is not present at all, nil is
16050 returned. In any other case, return the value as a string.
16051 Search is case-insensitive.
16053 If LITERAL-NIL is set, return the string value \"nil\" as
16054 a string, do not interpret it as the list atom nil. This is used
16055 for inheritance when a \"nil\" value can supersede a non-nil
16056 value higher up the hierarchy."
16057 (org-with-point-at pom
16058 (cond
16059 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16060 ;; We need a special property. Use `org-entry-properties' to
16061 ;; retrieve it, but specify the wanted property.
16062 (cdr (assoc-string property (org-entry-properties nil property))))
16063 ((and inherit
16064 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16065 (org-entry-get-with-inheritance property literal-nil))
16067 (let* ((local (org-property--local-values property literal-nil))
16068 (value (and local (mapconcat #'identity (delq nil local) " "))))
16069 (if literal-nil value (org-not-nil value)))))))
16071 (defun org-property-or-variable-value (var &optional inherit)
16072 "Check if there is a property fixing the value of VAR.
16073 If yes, return this value. If not, return the current value of the variable."
16074 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16075 (if (and prop (stringp prop) (string-match "\\S-" prop))
16076 (read prop)
16077 (symbol-value var))))
16079 (defun org-entry-delete (pom property)
16080 "Delete PROPERTY from entry at point-or-marker POM.
16081 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16082 non-nil when a property was removed."
16083 (unless (member property org-special-properties)
16084 (org-with-point-at pom
16085 (let ((range (org-get-property-block)))
16086 (when range
16087 (let* ((begin (car range))
16088 (origin (cdr range))
16089 (end (copy-marker origin))
16090 (re (org-re-property
16091 (concat (regexp-quote property) "\\+?") t t)))
16092 (goto-char begin)
16093 (while (re-search-forward re end t)
16094 (delete-region (match-beginning 0) (line-beginning-position 2)))
16095 ;; If drawer is empty, remove it altogether.
16096 (when (= begin end)
16097 (delete-region (line-beginning-position 0)
16098 (line-beginning-position 2)))
16099 ;; Return non-nil if some property was removed.
16100 (prog1 (/= end origin) (set-marker end nil))))))))
16102 ;; Multi-values properties are properties that contain multiple values
16103 ;; These values are assumed to be single words, separated by whitespace.
16104 (defun org-entry-add-to-multivalued-property (pom property value)
16105 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16106 (let* ((old (org-entry-get pom property))
16107 (values (and old (org-split-string old "[ \t]"))))
16108 (setq value (org-entry-protect-space value))
16109 (unless (member value values)
16110 (setq values (append values (list value)))
16111 (org-entry-put pom property
16112 (mapconcat 'identity values " ")))))
16114 (defun org-entry-remove-from-multivalued-property (pom property value)
16115 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16116 (let* ((old (org-entry-get pom property))
16117 (values (and old (org-split-string old "[ \t]"))))
16118 (setq value (org-entry-protect-space value))
16119 (when (member value values)
16120 (setq values (delete value values))
16121 (org-entry-put pom property
16122 (mapconcat 'identity values " ")))))
16124 (defun org-entry-member-in-multivalued-property (pom property value)
16125 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16126 (let* ((old (org-entry-get pom property))
16127 (values (and old (org-split-string old "[ \t]"))))
16128 (setq value (org-entry-protect-space value))
16129 (member value values)))
16131 (defun org-entry-get-multivalued-property (pom property)
16132 "Return a list of values in a multivalued property."
16133 (let* ((value (org-entry-get pom property))
16134 (values (and value (org-split-string value "[ \t]"))))
16135 (mapcar 'org-entry-restore-space values)))
16137 (defun org-entry-put-multivalued-property (pom property &rest values)
16138 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16139 VALUES should be a list of strings. Spaces will be protected."
16140 (org-entry-put pom property
16141 (mapconcat 'org-entry-protect-space values " "))
16142 (let* ((value (org-entry-get pom property))
16143 (values (and value (org-split-string value "[ \t]"))))
16144 (mapcar 'org-entry-restore-space values)))
16146 (defun org-entry-protect-space (s)
16147 "Protect spaces and newline in string S."
16148 (while (string-match " " s)
16149 (setq s (replace-match "%20" t t s)))
16150 (while (string-match "\n" s)
16151 (setq s (replace-match "%0A" t t s)))
16154 (defun org-entry-restore-space (s)
16155 "Restore spaces and newline in string S."
16156 (while (string-match "%20" s)
16157 (setq s (replace-match " " t t s)))
16158 (while (string-match "%0A" s)
16159 (setq s (replace-match "\n" t t s)))
16162 (defvar org-entry-property-inherited-from (make-marker)
16163 "Marker pointing to the entry from where a property was inherited.
16164 Each call to `org-entry-get-with-inheritance' will set this marker to the
16165 location of the entry where the inheritance search matched. If there was
16166 no match, the marker will point nowhere.
16167 Note that also `org-entry-get' calls this function, if the INHERIT flag
16168 is set.")
16170 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16171 "Get PROPERTY of entry or content at point, search higher levels if needed.
16172 The search will stop at the first ancestor which has the property defined.
16173 If the value found is \"nil\", return nil to show that the property
16174 should be considered as undefined (this is the meaning of nil here).
16175 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16176 (move-marker org-entry-property-inherited-from nil)
16177 (org-with-wide-buffer
16178 (let (value)
16179 (catch 'exit
16180 (while t
16181 (let ((v (org-property--local-values property literal-nil)))
16182 (when v
16183 (setq value
16184 (concat (mapconcat #'identity (delq nil v) " ")
16185 (and value " ")
16186 value)))
16187 (cond
16188 ((car v)
16189 (org-back-to-heading t)
16190 (move-marker org-entry-property-inherited-from (point))
16191 (throw 'exit nil))
16192 ((org-up-heading-safe))
16194 (let ((global
16195 (cdr (or (assoc-string property org-file-properties t)
16196 (assoc-string property org-global-properties t)
16197 (assoc-string property org-global-properties-fixed t)))))
16198 (cond ((not global))
16199 (value (setq value (concat global " " value)))
16200 (t (setq value global))))
16201 (throw 'exit nil))))))
16202 (if literal-nil value (org-not-nil value)))))
16204 (defvar org-property-changed-functions nil
16205 "Hook called when the value of a property has changed.
16206 Each hook function should accept two arguments, the name of the property
16207 and the new value.")
16209 (defun org-entry-put (pom property value)
16210 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16212 If the value is nil, it is converted to the empty string. If it
16213 is not a string, an error is raised. Also raise an error on
16214 invalid property names.
16216 PROPERTY can be any regular property (see
16217 `org-special-properties'). It can also be \"TODO\",
16218 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16220 For the last two properties, VALUE may have any of the special
16221 values \"earlier\" and \"later\". The function then increases or
16222 decreases scheduled or deadline date by one day."
16223 (cond ((null value) (setq value ""))
16224 ((not (stringp value)) (error "Properties values should be strings"))
16225 ((not (org--valid-property-p property))
16226 (user-error "Invalid property name: \"%s\"" property)))
16227 (org-with-point-at pom
16228 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16229 (org-back-to-heading t)
16230 (org-with-limited-levels (org-back-to-heading t)))
16231 (let ((beg (point)))
16232 (cond
16233 ((equal property "TODO")
16234 (cond ((not (org-string-nw-p value)) (setq value 'none))
16235 ((not (member value org-todo-keywords-1))
16236 (user-error "\"%s\" is not a valid TODO state" value)))
16237 (org-todo value)
16238 (org-set-tags nil 'align))
16239 ((equal property "PRIORITY")
16240 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16241 (org-set-tags nil 'align))
16242 ((equal property "SCHEDULED")
16243 (forward-line)
16244 (if (and (looking-at-p org-planning-line-re)
16245 (re-search-forward
16246 org-scheduled-time-regexp (line-end-position) t))
16247 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16248 ((string= value "later") (org-timestamp-change 1 'day))
16249 ((string= value "") (org-schedule '(4)))
16250 (t (org-schedule nil value)))
16251 (if (member value '("earlier" "later" ""))
16252 (call-interactively #'org-schedule)
16253 (org-schedule nil value))))
16254 ((equal property "DEADLINE")
16255 (forward-line)
16256 (if (and (looking-at-p org-planning-line-re)
16257 (re-search-forward
16258 org-deadline-time-regexp (line-end-position) t))
16259 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16260 ((string= value "later") (org-timestamp-change 1 'day))
16261 ((string= value "") (org-deadline '(4)))
16262 (t (org-deadline nil value)))
16263 (if (member value '("earlier" "later" ""))
16264 (call-interactively #'org-deadline)
16265 (org-deadline nil value))))
16266 ((member property org-special-properties)
16267 (error "The %s property cannot be set with `org-entry-put'" property))
16269 (let* ((range (org-get-property-block beg 'force))
16270 (end (cdr range))
16271 (case-fold-search t))
16272 (goto-char (car range))
16273 (if (re-search-forward (org-re-property property nil t) end t)
16274 (progn (delete-region (match-beginning 0) (match-end 0))
16275 (goto-char (match-beginning 0)))
16276 (goto-char end)
16277 (insert "\n")
16278 (backward-char))
16279 (insert ":" property ":")
16280 (when value (insert " " value))
16281 (org-indent-line)))))
16282 (run-hook-with-args 'org-property-changed-functions property value)))
16284 (defun org-buffer-property-keys
16285 (&optional specials defaults columns ignore-malformed)
16286 "Get all property keys in the current buffer.
16288 When SPECIALS is non-nil, also list the special properties that
16289 reflect things like tags and TODO state.
16291 When DEFAULTS is non-nil, also include properties that has
16292 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16293 DESCRIPTION, LOCATION, and LOGGING and others.
16295 When COLUMNS in non-nil, also include property names given in
16296 COLUMN formats in the current buffer.
16298 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16299 automatically performed, such drawers will be silently ignored."
16300 (let ((case-fold-search t)
16301 (props (append
16302 (and specials org-special-properties)
16303 (and defaults (cons org-effort-property org-default-properties))
16304 nil)))
16305 (org-with-wide-buffer
16306 (goto-char (point-min))
16307 (while (re-search-forward org-property-start-re nil t)
16308 (let ((range (org-get-property-block)))
16309 (catch 'skip
16310 (unless range
16311 (when (and (not ignore-malformed)
16312 (not (org-before-first-heading-p))
16313 (y-or-n-p (format "Malformed drawer at %d, repair?"
16314 (line-beginning-position))))
16315 (org-get-property-block nil t))
16316 (throw 'skip nil))
16317 (goto-char (car range))
16318 (let ((begin (car range))
16319 (end (cdr range)))
16320 ;; Make sure that found property block is not located
16321 ;; before current point, as it would generate an infloop.
16322 ;; It can happen, for example, in the following
16323 ;; situation:
16325 ;; * Headline
16326 ;; :PROPERTIES:
16327 ;; ...
16328 ;; :END:
16329 ;; *************** Inlinetask
16330 ;; #+BEGIN_EXAMPLE
16331 ;; :PROPERTIES:
16332 ;; #+END_EXAMPLE
16334 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16335 (while (< (point) end)
16336 (let ((p (progn (looking-at org-property-re)
16337 (match-string-no-properties 2))))
16338 ;; Only add true property name, not extension symbol.
16339 (push (if (not (string-match-p "\\+\\'" p)) p
16340 (substring p 0 -1))
16341 props))
16342 (forward-line))))
16343 (outline-next-heading)))
16344 (when columns
16345 (goto-char (point-min))
16346 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16347 (let ((element (org-element-at-point)))
16348 (when (memq (org-element-type element) '(keyword node-property))
16349 (let ((value (org-element-property :value element))
16350 (start 0))
16351 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16352 (setq start (match-end 0))
16353 (let ((p (match-string-no-properties 1 value)))
16354 (unless (member-ignore-case p org-special-properties)
16355 (push p props))))))))))
16356 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16358 (defun org-property-values (key)
16359 "List all non-nil values of property KEY in current buffer."
16360 (org-with-wide-buffer
16361 (goto-char (point-min))
16362 (let ((case-fold-search t)
16363 (re (org-re-property key))
16364 values)
16365 (while (re-search-forward re nil t)
16366 (push (org-entry-get (point) key) values))
16367 (delete-dups values))))
16369 (defun org-insert-property-drawer ()
16370 "Insert a property drawer into the current entry."
16371 (org-with-wide-buffer
16372 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16373 (org-back-to-heading t)
16374 (org-with-limited-levels (org-back-to-heading t)))
16375 (forward-line)
16376 (when (looking-at-p org-planning-line-re) (forward-line))
16377 (unless (looking-at-p org-property-drawer-re)
16378 ;; Make sure we start editing a line from current entry, not from
16379 ;; next one. It prevents extending text properties or overlays
16380 ;; belonging to the latter.
16381 (when (bolp) (backward-char))
16382 (let ((begin (1+ (point)))
16383 (inhibit-read-only t))
16384 (insert "\n:PROPERTIES:\n:END:")
16385 (when (eobp) (insert "\n"))
16386 (org-indent-region begin (point))))))
16388 (defun org-insert-drawer (&optional arg drawer)
16389 "Insert a drawer at point.
16391 When optional argument ARG is non-nil, insert a property drawer.
16393 Optional argument DRAWER, when non-nil, is a string representing
16394 drawer's name. Otherwise, the user is prompted for a name.
16396 If a region is active, insert the drawer around that region
16397 instead.
16399 Point is left between drawer's boundaries."
16400 (interactive "P")
16401 (let* ((drawer (if arg "PROPERTIES"
16402 (or drawer (read-from-minibuffer "Drawer: ")))))
16403 (cond
16404 ;; With C-u, fall back on `org-insert-property-drawer'
16405 (arg (org-insert-property-drawer))
16406 ;; Check validity of suggested drawer's name.
16407 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16408 (user-error "Invalid drawer name"))
16409 ;; With an active region, insert a drawer at point.
16410 ((not (org-region-active-p))
16411 (progn
16412 (unless (bolp) (insert "\n"))
16413 (insert (format ":%s:\n\n:END:\n" drawer))
16414 (forward-line -2)))
16415 ;; Otherwise, insert the drawer at point
16417 (let ((rbeg (region-beginning))
16418 (rend (copy-marker (region-end))))
16419 (unwind-protect
16420 (progn
16421 (goto-char rbeg)
16422 (beginning-of-line)
16423 (when (save-excursion
16424 (re-search-forward org-outline-regexp-bol rend t))
16425 (user-error "Drawers cannot contain headlines"))
16426 ;; Position point at the beginning of the first
16427 ;; non-blank line in region. Insert drawer's opening
16428 ;; there, then indent it.
16429 (org-skip-whitespace)
16430 (beginning-of-line)
16431 (insert ":" drawer ":\n")
16432 (forward-line -1)
16433 (indent-for-tab-command)
16434 ;; Move point to the beginning of the first blank line
16435 ;; after the last non-blank line in region. Insert
16436 ;; drawer's closing, then indent it.
16437 (goto-char rend)
16438 (skip-chars-backward " \r\t\n")
16439 (insert "\n:END:")
16440 (deactivate-mark t)
16441 (indent-for-tab-command)
16442 (unless (eolp) (insert "\n")))
16443 ;; Clear marker, whatever the outcome of insertion is.
16444 (set-marker rend nil)))))))
16446 (defvar org-property-set-functions-alist nil
16447 "Property set function alist.
16448 Each entry should have the following format:
16450 (PROPERTY . READ-FUNCTION)
16452 The read function will be called with the same argument as
16453 `org-completing-read'.")
16455 (defun org-set-property-function (property)
16456 "Get the function that should be used to set PROPERTY.
16457 This is computed according to `org-property-set-functions-alist'."
16458 (or (cdr (assoc property org-property-set-functions-alist))
16459 'org-completing-read))
16461 (defun org-read-property-value (property)
16462 "Read PROPERTY value from user."
16463 (let* ((completion-ignore-case t)
16464 (allowed (org-property-get-allowed-values nil property 'table))
16465 (cur (org-entry-get nil property))
16466 (prompt (concat property " value"
16467 (if (and cur (string-match "\\S-" cur))
16468 (concat " [" cur "]") "") ": "))
16469 (set-function (org-set-property-function property))
16470 (val (if allowed
16471 (funcall set-function prompt allowed nil
16472 (not (get-text-property 0 'org-unrestricted
16473 (caar allowed))))
16474 (funcall set-function prompt
16475 (mapcar 'list (org-property-values property))
16476 nil nil "" nil cur))))
16477 (org-trim val)))
16479 (defvar org-last-set-property nil)
16480 (defvar org-last-set-property-value nil)
16481 (defun org-read-property-name ()
16482 "Read a property name."
16483 (let ((completion-ignore-case t)
16484 (default-prop (or (and (org-at-property-p)
16485 (match-string-no-properties 2))
16486 org-last-set-property)))
16487 (org-completing-read
16488 (concat "Property"
16489 (if default-prop (concat " [" default-prop "]") "")
16490 ": ")
16491 (mapcar #'list (org-buffer-property-keys nil t t))
16492 nil nil nil nil default-prop)))
16494 (defun org-set-property-and-value (use-last)
16495 "Allow to set [PROPERTY]: [value] direction from prompt.
16496 When use-default, don't even ask, just use the last
16497 \"[PROPERTY]: [value]\" string from the history."
16498 (interactive "P")
16499 (let* ((completion-ignore-case t)
16500 (pv (or (and use-last org-last-set-property-value)
16501 (org-completing-read
16502 "Enter a \"[Property]: [value]\" pair: "
16503 nil nil nil nil nil
16504 org-last-set-property-value)))
16505 prop val)
16506 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16507 (setq prop (match-string 1 pv)
16508 val (match-string 2 pv))
16509 (org-set-property prop val))))
16511 (defun org-set-property (property value)
16512 "In the current entry, set PROPERTY to VALUE.
16514 When called interactively, this will prompt for a property name, offering
16515 completion on existing and default properties. And then it will prompt
16516 for a value, offering completion either on allowed values (via an inherited
16517 xxx_ALL property) or on existing values in other instances of this property
16518 in the current file.
16520 Throw an error when trying to set a property with an invalid name."
16521 (interactive (list nil nil))
16522 (let ((property (or property (org-read-property-name))))
16523 ;; `org-entry-put' also makes the following check, but this one
16524 ;; avoids polluting `org-last-set-property' and
16525 ;; `org-last-set-property-value' needlessly.
16526 (unless (org--valid-property-p property)
16527 (user-error "Invalid property name: \"%s\"" property))
16528 (let ((value (or value (org-read-property-value property)))
16529 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16530 (setq org-last-set-property property)
16531 (setq org-last-set-property-value (concat property ": " value))
16532 ;; Possibly postprocess the inserted value:
16533 (when fn (setq value (funcall fn value)))
16534 (unless (equal (org-entry-get nil property) value)
16535 (org-entry-put nil property value)))))
16537 (defun org-find-property (property &optional value)
16538 "Find first entry in buffer that sets PROPERTY.
16540 When optional argument VALUE is non-nil, only consider an entry
16541 if it contains PROPERTY set to this value. If PROPERTY should be
16542 explicitly set to nil, use string \"nil\" for VALUE.
16544 Return position where the entry begins, or nil if there is no
16545 such entry. If narrowing is in effect, only search the visible
16546 part of the buffer."
16547 (save-excursion
16548 (goto-char (point-min))
16549 (let ((case-fold-search t)
16550 (re (org-re-property property nil (not value) value)))
16551 (catch 'exit
16552 (while (re-search-forward re nil t)
16553 (when (if value (org-at-property-p)
16554 (org-entry-get (point) property nil t))
16555 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16557 (defun org-delete-property (property)
16558 "In the current entry, delete PROPERTY."
16559 (interactive
16560 (let* ((completion-ignore-case t)
16561 (cat (org-entry-get (point) "CATEGORY"))
16562 (props0 (org-entry-properties nil 'standard))
16563 (props (if cat props0
16564 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16565 (prop (if (< 1 (length props))
16566 (completing-read "Property: " props nil t)
16567 (caar props))))
16568 (list prop)))
16569 (if (not property)
16570 (message "No property to delete in this entry")
16571 (org-entry-delete nil property)
16572 (message "Property \"%s\" deleted" property)))
16574 (defun org-delete-property-globally (property)
16575 "Remove PROPERTY globally, from all entries.
16576 This function ignores narrowing, if any."
16577 (interactive
16578 (let* ((completion-ignore-case t)
16579 (prop (completing-read
16580 "Globally remove property: "
16581 (mapcar #'list (org-buffer-property-keys)))))
16582 (list prop)))
16583 (org-with-wide-buffer
16584 (goto-char (point-min))
16585 (let ((count 0)
16586 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16587 (while (re-search-forward re nil t)
16588 (when (org-entry-delete (point) property) (cl-incf count)))
16589 (message "Property \"%s\" removed from %d entries" property count))))
16591 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16593 (defun org-compute-property-at-point ()
16594 "Compute the property at point.
16595 This looks for an enclosing column format, extracts the operator and
16596 then applies it to the property in the column format's scope."
16597 (interactive)
16598 (unless (org-at-property-p)
16599 (user-error "Not at a property"))
16600 (let ((prop (match-string-no-properties 2)))
16601 (org-columns-get-format-and-top-level)
16602 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16603 (user-error "No operator defined for property %s" prop))
16604 (org-columns-compute prop)))
16606 (defvar org-property-allowed-value-functions nil
16607 "Hook for functions supplying allowed values for a specific property.
16608 The functions must take a single argument, the name of the property, and
16609 return a flat list of allowed values. If \":ETC\" is one of
16610 the values, this means that these values are intended as defaults for
16611 completion, but that other values should be allowed too.
16612 The functions must return nil if they are not responsible for this
16613 property.")
16615 (defun org-property-get-allowed-values (pom property &optional table)
16616 "Get allowed values for the property PROPERTY.
16617 When TABLE is non-nil, return an alist that can directly be used for
16618 completion."
16619 (let (vals)
16620 (cond
16621 ((equal property "TODO")
16622 (setq vals (org-with-point-at pom
16623 (append org-todo-keywords-1 '("")))))
16624 ((equal property "PRIORITY")
16625 (let ((n org-lowest-priority))
16626 (while (>= n org-highest-priority)
16627 (push (char-to-string n) vals)
16628 (setq n (1- n)))))
16629 ((equal property "CATEGORY"))
16630 ((member property org-special-properties))
16631 ((setq vals (run-hook-with-args-until-success
16632 'org-property-allowed-value-functions property)))
16634 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16635 (when (and vals (string-match "\\S-" vals))
16636 (setq vals (car (read-from-string (concat "(" vals ")"))))
16637 (setq vals (mapcar (lambda (x)
16638 (cond ((stringp x) x)
16639 ((numberp x) (number-to-string x))
16640 ((symbolp x) (symbol-name x))
16641 (t "???")))
16642 vals)))))
16643 (when (member ":ETC" vals)
16644 (setq vals (remove ":ETC" vals))
16645 (org-add-props (car vals) '(org-unrestricted t)))
16646 (if table (mapcar 'list vals) vals)))
16648 (defun org-property-previous-allowed-value (&optional _previous)
16649 "Switch to the next allowed value for this property."
16650 (interactive)
16651 (org-property-next-allowed-value t))
16653 (defun org-property-next-allowed-value (&optional previous)
16654 "Switch to the next allowed value for this property."
16655 (interactive)
16656 (unless (org-at-property-p)
16657 (user-error "Not at a property"))
16658 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16659 (key (match-string 2))
16660 (value (match-string 3))
16661 (allowed (or (org-property-get-allowed-values (point) key)
16662 (and (member value '("[ ]" "[-]" "[X]"))
16663 '("[ ]" "[X]"))))
16664 (heading (save-match-data (nth 4 (org-heading-components))))
16665 nval)
16666 (unless allowed
16667 (user-error "Allowed values for this property have not been defined"))
16668 (when previous (setq allowed (reverse allowed)))
16669 (when (member value allowed)
16670 (setq nval (car (cdr (member value allowed)))))
16671 (setq nval (or nval (car allowed)))
16672 (when (equal nval value)
16673 (user-error "Only one allowed value for this property"))
16674 (org-at-property-p)
16675 (replace-match (concat " :" key ": " nval) t t)
16676 (org-indent-line)
16677 (beginning-of-line 1)
16678 (skip-chars-forward " \t")
16679 (when (equal prop org-effort-property)
16680 (org-refresh-property
16681 '((effort . identity)
16682 (effort-minutes . org-duration-string-to-minutes))
16683 nval)
16684 (when (string= org-clock-current-task heading)
16685 (setq org-clock-effort nval)
16686 (org-clock-update-mode-line)))
16687 (run-hook-with-args 'org-property-changed-functions key nval)))
16689 (defun org-find-olp (path &optional this-buffer)
16690 "Return a marker pointing to the entry at outline path OLP.
16691 If anything goes wrong, throw an error.
16692 You can wrap this call to catch the error like this:
16694 \(condition-case msg
16695 \(org-mobile-locate-entry (match-string 4))
16696 \(error (nth 1 msg)))
16698 The return value will then be either a string with the error message,
16699 or a marker if everything is OK.
16701 If THIS-BUFFER is set, the outline path does not contain a file,
16702 only headings."
16703 (let* ((file (if this-buffer buffer-file-name (pop path)))
16704 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16705 (level 1)
16706 (lmin 1)
16707 (lmax 1)
16708 end found flevel)
16709 (unless buffer (error "File not found :%s" file))
16710 (with-current-buffer buffer
16711 (org-with-wide-buffer
16712 (goto-char (point-min))
16713 (dolist (heading path)
16714 (let ((re (format org-complex-heading-regexp-format
16715 (regexp-quote heading)))
16716 (cnt 0))
16717 (while (re-search-forward re end t)
16718 (setq level (- (match-end 1) (match-beginning 1)))
16719 (when (and (>= level lmin) (<= level lmax))
16720 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16721 (when (= cnt 0)
16722 (error "Heading not found on level %d: %s" lmax heading))
16723 (when (> cnt 1)
16724 (error "Heading not unique on level %d: %s" lmax heading))
16725 (goto-char found)
16726 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16727 (setq end (save-excursion (org-end-of-subtree t t)))))
16728 (when (org-at-heading-p)
16729 (point-marker))))))
16731 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16732 "Find node HEADING in BUFFER.
16733 Return a marker to the heading if it was found, or nil if not.
16734 If POS-ONLY is set, return just the position instead of a marker.
16736 The heading text must match exact, but it may have a TODO keyword,
16737 a priority cookie and tags in the standard locations."
16738 (with-current-buffer (or buffer (current-buffer))
16739 (save-excursion
16740 (save-restriction
16741 (widen)
16742 (goto-char (point-min))
16743 (let (case-fold-search)
16744 (when (re-search-forward
16745 (format org-complex-heading-regexp-format
16746 (regexp-quote heading)) nil t)
16747 (if pos-only
16748 (match-beginning 0)
16749 (move-marker (make-marker) (match-beginning 0)))))))))
16751 (defun org-find-exact-heading-in-directory (heading &optional dir)
16752 "Find Org node headline HEADING in all .org files in directory DIR.
16753 When the target headline is found, return a marker to this location."
16754 (let ((files (directory-files (or dir default-directory)
16755 t "\\`[^.#].*\\.org\\'"))
16756 visiting m buffer)
16757 (catch 'found
16758 (dolist (file files)
16759 (message "trying %s" file)
16760 (setq visiting (org-find-base-buffer-visiting file))
16761 (setq buffer (or visiting (find-file-noselect file)))
16762 (setq m (org-find-exact-headline-in-buffer
16763 heading buffer))
16764 (when (and (not m) (not visiting)) (kill-buffer buffer))
16765 (and m (throw 'found m))))))
16767 (defun org-find-entry-with-id (ident)
16768 "Locate the entry that contains the ID property with exact value IDENT.
16769 IDENT can be a string, a symbol or a number, this function will search for
16770 the string representation of it.
16771 Return the position where this entry starts, or nil if there is no such entry."
16772 (interactive "sID: ")
16773 (let ((id (cond
16774 ((stringp ident) ident)
16775 ((symbolp ident) (symbol-name ident))
16776 ((numberp ident) (number-to-string ident))
16777 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16778 (org-with-wide-buffer (org-find-property "ID" id))))
16780 ;;;; Timestamps
16782 (defvar org-last-changed-timestamp nil)
16783 (defvar org-last-inserted-timestamp nil
16784 "The last time stamp inserted with `org-insert-time-stamp'.")
16785 (defvar org-ts-what) ; dynamically scoped parameter
16787 (defun org-time-stamp (arg &optional inactive)
16788 "Prompt for a date/time and insert a time stamp.
16790 If the user specifies a time like HH:MM or if this command is
16791 called with at least one prefix argument, the time stamp contains
16792 the date and the time. Otherwise, only the date is included.
16794 All parts of a date not specified by the user are filled in from
16795 the timestamp at point, if any, or the current date/time
16796 otherwise.
16798 If there is already a timestamp at the cursor, it is replaced.
16800 With two universal prefix arguments, insert an active timestamp
16801 with the current time without prompting the user.
16803 When called from lisp, the timestamp is inactive if INACTIVE is
16804 non-nil."
16805 (interactive "P")
16806 (let* ((ts (cond
16807 ((org-at-date-range-p t)
16808 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16809 ((org-at-timestamp-p t) (match-string 0))))
16810 ;; Default time is either the timestamp at point or today.
16811 ;; When entering a range, only the range start is considered.
16812 (default-time (if (not ts) (current-time)
16813 (apply #'encode-time (org-parse-time-string ts))))
16814 (default-input (and ts (org-get-compact-tod ts)))
16815 (repeater (and ts
16816 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16817 (match-string 0 ts)))
16818 org-time-was-given
16819 org-end-time-was-given
16820 (time
16821 (and (if (equal arg '(16)) (current-time)
16822 ;; Preserve `this-command' and `last-command'.
16823 (let ((this-command this-command)
16824 (last-command last-command))
16825 (org-read-date
16826 arg 'totime nil nil default-time default-input
16827 inactive))))))
16828 (cond
16829 ((and ts
16830 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16831 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16832 (insert "--")
16833 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16835 ;; Make sure we're on a timestamp. When in the middle of a date
16836 ;; range, move arbitrarily to range end.
16837 (unless (org-at-timestamp-p t)
16838 (skip-chars-forward "-")
16839 (org-at-timestamp-p t))
16840 (replace-match "")
16841 (setq org-last-changed-timestamp
16842 (org-insert-time-stamp
16843 time (or org-time-was-given arg)
16844 inactive nil nil (list org-end-time-was-given)))
16845 (when repeater
16846 (backward-char)
16847 (insert " " repeater)
16848 (setq org-last-changed-timestamp
16849 (concat (substring org-last-inserted-timestamp 0 -1)
16850 " " repeater ">")))
16851 (message "Timestamp updated"))
16852 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16853 (t (org-insert-time-stamp
16854 time (or org-time-was-given arg) inactive nil nil
16855 (list org-end-time-was-given))))))
16857 ;; FIXME: can we use this for something else, like computing time differences?
16858 (defun org-get-compact-tod (s)
16859 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16860 (let* ((t1 (match-string 1 s))
16861 (h1 (string-to-number (match-string 2 s)))
16862 (m1 (string-to-number (match-string 3 s)))
16863 (t2 (and (match-end 4) (match-string 5 s)))
16864 (h2 (and t2 (string-to-number (match-string 6 s))))
16865 (m2 (and t2 (string-to-number (match-string 7 s))))
16866 dh dm)
16867 (if (not t2)
16869 (setq dh (- h2 h1) dm (- m2 m1))
16870 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16871 (concat t1 "+" (number-to-string dh)
16872 (and (/= 0 dm) (format ":%02d" dm)))))))
16874 (defun org-time-stamp-inactive (&optional arg)
16875 "Insert an inactive time stamp.
16876 An inactive time stamp is enclosed in square brackets instead of angle
16877 brackets. It is inactive in the sense that it does not trigger agenda entries,
16878 does not link to the calendar and cannot be changed with the S-cursor keys.
16879 So these are more for recording a certain time/date."
16880 (interactive "P")
16881 (org-time-stamp arg 'inactive))
16883 (defvar org-date-ovl (make-overlay 1 1))
16884 (overlay-put org-date-ovl 'face 'org-date-selected)
16885 (delete-overlay org-date-ovl)
16887 (defvar org-ans1) ; dynamically scoped parameter
16888 (defvar org-ans2) ; dynamically scoped parameter
16890 (defvar org-plain-time-of-day-regexp) ; defined below
16892 (defvar org-overriding-default-time nil) ; dynamically scoped
16893 (defvar org-read-date-overlay nil)
16894 (defvar org-dcst nil) ; dynamically scoped
16895 (defvar org-read-date-history nil)
16896 (defvar org-read-date-final-answer nil)
16897 (defvar org-read-date-analyze-futurep nil)
16898 (defvar org-read-date-analyze-forced-year nil)
16899 (defvar org-read-date-inactive)
16901 (defvar org-read-date-minibuffer-local-map
16902 (let* ((map (make-sparse-keymap)))
16903 (set-keymap-parent map minibuffer-local-map)
16904 (org-defkey map (kbd ".")
16905 (lambda () (interactive)
16906 ;; Are we at the beginning of the prompt?
16907 (if (looking-back "^[^:]+: "
16908 (let ((inhibit-field-text-motion t))
16909 (line-beginning-position)))
16910 (org-eval-in-calendar '(calendar-goto-today))
16911 (insert "."))))
16912 (org-defkey map (kbd "C-.")
16913 (lambda () (interactive)
16914 (org-eval-in-calendar '(calendar-goto-today))))
16915 (org-defkey map [(meta shift left)]
16916 (lambda () (interactive)
16917 (org-eval-in-calendar '(calendar-backward-month 1))))
16918 (org-defkey map [(meta shift right)]
16919 (lambda () (interactive)
16920 (org-eval-in-calendar '(calendar-forward-month 1))))
16921 (org-defkey map [(meta shift up)]
16922 (lambda () (interactive)
16923 (org-eval-in-calendar '(calendar-backward-year 1))))
16924 (org-defkey map [(meta shift down)]
16925 (lambda () (interactive)
16926 (org-eval-in-calendar '(calendar-forward-year 1))))
16927 (org-defkey map [?\e (shift left)]
16928 (lambda () (interactive)
16929 (org-eval-in-calendar '(calendar-backward-month 1))))
16930 (org-defkey map [?\e (shift right)]
16931 (lambda () (interactive)
16932 (org-eval-in-calendar '(calendar-forward-month 1))))
16933 (org-defkey map [?\e (shift up)]
16934 (lambda () (interactive)
16935 (org-eval-in-calendar '(calendar-backward-year 1))))
16936 (org-defkey map [?\e (shift down)]
16937 (lambda () (interactive)
16938 (org-eval-in-calendar '(calendar-forward-year 1))))
16939 (org-defkey map [(shift up)]
16940 (lambda () (interactive)
16941 (org-eval-in-calendar '(calendar-backward-week 1))))
16942 (org-defkey map [(shift down)]
16943 (lambda () (interactive)
16944 (org-eval-in-calendar '(calendar-forward-week 1))))
16945 (org-defkey map [(shift left)]
16946 (lambda () (interactive)
16947 (org-eval-in-calendar '(calendar-backward-day 1))))
16948 (org-defkey map [(shift right)]
16949 (lambda () (interactive)
16950 (org-eval-in-calendar '(calendar-forward-day 1))))
16951 (org-defkey map "!"
16952 (lambda () (interactive)
16953 (org-eval-in-calendar '(diary-view-entries))
16954 (message "")))
16955 (org-defkey map ">"
16956 (lambda () (interactive)
16957 (org-eval-in-calendar '(calendar-scroll-left 1))))
16958 (org-defkey map "<"
16959 (lambda () (interactive)
16960 (org-eval-in-calendar '(calendar-scroll-right 1))))
16961 (org-defkey map "\C-v"
16962 (lambda () (interactive)
16963 (org-eval-in-calendar
16964 '(calendar-scroll-left-three-months 1))))
16965 (org-defkey map "\M-v"
16966 (lambda () (interactive)
16967 (org-eval-in-calendar
16968 '(calendar-scroll-right-three-months 1))))
16969 map)
16970 "Keymap for minibuffer commands when using `org-read-date'.")
16972 (defvar org-def)
16973 (defvar org-defdecode)
16974 (defvar org-with-time)
16976 (defvar calendar-setup) ; Dynamically scoped.
16977 (defun org-read-date (&optional with-time to-time from-string prompt
16978 default-time default-input inactive)
16979 "Read a date, possibly a time, and make things smooth for the user.
16980 The prompt will suggest to enter an ISO date, but you can also enter anything
16981 which will at least partially be understood by `parse-time-string'.
16982 Unrecognized parts of the date will default to the current day, month, year,
16983 hour and minute. If this command is called to replace a timestamp at point,
16984 or to enter the second timestamp of a range, the default time is taken
16985 from the existing stamp. Furthermore, the command prefers the future,
16986 so if you are giving a date where the year is not given, and the day-month
16987 combination is already past in the current year, it will assume you
16988 mean next year. For details, see the manual. A few examples:
16990 3-2-5 --> 2003-02-05
16991 feb 15 --> currentyear-02-15
16992 2/15 --> currentyear-02-15
16993 sep 12 9 --> 2009-09-12
16994 12:45 --> today 12:45
16995 22 sept 0:34 --> currentyear-09-22 0:34
16996 12 --> currentyear-currentmonth-12
16997 Fri --> nearest Friday after today
16998 -Tue --> last Tuesday
16999 etc.
17001 Furthermore you can specify a relative date by giving, as the *first* thing
17002 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
17003 change in days weeks, months, years.
17004 With a single plus or minus, the date is relative to today. With a double
17005 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17006 +4d --> four days from today
17007 +4 --> same as above
17008 +2w --> two weeks from today
17009 ++5 --> five days from default date
17011 The function understands only English month and weekday abbreviations.
17013 While prompting, a calendar is popped up - you can also select the
17014 date with the mouse (button 1). The calendar shows a period of three
17015 months. To scroll it to other months, use the keys `>' and `<'.
17016 If you don't like the calendar, turn it off with
17017 (setq org-read-date-popup-calendar nil)
17019 With optional argument TO-TIME, the date will immediately be converted
17020 to an internal time.
17021 With an optional argument WITH-TIME, the prompt will suggest to
17022 also insert a time. Note that when WITH-TIME is not set, you can
17023 still enter a time, and this function will inform the calling routine
17024 about this change. The calling routine may then choose to change the
17025 format used to insert the time stamp into the buffer to include the time.
17026 With optional argument FROM-STRING, read from this string instead from
17027 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17028 the time/date that is used for everything that is not specified by the
17029 user."
17030 (require 'parse-time)
17031 (let* ((org-with-time with-time)
17032 (org-time-stamp-rounding-minutes
17033 (if (equal org-with-time '(16))
17034 '(0 0)
17035 org-time-stamp-rounding-minutes))
17036 (org-dcst org-display-custom-times)
17037 (ct (org-current-time))
17038 (org-def (or org-overriding-default-time default-time ct))
17039 (org-defdecode (decode-time org-def))
17040 (cur-frame (selected-frame))
17041 (mouse-autoselect-window nil) ; Don't let the mouse jump
17042 (calendar-setup
17043 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17044 (calendar-move-hook nil)
17045 (calendar-view-diary-initially-flag nil)
17046 (calendar-view-holidays-initially-flag nil)
17047 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17048 ;; Rationalize `org-def' and `org-defdecode', if required.
17049 (when (< (nth 2 org-defdecode) org-extend-today-until)
17050 (setf (nth 2 org-defdecode) -1)
17051 (setf (nth 1 org-defdecode) 59)
17052 (setq org-def (apply #'encode-time org-defdecode))
17053 (setq org-defdecode (decode-time org-def)))
17054 (let* ((timestr (format-time-string
17055 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17056 org-def))
17057 (prompt (concat (if prompt (concat prompt " ") "")
17058 (format "Date+time [%s]: " timestr))))
17059 (cond
17060 (from-string (setq ans from-string))
17061 (org-read-date-popup-calendar
17062 (save-excursion
17063 (save-window-excursion
17064 (calendar)
17065 (when (eq calendar-setup 'calendar-only)
17066 (setq cal-frame
17067 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17068 (select-frame cal-frame))
17069 (org-eval-in-calendar '(setq cursor-type nil) t)
17070 (unwind-protect
17071 (progn
17072 (calendar-forward-day (- (time-to-days org-def)
17073 (calendar-absolute-from-gregorian
17074 (calendar-current-date))))
17075 (org-eval-in-calendar nil t)
17076 (let* ((old-map (current-local-map))
17077 (map (copy-keymap calendar-mode-map))
17078 (minibuffer-local-map
17079 (copy-keymap org-read-date-minibuffer-local-map)))
17080 (org-defkey map (kbd "RET") 'org-calendar-select)
17081 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17082 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17083 (unwind-protect
17084 (progn
17085 (use-local-map map)
17086 (setq org-read-date-inactive inactive)
17087 (add-hook 'post-command-hook 'org-read-date-display)
17088 (setq org-ans0
17089 (read-string prompt
17090 default-input
17091 'org-read-date-history
17092 nil))
17093 ;; org-ans0: from prompt
17094 ;; org-ans1: from mouse click
17095 ;; org-ans2: from calendar motion
17096 (setq ans
17097 (concat org-ans0 " " (or org-ans1 org-ans2))))
17098 (remove-hook 'post-command-hook 'org-read-date-display)
17099 (use-local-map old-map)
17100 (when org-read-date-overlay
17101 (delete-overlay org-read-date-overlay)
17102 (setq org-read-date-overlay nil)))))
17103 (bury-buffer "*Calendar*")
17104 (when cal-frame
17105 (delete-frame cal-frame)
17106 (select-frame-set-input-focus cur-frame))))))
17108 (t ; Naked prompt only
17109 (unwind-protect
17110 (setq ans (read-string prompt default-input
17111 'org-read-date-history timestr))
17112 (when org-read-date-overlay
17113 (delete-overlay org-read-date-overlay)
17114 (setq org-read-date-overlay nil))))))
17116 (setq final (org-read-date-analyze ans org-def org-defdecode))
17118 (when org-read-date-analyze-forced-year
17119 (message "Year was forced into %s"
17120 (if org-read-date-force-compatible-dates
17121 "compatible range (1970-2037)"
17122 "range representable on this machine"))
17123 (ding))
17125 ;; One round trip to get rid of 34th of August and stuff like that....
17126 (setq final (decode-time (apply 'encode-time final)))
17128 (setq org-read-date-final-answer ans)
17130 (if to-time
17131 (apply 'encode-time final)
17132 (if (and (boundp 'org-time-was-given) org-time-was-given)
17133 (format "%04d-%02d-%02d %02d:%02d"
17134 (nth 5 final) (nth 4 final) (nth 3 final)
17135 (nth 2 final) (nth 1 final))
17136 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17138 (defun org-read-date-display ()
17139 "Display the current date prompt interpretation in the minibuffer."
17140 (when org-read-date-display-live
17141 (when org-read-date-overlay
17142 (delete-overlay org-read-date-overlay))
17143 (when (minibufferp (current-buffer))
17144 (save-excursion
17145 (end-of-line 1)
17146 (while (not (equal (buffer-substring
17147 (max (point-min) (- (point) 4)) (point))
17148 " "))
17149 (insert " ")))
17150 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17151 " " (or org-ans1 org-ans2)))
17152 (org-end-time-was-given nil)
17153 (f (org-read-date-analyze ans org-def org-defdecode))
17154 (fmts (if org-dcst
17155 org-time-stamp-custom-formats
17156 org-time-stamp-formats))
17157 (fmt (if (or org-with-time
17158 (and (boundp 'org-time-was-given) org-time-was-given))
17159 (cdr fmts)
17160 (car fmts)))
17161 (txt (format-time-string fmt (apply 'encode-time f)))
17162 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17163 (txt (concat "=> " txt)))
17164 (when (and org-end-time-was-given
17165 (string-match org-plain-time-of-day-regexp txt))
17166 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17167 org-end-time-was-given
17168 (substring txt (match-end 0)))))
17169 (when org-read-date-analyze-futurep
17170 (setq txt (concat txt " (=>F)")))
17171 (setq org-read-date-overlay
17172 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17173 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17175 (defun org-read-date-analyze (ans def defdecode)
17176 "Analyze the combined answer of the date prompt."
17177 ;; FIXME: cleanup and comment
17178 ;; Pass `current-time' result to `decode-time' (instead of calling
17179 ;; without arguments) so that only `current-time' has to be
17180 ;; overriden in tests.
17181 (let ((org-def def)
17182 (org-defdecode defdecode)
17183 (nowdecode (decode-time (current-time)))
17184 delta deltan deltaw deltadef year month day
17185 hour minute second wday pm h2 m2 tl wday1
17186 iso-year iso-weekday iso-week iso-date futurep kill-year)
17187 (setq org-read-date-analyze-futurep nil
17188 org-read-date-analyze-forced-year nil)
17189 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17190 (setq ans "+0"))
17192 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17193 (setq ans (replace-match "" t t ans)
17194 deltan (car delta)
17195 deltaw (nth 1 delta)
17196 deltadef (nth 2 delta)))
17198 ;; Check if there is an iso week date in there. If yes, store the
17199 ;; info and postpone interpreting it until the rest of the parsing
17200 ;; is done.
17201 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17202 (setq iso-year (when (match-end 1)
17203 (org-small-year-to-year
17204 (string-to-number (match-string 1 ans))))
17205 iso-weekday (when (match-end 3)
17206 (string-to-number (match-string 3 ans)))
17207 iso-week (string-to-number (match-string 2 ans)))
17208 (setq ans (replace-match "" t t ans)))
17210 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17211 (when (string-match
17212 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17213 (setq year (if (match-end 2)
17214 (string-to-number (match-string 2 ans))
17215 (progn (setq kill-year t)
17216 (string-to-number (format-time-string "%Y"))))
17217 month (string-to-number (match-string 3 ans))
17218 day (string-to-number (match-string 4 ans)))
17219 (setq year (org-small-year-to-year year))
17220 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17221 t nil ans)))
17223 ;; Help matching dotted european dates
17224 (when (string-match
17225 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17226 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17227 (setq kill-year t)
17228 (string-to-number (format-time-string "%Y")))
17229 day (string-to-number (match-string 1 ans))
17230 month (string-to-number (match-string 2 ans))
17231 ans (replace-match (format "%04d-%02d-%02d" year month day)
17232 t nil ans)))
17234 ;; Help matching american dates, like 5/30 or 5/30/7
17235 (when (string-match
17236 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17237 (setq year (if (match-end 4)
17238 (string-to-number (match-string 4 ans))
17239 (progn (setq kill-year t)
17240 (string-to-number (format-time-string "%Y"))))
17241 month (string-to-number (match-string 1 ans))
17242 day (string-to-number (match-string 2 ans)))
17243 (setq year (org-small-year-to-year year))
17244 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17245 t nil ans)))
17246 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17247 ;; If there is a time with am/pm, and *no* time without it, we convert
17248 ;; so that matching will be successful.
17249 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17250 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17251 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17252 (setq hour (string-to-number (match-string 1 ans))
17253 minute (if (match-end 3)
17254 (string-to-number (match-string 3 ans))
17256 pm (equal ?p
17257 (string-to-char (downcase (match-string 4 ans)))))
17258 (if (and (= hour 12) (not pm))
17259 (setq hour 0)
17260 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17261 (setq ans (replace-match (format "%02d:%02d" hour minute)
17262 t t ans))))
17264 ;; Check if a time range is given as a duration
17265 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17266 (setq hour (string-to-number (match-string 1 ans))
17267 h2 (+ hour (string-to-number (match-string 3 ans)))
17268 minute (string-to-number (match-string 2 ans))
17269 m2 (+ minute (if (match-end 5) (string-to-number
17270 (match-string 5 ans))0)))
17271 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17272 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17273 t t ans)))
17275 ;; Check if there is a time range
17276 (when (boundp 'org-end-time-was-given)
17277 (setq org-time-was-given nil)
17278 (when (and (string-match org-plain-time-of-day-regexp ans)
17279 (match-end 8))
17280 (setq org-end-time-was-given (match-string 8 ans))
17281 (setq ans (concat (substring ans 0 (match-beginning 7))
17282 (substring ans (match-end 7))))))
17284 (setq tl (parse-time-string ans)
17285 day (or (nth 3 tl) (nth 3 org-defdecode))
17286 month
17287 (cond ((nth 4 tl))
17288 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17289 ;; Day was specified. Make sure DAY+MONTH
17290 ;; combination happens in the future.
17291 ((nth 3 tl)
17292 (setq futurep t)
17293 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17294 (nth 4 nowdecode)))
17295 (t (nth 4 org-defdecode)))
17296 year
17297 (cond ((and (not kill-year) (nth 5 tl)))
17298 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17299 ;; Month was guessed in the future and is at least
17300 ;; equal to NOWDECODE's. Fix year accordingly.
17301 (futurep
17302 (if (or (> month (nth 4 nowdecode))
17303 (>= day (nth 3 nowdecode)))
17304 (nth 5 nowdecode)
17305 (1+ (nth 5 nowdecode))))
17306 ;; Month was specified. Make sure MONTH+YEAR
17307 ;; combination happens in the future.
17308 ((nth 4 tl)
17309 (setq futurep t)
17310 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17311 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17312 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17313 (t (nth 5 nowdecode))))
17314 (t (nth 5 org-defdecode)))
17315 hour (or (nth 2 tl) (nth 2 org-defdecode))
17316 minute (or (nth 1 tl) (nth 1 org-defdecode))
17317 second (or (nth 0 tl) 0)
17318 wday (nth 6 tl))
17320 (when (and (eq org-read-date-prefer-future 'time)
17321 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17322 (equal day (nth 3 nowdecode))
17323 (equal month (nth 4 nowdecode))
17324 (equal year (nth 5 nowdecode))
17325 (nth 2 tl)
17326 (or (< (nth 2 tl) (nth 2 nowdecode))
17327 (and (= (nth 2 tl) (nth 2 nowdecode))
17328 (nth 1 tl)
17329 (< (nth 1 tl) (nth 1 nowdecode)))))
17330 (setq day (1+ day)
17331 futurep t))
17333 ;; Special date definitions below
17334 (cond
17335 (iso-week
17336 ;; There was an iso week
17337 (require 'cal-iso)
17338 (setq futurep nil)
17339 (setq year (or iso-year year)
17340 day (or iso-weekday wday 1)
17341 wday nil ; to make sure that the trigger below does not match
17342 iso-date (calendar-gregorian-from-absolute
17343 (calendar-iso-to-absolute
17344 (list iso-week day year))))
17345 ; FIXME: Should we also push ISO weeks into the future?
17346 ; (when (and org-read-date-prefer-future
17347 ; (not iso-year)
17348 ; (< (calendar-absolute-from-gregorian iso-date)
17349 ; (time-to-days (current-time))))
17350 ; (setq year (1+ year)
17351 ; iso-date (calendar-gregorian-from-absolute
17352 ; (calendar-iso-to-absolute
17353 ; (list iso-week day year)))))
17354 (setq month (car iso-date)
17355 year (nth 2 iso-date)
17356 day (nth 1 iso-date)))
17357 (deltan
17358 (setq futurep nil)
17359 (unless deltadef
17360 ;; Pass `current-time' result to `decode-time' (instead of
17361 ;; calling without arguments) so that only `current-time' has
17362 ;; to be overriden in tests.
17363 (let ((now (decode-time (current-time))))
17364 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17365 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17366 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17367 ((equal deltaw "m") (setq month (+ month deltan)))
17368 ((equal deltaw "y") (setq year (+ year deltan)))))
17369 ((and wday (not (nth 3 tl)))
17370 ;; Weekday was given, but no day, so pick that day in the week
17371 ;; on or after the derived date.
17372 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17373 (unless (equal wday wday1)
17374 (setq day (+ day (% (- wday wday1 -7) 7))))))
17375 (when (and (boundp 'org-time-was-given)
17376 (nth 2 tl))
17377 (setq org-time-was-given t))
17378 (when (< year 100) (setq year (+ 2000 year)))
17379 ;; Check of the date is representable
17380 (if org-read-date-force-compatible-dates
17381 (progn
17382 (when (< year 1970)
17383 (setq year 1970 org-read-date-analyze-forced-year t))
17384 (when (> year 2037)
17385 (setq year 2037 org-read-date-analyze-forced-year t)))
17386 (condition-case nil
17387 (ignore (encode-time second minute hour day month year))
17388 (error
17389 (setq year (nth 5 org-defdecode))
17390 (setq org-read-date-analyze-forced-year t))))
17391 (setq org-read-date-analyze-futurep futurep)
17392 (list second minute hour day month year)))
17394 (defvar parse-time-weekdays)
17395 (defun org-read-date-get-relative (s today default)
17396 "Check string S for special relative date string.
17397 TODAY and DEFAULT are internal times, for today and for a default.
17398 Return shift list (N what def-flag)
17399 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17400 N is the number of WHATs to shift.
17401 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17402 the DEFAULT date rather than TODAY."
17403 (require 'parse-time)
17404 (when (and
17405 (string-match
17406 (concat
17407 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17408 "\\([0-9]+\\)?"
17409 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17410 "\\([ \t]\\|$\\)") s)
17411 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17412 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17413 (string-to-char (substring (match-string 1 s) -1))
17414 ?+))
17415 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17416 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17417 (what (if (match-end 3) (match-string 3 s) "d"))
17418 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17419 (date (if rel default today))
17420 (wday (nth 6 (decode-time date)))
17421 delta)
17422 (if wday1
17423 (progn
17424 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17425 (when (= delta 0) (setq delta 7))
17426 (when (= dir ?-)
17427 (setq delta (- delta 7))
17428 (when (= delta 0) (setq delta -7)))
17429 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17430 (list delta "d" rel))
17431 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17433 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17434 "Turn a user-specified date into the internal representation.
17435 The internal representation needed by the calendar is (month day year).
17436 This is a wrapper to handle the brain-dead convention in calendar that
17437 user function argument order change dependent on argument order."
17438 (pcase calendar-date-style
17439 (`american (list arg1 arg2 arg3))
17440 (`european (list arg2 arg1 arg3))
17441 (`iso (list arg2 arg3 arg1))))
17443 (defun org-eval-in-calendar (form &optional keepdate)
17444 "Eval FORM in the calendar window and return to current window.
17445 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17446 (let ((sf (selected-frame))
17447 (sw (selected-window)))
17448 (select-window (get-buffer-window "*Calendar*" t))
17449 (eval form)
17450 (when (and (not keepdate) (calendar-cursor-to-date))
17451 (let* ((date (calendar-cursor-to-date))
17452 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17453 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17454 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17455 (select-window sw)
17456 (select-frame-set-input-focus sf)))
17458 (defun org-calendar-select ()
17459 "Return to `org-read-date' with the date currently selected.
17460 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17461 (interactive)
17462 (when (calendar-cursor-to-date)
17463 (let* ((date (calendar-cursor-to-date))
17464 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17465 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17466 (when (active-minibuffer-window) (exit-minibuffer))))
17468 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17469 "Insert a date stamp for the date given by the internal TIME.
17470 See `format-time-string' for the format of TIME.
17471 WITH-HM means use the stamp format that includes the time of the day.
17472 INACTIVE means use square brackets instead of angular ones, so that the
17473 stamp will not contribute to the agenda.
17474 PRE and POST are optional strings to be inserted before and after the
17475 stamp.
17476 The command returns the inserted time stamp."
17477 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17478 stamp)
17479 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17480 (insert-before-markers (or pre ""))
17481 (when (listp extra)
17482 (setq extra (car extra))
17483 (if (and (stringp extra)
17484 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17485 (setq extra (format "-%02d:%02d"
17486 (string-to-number (match-string 1 extra))
17487 (string-to-number (match-string 2 extra))))
17488 (setq extra nil)))
17489 (when extra
17490 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17491 (insert-before-markers (setq stamp (format-time-string fmt time)))
17492 (insert-before-markers (or post ""))
17493 (setq org-last-inserted-timestamp stamp)))
17495 (defun org-toggle-time-stamp-overlays ()
17496 "Toggle the use of custom time stamp formats."
17497 (interactive)
17498 (setq org-display-custom-times (not org-display-custom-times))
17499 (unless org-display-custom-times
17500 (let ((p (point-min)) (bmp (buffer-modified-p)))
17501 (while (setq p (next-single-property-change p 'display))
17502 (when (and (get-text-property p 'display)
17503 (eq (get-text-property p 'face) 'org-date))
17504 (remove-text-properties
17505 p (setq p (next-single-property-change p 'display))
17506 '(display t))))
17507 (set-buffer-modified-p bmp)))
17508 (org-restart-font-lock)
17509 (setq org-table-may-need-update t)
17510 (if org-display-custom-times
17511 (message "Time stamps are overlaid with custom format")
17512 (message "Time stamp overlays removed")))
17514 (defun org-display-custom-time (beg end)
17515 "Overlay modified time stamp format over timestamp between BEG and END."
17516 (let* ((ts (buffer-substring beg end))
17517 t1 w1 with-hm tf time str w2 (off 0))
17518 (save-match-data
17519 (setq t1 (org-parse-time-string ts t))
17520 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17521 (setq off (- (match-end 0) (match-beginning 0)))))
17522 (setq end (- end off))
17523 (setq w1 (- end beg)
17524 with-hm (and (nth 1 t1) (nth 2 t1))
17525 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17526 time (org-fix-decoded-time t1)
17527 str (org-add-props
17528 (format-time-string
17529 (substring tf 1 -1) (apply 'encode-time time))
17530 nil 'mouse-face 'highlight)
17531 w2 (length str))
17532 (unless (= w2 w1)
17533 (add-text-properties (1+ beg) (+ 2 beg)
17534 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17535 (put-text-property beg end 'display str)))
17537 (defun org-fix-decoded-time (time)
17538 "Set 0 instead of nil for the first 6 elements of time.
17539 Don't touch the rest."
17540 (let ((n 0))
17541 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17543 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17544 "Difference between TIMESTAMP-STRING and now in days.
17545 If SECONDS is non-nil, return the difference in seconds."
17546 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17547 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17548 (funcall fdiff (current-time)))))
17550 (defun org-deadline-close-p (timestamp-string &optional ndays)
17551 "Is the time in TIMESTAMP-STRING close to the current date?"
17552 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17553 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17554 (not (org-entry-is-done-p))))
17556 (defun org-get-wdays (ts &optional delay zero-delay)
17557 "Get the deadline lead time appropriate for timestring TS.
17558 When DELAY is non-nil, get the delay time for scheduled items
17559 instead of the deadline lead time. When ZERO-DELAY is non-nil
17560 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17561 don't try to find the delay cookie in the scheduled timestamp."
17562 (let ((tv (if delay org-scheduled-delay-days
17563 org-deadline-warning-days)))
17564 (cond
17565 ((or (and delay (< tv 0))
17566 (and delay zero-delay (<= tv 0))
17567 (and (not delay) (<= tv 0)))
17568 ;; Enforce this value no matter what
17569 (- tv))
17570 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17571 ;; lead time is specified.
17572 (floor (* (string-to-number (match-string 1 ts))
17573 (cdr (assoc (match-string 2 ts)
17574 '(("d" . 1) ("w" . 7)
17575 ("m" . 30.4) ("y" . 365.25)
17576 ("h" . 0.041667)))))))
17577 ;; go for the default.
17578 (t tv))))
17580 (defun org-calendar-select-mouse (ev)
17581 "Return to `org-read-date' with the date currently selected.
17582 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17583 (interactive "e")
17584 (mouse-set-point ev)
17585 (when (calendar-cursor-to-date)
17586 (let* ((date (calendar-cursor-to-date))
17587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17588 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17589 (when (active-minibuffer-window) (exit-minibuffer))))
17591 (defun org-check-deadlines (ndays)
17592 "Check if there are any deadlines due or past due.
17593 A deadline is considered due if it happens within `org-deadline-warning-days'
17594 days from today's date. If the deadline appears in an entry marked DONE,
17595 it is not shown. The prefix arg NDAYS can be used to test that many
17596 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17597 (interactive "P")
17598 (let* ((org-warn-days
17599 (cond
17600 ((equal ndays '(4)) 100000)
17601 (ndays (prefix-numeric-value ndays))
17602 (t (abs org-deadline-warning-days))))
17603 (case-fold-search nil)
17604 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17605 (callback
17606 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17607 (message "%d deadlines past-due or due within %d days"
17608 (org-occur regexp nil callback)
17609 org-warn-days)))
17611 (defsubst org-re-timestamp (type)
17612 "Return a regexp for timestamp TYPE.
17613 Allowed values for TYPE are:
17615 all: all timestamps
17616 active: only active timestamps (<...>)
17617 inactive: only inactive timestamps ([...])
17618 scheduled: only scheduled timestamps
17619 deadline: only deadline timestamps
17620 closed: only closed time-stamps
17622 When TYPE is nil, fall back on returning a regexp that matches
17623 both scheduled and deadline timestamps."
17624 (cl-case type
17625 (all org-ts-regexp-both)
17626 (active org-ts-regexp)
17627 (inactive org-ts-regexp-inactive)
17628 (scheduled org-scheduled-time-regexp)
17629 (deadline org-deadline-time-regexp)
17630 (closed org-closed-time-regexp)
17631 (otherwise
17632 (concat "\\<"
17633 (regexp-opt (list org-deadline-string org-scheduled-string))
17634 " *<\\([^>]+\\)>"))))
17636 (defun org-check-before-date (d)
17637 "Check if there are deadlines or scheduled entries before date D."
17638 (interactive (list (org-read-date)))
17639 (let* ((case-fold-search nil)
17640 (regexp (org-re-timestamp org-ts-type))
17641 (ts-type org-ts-type)
17642 (callback
17643 (lambda ()
17644 (let ((match (match-string 1)))
17645 (and (if (memq ts-type '(active inactive all))
17646 (eq (org-element-type (save-excursion
17647 (backward-char)
17648 (org-element-context)))
17649 'timestamp)
17650 (org-at-planning-p))
17651 (time-less-p
17652 (org-time-string-to-time match)
17653 (org-time-string-to-time d)))))))
17654 (message "%d entries before %s"
17655 (org-occur regexp nil callback)
17656 d)))
17658 (defun org-check-after-date (d)
17659 "Check if there are deadlines or scheduled entries after date D."
17660 (interactive (list (org-read-date)))
17661 (let* ((case-fold-search nil)
17662 (regexp (org-re-timestamp org-ts-type))
17663 (ts-type org-ts-type)
17664 (callback
17665 (lambda ()
17666 (let ((match (match-string 1)))
17667 (and (if (memq ts-type '(active inactive all))
17668 (eq (org-element-type (save-excursion
17669 (backward-char)
17670 (org-element-context)))
17671 'timestamp)
17672 (org-at-planning-p))
17673 (not (time-less-p
17674 (org-time-string-to-time match)
17675 (org-time-string-to-time d))))))))
17676 (message "%d entries after %s"
17677 (org-occur regexp nil callback)
17678 d)))
17680 (defun org-check-dates-range (start-date end-date)
17681 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17682 (interactive (list (org-read-date nil nil nil "Range starts")
17683 (org-read-date nil nil nil "Range end")))
17684 (let ((case-fold-search nil)
17685 (regexp (org-re-timestamp org-ts-type))
17686 (callback
17687 (let ((type org-ts-type))
17688 (lambda ()
17689 (let ((match (match-string 1)))
17690 (and
17691 (if (memq type '(active inactive all))
17692 (eq (org-element-type (save-excursion
17693 (backward-char)
17694 (org-element-context)))
17695 'timestamp)
17696 (org-at-planning-p))
17697 (not (time-less-p
17698 (org-time-string-to-time match)
17699 (org-time-string-to-time start-date)))
17700 (time-less-p
17701 (org-time-string-to-time match)
17702 (org-time-string-to-time end-date))))))))
17703 (message "%d entries between %s and %s"
17704 (org-occur regexp nil callback) start-date end-date)))
17706 (defun org-evaluate-time-range (&optional to-buffer)
17707 "Evaluate a time range by computing the difference between start and end.
17708 Normally the result is just printed in the echo area, but with prefix arg
17709 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17710 If the time range is actually in a table, the result is inserted into the
17711 next column.
17712 For time difference computation, a year is assumed to be exactly 365
17713 days in order to avoid rounding problems."
17714 (interactive "P")
17716 (org-clock-update-time-maybe)
17717 (save-excursion
17718 (unless (org-at-date-range-p t)
17719 (goto-char (point-at-bol))
17720 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17721 (unless (org-at-date-range-p t)
17722 (user-error "Not at a time-stamp range, and none found in current line")))
17723 (let* ((ts1 (match-string 1))
17724 (ts2 (match-string 2))
17725 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17726 (match-end (match-end 0))
17727 (time1 (org-time-string-to-time ts1))
17728 (time2 (org-time-string-to-time ts2))
17729 (t1 (float-time time1))
17730 (t2 (float-time time2))
17731 (diff (abs (- t2 t1)))
17732 (negative (< (- t2 t1) 0))
17733 ;; (ys (floor (* 365 24 60 60)))
17734 (ds (* 24 60 60))
17735 (hs (* 60 60))
17736 (fy "%dy %dd %02d:%02d")
17737 (fy1 "%dy %dd")
17738 (fd "%dd %02d:%02d")
17739 (fd1 "%dd")
17740 (fh "%02d:%02d")
17741 y d h m align)
17742 (if havetime
17743 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17745 d (floor (/ diff ds)) diff (mod diff ds)
17746 h (floor (/ diff hs)) diff (mod diff hs)
17747 m (floor (/ diff 60)))
17748 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17750 d (floor (+ (/ diff ds) 0.5))
17751 h 0 m 0))
17752 (if (not to-buffer)
17753 (message "%s" (org-make-tdiff-string y d h m))
17754 (if (org-at-table-p)
17755 (progn
17756 (goto-char match-end)
17757 (setq align t)
17758 (and (looking-at " *|") (goto-char (match-end 0))))
17759 (goto-char match-end))
17760 (when (looking-at
17761 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17762 (replace-match ""))
17763 (when negative (insert " -"))
17764 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17765 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17766 (insert " " (format fh h m))))
17767 (when align (org-table-align))
17768 (message "Time difference inserted")))))
17770 (defun org-make-tdiff-string (y d h m)
17771 (let ((fmt "")
17772 (l nil))
17773 (when (> y 0)
17774 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17775 (push y l))
17776 (when (> d 0)
17777 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17778 (push d l))
17779 (when (> h 0)
17780 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17781 (push h l))
17782 (when (> m 0)
17783 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17784 (push m l))
17785 (apply 'format fmt (nreverse l))))
17787 (defun org-time-string-to-time (s &optional buffer pos)
17788 "Convert a timestamp string into internal time."
17789 (condition-case errdata
17790 (apply 'encode-time (org-parse-time-string s))
17791 (error (error "Bad timestamp `%s'%s\nError was: %s"
17792 s (if (not (and buffer pos))
17794 (format-message " at %d in buffer `%s'" pos buffer))
17795 (cdr errdata)))))
17797 (defun org-time-string-to-seconds (s)
17798 "Convert a timestamp string to a number of seconds."
17799 (float-time (org-time-string-to-time s)))
17801 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17803 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17804 "Convert time stamp S to an absolute day number.
17806 If DAYNR in non-nil, and there is a specifier for a cyclic time
17807 stamp, get the closest date to DAYNR. If PREFER is
17808 `past' (respectively `future') return a date past (respectively
17809 after) or equal to DAYNR.
17811 POS is the location of time stamp S, as a buffer position in
17812 BUFFER.
17814 Diary sexp timestamps are matched against DAYNR, when non-nil.
17815 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17816 signalled."
17817 (cond
17818 ((string-match "\\`%%\\((.*)\\)" s)
17819 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17820 ;; only able to match individual dates. If it fails, raise an
17821 ;; error.
17822 (if (and daynr
17823 (org-diary-sexp-entry
17824 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17825 daynr
17826 (signal 'org-diary-sexp-no-match (list s))))
17827 ((and daynr show-all) (org-closest-date s daynr prefer))
17828 (t (time-to-days
17829 (condition-case errdata
17830 (apply #'encode-time (org-parse-time-string s))
17831 (error (error "Bad timestamp `%s'%s\nError was: %s"
17833 (if (not (and buffer pos)) ""
17834 (format-message " at %d in buffer `%s'" pos buffer))
17835 (cdr errdata))))))))
17837 (defun org-days-to-iso-week (days)
17838 "Return the iso week number."
17839 (require 'cal-iso)
17840 (car (calendar-iso-from-absolute days)))
17842 (defun org-small-year-to-year (year)
17843 "Convert 2-digit years into 4-digit years.
17844 YEAR is expanded into one of the 30 next years, if possible, or
17845 into a past one. Any year larger than 99 is returned unchanged."
17846 (if (>= year 100) year
17847 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17848 (century (/ current 100))
17849 (offset (- year (% current 100))))
17850 (cond ((> offset 30) (+ (* (1- century) 100) year))
17851 ((> offset -70) (+ (* century 100) year))
17852 (t (+ (* (1+ century) 100) year))))))
17854 (defun org-time-from-absolute (d)
17855 "Return the time corresponding to date D.
17856 D may be an absolute day number, or a calendar-type list (month day year)."
17857 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17858 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17860 (defvar org-agenda-current-date)
17861 (defun org-calendar-holiday ()
17862 "List of holidays, for Diary display in Org mode."
17863 (require 'holidays)
17864 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17865 (and hl (mapconcat #'identity hl "; "))))
17867 (defun org-diary-sexp-entry (sexp entry d)
17868 "Process a SEXP diary ENTRY for date D."
17869 (require 'diary-lib)
17870 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17871 ;; dynamically.
17872 (let* ((sexp `(let ((entry ,entry)
17873 (date ',d))
17874 ,(car (read-from-string sexp))))
17875 (result (if calendar-debug-sexp (eval sexp)
17876 (condition-case nil
17877 (eval sexp)
17878 (error
17879 (beep)
17880 (message "Bad sexp at line %d in %s: %s"
17881 (org-current-line)
17882 (buffer-file-name) sexp)
17883 (sleep-for 2))))))
17884 (cond ((stringp result) (split-string result "; "))
17885 ((and (consp result)
17886 (not (consp (cdr result)))
17887 (stringp (cdr result))) (cdr result))
17888 ((and (consp result)
17889 (stringp (car result))) result)
17890 (result entry))))
17892 (defun org-diary-to-ical-string (frombuf)
17893 "Get iCalendar entries from diary entries in buffer FROMBUF.
17894 This uses the icalendar.el library."
17895 (let* ((tmpdir temporary-file-directory)
17896 (tmpfile (make-temp-name
17897 (expand-file-name "orgics" tmpdir)))
17898 buf rtn b e)
17899 (with-current-buffer frombuf
17900 (icalendar-export-region (point-min) (point-max) tmpfile)
17901 (setq buf (find-buffer-visiting tmpfile))
17902 (set-buffer buf)
17903 (goto-char (point-min))
17904 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17905 (setq b (match-beginning 0)))
17906 (goto-char (point-max))
17907 (when (re-search-backward "^END:VEVENT" nil t)
17908 (setq e (match-end 0)))
17909 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17910 (kill-buffer buf)
17911 (delete-file tmpfile)
17912 rtn))
17914 (defun org-closest-date (start current prefer)
17915 "Return closest date to CURRENT starting from START.
17917 CURRENT and START are both time stamps.
17919 When PREFER is `past', return a date that is either CURRENT or
17920 past. When PREFER is `future', return a date that is either
17921 CURRENT or future.
17923 Only time stamps with a repeater are modified. Any other time
17924 stamp stay unchanged. In any case, return value is an absolute
17925 day number."
17926 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17927 ;; No repeater. Do not shift time stamp.
17928 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17929 (let ((value (string-to-number (match-string 1 start)))
17930 (type (match-string 2 start)))
17931 (if (= 0 value)
17932 ;; Repeater with a 0-value is considered as void.
17933 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17934 (let* ((base (org-date-to-gregorian start))
17935 (target (org-date-to-gregorian current))
17936 (sday (calendar-absolute-from-gregorian base))
17937 (cday (calendar-absolute-from-gregorian target))
17938 n1 n2)
17939 ;; If START is already past CURRENT, just return START.
17940 (if (<= cday sday) sday
17941 ;; Compute closest date before (N1) and closest date past
17942 ;; (N2) CURRENT.
17943 (pcase type
17944 ("h"
17945 (let ((missing-hours
17946 (mod (+ (- (* 24 (- cday sday))
17947 (nth 2 (org-parse-time-string start)))
17948 org-extend-today-until)
17949 value)))
17950 (setf n1 (if (= missing-hours 0) cday
17951 (- cday (1+ (/ missing-hours 24)))))
17952 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17953 ((or "d" "w")
17954 (let ((value (if (equal type "w") (* 7 value) value)))
17955 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17956 (setf n2 (+ n1 value))))
17957 ("m"
17958 (let* ((add-months
17959 (lambda (d n)
17960 ;; Add N months to gregorian date D, i.e.,
17961 ;; a list (MONTH DAY YEAR). Return a valid
17962 ;; gregorian date.
17963 (let ((m (+ (nth 0 d) n)))
17964 (list (mod m 12)
17965 (nth 1 d)
17966 (+ (/ m 12) (nth 2 d))))))
17967 (months ; Complete months to TARGET.
17968 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17969 (- (nth 0 target) (nth 0 base))
17970 ;; If START's day is greater than
17971 ;; TARGET's, remove incomplete month.
17972 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17973 value)
17974 value))
17975 (before (funcall add-months base months)))
17976 (setf n1 (calendar-absolute-from-gregorian before))
17977 (setf n2
17978 (calendar-absolute-from-gregorian
17979 (funcall add-months before value)))))
17981 (let* ((d (nth 1 base))
17982 (m (nth 0 base))
17983 (y (nth 2 base))
17984 (years ; Complete years to TARGET.
17985 (* (/ (- (nth 2 target)
17987 ;; If START's month and day are
17988 ;; greater than TARGET's, remove
17989 ;; incomplete year.
17990 (if (or (> (nth 0 target) m)
17991 (and (= (nth 0 target) m)
17992 (> (nth 1 target) d)))
17995 value)
17996 value))
17997 (before (list m d (+ y years))))
17998 (setf n1 (calendar-absolute-from-gregorian before))
17999 (setf n2 (calendar-absolute-from-gregorian
18000 (list m d (+ (nth 2 before) value)))))))
18001 ;; Handle PREFER parameter, if any.
18002 (cond
18003 ((eq prefer 'past) (if (= cday n2) n2 n1))
18004 ((eq prefer 'future) (if (= cday n1) n1 n2))
18005 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18007 (defun org-date-to-gregorian (d)
18008 "Turn any specification of date D into a Gregorian date for the calendar."
18009 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18010 ((and (listp d) (= (length d) 3)) d)
18011 ((stringp d)
18012 (let ((d (org-parse-time-string d)))
18013 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18014 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18016 (defun org-parse-time-string (s &optional nodefault)
18017 "Parse the standard Org-mode time string.
18018 This should be a lot faster than the normal `parse-time-string'.
18019 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18020 hour and minute fields will be nil if not given."
18021 (cond ((string-match org-ts-regexp0 s)
18022 (list 0
18023 (when (or (match-beginning 8) (not nodefault))
18024 (string-to-number (or (match-string 8 s) "0")))
18025 (when (or (match-beginning 7) (not nodefault))
18026 (string-to-number (or (match-string 7 s) "0")))
18027 (string-to-number (match-string 4 s))
18028 (string-to-number (match-string 3 s))
18029 (string-to-number (match-string 2 s))
18030 nil nil nil))
18031 ((string-match "^<[^>]+>$" s)
18032 (decode-time (seconds-to-time (org-matcher-time s))))
18033 (t (error "Not a standard Org-mode time string: %s" s))))
18035 (defun org-timestamp-up (&optional arg)
18036 "Increase the date item at the cursor by one.
18037 If the cursor is on the year, change the year. If it is on the month,
18038 the day or the time, change that.
18039 With prefix ARG, change by that many units."
18040 (interactive "p")
18041 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18043 (defun org-timestamp-down (&optional arg)
18044 "Decrease the date item at the cursor by one.
18045 If the cursor is on the year, change the year. If it is on the month,
18046 the day or the time, change that.
18047 With prefix ARG, change by that many units."
18048 (interactive "p")
18049 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18051 (defun org-timestamp-up-day (&optional arg)
18052 "Increase the date in the time stamp by one day.
18053 With prefix ARG, change that many days."
18054 (interactive "p")
18055 (if (and (not (org-at-timestamp-p t))
18056 (org-at-heading-p))
18057 (org-todo 'up)
18058 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18060 (defun org-timestamp-down-day (&optional arg)
18061 "Decrease the date in the time stamp by one day.
18062 With prefix ARG, change that many days."
18063 (interactive "p")
18064 (if (and (not (org-at-timestamp-p t))
18065 (org-at-heading-p))
18066 (org-todo 'down)
18067 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18069 (defun org-at-timestamp-p (&optional inactive-ok)
18070 "Non-nil if point is inside a timestamp.
18072 When optional argument INACTIVE-OK is non-nil, also consider
18073 inactive timestamps.
18075 When this function returns a non-nil value, match data is set
18076 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18077 INACTIVE-OK."
18078 (interactive)
18079 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18080 (pos (point))
18081 (ans (or (looking-at tsr)
18082 (save-excursion
18083 (skip-chars-backward "^[<\n\r\t")
18084 (when (> (point) (point-min)) (backward-char 1))
18085 (and (looking-at tsr)
18086 (> (- (match-end 0) pos) -1))))))
18087 (and ans
18088 (boundp 'org-ts-what)
18089 (setq org-ts-what
18090 (cond
18091 ((= pos (match-beginning 0)) 'bracket)
18092 ;; Point is considered to be "on the bracket" whether
18093 ;; it's really on it or right after it.
18094 ((= pos (1- (match-end 0))) 'bracket)
18095 ((= pos (match-end 0)) 'after)
18096 ((org-pos-in-match-range pos 2) 'year)
18097 ((org-pos-in-match-range pos 3) 'month)
18098 ((org-pos-in-match-range pos 7) 'hour)
18099 ((org-pos-in-match-range pos 8) 'minute)
18100 ((or (org-pos-in-match-range pos 4)
18101 (org-pos-in-match-range pos 5)) 'day)
18102 ((and (> pos (or (match-end 8) (match-end 5)))
18103 (< pos (match-end 0)))
18104 (- pos (or (match-end 8) (match-end 5))))
18105 (t 'day))))
18106 ans))
18108 (defun org-toggle-timestamp-type ()
18109 "Toggle the type (<active> or [inactive]) of a time stamp."
18110 (interactive)
18111 (when (org-at-timestamp-p t)
18112 (let ((beg (match-beginning 0)) (end (match-end 0))
18113 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18114 (save-excursion
18115 (goto-char beg)
18116 (while (re-search-forward "[][<>]" end t)
18117 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18118 t t)))
18119 (message "Timestamp is now %sactive"
18120 (if (equal (char-after beg) ?<) "" "in")))))
18122 (defun org-at-clock-log-p nil
18123 "Is the cursor on the clock log line?"
18124 (save-excursion
18125 (move-beginning-of-line 1)
18126 (looking-at org-clock-line-re)))
18128 (defvar org-clock-history) ; defined in org-clock.el
18129 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18130 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18131 "Change the date in the time stamp at point.
18132 The date will be changed by N times WHAT. WHAT can be `day', `month',
18133 `year', `minute', `second'. If WHAT is not given, the cursor position
18134 in the timestamp determines what will be changed.
18135 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18136 (let ((origin (point)) origin-cat
18137 with-hm inactive
18138 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18139 org-ts-what
18140 extra rem
18141 ts time time0 fixnext clrgx)
18142 (unless (org-at-timestamp-p t)
18143 (user-error "Not at a timestamp"))
18144 (if (and (not what) (eq org-ts-what 'bracket))
18145 (org-toggle-timestamp-type)
18146 ;; Point isn't on brackets. Remember the part of the time-stamp
18147 ;; the point was in. Indeed, size of time-stamps may change,
18148 ;; but point must be kept in the same category nonetheless.
18149 (setq origin-cat org-ts-what)
18150 (when (and (not what) (not (eq org-ts-what 'day))
18151 org-display-custom-times
18152 (get-text-property (point) 'display)
18153 (not (get-text-property (1- (point)) 'display)))
18154 (setq org-ts-what 'day))
18155 (setq org-ts-what (or what org-ts-what)
18156 inactive (= (char-after (match-beginning 0)) ?\[)
18157 ts (match-string 0))
18158 (replace-match "")
18159 (when (string-match
18160 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18162 (setq extra (match-string 1 ts))
18163 (when suppress-tmp-delay
18164 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18165 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18166 (setq with-hm t))
18167 (setq time0 (org-parse-time-string ts))
18168 (when (and updown
18169 (eq org-ts-what 'minute)
18170 (not current-prefix-arg))
18171 ;; This looks like s-up and s-down. Change by one rounding step.
18172 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18173 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18174 (setcar (cdr time0) (+ (nth 1 time0)
18175 (if (> n 0) (- rem) (- dm rem))))))
18176 (setq time
18177 (apply #'encode-time
18178 (or (car time0) 0)
18179 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18180 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18181 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18182 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18183 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18184 (nthcdr 6 time0)))
18185 (when (and (member org-ts-what '(hour minute))
18186 extra
18187 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18188 (setq extra (org-modify-ts-extra
18189 extra
18190 (if (eq org-ts-what 'hour) 2 5)
18191 n dm)))
18192 (when (integerp org-ts-what)
18193 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18194 (when (eq what 'calendar)
18195 (let ((cal-date (org-get-date-from-calendar)))
18196 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18197 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18198 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18199 (setcar time0 (or (car time0) 0))
18200 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18201 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18202 (setq time (apply 'encode-time time0))))
18203 ;; Insert the new time-stamp, and ensure point stays in the same
18204 ;; category as before (i.e. not after the last position in that
18205 ;; category).
18206 (let ((pos (point)))
18207 ;; Stay before inserted string. `save-excursion' is of no use.
18208 (setq org-last-changed-timestamp
18209 (org-insert-time-stamp time with-hm inactive nil nil extra))
18210 (goto-char pos))
18211 (save-match-data
18212 (looking-at org-ts-regexp3)
18213 (goto-char (cond
18214 ;; `day' category ends before `hour' if any, or at
18215 ;; the end of the day name.
18216 ((eq origin-cat 'day)
18217 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18218 ((eq origin-cat 'hour) (min (match-end 7) origin))
18219 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18220 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18221 ;; `year' and `month' have both fixed size: point
18222 ;; couldn't have moved into another part.
18223 (t origin))))
18224 ;; Update clock if on a CLOCK line.
18225 (org-clock-update-time-maybe)
18226 ;; Maybe adjust the closest clock in `org-clock-history'
18227 (when org-clock-adjust-closest
18228 (if (not (and (org-at-clock-log-p)
18229 (< 1 (length (delq nil (mapcar 'marker-position
18230 org-clock-history))))))
18231 (message "No clock to adjust")
18232 (cond ((save-excursion ; fix previous clock?
18233 (re-search-backward org-ts-regexp0 nil t)
18234 (looking-back (concat org-clock-string " \\[")
18235 (line-beginning-position)))
18236 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18237 ((save-excursion ; fix next clock?
18238 (re-search-backward org-ts-regexp0 nil t)
18239 (looking-at (concat org-ts-regexp0 "\\] =>")))
18240 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18241 (save-window-excursion
18242 ;; Find closest clock to point, adjust the previous/next one in history
18243 (let* ((p (save-excursion (org-back-to-heading t)))
18244 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18245 (clfixnth
18246 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18247 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18248 (if (not clfixpos)
18249 (message "No clock to adjust")
18250 (save-excursion
18251 (org-goto-marker-or-bmk clfixpos)
18252 (org-show-subtree)
18253 (when (re-search-forward clrgx nil t)
18254 (goto-char (match-beginning 1))
18255 (let (org-clock-adjust-closest)
18256 (org-timestamp-change n org-ts-what updown))
18257 (message "Clock adjusted in %s for heading: %s"
18258 (file-name-nondirectory (buffer-file-name))
18259 (org-get-heading t t)))))))))
18260 ;; Try to recenter the calendar window, if any.
18261 (when (and org-calendar-follow-timestamp-change
18262 (get-buffer-window "*Calendar*" t)
18263 (memq org-ts-what '(day month year)))
18264 (org-recenter-calendar (time-to-days time))))))
18266 (defun org-modify-ts-extra (s pos n dm)
18267 "Change the different parts of the lead-time and repeat fields in timestamp."
18268 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18269 ng h m new rem)
18270 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18271 (cond
18272 ((or (org-pos-in-match-range pos 2)
18273 (org-pos-in-match-range pos 3))
18274 (setq m (string-to-number (match-string 3 s))
18275 h (string-to-number (match-string 2 s)))
18276 (if (org-pos-in-match-range pos 2)
18277 (setq h (+ h n))
18278 (setq n (* dm (with-no-warnings (signum n))))
18279 (unless (= 0 (setq rem (% m dm)))
18280 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18281 (setq m (+ m n)))
18282 (when (< m 0) (setq m (+ m 60) h (1- h)))
18283 (when (> m 59) (setq m (- m 60) h (1+ h)))
18284 (setq h (mod h 24))
18285 (setq ng 1 new (format "-%02d:%02d" h m)))
18286 ((org-pos-in-match-range pos 6)
18287 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18288 ((org-pos-in-match-range pos 5)
18289 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18291 ((org-pos-in-match-range pos 9)
18292 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18293 ((org-pos-in-match-range pos 8)
18294 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18296 (when ng
18297 (setq s (concat
18298 (substring s 0 (match-beginning ng))
18300 (substring s (match-end ng))))))
18303 (defun org-recenter-calendar (d)
18304 "If the calendar is visible, recenter it to date D."
18305 (let ((cwin (get-buffer-window "*Calendar*" t)))
18306 (when cwin
18307 (let ((calendar-move-hook nil))
18308 (with-selected-window cwin
18309 (calendar-goto-date
18310 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18312 (defun org-goto-calendar (&optional arg)
18313 "Go to the Emacs calendar at the current date.
18314 If there is a time stamp in the current line, go to that date.
18315 A prefix ARG can be used to force the current date."
18316 (interactive "P")
18317 (let ((tsr org-ts-regexp) diff
18318 (calendar-move-hook nil)
18319 (calendar-view-holidays-initially-flag nil)
18320 (calendar-view-diary-initially-flag nil))
18321 (when (or (org-at-timestamp-p)
18322 (save-excursion
18323 (beginning-of-line 1)
18324 (looking-at (concat ".*" tsr))))
18325 (let ((d1 (time-to-days (current-time)))
18326 (d2 (time-to-days
18327 (org-time-string-to-time (match-string 1)))))
18328 (setq diff (- d2 d1))))
18329 (calendar)
18330 (calendar-goto-today)
18331 (when (and diff (not arg)) (calendar-forward-day diff))))
18333 (defun org-get-date-from-calendar ()
18334 "Return a list (month day year) of date at point in calendar."
18335 (with-current-buffer "*Calendar*"
18336 (save-match-data
18337 (calendar-cursor-to-date))))
18339 (defun org-date-from-calendar ()
18340 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18341 If there is already a time stamp at the cursor position, update it."
18342 (interactive)
18343 (if (org-at-timestamp-p t)
18344 (org-timestamp-change 0 'calendar)
18345 (let ((cal-date (org-get-date-from-calendar)))
18346 (org-insert-time-stamp
18347 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18349 (defcustom org-effort-durations
18350 `(("min" . 1)
18351 ("h" . 60)
18352 ("d" . ,(* 60 8))
18353 ("w" . ,(* 60 8 5))
18354 ("m" . ,(* 60 8 5 4))
18355 ("y" . ,(* 60 8 5 40)))
18356 "Conversion factor to minutes for an effort modifier.
18358 Each entry has the form (MODIFIER . MINUTES).
18360 In an effort string, a number followed by MODIFIER is multiplied
18361 by the specified number of MINUTES to obtain an effort in
18362 minutes.
18364 For example, if the value of this variable is ((\"hours\" . 60)), then an
18365 effort string \"2hours\" is equivalent to 120 minutes."
18366 :group 'org-agenda
18367 :version "25.1"
18368 :package-version '(Org . "8.3")
18369 :type '(alist :key-type (string :tag "Modifier")
18370 :value-type (number :tag "Minutes")))
18372 (defun org-minutes-to-clocksum-string (m)
18373 "Format number of minutes as a clocksum string.
18374 The format is determined by `org-time-clocksum-format',
18375 `org-time-clocksum-use-fractional' and
18376 `org-time-clocksum-fractional-format' and
18377 `org-time-clocksum-use-effort-durations'."
18378 (let ((clocksum "")
18379 (m (round m)) ; Don't allow fractions of minutes
18380 h d w mo y fmt n)
18381 (setq h (if org-time-clocksum-use-effort-durations
18382 (cdr (assoc "h" org-effort-durations)) 60)
18383 d (if org-time-clocksum-use-effort-durations
18384 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18385 w (if org-time-clocksum-use-effort-durations
18386 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18387 mo (if org-time-clocksum-use-effort-durations
18388 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18389 y (if org-time-clocksum-use-effort-durations
18390 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18391 ;; fractional format
18392 (if org-time-clocksum-use-fractional
18393 (cond
18394 ;; single format string
18395 ((stringp org-time-clocksum-fractional-format)
18396 (format org-time-clocksum-fractional-format (/ m (float h))))
18397 ;; choice of fractional formats for different time units
18398 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18399 (> (/ (truncate m) (* y d h)) 0))
18400 (format fmt (/ m (* y d (float h)))))
18401 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18402 (> (/ (truncate m) (* mo d h)) 0))
18403 (format fmt (/ m (* mo d (float h)))))
18404 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18405 (> (/ (truncate m) (* w d h)) 0))
18406 (format fmt (/ m (* w d (float h)))))
18407 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18408 (> (/ (truncate m) (* d h)) 0))
18409 (format fmt (/ m (* d (float h)))))
18410 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18411 (> (/ (truncate m) h) 0))
18412 (format fmt (/ m (float h))))
18413 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18414 (format fmt m))
18415 ;; fall back to smallest time unit with a format
18416 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18417 (format fmt (/ m (float h))))
18418 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18419 (format fmt (/ m (* d (float h)))))
18420 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18421 (format fmt (/ m (* w d (float h)))))
18422 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18423 (format fmt (/ m (* mo d (float h)))))
18424 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18425 (format fmt (/ m (* y d (float h))))))
18426 ;; standard (non-fractional) format, with single format string
18427 (if (stringp org-time-clocksum-format)
18428 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18429 ;; separate formats components
18430 (and (setq fmt (plist-get org-time-clocksum-format :years))
18431 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18432 (plist-get org-time-clocksum-format :require-years))
18433 (setq clocksum (concat clocksum (format fmt n))
18434 m (- m (* n y d h))))
18435 (and (setq fmt (plist-get org-time-clocksum-format :months))
18436 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18437 (plist-get org-time-clocksum-format :require-months))
18438 (setq clocksum (concat clocksum (format fmt n))
18439 m (- m (* n mo d h))))
18440 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18441 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18442 (plist-get org-time-clocksum-format :require-weeks))
18443 (setq clocksum (concat clocksum (format fmt n))
18444 m (- m (* n w d h))))
18445 (and (setq fmt (plist-get org-time-clocksum-format :days))
18446 (or (> (setq n (/ (truncate m) (* d h))) 0)
18447 (plist-get org-time-clocksum-format :require-days))
18448 (setq clocksum (concat clocksum (format fmt n))
18449 m (- m (* n d h))))
18450 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18451 (or (> (setq n (/ (truncate m) h)) 0)
18452 (plist-get org-time-clocksum-format :require-hours))
18453 (setq clocksum (concat clocksum (format fmt n))
18454 m (- m (* n h))))
18455 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18456 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18457 (setq clocksum (concat clocksum (format fmt m))))
18458 ;; return formatted time duration
18459 clocksum))))
18461 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18462 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18463 "Org mode version 8.0")
18465 (defun org-hours-to-clocksum-string (n)
18466 (org-minutes-to-clocksum-string (* n 60)))
18468 (defun org-hh:mm-string-to-minutes (s)
18469 "Convert a string H:MM to a number of minutes.
18470 If the string is just a number, interpret it as minutes.
18471 In fact, the first hh:mm or number in the string will be taken,
18472 there can be extra stuff in the string.
18473 If no number is found, the return value is 0."
18474 (cond
18475 ((integerp s) s)
18476 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18477 (+ (* (string-to-number (match-string 1 s)) 60)
18478 (string-to-number (match-string 2 s))))
18479 ((string-match "\\([0-9]+\\)" s)
18480 (string-to-number (match-string 1 s)))
18481 (t 0)))
18483 (defcustom org-image-actual-width t
18484 "Should we use the actual width of images when inlining them?
18486 When set to t, always use the image width.
18488 When set to a number, use imagemagick (when available) to set
18489 the image's width to this value.
18491 When set to a number in a list, try to get the width from any
18492 #+ATTR.* keyword if it matches a width specification like
18494 #+ATTR_HTML: :width 300px
18496 and fall back on that number if none is found.
18498 When set to nil, try to get the width from an #+ATTR.* keyword
18499 and fall back on the original width if none is found.
18501 This requires Emacs >= 24.1, build with imagemagick support."
18502 :group 'org-appearance
18503 :version "24.4"
18504 :package-version '(Org . "8.0")
18505 :type '(choice
18506 (const :tag "Use the image width" t)
18507 (integer :tag "Use a number of pixels")
18508 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18509 (const :tag "Use #+ATTR* or don't resize" nil)))
18511 (defcustom org-agenda-inhibit-startup nil
18512 "Inhibit startup when preparing agenda buffers.
18513 When this variable is t, the initialization of the Org agenda
18514 buffers is inhibited: e.g. the visibility state is not set, the
18515 tables are not re-aligned, etc."
18516 :type 'boolean
18517 :version "24.3"
18518 :group 'org-agenda)
18520 (defcustom org-agenda-ignore-properties nil
18521 "Avoid updating text properties when building the agenda.
18522 Properties are used to prepare buffers for effort estimates,
18523 appointments, statistics and subtree-local categories.
18524 If you don't use these in the agenda, you can add them to this
18525 list and agenda building will be a bit faster.
18526 The value is a list, with zero or more of the symbols `effort', `appt',
18527 `stats' or `category'."
18528 :type '(set :greedy t
18529 (const effort)
18530 (const appt)
18531 (const stats)
18532 (const category))
18533 :version "25.1"
18534 :package-version '(Org . "8.3")
18535 :group 'org-agenda)
18537 (defun org-duration-string-to-minutes (s &optional output-to-string)
18538 "Convert a duration string S to minutes.
18540 A bare number is interpreted as minutes, modifiers can be set by
18541 customizing `org-effort-durations' (which see).
18543 Entries containing a colon are interpreted as H:MM by
18544 `org-hh:mm-string-to-minutes'."
18545 (let ((result 0)
18546 (re (concat "\\([0-9.]+\\) *\\("
18547 (regexp-opt (mapcar 'car org-effort-durations))
18548 "\\)")))
18549 (while (string-match re s)
18550 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18551 (string-to-number (match-string 1 s))))
18552 (setq s (replace-match "" nil t s)))
18553 (setq result (floor result))
18554 (cl-incf result (org-hh:mm-string-to-minutes s))
18555 (if output-to-string (number-to-string result) result)))
18557 ;;;; Files
18559 (defun org-save-all-org-buffers ()
18560 "Save all Org-mode buffers without user confirmation."
18561 (interactive)
18562 (message "Saving all Org-mode buffers...")
18563 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18564 (when (featurep 'org-id) (org-id-locations-save))
18565 (message "Saving all Org-mode buffers... done"))
18567 (defun org-revert-all-org-buffers ()
18568 "Revert all Org-mode buffers.
18569 Prompt for confirmation when there are unsaved changes.
18570 Be sure you know what you are doing before letting this function
18571 overwrite your changes.
18573 This function is useful in a setup where one tracks org files
18574 with a version control system, to revert on one machine after pulling
18575 changes from another. I believe the procedure must be like this:
18577 1. M-x org-save-all-org-buffers
18578 2. Pull changes from the other machine, resolve conflicts
18579 3. M-x org-revert-all-org-buffers"
18580 (interactive)
18581 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18582 (user-error "Abort"))
18583 (save-excursion
18584 (save-window-excursion
18585 (dolist (b (buffer-list))
18586 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18587 (with-current-buffer b buffer-file-name))
18588 (pop-to-buffer-same-window b)
18589 (revert-buffer t 'no-confirm)))
18590 (when (and (featurep 'org-id) org-id-track-globally)
18591 (org-id-locations-load)))))
18593 ;;;; Agenda files
18595 ;;;###autoload
18596 (defun org-switchb (&optional arg)
18597 "Switch between Org buffers.
18599 With \\[universal-argument] prefix, restrict available buffers to files.
18601 With \\[universal-argument] \\[universal-argument] \
18602 prefix, restrict available buffers to agenda files."
18603 (interactive "P")
18604 (let ((blist (org-buffer-list
18605 (cond ((equal arg '(4)) 'files)
18606 ((equal arg '(16)) 'agenda)))))
18607 (pop-to-buffer-same-window
18608 (completing-read "Org buffer: "
18609 (mapcar #'list (mapcar #'buffer-name blist))
18610 nil t))))
18612 (defun org-buffer-list (&optional predicate exclude-tmp)
18613 "Return a list of Org buffers.
18614 PREDICATE can be `export', `files' or `agenda'.
18616 export restrict the list to Export buffers.
18617 files restrict the list to buffers visiting Org files.
18618 agenda restrict the list to buffers visiting agenda files.
18620 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18621 (let* ((bfn nil)
18622 (agenda-files (and (eq predicate 'agenda)
18623 (mapcar 'file-truename (org-agenda-files t))))
18624 (filter
18625 (cond
18626 ((eq predicate 'files)
18627 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18628 ((eq predicate 'export)
18629 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18630 ((eq predicate 'agenda)
18631 (lambda (b)
18632 (with-current-buffer b
18633 (and (derived-mode-p 'org-mode)
18634 (setq bfn (buffer-file-name b))
18635 (member (file-truename bfn) agenda-files)))))
18636 (t (lambda (b) (with-current-buffer b
18637 (or (derived-mode-p 'org-mode)
18638 (string-match "\\*Org .*Export"
18639 (buffer-name b)))))))))
18640 (delq nil
18641 (mapcar
18642 (lambda(b)
18643 (if (and (funcall filter b)
18644 (or (not exclude-tmp)
18645 (not (string-match "tmp" (buffer-name b)))))
18647 nil))
18648 (buffer-list)))))
18650 (defun org-agenda-files (&optional unrestricted archives)
18651 "Get the list of agenda files.
18652 Optional UNRESTRICTED means return the full list even if a restriction
18653 is currently in place.
18654 When ARCHIVES is t, include all archive files that are really being
18655 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18656 `org-agenda-archives-mode' is t."
18657 (let ((files
18658 (cond
18659 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18660 ((stringp org-agenda-files) (org-read-agenda-file-list))
18661 ((listp org-agenda-files) org-agenda-files)
18662 (t (error "Invalid value of `org-agenda-files'")))))
18663 (setq files (apply 'append
18664 (mapcar (lambda (f)
18665 (if (file-directory-p f)
18666 (directory-files
18667 f t org-agenda-file-regexp)
18668 (list f)))
18669 files)))
18670 (when org-agenda-skip-unavailable-files
18671 (setq files (delq nil
18672 (mapcar (function
18673 (lambda (file)
18674 (and (file-readable-p file) file)))
18675 files))))
18676 (when (or (eq archives t)
18677 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18678 (setq files (org-add-archive-files files)))
18679 files))
18681 (defun org-agenda-file-p (&optional file)
18682 "Return non-nil, if FILE is an agenda file.
18683 If FILE is omitted, use the file associated with the current
18684 buffer."
18685 (let ((fname (or file (buffer-file-name))))
18686 (and fname
18687 (member (file-truename fname)
18688 (mapcar #'file-truename (org-agenda-files t))))))
18690 (defun org-edit-agenda-file-list ()
18691 "Edit the list of agenda files.
18692 Depending on setup, this either uses customize to edit the variable
18693 `org-agenda-files', or it visits the file that is holding the list. In the
18694 latter case, the buffer is set up in a way that saving it automatically kills
18695 the buffer and restores the previous window configuration."
18696 (interactive)
18697 (if (stringp org-agenda-files)
18698 (let ((cw (current-window-configuration)))
18699 (find-file org-agenda-files)
18700 (setq-local org-window-configuration cw)
18701 (add-hook 'after-save-hook
18702 (lambda ()
18703 (set-window-configuration
18704 (prog1 org-window-configuration
18705 (kill-buffer (current-buffer))))
18706 (org-install-agenda-files-menu)
18707 (message "New agenda file list installed"))
18708 nil 'local)
18709 (message "%s" (substitute-command-keys
18710 "Edit list and finish with \\[save-buffer]")))
18711 (customize-variable 'org-agenda-files)))
18713 (defun org-store-new-agenda-file-list (list)
18714 "Set new value for the agenda file list and save it correctly."
18715 (if (stringp org-agenda-files)
18716 (let ((fe (org-read-agenda-file-list t)) b u)
18717 (while (setq b (find-buffer-visiting org-agenda-files))
18718 (kill-buffer b))
18719 (with-temp-file org-agenda-files
18720 (insert
18721 (mapconcat
18722 (lambda (f) ;; Keep un-expanded entries.
18723 (if (setq u (assoc f fe))
18724 (cdr u)
18726 list "\n")
18727 "\n")))
18728 (let ((org-mode-hook nil) (org-inhibit-startup t)
18729 (org-insert-mode-line-in-empty-file nil))
18730 (setq org-agenda-files list)
18731 (customize-save-variable 'org-agenda-files org-agenda-files))))
18733 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18734 "Read the list of agenda files from a file.
18735 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18736 filenames, used by `org-store-new-agenda-file-list' to write back
18737 un-expanded file names."
18738 (when (file-directory-p org-agenda-files)
18739 (error "`org-agenda-files' cannot be a single directory"))
18740 (when (stringp org-agenda-files)
18741 (with-temp-buffer
18742 (insert-file-contents org-agenda-files)
18743 (mapcar
18744 (lambda (f)
18745 (let ((e (expand-file-name (substitute-in-file-name f)
18746 org-directory)))
18747 (if pair-with-expansion
18748 (cons e f)
18749 e)))
18750 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18752 ;;;###autoload
18753 (defun org-cycle-agenda-files ()
18754 "Cycle through the files in `org-agenda-files'.
18755 If the current buffer visits an agenda file, find the next one in the list.
18756 If the current buffer does not, find the first agenda file."
18757 (interactive)
18758 (let* ((fs (or (org-agenda-files t)
18759 (user-error "No agenda files")))
18760 (files (copy-sequence fs))
18761 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18762 file)
18763 (when tcf
18764 (while (and (setq file (pop files))
18765 (not (equal (file-truename file) tcf)))))
18766 (find-file (car (or files fs)))
18767 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18769 (defun org-agenda-file-to-front (&optional to-end)
18770 "Move/add the current file to the top of the agenda file list.
18771 If the file is not present in the list, it is added to the front. If it is
18772 present, it is moved there. With optional argument TO-END, add/move to the
18773 end of the list."
18774 (interactive "P")
18775 (let ((org-agenda-skip-unavailable-files nil)
18776 (file-alist (mapcar (lambda (x)
18777 (cons (file-truename x) x))
18778 (org-agenda-files t)))
18779 (ctf (file-truename
18780 (or buffer-file-name
18781 (user-error "Please save the current buffer to a file"))))
18782 x had)
18783 (setq x (assoc ctf file-alist) had x)
18785 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18786 (if to-end
18787 (setq file-alist (append (delq x file-alist) (list x)))
18788 (setq file-alist (cons x (delq x file-alist))))
18789 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18790 (org-install-agenda-files-menu)
18791 (message "File %s to %s of agenda file list"
18792 (if had "moved" "added") (if to-end "end" "front"))))
18794 (defun org-remove-file (&optional file)
18795 "Remove current file from the list of files in variable `org-agenda-files'.
18796 These are the files which are being checked for agenda entries.
18797 Optional argument FILE means use this file instead of the current."
18798 (interactive)
18799 (let* ((org-agenda-skip-unavailable-files nil)
18800 (file (or file buffer-file-name
18801 (user-error "Current buffer does not visit a file")))
18802 (true-file (file-truename file))
18803 (afile (abbreviate-file-name file))
18804 (files (delq nil (mapcar
18805 (lambda (x)
18806 (unless (equal true-file
18807 (file-truename x))
18809 (org-agenda-files t)))))
18810 (if (not (= (length files) (length (org-agenda-files t))))
18811 (progn
18812 (org-store-new-agenda-file-list files)
18813 (org-install-agenda-files-menu)
18814 (message "Removed from Org Agenda list: %s" afile))
18815 (message "File was not in list: %s (not removed)" afile))))
18817 (defun org-file-menu-entry (file)
18818 (vector file (list 'find-file file) t))
18820 (defun org-check-agenda-file (file)
18821 "Make sure FILE exists. If not, ask user what to do."
18822 (unless (file-exists-p file)
18823 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18824 (abbreviate-file-name file))
18825 (let ((r (downcase (read-char-exclusive))))
18826 (cond
18827 ((equal r ?r)
18828 (org-remove-file file)
18829 (throw 'nextfile t))
18830 (t (user-error "Abort"))))))
18832 (defun org-get-agenda-file-buffer (file)
18833 "Get an agenda buffer visiting FILE.
18834 If the buffer needs to be created, add it to the list of buffers
18835 which might be released later."
18836 (let ((buf (org-find-base-buffer-visiting file)))
18837 (if buf
18838 buf ; just return it
18839 ;; Make a new buffer and remember it
18840 (setq buf (find-file-noselect file))
18841 (when buf (push buf org-agenda-new-buffers))
18842 buf)))
18844 (defun org-release-buffers (blist)
18845 "Release all buffers in list, asking the user for confirmation when needed.
18846 When a buffer is unmodified, it is just killed. When modified, it is saved
18847 \(if the user agrees) and then killed."
18848 (let (file)
18849 (dolist (buf blist)
18850 (setq file (buffer-file-name buf))
18851 (when (and (buffer-modified-p buf)
18852 file
18853 (y-or-n-p (format "Save file %s? " file)))
18854 (with-current-buffer buf (save-buffer)))
18855 (kill-buffer buf))))
18857 (defun org-agenda-prepare-buffers (files)
18858 "Create buffers for all agenda files, protect archived trees and comments."
18859 (interactive)
18860 (let ((pa '(:org-archived t))
18861 (pc '(:org-comment t))
18862 (pall '(:org-archived t :org-comment t))
18863 (inhibit-read-only t)
18864 (org-inhibit-startup org-agenda-inhibit-startup)
18865 (rea (concat ":" org-archive-tag ":"))
18866 re pos)
18867 (setq org-tag-alist-for-agenda nil
18868 org-tag-groups-alist-for-agenda nil)
18869 (save-excursion
18870 (save-restriction
18871 (dolist (file files)
18872 (catch 'nextfile
18873 (if (bufferp file)
18874 (set-buffer file)
18875 (org-check-agenda-file file)
18876 (set-buffer (org-get-agenda-file-buffer file)))
18877 (widen)
18878 (org-set-regexps-and-options 'tags-only)
18879 (setq pos (point))
18880 (or (memq 'category org-agenda-ignore-properties)
18881 (org-refresh-category-properties))
18882 (or (memq 'stats org-agenda-ignore-properties)
18883 (org-refresh-stats-properties))
18884 (or (memq 'effort org-agenda-ignore-properties)
18885 (org-refresh-effort-properties))
18886 (or (memq 'appt org-agenda-ignore-properties)
18887 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18888 (setq org-todo-keywords-for-agenda
18889 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18890 (setq org-done-keywords-for-agenda
18891 (append org-done-keywords-for-agenda org-done-keywords))
18892 (setq org-todo-keyword-alist-for-agenda
18893 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18894 (setq org-tag-alist-for-agenda
18895 (org-uniquify
18896 (append org-tag-alist-for-agenda
18897 org-current-tag-alist)))
18898 ;; Merge current file's tag groups into global
18899 ;; `org-tag-groups-alist-for-agenda'.
18900 (when org-group-tags
18901 (dolist (alist org-tag-groups-alist)
18902 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18903 (if old
18904 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18905 (push alist org-tag-groups-alist-for-agenda)))))
18906 (org-with-silent-modifications
18907 (save-excursion
18908 (remove-text-properties (point-min) (point-max) pall)
18909 (when org-agenda-skip-archived-trees
18910 (goto-char (point-min))
18911 (while (re-search-forward rea nil t)
18912 (when (org-at-heading-p t)
18913 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18914 (goto-char (point-min))
18915 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18916 (while (re-search-forward re nil t)
18917 (when (save-match-data (org-in-commented-heading-p t))
18918 (add-text-properties
18919 (match-beginning 0) (org-end-of-subtree t) pc)))))
18920 (goto-char pos)))))
18921 (setq org-todo-keywords-for-agenda
18922 (org-uniquify org-todo-keywords-for-agenda))
18923 (setq org-todo-keyword-alist-for-agenda
18924 (org-uniquify org-todo-keyword-alist-for-agenda))))
18927 ;;;; CDLaTeX minor mode
18929 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18930 "Keymap for the minor `org-cdlatex-mode'.")
18932 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18933 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18934 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18935 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18936 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18938 (defvar org-cdlatex-texmathp-advice-is-done nil
18939 "Flag remembering if we have applied the advice to texmathp already.")
18941 (define-minor-mode org-cdlatex-mode
18942 "Toggle the minor `org-cdlatex-mode'.
18943 This mode supports entering LaTeX environment and math in LaTeX fragments
18944 in Org-mode.
18945 \\{org-cdlatex-mode-map}"
18946 nil " OCDL" nil
18947 (when org-cdlatex-mode
18948 (require 'cdlatex)
18949 (run-hooks 'cdlatex-mode-hook)
18950 (cdlatex-compute-tables))
18951 (unless org-cdlatex-texmathp-advice-is-done
18952 (setq org-cdlatex-texmathp-advice-is-done t)
18953 (defadvice texmathp (around org-math-always-on activate)
18954 "Always return t in org-mode buffers.
18955 This is because we want to insert math symbols without dollars even outside
18956 the LaTeX math segments. If Orgmode thinks that point is actually inside
18957 an embedded LaTeX fragment, let texmathp do its job.
18958 \\[org-cdlatex-mode-map]"
18959 (interactive)
18960 (let (p)
18961 (cond
18962 ((not (derived-mode-p 'org-mode)) ad-do-it)
18963 ((eq this-command 'cdlatex-math-symbol)
18964 (setq ad-return-value t
18965 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18967 (let ((p (org-inside-LaTeX-fragment-p)))
18968 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18969 (setq ad-return-value t
18970 texmathp-why '("Org-mode embedded math" . 0))
18971 (when p ad-do-it)))))))))
18973 (defun turn-on-org-cdlatex ()
18974 "Unconditionally turn on `org-cdlatex-mode'."
18975 (org-cdlatex-mode 1))
18977 (defun org-try-cdlatex-tab ()
18978 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18979 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18980 - inside a LaTeX fragment, or
18981 - after the first word in a line, where an abbreviation expansion could
18982 insert a LaTeX environment."
18983 (when org-cdlatex-mode
18984 (cond
18985 ;; Before any word on the line: No expansion possible.
18986 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18987 ;; Just after first word on the line: Expand it. Make sure it
18988 ;; cannot happen on headlines, though.
18989 ((save-excursion
18990 (skip-chars-backward "a-zA-Z0-9*")
18991 (skip-chars-backward " \t")
18992 (and (bolp) (not (org-at-heading-p))))
18993 (cdlatex-tab) t)
18994 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18996 (defun org-cdlatex-underscore-caret (&optional _arg)
18997 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18998 Revert to the normal definition outside of these fragments."
18999 (interactive "P")
19000 (if (org-inside-LaTeX-fragment-p)
19001 (call-interactively 'cdlatex-sub-superscript)
19002 (let (org-cdlatex-mode)
19003 (call-interactively (key-binding (vector last-input-event))))))
19005 (defun org-cdlatex-math-modify (&optional _arg)
19006 "Execute `cdlatex-math-modify' in LaTeX fragments.
19007 Revert to the normal definition outside of these fragments."
19008 (interactive "P")
19009 (if (org-inside-LaTeX-fragment-p)
19010 (call-interactively 'cdlatex-math-modify)
19011 (let (org-cdlatex-mode)
19012 (call-interactively (key-binding (vector last-input-event))))))
19014 (defun org-cdlatex-environment-indent (&optional environment item)
19015 "Execute `cdlatex-environment' and indent the inserted environment.
19017 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19019 The inserted environment is indented to current indentation
19020 unless point is at the beginning of the line, in which the
19021 environment remains unintended."
19022 (interactive)
19023 ;; cdlatex-environment always return nil. Therefore, capture output
19024 ;; first and determine if an environment was selected.
19025 (let* ((beg (point-marker))
19026 (end (copy-marker (point) t))
19027 (inserted (progn
19028 (ignore-errors (cdlatex-environment environment item))
19029 (< beg end)))
19030 ;; Figure out how many lines to move forward after the
19031 ;; environment has been inserted.
19032 (lines (when inserted
19033 (save-excursion
19034 (- (cl-loop while (< beg (point))
19035 with x = 0
19036 do (forward-line -1)
19037 (cl-incf x)
19038 finally return x)
19039 (if (progn (goto-char beg)
19040 (and (progn (skip-chars-forward " \t") (eolp))
19041 (progn (skip-chars-backward " \t") (bolp))))
19042 1 0)))))
19043 (env (org-trim (delete-and-extract-region beg end))))
19044 (when inserted
19045 ;; Get indentation of next line unless at column 0.
19046 (let ((ind (if (bolp) 0
19047 (save-excursion
19048 (org-return-indent)
19049 (prog1 (org-get-indentation)
19050 (when (progn (skip-chars-forward " \t") (eolp))
19051 (delete-region beg (point)))))))
19052 (bol (progn (skip-chars-backward " \t") (bolp))))
19053 ;; Insert a newline before environment unless at column zero
19054 ;; to "escape" the current line. Insert a newline if
19055 ;; something is one the same line as \end{ENVIRONMENT}.
19056 (insert
19057 (concat (unless bol "\n") env
19058 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19059 (unless (zerop ind)
19060 (save-excursion
19061 (goto-char beg)
19062 (while (< (point) end)
19063 (unless (eolp) (indent-line-to ind))
19064 (forward-line))))
19065 (goto-char beg)
19066 (forward-line lines)
19067 (indent-line-to ind)))
19068 (set-marker beg nil)
19069 (set-marker end nil)))
19072 ;;;; LaTeX fragments
19074 (defun org-inside-LaTeX-fragment-p ()
19075 "Test if point is inside a LaTeX fragment.
19076 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19077 sequence appearing also before point.
19078 Even though the matchers for math are configurable, this function assumes
19079 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19080 delimiters are skipped when they have been removed by customization.
19081 The return value is nil, or a cons cell with the delimiter and the
19082 position of this delimiter.
19084 This function does a reasonably good job, but can locally be fooled by
19085 for example currency specifications. For example it will assume being in
19086 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19087 fragments that are properly closed, but during editing, we have to live
19088 with the uncertainty caused by missing closing delimiters. This function
19089 looks only before point, not after."
19090 (catch 'exit
19091 (let ((pos (point))
19092 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19093 (lim (progn
19094 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19095 (point)))
19096 dd-on str (start 0) m re)
19097 (goto-char pos)
19098 (when dodollar
19099 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19100 re (nth 1 (assoc "$" org-latex-regexps)))
19101 (while (string-match re str start)
19102 (cond
19103 ((= (match-end 0) (length str))
19104 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19105 ((= (match-end 0) (- (length str) 5))
19106 (throw 'exit nil))
19107 (t (setq start (match-end 0))))))
19108 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19109 (goto-char pos)
19110 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19111 (and (match-beginning 2) (throw 'exit nil))
19112 ;; count $$
19113 (while (re-search-backward "\\$\\$" lim t)
19114 (setq dd-on (not dd-on)))
19115 (goto-char pos)
19116 (when dd-on (cons "$$" m))))))
19118 (defun org-inside-latex-macro-p ()
19119 "Is point inside a LaTeX macro or its arguments?"
19120 (save-match-data
19121 (org-in-regexp
19122 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19124 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19125 "Build an overlay between BEG and END using IMAGE file.
19126 Argument IMAGETYPE is the extension of the displayed image,
19127 as a string. It defaults to \"png\"."
19128 (let ((ov (make-overlay beg end))
19129 (imagetype (or (intern imagetype) 'png)))
19130 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19131 (overlay-put ov 'evaporate t)
19132 (overlay-put ov
19133 'modification-hooks
19134 (list (lambda (o _flag _beg _end &optional _l)
19135 (delete-overlay o))))
19136 (overlay-put ov
19137 'display
19138 (list 'image :type imagetype :file image :ascent 'center))))
19140 (defun org--list-latex-overlays (&optional beg end)
19141 "List all Org LaTeX overlays in current buffer.
19142 Limit to overlays between BEG and END when those are provided."
19143 (cl-remove-if-not
19144 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19145 (overlays-in (or beg (point-min)) (or end (point-max)))))
19147 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19148 "Remove all overlays with LaTeX fragment images in current buffer.
19149 When optional arguments BEG and END are non-nil, remove all
19150 overlays between them instead. Return a non-nil value when some
19151 overlays were removed, nil otherwise."
19152 (let ((overlays (org--list-latex-overlays beg end)))
19153 (mapc #'delete-overlay overlays)
19154 overlays))
19156 (defun org-toggle-latex-fragment (&optional arg)
19157 "Preview the LaTeX fragment at point, or all locally or globally.
19159 If the cursor is on a LaTeX fragment, create the image and overlay
19160 it over the source code, if there is none. Remove it otherwise.
19161 If there is no fragment at point, display all fragments in the
19162 current section.
19164 With prefix ARG, preview or clear image for all fragments in the
19165 current subtree or in the whole buffer when used before the first
19166 headline. With a double prefix ARG \\[universal-argument] \
19167 \\[universal-argument] preview or clear images
19168 for all fragments in the buffer."
19169 (interactive "P")
19170 (when (display-graphic-p)
19171 (catch 'exit
19172 (save-excursion
19173 (let (beg end msg)
19174 (cond
19175 ((or (equal arg '(16))
19176 (and (equal arg '(4))
19177 (org-with-limited-levels (org-before-first-heading-p))))
19178 (if (org-remove-latex-fragment-image-overlays)
19179 (progn (message "LaTeX fragments images removed from buffer")
19180 (throw 'exit nil))
19181 (setq msg "Creating images for buffer...")))
19182 ((equal arg '(4))
19183 (org-with-limited-levels (org-back-to-heading t))
19184 (setq beg (point))
19185 (setq end (progn (org-end-of-subtree t) (point)))
19186 (if (org-remove-latex-fragment-image-overlays beg end)
19187 (progn
19188 (message "LaTeX fragment images removed from subtree")
19189 (throw 'exit nil))
19190 (setq msg "Creating images for subtree...")))
19191 ((let ((datum (org-element-context)))
19192 (when (memq (org-element-type datum)
19193 '(latex-environment latex-fragment))
19194 (setq beg (org-element-property :begin datum))
19195 (setq end (org-element-property :end datum))
19196 (if (org-remove-latex-fragment-image-overlays beg end)
19197 (progn (message "LaTeX fragment image removed")
19198 (throw 'exit nil))
19199 (setq msg "Creating image...")))))
19201 (org-with-limited-levels
19202 (setq beg (if (org-at-heading-p) (line-beginning-position)
19203 (outline-previous-heading)
19204 (point)))
19205 (setq end (progn (outline-next-heading) (point)))
19206 (if (org-remove-latex-fragment-image-overlays beg end)
19207 (progn
19208 (message "LaTeX fragment images removed from section")
19209 (throw 'exit nil))
19210 (setq msg "Creating images for section...")))))
19211 (let ((file (buffer-file-name (buffer-base-buffer))))
19212 (org-format-latex
19213 (concat org-preview-latex-image-directory "org-ltximg")
19214 beg end
19215 ;; Emacs cannot overlay images from remote hosts. Create
19216 ;; it in `temporary-file-directory' instead.
19217 (if (or (not file) (file-remote-p file))
19218 temporary-file-directory
19219 default-directory)
19220 'overlays msg 'forbuffer org-preview-latex-default-process))
19221 (message (concat msg "done")))))))
19223 (defun org-format-latex
19224 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19225 "Replace LaTeX fragments with links to an image.
19227 The function takes care of creating the replacement image.
19229 Only consider fragments between BEG and END when those are
19230 provided.
19232 When optional argument OVERLAYS is non-nil, display the image on
19233 top of the fragment instead of replacing it.
19235 PROCESSING-TYPE is the conversion method to use, as a symbol.
19237 Some of the options can be changed using the variable
19238 `org-format-latex-options', which see."
19239 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19240 (unless (eq processing-type 'verbatim)
19241 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19242 (cnt 0)
19243 checkdir-flag)
19244 (goto-char (or beg (point-min)))
19245 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19246 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19247 (overlay-recenter (or end (point-max))))
19248 (while (re-search-forward math-regexp end t)
19249 (unless (and overlays
19250 (eq (get-char-property (point) 'org-overlay-type)
19251 'org-latex-overlay))
19252 (let* ((context (org-element-context))
19253 (type (org-element-type context)))
19254 (when (memq type '(latex-environment latex-fragment))
19255 (let ((block-type (eq type 'latex-environment))
19256 (value (org-element-property :value context))
19257 (beg (org-element-property :begin context))
19258 (end (save-excursion
19259 (goto-char (org-element-property :end context))
19260 (skip-chars-backward " \r\t\n")
19261 (point))))
19262 (cond
19263 ((eq processing-type 'mathjax)
19264 ;; Prepare for MathJax processing.
19265 (if (not (string-match "\\`\\$\\$?" value))
19266 (goto-char end)
19267 (delete-region beg end)
19268 (if (string= (match-string 0 value) "$$")
19269 (insert "\\[" (substring value 2 -2) "\\]")
19270 (insert "\\(" (substring value 1 -1) "\\)"))))
19271 ((assq processing-type org-preview-latex-process-alist)
19272 ;; Process to an image.
19273 (cl-incf cnt)
19274 (goto-char beg)
19275 (let* ((processing-info
19276 (cdr (assq processing-type org-preview-latex-process-alist)))
19277 (face (face-at-point))
19278 ;; Get the colors from the face at point.
19280 (let ((color (plist-get org-format-latex-options
19281 :foreground)))
19282 (if (and forbuffer (eq color 'auto))
19283 (face-attribute face :foreground nil 'default)
19284 color)))
19286 (let ((color (plist-get org-format-latex-options
19287 :background)))
19288 (if (and forbuffer (eq color 'auto))
19289 (face-attribute face :background nil 'default)
19290 color)))
19291 (hash (sha1 (prin1-to-string
19292 (list org-format-latex-header
19293 org-latex-default-packages-alist
19294 org-latex-packages-alist
19295 org-format-latex-options
19296 forbuffer value fg bg))))
19297 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19298 (absprefix (expand-file-name prefix dir))
19299 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19300 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19301 (sep (and block-type "\n\n"))
19302 (link (concat sep "[[file:" linkfile "]]" sep))
19303 (options
19304 (org-combine-plists
19305 org-format-latex-options
19306 `(:foreground ,fg :background ,bg))))
19307 (when msg (message msg cnt))
19308 (unless checkdir-flag ; Ensure the directory exists.
19309 (setq checkdir-flag t)
19310 (let ((todir (file-name-directory absprefix)))
19311 (unless (file-directory-p todir)
19312 (make-directory todir t))))
19313 (unless (file-exists-p movefile)
19314 (org-create-formula-image
19315 value movefile options forbuffer processing-type))
19316 (if overlays
19317 (progn
19318 (dolist (o (overlays-in beg end))
19319 (when (eq (overlay-get o 'org-overlay-type)
19320 'org-latex-overlay)
19321 (delete-overlay o)))
19322 (org--format-latex-make-overlay beg end movefile imagetype)
19323 (goto-char end))
19324 (delete-region beg end)
19325 (insert
19326 (org-add-props link
19327 (list 'org-latex-src
19328 (replace-regexp-in-string "\"" "" value)
19329 'org-latex-src-embed-type
19330 (if block-type 'paragraph 'character)))))))
19331 ((eq processing-type 'mathml)
19332 ;; Process to MathML.
19333 (unless (org-format-latex-mathml-available-p)
19334 (user-error "LaTeX to MathML converter not configured"))
19335 (cl-incf cnt)
19336 (when msg (message msg cnt))
19337 (goto-char beg)
19338 (delete-region beg end)
19339 (insert (org-format-latex-as-mathml
19340 value block-type prefix dir)))
19342 (error "Unknown conversion process %s for LaTeX fragments"
19343 processing-type)))))))))))
19345 (defun org-create-math-formula (latex-frag &optional mathml-file)
19346 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19347 Use `org-latex-to-mathml-convert-command'. If the conversion is
19348 sucessful, return the portion between \"<math...> </math>\"
19349 elements otherwise return nil. When MATHML-FILE is specified,
19350 write the results in to that file. When invoked as an
19351 interactive command, prompt for LATEX-FRAG, with initial value
19352 set to the current active region and echo the results for user
19353 inspection."
19354 (interactive (list (let ((frag (when (org-region-active-p)
19355 (buffer-substring-no-properties
19356 (region-beginning) (region-end)))))
19357 (read-string "LaTeX Fragment: " frag nil frag))))
19358 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19359 (let* ((tmp-in-file
19360 (let ((file (file-relative-name
19361 (make-temp-name (expand-file-name "ltxmathml-in")))))
19362 (write-region latex-frag nil file)
19363 file))
19364 (tmp-out-file (file-relative-name
19365 (make-temp-name (expand-file-name "ltxmathml-out"))))
19366 (cmd (format-spec
19367 org-latex-to-mathml-convert-command
19368 `((?j . ,(and org-latex-to-mathml-jar-file
19369 (shell-quote-argument
19370 (expand-file-name
19371 org-latex-to-mathml-jar-file))))
19372 (?I . ,(shell-quote-argument tmp-in-file))
19373 (?i . ,latex-frag)
19374 (?o . ,(shell-quote-argument tmp-out-file)))))
19375 mathml shell-command-output)
19376 (when (called-interactively-p 'any)
19377 (unless (org-format-latex-mathml-available-p)
19378 (user-error "LaTeX to MathML converter not configured")))
19379 (message "Running %s" cmd)
19380 (setq shell-command-output (shell-command-to-string cmd))
19381 (setq mathml
19382 (when (file-readable-p tmp-out-file)
19383 (with-current-buffer (find-file-noselect tmp-out-file t)
19384 (goto-char (point-min))
19385 (when (re-search-forward
19386 (concat
19387 (regexp-quote
19388 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19389 "[^>]*?>"
19390 "\\(.\\|\n\\)*"
19391 "</math>")
19392 nil t)
19393 (prog1 (match-string 0) (kill-buffer))))))
19394 (cond
19395 (mathml
19396 (setq mathml
19397 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19398 (when mathml-file
19399 (write-region mathml nil mathml-file))
19400 (when (called-interactively-p 'any)
19401 (message mathml)))
19402 ((message "LaTeX to MathML conversion failed")
19403 (message shell-command-output)))
19404 (delete-file tmp-in-file)
19405 (when (file-exists-p tmp-out-file)
19406 (delete-file tmp-out-file))
19407 mathml))
19409 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19410 prefix &optional dir)
19411 "Use `org-create-math-formula' but check local cache first."
19412 (let* ((absprefix (expand-file-name prefix dir))
19413 (print-length nil) (print-level nil)
19414 (formula-id (concat
19415 "formula-"
19416 (sha1
19417 (prin1-to-string
19418 (list latex-frag
19419 org-latex-to-mathml-convert-command)))))
19420 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19421 (formula-cache-dir (file-name-directory formula-cache)))
19423 (unless (file-directory-p formula-cache-dir)
19424 (make-directory formula-cache-dir t))
19426 (unless (file-exists-p formula-cache)
19427 (org-create-math-formula latex-frag formula-cache))
19429 (if (file-exists-p formula-cache)
19430 ;; Successful conversion. Return the link to MathML file.
19431 (org-add-props
19432 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19433 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19434 'org-latex-src-embed-type (if latex-frag-type
19435 'paragraph 'character)))
19436 ;; Failed conversion. Return the LaTeX fragment verbatim
19437 latex-frag)))
19439 (declare-function org-export-get-backend "ox" (name))
19440 (declare-function org-export--get-global-options "ox" (&optional backend))
19441 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19442 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19443 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19444 (defun org-create-formula--latex-header ()
19445 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19446 (let ((info (org-combine-plists (org-export--get-global-options
19447 (org-export-get-backend 'latex))
19448 (org-export--get-inbuffer-options
19449 (org-export-get-backend 'latex)))))
19450 (org-latex-guess-babel-language
19451 (org-latex-guess-inputenc
19452 (org-splice-latex-header
19453 org-format-latex-header
19454 org-latex-default-packages-alist
19455 org-latex-packages-alist t
19456 (plist-get info :latex-header)))
19457 info)))
19459 (defun org--get-display-dpi ()
19460 "Get the DPI of the display.
19462 Assumes that the display has the same pixel width in the
19463 horizontal and vertical directions."
19464 (if (display-graphic-p)
19465 (round (/ (display-pixel-height)
19466 (/ (display-mm-height) 25.4)))
19467 (error "Attempt to calculate the dpi of a non-graphic display")))
19469 (defun org-create-formula-image
19470 (string tofile options buffer &optional processing-type)
19471 "Create an image from LaTeX source using external processes.
19473 The LaTeX STRING is saved to a temporary LaTeX file, then
19474 converted to an image file by process PROCESSING-TYPE defined in
19475 `org-preview-latex-process-alist'. A nil value defaults to
19476 `org-preview-latex-default-process'.
19478 The generated image file is eventually moved to TOFILE.
19480 The OPTIONS argument controls the size, foreground color and
19481 background color of the generated image.
19483 When BUFFER non-nil, this function is used for LaTeX previewing.
19484 Otherwise, it is used to deal with LaTeX snippets showed in
19485 a HTML file."
19486 (let* ((processing-type (or processing-type
19487 org-preview-latex-default-process))
19488 (processing-info
19489 (cdr (assq processing-type org-preview-latex-process-alist)))
19490 (programs (plist-get processing-info :programs))
19491 (error-message (or (plist-get processing-info :message) ""))
19492 (use-xcolor (plist-get processing-info :use-xcolor))
19493 (image-input-type (plist-get processing-info :image-input-type))
19494 (image-output-type (plist-get processing-info :image-output-type))
19495 (post-clean (or (plist-get processing-info :post-clean)
19496 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19497 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19498 (latex-header (or (plist-get processing-info :latex-header)
19499 (org-create-formula--latex-header)))
19500 (latex-compiler (plist-get processing-info :latex-compiler))
19501 (image-converter (plist-get processing-info :image-converter))
19502 (tmpdir temporary-file-directory)
19503 (texfilebase (make-temp-name
19504 (expand-file-name "orgtex" tmpdir)))
19505 (texfile (concat texfilebase ".tex"))
19506 (font-height (face-attribute 'default :height nil))
19507 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19508 '(1.0 . 1.0)))
19509 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19510 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19511 (dpi (* scale (floor (if buffer font-height 140.0))))
19512 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19513 "Black"))
19514 (bg (or (plist-get options (if buffer :background :html-background))
19515 "Transparent"))
19516 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19517 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19518 (dolist (program programs)
19519 (org-check-external-command program error-message))
19520 (if use-xcolor
19521 (progn (if (eq fg 'default)
19522 (setq fg (org-latex-color :foreground))
19523 (setq fg (org-latex-color-format fg)))
19524 (if (eq bg 'default)
19525 (setq bg (org-latex-color :background))
19526 (setq bg (org-latex-color-format
19527 (if (string= bg "Transparent") "white" bg))))
19528 (with-temp-file texfile
19529 (insert latex-header)
19530 (insert "\n\\begin{document}\n"
19531 "\\definecolor{fg}{rgb}{" fg "}\n"
19532 "\\definecolor{bg}{rgb}{" bg "}\n"
19533 "\n\\pagecolor{bg}\n"
19534 "\n{\\color{fg}\n"
19535 string
19536 "\n}\n"
19537 "\n\\end{document}\n")))
19538 (if (eq fg 'default)
19539 (setq fg (org-dvipng-color :foreground))
19540 (unless (string= fg "Transparent")
19541 (setq fg (org-dvipng-color-format fg))))
19542 (if (eq bg 'default)
19543 (setq bg (org-dvipng-color :background))
19544 (unless (string= bg "Transparent")
19545 (setq bg (org-dvipng-color-format bg))))
19546 (with-temp-file texfile
19547 (insert latex-header)
19548 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19550 (let* ((err-msg (format "Please adjust '%s' part of \
19551 `org-preview-latex-process-alist'."
19552 processing-type))
19553 (image-input-file
19554 (org-compile-file
19555 texfile latex-compiler image-input-type err-msg log-buf))
19556 (image-output-file
19557 (org-compile-file
19558 image-input-file image-converter image-output-type err-msg log-buf
19559 `((?F . ,(shell-quote-argument fg))
19560 (?B . ,(shell-quote-argument bg))
19561 (?D . ,(shell-quote-argument (format "%s" dpi)))
19562 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19563 (copy-file image-output-file tofile 'replace)
19564 (dolist (e post-clean)
19565 (when (file-exists-p (concat texfilebase e))
19566 (delete-file (concat texfilebase e))))
19567 image-output-file)))
19569 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19570 "Fill a LaTeX header template TPL.
19571 In the template, the following place holders will be recognized:
19573 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19574 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19575 [PACKAGES] \\usepackage statements for PKG
19576 [NO-PACKAGES] do not include PKG
19577 [EXTRA] the string EXTRA
19578 [NO-EXTRA] do not include EXTRA
19580 For backward compatibility, if both the positive and the negative place
19581 holder is missing, the positive one (without the \"NO-\") will be
19582 assumed to be present at the end of the template.
19583 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19584 EXTRA is a string.
19585 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19586 (let (rpl (end ""))
19587 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19588 (setq rpl (if (or (match-end 1) (not def-pkg))
19589 "" (org-latex-packages-to-string def-pkg snippets-p t))
19590 tpl (replace-match rpl t t tpl))
19591 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19593 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19594 (setq rpl (if (or (match-end 1) (not pkg))
19595 "" (org-latex-packages-to-string pkg snippets-p t))
19596 tpl (replace-match rpl t t tpl))
19597 (when pkg (setq end
19598 (concat end "\n"
19599 (org-latex-packages-to-string pkg snippets-p)))))
19601 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19602 (setq rpl (if (or (match-end 1) (not extra))
19603 "" (concat extra "\n"))
19604 tpl (replace-match rpl t t tpl))
19605 (when (and extra (string-match "\\S-" extra))
19606 (setq end (concat end "\n" extra))))
19608 (if (string-match "\\S-" end)
19609 (concat tpl "\n" end)
19610 tpl)))
19612 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19613 "Turn an alist of packages into a string with the \\usepackage macros."
19614 (setq pkg (mapconcat (lambda(p)
19615 (cond
19616 ((stringp p) p)
19617 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19618 (format "%% Package %s omitted" (cadr p)))
19619 ((equal "" (car p))
19620 (format "\\usepackage{%s}" (cadr p)))
19622 (format "\\usepackage[%s]{%s}"
19623 (car p) (cadr p)))))
19625 "\n"))
19626 (if newline (concat pkg "\n") pkg))
19628 (defun org-dvipng-color (attr)
19629 "Return a RGB color specification for dvipng."
19630 (apply #'format "rgb %s %s %s"
19631 (mapcar #'org-normalize-color
19632 (color-values (face-attribute 'default attr nil)))))
19634 (defun org-dvipng-color-format (color-name)
19635 "Convert COLOR-NAME to a RGB color value for dvipng."
19636 (apply 'format "rgb %s %s %s"
19637 (mapcar 'org-normalize-color
19638 (color-values color-name))))
19640 (defun org-latex-color (attr)
19641 "Return a RGB color for the LaTeX color package."
19642 (apply #'format "%s,%s,%s"
19643 (mapcar #'org-normalize-color
19644 (color-values (face-attribute 'default attr nil)))))
19646 (defun org-latex-color-format (color-name)
19647 "Convert COLOR-NAME to a RGB color value."
19648 (apply 'format "%s,%s,%s"
19649 (mapcar 'org-normalize-color
19650 (color-values color-name))))
19652 (defun org-normalize-color (value)
19653 "Return string to be used as color value for an RGB component."
19654 (format "%g" (/ value 65535.0)))
19658 ;; Image display
19660 (defvar-local org-inline-image-overlays nil)
19662 (defun org-toggle-inline-images (&optional include-linked)
19663 "Toggle the display of inline images.
19664 INCLUDE-LINKED is passed to `org-display-inline-images'."
19665 (interactive "P")
19666 (if org-inline-image-overlays
19667 (progn
19668 (org-remove-inline-images)
19669 (when (called-interactively-p 'interactive)
19670 (message "Inline image display turned off")))
19671 (org-display-inline-images include-linked)
19672 (when (called-interactively-p 'interactive)
19673 (message (if org-inline-image-overlays
19674 (format "%d images displayed inline"
19675 (length org-inline-image-overlays))
19676 "No images to display inline")))))
19678 (defun org-redisplay-inline-images ()
19679 "Refresh the display of inline images."
19680 (interactive)
19681 (if (not org-inline-image-overlays)
19682 (org-toggle-inline-images)
19683 (org-toggle-inline-images)
19684 (org-toggle-inline-images)))
19686 (defun org-display-inline-images (&optional include-linked refresh beg end)
19687 "Display inline images.
19689 An inline image is a link which follows either of these
19690 conventions:
19692 1. Its path is a file with an extension matching return value
19693 from `image-file-name-regexp' and it has no contents.
19695 2. Its description consists in a single link of the previous
19696 type.
19698 When optional argument INCLUDE-LINKED is non-nil, also links with
19699 a text description part will be inlined. This can be nice for
19700 a quick look at those images, but it does not reflect what
19701 exported files will look like.
19703 When optional argument REFRESH is non-nil, refresh existing
19704 images between BEG and END. This will create new image displays
19705 only if necessary. BEG and END default to the buffer
19706 boundaries."
19707 (interactive "P")
19708 (when (display-graphic-p)
19709 (unless refresh
19710 (org-remove-inline-images)
19711 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19712 (org-with-wide-buffer
19713 (goto-char (or beg (point-min)))
19714 (let ((case-fold-search t)
19715 (file-extension-re (image-file-name-regexp)))
19716 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19717 (let ((link (save-match-data (org-element-context))))
19718 ;; Check if we're at an inline image.
19719 (when (and (equal (org-element-property :type link) "file")
19720 (or include-linked
19721 (not (org-element-property :contents-begin link)))
19722 (let ((parent (org-element-property :parent link)))
19723 (or (not (eq (org-element-type parent) 'link))
19724 (not (cdr (org-element-contents parent)))))
19725 (string-match-p file-extension-re
19726 (org-element-property :path link)))
19727 (let ((file (expand-file-name
19728 (org-link-unescape
19729 (org-element-property :path link)))))
19730 (when (file-exists-p file)
19731 (let ((width
19732 ;; Apply `org-image-actual-width' specifications.
19733 (cond
19734 ((not (image-type-available-p 'imagemagick)) nil)
19735 ((eq org-image-actual-width t) nil)
19736 ((listp org-image-actual-width)
19738 ;; First try to find a width among
19739 ;; attributes associated to the paragraph
19740 ;; containing link.
19741 (let ((paragraph
19742 (let ((e link))
19743 (while (and (setq e (org-element-property
19744 :parent e))
19745 (not (eq (org-element-type e)
19746 'paragraph))))
19747 e)))
19748 (when paragraph
19749 (save-excursion
19750 (goto-char (org-element-property :begin paragraph))
19751 (when
19752 (re-search-forward
19753 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19754 (org-element-property
19755 :post-affiliated paragraph)
19757 (string-to-number (match-string 1))))))
19758 ;; Otherwise, fall-back to provided number.
19759 (car org-image-actual-width)))
19760 ((numberp org-image-actual-width)
19761 org-image-actual-width)))
19762 (old (get-char-property-and-overlay
19763 (org-element-property :begin link)
19764 'org-image-overlay)))
19765 (if (and (car-safe old) refresh)
19766 (image-refresh (overlay-get (cdr old) 'display))
19767 (let ((image (create-image file
19768 (and width 'imagemagick)
19770 :width width)))
19771 (when image
19772 (let* ((link
19773 ;; If inline image is the description
19774 ;; of another link, be sure to
19775 ;; consider the latter as the one to
19776 ;; apply the overlay on.
19777 (let ((parent
19778 (org-element-property :parent link)))
19779 (if (eq (org-element-type parent) 'link)
19780 parent
19781 link)))
19782 (ov (make-overlay
19783 (org-element-property :begin link)
19784 (progn
19785 (goto-char
19786 (org-element-property :end link))
19787 (skip-chars-backward " \t")
19788 (point)))))
19789 (overlay-put ov 'display image)
19790 (overlay-put ov 'face 'default)
19791 (overlay-put ov 'org-image-overlay t)
19792 (overlay-put
19793 ov 'modification-hooks
19794 (list 'org-display-inline-remove-overlay))
19795 (push ov org-inline-image-overlays)))))))))))))))
19797 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19798 "Remove inline-display overlay if a corresponding region is modified."
19799 (let ((inhibit-modification-hooks t))
19800 (when (and ov after)
19801 (delete ov org-inline-image-overlays)
19802 (delete-overlay ov))))
19804 (defun org-remove-inline-images ()
19805 "Remove inline display of images."
19806 (interactive)
19807 (mapc #'delete-overlay org-inline-image-overlays)
19808 (setq org-inline-image-overlays nil))
19810 ;;;; Key bindings
19812 ;; Outline functions from `outline-mode-prefix-map'
19813 ;; that can be remapped in Org:
19814 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19815 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19816 (define-key org-mode-map [remap outline-forward-same-level]
19817 'org-forward-heading-same-level)
19818 (define-key org-mode-map [remap outline-backward-same-level]
19819 'org-backward-heading-same-level)
19820 (define-key org-mode-map [remap outline-show-branches]
19821 'org-kill-note-or-show-branches)
19822 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19823 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19824 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19825 (define-key org-mode-map [remap outline-next-visible-heading]
19826 'org-next-visible-heading)
19827 (define-key org-mode-map [remap outline-previous-visible-heading]
19828 'org-previous-visible-heading)
19829 (define-key org-mode-map [remap show-children] 'org-show-children)
19831 ;; Outline functions from `outline-mode-prefix-map' that can not
19832 ;; be remapped in Org:
19834 ;; - the column "key binding" shows whether the Outline function is still
19835 ;; available in Org mode on the same key that it has been bound to in
19836 ;; Outline mode:
19837 ;; - "overridden": key used for a different functionality in Org mode
19838 ;; - else: key still bound to the same Outline function in Org mode
19840 ;; | Outline function | key binding | Org replacement |
19841 ;; |------------------------------------+-------------+--------------------------|
19842 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19843 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19844 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19845 ;; | `show-entry' | overridden | no replacement |
19846 ;; | `show-branches' | `C-c C-k' | still same function |
19847 ;; | `show-subtree' | overridden | visibility cycling |
19848 ;; | `show-all' | overridden | no replacement |
19849 ;; | `hide-subtree' | overridden | visibility cycling |
19850 ;; | `hide-body' | overridden | no replacement |
19851 ;; | `hide-entry' | overridden | visibility cycling |
19852 ;; | `hide-leaves' | overridden | no replacement |
19853 ;; | `hide-sublevels' | overridden | no replacement |
19854 ;; | `hide-other' | overridden | no replacement |
19856 ;; Make `C-c C-x' a prefix key
19857 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19859 ;; TAB key with modifiers
19860 (org-defkey org-mode-map "\C-i" 'org-cycle)
19861 (org-defkey org-mode-map [(tab)] 'org-cycle)
19862 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19863 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19864 ;; The following line is necessary under Suse GNU/Linux
19865 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19866 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19867 (define-key org-mode-map [backtab] 'org-shifttab)
19869 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19870 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19871 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19873 ;; Cursor keys with modifiers
19874 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19875 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19876 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19877 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19879 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19880 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19881 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19882 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19883 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19884 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19886 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19887 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19888 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19889 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19891 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19892 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19893 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19894 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19896 ;; Babel keys
19897 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19898 (dolist (pair org-babel-key-bindings)
19899 (define-key org-babel-map (car pair) (cdr pair)))
19901 ;;; Extra keys for tty access.
19902 ;; We only set them when really needed because otherwise the
19903 ;; menus don't show the simple keys
19905 (when (or org-use-extra-keys (not window-system))
19906 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19907 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19908 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19909 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19910 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19911 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19912 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19913 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19914 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19915 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19916 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19917 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19918 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19919 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19920 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19921 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19922 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19923 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19924 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19925 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19926 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19927 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19928 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19929 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19930 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19931 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19932 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19933 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19935 ;; All the other keys
19937 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19938 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19939 (if (boundp 'narrow-map)
19940 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19941 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19942 (if (boundp 'narrow-map)
19943 (org-defkey narrow-map "b" 'org-narrow-to-block)
19944 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19945 (if (boundp 'narrow-map)
19946 (org-defkey narrow-map "e" 'org-narrow-to-element)
19947 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19948 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19949 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19950 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19951 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19952 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19953 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19954 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19955 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19956 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19957 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19958 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19959 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19960 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19961 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19962 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19963 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19964 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19965 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19966 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19967 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19968 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19969 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19970 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19971 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19972 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19973 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19974 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19975 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19976 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19977 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19978 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19979 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19980 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19981 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19982 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19983 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19984 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19985 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19986 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19987 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19988 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19989 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19990 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19991 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19992 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19993 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19994 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19995 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19996 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19997 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19998 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19999 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
20000 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
20001 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20002 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
20003 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
20004 (org-defkey org-mode-map "\C-c^" 'org-sort)
20005 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20006 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20007 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20008 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20009 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20010 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20011 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20012 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20013 (org-defkey org-mode-map "\C-m" 'org-return)
20014 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20015 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20016 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20017 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20018 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20019 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20020 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20021 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20022 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20023 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20024 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20025 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20026 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20027 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20028 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20029 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20030 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20031 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20032 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20033 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20034 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20035 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20036 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20037 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20038 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20040 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20041 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20042 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20044 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20045 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20046 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20047 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20048 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20049 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20050 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20051 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20052 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20053 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20054 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20055 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20056 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20057 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20058 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20059 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20060 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20061 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20062 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20063 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20064 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20065 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20067 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20068 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20069 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20070 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20071 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20073 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20075 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20077 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20078 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20080 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20083 (defconst org-speed-commands-default
20085 ("Outline Navigation")
20086 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20087 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20088 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20089 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20090 ("F" . org-next-block)
20091 ("B" . org-previous-block)
20092 ("u" . (org-speed-move-safe 'outline-up-heading))
20093 ("j" . org-goto)
20094 ("g" . (org-refile t))
20095 ("Outline Visibility")
20096 ("c" . org-cycle)
20097 ("C" . org-shifttab)
20098 (" " . org-display-outline-path)
20099 ("s" . org-narrow-to-subtree)
20100 ("=" . org-columns)
20101 ("Outline Structure Editing")
20102 ("U" . org-metaup)
20103 ("D" . org-metadown)
20104 ("r" . org-metaright)
20105 ("l" . org-metaleft)
20106 ("R" . org-shiftmetaright)
20107 ("L" . org-shiftmetaleft)
20108 ("i" . (progn (forward-char 1) (call-interactively
20109 'org-insert-heading-respect-content)))
20110 ("^" . org-sort)
20111 ("w" . org-refile)
20112 ("a" . org-archive-subtree-default-with-confirmation)
20113 ("@" . org-mark-subtree)
20114 ("#" . org-toggle-comment)
20115 ("Clock Commands")
20116 ("I" . org-clock-in)
20117 ("O" . org-clock-out)
20118 ("Meta Data Editing")
20119 ("t" . org-todo)
20120 ("," . (org-priority))
20121 ("0" . (org-priority ?\ ))
20122 ("1" . (org-priority ?A))
20123 ("2" . (org-priority ?B))
20124 ("3" . (org-priority ?C))
20125 (":" . org-set-tags-command)
20126 ("e" . org-set-effort)
20127 ("E" . org-inc-effort)
20128 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20129 (org-entry-put (point) "APPT_WARNTIME" m)))
20130 ("Agenda Views etc")
20131 ("v" . org-agenda)
20132 ("/" . org-sparse-tree)
20133 ("Misc")
20134 ("o" . org-open-at-point)
20135 ("?" . org-speed-command-help)
20136 ("<" . (org-agenda-set-restriction-lock 'subtree))
20137 (">" . (org-agenda-remove-restriction-lock))
20139 "The default speed commands.")
20141 (defun org-print-speed-command (e)
20142 (if (> (length (car e)) 1)
20143 (progn
20144 (princ "\n")
20145 (princ (car e))
20146 (princ "\n")
20147 (princ (make-string (length (car e)) ?-))
20148 (princ "\n"))
20149 (princ (car e))
20150 (princ " ")
20151 (if (symbolp (cdr e))
20152 (princ (symbol-name (cdr e)))
20153 (prin1 (cdr e)))
20154 (princ "\n")))
20156 (defun org-speed-command-help ()
20157 "Show the available speed commands."
20158 (interactive)
20159 (if (not org-use-speed-commands)
20160 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20161 (with-output-to-temp-buffer "*Help*"
20162 (princ "User-defined Speed commands\n===========================\n")
20163 (mapc #'org-print-speed-command org-speed-commands-user)
20164 (princ "\n")
20165 (princ "Built-in Speed commands\n=======================\n")
20166 (mapc #'org-print-speed-command org-speed-commands-default))
20167 (with-current-buffer "*Help*"
20168 (setq truncate-lines t))))
20170 (defun org-speed-move-safe (cmd)
20171 "Execute CMD, but make sure that the cursor always ends up in a headline.
20172 If not, return to the original position and throw an error."
20173 (interactive)
20174 (let ((pos (point)))
20175 (call-interactively cmd)
20176 (unless (and (bolp) (org-at-heading-p))
20177 (goto-char pos)
20178 (error "Boundary reached while executing %s" cmd))))
20180 (defvar org-self-insert-command-undo-counter 0)
20182 (defvar org-table-auto-blank-field) ; defined in org-table.el
20183 (defvar org-speed-command nil)
20185 (defun org-speed-command-activate (keys)
20186 "Hook for activating single-letter speed commands.
20187 `org-speed-commands-default' specifies a minimal command set.
20188 Use `org-speed-commands-user' for further customization."
20189 (when (or (and (bolp) (looking-at org-outline-regexp))
20190 (and (functionp org-use-speed-commands)
20191 (funcall org-use-speed-commands)))
20192 (cdr (assoc keys (append org-speed-commands-user
20193 org-speed-commands-default)))))
20195 (defun org-babel-speed-command-activate (keys)
20196 "Hook for activating single-letter code block commands."
20197 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20198 (cdr (assoc keys org-babel-key-bindings))))
20200 (defcustom org-speed-command-hook
20201 '(org-speed-command-default-hook org-babel-speed-command-hook)
20202 "Hook for activating speed commands at strategic locations.
20203 Hook functions are called in sequence until a valid handler is
20204 found.
20206 Each hook takes a single argument, a user-pressed command key
20207 which is also a `self-insert-command' from the global map.
20209 Within the hook, examine the cursor position and the command key
20210 and return nil or a valid handler as appropriate. Handler could
20211 be one of an interactive command, a function, or a form.
20213 Set `org-use-speed-commands' to non-nil value to enable this
20214 hook. The default setting is `org-speed-command-activate'."
20215 :group 'org-structure
20216 :version "24.1"
20217 :type 'hook)
20219 (defun org-self-insert-command (N)
20220 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20221 If the cursor is in a table looking at whitespace, the whitespace is
20222 overwritten, and the table is not marked as requiring realignment."
20223 (interactive "p")
20224 (org-check-before-invisible-edit 'insert)
20225 (cond
20226 ((and org-use-speed-commands
20227 (let ((kv (this-command-keys-vector)))
20228 (setq org-speed-command
20229 (run-hook-with-args-until-success
20230 'org-speed-command-hook
20231 (make-string 1 (aref kv (1- (length kv))))))))
20232 (cond
20233 ((commandp org-speed-command)
20234 (setq this-command org-speed-command)
20235 (call-interactively org-speed-command))
20236 ((functionp org-speed-command)
20237 (funcall org-speed-command))
20238 ((and org-speed-command (listp org-speed-command))
20239 (eval org-speed-command))
20240 (t (let (org-use-speed-commands)
20241 (call-interactively 'org-self-insert-command)))))
20242 ((and
20243 (org-at-table-p)
20244 (progn
20245 ;; Check if we blank the field, and if that triggers align.
20246 (and (featurep 'org-table) org-table-auto-blank-field
20247 (memq last-command
20248 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20249 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20250 ;; Got extra space, this field does not determine
20251 ;; column width.
20252 (let (org-table-may-need-update) (org-table-blank-field))
20253 ;; No extra space, this field may determine column
20254 ;; width.
20255 (org-table-blank-field)))
20257 (eq N 1)
20258 (looking-at "[^|\n]* \\( \\)|"))
20259 ;; There is room for insertion without re-aligning the table.
20260 (delete-region (match-beginning 1) (match-end 1))
20261 (self-insert-command N))
20263 (setq org-table-may-need-update t)
20264 (self-insert-command N)
20265 (org-fix-tags-on-the-fly)
20266 (when org-self-insert-cluster-for-undo
20267 (if (not (eq last-command 'org-self-insert-command))
20268 (setq org-self-insert-command-undo-counter 1)
20269 (if (>= org-self-insert-command-undo-counter 20)
20270 (setq org-self-insert-command-undo-counter 1)
20271 (and (> org-self-insert-command-undo-counter 0)
20272 buffer-undo-list (listp buffer-undo-list)
20273 (not (cadr buffer-undo-list)) ; remove nil entry
20274 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20275 (setq org-self-insert-command-undo-counter
20276 (1+ org-self-insert-command-undo-counter))))))))
20278 (defun org-check-before-invisible-edit (kind)
20279 "Check is editing if kind KIND would be dangerous with invisible text around.
20280 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20281 ;; First, try to get out of here as quickly as possible, to reduce overhead
20282 (when (and org-catch-invisible-edits
20283 (or (not (boundp 'visible-mode)) (not visible-mode))
20284 (or (get-char-property (point) 'invisible)
20285 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20286 ;; OK, we need to take a closer look
20287 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20288 (invisible-before-point (unless (bobp) (get-char-property
20289 (1- (point)) 'invisible)))
20290 (border-and-ok-direction
20292 ;; Check if we are acting predictably before invisible text
20293 (and invisible-at-point (not invisible-before-point)
20294 (memq kind '(insert delete-backward)))
20295 ;; Check if we are acting predictably after invisible text
20296 ;; This works not well, and I have turned it off. It seems
20297 ;; better to always show and stop after invisible text.
20298 ;; (and (not invisible-at-point) invisible-before-point
20299 ;; (memq kind '(insert delete)))
20301 (when (or (memq invisible-at-point '(outline org-hide-block t))
20302 (memq invisible-before-point '(outline org-hide-block t)))
20303 (when (eq org-catch-invisible-edits 'error)
20304 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20305 (if (and org-custom-properties-overlays
20306 (y-or-n-p "Display invisible properties in this buffer? "))
20307 (org-toggle-custom-properties-visibility)
20308 ;; Make the area visible
20309 (save-excursion
20310 (when invisible-before-point
20311 (goto-char (previous-single-char-property-change
20312 (point) 'invisible)))
20313 (outline-show-subtree))
20314 (cond
20315 ((eq org-catch-invisible-edits 'show)
20316 ;; That's it, we do the edit after showing
20317 (message
20318 "Unfolding invisible region around point before editing")
20319 (sit-for 1))
20320 ((and (eq org-catch-invisible-edits 'smart)
20321 border-and-ok-direction)
20322 (message "Unfolding invisible region around point before editing"))
20324 ;; Don't do the edit, make the user repeat it in full visibility
20325 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20327 (defun org-fix-tags-on-the-fly ()
20328 (when (and (equal (char-after (point-at-bol)) ?*)
20329 (org-at-heading-p))
20330 (org-align-tags-here org-tags-column)))
20332 (defun org-delete-backward-char (N)
20333 "Like `delete-backward-char', insert whitespace at field end in tables.
20334 When deleting backwards, in tables this function will insert whitespace in
20335 front of the next \"|\" separator, to keep the table aligned. The table will
20336 still be marked for re-alignment if the field did fill the entire column,
20337 because, in this case the deletion might narrow the column."
20338 (interactive "p")
20339 (save-match-data
20340 (org-check-before-invisible-edit 'delete-backward)
20341 (if (and (org-at-table-p)
20342 (eq N 1)
20343 (string-match "|" (buffer-substring (point-at-bol) (point)))
20344 (looking-at ".*?|"))
20345 (let ((pos (point))
20346 (noalign (looking-at "[^|\n\r]* |"))
20347 (c org-table-may-need-update))
20348 (backward-delete-char N)
20349 (unless overwrite-mode
20350 (skip-chars-forward "^|")
20351 (insert " ")
20352 (goto-char (1- pos)))
20353 ;; noalign: if there were two spaces at the end, this field
20354 ;; does not determine the width of the column.
20355 (when noalign (setq org-table-may-need-update c)))
20356 (backward-delete-char N)
20357 (org-fix-tags-on-the-fly))))
20359 (defun org-delete-char (N)
20360 "Like `delete-char', but insert whitespace at field end in tables.
20361 When deleting characters, in tables this function will insert whitespace in
20362 front of the next \"|\" separator, to keep the table aligned. The table will
20363 still be marked for re-alignment if the field did fill the entire column,
20364 because, in this case the deletion might narrow the column."
20365 (interactive "p")
20366 (save-match-data
20367 (org-check-before-invisible-edit 'delete)
20368 (if (and (org-at-table-p)
20369 (not (bolp))
20370 (not (= (char-after) ?|))
20371 (eq N 1))
20372 (if (looking-at ".*?|")
20373 (let ((pos (point))
20374 (noalign (looking-at "[^|\n\r]* |"))
20375 (c org-table-may-need-update))
20376 (replace-match
20377 (concat (substring (match-string 0) 1 -1) " |") nil t)
20378 (goto-char pos)
20379 ;; noalign: if there were two spaces at the end, this field
20380 ;; does not determine the width of the column.
20381 (when noalign (setq org-table-may-need-update c)))
20382 (delete-char N))
20383 (delete-char N)
20384 (org-fix-tags-on-the-fly))))
20386 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20387 (put 'org-self-insert-command 'delete-selection
20388 (lambda ()
20389 (not (run-hook-with-args-until-success
20390 'self-insert-uses-region-functions))))
20391 (put 'orgtbl-self-insert-command 'delete-selection
20392 (lambda ()
20393 (not (run-hook-with-args-until-success
20394 'self-insert-uses-region-functions))))
20395 (put 'org-delete-char 'delete-selection 'supersede)
20396 (put 'org-delete-backward-char 'delete-selection 'supersede)
20397 (put 'org-yank 'delete-selection 'yank)
20399 ;; Make `flyspell-mode' delay after some commands
20400 (put 'org-self-insert-command 'flyspell-delayed t)
20401 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20402 (put 'org-delete-char 'flyspell-delayed t)
20403 (put 'org-delete-backward-char 'flyspell-delayed t)
20405 ;; Make pabbrev-mode expand after org-mode commands
20406 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20407 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20409 (defun org-remap (map &rest commands)
20410 "In MAP, remap the functions given in COMMANDS.
20411 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20412 (let (new old)
20413 (while commands
20414 (setq old (pop commands) new (pop commands))
20415 (if (fboundp 'command-remapping)
20416 (org-defkey map (vector 'remap old) new)
20417 (substitute-key-definition old new map global-map)))))
20419 (defun org-transpose-words ()
20420 "Transpose words for Org.
20421 This uses the `org-mode-transpose-word-syntax-table' syntax
20422 table, which interprets characters in `org-emphasis-alist' as
20423 word constituents."
20424 (interactive)
20425 (with-syntax-table org-mode-transpose-word-syntax-table
20426 (call-interactively 'transpose-words)))
20427 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20429 (when (eq org-enable-table-editor 'optimized)
20430 ;; If the user wants maximum table support, we need to hijack
20431 ;; some standard editing functions
20432 (org-remap org-mode-map
20433 'self-insert-command 'org-self-insert-command
20434 'delete-char 'org-delete-char
20435 'delete-backward-char 'org-delete-backward-char)
20436 (org-defkey org-mode-map "|" 'org-force-self-insert))
20438 (defvar org-ctrl-c-ctrl-c-hook nil
20439 "Hook for functions attaching themselves to `C-c C-c'.
20441 This can be used to add additional functionality to the C-c C-c
20442 key which executes context-dependent commands. This hook is run
20443 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20444 run after the last test.
20446 Each function will be called with no arguments. The function
20447 must check if the context is appropriate for it to act. If yes,
20448 it should do its thing and then return a non-nil value. If the
20449 context is wrong, just do nothing and return nil.")
20451 (defvar org-ctrl-c-ctrl-c-final-hook nil
20452 "Hook for functions attaching themselves to `C-c C-c'.
20454 This can be used to add additional functionality to the C-c C-c
20455 key which executes context-dependent commands. This hook is run
20456 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20457 before the first test.
20459 Each function will be called with no arguments. The function
20460 must check if the context is appropriate for it to act. If yes,
20461 it should do its thing and then return a non-nil value. If the
20462 context is wrong, just do nothing and return nil.")
20464 (defvar org-tab-first-hook nil
20465 "Hook for functions to attach themselves to TAB.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.
20467 This hook runs as the first action when TAB is pressed, even before
20468 `org-cycle' messes around with the `outline-regexp' to cater for
20469 inline tasks and plain list item folding.
20470 If any function in this hook returns t, any other actions that
20471 would have been caused by TAB (such as table field motion or visibility
20472 cycling) will not occur.")
20474 (defvar org-tab-after-check-for-table-hook nil
20475 "Hook for functions to attach themselves to TAB.
20476 See `org-ctrl-c-ctrl-c-hook' for more information.
20477 This hook runs after it has been established that the cursor is not in a
20478 table, but before checking if the cursor is in a headline or if global cycling
20479 should be done.
20480 If any function in this hook returns t, not other actions like visibility
20481 cycling will be done.")
20483 (defvar org-tab-after-check-for-cycling-hook nil
20484 "Hook for functions to attach themselves to TAB.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.
20486 This hook runs after it has been established that not table field motion and
20487 not visibility should be done because of current context. This is probably
20488 the place where a package like yasnippets can hook in.")
20490 (defvar org-tab-before-tab-emulation-hook nil
20491 "Hook for functions to attach themselves to TAB.
20492 See `org-ctrl-c-ctrl-c-hook' for more information.
20493 This hook runs after every other options for TAB have been exhausted, but
20494 before indentation and \t insertion takes place.")
20496 (defvar org-metaleft-hook nil
20497 "Hook for functions attaching themselves to `M-left'.
20498 See `org-ctrl-c-ctrl-c-hook' for more information.")
20499 (defvar org-metaright-hook nil
20500 "Hook for functions attaching themselves to `M-right'.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20502 (defvar org-metaup-hook nil
20503 "Hook for functions attaching themselves to `M-up'.
20504 See `org-ctrl-c-ctrl-c-hook' for more information.")
20505 (defvar org-metadown-hook nil
20506 "Hook for functions attaching themselves to `M-down'.
20507 See `org-ctrl-c-ctrl-c-hook' for more information.")
20508 (defvar org-shiftmetaleft-hook nil
20509 "Hook for functions attaching themselves to `M-S-left'.
20510 See `org-ctrl-c-ctrl-c-hook' for more information.")
20511 (defvar org-shiftmetaright-hook nil
20512 "Hook for functions attaching themselves to `M-S-right'.
20513 See `org-ctrl-c-ctrl-c-hook' for more information.")
20514 (defvar org-shiftmetaup-hook nil
20515 "Hook for functions attaching themselves to `M-S-up'.
20516 See `org-ctrl-c-ctrl-c-hook' for more information.")
20517 (defvar org-shiftmetadown-hook nil
20518 "Hook for functions attaching themselves to `M-S-down'.
20519 See `org-ctrl-c-ctrl-c-hook' for more information.")
20520 (defvar org-metareturn-hook nil
20521 "Hook for functions attaching themselves to `M-RET'.
20522 See `org-ctrl-c-ctrl-c-hook' for more information.")
20523 (defvar org-shiftup-hook nil
20524 "Hook for functions attaching themselves to `S-up'.
20525 See `org-ctrl-c-ctrl-c-hook' for more information.")
20526 (defvar org-shiftup-final-hook nil
20527 "Hook for functions attaching themselves to `S-up'.
20528 This one runs after all other options except shift-select have been excluded.
20529 See `org-ctrl-c-ctrl-c-hook' for more information.")
20530 (defvar org-shiftdown-hook nil
20531 "Hook for functions attaching themselves to `S-down'.
20532 See `org-ctrl-c-ctrl-c-hook' for more information.")
20533 (defvar org-shiftdown-final-hook nil
20534 "Hook for functions attaching themselves to `S-down'.
20535 This one runs after all other options except shift-select have been excluded.
20536 See `org-ctrl-c-ctrl-c-hook' for more information.")
20537 (defvar org-shiftleft-hook nil
20538 "Hook for functions attaching themselves to `S-left'.
20539 See `org-ctrl-c-ctrl-c-hook' for more information.")
20540 (defvar org-shiftleft-final-hook nil
20541 "Hook for functions attaching themselves to `S-left'.
20542 This one runs after all other options except shift-select have been excluded.
20543 See `org-ctrl-c-ctrl-c-hook' for more information.")
20544 (defvar org-shiftright-hook nil
20545 "Hook for functions attaching themselves to `S-right'.
20546 See `org-ctrl-c-ctrl-c-hook' for more information.")
20547 (defvar org-shiftright-final-hook nil
20548 "Hook for functions attaching themselves to `S-right'.
20549 This one runs after all other options except shift-select have been excluded.
20550 See `org-ctrl-c-ctrl-c-hook' for more information.")
20552 (defun org-modifier-cursor-error ()
20553 "Throw an error, a modified cursor command was applied in wrong context."
20554 (user-error "This command is active in special context like tables, headlines or items"))
20556 (defun org-shiftselect-error ()
20557 "Throw an error because Shift-Cursor command was applied in wrong context."
20558 (if (and (boundp 'shift-select-mode) shift-select-mode)
20559 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20560 (user-error "This command works only in special context like headlines or timestamps")))
20562 (defun org-call-for-shift-select (cmd)
20563 (let ((this-command-keys-shift-translated t))
20564 (call-interactively cmd)))
20566 (defun org-shifttab (&optional arg)
20567 "Global visibility cycling or move to previous table field.
20568 Call `org-table-previous-field' within a table.
20569 When ARG is nil, cycle globally through visibility states.
20570 When ARG is a numeric prefix, show contents of this level."
20571 (interactive "P")
20572 (cond
20573 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20574 ((integerp arg)
20575 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20576 (message "Content view to level: %d" arg)
20577 (org-content (prefix-numeric-value arg2))
20578 (org-cycle-show-empty-lines t)
20579 (setq org-cycle-global-status 'overview)))
20580 (t (call-interactively 'org-global-cycle))))
20582 (defun org-shiftmetaleft ()
20583 "Promote subtree or delete table column.
20584 Calls `org-promote-subtree', `org-outdent-item-tree', or
20585 `org-table-delete-column', depending on context. See the
20586 individual commands for more information."
20587 (interactive)
20588 (cond
20589 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20590 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20591 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20592 ((if (not (org-region-active-p)) (org-at-item-p)
20593 (save-excursion (goto-char (region-beginning))
20594 (org-at-item-p)))
20595 (call-interactively 'org-outdent-item-tree))
20596 (t (org-modifier-cursor-error))))
20598 (defun org-shiftmetaright ()
20599 "Demote subtree or insert table column.
20600 Calls `org-demote-subtree', `org-indent-item-tree', or
20601 `org-table-insert-column', depending on context. See the
20602 individual commands for more information."
20603 (interactive)
20604 (cond
20605 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20606 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20607 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20608 ((if (not (org-region-active-p)) (org-at-item-p)
20609 (save-excursion (goto-char (region-beginning))
20610 (org-at-item-p)))
20611 (call-interactively 'org-indent-item-tree))
20612 (t (org-modifier-cursor-error))))
20614 (defun org-shiftmetaup (&optional _arg)
20615 "Drag the line at point up.
20616 In a table, kill the current row.
20617 On a clock timestamp, update the value of the timestamp like `S-<up>'
20618 but also adjust the previous clocked item in the clock history.
20619 Everywhere else, drag the line at point up."
20620 (interactive "P")
20621 (cond
20622 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20623 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20624 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20625 (call-interactively 'org-timestamp-up)))
20626 (t (call-interactively 'org-drag-line-backward))))
20628 (defun org-shiftmetadown (&optional _arg)
20629 "Drag the line at point down.
20630 In a table, insert an empty row at the current line.
20631 On a clock timestamp, update the value of the timestamp like `S-<down>'
20632 but also adjust the previous clocked item in the clock history.
20633 Everywhere else, drag the line at point down."
20634 (interactive "P")
20635 (cond
20636 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20637 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20638 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20639 (call-interactively 'org-timestamp-down)))
20640 (t (call-interactively 'org-drag-line-forward))))
20642 (defsubst org-hidden-tree-error ()
20643 (user-error
20644 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20646 (defun org-metaleft (&optional _arg)
20647 "Promote heading, list item at point or move table column left.
20649 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20650 depending on context. With no specific context, calls the Emacs
20651 default `backward-word'. See the individual commands for more
20652 information.
20654 This function runs the hook `org-metaleft-hook' as a first step,
20655 and returns at first non-nil value."
20656 (interactive "P")
20657 (cond
20658 ((run-hook-with-args-until-success 'org-metaleft-hook))
20659 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20660 ((org-with-limited-levels
20661 (or (org-at-heading-p)
20662 (and (org-region-active-p)
20663 (save-excursion
20664 (goto-char (region-beginning))
20665 (org-at-heading-p)))))
20666 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20667 (call-interactively 'org-do-promote))
20668 ;; At an inline task.
20669 ((org-at-heading-p)
20670 (call-interactively 'org-inlinetask-promote))
20671 ((or (org-at-item-p)
20672 (and (org-region-active-p)
20673 (save-excursion
20674 (goto-char (region-beginning))
20675 (org-at-item-p))))
20676 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20677 (call-interactively 'org-outdent-item))
20678 (t (call-interactively 'backward-word))))
20680 (defun org-metaright (&optional _arg)
20681 "Demote heading, list item at point or move table column right.
20683 In front of a drawer or a block keyword, indent it correctly.
20685 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20686 `org-indnet-drawer' or `org-indent-block' depending on context.
20687 With no specific context, calls the Emacs default `forward-word'.
20688 See the individual commands for more information.
20690 This function runs the hook `org-metaright-hook' as a first step,
20691 and returns at first non-nil value."
20692 (interactive "P")
20693 (cond
20694 ((run-hook-with-args-until-success 'org-metaright-hook))
20695 ((org-at-table-p) (call-interactively 'org-table-move-column))
20696 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20697 ((org-at-block-p) (call-interactively 'org-indent-block))
20698 ((org-with-limited-levels
20699 (or (org-at-heading-p)
20700 (and (org-region-active-p)
20701 (save-excursion
20702 (goto-char (region-beginning))
20703 (org-at-heading-p)))))
20704 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20705 (call-interactively 'org-do-demote))
20706 ;; At an inline task.
20707 ((org-at-heading-p)
20708 (call-interactively 'org-inlinetask-demote))
20709 ((or (org-at-item-p)
20710 (and (org-region-active-p)
20711 (save-excursion
20712 (goto-char (region-beginning))
20713 (org-at-item-p))))
20714 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20715 (call-interactively 'org-indent-item))
20716 (t (call-interactively 'forward-word))))
20718 (defun org-check-for-hidden (what)
20719 "Check if there are hidden headlines/items in the current visual line.
20720 WHAT can be either `headlines' or `items'. If the current line is
20721 an outline or item heading and it has a folded subtree below it,
20722 this function returns t, nil otherwise."
20723 (let ((re (cond
20724 ((eq what 'headlines) org-outline-regexp-bol)
20725 ((eq what 'items) (org-item-beginning-re))
20726 (t (error "This should not happen"))))
20727 beg end)
20728 (save-excursion
20729 (catch 'exit
20730 (unless (org-region-active-p)
20731 (setq beg (point-at-bol))
20732 (beginning-of-line 2)
20733 (while (and (not (eobp)) ;; this is like `next-line'
20734 (get-char-property (1- (point)) 'invisible))
20735 (beginning-of-line 2))
20736 (setq end (point))
20737 (goto-char beg)
20738 (goto-char (point-at-eol))
20739 (setq end (max end (point)))
20740 (while (re-search-forward re end t)
20741 (when (get-char-property (match-beginning 0) 'invisible)
20742 (throw 'exit t))))
20743 nil))))
20745 (defun org-metaup (&optional _arg)
20746 "Move subtree up or move table row up.
20747 Calls `org-move-subtree-up' or `org-table-move-row' or
20748 `org-move-item-up', depending on context. See the individual commands
20749 for more information."
20750 (interactive "P")
20751 (cond
20752 ((run-hook-with-args-until-success 'org-metaup-hook))
20753 ((org-region-active-p)
20754 (let* ((a (min (region-beginning) (region-end)))
20755 (b (1- (max (region-beginning) (region-end))))
20756 (c (save-excursion (goto-char a)
20757 (move-beginning-of-line 0)))
20758 (d (save-excursion (goto-char a)
20759 (move-end-of-line 0) (point))))
20760 (transpose-regions a b c d)
20761 (goto-char c)))
20762 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20763 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20764 ((org-at-item-p) (call-interactively 'org-move-item-up))
20765 (t (org-drag-element-backward))))
20767 (defun org-metadown (&optional _arg)
20768 "Move subtree down or move table row down.
20769 Calls `org-move-subtree-down' or `org-table-move-row' or
20770 `org-move-item-down', depending on context. See the individual
20771 commands for more information."
20772 (interactive "P")
20773 (cond
20774 ((run-hook-with-args-until-success 'org-metadown-hook))
20775 ((org-region-active-p)
20776 (let* ((a (min (region-beginning) (region-end)))
20777 (b (max (region-beginning) (region-end)))
20778 (c (save-excursion (goto-char b)
20779 (move-beginning-of-line 1)))
20780 (d (save-excursion (goto-char b)
20781 (move-end-of-line 1) (1+ (point)))))
20782 (transpose-regions a b c d)
20783 (goto-char d)))
20784 ((org-at-table-p) (call-interactively 'org-table-move-row))
20785 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20786 ((org-at-item-p) (call-interactively 'org-move-item-down))
20787 (t (org-drag-element-forward))))
20789 (defun org-shiftup (&optional arg)
20790 "Increase item in timestamp or increase priority of current headline.
20791 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20792 depending on context. See the individual commands for more information."
20793 (interactive "P")
20794 (cond
20795 ((run-hook-with-args-until-success 'org-shiftup-hook))
20796 ((and org-support-shift-select (org-region-active-p))
20797 (org-call-for-shift-select 'previous-line))
20798 ((org-at-timestamp-p t)
20799 (call-interactively (if org-edit-timestamp-down-means-later
20800 'org-timestamp-down 'org-timestamp-up)))
20801 ((and (not (eq org-support-shift-select 'always))
20802 org-enable-priority-commands
20803 (org-at-heading-p))
20804 (call-interactively 'org-priority-up))
20805 ((and (not org-support-shift-select) (org-at-item-p))
20806 (call-interactively 'org-previous-item))
20807 ((org-clocktable-try-shift 'up arg))
20808 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20809 (org-support-shift-select
20810 (org-call-for-shift-select 'previous-line))
20811 (t (org-shiftselect-error))))
20813 (defun org-shiftdown (&optional arg)
20814 "Decrease item in timestamp or decrease priority of current headline.
20815 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20816 depending on context. See the individual commands for more information."
20817 (interactive "P")
20818 (cond
20819 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'next-line))
20822 ((org-at-timestamp-p t)
20823 (call-interactively (if org-edit-timestamp-down-means-later
20824 'org-timestamp-up 'org-timestamp-down)))
20825 ((and (not (eq org-support-shift-select 'always))
20826 org-enable-priority-commands
20827 (org-at-heading-p))
20828 (call-interactively 'org-priority-down))
20829 ((and (not org-support-shift-select) (org-at-item-p))
20830 (call-interactively 'org-next-item))
20831 ((org-clocktable-try-shift 'down arg))
20832 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20833 (org-support-shift-select
20834 (org-call-for-shift-select 'next-line))
20835 (t (org-shiftselect-error))))
20837 (defun org-shiftright (&optional arg)
20838 "Cycle the thing at point or in the current line, depending on context.
20839 Depending on context, this does one of the following:
20841 - switch a timestamp at point one day into the future
20842 - on a headline, switch to the next TODO keyword.
20843 - on an item, switch entire list to the next bullet type
20844 - on a property line, switch to the next allowed value
20845 - on a clocktable definition line, move time block into the future"
20846 (interactive "P")
20847 (cond
20848 ((run-hook-with-args-until-success 'org-shiftright-hook))
20849 ((and org-support-shift-select (org-region-active-p))
20850 (org-call-for-shift-select 'forward-char))
20851 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20852 ((and (not (eq org-support-shift-select 'always))
20853 (org-at-heading-p))
20854 (let ((org-inhibit-logging
20855 (not org-treat-S-cursor-todo-selection-as-state-change))
20856 (org-inhibit-blocking
20857 (not org-treat-S-cursor-todo-selection-as-state-change)))
20858 (org-call-with-arg 'org-todo 'right)))
20859 ((or (and org-support-shift-select
20860 (not (eq org-support-shift-select 'always))
20861 (org-at-item-bullet-p))
20862 (and (not org-support-shift-select) (org-at-item-p)))
20863 (org-call-with-arg 'org-cycle-list-bullet nil))
20864 ((and (not (eq org-support-shift-select 'always))
20865 (org-at-property-p))
20866 (call-interactively 'org-property-next-allowed-value))
20867 ((org-clocktable-try-shift 'right arg))
20868 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20869 (org-support-shift-select
20870 (org-call-for-shift-select 'forward-char))
20871 (t (org-shiftselect-error))))
20873 (defun org-shiftleft (&optional arg)
20874 "Cycle the thing at point or in the current line, depending on context.
20875 Depending on context, this does one of the following:
20877 - switch a timestamp at point one day into the past
20878 - on a headline, switch to the previous TODO keyword.
20879 - on an item, switch entire list to the previous bullet type
20880 - on a property line, switch to the previous allowed value
20881 - on a clocktable definition line, move time block into the past"
20882 (interactive "P")
20883 (cond
20884 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20885 ((and org-support-shift-select (org-region-active-p))
20886 (org-call-for-shift-select 'backward-char))
20887 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20888 ((and (not (eq org-support-shift-select 'always))
20889 (org-at-heading-p))
20890 (let ((org-inhibit-logging
20891 (not org-treat-S-cursor-todo-selection-as-state-change))
20892 (org-inhibit-blocking
20893 (not org-treat-S-cursor-todo-selection-as-state-change)))
20894 (org-call-with-arg 'org-todo 'left)))
20895 ((or (and org-support-shift-select
20896 (not (eq org-support-shift-select 'always))
20897 (org-at-item-bullet-p))
20898 (and (not org-support-shift-select) (org-at-item-p)))
20899 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20900 ((and (not (eq org-support-shift-select 'always))
20901 (org-at-property-p))
20902 (call-interactively 'org-property-previous-allowed-value))
20903 ((org-clocktable-try-shift 'left arg))
20904 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20905 (org-support-shift-select
20906 (org-call-for-shift-select 'backward-char))
20907 (t (org-shiftselect-error))))
20909 (defun org-shiftcontrolright ()
20910 "Switch to next TODO set."
20911 (interactive)
20912 (cond
20913 ((and org-support-shift-select (org-region-active-p))
20914 (org-call-for-shift-select 'forward-word))
20915 ((and (not (eq org-support-shift-select 'always))
20916 (org-at-heading-p))
20917 (org-call-with-arg 'org-todo 'nextset))
20918 (org-support-shift-select
20919 (org-call-for-shift-select 'forward-word))
20920 (t (org-shiftselect-error))))
20922 (defun org-shiftcontrolleft ()
20923 "Switch to previous TODO set."
20924 (interactive)
20925 (cond
20926 ((and org-support-shift-select (org-region-active-p))
20927 (org-call-for-shift-select 'backward-word))
20928 ((and (not (eq org-support-shift-select 'always))
20929 (org-at-heading-p))
20930 (org-call-with-arg 'org-todo 'previousset))
20931 (org-support-shift-select
20932 (org-call-for-shift-select 'backward-word))
20933 (t (org-shiftselect-error))))
20935 (defun org-shiftcontrolup (&optional n)
20936 "Change timestamps synchronously up in CLOCK log lines.
20937 Optional argument N tells to change by that many units."
20938 (interactive "P")
20939 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20940 (let (org-support-shift-select)
20941 (org-clock-timestamps-up n))
20942 (user-error "Not at a clock log")))
20944 (defun org-shiftcontroldown (&optional n)
20945 "Change timestamps synchronously down in CLOCK log lines.
20946 Optional argument N tells to change by that many units."
20947 (interactive "P")
20948 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20949 (let (org-support-shift-select)
20950 (org-clock-timestamps-down n))
20951 (user-error "Not at a clock log")))
20953 (defun org-increase-number-at-point (&optional inc)
20954 "Increment the number at point.
20955 With an optional prefix numeric argument INC, increment using
20956 this numeric value."
20957 (interactive "p")
20958 (if (not (number-at-point))
20959 (user-error "Not on a number")
20960 (unless inc (setq inc 1))
20961 (let ((pos (point))
20962 (beg (skip-chars-backward "-+^/*0-9eE."))
20963 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20964 (setq nap (buffer-substring-no-properties
20965 (+ pos beg) (+ pos beg end)))
20966 (delete-region (+ pos beg) (+ pos beg end))
20967 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20968 (when (org-at-table-p)
20969 (org-table-align)
20970 (org-table-end-of-field 1))))
20972 (defun org-decrease-number-at-point (&optional inc)
20973 "Decrement the number at point.
20974 With an optional prefix numeric argument INC, decrement using
20975 this numeric value."
20976 (interactive "p")
20977 (org-increase-number-at-point (- (or inc 1))))
20979 (defun org-ctrl-c-ret ()
20980 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20981 (interactive)
20982 (cond
20983 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20984 (t (call-interactively 'org-insert-heading))))
20986 (defun org-find-visible ()
20987 (let ((s (point)))
20988 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20989 (get-char-property s 'invisible)))
20991 (defun org-find-invisible ()
20992 (let ((s (point)))
20993 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20994 (not (get-char-property s 'invisible))))
20997 (defun org-copy-visible (beg end)
20998 "Copy the visible parts of the region."
20999 (interactive "r")
21000 (let (snippets s)
21001 (save-excursion
21002 (save-restriction
21003 (narrow-to-region beg end)
21004 (setq s (goto-char (point-min)))
21005 (while (not (= (point) (point-max)))
21006 (goto-char (org-find-invisible))
21007 (push (buffer-substring s (point)) snippets)
21008 (setq s (goto-char (org-find-visible))))))
21009 (kill-new (apply 'concat (nreverse snippets)))))
21011 (defun org-copy-special ()
21012 "Copy region in table or copy current subtree.
21013 Calls `org-table-copy' or `org-copy-subtree', depending on context.
21014 See the individual commands for more information."
21015 (interactive)
21016 (call-interactively
21017 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
21019 (defun org-cut-special ()
21020 "Cut region in table or cut current subtree.
21021 Calls `org-table-copy' or `org-cut-subtree', depending on context.
21022 See the individual commands for more information."
21023 (interactive)
21024 (call-interactively
21025 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
21027 (defun org-paste-special (arg)
21028 "Paste rectangular region into table, or past subtree relative to level.
21029 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21030 See the individual commands for more information."
21031 (interactive "P")
21032 (if (org-at-table-p)
21033 (org-table-paste-rectangle)
21034 (org-paste-subtree arg)))
21036 (defsubst org-in-fixed-width-region-p ()
21037 "Is point in a fixed-width region?"
21038 (save-match-data
21039 (eq 'fixed-width (org-element-type (org-element-at-point)))))
21041 (defun org-edit-special (&optional arg)
21042 "Call a special editor for the element at point.
21043 When at a table, call the formula editor with `org-table-edit-formulas'.
21044 When in a source code block, call `org-edit-src-code'.
21045 When in a fixed-width region, call `org-edit-fixed-width-region'.
21046 When in an export block, call `org-edit-export-block'.
21047 When at an #+INCLUDE keyword, visit the included file.
21048 When at a footnote reference, call `org-edit-footnote-reference'
21049 On a link, call `ffap' to visit the link at point.
21050 Otherwise, return a user error."
21051 (interactive "P")
21052 (let ((element (org-element-at-point)))
21053 (cl-assert (not buffer-read-only) nil
21054 "Buffer is read-only: %s" (buffer-name))
21055 (pcase (org-element-type element)
21056 (`src-block
21057 (if (not arg) (org-edit-src-code)
21058 (let* ((info (org-babel-get-src-block-info))
21059 (lang (nth 0 info))
21060 (params (nth 2 info))
21061 (session (cdr (assq :session params))))
21062 (if (not session) (org-edit-src-code)
21063 ;; At a src-block with a session and function called with
21064 ;; an ARG: switch to the buffer related to the inferior
21065 ;; process.
21066 (switch-to-buffer
21067 (funcall (intern (concat "org-babel-prep-session:" lang))
21068 session params))))))
21069 (`keyword
21070 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21071 (org-open-link-from-string
21072 (format "[[%s]]"
21073 (expand-file-name
21074 (let ((value (org-element-property :value element)))
21075 (cond ((not (org-string-nw-p value))
21076 (user-error "No file to edit"))
21077 ((string-match "\\`\"\\(.*?\\)\"" value)
21078 (match-string 1 value))
21079 ((string-match "\\`[^ \t\"]\\S-*" value)
21080 (match-string 0 value))
21081 (t (user-error "No valid file specified")))))))
21082 (user-error "No special environment to edit here")))
21083 (`table
21084 (if (eq (org-element-property :type element) 'table.el)
21085 (org-edit-table.el)
21086 (call-interactively 'org-table-edit-formulas)))
21087 ;; Only Org tables contain `table-row' type elements.
21088 (`table-row (call-interactively 'org-table-edit-formulas))
21089 (`example-block (org-edit-src-code))
21090 (`export-block (org-edit-export-block))
21091 (`fixed-width (org-edit-fixed-width-region))
21093 ;; No notable element at point. Though, we may be at a link or
21094 ;; a footnote reference, which are objects. Thus, scan deeper.
21095 (let ((context (org-element-context element)))
21096 (pcase (org-element-type context)
21097 (`footnote-reference (org-edit-footnote-reference))
21098 (`inline-src-block (org-edit-inline-src-code))
21099 (`link (call-interactively #'ffap))
21100 (_ (user-error "No special environment to edit here"))))))))
21102 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21103 (defun org-ctrl-c-ctrl-c (&optional arg)
21104 "Set tags in headline, or update according to changed information at point.
21106 This command does many different things, depending on context:
21108 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21109 this is what we do.
21111 - If the cursor is on a statistics cookie, update it.
21113 - If the cursor is in a headline, prompt for tags and insert them
21114 into the current line, aligned to `org-tags-column'. When called
21115 with prefix arg, realign all tags in the current buffer.
21117 - If the cursor is in one of the special #+KEYWORD lines, this
21118 triggers scanning the buffer for these lines and updating the
21119 information.
21121 - If the cursor is inside a table, realign the table. This command
21122 works even if the automatic table editor has been turned off.
21124 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21125 the entire table.
21127 - If the cursor is at a footnote reference or definition, jump to
21128 the corresponding definition or references, respectively.
21130 - If the cursor is a the beginning of a dynamic block, update it.
21132 - If the current buffer is a capture buffer, close note and file it.
21134 - If the cursor is on a <<<target>>>, update radio targets and
21135 corresponding links in this buffer.
21137 - If the cursor is on a numbered item in a plain list, renumber the
21138 ordered list.
21140 - If the cursor is on a checkbox, toggle it.
21142 - If the cursor is on a code block, evaluate it. The variable
21143 `org-confirm-babel-evaluate' can be used to control prompting
21144 before code block evaluation, by default every code block
21145 evaluation requires confirmation. Code block evaluation can be
21146 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21147 (interactive "P")
21148 (cond
21149 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21150 org-occur-highlights)
21151 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21152 (org-remove-occur-highlights)
21153 (message "Temporary highlights/overlays removed from current buffer"))
21154 ((and (local-variable-p 'org-finish-function (current-buffer))
21155 (fboundp org-finish-function))
21156 (funcall org-finish-function))
21157 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21159 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21160 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21161 (user-error "C-c C-c can do nothing useful at this location"))
21162 (let* ((context (org-element-context))
21163 (type (org-element-type context)))
21164 (cl-case type
21165 ;; When at a link, act according to the parent instead.
21166 (link (setq context (org-element-property :parent context))
21167 (setq type (org-element-type context)))
21168 ;; Unsupported object types: refer to the first supported
21169 ;; element or object containing it.
21170 ((bold code entity export-snippet inline-babel-call inline-src-block
21171 italic latex-fragment line-break macro strike-through subscript
21172 superscript underline verbatim)
21173 (setq context
21174 (org-element-lineage
21175 context '(radio-target paragraph verse-block table-cell)))))
21176 ;; For convenience: at the first line of a paragraph on the
21177 ;; same line as an item, apply function on that item instead.
21178 (when (eq type 'paragraph)
21179 (let ((parent (org-element-property :parent context)))
21180 (when (and (eq (org-element-type parent) 'item)
21181 (= (line-beginning-position)
21182 (org-element-property :begin parent)))
21183 (setq context parent type 'item))))
21184 ;; Act according to type of element or object at point.
21185 (cl-case type
21186 (clock (org-clock-update-time-maybe))
21187 (dynamic-block
21188 (save-excursion
21189 (goto-char (org-element-property :post-affiliated context))
21190 (org-update-dblock)))
21191 (footnote-definition
21192 (goto-char (org-element-property :post-affiliated context))
21193 (call-interactively 'org-footnote-action))
21194 (footnote-reference (call-interactively 'org-footnote-action))
21195 ((headline inlinetask)
21196 (save-excursion (goto-char (org-element-property :begin context))
21197 (call-interactively 'org-set-tags)))
21198 (item
21199 ;; At an item: a double C-u set checkbox to "[-]"
21200 ;; unconditionally, whereas a single one will toggle its
21201 ;; presence. Without a universal argument, if the item
21202 ;; has a checkbox, toggle it. Otherwise repair the list.
21203 (let* ((box (org-element-property :checkbox context))
21204 (struct (org-element-property :structure context))
21205 (old-struct (copy-tree struct))
21206 (parents (org-list-parents-alist struct))
21207 (prevs (org-list-prevs-alist struct))
21208 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21209 (org-list-set-checkbox
21210 (org-element-property :begin context) struct
21211 (cond ((equal arg '(16)) "[-]")
21212 ((and (not box) (equal arg '(4))) "[ ]")
21213 ((or (not box) (equal arg '(4))) nil)
21214 ((eq box 'on) "[ ]")
21215 (t "[X]")))
21216 ;; Mimic `org-list-write-struct' but with grabbing
21217 ;; a return value from `org-list-struct-fix-box'.
21218 (org-list-struct-fix-ind struct parents 2)
21219 (org-list-struct-fix-item-end struct)
21220 (org-list-struct-fix-bul struct prevs)
21221 (org-list-struct-fix-ind struct parents)
21222 (let ((block-item
21223 (org-list-struct-fix-box struct parents prevs orderedp)))
21224 (if (and box (equal struct old-struct))
21225 (if (equal arg '(16))
21226 (message "Checkboxes already reset")
21227 (user-error "Cannot toggle this checkbox: %s"
21228 (if (eq box 'on)
21229 "all subitems checked"
21230 "unchecked subitems")))
21231 (org-list-struct-apply-struct struct old-struct)
21232 (org-update-checkbox-count-maybe))
21233 (when block-item
21234 (message "Checkboxes were removed due to empty box at line %d"
21235 (org-current-line block-item))))))
21236 (keyword
21237 (let ((org-inhibit-startup-visibility-stuff t)
21238 (org-startup-align-all-tables nil))
21239 (when (boundp 'org-table-coordinate-overlays)
21240 (mapc #'delete-overlay org-table-coordinate-overlays)
21241 (setq org-table-coordinate-overlays nil))
21242 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21243 (message "Local setup has been refreshed"))
21244 (plain-list
21245 ;; At a plain list, with a double C-u argument, set
21246 ;; checkboxes of each item to "[-]", whereas a single one
21247 ;; will toggle their presence according to the state of the
21248 ;; first item in the list. Without an argument, repair the
21249 ;; list.
21250 (let* ((begin (org-element-property :contents-begin context))
21251 (beginm (move-marker (make-marker) begin))
21252 (struct (org-element-property :structure context))
21253 (old-struct (copy-tree struct))
21254 (first-box (save-excursion
21255 (goto-char begin)
21256 (looking-at org-list-full-item-re)
21257 (match-string-no-properties 3)))
21258 (new-box (cond ((equal arg '(16)) "[-]")
21259 ((equal arg '(4)) (unless first-box "[ ]"))
21260 ((equal first-box "[X]") "[ ]")
21261 (t "[X]"))))
21262 (cond
21263 (arg
21264 (dolist (pos
21265 (org-list-get-all-items
21266 begin struct (org-list-prevs-alist struct)))
21267 (org-list-set-checkbox pos struct new-box)))
21268 ((and first-box (eq (point) begin))
21269 ;; For convenience, when point is at bol on the first
21270 ;; item of the list and no argument is provided, simply
21271 ;; toggle checkbox of that item, if any.
21272 (org-list-set-checkbox begin struct new-box)))
21273 (org-list-write-struct
21274 struct (org-list-parents-alist struct) old-struct)
21275 (org-update-checkbox-count-maybe)
21276 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21277 ((property-drawer node-property)
21278 (call-interactively 'org-property-action))
21279 ((radio-target target)
21280 (call-interactively 'org-update-radio-target-regexp))
21281 (statistics-cookie
21282 (call-interactively 'org-update-statistics-cookies))
21283 ((table table-cell table-row)
21284 ;; At a table, recalculate every field and align it. Also
21285 ;; send the table if necessary. If the table has
21286 ;; a `table.el' type, just give up. At a table row or
21287 ;; cell, maybe recalculate line but always align table.
21288 (if (eq (org-element-property :type context) 'table.el)
21289 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21290 Use \\[org-edit-special] to edit table.el tables"))
21291 (let ((org-enable-table-editor t))
21292 (if (or (eq type 'table)
21293 ;; Check if point is at a TBLFM line.
21294 (and (eq type 'table-row)
21295 (= (point) (org-element-property :end context))))
21296 (save-excursion
21297 (if (org-at-TBLFM-p)
21298 (progn (require 'org-table)
21299 (org-table-calc-current-TBLFM))
21300 (goto-char (org-element-property :contents-begin context))
21301 (org-call-with-arg 'org-table-recalculate (or arg t))
21302 (orgtbl-send-table 'maybe)))
21303 (org-table-maybe-eval-formula)
21304 (cond (arg (call-interactively 'org-table-recalculate))
21305 ((org-table-maybe-recalculate-line))
21306 (t (org-table-align)))))))
21307 (timestamp (org-timestamp-change 0 'day))
21308 (otherwise
21309 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21310 (user-error
21311 "C-c C-c can do nothing useful at this location")))))))))
21313 (defun org-mode-restart ()
21314 (interactive)
21315 (let ((indent-status (bound-and-true-p org-indent-mode)))
21316 (funcall major-mode)
21317 (hack-local-variables)
21318 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21319 (org-indent-mode -1)))
21320 (message "%s restarted" major-mode))
21322 (defun org-kill-note-or-show-branches ()
21323 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21324 (interactive)
21325 (if (not org-finish-function)
21326 (progn
21327 (outline-hide-subtree)
21328 (call-interactively 'outline-show-branches))
21329 (let ((org-note-abort t))
21330 (funcall org-finish-function))))
21332 (defun org-delete-indentation (&optional ARG)
21333 "Join current line to previous and fix whitespace at join.
21335 If previous line is a headline add to headline title. Otherwise
21336 the function calls `delete-indentation'.
21338 With argument, join this line to following line."
21339 (interactive "*P")
21340 (if (save-excursion
21341 (if ARG (beginning-of-line)
21342 (forward-line -1))
21343 (looking-at org-complex-heading-regexp))
21344 ;; At headline.
21345 (let ((tags-column (when (match-beginning 5)
21346 (save-excursion (goto-char (match-beginning 5))
21347 (current-column))))
21348 (string (concat " " (progn (when ARG (forward-line 1))
21349 (org-trim (delete-and-extract-region
21350 (line-beginning-position)
21351 (line-end-position)))))))
21352 (unless (bobp) (delete-region (point) (1- (point))))
21353 (goto-char (or (match-end 4)
21354 (match-beginning 5)
21355 (match-end 0)))
21356 (skip-chars-backward " \t")
21357 (save-excursion (insert string))
21358 ;; Adjust alignment of tags.
21359 (when tags-column
21360 (org-align-tags-here (if org-auto-align-tags
21361 org-tags-column
21362 tags-column))))
21363 (delete-indentation ARG)))
21365 (defun org-open-line (n)
21366 "Insert a new row in tables, call `open-line' elsewhere.
21367 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21368 (interactive "*p")
21369 (cond
21370 ((not org-special-ctrl-o)
21371 (open-line n))
21372 ((org-at-table-p)
21373 (org-table-insert-row))
21375 (open-line n))))
21377 (defun org-return (&optional indent)
21378 "Goto next table row or insert a newline.
21380 Calls `org-table-next-row' or `newline', depending on context.
21382 When optional INDENT argument is non-nil, call
21383 `newline-and-indent' instead of `newline'.
21385 When `org-return-follows-link' is non-nil and point is on
21386 a timestamp or a link, call `org-open-at-point'. However, it
21387 will not happen if point is in a table or on a \"dead\"
21388 object (e.g., within a comment). In these case, you need to use
21389 `org-open-at-point' directly."
21390 (interactive)
21391 (let ((context (if org-return-follows-link (org-element-context)
21392 (org-element-at-point))))
21393 (cond
21394 ;; In a table, call `org-table-next-row'.
21395 ((or (and (eq (org-element-type context) 'table)
21396 (>= (point) (org-element-property :contents-begin context))
21397 (< (point) (org-element-property :contents-end context)))
21398 (org-element-lineage context '(table-row table-cell) t))
21399 (org-table-justify-field-maybe)
21400 (call-interactively #'org-table-next-row))
21401 ;; On a link or a timestamp, call `org-open-at-point' if
21402 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21403 ;; locations, e.g., in a comment, as `org-open-at-point'.
21404 ((and org-return-follows-link
21405 (or (org-in-regexp org-ts-regexp-both nil t)
21406 (org-in-regexp org-tsr-regexp-both nil t)
21407 (org-in-regexp org-any-link-re nil t)))
21408 (call-interactively #'org-open-at-point))
21409 ;; Insert newline in heading, but preserve tags.
21410 ((and (not (bolp))
21411 (save-excursion (beginning-of-line)
21412 (looking-at org-complex-heading-regexp)))
21413 ;; At headline. Split line. However, if point is on keyword,
21414 ;; priority cookie or tags, do not break any of them: add
21415 ;; a newline after the headline instead.
21416 (let ((tags-column (and (match-beginning 5)
21417 (save-excursion (goto-char (match-beginning 5))
21418 (current-column))))
21419 (string
21420 (when (and (match-end 4)
21421 (>= (point)
21422 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21423 (<= (point) (match-end 4)))
21424 (delete-and-extract-region (point) (match-end 4)))))
21425 (when (and tags-column string) ; Adjust tag alignment.
21426 (org-align-tags-here
21427 (if org-auto-align-tags org-tags-column tags-column)))
21428 (end-of-line)
21429 (org-show-entry)
21430 (if indent (newline-and-indent) (newline))
21431 (when string (save-excursion (insert (org-trim string))))))
21432 ;; In a list, make sure indenting keeps trailing text within.
21433 ((and indent
21434 (not (eolp))
21435 (org-element-lineage context '(item)))
21436 (let ((trailing-data
21437 (delete-and-extract-region (point) (line-end-position))))
21438 (newline-and-indent)
21439 (save-excursion (insert trailing-data))))
21440 (t (if indent (newline-and-indent) (newline))))))
21442 (defun org-return-indent ()
21443 "Goto next table row or insert a newline and indent.
21444 Calls `org-table-next-row' or `newline-and-indent', depending on
21445 context. See the individual commands for more information."
21446 (interactive)
21447 (org-return t))
21449 (defun org-ctrl-c-star ()
21450 "Compute table, or change heading status of lines.
21451 Calls `org-table-recalculate' or `org-toggle-heading',
21452 depending on context."
21453 (interactive)
21454 (cond
21455 ((org-at-table-p)
21456 (call-interactively 'org-table-recalculate))
21458 ;; Convert all lines in region to list items
21459 (call-interactively 'org-toggle-heading))))
21461 (defun org-ctrl-c-minus ()
21462 "Insert separator line in table or modify bullet status of line.
21463 Also turns a plain line or a region of lines into list items.
21464 Calls `org-table-insert-hline', `org-toggle-item', or
21465 `org-cycle-list-bullet', depending on context."
21466 (interactive)
21467 (cond
21468 ((org-at-table-p)
21469 (call-interactively 'org-table-insert-hline))
21470 ((org-region-active-p)
21471 (call-interactively 'org-toggle-item))
21472 ((org-in-item-p)
21473 (call-interactively 'org-cycle-list-bullet))
21475 (call-interactively 'org-toggle-item))))
21477 (defun org-toggle-heading (&optional nstars)
21478 "Convert headings to normal text, or items or text to headings.
21479 If there is no active region, only convert the current line.
21481 With a \\[universal-argument] prefix, convert the whole list at
21482 point into heading.
21484 In a region:
21486 - If the first non blank line is a headline, remove the stars
21487 from all headlines in the region.
21489 - If it is a normal line, turn each and every normal line (i.e.,
21490 not an heading or an item) in the region into headings. If you
21491 want to convert only the first line of this region, use one
21492 universal prefix argument.
21494 - If it is a plain list item, turn all plain list items into headings.
21496 When converting a line into a heading, the number of stars is chosen
21497 such that the lines become children of the current entry. However,
21498 when a numeric prefix argument is given, its value determines the
21499 number of stars to add."
21500 (interactive "P")
21501 (let ((skip-blanks
21502 (function
21503 ;; Return beginning of first non-blank line, starting from
21504 ;; line at POS.
21505 (lambda (pos)
21506 (save-excursion
21507 (goto-char pos)
21508 (while (org-at-comment-p) (forward-line))
21509 (skip-chars-forward " \r\t\n")
21510 (point-at-bol)))))
21511 beg end toggled)
21512 ;; Determine boundaries of changes. If a universal prefix has
21513 ;; been given, put the list in a region. If region ends at a bol,
21514 ;; do not consider the last line to be in the region.
21516 (when (and current-prefix-arg (org-at-item-p))
21517 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21518 (org-mark-element))
21520 (if (org-region-active-p)
21521 (setq beg (funcall skip-blanks (region-beginning))
21522 end (copy-marker (save-excursion
21523 (goto-char (region-end))
21524 (if (bolp) (point) (point-at-eol)))))
21525 (setq beg (funcall skip-blanks (point-at-bol))
21526 end (copy-marker (point-at-eol))))
21527 ;; Ensure inline tasks don't count as headings.
21528 (org-with-limited-levels
21529 (save-excursion
21530 (goto-char beg)
21531 (cond
21532 ;; Case 1. Started at an heading: de-star headings.
21533 ((org-at-heading-p)
21534 (while (< (point) end)
21535 (when (org-at-heading-p t)
21536 (looking-at org-outline-regexp) (replace-match "")
21537 (setq toggled t))
21538 (forward-line)))
21539 ;; Case 2. Started at an item: change items into headlines.
21540 ;; One star will be added by `org-list-to-subtree'.
21541 ((org-at-item-p)
21542 (while (< (point) end)
21543 (when (org-at-item-p)
21544 ;; Pay attention to cases when region ends before list.
21545 (let* ((struct (org-list-struct))
21546 (list-end
21547 (min (org-list-get-bottom-point struct) (1+ end))))
21548 (save-restriction
21549 (narrow-to-region (point) list-end)
21550 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21551 (setq toggled t))
21552 (forward-line)))
21553 ;; Case 3. Started at normal text: make every line an heading,
21554 ;; skipping headlines and items.
21555 (t (let* ((stars
21556 (make-string
21557 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21558 (add-stars
21559 (cond (nstars "") ; stars from prefix only
21560 ((equal stars "") "*") ; before first heading
21561 (org-odd-levels-only "**") ; inside heading, odd
21562 (t "*"))) ; inside heading, oddeven
21563 (rpl (concat stars add-stars " "))
21564 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21565 (while (< (point) (if (equal nstars '(4)) lend end))
21566 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21567 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21568 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21569 (forward-line)))))))
21570 (unless toggled (message "Cannot toggle heading from here"))))
21572 (defun org-meta-return (&optional _arg)
21573 "Insert a new heading or wrap a region in a table.
21574 Calls `org-insert-heading' or `org-table-wrap-region', depending
21575 on context. See the individual commands for more information."
21576 (interactive)
21577 (org-check-before-invisible-edit 'insert)
21578 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21579 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21580 #'org-insert-heading))))
21582 ;;; Menu entries
21584 (defsubst org-in-subtree-not-table-p ()
21585 "Are we in a subtree and not in a table?"
21586 (and (not (org-before-first-heading-p))
21587 (not (org-at-table-p))))
21589 ;; Define the Org-mode menus
21590 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21591 '("Tbl"
21592 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21593 ["Next Field" org-cycle (org-at-table-p)]
21594 ["Previous Field" org-shifttab (org-at-table-p)]
21595 ["Next Row" org-return (org-at-table-p)]
21596 "--"
21597 ["Blank Field" org-table-blank-field (org-at-table-p)]
21598 ["Edit Field" org-table-edit-field (org-at-table-p)]
21599 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21600 "--"
21601 ("Column"
21602 ["Move Column Left" org-metaleft (org-at-table-p)]
21603 ["Move Column Right" org-metaright (org-at-table-p)]
21604 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21605 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21606 ("Row"
21607 ["Move Row Up" org-metaup (org-at-table-p)]
21608 ["Move Row Down" org-metadown (org-at-table-p)]
21609 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21610 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21611 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21612 "--"
21613 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21614 ("Rectangle"
21615 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21616 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21617 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21618 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21619 "--"
21620 ("Calculate"
21621 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21622 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21623 ["Edit Formulas" org-edit-special (org-at-table-p)]
21624 "--"
21625 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21626 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21627 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21628 "--"
21629 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21630 "--"
21631 ["Sum Column/Rectangle" org-table-sum
21632 (or (org-at-table-p) (org-region-active-p))]
21633 ["Which Column?" org-table-current-column (org-at-table-p)])
21634 ["Debug Formulas"
21635 org-table-toggle-formula-debugger
21636 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21637 ["Show Col/Row Numbers"
21638 org-table-toggle-coordinate-overlays
21639 :style toggle
21640 :selected (bound-and-true-p org-table-overlay-coordinates)]
21641 "--"
21642 ["Create" org-table-create (and (not (org-at-table-p))
21643 org-enable-table-editor)]
21644 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21645 ["Import from File" org-table-import (not (org-at-table-p))]
21646 ["Export to File" org-table-export (org-at-table-p)]
21647 "--"
21648 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21649 "--"
21650 ("Plot"
21651 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21652 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21654 (easy-menu-define org-org-menu org-mode-map "Org menu"
21655 '("Org"
21656 ("Show/Hide"
21657 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21658 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21659 ["Sparse Tree..." org-sparse-tree t]
21660 ["Reveal Context" org-reveal t]
21661 ["Show All" outline-show-all t]
21662 "--"
21663 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21664 "--"
21665 ["New Heading" org-insert-heading t]
21666 ("Navigate Headings"
21667 ["Up" outline-up-heading t]
21668 ["Next" outline-next-visible-heading t]
21669 ["Previous" outline-previous-visible-heading t]
21670 ["Next Same Level" outline-forward-same-level t]
21671 ["Previous Same Level" outline-backward-same-level t]
21672 "--"
21673 ["Jump" org-goto t])
21674 ("Edit Structure"
21675 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21676 "--"
21677 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21678 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21679 "--"
21680 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21681 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21682 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21683 "--"
21684 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21685 "--"
21686 ["Copy visible text" org-copy-visible t]
21687 "--"
21688 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21689 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21690 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21691 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21692 "--"
21693 ["Sort Region/Children" org-sort t]
21694 "--"
21695 ["Convert to odd levels" org-convert-to-odd-levels t]
21696 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21697 ("Editing"
21698 ["Emphasis..." org-emphasize t]
21699 ["Edit Source Example" org-edit-special t]
21700 "--"
21701 ["Footnote new/jump" org-footnote-action t]
21702 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21703 ("Archive"
21704 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21705 "--"
21706 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21707 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21708 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21710 "--"
21711 ("Hyperlinks"
21712 ["Store Link (Global)" org-store-link t]
21713 ["Find existing link to here" org-occur-link-in-agenda-files t]
21714 ["Insert Link" org-insert-link t]
21715 ["Follow Link" org-open-at-point t]
21716 "--"
21717 ["Next link" org-next-link t]
21718 ["Previous link" org-previous-link t]
21719 "--"
21720 ["Descriptive Links"
21721 org-toggle-link-display
21722 :style radio
21723 :selected org-descriptive-links
21725 ["Literal Links"
21726 org-toggle-link-display
21727 :style radio
21728 :selected (not org-descriptive-links)])
21729 "--"
21730 ("TODO Lists"
21731 ["TODO/DONE/-" org-todo t]
21732 ("Select keyword"
21733 ["Next keyword" org-shiftright (org-at-heading-p)]
21734 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21735 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21736 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21737 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21738 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21739 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21740 "--"
21741 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21742 :selected org-enforce-todo-dependencies :style toggle :active t]
21743 "Settings for tree at point"
21744 ["Do Children sequentially" org-toggle-ordered-property :style radio
21745 :selected (org-entry-get nil "ORDERED")
21746 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21747 ["Do Children parallel" org-toggle-ordered-property :style radio
21748 :selected (not (org-entry-get nil "ORDERED"))
21749 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21750 "--"
21751 ["Set Priority" org-priority t]
21752 ["Priority Up" org-shiftup t]
21753 ["Priority Down" org-shiftdown t]
21754 "--"
21755 ["Get news from all feeds" org-feed-update-all t]
21756 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21757 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21758 ("TAGS and Properties"
21759 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21760 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21761 "--"
21762 ["Set property" org-set-property (not (org-before-first-heading-p))]
21763 ["Column view of properties" org-columns t]
21764 ["Insert Column View DBlock" org-columns-insert-dblock t])
21765 ("Dates and Scheduling"
21766 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21767 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21768 ("Change Date"
21769 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21770 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21771 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21772 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21773 ["Compute Time Range" org-evaluate-time-range t]
21774 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21775 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21776 "--"
21777 ["Custom time format" org-toggle-time-stamp-overlays
21778 :style radio :selected org-display-custom-times]
21779 "--"
21780 ["Goto Calendar" org-goto-calendar t]
21781 ["Date from Calendar" org-date-from-calendar t]
21782 "--"
21783 ["Start/Restart Timer" org-timer-start t]
21784 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21785 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21786 ["Insert Timer String" org-timer t]
21787 ["Insert Timer Item" org-timer-item t])
21788 ("Logging work"
21789 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21790 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21791 ["Clock out" org-clock-out t]
21792 ["Clock cancel" org-clock-cancel t]
21793 "--"
21794 ["Mark as default task" org-clock-mark-default-task t]
21795 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21796 ["Goto running clock" org-clock-goto t]
21797 "--"
21798 ["Display times" org-clock-display t]
21799 ["Create clock table" org-clock-report t]
21800 "--"
21801 ["Record DONE time"
21802 (progn (setq org-log-done (not org-log-done))
21803 (message "Switching to %s will %s record a timestamp"
21804 (car org-done-keywords)
21805 (if org-log-done "automatically" "not")))
21806 :style toggle :selected org-log-done])
21807 "--"
21808 ["Agenda Command..." org-agenda t]
21809 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21810 ("File List for Agenda")
21811 ("Special views current file"
21812 ["TODO Tree" org-show-todo-tree t]
21813 ["Check Deadlines" org-check-deadlines t]
21814 ["Timeline" org-timeline t]
21815 ["Tags/Property tree" org-match-sparse-tree t])
21816 "--"
21817 ["Export/Publish..." org-export-dispatch t]
21818 ("LaTeX"
21819 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21820 :selected org-cdlatex-mode]
21821 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21822 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21823 ["Modify math symbol" org-cdlatex-math-modify
21824 (org-inside-LaTeX-fragment-p)]
21825 ["Insert citation" org-reftex-citation t])
21826 "--"
21827 ("MobileOrg"
21828 ["Push Files and Views" org-mobile-push t]
21829 ["Get Captured and Flagged" org-mobile-pull t]
21830 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21831 "--"
21832 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21833 "--"
21834 ("Documentation"
21835 ["Show Version" org-version t]
21836 ["Info Documentation" org-info t])
21837 ("Customize"
21838 ["Browse Org Group" org-customize t]
21839 "--"
21840 ["Expand This Menu" org-create-customize-menu
21841 (fboundp 'customize-menu-create)])
21842 ["Send bug report" org-submit-bug-report t]
21843 "--"
21844 ("Refresh/Reload"
21845 ["Refresh setup current buffer" org-mode-restart t]
21846 ["Reload Org (after update)" org-reload t]
21847 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21850 (defun org-info (&optional node)
21851 "Read documentation for Org-mode in the info system.
21852 With optional NODE, go directly to that node."
21853 (interactive)
21854 (info (format "(org)%s" (or node ""))))
21856 ;;;###autoload
21857 (defun org-submit-bug-report ()
21858 "Submit a bug report on Org-mode via mail.
21860 Don't hesitate to report any problems or inaccurate documentation.
21862 If you don't have setup sending mail from (X)Emacs, please copy the
21863 output buffer into your mail program, as it gives us important
21864 information about your Org-mode version and configuration."
21865 (interactive)
21866 (require 'reporter)
21867 (defvar reporter-prompt-for-summary-p)
21868 (org-load-modules-maybe)
21869 (org-require-autoloaded-modules)
21870 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21871 (reporter-submit-bug-report
21872 "emacs-orgmode@gnu.org"
21873 (org-version nil 'full)
21874 (let (list)
21875 (save-window-excursion
21876 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21877 (delete-other-windows)
21878 (erase-buffer)
21879 (insert "You are about to submit a bug report to the Org-mode mailing list.
21881 We would like to add your full Org-mode and Outline configuration to the
21882 bug report. This greatly simplifies the work of the maintainer and
21883 other experts on the mailing list.
21885 HOWEVER, some variables you have customized may contain private
21886 information. The names of customers, colleagues, or friends, might
21887 appear in the form of file names, tags, todo states, or search strings.
21888 If you answer yes to the prompt, you might want to check and remove
21889 such private information before sending the email.")
21890 (add-text-properties (point-min) (point-max) '(face org-warning))
21891 (when (yes-or-no-p "Include your Org-mode configuration ")
21892 (mapatoms
21893 (lambda (v)
21894 (and (boundp v)
21895 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21896 (or (and (symbol-value v)
21897 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21898 (and
21899 (get v 'custom-type) (get v 'standard-value)
21900 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21901 (push v list)))))
21902 (kill-buffer (get-buffer "*Warn about privacy*"))
21903 list))
21904 nil nil
21905 "Remember to cover the basics, that is, what you expected to happen and
21906 what in fact did happen. You don't know how to make a good report? See
21908 http://orgmode.org/manual/Feedback.html#Feedback
21910 Your bug report will be posted to the Org-mode mailing list.
21911 ------------------------------------------------------------------------")
21912 (save-excursion
21913 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21914 (replace-match "\\1Bug: \\3 [\\2]")))))
21917 (defun org-install-agenda-files-menu ()
21918 (let ((bl (buffer-list)))
21919 (save-excursion
21920 (while bl
21921 (set-buffer (pop bl))
21922 (when (derived-mode-p 'org-mode) (setq bl nil)))
21923 (when (derived-mode-p 'org-mode)
21924 (easy-menu-change
21925 '("Org") "File List for Agenda"
21926 (append
21927 (list
21928 ["Edit File List" (org-edit-agenda-file-list) t]
21929 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21930 ["Remove Current File from List" org-remove-file t]
21931 ["Cycle through agenda files" org-cycle-agenda-files t]
21932 ["Occur in all agenda files" org-occur-in-agenda-files t]
21933 "--")
21934 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21936 ;;;; Documentation
21938 (defun org-require-autoloaded-modules ()
21939 (interactive)
21940 (mapc #'require
21941 '(org-agenda org-archive org-attach org-clock org-colview org-id
21942 org-table org-timer)))
21944 ;;;###autoload
21945 (defun org-reload (&optional uncompiled)
21946 "Reload all org lisp files.
21947 With prefix arg UNCOMPILED, load the uncompiled versions."
21948 (interactive "P")
21949 (require 'loadhist)
21950 (let* ((org-dir (org-find-library-dir "org"))
21951 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21952 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21953 (remove-re (format "\\`%s\\'"
21954 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21955 (feats (delete-dups
21956 (mapcar 'file-name-sans-extension
21957 (mapcar 'file-name-nondirectory
21958 (delq nil
21959 (mapcar 'feature-file
21960 features))))))
21961 (lfeat (append
21962 (sort
21963 (setq feats
21964 (delq nil (mapcar
21965 (lambda (f)
21966 (if (and (string-match feature-re f)
21967 (not (string-match remove-re f)))
21968 f nil))
21969 feats)))
21970 'string-lessp)
21971 (list "org-version" "org")))
21972 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21973 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21974 load-uncore load-misses)
21975 (setq load-misses
21976 (delq 't
21977 (mapcar (lambda (f)
21978 (or (org-load-noerror-mustsuffix (concat org-dir f))
21979 (and (string= org-dir contrib-dir)
21980 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21981 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21982 (add-to-list 'load-uncore f 'append)
21985 lfeat)))
21986 (when load-uncore
21987 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21988 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21989 (if load-misses
21990 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21991 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21992 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21994 ;;;###autoload
21995 (defun org-customize ()
21996 "Call the customize function with org as argument."
21997 (interactive)
21998 (org-load-modules-maybe)
21999 (org-require-autoloaded-modules)
22000 (customize-browse 'org))
22002 (defun org-create-customize-menu ()
22003 "Create a full customization menu for Org-mode, insert it into the menu."
22004 (interactive)
22005 (org-load-modules-maybe)
22006 (org-require-autoloaded-modules)
22007 (if (fboundp 'customize-menu-create)
22008 (progn
22009 (easy-menu-change
22010 '("Org") "Customize"
22011 `(["Browse Org group" org-customize t]
22012 "--"
22013 ,(customize-menu-create 'org)
22014 ["Set" Custom-set t]
22015 ["Save" Custom-save t]
22016 ["Reset to Current" Custom-reset-current t]
22017 ["Reset to Saved" Custom-reset-saved t]
22018 ["Reset to Standard Settings" Custom-reset-standard t]))
22019 (message "\"Org\"-menu now contains full customization menu"))
22020 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22022 ;;;; Miscellaneous stuff
22024 ;;; Generally useful functions
22026 (defun org-get-at-eol (property n)
22027 "Get text property PROPERTY at the end of line less N characters."
22028 (get-text-property (- (point-at-eol) n) property))
22030 (defun org-find-text-property-in-string (prop s)
22031 "Return the first non-nil value of property PROP in string S."
22032 (or (get-text-property 0 prop s)
22033 (get-text-property (or (next-single-property-change 0 prop s) 0)
22034 prop s)))
22036 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22037 "Display the given MESSAGE as a warning."
22038 (if (fboundp 'display-warning)
22039 (display-warning 'org message :warning)
22040 (let ((buf (get-buffer-create "*Org warnings*")))
22041 (with-current-buffer buf
22042 (goto-char (point-max))
22043 (insert "Warning (Org): " message)
22044 (unless (bolp)
22045 (newline)))
22046 (display-buffer buf)
22047 (sit-for 0))))
22049 (defun org-eval (form)
22050 "Eval FORM and return result."
22051 (condition-case error
22052 (eval form)
22053 (error (format "%%![Error: %s]" error))))
22055 (defun org-in-clocktable-p ()
22056 "Check if the cursor is in a clocktable."
22057 (let ((pos (point)) start)
22058 (save-excursion
22059 (end-of-line 1)
22060 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22061 (setq start (match-beginning 0))
22062 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22063 (>= (match-end 0) pos)
22064 start))))
22066 (defun org-in-verbatim-emphasis ()
22067 (save-match-data
22068 (and (org-in-regexp org-emph-re 2)
22069 (>= (point) (match-beginning 3))
22070 (<= (point) (match-end 4))
22071 (member (match-string 3) '("=" "~")))))
22073 (defun org-overlay-display (ovl text &optional face evap)
22074 "Make overlay OVL display TEXT with face FACE."
22075 (overlay-put ovl 'display text)
22076 (if face (overlay-put ovl 'face face))
22077 (if evap (overlay-put ovl 'evaporate t)))
22079 (defun org-overlay-before-string (ovl text &optional face evap)
22080 "Make overlay OVL display TEXT with face FACE."
22081 (if face (org-add-props text nil 'face face))
22082 (overlay-put ovl 'before-string text)
22083 (if evap (overlay-put ovl 'evaporate t)))
22085 (defun org-find-overlays (prop &optional pos delete)
22086 "Find all overlays specifying PROP at POS or point.
22087 If DELETE is non-nil, delete all those overlays."
22088 (let (found)
22089 (dolist (ov (overlays-at (or pos (point))) found)
22090 (cond ((not (overlay-get ov prop)))
22091 (delete (delete-overlay ov))
22092 (t (push ov found))))))
22094 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22095 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22096 (if (and marker (marker-buffer marker)
22097 (buffer-live-p (marker-buffer marker)))
22098 (progn
22099 (pop-to-buffer-same-window (marker-buffer marker))
22100 (when (or (> marker (point-max)) (< marker (point-min)))
22101 (widen))
22102 (goto-char marker)
22103 (org-show-context 'org-goto))
22104 (if bookmark
22105 (bookmark-jump bookmark)
22106 (error "Cannot find location"))))
22108 (defun org-quote-csv-field (s)
22109 "Quote field for inclusion in CSV material."
22110 (if (string-match "[\",]" s)
22111 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22114 (defun org-force-self-insert (N)
22115 "Needed to enforce self-insert under remapping."
22116 (interactive "p")
22117 (self-insert-command N))
22119 (defun org-string-width (s)
22120 "Compute width of string, ignoring invisible characters.
22121 This ignores character with invisibility property `org-link', and also
22122 characters with property `org-cwidth', because these will become invisible
22123 upon the next fontification round."
22124 (let (b l)
22125 (when (or (eq t buffer-invisibility-spec)
22126 (assq 'org-link buffer-invisibility-spec))
22127 (while (setq b (text-property-any 0 (length s)
22128 'invisible 'org-link s))
22129 (setq s (concat (substring s 0 b)
22130 (substring s (or (next-single-property-change
22131 b 'invisible s)
22132 (length s)))))))
22133 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22134 (setq s (concat (substring s 0 b)
22135 (substring s (or (next-single-property-change
22136 b 'org-cwidth s)
22137 (length s))))))
22138 (setq l (string-width s) b -1)
22139 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22140 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22143 (defun org-shorten-string (s maxlength)
22144 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22145 If the string is shorter or has length MAXLENGTH, just return the
22146 original string. If it is longer, the functions finds a space in the
22147 string, breaks this string off at that locations and adds three dots
22148 as ellipsis. Including the ellipsis, the string will not be longer
22149 than MAXLENGTH. If finding a good breaking point in the string does
22150 not work, the string is just chopped off in the middle of a word
22151 if necessary."
22152 (if (<= (length s) maxlength)
22154 (let* ((n (max (- maxlength 4) 1))
22155 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22156 (if (string-match re s)
22157 (concat (match-string 1 s) "...")
22158 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22160 (defun org-get-indentation (&optional line)
22161 "Get the indentation of the current line, interpreting tabs.
22162 When LINE is given, assume it represents a line and compute its indentation."
22163 (if line
22164 (when (string-match "^ *" (org-remove-tabs line))
22165 (match-end 0))
22166 (save-excursion
22167 (beginning-of-line 1)
22168 (skip-chars-forward " \t")
22169 (current-column))))
22171 (defun org-get-string-indentation (s)
22172 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22173 (let ((n -1) (i 0) (w tab-width) c)
22174 (catch 'exit
22175 (while (< (setq n (1+ n)) (length s))
22176 (setq c (aref s n))
22177 (cond ((= c ?\ ) (setq i (1+ i)))
22178 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22179 (t (throw 'exit t)))))
22182 (defun org-remove-tabs (s &optional width)
22183 "Replace tabulators in S with spaces.
22184 Assumes that s is a single line, starting in column 0."
22185 (setq width (or width tab-width))
22186 (while (string-match "\t" s)
22187 (setq s (replace-match
22188 (make-string
22189 (- (* width (/ (+ (match-beginning 0) width) width))
22190 (match-beginning 0)) ?\ )
22191 t t s)))
22194 (defun org-fix-indentation (line ind)
22195 "Fix indentation in LINE.
22196 IND is a cons cell with target and minimum indentation.
22197 If the current indentation in LINE is smaller than the minimum,
22198 leave it alone. If it is larger than ind, set it to the target."
22199 (let* ((l (org-remove-tabs line))
22200 (i (org-get-indentation l))
22201 (i1 (car ind)) (i2 (cdr ind)))
22202 (when (>= i i2) (setq l (substring line i2)))
22203 (if (> i1 0)
22204 (concat (make-string i1 ?\ ) l)
22205 l)))
22207 (defun org-remove-indentation (code &optional n)
22208 "Remove maximum common indentation in string CODE and return it.
22209 N may optionally be the number of columns to remove. Return CODE
22210 as-is if removal failed."
22211 (with-temp-buffer
22212 (insert code)
22213 (if (org-do-remove-indentation n) (buffer-string) code)))
22215 (defun org-do-remove-indentation (&optional n)
22216 "Remove the maximum common indentation from the buffer.
22217 When optional argument N is a positive integer, remove exactly
22218 that much characters from indentation, if possible. Return nil
22219 if it fails."
22220 (catch :exit
22221 (goto-char (point-min))
22222 ;; Find maximum common indentation, if not specified.
22223 (let ((n (or n
22224 (let ((min-ind (point-max)))
22225 (save-excursion
22226 (while (re-search-forward "^[ \t]*\\S-" nil t)
22227 (let ((ind (1- (current-column))))
22228 (if (zerop ind) (throw :exit nil)
22229 (setq min-ind (min min-ind ind))))))
22230 min-ind))))
22231 (if (zerop n) (throw :exit nil)
22232 ;; Remove exactly N indentation, but give up if not possible.
22233 (while (not (eobp))
22234 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22235 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22236 ((< ind n) (throw :exit nil))
22237 (t (indent-line-to (- ind n))))
22238 (forward-line)))
22239 ;; Signal success.
22240 t))))
22242 (defun org-fill-template (template alist)
22243 "Find each %key of ALIST in TEMPLATE and replace it."
22244 (let ((case-fold-search nil))
22245 (dolist (entry (sort (copy-sequence alist)
22246 (lambda (a b) (< (length (car a)) (length (car b))))))
22247 (setq template
22248 (replace-regexp-in-string
22249 (concat "%" (regexp-quote (car entry)))
22250 (or (cdr entry) "") template t t)))
22251 template))
22253 (defun org-base-buffer (buffer)
22254 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22255 (if (not buffer)
22256 buffer
22257 (or (buffer-base-buffer buffer)
22258 buffer)))
22260 (defun org-wrap (string &optional width lines)
22261 "Wrap string to either a number of lines, or a width in characters.
22262 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22263 that costs. If there is a word longer than WIDTH, the text is actually
22264 wrapped to the length of that word.
22265 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22266 many lines, whatever width that takes.
22267 The return value is a list of lines, without newlines at the end."
22268 (let* ((words (org-split-string string "[ \t\n]+"))
22269 (maxword (apply 'max (mapcar 'org-string-width words)))
22270 w ll)
22271 (cond (width
22272 (org-do-wrap words (max maxword width)))
22273 (lines
22274 (setq w maxword)
22275 (setq ll (org-do-wrap words maxword))
22276 (if (<= (length ll) lines)
22278 (setq ll words)
22279 (while (> (length ll) lines)
22280 (setq w (1+ w))
22281 (setq ll (org-do-wrap words w)))
22282 ll))
22283 (t (error "Cannot wrap this")))))
22285 (defun org-do-wrap (words width)
22286 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22287 (let (lines line)
22288 (while words
22289 (setq line (pop words))
22290 (while (and words (< (+ (length line) (length (car words))) width))
22291 (setq line (concat line " " (pop words))))
22292 (setq lines (push line lines)))
22293 (nreverse lines)))
22295 (defun org-split-string (string &optional separators)
22296 "Splits STRING into substrings at SEPARATORS.
22297 SEPARATORS is a regular expression.
22298 No empty strings are returned if there are matches at the beginning
22299 and end of string."
22300 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22301 (let ((start 0) notfirst list)
22302 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22303 (if (and notfirst
22304 (= start (match-beginning 0))
22305 (< start (length string)))
22306 (1+ start) start))
22307 (< (match-beginning 0) (length string)))
22308 (setq notfirst t)
22309 (or (eq (match-beginning 0) 0)
22310 (and (eq (match-beginning 0) (match-end 0))
22311 (eq (match-beginning 0) start))
22312 (push (substring string start (match-beginning 0)) list))
22313 (setq start (match-end 0)))
22314 (or (eq start (length string))
22315 (push (substring string start) list))
22316 (nreverse list)))
22318 (defun org-quote-vert (s)
22319 "Replace \"|\" with \"\\vert\"."
22320 (while (string-match "|" s)
22321 (setq s (replace-match "\\vert" t t s)))
22324 (defun org-uuidgen-p (s)
22325 "Is S an ID created by UUIDGEN?"
22326 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22328 (defun org-in-src-block-p (&optional inside)
22329 "Whether point is in a code source block.
22330 When INSIDE is non-nil, don't consider we are within a src block
22331 when point is at #+BEGIN_SRC or #+END_SRC."
22332 (let ((case-fold-search t))
22333 (or (and (eq (get-char-property (point) 'src-block) t))
22334 (and (not inside)
22335 (save-match-data
22336 (save-excursion
22337 (beginning-of-line)
22338 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22340 (defun org-context ()
22341 "Return a list of contexts of the current cursor position.
22342 If several contexts apply, all are returned.
22343 Each context entry is a list with a symbol naming the context, and
22344 two positions indicating start and end of the context. Possible
22345 contexts are:
22347 :headline anywhere in a headline
22348 :headline-stars on the leading stars in a headline
22349 :todo-keyword on a TODO keyword (including DONE) in a headline
22350 :tags on the TAGS in a headline
22351 :priority on the priority cookie in a headline
22352 :item on the first line of a plain list item
22353 :item-bullet on the bullet/number of a plain list item
22354 :checkbox on the checkbox in a plain list item
22355 :table in an org-mode table
22356 :table-special on a special filed in a table
22357 :table-table in a table.el table
22358 :clocktable in a clocktable
22359 :src-block in a source block
22360 :link on a hyperlink
22361 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22362 :target on a <<target>>
22363 :radio-target on a <<<radio-target>>>
22364 :latex-fragment on a LaTeX fragment
22365 :latex-preview on a LaTeX fragment with overlaid preview image
22367 This function expects the position to be visible because it uses font-lock
22368 faces as a help to recognize the following contexts: :table-special, :link,
22369 and :keyword."
22370 (let* ((f (get-text-property (point) 'face))
22371 (faces (if (listp f) f (list f)))
22372 (case-fold-search t)
22373 (p (point)) clist o)
22374 ;; First the large context
22375 (cond
22376 ((org-at-heading-p t)
22377 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22378 (when (progn
22379 (beginning-of-line 1)
22380 (looking-at org-todo-line-tags-regexp))
22381 (push (org-point-in-group p 1 :headline-stars) clist)
22382 (push (org-point-in-group p 2 :todo-keyword) clist)
22383 (push (org-point-in-group p 4 :tags) clist))
22384 (goto-char p)
22385 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22386 (when (looking-at "\\[#[A-Z0-9]\\]")
22387 (push (org-point-in-group p 0 :priority) clist)))
22389 ((org-at-item-p)
22390 (push (org-point-in-group p 2 :item-bullet) clist)
22391 (push (list :item (point-at-bol)
22392 (save-excursion (org-end-of-item) (point)))
22393 clist)
22394 (and (org-at-item-checkbox-p)
22395 (push (org-point-in-group p 0 :checkbox) clist)))
22397 ((org-at-table-p)
22398 (push (list :table (org-table-begin) (org-table-end)) clist)
22399 (when (memq 'org-formula faces)
22400 (push (list :table-special
22401 (previous-single-property-change p 'face)
22402 (next-single-property-change p 'face)) clist)))
22403 ((org-at-table-p 'any)
22404 (push (list :table-table) clist)))
22405 (goto-char p)
22407 (let ((case-fold-search t))
22408 ;; New the "medium" contexts: clocktables, source blocks
22409 (cond ((org-in-clocktable-p)
22410 (push (list :clocktable
22411 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22412 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22413 (match-beginning 1))
22414 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22415 (match-end 0))) clist))
22416 ((org-in-src-block-p)
22417 (push (list :src-block
22418 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22419 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22420 (match-beginning 1))
22421 (and (search-forward "#+END_SRC" nil t)
22422 (match-beginning 0))) clist))))
22423 (goto-char p)
22425 ;; Now the small context
22426 (cond
22427 ((org-at-timestamp-p)
22428 (push (org-point-in-group p 0 :timestamp) clist))
22429 ((memq 'org-link faces)
22430 (push (list :link
22431 (previous-single-property-change p 'face)
22432 (next-single-property-change p 'face)) clist))
22433 ((memq 'org-special-keyword faces)
22434 (push (list :keyword
22435 (previous-single-property-change p 'face)
22436 (next-single-property-change p 'face)) clist))
22437 ((org-at-target-p)
22438 (push (org-point-in-group p 0 :target) clist)
22439 (goto-char (1- (match-beginning 0)))
22440 (when (looking-at org-radio-target-regexp)
22441 (push (org-point-in-group p 0 :radio-target) clist))
22442 (goto-char p))
22443 ((setq o (cl-some
22444 (lambda (o)
22445 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22447 (overlays-at (point))))
22448 (push (list :latex-fragment
22449 (overlay-start o) (overlay-end o)) clist)
22450 (push (list :latex-preview
22451 (overlay-start o) (overlay-end o)) clist))
22452 ((org-inside-LaTeX-fragment-p)
22453 ;; FIXME: positions wrong.
22454 (push (list :latex-fragment (point) (point)) clist)))
22456 (setq clist (nreverse (delq nil clist)))
22457 clist))
22459 (defun org-in-regexp (regexp &optional nlines visually)
22460 "Check if point is inside a match of REGEXP.
22462 Normally only the current line is checked, but you can include
22463 NLINES extra lines around point into the search. If VISUALLY is
22464 set, require that the cursor is not after the match but really
22465 on, so that the block visually is on the match.
22467 Return nil or a cons cell (BEG . END) where BEG and END are,
22468 respectively, the positions at the beginning and the end of the
22469 match."
22470 (catch :exit
22471 (let ((pos (point))
22472 (eol (line-end-position (if nlines (1+ nlines) 1))))
22473 (save-excursion
22474 (beginning-of-line (- 1 (or nlines 0)))
22475 (while (and (re-search-forward regexp eol t)
22476 (<= (match-beginning 0) pos))
22477 (let ((end (match-end 0)))
22478 (when (or (> end pos) (and (= end pos) (not visually)))
22479 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22481 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22482 "Non-nil when point is between matches of START-RE and END-RE.
22484 Also return a non-nil value when point is on one of the matches.
22486 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22487 buffer positions. Default values are the positions of headlines
22488 surrounding the point.
22490 The functions returns a cons cell whose car (resp. cdr) is the
22491 position before START-RE (resp. after END-RE)."
22492 (save-match-data
22493 (let ((pos (point))
22494 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22495 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22496 beg end)
22497 (save-excursion
22498 ;; Point is on a block when on START-RE or if START-RE can be
22499 ;; found before it...
22500 (and (or (org-in-regexp start-re)
22501 (re-search-backward start-re limit-up t))
22502 (setq beg (match-beginning 0))
22503 ;; ... and END-RE after it...
22504 (goto-char (match-end 0))
22505 (re-search-forward end-re limit-down t)
22506 (> (setq end (match-end 0)) pos)
22507 ;; ... without another START-RE in-between.
22508 (goto-char (match-beginning 0))
22509 (not (re-search-backward start-re (1+ beg) t))
22510 ;; Return value.
22511 (cons beg end))))))
22513 (defun org-in-block-p (names)
22514 "Non-nil when point belongs to a block whose name belongs to NAMES.
22516 NAMES is a list of strings containing names of blocks.
22518 Return first block name matched, or nil. Beware that in case of
22519 nested blocks, the returned name may not belong to the closest
22520 block from point."
22521 (save-match-data
22522 (catch 'exit
22523 (let ((case-fold-search t)
22524 (lim-up (save-excursion (outline-previous-heading)))
22525 (lim-down (save-excursion (outline-next-heading))))
22526 (dolist (name names)
22527 (let ((n (regexp-quote name)))
22528 (when (org-between-regexps-p
22529 (concat "^[ \t]*#\\+begin_" n)
22530 (concat "^[ \t]*#\\+end_" n)
22531 lim-up lim-down)
22532 (throw 'exit n)))))
22533 nil)))
22535 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22536 "Call `multi-occur' with buffers for all agenda files."
22537 (interactive "sOrg-files matching: ")
22538 (let* ((files (org-agenda-files))
22539 (tnames (mapcar #'file-truename files))
22540 (extra org-agenda-text-search-extra-files))
22541 (when (eq (car extra) 'agenda-archives)
22542 (setq extra (cdr extra))
22543 (setq files (org-add-archive-files files)))
22544 (dolist (f extra)
22545 (unless (member (file-truename f) tnames)
22546 (unless (member f files) (setq files (append files (list f))))
22547 (setq tnames (append tnames (list (file-truename f))))))
22548 (multi-occur
22549 (mapcar (lambda (x)
22550 (with-current-buffer
22551 ;; FIXME: Why not just (find-file-noselect x)?
22552 ;; Is it to avoid the "revert buffer" prompt?
22553 (or (get-file-buffer x) (find-file-noselect x))
22554 (widen)
22555 (current-buffer)))
22556 files)
22557 regexp)))
22559 (add-hook 'occur-mode-find-occurrence-hook
22560 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22562 (defun org-occur-link-in-agenda-files ()
22563 "Create a link and search for it in the agendas.
22564 The link is not stored in `org-stored-links', it is just created
22565 for the search purpose."
22566 (interactive)
22567 (let ((link (condition-case nil
22568 (org-store-link nil)
22569 (error "Unable to create a link to here"))))
22570 (org-occur-in-agenda-files (regexp-quote link))))
22572 (defun org-reverse-string (string)
22573 "Return the reverse of STRING."
22574 (apply 'string (reverse (string-to-list string))))
22576 ;; defsubst org-uniquify must be defined before first use
22578 (defun org-uniquify-alist (alist)
22579 "Merge elements of ALIST with the same key.
22581 For example, in this alist:
22583 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22584 => \\='((a 1 3) (b 2))
22586 merge (a 1) and (a 3) into (a 1 3).
22588 The function returns the new ALIST."
22589 (let (rtn)
22590 (dolist (e alist rtn)
22591 (let (n)
22592 (if (not (assoc (car e) rtn))
22593 (push e rtn)
22594 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22595 (setq rtn (assq-delete-all (car e) rtn))
22596 (push n rtn))))))
22598 (defun org-delete-all (elts list)
22599 "Remove all elements in ELTS from LIST.
22600 Comparison is done with `equal'. It is a destructive operation
22601 that may remove elements by altering the list structure."
22602 (while elts
22603 (setq list (delete (pop elts) list)))
22604 list)
22606 (defun org-back-over-empty-lines ()
22607 "Move backwards over whitespace, to the beginning of the first empty line.
22608 Returns the number of empty lines passed."
22609 (let ((pos (point)))
22610 (if (cdr (assoc 'heading org-blank-before-new-entry))
22611 (skip-chars-backward " \t\n\r")
22612 (unless (eobp)
22613 (forward-line -1)))
22614 (beginning-of-line 2)
22615 (goto-char (min (point) pos))
22616 (count-lines (point) pos)))
22618 (defun org-skip-whitespace ()
22619 (skip-chars-forward " \t\n\r"))
22621 (defun org-point-in-group (point group &optional context)
22622 "Check if POINT is in match-group GROUP.
22623 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22624 match. If the match group does not exist or point is not inside it,
22625 return nil."
22626 (and (match-beginning group)
22627 (>= point (match-beginning group))
22628 (<= point (match-end group))
22629 (if context
22630 (list context (match-beginning group) (match-end group))
22631 t)))
22633 (defun org-switch-to-buffer-other-window (&rest args)
22634 "Switch to buffer in a second window on the current frame.
22635 In particular, do not allow pop-up frames.
22636 Returns the newly created buffer."
22637 (org-no-popups
22638 (apply 'switch-to-buffer-other-window args)))
22640 (defun org-combine-plists (&rest plists)
22641 "Create a single property list from all plists in PLISTS.
22642 The process starts by copying the first list, and then setting properties
22643 from the other lists. Settings in the last list are the most significant
22644 ones and overrule settings in the other lists."
22645 (let ((rtn (copy-sequence (pop plists)))
22646 p v ls)
22647 (while plists
22648 (setq ls (pop plists))
22649 (while ls
22650 (setq p (pop ls) v (pop ls))
22651 (setq rtn (plist-put rtn p v))))
22652 rtn))
22654 (defun org-replace-escapes (string table)
22655 "Replace %-escapes in STRING with values in TABLE.
22656 TABLE is an association list with keys like \"%a\" and string values.
22657 The sequences in STRING may contain normal field width and padding information,
22658 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22659 so values can contain further %-escapes if they are define later in TABLE."
22660 (let ((tbl (copy-alist table))
22661 (case-fold-search nil)
22662 (pchg 0)
22663 re rpl)
22664 (dolist (e tbl)
22665 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22666 (when (and (cdr e) (string-match re (cdr e)))
22667 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22668 (safe "SREF"))
22669 (add-text-properties 0 3 (list 'sref sref) safe)
22670 (setcdr e (replace-match safe t t (cdr e)))))
22671 (while (string-match re string)
22672 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22673 (cdr e)))
22674 (setq string (replace-match rpl t t string))))
22675 (while (setq pchg (next-property-change pchg string))
22676 (let ((sref (get-text-property pchg 'sref string)))
22677 (when (and sref (string-match "SREF" string pchg))
22678 (setq string (replace-match sref t t string)))))
22679 string))
22681 (defun org-sublist (list start end)
22682 "Return a section of LIST, from START to END.
22684 Counting starts at 1."
22685 (cl-subseq list (1- start) end))
22686 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22688 (defun org-find-base-buffer-visiting (file)
22689 "Like `find-buffer-visiting' but always return the base buffer and
22690 not an indirect buffer."
22691 (let ((buf (or (get-file-buffer file)
22692 (find-buffer-visiting file))))
22693 (if buf
22694 (or (buffer-base-buffer buf) buf)
22695 nil)))
22697 ;;; TODO: Only called once, from ox-odt which should probably use
22698 ;;; org-export-inline-image-p or something.
22699 (defun org-file-image-p (file)
22700 "Return non-nil if FILE is an image."
22701 (save-match-data
22702 (string-match (image-file-name-regexp) file)))
22704 (defun org-get-cursor-date (&optional with-time)
22705 "Return the date at cursor in as a time.
22706 This works in the calendar and in the agenda, anywhere else it just
22707 returns the current time.
22708 If WITH-TIME is non-nil, returns the time of the event at point (in
22709 the agenda) or the current time of the day."
22710 (let (date day defd tp hod mod)
22711 (when with-time
22712 (setq tp (get-text-property (point) 'time))
22713 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22714 (setq hod (string-to-number (match-string 1 tp))
22715 mod (string-to-number (match-string 2 tp))))
22716 (or tp (let ((now (decode-time)))
22717 (setq hod (nth 2 now)
22718 mod (nth 1 now)))))
22719 (cond
22720 ((eq major-mode 'calendar-mode)
22721 (setq date (calendar-cursor-to-date)
22722 defd (encode-time 0 (or mod 0) (or hod 0)
22723 (nth 1 date) (nth 0 date) (nth 2 date))))
22724 ((eq major-mode 'org-agenda-mode)
22725 (setq day (get-text-property (point) 'day))
22726 (when day
22727 (setq date (calendar-gregorian-from-absolute day)
22728 defd (encode-time 0 (or mod 0) (or hod 0)
22729 (nth 1 date) (nth 0 date) (nth 2 date))))))
22730 (or defd (current-time))))
22732 (defun org-mark-subtree (&optional up)
22733 "Mark the current subtree.
22734 This puts point at the start of the current subtree, and mark at
22735 the end. If a numeric prefix UP is given, move up into the
22736 hierarchy of headlines by UP levels before marking the subtree."
22737 (interactive "P")
22738 (org-with-limited-levels
22739 (cond ((org-at-heading-p) (beginning-of-line))
22740 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22741 (t (outline-previous-visible-heading 1))))
22742 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22743 (if (called-interactively-p 'any)
22744 (call-interactively 'org-mark-element)
22745 (org-mark-element)))
22747 (defun org-file-newer-than-p (file time)
22748 "Non-nil if FILE is newer than TIME.
22749 FILE is a filename, as a string, TIME is a list of integers, as
22750 returned by, e.g., `current-time'."
22751 (and (file-exists-p file)
22752 ;; Only compare times up to whole seconds as some file-systems
22753 ;; (e.g. HFS+) do not retain any finer granularity. As
22754 ;; a consequence, make sure we return non-nil when the two
22755 ;; times are equal.
22756 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22757 (cl-subseq time 0 2)))))
22759 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22760 "Compile a SOURCE file using PROCESS.
22762 PROCESS is either a function or a list of shell commands, as
22763 strings. EXT is a file extension, without the leading dot, as
22764 a string. It is used to check if the process actually succeeded.
22766 PROCESS must create a file with the same base name and directory
22767 as SOURCE, but ending with EXT. The function then returns its
22768 filename. Otherwise, it raises an error. The error message can
22769 then be refined by providing string ERR-MSG, which is appended to
22770 the standard message.
22772 If PROCESS is a function, it is called with a single argument:
22773 the SOURCE file.
22775 If it is a list of commands, each of them is called using
22776 `shell-command'. By default, in each command, %b, %f, %F and %o
22777 are replaced with, respectively, SOURCE base name, name, full
22778 name and directory. It is possible, however, to use more
22779 place-holders by specifying them in optional argument SPEC, as an
22780 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22782 When PROCESS is a list of commands, optional argument LOG-BUF can
22783 be set to a buffer or a buffer name. `shell-command' then uses
22784 it for output.
22786 `default-directory' is set to SOURCE directory during the whole
22787 process."
22788 (let* ((source-name (file-name-nondirectory source))
22789 (base-name (file-name-sans-extension source-name))
22790 (full-name (file-truename source))
22791 (out-dir (file-name-directory source))
22792 (time (current-time))
22793 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22794 (save-window-excursion
22795 (let ((default-directory (file-name-directory full-name)))
22796 (pcase process
22797 ((pred functionp) (funcall process (shell-quote-argument source)))
22798 ((pred consp)
22799 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22800 (spec (append spec
22801 `((?b . ,(shell-quote-argument base-name))
22802 (?f . ,(shell-quote-argument source-name))
22803 (?F . ,(shell-quote-argument full-name))
22804 (?o . ,(shell-quote-argument out-dir))))))
22805 (dolist (command process)
22806 (shell-command (format-spec command spec) log-buf))))
22807 (_ (error "No valid command to process %S%s" source err-msg)))))
22808 ;; Check for process failure.
22809 (let ((output (concat out-dir base-name "." ext)))
22810 (unless (org-file-newer-than-p output time)
22811 (error (format "File %S wasn't produced%s" output err-msg)))
22812 output)))
22814 ;;; Indentation
22816 (defun org--get-expected-indentation (element contentsp)
22817 "Expected indentation column for current line, according to ELEMENT.
22818 ELEMENT is an element containing point. CONTENTSP is non-nil
22819 when indentation is to be computed according to contents of
22820 ELEMENT."
22821 (let ((type (org-element-type element))
22822 (start (org-element-property :begin element))
22823 (post-affiliated (org-element-property :post-affiliated element)))
22824 (org-with-wide-buffer
22825 (cond
22826 (contentsp
22827 (cl-case type
22828 ((diary-sexp footnote-definition) 0)
22829 ((headline inlinetask nil)
22830 (if (not org-adapt-indentation) 0
22831 (let ((level (org-current-level)))
22832 (if level (1+ level) 0))))
22833 ((item plain-list) (org-list-item-body-column post-affiliated))
22835 (goto-char start)
22836 (org-get-indentation))))
22837 ((memq type '(headline inlinetask nil))
22838 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22839 (org--get-expected-indentation element t)
22841 ((memq type '(diary-sexp footnote-definition)) 0)
22842 ;; First paragraph of a footnote definition or an item.
22843 ;; Indent like parent.
22844 ((< (line-beginning-position) start)
22845 (org--get-expected-indentation
22846 (org-element-property :parent element) t))
22847 ;; At first line: indent according to previous sibling, if any,
22848 ;; ignoring footnote definitions and inline tasks, or parent's
22849 ;; contents.
22850 ((= (line-beginning-position) start)
22851 (catch 'exit
22852 (while t
22853 (if (= (point-min) start) (throw 'exit 0)
22854 (goto-char (1- start))
22855 (let* ((previous (org-element-at-point))
22856 (parent previous))
22857 (while (and parent (<= (org-element-property :end parent) start))
22858 (setq previous parent
22859 parent (org-element-property :parent parent)))
22860 (cond
22861 ((not previous) (throw 'exit 0))
22862 ((> (org-element-property :end previous) start)
22863 (throw 'exit (org--get-expected-indentation previous t)))
22864 ((memq (org-element-type previous)
22865 '(footnote-definition inlinetask))
22866 (setq start (org-element-property :begin previous)))
22867 (t (goto-char (org-element-property :begin previous))
22868 (throw 'exit
22869 (if (bolp) (org-get-indentation)
22870 ;; At first paragraph in an item or
22871 ;; a footnote definition.
22872 (org--get-expected-indentation
22873 (org-element-property :parent previous) t))))))))))
22874 ;; Otherwise, move to the first non-blank line above.
22876 (beginning-of-line)
22877 (let ((pos (point)))
22878 (skip-chars-backward " \r\t\n")
22879 (cond
22880 ;; Two blank lines end a footnote definition or a plain
22881 ;; list. When we indent an empty line after them, the
22882 ;; containing list or footnote definition is over, so it
22883 ;; qualifies as a previous sibling. Therefore, we indent
22884 ;; like its first line.
22885 ((and (memq type '(footnote-definition plain-list))
22886 (> (count-lines (point) pos) 2))
22887 (goto-char start)
22888 (org-get-indentation))
22889 ;; Line above is the first one of a paragraph at the
22890 ;; beginning of an item or a footnote definition. Indent
22891 ;; like parent.
22892 ((< (line-beginning-position) start)
22893 (org--get-expected-indentation
22894 (org-element-property :parent element) t))
22895 ;; Line above is the beginning of an element, i.e., point
22896 ;; was originally on the blank lines between element's start
22897 ;; and contents.
22898 ((= (line-beginning-position) post-affiliated)
22899 (org--get-expected-indentation element t))
22900 ;; POS is after contents in a greater element. Indent like
22901 ;; the beginning of the element.
22903 ;; As a special case, if point is at the end of a footnote
22904 ;; definition or an item, indent like the very last element
22905 ;; within. If that last element is an item, indent like its
22906 ;; contents.
22907 ((and (not (eq type 'paragraph))
22908 (let ((cend (org-element-property :contents-end element)))
22909 (and cend (<= cend pos))))
22910 (if (memq type '(footnote-definition item plain-list))
22911 (let ((last (org-element-at-point)))
22912 (org--get-expected-indentation
22913 last (eq (org-element-type last) 'item)))
22914 (goto-char start)
22915 (org-get-indentation)))
22916 ;; In any other case, indent like the current line.
22917 (t (org-get-indentation)))))))))
22919 (defun org--align-node-property ()
22920 "Align node property at point.
22921 Alignment is done according to `org-property-format', which see."
22922 (when (save-excursion
22923 (beginning-of-line)
22924 (looking-at org-property-re))
22925 (replace-match
22926 (concat (match-string 4)
22927 (org-trim
22928 (format org-property-format (match-string 1) (match-string 3))))
22929 t t)))
22931 (defun org-indent-line ()
22932 "Indent line depending on context.
22934 Indentation is done according to the following rules:
22936 - Footnote definitions, diary sexps, headlines and inline tasks
22937 have to start at column 0.
22939 - On the very first line of an element, consider, in order, the
22940 next rules until one matches:
22942 1. If there's a sibling element before, ignoring footnote
22943 definitions and inline tasks, indent like its first line.
22945 2. If element has a parent, indent like its contents. More
22946 precisely, if parent is an item, indent after the
22947 description part, if any, or the bullet (see
22948 `org-list-description-max-indent'). Else, indent like
22949 parent's first line.
22951 3. Otherwise, indent relatively to current level, if
22952 `org-adapt-indentation' is non-nil, or to left margin.
22954 - On a blank line at the end of an element, indent according to
22955 the type of the element. More precisely
22957 1. If element is a plain list, an item, or a footnote
22958 definition, indent like the very last element within.
22960 2. If element is a paragraph, indent like its last non blank
22961 line.
22963 3. Otherwise, indent like its very first line.
22965 - In the code part of a source block, use language major mode
22966 to indent current line if `org-src-tab-acts-natively' is
22967 non-nil. If it is nil, do nothing.
22969 - Otherwise, indent like the first non-blank line above.
22971 The function doesn't indent an item as it could break the whole
22972 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22973 \\[org-shiftmetaright].
22975 Also align node properties according to `org-property-format'."
22976 (interactive)
22977 (cond
22978 (orgstruct-is-++
22979 (let ((indent-line-function
22980 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22981 (indent-according-to-mode)))
22982 ((org-at-heading-p) 'noindent)
22984 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22985 (type (org-element-type element)))
22986 (cond ((and (memq type '(plain-list item))
22987 (= (line-beginning-position)
22988 (org-element-property :post-affiliated element)))
22989 'noindent)
22990 ((and (eq type 'src-block)
22991 org-src-tab-acts-natively
22992 (> (line-beginning-position)
22993 (org-element-property :post-affiliated element))
22994 (< (line-beginning-position)
22995 (org-with-wide-buffer
22996 (goto-char (org-element-property :end element))
22997 (skip-chars-backward " \r\t\n")
22998 (line-beginning-position))))
22999 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23001 (let ((column (org--get-expected-indentation element nil)))
23002 ;; Preserve current column.
23003 (if (<= (current-column) (current-indentation))
23004 (indent-line-to column)
23005 (save-excursion (indent-line-to column))))
23006 ;; Align node property. Also preserve current column.
23007 (when (eq type 'node-property)
23008 (let ((column (current-column)))
23009 (org--align-node-property)
23010 (org-move-to-column column)))))))))
23012 (defun org-indent-region (start end)
23013 "Indent each non-blank line in the region.
23014 Called from a program, START and END specify the region to
23015 indent. The function will not indent contents of example blocks,
23016 verse blocks and export blocks as leading white spaces are
23017 assumed to be significant there."
23018 (interactive "r")
23019 (save-excursion
23020 (goto-char start)
23021 (skip-chars-forward " \r\t\n")
23022 (unless (eobp) (beginning-of-line))
23023 (let ((indent-to
23024 (lambda (ind pos)
23025 ;; Set IND as indentation for all lines between point and
23026 ;; POS. Blank lines are ignored. Leave point after POS
23027 ;; once done.
23028 (let ((limit (copy-marker pos)))
23029 (while (< (point) limit)
23030 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23031 (forward-line))
23032 (set-marker limit nil))))
23033 (end (copy-marker end)))
23034 (while (< (point) end)
23035 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23036 (let* ((element (org-element-at-point))
23037 (type (org-element-type element))
23038 (element-end (copy-marker (org-element-property :end element)))
23039 (ind (org--get-expected-indentation element nil)))
23040 (cond
23041 ((or (memq type '(paragraph table table-row))
23042 (not (or (org-element-property :contents-begin element)
23043 (memq type
23044 '(example-block export-block src-block)))))
23045 ;; Elements here are indented as a single block. Also
23046 ;; align node properties.
23047 (when (eq type 'node-property)
23048 (org--align-node-property)
23049 (beginning-of-line))
23050 (funcall indent-to ind (min element-end end)))
23052 ;; Elements in this category consist of three parts:
23053 ;; before the contents, the contents, and after the
23054 ;; contents. The contents are treated specially,
23055 ;; according to the element type, or not indented at
23056 ;; all. Other parts are indented as a single block.
23057 (let* ((post (copy-marker
23058 (org-element-property :post-affiliated element)))
23059 (cbeg
23060 (copy-marker
23061 (cond
23062 ((not (org-element-property :contents-begin element))
23063 ;; Fake contents for source blocks.
23064 (org-with-wide-buffer
23065 (goto-char post)
23066 (forward-line)
23067 (point)))
23068 ((memq type '(footnote-definition item plain-list))
23069 ;; Contents in these elements could start on
23070 ;; the same line as the beginning of the
23071 ;; element. Make sure we start indenting
23072 ;; from the second line.
23073 (org-with-wide-buffer
23074 (goto-char post)
23075 (end-of-line)
23076 (skip-chars-forward " \r\t\n")
23077 (if (eobp) (point) (line-beginning-position))))
23078 (t (org-element-property :contents-begin element)))))
23079 (cend (copy-marker
23080 (or (org-element-property :contents-end element)
23081 ;; Fake contents for source blocks.
23082 (org-with-wide-buffer
23083 (goto-char element-end)
23084 (skip-chars-backward " \r\t\n")
23085 (line-beginning-position)))
23086 t)))
23087 ;; Do not change items indentation individually as it
23088 ;; might break the list as a whole. On the other
23089 ;; hand, when at a plain list, indent it as a whole.
23090 (cond ((eq type 'plain-list)
23091 (let ((offset (- ind (org-get-indentation))))
23092 (unless (zerop offset)
23093 (indent-rigidly (org-element-property :begin element)
23094 (org-element-property :end element)
23095 offset))
23096 (goto-char cbeg)))
23097 ((eq type 'item) (goto-char cbeg))
23098 (t (funcall indent-to ind (min cbeg end))))
23099 (when (< (point) end)
23100 (cl-case type
23101 ((example-block export-block verse-block))
23102 (src-block
23103 ;; In a source block, indent source code
23104 ;; according to language major mode, but only if
23105 ;; `org-src-tab-acts-natively' is non-nil.
23106 (when (and (< (point) end) org-src-tab-acts-natively)
23107 (ignore-errors
23108 (org-babel-do-in-edit-buffer
23109 (indent-region (point-min) (point-max))))))
23110 (t (org-indent-region (point) (min cend end))))
23111 (goto-char (min cend end))
23112 (when (< (point) end)
23113 (funcall indent-to ind (min element-end end))))
23114 (set-marker post nil)
23115 (set-marker cbeg nil)
23116 (set-marker cend nil))))
23117 (set-marker element-end nil))))
23118 (set-marker end nil))))
23120 (defun org-indent-drawer ()
23121 "Indent the drawer at point."
23122 (interactive)
23123 (unless (save-excursion
23124 (beginning-of-line)
23125 (looking-at-p org-drawer-regexp))
23126 (user-error "Not at a drawer"))
23127 (let ((element (org-element-at-point)))
23128 (unless (memq (org-element-type element) '(drawer property-drawer))
23129 (user-error "Not at a drawer"))
23130 (org-with-wide-buffer
23131 (org-indent-region (org-element-property :begin element)
23132 (org-element-property :end element))))
23133 (message "Drawer at point indented"))
23135 (defun org-indent-block ()
23136 "Indent the block at point."
23137 (interactive)
23138 (unless (save-excursion
23139 (beginning-of-line)
23140 (let ((case-fold-search t))
23141 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23142 (user-error "Not at a block"))
23143 (let ((element (org-element-at-point)))
23144 (unless (memq (org-element-type element)
23145 '(comment-block center-block dynamic-block example-block
23146 export-block quote-block special-block
23147 src-block verse-block))
23148 (user-error "Not at a block"))
23149 (org-with-wide-buffer
23150 (org-indent-region (org-element-property :begin element)
23151 (org-element-property :end element))))
23152 (message "Block at point indented"))
23155 ;;; Filling
23157 ;; We use our own fill-paragraph and auto-fill functions.
23159 ;; `org-fill-paragraph' relies on adaptive filling and context
23160 ;; checking. Appropriate `fill-prefix' is computed with
23161 ;; `org-adaptive-fill-function'.
23163 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23164 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23165 ;; `org-adaptive-fill-function' value. Internally,
23166 ;; `org-comment-line-break-function' breaks the line.
23168 ;; `org-setup-filling' installs filling and auto-filling related
23169 ;; variables during `org-mode' initialization.
23171 (defvar org-element-paragraph-separate) ; org-element.el
23172 (defun org-setup-filling ()
23173 (require 'org-element)
23174 ;; Prevent auto-fill from inserting unwanted new items.
23175 (when (boundp 'fill-nobreak-predicate)
23176 (setq-local
23177 fill-nobreak-predicate
23178 (org-uniquify
23179 (append fill-nobreak-predicate
23180 '(org-fill-line-break-nobreak-p
23181 org-fill-paragraph-with-timestamp-nobreak-p)))))
23182 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23183 (setq-local paragraph-start paragraph-ending)
23184 (setq-local paragraph-separate paragraph-ending))
23185 (setq-local fill-paragraph-function 'org-fill-paragraph)
23186 (setq-local auto-fill-inhibit-regexp nil)
23187 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23188 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23189 (setq-local comment-line-break-function 'org-comment-line-break-function))
23191 (defun org-fill-line-break-nobreak-p ()
23192 "Non-nil when a new line at point would create an Org line break."
23193 (save-excursion
23194 (skip-chars-backward "[ \t]")
23195 (skip-chars-backward "\\\\")
23196 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23198 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23199 "Non-nil when a new line at point would split a timestamp."
23200 (and (org-at-timestamp-p t)
23201 (not (looking-at org-ts-regexp-both))))
23203 (declare-function message-in-body-p "message" ())
23204 (defvar orgtbl-line-start-regexp) ; From org-table.el
23205 (defun org-adaptive-fill-function ()
23206 "Compute a fill prefix for the current line.
23207 Return fill prefix, as a string, or nil if current line isn't
23208 meant to be filled. For convenience, if `adaptive-fill-regexp'
23209 matches in paragraphs or comments, use it."
23210 (catch 'exit
23211 (when (derived-mode-p 'message-mode)
23212 (save-excursion
23213 (beginning-of-line)
23214 (cond ((not (message-in-body-p)) (throw 'exit nil))
23215 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23216 ((looking-at message-cite-prefix-regexp)
23217 (throw 'exit (match-string-no-properties 0)))
23218 ((looking-at org-outline-regexp)
23219 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23220 (org-with-wide-buffer
23221 (unless (org-at-heading-p)
23222 (let* ((p (line-beginning-position))
23223 (element (save-excursion
23224 (beginning-of-line)
23225 (org-element-at-point)))
23226 (type (org-element-type element))
23227 (post-affiliated (org-element-property :post-affiliated element)))
23228 (unless (< p post-affiliated)
23229 (cl-case type
23230 (comment
23231 (save-excursion
23232 (beginning-of-line)
23233 (looking-at "[ \t]*")
23234 (concat (match-string 0) "# ")))
23235 (footnote-definition "")
23236 ((item plain-list)
23237 (make-string (org-list-item-body-column post-affiliated) ?\s))
23238 (paragraph
23239 ;; Fill prefix is usually the same as the current line,
23240 ;; unless the paragraph is at the beginning of an item.
23241 (let ((parent (org-element-property :parent element)))
23242 (save-excursion
23243 (beginning-of-line)
23244 (cond ((eq (org-element-type parent) 'item)
23245 (make-string (org-list-item-body-column
23246 (org-element-property :begin parent))
23247 ?\s))
23248 ((and adaptive-fill-regexp
23249 ;; Locally disable
23250 ;; `adaptive-fill-function' to let
23251 ;; `fill-context-prefix' handle
23252 ;; `adaptive-fill-regexp' variable.
23253 (let (adaptive-fill-function)
23254 (fill-context-prefix
23255 post-affiliated
23256 (org-element-property :end element)))))
23257 ((looking-at "[ \t]+") (match-string 0))
23258 (t "")))))
23259 (comment-block
23260 ;; Only fill contents if P is within block boundaries.
23261 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23262 (forward-line)
23263 (point)))
23264 (cend (save-excursion
23265 (goto-char (org-element-property :end element))
23266 (skip-chars-backward " \r\t\n")
23267 (line-beginning-position))))
23268 (when (and (>= p cbeg) (< p cend))
23269 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23270 (match-string 0)
23271 "")))))))))))
23273 (declare-function message-goto-body "message" ())
23274 (defvar message-cite-prefix-regexp) ; From message.el
23275 (defun org-fill-paragraph (&optional justify)
23276 "Fill element at point, when applicable.
23278 This function only applies to comment blocks, comments, example
23279 blocks and paragraphs. Also, as a special case, re-align table
23280 when point is at one.
23282 If JUSTIFY is non-nil (interactively, with prefix argument),
23283 justify as well. If `sentence-end-double-space' is non-nil, then
23284 period followed by one space does not end a sentence, so don't
23285 break a line there. The variable `fill-column' controls the
23286 width for filling.
23288 For convenience, when point is at a plain list, an item or
23289 a footnote definition, try to fill the first paragraph within."
23290 (interactive)
23291 (if (and (derived-mode-p 'message-mode)
23292 (or (not (message-in-body-p))
23293 (save-excursion (move-beginning-of-line 1)
23294 (looking-at message-cite-prefix-regexp))))
23295 ;; First ensure filling is correct in message-mode.
23296 (let ((fill-paragraph-function
23297 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23298 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23299 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23300 (paragraph-separate
23301 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23302 (fill-paragraph nil))
23303 (with-syntax-table org-mode-transpose-word-syntax-table
23304 ;; Move to end of line in order to get the first paragraph
23305 ;; within a plain list or a footnote definition.
23306 (let ((element (save-excursion
23307 (end-of-line)
23308 (or (ignore-errors (org-element-at-point))
23309 (user-error "An element cannot be parsed line %d"
23310 (line-number-at-pos (point)))))))
23311 ;; First check if point is in a blank line at the beginning of
23312 ;; the buffer. In that case, ignore filling.
23313 (cl-case (org-element-type element)
23314 ;; Use major mode filling function is src blocks.
23315 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23316 ;; Align Org tables, leave table.el tables as-is.
23317 (table-row (org-table-align) t)
23318 (table
23319 (when (eq (org-element-property :type element) 'org)
23320 (save-excursion
23321 (goto-char (org-element-property :post-affiliated element))
23322 (org-table-align)))
23324 (paragraph
23325 ;; Paragraphs may contain `line-break' type objects.
23326 (let ((beg (max (point-min)
23327 (org-element-property :contents-begin element)))
23328 (end (min (point-max)
23329 (org-element-property :contents-end element))))
23330 ;; Do nothing if point is at an affiliated keyword.
23331 (if (< (line-end-position) beg) t
23332 (when (derived-mode-p 'message-mode)
23333 ;; In `message-mode', do not fill following citation
23334 ;; in current paragraph nor text before message body.
23335 (let ((body-start (save-excursion (message-goto-body))))
23336 (when body-start (setq beg (max body-start beg))))
23337 (when (save-excursion
23338 (re-search-forward
23339 (concat "^" message-cite-prefix-regexp) end t))
23340 (setq end (match-beginning 0))))
23341 ;; Fill paragraph, taking line breaks into account.
23342 (save-excursion
23343 (goto-char beg)
23344 (let ((cuts (list beg)))
23345 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23346 (when (eq 'line-break
23347 (org-element-type
23348 (save-excursion (backward-char)
23349 (org-element-context))))
23350 (push (point) cuts)))
23351 (dolist (c (delq end cuts))
23352 (fill-region-as-paragraph c end justify)
23353 (setq end c))))
23354 t)))
23355 ;; Contents of `comment-block' type elements should be
23356 ;; filled as plain text, but only if point is within block
23357 ;; markers.
23358 (comment-block
23359 (let* ((case-fold-search t)
23360 (beg (save-excursion
23361 (goto-char (org-element-property :begin element))
23362 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23363 (forward-line)
23364 (point)))
23365 (end (save-excursion
23366 (goto-char (org-element-property :end element))
23367 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23368 (line-beginning-position))))
23369 (if (or (< (point) beg) (> (point) end)) t
23370 (fill-region-as-paragraph
23371 (save-excursion (end-of-line)
23372 (re-search-backward "^[ \t]*$" beg 'move)
23373 (line-beginning-position))
23374 (save-excursion (beginning-of-line)
23375 (re-search-forward "^[ \t]*$" end 'move)
23376 (line-beginning-position))
23377 justify))))
23378 ;; Fill comments.
23379 (comment
23380 (let ((begin (org-element-property :post-affiliated element))
23381 (end (org-element-property :end element)))
23382 (when (and (>= (point) begin) (<= (point) end))
23383 (let ((begin (save-excursion
23384 (end-of-line)
23385 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23386 (progn (forward-line) (point))
23387 begin)))
23388 (end (save-excursion
23389 (end-of-line)
23390 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23391 (1- (line-beginning-position))
23392 (skip-chars-backward " \r\t\n")
23393 (line-end-position)))))
23394 ;; Do not fill comments when at a blank line.
23395 (when (> end begin)
23396 (let ((fill-prefix
23397 (save-excursion
23398 (beginning-of-line)
23399 (looking-at "[ \t]*#")
23400 (let ((comment-prefix (match-string 0)))
23401 (goto-char (match-end 0))
23402 (if (looking-at adaptive-fill-regexp)
23403 (concat comment-prefix (match-string 0))
23404 (concat comment-prefix " "))))))
23405 (save-excursion
23406 (fill-region-as-paragraph begin end justify))))))
23408 ;; Ignore every other element.
23409 (otherwise t))))))
23411 (defun org-auto-fill-function ()
23412 "Auto-fill function."
23413 ;; Check if auto-filling is meaningful.
23414 (let ((fc (current-fill-column)))
23415 (when (and fc (> (current-column) fc))
23416 (let* ((fill-prefix (org-adaptive-fill-function))
23417 ;; Enforce empty fill prefix, if required. Otherwise, it
23418 ;; will be computed again.
23419 (adaptive-fill-mode (not (equal fill-prefix ""))))
23420 (when fill-prefix (do-auto-fill))))))
23422 (defun org-comment-line-break-function (&optional soft)
23423 "Break line at point and indent, continuing comment if within one.
23424 The inserted newline is marked hard if variable
23425 `use-hard-newlines' is true, unless optional argument SOFT is
23426 non-nil."
23427 (if soft (insert-and-inherit ?\n) (newline 1))
23428 (save-excursion (forward-char -1) (delete-horizontal-space))
23429 (delete-horizontal-space)
23430 (indent-to-left-margin)
23431 (insert-before-markers-and-inherit fill-prefix))
23434 ;;; Fixed Width Areas
23436 (defun org-toggle-fixed-width ()
23437 "Toggle fixed-width markup.
23439 Add or remove fixed-width markup on current line, whenever it
23440 makes sense. Return an error otherwise.
23442 If a region is active and if it contains only fixed-width areas
23443 or blank lines, remove all fixed-width markup in it. If the
23444 region contains anything else, convert all non-fixed-width lines
23445 to fixed-width ones.
23447 Blank lines at the end of the region are ignored unless the
23448 region only contains such lines."
23449 (interactive)
23450 (if (not (org-region-active-p))
23451 ;; No region:
23453 ;; Remove fixed width marker only in a fixed-with element.
23455 ;; Add fixed width maker in paragraphs, in blank lines after
23456 ;; elements or at the beginning of a headline or an inlinetask,
23457 ;; and before any one-line elements (e.g., a clock).
23458 (progn
23459 (beginning-of-line)
23460 (let* ((element (org-element-at-point))
23461 (type (org-element-type element)))
23462 (cond
23463 ((and (eq type 'fixed-width)
23464 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23465 (replace-match
23466 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23467 ((and (memq type '(babel-call clock comment diary-sexp headline
23468 horizontal-rule keyword paragraph
23469 planning))
23470 (<= (org-element-property :post-affiliated element) (point)))
23471 (skip-chars-forward " \t")
23472 (insert ": "))
23473 ((and (looking-at-p "[ \t]*$")
23474 (or (eq type 'inlinetask)
23475 (save-excursion
23476 (skip-chars-forward " \r\t\n")
23477 (<= (org-element-property :end element) (point)))))
23478 (delete-region (point) (line-end-position))
23479 (org-indent-line)
23480 (insert ": "))
23481 (t (user-error "Cannot insert a fixed-width line here")))))
23482 ;; Region active.
23483 (let* ((begin (save-excursion
23484 (goto-char (region-beginning))
23485 (line-beginning-position)))
23486 (end (copy-marker
23487 (save-excursion
23488 (goto-char (region-end))
23489 (unless (eolp) (beginning-of-line))
23490 (if (save-excursion (re-search-backward "\\S-" begin t))
23491 (progn (skip-chars-backward " \r\t\n") (point))
23492 (point)))))
23493 (all-fixed-width-p
23494 (catch 'not-all-p
23495 (save-excursion
23496 (goto-char begin)
23497 (skip-chars-forward " \r\t\n")
23498 (when (eobp) (throw 'not-all-p nil))
23499 (while (< (point) end)
23500 (let ((element (org-element-at-point)))
23501 (if (eq (org-element-type element) 'fixed-width)
23502 (goto-char (org-element-property :end element))
23503 (throw 'not-all-p nil))))
23504 t))))
23505 (if all-fixed-width-p
23506 (save-excursion
23507 (goto-char begin)
23508 (while (< (point) end)
23509 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23510 (replace-match
23511 "" nil nil nil
23512 (if (= (line-end-position) (match-end 0)) 0 1)))
23513 (forward-line)))
23514 (let ((min-ind (point-max)))
23515 ;; Find minimum indentation across all lines.
23516 (save-excursion
23517 (goto-char begin)
23518 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23519 (setq min-ind 0)
23520 (catch 'zerop
23521 (while (< (point) end)
23522 (unless (looking-at-p "[ \t]*$")
23523 (let ((ind (org-get-indentation)))
23524 (setq min-ind (min min-ind ind))
23525 (when (zerop ind) (throw 'zerop t))))
23526 (forward-line)))))
23527 ;; Loop over all lines and add fixed-width markup everywhere
23528 ;; but in fixed-width lines.
23529 (save-excursion
23530 (goto-char begin)
23531 (while (< (point) end)
23532 (cond
23533 ((org-at-heading-p)
23534 (insert ": ")
23535 (forward-line)
23536 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23537 (insert ":")
23538 (forward-line)))
23539 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23540 (let* ((element (org-element-at-point))
23541 (element-end (org-element-property :end element)))
23542 (if (eq (org-element-type element) 'fixed-width)
23543 (progn (goto-char element-end)
23544 (skip-chars-backward " \r\t\n")
23545 (forward-line))
23546 (let ((limit (min end element-end)))
23547 (while (< (point) limit)
23548 (org-move-to-column min-ind t)
23549 (insert ": ")
23550 (forward-line))))))
23552 (org-move-to-column min-ind t)
23553 (insert ": ")
23554 (forward-line)))))))
23555 (set-marker end nil))))
23558 ;;; Comments
23560 ;; Org comments syntax is quite complex. It requires the entire line
23561 ;; to be just a comment. Also, even with the right syntax at the
23562 ;; beginning of line, some some elements (i.e. verse-block or
23563 ;; example-block) don't accept comments. Usual Emacs comment commands
23564 ;; cannot cope with those requirements. Therefore, Org replaces them.
23566 ;; Org still relies on `comment-dwim', but cannot trust
23567 ;; `comment-only-p'. So, `comment-region-function' and
23568 ;; `uncomment-region-function' both point
23569 ;; to`org-comment-or-uncomment-region'. Eventually,
23570 ;; `org-insert-comment' takes care of insertion of comments at the
23571 ;; beginning of line.
23573 ;; `org-setup-comments-handling' install comments related variables
23574 ;; during `org-mode' initialization.
23576 (defun org-setup-comments-handling ()
23577 (interactive)
23578 (setq-local comment-use-syntax nil)
23579 (setq-local comment-start "# ")
23580 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23581 (setq-local comment-insert-comment-function 'org-insert-comment)
23582 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23583 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23585 (defun org-insert-comment ()
23586 "Insert an empty comment above current line.
23587 If the line is empty, insert comment at its beginning. When
23588 point is within a source block, comment according to the related
23589 major mode."
23590 (if (let ((element (org-element-at-point)))
23591 (and (eq (org-element-type element) 'src-block)
23592 (< (save-excursion
23593 (goto-char (org-element-property :post-affiliated element))
23594 (line-end-position))
23595 (point))
23596 (> (save-excursion
23597 (goto-char (org-element-property :end element))
23598 (skip-chars-backward " \r\t\n")
23599 (line-beginning-position))
23600 (point))))
23601 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23602 (beginning-of-line)
23603 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23604 (open-line 1))
23605 (org-indent-line)
23606 (insert "# ")))
23608 (defvar comment-empty-lines) ; From newcomment.el.
23609 (defun org-comment-or-uncomment-region (beg end &rest _)
23610 "Comment or uncomment each non-blank line in the region.
23611 Uncomment each non-blank line between BEG and END if it only
23612 contains commented lines. Otherwise, comment them. If region is
23613 strictly within a source block, use appropriate comment syntax."
23614 (if (let ((element (org-element-at-point)))
23615 (and (eq (org-element-type element) 'src-block)
23616 (< (save-excursion
23617 (goto-char (org-element-property :post-affiliated element))
23618 (line-end-position))
23619 beg)
23620 (>= (save-excursion
23621 (goto-char (org-element-property :end element))
23622 (skip-chars-backward " \r\t\n")
23623 (line-beginning-position))
23624 end)))
23625 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23626 (save-restriction
23627 ;; Restrict region
23628 (narrow-to-region (save-excursion (goto-char beg)
23629 (skip-chars-forward " \r\t\n" end)
23630 (line-beginning-position))
23631 (save-excursion (goto-char end)
23632 (skip-chars-backward " \r\t\n" beg)
23633 (line-end-position)))
23634 (let ((uncommentp
23635 ;; UNCOMMENTP is non-nil when every non blank line between
23636 ;; BEG and END is a comment.
23637 (save-excursion
23638 (goto-char (point-min))
23639 (while (and (not (eobp))
23640 (let ((element (org-element-at-point)))
23641 (and (eq (org-element-type element) 'comment)
23642 (goto-char (min (point-max)
23643 (org-element-property
23644 :end element)))))))
23645 (eobp))))
23646 (if uncommentp
23647 ;; Only blank lines and comments in region: uncomment it.
23648 (save-excursion
23649 (goto-char (point-min))
23650 (while (not (eobp))
23651 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23652 (replace-match "" nil nil nil 1))
23653 (forward-line)))
23654 ;; Comment each line in region.
23655 (let ((min-indent (point-max)))
23656 ;; First find the minimum indentation across all lines.
23657 (save-excursion
23658 (goto-char (point-min))
23659 (while (and (not (eobp)) (not (zerop min-indent)))
23660 (unless (looking-at "[ \t]*$")
23661 (setq min-indent (min min-indent (current-indentation))))
23662 (forward-line)))
23663 ;; Then loop over all lines.
23664 (save-excursion
23665 (goto-char (point-min))
23666 (while (not (eobp))
23667 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23668 ;; Don't get fooled by invisible text (e.g. link path)
23669 ;; when moving to column MIN-INDENT.
23670 (let ((buffer-invisibility-spec nil))
23671 (org-move-to-column min-indent t))
23672 (insert comment-start))
23673 (forward-line)))))))))
23675 (defun org-comment-dwim (_arg)
23676 "Call `comment-dwim' within a source edit buffer if needed."
23677 (interactive "*P")
23678 (if (org-in-src-block-p)
23679 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23680 (call-interactively 'comment-dwim)))
23683 ;;; Timestamps API
23685 ;; This section contains tools to operate on timestamp objects, as
23686 ;; returned by, e.g. `org-element-context'.
23688 (defun org-timestamp--to-internal-time (timestamp &optional end)
23689 "Encode TIMESTAMP object into Emacs internal time.
23690 Use end of date range or time range when END is non-nil."
23691 (apply #'encode-time
23692 (cons 0
23693 (mapcar
23694 (lambda (prop) (or (org-element-property prop timestamp) 0))
23695 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23696 '(:minute-start :hour-start :day-start :month-start
23697 :year-start))))))
23699 (defun org-timestamp-has-time-p (timestamp)
23700 "Non-nil when TIMESTAMP has a time specified."
23701 (org-element-property :hour-start timestamp))
23703 (defun org-timestamp-format (timestamp format &optional end utc)
23704 "Format a TIMESTAMP object into a string.
23706 FORMAT is a format specifier to be passed to
23707 `format-time-string'.
23709 When optional argument END is non-nil, use end of date-range or
23710 time-range, if possible.
23712 When optional argument UTC is non-nil, time will be expressed as
23713 Universal Time."
23714 (format-time-string
23715 format (org-timestamp--to-internal-time timestamp end)
23716 (and utc t)))
23718 (defun org-timestamp-split-range (timestamp &optional end)
23719 "Extract a TIMESTAMP object from a date or time range.
23721 END, when non-nil, means extract the end of the range.
23722 Otherwise, extract its start.
23724 Return a new timestamp object."
23725 (let ((type (org-element-property :type timestamp)))
23726 (if (memq type '(active inactive diary)) timestamp
23727 (let ((split-ts (org-element-copy timestamp)))
23728 ;; Set new type.
23729 (org-element-put-property
23730 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23731 ;; Copy start properties over end properties if END is
23732 ;; non-nil. Otherwise, copy end properties over `start' ones.
23733 (let ((p-alist '((:minute-start . :minute-end)
23734 (:hour-start . :hour-end)
23735 (:day-start . :day-end)
23736 (:month-start . :month-end)
23737 (:year-start . :year-end))))
23738 (dolist (p-cell p-alist)
23739 (org-element-put-property
23740 split-ts
23741 (funcall (if end #'car #'cdr) p-cell)
23742 (org-element-property
23743 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23744 ;; Eventually refresh `:raw-value'.
23745 (org-element-put-property split-ts :raw-value nil)
23746 (org-element-put-property
23747 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23749 (defun org-timestamp-translate (timestamp &optional boundary)
23750 "Translate TIMESTAMP object to custom format.
23752 Format string is defined in `org-time-stamp-custom-formats',
23753 which see.
23755 When optional argument BOUNDARY is non-nil, it is either the
23756 symbol `start' or `end'. In this case, only translate the
23757 starting or ending part of TIMESTAMP if it is a date or time
23758 range. Otherwise, translate both parts.
23760 Return timestamp as-is if `org-display-custom-times' is nil or if
23761 it has a `diary' type."
23762 (let ((type (org-element-property :type timestamp)))
23763 (if (or (not org-display-custom-times) (eq type 'diary))
23764 (org-element-interpret-data timestamp)
23765 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23766 org-time-stamp-custom-formats)))
23767 (if (and (not boundary) (memq type '(active-range inactive-range)))
23768 (concat (org-timestamp-format timestamp fmt)
23769 "--"
23770 (org-timestamp-format timestamp fmt t))
23771 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23775 ;;; Other stuff.
23777 (defvar reftex-docstruct-symbol)
23778 (defvar reftex-cite-format)
23779 (defvar org--rds)
23781 (defun org-reftex-citation ()
23782 "Use reftex-citation to insert a citation into the buffer.
23783 This looks for a line like
23785 #+BIBLIOGRAPHY: foo plain option:-d
23787 and derives from it that foo.bib is the bibliography file relevant
23788 for this document. It then installs the necessary environment for RefTeX
23789 to work in this buffer and calls `reftex-citation' to insert a citation
23790 into the buffer.
23792 Export of such citations to both LaTeX and HTML is handled by the contributed
23793 package ox-bibtex by Taru Karttunen."
23794 (interactive)
23795 (let ((reftex-docstruct-symbol 'org--rds)
23796 (reftex-cite-format "\\cite{%l}")
23797 org--rds bib)
23798 (save-excursion
23799 (save-restriction
23800 (widen)
23801 (let ((case-fold-search t)
23802 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23803 (if (not (save-excursion
23804 (or (re-search-forward re nil t)
23805 (re-search-backward re nil t))))
23806 (user-error "No bibliography defined in file")
23807 (setq bib (concat (match-string 1) ".bib")
23808 org--rds (list (list 'bib bib)))))))
23809 (call-interactively 'reftex-citation)))
23811 ;;;; Functions extending outline functionality
23813 (defun org-beginning-of-line (&optional arg)
23814 "Go to the beginning of the current line. If that is invisible, continue
23815 to a visible line beginning. This makes the function of C-a more intuitive.
23816 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23817 first attempt, and only move to after the tags when the cursor is already
23818 beyond the end of the headline."
23819 (interactive "P")
23820 (let ((pos (point))
23821 (special (if (consp org-special-ctrl-a/e)
23822 (car org-special-ctrl-a/e)
23823 org-special-ctrl-a/e))
23824 deactivate-mark refpos)
23825 (call-interactively (if (bound-and-true-p visual-line-mode)
23826 #'beginning-of-visual-line
23827 #'move-beginning-of-line))
23828 (cond
23829 ((or arg (not special)))
23830 ((and (looking-at org-complex-heading-regexp)
23831 (eq (char-after (match-end 1)) ?\s))
23832 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23833 (point-at-eol)))
23834 (goto-char
23835 (if (eq special t)
23836 (cond ((> pos refpos) refpos)
23837 ((= pos (point)) refpos)
23838 (t (point)))
23839 (cond ((> pos (point)) (point))
23840 ((not (eq last-command this-command)) (point))
23841 (t refpos)))))
23842 ((org-at-item-p)
23843 ;; Being at an item and not looking at an the item means point
23844 ;; was previously moved to beginning of a visual line, which
23845 ;; doesn't contain the item. Therefore, do nothing special,
23846 ;; just stay here.
23847 (when (looking-at org-list-full-item-re)
23848 ;; Set special position at first white space character after
23849 ;; bullet, and check-box, if any.
23850 (let ((after-bullet
23851 (let ((box (match-end 3)))
23852 (if (not box) (match-end 1)
23853 (let ((after (char-after box)))
23854 (if (and after (= after ? )) (1+ box) box))))))
23855 ;; Special case: Move point to special position when
23856 ;; currently after it or at beginning of line.
23857 (if (eq special t)
23858 (when (or (> pos after-bullet) (= (point) pos))
23859 (goto-char after-bullet))
23860 ;; Reversed case: Move point to special position when
23861 ;; point was already at beginning of line and command is
23862 ;; repeated.
23863 (when (and (= (point) pos) (eq last-command this-command))
23864 (goto-char after-bullet))))))))
23865 (setq disable-point-adjustment
23866 (or (not (invisible-p (point)))
23867 (not (invisible-p (max (point-min) (1- (point))))))))
23869 (defun org-end-of-line (&optional arg)
23870 "Go to the end of the line.
23871 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23872 tags on the first attempt, and only move to after the tags when
23873 the cursor is already beyond the end of the headline."
23874 (interactive "P")
23875 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23876 org-special-ctrl-a/e))
23877 (move-fun (cond ((bound-and-true-p visual-line-mode)
23878 'end-of-visual-line)
23879 ((fboundp 'move-end-of-line) 'move-end-of-line)
23880 (t 'end-of-line)))
23881 deactivate-mark)
23882 (if (or (not special) arg) (call-interactively move-fun)
23883 (let* ((element (save-excursion (beginning-of-line)
23884 (org-element-at-point)))
23885 (type (org-element-type element)))
23886 (cond
23887 ((memq type '(headline inlinetask))
23888 (let ((pos (point)))
23889 (beginning-of-line 1)
23890 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23891 (if (eq special t)
23892 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23893 (goto-char (match-beginning 1))
23894 (goto-char (match-end 0)))
23895 (if (or (< pos (match-end 0))
23896 (not (eq this-command last-command)))
23897 (goto-char (match-end 0))
23898 (goto-char (match-beginning 1))))
23899 (call-interactively move-fun))))
23900 ((outline-invisible-p (line-end-position))
23901 ;; If element is hidden, `move-end-of-line' would put point
23902 ;; after it. Use `end-of-line' to stay on current line.
23903 (call-interactively 'end-of-line))
23904 (t (call-interactively move-fun))))))
23905 (setq disable-point-adjustment
23906 (or (not (invisible-p (point)))
23907 (not (invisible-p (max (point-min) (1- (point))))))))
23909 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23910 (define-key org-mode-map "\C-e" 'org-end-of-line)
23912 (defun org-backward-sentence (&optional _arg)
23913 "Go to beginning of sentence, or beginning of table field.
23914 This will call `backward-sentence' or `org-table-beginning-of-field',
23915 depending on context."
23916 (interactive)
23917 (let* ((element (org-element-at-point))
23918 (contents-begin (org-element-property :contents-begin element))
23919 (table (org-element-lineage element '(table) t)))
23920 (if (and table
23921 (> (point) contents-begin)
23922 (<= (point) (org-element-property :contents-end table)))
23923 (call-interactively #'org-table-beginning-of-field)
23924 (save-restriction
23925 (when (and contents-begin
23926 (< (point-min) contents-begin)
23927 (> (point) contents-begin))
23928 (narrow-to-region contents-begin
23929 (org-element-property :contents-end element)))
23930 (call-interactively #'backward-sentence)))))
23932 (defun org-forward-sentence (&optional _arg)
23933 "Go to end of sentence, or end of table field.
23934 This will call `forward-sentence' or `org-table-end-of-field',
23935 depending on context."
23936 (interactive)
23937 (let* ((element (org-element-at-point))
23938 (contents-end (org-element-property :contents-end element))
23939 (table (org-element-lineage element '(table) t)))
23940 (if (and table
23941 (>= (point) (org-element-property :contents-begin table))
23942 (< (point) contents-end))
23943 (call-interactively #'org-table-end-of-field)
23944 (save-restriction
23945 (when (and contents-end
23946 (> (point-max) contents-end)
23947 ;; Skip blank lines between elements.
23948 (< (org-element-property :end element)
23949 (save-excursion (goto-char contents-end)
23950 (skip-chars-forward " \r\t\n"))))
23951 (narrow-to-region (org-element-property :contents-begin element)
23952 contents-end))
23953 (call-interactively #'forward-sentence)))))
23955 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23956 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23958 (defun org-kill-line (&optional _arg)
23959 "Kill line, to tags or end of line."
23960 (interactive)
23961 (cond
23962 ((or (not org-special-ctrl-k)
23963 (bolp)
23964 (not (org-at-heading-p)))
23965 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23966 org-ctrl-k-protect-subtree
23967 (or (eq org-ctrl-k-protect-subtree 'error)
23968 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23969 (user-error "C-k aborted as it would kill a hidden subtree"))
23970 (call-interactively
23971 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23972 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23973 (kill-region (point) (match-beginning 1))
23974 (org-set-tags nil t))
23975 (t (kill-region (point) (point-at-eol)))))
23977 (define-key org-mode-map "\C-k" 'org-kill-line)
23979 (defun org-yank (&optional arg)
23980 "Yank. If the kill is a subtree, treat it specially.
23981 This command will look at the current kill and check if is a single
23982 subtree, or a series of subtrees[1]. If it passes the test, and if the
23983 cursor is at the beginning of a line or after the stars of a currently
23984 empty headline, then the yank is handled specially. How exactly depends
23985 on the value of the following variables.
23987 `org-yank-folded-subtrees'
23988 By default, this variable is non-nil, which results in subtree(s)
23989 being folded after insertion, but only if doing so would now
23990 swallow text after the yanked text.
23992 `org-yank-adjusted-subtrees'
23993 When non-nil (the default value is nil), the subtree will be
23994 promoted or demoted in order to fit into the local outline tree
23995 structure, which means that the level will be adjusted so that it
23996 becomes the smaller one of the two *visible* surrounding headings.
23998 Any prefix to this command will cause `yank' to be called directly with
23999 no special treatment. In particular, a simple \\[universal-argument] prefix \
24000 will just
24001 plainly yank the text as it is.
24003 \[1] The test checks if the first non-white line is a heading
24004 and if there are no other headings with fewer stars."
24005 (interactive "P")
24006 (org-yank-generic 'yank arg))
24008 (defun org-yank-generic (command arg)
24009 "Perform some yank-like command.
24011 This function implements the behavior described in the `org-yank'
24012 documentation. However, it has been generalized to work for any
24013 interactive command with similar behavior."
24015 ;; pretend to be command COMMAND
24016 (setq this-command command)
24018 (if arg
24019 (call-interactively command)
24021 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24022 (and (org-kill-is-subtree-p)
24023 (or (bolp)
24024 (and (looking-at "[ \t]*$")
24025 (string-match
24026 "\\`\\*+\\'"
24027 (buffer-substring (point-at-bol) (point)))))))
24028 swallowp)
24029 (cond
24030 ((and subtreep org-yank-folded-subtrees)
24031 (let ((beg (point))
24032 end)
24033 (if (and subtreep org-yank-adjusted-subtrees)
24034 (org-paste-subtree nil nil 'for-yank)
24035 (call-interactively command))
24037 (setq end (point))
24038 (goto-char beg)
24039 (when (and (bolp) subtreep
24040 (not (setq swallowp
24041 (org-yank-folding-would-swallow-text beg end))))
24042 (org-with-limited-levels
24043 (or (looking-at org-outline-regexp)
24044 (re-search-forward org-outline-regexp-bol end t))
24045 (while (and (< (point) end) (looking-at org-outline-regexp))
24046 (outline-hide-subtree)
24047 (org-cycle-show-empty-lines 'folded)
24048 (condition-case nil
24049 (outline-forward-same-level 1)
24050 (error (goto-char end))))))
24051 (when swallowp
24052 (message
24053 "Inserted text not folded because that would swallow text"))
24055 (goto-char end)
24056 (skip-chars-forward " \t\n\r")
24057 (beginning-of-line 1)
24058 (push-mark beg 'nomsg)))
24059 ((and subtreep org-yank-adjusted-subtrees)
24060 (let ((beg (point-at-bol)))
24061 (org-paste-subtree nil nil 'for-yank)
24062 (push-mark beg 'nomsg)))
24064 (call-interactively command))))))
24066 (defun org-yank-folding-would-swallow-text (beg end)
24067 "Would hide-subtree at BEG swallow any text after END?"
24068 (let (level)
24069 (org-with-limited-levels
24070 (save-excursion
24071 (goto-char beg)
24072 (when (or (looking-at org-outline-regexp)
24073 (re-search-forward org-outline-regexp-bol end t))
24074 (setq level (org-outline-level)))
24075 (goto-char end)
24076 (skip-chars-forward " \t\r\n\v\f")
24077 (not (or (eobp)
24078 (and (bolp) (looking-at-p org-outline-regexp)
24079 (<= (org-outline-level) level))))))))
24081 (define-key org-mode-map "\C-y" 'org-yank)
24083 (defun org-truely-invisible-p ()
24084 "Check if point is at a character currently not visible.
24085 This version does not only check the character property, but also
24086 `visible-mode'."
24087 ;; Early versions of noutline don't have `outline-invisible-p'.
24088 (unless (bound-and-true-p visible-mode)
24089 (outline-invisible-p)))
24091 (defun org-invisible-p2 ()
24092 "Check if point is at a character currently not visible."
24093 (save-excursion
24094 (when (and (eolp) (not (bobp))) (backward-char 1))
24095 ;; Early versions of noutline don't have `outline-invisible-p'.
24096 (outline-invisible-p)))
24098 (defun org-back-to-heading (&optional invisible-ok)
24099 "Call `outline-back-to-heading', but provide a better error message."
24100 (condition-case nil
24101 (outline-back-to-heading invisible-ok)
24102 (error (error "Before first headline at position %d in buffer %s"
24103 (point) (current-buffer)))))
24105 (defun org-before-first-heading-p ()
24106 "Before first heading?"
24107 (save-excursion
24108 (end-of-line)
24109 (null (re-search-backward org-outline-regexp-bol nil t))))
24111 (defun org-at-heading-p (&optional ignored)
24112 (outline-on-heading-p t))
24114 (defun org-in-commented-heading-p (&optional no-inheritance)
24115 "Non-nil if point is under a commented heading.
24116 This function also checks ancestors of the current headline,
24117 unless optional argument NO-INHERITANCE is non-nil."
24118 (cond
24119 ((org-before-first-heading-p) nil)
24120 ((let ((headline (nth 4 (org-heading-components))))
24121 (and headline
24122 (let ((case-fold-search nil))
24123 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24124 headline)))))
24125 (no-inheritance nil)
24127 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24129 (defun org-at-comment-p nil
24130 "Is cursor in a commented line?"
24131 (save-excursion
24132 (save-match-data
24133 (beginning-of-line)
24134 (looking-at "^[ \t]*# "))))
24136 (defun org-at-drawer-p nil
24137 "Is cursor at a drawer keyword?"
24138 (save-excursion
24139 (move-beginning-of-line 1)
24140 (looking-at org-drawer-regexp)))
24142 (defun org-at-block-p nil
24143 "Is cursor at a block keyword?"
24144 (save-excursion
24145 (move-beginning-of-line 1)
24146 (looking-at org-block-regexp)))
24148 (defun org-point-at-end-of-empty-headline ()
24149 "If point is at the end of an empty headline, return t, else nil.
24150 If the heading only contains a TODO keyword, it is still still considered
24151 empty."
24152 (and (looking-at "[ \t]*$")
24153 (when org-todo-line-regexp
24154 (save-excursion
24155 (beginning-of-line 1)
24156 (let ((case-fold-search nil))
24157 (looking-at org-todo-line-regexp)
24158 (string= (match-string 3) ""))))))
24160 (defun org-at-heading-or-item-p ()
24161 (or (org-at-heading-p) (org-at-item-p)))
24163 (defun org-at-target-p ()
24164 (or (org-in-regexp org-radio-target-regexp)
24165 (org-in-regexp org-target-regexp)))
24166 ;; Compatibility alias with Org versions < 7.8.03
24167 (defalias 'org-on-target-p 'org-at-target-p)
24169 (defun org-up-heading-all (arg)
24170 "Move to the heading line of which the present line is a subheading.
24171 This function considers both visible and invisible heading lines.
24172 With argument, move up ARG levels."
24173 (outline-up-heading arg t))
24175 (defun org-up-heading-safe ()
24176 "Move to the heading line of which the present line is a subheading.
24177 This version will not throw an error. It will return the level of the
24178 headline found, or nil if no higher level is found.
24180 Also, this function will be a lot faster than `outline-up-heading',
24181 because it relies on stars being the outline starters. This can really
24182 make a significant difference in outlines with very many siblings."
24183 (when (ignore-errors (org-back-to-heading t))
24184 (let ((level-up (1- (funcall outline-level))))
24185 (and (> level-up 0)
24186 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24187 (funcall outline-level)))))
24189 (defun org-first-sibling-p ()
24190 "Is this heading the first child of its parents?"
24191 (interactive)
24192 (let ((re org-outline-regexp-bol)
24193 level l)
24194 (unless (org-at-heading-p t)
24195 (user-error "Not at a heading"))
24196 (setq level (funcall outline-level))
24197 (save-excursion
24198 (if (not (re-search-backward re nil t))
24200 (setq l (funcall outline-level))
24201 (< l level)))))
24203 (defun org-goto-sibling (&optional previous)
24204 "Goto the next sibling, even if it is invisible.
24205 When PREVIOUS is set, go to the previous sibling instead. Returns t
24206 when a sibling was found. When none is found, return nil and don't
24207 move point."
24208 (let ((fun (if previous 're-search-backward 're-search-forward))
24209 (pos (point))
24210 (re org-outline-regexp-bol)
24211 level l)
24212 (when (ignore-errors (org-back-to-heading t))
24213 (setq level (funcall outline-level))
24214 (catch 'exit
24215 (or previous (forward-char 1))
24216 (while (funcall fun re nil t)
24217 (setq l (funcall outline-level))
24218 (when (< l level) (goto-char pos) (throw 'exit nil))
24219 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24220 (goto-char pos)
24221 nil))))
24223 (defun org-show-siblings ()
24224 "Show all siblings of the current headline."
24225 (save-excursion
24226 (while (org-goto-sibling) (org-flag-heading nil)))
24227 (save-excursion
24228 (while (org-goto-sibling 'previous)
24229 (org-flag-heading nil))))
24231 (defun org-goto-first-child ()
24232 "Goto the first child, even if it is invisible.
24233 Return t when a child was found. Otherwise don't move point and
24234 return nil."
24235 (let (level (pos (point)) (re org-outline-regexp-bol))
24236 (when (ignore-errors (org-back-to-heading t))
24237 (setq level (outline-level))
24238 (forward-char 1)
24239 (if (and (re-search-forward re nil t) (> (outline-level) level))
24240 (progn (goto-char (match-beginning 0)) t)
24241 (goto-char pos) nil))))
24243 (defun org-show-hidden-entry ()
24244 "Show an entry where even the heading is hidden."
24245 (save-excursion
24246 (org-show-entry)))
24248 (defun org-flag-heading (flag &optional entry)
24249 "Flag the current heading. FLAG non-nil means make invisible.
24250 When ENTRY is non-nil, show the entire entry."
24251 (save-excursion
24252 (org-back-to-heading t)
24253 ;; Check if we should show the entire entry
24254 (if entry
24255 (progn
24256 (org-show-entry)
24257 (save-excursion
24258 (and (outline-next-heading)
24259 (org-flag-heading nil))))
24260 (outline-flag-region (max (point-min) (1- (point)))
24261 (save-excursion (outline-end-of-heading) (point))
24262 flag))))
24264 (defun org-get-next-sibling ()
24265 "Move to next heading of the same level, and return point.
24266 If there is no such heading, return nil.
24267 This is like outline-next-sibling, but invisible headings are ok."
24268 (let ((level (funcall outline-level)))
24269 (outline-next-heading)
24270 (while (and (not (eobp)) (> (funcall outline-level) level))
24271 (outline-next-heading))
24272 (unless (or (eobp) (< (funcall outline-level) level))
24273 (point))))
24275 (defun org-get-last-sibling ()
24276 "Move to previous heading of the same level, and return point.
24277 If there is no such heading, return nil."
24278 (let ((opoint (point))
24279 (level (funcall outline-level)))
24280 (outline-previous-heading)
24281 (when (and (/= (point) opoint) (outline-on-heading-p t))
24282 (while (and (> (funcall outline-level) level)
24283 (not (bobp)))
24284 (outline-previous-heading))
24285 (unless (< (funcall outline-level) level)
24286 (point)))))
24288 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24289 "Goto to the end of a subtree."
24290 ;; This contains an exact copy of the original function, but it uses
24291 ;; `org-back-to-heading', to make it work also in invisible
24292 ;; trees. And is uses an invisible-ok argument.
24293 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24294 ;; Furthermore, when used inside Org, finding the end of a large subtree
24295 ;; with many children and grandchildren etc, this can be much faster
24296 ;; than the outline version.
24297 (org-back-to-heading invisible-ok)
24298 (let ((first t)
24299 (level (funcall outline-level)))
24300 (if (and (derived-mode-p 'org-mode) (< level 1000))
24301 ;; A true heading (not a plain list item), in Org-mode
24302 ;; This means we can easily find the end by looking
24303 ;; only for the right number of stars. Using a regexp to do
24304 ;; this is so much faster than using a Lisp loop.
24305 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24306 (forward-char 1)
24307 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24308 ;; something else, do it the slow way
24309 (while (and (not (eobp))
24310 (or first (> (funcall outline-level) level)))
24311 (setq first nil)
24312 (outline-next-heading)))
24313 (unless to-heading
24314 (when (memq (preceding-char) '(?\n ?\^M))
24315 ;; Go to end of line before heading
24316 (forward-char -1)
24317 (when (memq (preceding-char) '(?\n ?\^M))
24318 ;; leave blank line before heading
24319 (forward-char -1)))))
24320 (point))
24322 (defun org-end-of-meta-data (&optional full)
24323 "Skip planning line and properties drawer in current entry.
24324 When optional argument FULL is non-nil, also skip empty lines,
24325 clocking lines and regular drawers at the beginning of the
24326 entry."
24327 (org-back-to-heading t)
24328 (forward-line)
24329 (when (looking-at-p org-planning-line-re) (forward-line))
24330 (when (looking-at org-property-drawer-re)
24331 (goto-char (match-end 0))
24332 (forward-line))
24333 (when (and full (not (org-at-heading-p)))
24334 (catch 'exit
24335 (let ((end (save-excursion (outline-next-heading) (point)))
24336 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24337 (while (not (eobp))
24338 (cond ((looking-at-p org-drawer-regexp)
24339 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24340 (forward-line)
24341 (throw 'exit t)))
24342 ((looking-at-p re) (forward-line))
24343 (t (throw 'exit t))))))))
24345 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24346 "Move forward to the ARG'th subheading at same level as this one.
24347 Stop at the first and last subheadings of a superior heading.
24348 Normally this only looks at visible headings, but when INVISIBLE-OK is
24349 non-nil it will also look at invisible ones."
24350 (interactive "p")
24351 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24352 (if (and arg (< arg 0))
24353 (goto-char (point-min))
24354 (outline-next-heading))
24355 (org-at-heading-p)
24356 (let ((level (- (match-end 0) (match-beginning 0) 1))
24357 (f (if (and arg (< arg 0))
24358 're-search-backward
24359 're-search-forward))
24360 (count (if arg (abs arg) 1))
24361 (result (point)))
24362 (while (and (prog1 (> count 0)
24363 (forward-char (if (and arg (< arg 0)) -1 1)))
24364 (funcall f org-outline-regexp-bol nil 'move))
24365 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24366 (cond ((< l level) (setq count 0))
24367 ((and (= l level)
24368 (or invisible-ok
24369 (progn
24370 (goto-char (line-beginning-position))
24371 (not (outline-invisible-p)))))
24372 (setq count (1- count))
24373 (when (eq l level)
24374 (setq result (point)))))))
24375 (goto-char result))
24376 (beginning-of-line 1)))
24378 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24379 "Move backward to the ARG'th subheading at same level as this one.
24380 Stop at the first and last subheadings of a superior heading."
24381 (interactive "p")
24382 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24384 (defun org-next-visible-heading (arg)
24385 "Move to the next visible heading.
24387 This function wraps `outline-next-visible-heading' with
24388 `org-with-limited-levels' in order to skip over inline tasks and
24389 respect customization of `org-odd-levels-only'."
24390 (interactive "p")
24391 (org-with-limited-levels
24392 (outline-next-visible-heading arg)))
24394 (defun org-previous-visible-heading (arg)
24395 "Move to the previous visible heading.
24397 This function wraps `outline-previous-visible-heading' with
24398 `org-with-limited-levels' in order to skip over inline tasks and
24399 respect customization of `org-odd-levels-only'."
24400 (interactive "p")
24401 (org-with-limited-levels
24402 (outline-previous-visible-heading arg)))
24404 (defun org-next-block (arg &optional backward block-regexp)
24405 "Jump to the next block.
24407 With a prefix argument ARG, jump forward ARG many blocks.
24409 When BACKWARD is non-nil, jump to the previous block.
24411 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24412 Match data is set according to this regexp when the function
24413 returns.
24415 Return point at beginning of the opening line of found block.
24416 Throw an error if no block is found."
24417 (interactive "p")
24418 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24419 (case-fold-search t)
24420 (search-fn (if backward #'re-search-backward #'re-search-forward))
24421 (count (or arg 1))
24422 (origin (point))
24423 last-element)
24424 (if backward (beginning-of-line) (end-of-line))
24425 (while (and (> count 0) (funcall search-fn re nil t))
24426 (let ((element (save-excursion
24427 (goto-char (match-beginning 0))
24428 (save-match-data (org-element-at-point)))))
24429 (when (and (memq (org-element-type element)
24430 '(center-block comment-block dynamic-block
24431 example-block export-block quote-block
24432 special-block src-block verse-block))
24433 (<= (match-beginning 0)
24434 (org-element-property :post-affiliated element)))
24435 (setq last-element element)
24436 (cl-decf count))))
24437 (if (= count 0)
24438 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24439 (save-match-data (org-show-context)))
24440 (goto-char origin)
24441 (user-error "No %s code blocks" (if backward "previous" "further")))))
24443 (defun org-previous-block (arg &optional block-regexp)
24444 "Jump to the previous block.
24445 With a prefix argument ARG, jump backward ARG many source blocks.
24446 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24447 (interactive "p")
24448 (org-next-block arg t block-regexp))
24450 (defun org-forward-paragraph ()
24451 "Move forward to beginning of next paragraph or equivalent.
24453 The function moves point to the beginning of the next visible
24454 structural element, which can be a paragraph, a table, a list
24455 item, etc. It also provides some special moves for convenience:
24457 - On an affiliated keyword, jump to the beginning of the
24458 relative element.
24459 - On an item or a footnote definition, move to the second
24460 element inside, if any.
24461 - On a table or a property drawer, jump after it.
24462 - On a verse or source block, stop after blank lines."
24463 (interactive)
24464 (when (eobp) (user-error "Cannot move further down"))
24465 (let* ((deactivate-mark nil)
24466 (element (org-element-at-point))
24467 (type (org-element-type element))
24468 (post-affiliated (org-element-property :post-affiliated element))
24469 (contents-begin (org-element-property :contents-begin element))
24470 (contents-end (org-element-property :contents-end element))
24471 (end (let ((end (org-element-property :end element)) (parent element))
24472 (while (and (setq parent (org-element-property :parent parent))
24473 (= (org-element-property :contents-end parent) end))
24474 (setq end (org-element-property :end parent)))
24475 end)))
24476 (cond ((not element)
24477 (skip-chars-forward " \r\t\n")
24478 (or (eobp) (beginning-of-line)))
24479 ;; On affiliated keywords, move to element's beginning.
24480 ((< (point) post-affiliated)
24481 (goto-char post-affiliated))
24482 ;; At a table row, move to the end of the table. Similarly,
24483 ;; at a node property, move to the end of the property
24484 ;; drawer.
24485 ((memq type '(node-property table-row))
24486 (goto-char (org-element-property
24487 :end (org-element-property :parent element))))
24488 ((memq type '(property-drawer table)) (goto-char end))
24489 ;; Consider blank lines as separators in verse and source
24490 ;; blocks to ease editing.
24491 ((memq type '(src-block verse-block))
24492 (when (eq type 'src-block)
24493 (setq contents-end
24494 (save-excursion (goto-char end)
24495 (skip-chars-backward " \r\t\n")
24496 (line-beginning-position))))
24497 (beginning-of-line)
24498 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24499 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24500 (goto-char end)
24501 (skip-chars-forward " \r\t\n")
24502 (if (= (point) contents-end) (goto-char end)
24503 (beginning-of-line))))
24504 ;; With no contents, just skip element.
24505 ((not contents-begin) (goto-char end))
24506 ;; If contents are invisible, skip the element altogether.
24507 ((outline-invisible-p (line-end-position))
24508 (cl-case type
24509 (headline
24510 (org-with-limited-levels (outline-next-visible-heading 1)))
24511 ;; At a plain list, make sure we move to the next item
24512 ;; instead of skipping the whole list.
24513 (plain-list (forward-char)
24514 (org-forward-paragraph))
24515 (otherwise (goto-char end))))
24516 ((>= (point) contents-end) (goto-char end))
24517 ((>= (point) contents-begin)
24518 ;; This can only happen on paragraphs and plain lists.
24519 (cl-case type
24520 (paragraph (goto-char end))
24521 ;; At a plain list, try to move to second element in
24522 ;; first item, if possible.
24523 (plain-list (end-of-line)
24524 (org-forward-paragraph))))
24525 ;; When contents start on the middle of a line (e.g. in
24526 ;; items and footnote definitions), try to reach first
24527 ;; element starting after current line.
24528 ((> (line-end-position) contents-begin)
24529 (end-of-line)
24530 (org-forward-paragraph))
24531 (t (goto-char contents-begin)))))
24533 (defun org-backward-paragraph ()
24534 "Move backward to start of previous paragraph or equivalent.
24536 The function moves point to the beginning of the current
24537 structural element, which can be a paragraph, a table, a list
24538 item, etc., or to the beginning of the previous visible one if
24539 point is already there. It also provides some special moves for
24540 convenience:
24542 - On an affiliated keyword, jump to the first one.
24543 - On a table or a property drawer, move to its beginning.
24544 - On a verse or source block, stop before blank lines."
24545 (interactive)
24546 (when (bobp) (user-error "Cannot move further up"))
24547 (let* ((deactivate-mark nil)
24548 (element (org-element-at-point))
24549 (type (org-element-type element))
24550 (contents-begin (org-element-property :contents-begin element))
24551 (contents-end (org-element-property :contents-end element))
24552 (post-affiliated (org-element-property :post-affiliated element))
24553 (begin (org-element-property :begin element)))
24554 (cond
24555 ((not element) (goto-char (point-min)))
24556 ((= (point) begin)
24557 (backward-char)
24558 (org-backward-paragraph))
24559 ((<= (point) post-affiliated) (goto-char begin))
24560 ((memq type '(node-property table-row))
24561 (goto-char (org-element-property
24562 :post-affiliated (org-element-property :parent element))))
24563 ((memq type '(property-drawer table)) (goto-char begin))
24564 ((memq type '(src-block verse-block))
24565 (when (eq type 'src-block)
24566 (setq contents-begin
24567 (save-excursion (goto-char begin) (forward-line) (point))))
24568 (if (= (point) contents-begin) (goto-char post-affiliated)
24569 ;; Inside a verse block, see blank lines as paragraph
24570 ;; separators.
24571 (let ((origin (point)))
24572 (skip-chars-backward " \r\t\n" contents-begin)
24573 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24574 (skip-chars-forward " \r\t\n" origin)
24575 (if (= (point) origin) (goto-char contents-begin)
24576 (beginning-of-line))))))
24577 ((not contents-begin) (goto-char (or post-affiliated begin)))
24578 ((eq type 'paragraph)
24579 (goto-char contents-begin)
24580 ;; When at first paragraph in an item or a footnote definition,
24581 ;; move directly to beginning of line.
24582 (let ((parent-contents
24583 (org-element-property
24584 :contents-begin (org-element-property :parent element))))
24585 (when (and parent-contents (= parent-contents contents-begin))
24586 (beginning-of-line))))
24587 ;; At the end of a greater element, move to the beginning of the
24588 ;; last element within.
24589 ((>= (point) contents-end)
24590 (goto-char (1- contents-end))
24591 (org-backward-paragraph))
24592 (t (goto-char (or post-affiliated begin))))
24593 ;; Ensure we never leave point invisible.
24594 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24596 (defun org-forward-element ()
24597 "Move forward by one element.
24598 Move to the next element at the same level, when possible."
24599 (interactive)
24600 (cond ((eobp) (user-error "Cannot move further down"))
24601 ((org-with-limited-levels (org-at-heading-p))
24602 (let ((origin (point)))
24603 (goto-char (org-end-of-subtree nil t))
24604 (unless (org-with-limited-levels (org-at-heading-p))
24605 (goto-char origin)
24606 (user-error "Cannot move further down"))))
24608 (let* ((elem (org-element-at-point))
24609 (end (org-element-property :end elem))
24610 (parent (org-element-property :parent elem)))
24611 (cond ((and parent (= (org-element-property :contents-end parent) end))
24612 (goto-char (org-element-property :end parent)))
24613 ((integer-or-marker-p end) (goto-char end))
24614 (t (message "No element at point")))))))
24616 (defun org-backward-element ()
24617 "Move backward by one element.
24618 Move to the previous element at the same level, when possible."
24619 (interactive)
24620 (cond ((bobp) (user-error "Cannot move further up"))
24621 ((org-with-limited-levels (org-at-heading-p))
24622 ;; At a headline, move to the previous one, if any, or stay
24623 ;; here.
24624 (let ((origin (point)))
24625 (org-with-limited-levels (org-backward-heading-same-level 1))
24626 ;; When current headline has no sibling above, move to its
24627 ;; parent.
24628 (when (= (point) origin)
24629 (or (org-with-limited-levels (org-up-heading-safe))
24630 (progn (goto-char origin)
24631 (user-error "Cannot move further up"))))))
24633 (let* ((elem (org-element-at-point))
24634 (beg (org-element-property :begin elem)))
24635 (cond
24636 ;; Move to beginning of current element if point isn't
24637 ;; there already.
24638 ((null beg) (message "No element at point"))
24639 ((/= (point) beg) (goto-char beg))
24640 (t (goto-char beg)
24641 (skip-chars-backward " \r\t\n")
24642 (unless (bobp)
24643 (let ((prev (org-element-at-point)))
24644 (goto-char (org-element-property :begin prev))
24645 (while (and (setq prev (org-element-property :parent prev))
24646 (<= (org-element-property :end prev) beg))
24647 (goto-char (org-element-property :begin prev)))))))))))
24649 (defun org-up-element ()
24650 "Move to upper element."
24651 (interactive)
24652 (if (org-with-limited-levels (org-at-heading-p))
24653 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24654 (let* ((elem (org-element-at-point))
24655 (parent (org-element-property :parent elem)))
24656 (if parent (goto-char (org-element-property :begin parent))
24657 (if (org-with-limited-levels (org-before-first-heading-p))
24658 (user-error "No surrounding element")
24659 (org-with-limited-levels (org-back-to-heading)))))))
24661 (defvar org-element-greater-elements)
24662 (defun org-down-element ()
24663 "Move to inner element."
24664 (interactive)
24665 (let ((element (org-element-at-point)))
24666 (cond
24667 ((memq (org-element-type element) '(plain-list table))
24668 (goto-char (org-element-property :contents-begin element))
24669 (forward-char))
24670 ((memq (org-element-type element) org-element-greater-elements)
24671 ;; If contents are hidden, first disclose them.
24672 (when (outline-invisible-p (line-end-position)) (org-cycle))
24673 (goto-char (or (org-element-property :contents-begin element)
24674 (user-error "No content for this element"))))
24675 (t (user-error "No inner element")))))
24677 (defun org-drag-element-backward ()
24678 "Move backward element at point."
24679 (interactive)
24680 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24681 (let* ((elem (org-element-at-point))
24682 (prev-elem
24683 (save-excursion
24684 (goto-char (org-element-property :begin elem))
24685 (skip-chars-backward " \r\t\n")
24686 (unless (bobp)
24687 (let* ((beg (org-element-property :begin elem))
24688 (prev (org-element-at-point))
24689 (up prev))
24690 (while (and (setq up (org-element-property :parent up))
24691 (<= (org-element-property :end up) beg))
24692 (setq prev up))
24693 prev)))))
24694 ;; Error out if no previous element or previous element is
24695 ;; a parent of the current one.
24696 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24697 (user-error "Cannot drag element backward")
24698 (let ((pos (point)))
24699 (org-element-swap-A-B prev-elem elem)
24700 (goto-char (+ (org-element-property :begin prev-elem)
24701 (- pos (org-element-property :begin elem)))))))))
24703 (defun org-drag-element-forward ()
24704 "Move forward element at point."
24705 (interactive)
24706 (let* ((pos (point))
24707 (elem (org-element-at-point)))
24708 (when (= (point-max) (org-element-property :end elem))
24709 (user-error "Cannot drag element forward"))
24710 (goto-char (org-element-property :end elem))
24711 (let ((next-elem (org-element-at-point)))
24712 (when (or (org-element-nested-p elem next-elem)
24713 (and (eq (org-element-type next-elem) 'headline)
24714 (not (eq (org-element-type elem) 'headline))))
24715 (goto-char pos)
24716 (user-error "Cannot drag element forward"))
24717 ;; Compute new position of point: it's shifted by NEXT-ELEM
24718 ;; body's length (without final blanks) and by the length of
24719 ;; blanks between ELEM and NEXT-ELEM.
24720 (let ((size-next (- (save-excursion
24721 (goto-char (org-element-property :end next-elem))
24722 (skip-chars-backward " \r\t\n")
24723 (forward-line)
24724 ;; Small correction if buffer doesn't end
24725 ;; with a newline character.
24726 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24727 (org-element-property :begin next-elem)))
24728 (size-blank (- (org-element-property :end elem)
24729 (save-excursion
24730 (goto-char (org-element-property :end elem))
24731 (skip-chars-backward " \r\t\n")
24732 (forward-line)
24733 (point)))))
24734 (org-element-swap-A-B elem next-elem)
24735 (goto-char (+ pos size-next size-blank))))))
24737 (defun org-drag-line-forward (arg)
24738 "Drag the line at point ARG lines forward."
24739 (interactive "p")
24740 (dotimes (_ (abs arg))
24741 (let ((c (current-column)))
24742 (if (< 0 arg)
24743 (progn
24744 (beginning-of-line 2)
24745 (transpose-lines 1)
24746 (beginning-of-line 0))
24747 (transpose-lines 1)
24748 (beginning-of-line -1))
24749 (org-move-to-column c))))
24751 (defun org-drag-line-backward (arg)
24752 "Drag the line at point ARG lines backward."
24753 (interactive "p")
24754 (org-drag-line-forward (- arg)))
24756 (defun org-mark-element ()
24757 "Put point at beginning of this element, mark at end.
24759 Interactively, if this command is repeated or (in Transient Mark
24760 mode) if the mark is active, it marks the next element after the
24761 ones already marked."
24762 (interactive)
24763 (let (deactivate-mark)
24764 (if (and (called-interactively-p 'any)
24765 (or (and (eq last-command this-command) (mark t))
24766 (and transient-mark-mode mark-active)))
24767 (set-mark
24768 (save-excursion
24769 (goto-char (mark))
24770 (goto-char (org-element-property :end (org-element-at-point)))))
24771 (let ((element (org-element-at-point)))
24772 (end-of-line)
24773 (push-mark (org-element-property :end element) t t)
24774 (goto-char (org-element-property :begin element))))))
24776 (defun org-narrow-to-element ()
24777 "Narrow buffer to current element."
24778 (interactive)
24779 (let ((elem (org-element-at-point)))
24780 (cond
24781 ((eq (car elem) 'headline)
24782 (narrow-to-region
24783 (org-element-property :begin elem)
24784 (org-element-property :end elem)))
24785 ((memq (car elem) org-element-greater-elements)
24786 (narrow-to-region
24787 (org-element-property :contents-begin elem)
24788 (org-element-property :contents-end elem)))
24790 (narrow-to-region
24791 (org-element-property :begin elem)
24792 (org-element-property :end elem))))))
24794 (defun org-transpose-element ()
24795 "Transpose current and previous elements, keeping blank lines between.
24796 Point is moved after both elements."
24797 (interactive)
24798 (org-skip-whitespace)
24799 (let ((end (org-element-property :end (org-element-at-point))))
24800 (org-drag-element-backward)
24801 (goto-char end)))
24803 (defun org-unindent-buffer ()
24804 "Un-indent the visible part of the buffer.
24805 Relative indentation (between items, inside blocks, etc.) isn't
24806 modified."
24807 (interactive)
24808 (unless (eq major-mode 'org-mode)
24809 (user-error "Cannot un-indent a buffer not in Org mode"))
24810 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24811 (unindent-tree
24812 (lambda (contents)
24813 (dolist (element (reverse contents))
24814 (if (memq (org-element-type element) '(headline section))
24815 (funcall unindent-tree (org-element-contents element))
24816 (save-excursion
24817 (save-restriction
24818 (narrow-to-region
24819 (org-element-property :begin element)
24820 (org-element-property :end element))
24821 (org-do-remove-indentation))))))))
24822 (funcall unindent-tree (org-element-contents parse-tree))))
24824 (defun org-show-children (&optional level)
24825 "Show all direct subheadings of this heading.
24826 Prefix arg LEVEL is how many levels below the current level
24827 should be shown. Default is enough to cause the following
24828 heading to appear."
24829 (interactive "p")
24830 ;; If `orgstruct-mode' is active, use the slower version.
24831 (if orgstruct-mode (call-interactively #'outline-show-children)
24832 (save-excursion
24833 (org-back-to-heading t)
24834 (let* ((current-level (funcall outline-level))
24835 (max-level (org-get-valid-level
24836 current-level
24837 (if level (prefix-numeric-value level) 1)))
24838 (end (save-excursion (org-end-of-subtree t t)))
24839 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24840 (past-first-child nil)
24841 ;; Make sure to skip inlinetasks.
24842 (re (format regexp-fmt
24843 current-level
24844 (cond
24845 ((not (featurep 'org-inlinetask)) "")
24846 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24848 (t (1- org-inlinetask-min-level))))))
24849 ;; Display parent heading.
24850 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24851 (forward-line)
24852 ;; Display children. First child may be deeper than expected
24853 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24854 ;; MAX-LEVEL accordingly.
24855 (while (re-search-forward re end t)
24856 (unless past-first-child
24857 (setq re (format regexp-fmt
24858 current-level
24859 (max (funcall outline-level) max-level)))
24860 (setq past-first-child t))
24861 (outline-flag-region
24862 (line-end-position 0) (line-end-position) nil))))))
24864 (defun org-show-subtree ()
24865 "Show everything after this heading at deeper levels."
24866 (interactive)
24867 (outline-flag-region
24868 (point)
24869 (save-excursion
24870 (org-end-of-subtree t t))
24871 nil))
24873 (defun org-show-entry ()
24874 "Show the body directly following this heading.
24875 Show the heading too, if it is currently invisible."
24876 (interactive)
24877 (save-excursion
24878 (ignore-errors
24879 (org-back-to-heading t)
24880 (outline-flag-region
24881 (max (point-min) (1- (point)))
24882 (save-excursion
24883 (if (re-search-forward
24884 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24885 (match-beginning 1)
24886 (point-max)))
24887 nil)
24888 (org-cycle-hide-drawers 'children))))
24890 (defun org-make-options-regexp (kwds &optional extra)
24891 "Make a regular expression for keyword lines.
24892 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24893 when non-nil, is a regexp matching keywords names."
24894 (concat "^[ \t]*#\\+\\("
24895 (regexp-opt kwds)
24896 (and extra (concat (and kwds "\\|") extra))
24897 "\\):[ \t]*\\(.*\\)"))
24899 ;;;; Integration with and fixes for other packages
24901 ;;; Imenu support
24903 (defvar-local org-imenu-markers nil
24904 "All markers currently used by Imenu.")
24906 (defun org-imenu-new-marker (&optional pos)
24907 "Return a new marker for use by Imenu, and remember the marker."
24908 (let ((m (make-marker)))
24909 (move-marker m (or pos (point)))
24910 (push m org-imenu-markers)
24913 (defun org-imenu-get-tree ()
24914 "Produce the index for Imenu."
24915 (dolist (x org-imenu-markers) (move-marker x nil))
24916 (setq org-imenu-markers nil)
24917 (let* ((case-fold-search nil)
24918 (n org-imenu-depth)
24919 (re (concat "^" (org-get-limited-outline-regexp)))
24920 (subs (make-vector (1+ n) nil))
24921 (last-level 0)
24922 m level head0 head)
24923 (save-excursion
24924 (save-restriction
24925 (widen)
24926 (goto-char (point-max))
24927 (while (re-search-backward re nil t)
24928 (setq level (org-reduced-level (funcall outline-level)))
24929 (when (and (<= level n)
24930 (looking-at org-complex-heading-regexp)
24931 (setq head0 (match-string-no-properties 4)))
24932 (setq head (org-link-display-format head0)
24933 m (org-imenu-new-marker))
24934 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24935 (if (>= level last-level)
24936 (push (cons head m) (aref subs level))
24937 (push (cons head (aref subs (1+ level))) (aref subs level))
24938 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24939 (setq last-level level)))))
24940 (aref subs 1)))
24942 (eval-after-load "imenu"
24943 '(progn
24944 (add-hook 'imenu-after-jump-hook
24945 (lambda ()
24946 (when (derived-mode-p 'org-mode)
24947 (org-show-context 'org-goto))))))
24949 (defun org-link-display-format (s)
24950 "Replace links in string S with their description.
24951 If there is no description, use the link target."
24952 (save-match-data
24953 (replace-regexp-in-string
24954 org-bracket-link-analytic-regexp
24955 (lambda (m)
24956 (if (match-end 5) (match-string 5 m)
24957 (concat (match-string 1 m) (match-string 3 m))))
24958 s nil t)))
24960 (defun org-toggle-link-display ()
24961 "Toggle the literal or descriptive display of links."
24962 (interactive)
24963 (if org-descriptive-links
24964 (progn (org-remove-from-invisibility-spec '(org-link))
24965 (org-restart-font-lock)
24966 (setq org-descriptive-links nil))
24967 (progn (add-to-invisibility-spec '(org-link))
24968 (org-restart-font-lock)
24969 (setq org-descriptive-links t))))
24971 ;; Speedbar support
24973 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24974 "Overlay marking the agenda restriction line in speedbar.")
24975 (overlay-put org-speedbar-restriction-lock-overlay
24976 'face 'org-agenda-restriction-lock)
24977 (overlay-put org-speedbar-restriction-lock-overlay
24978 'help-echo "Agendas are currently limited to this item.")
24979 (delete-overlay org-speedbar-restriction-lock-overlay)
24981 (defun org-speedbar-set-agenda-restriction ()
24982 "Restrict future agenda commands to the location at point in speedbar.
24983 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24984 (interactive)
24985 (require 'org-agenda)
24986 (let (p m tp np dir txt)
24987 (cond
24988 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24989 'org-imenu t))
24990 (setq m (get-text-property p 'org-imenu-marker))
24991 (with-current-buffer (marker-buffer m)
24992 (goto-char m)
24993 (org-agenda-set-restriction-lock 'subtree)))
24994 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24995 'speedbar-function 'speedbar-find-file))
24996 (setq tp (previous-single-property-change
24997 (1+ p) 'speedbar-function)
24998 np (next-single-property-change
24999 tp 'speedbar-function)
25000 dir (speedbar-line-directory)
25001 txt (buffer-substring-no-properties (or tp (point-min))
25002 (or np (point-max))))
25003 (with-current-buffer (find-file-noselect
25004 (let ((default-directory dir))
25005 (expand-file-name txt)))
25006 (unless (derived-mode-p 'org-mode)
25007 (user-error "Cannot restrict to non-Org-mode file"))
25008 (org-agenda-set-restriction-lock 'file)))
25009 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25010 (move-overlay org-speedbar-restriction-lock-overlay
25011 (point-at-bol) (point-at-eol))
25012 (setq current-prefix-arg nil)
25013 (org-agenda-maybe-redo)))
25015 (defvar speedbar-file-key-map)
25016 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25017 (eval-after-load "speedbar"
25018 '(progn
25019 (speedbar-add-supported-extension ".org")
25020 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25021 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25022 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25023 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25024 (add-hook 'speedbar-visiting-tag-hook
25025 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25027 ;;; Fixes and Hacks for problems with other packages
25029 (defun org--flyspell-object-check-p (element)
25030 "Non-nil when Flyspell can check object at point.
25031 ELEMENT is the element at point."
25032 (let ((object (save-excursion
25033 (when (looking-at-p "\\>") (backward-char))
25034 (org-element-context element))))
25035 (cl-case (org-element-type object)
25036 ;; Prevent checks in links due to keybinding conflict with
25037 ;; Flyspell.
25038 ((code entity export-snippet inline-babel-call
25039 inline-src-block line-break latex-fragment link macro
25040 statistics-cookie target timestamp verbatim)
25041 nil)
25042 (footnote-reference
25043 ;; Only in inline footnotes, within the definition.
25044 (and (eq (org-element-property :type object) 'inline)
25045 (< (save-excursion
25046 (goto-char (org-element-property :begin object))
25047 (search-forward ":" nil t 2))
25048 (point))))
25049 (otherwise t))))
25051 (defun org-mode-flyspell-verify ()
25052 "Function used for `flyspell-generic-check-word-predicate'."
25053 (if (org-at-heading-p)
25054 ;; At a headline or an inlinetask, check title only. This is
25055 ;; faster than relying on `org-element-at-point'.
25056 (and (save-excursion (beginning-of-line)
25057 (and (let ((case-fold-search t))
25058 (not (looking-at "\\*+ END[ \t]*$")))
25059 (looking-at org-complex-heading-regexp)))
25060 (match-beginning 4)
25061 (>= (point) (match-beginning 4))
25062 (or (not (match-beginning 5))
25063 (< (point) (match-beginning 5))))
25064 (let* ((element (org-element-at-point))
25065 (post-affiliated (org-element-property :post-affiliated element)))
25066 (cond
25067 ;; Ignore checks in all affiliated keywords but captions.
25068 ((< (point) post-affiliated)
25069 (and (save-excursion
25070 (beginning-of-line)
25071 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25072 (> (point) (match-end 0))
25073 (org--flyspell-object-check-p element)))
25074 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25075 ((let ((log (org-log-into-drawer)))
25076 (and log
25077 (let ((drawer (org-element-lineage element '(drawer))))
25078 (and drawer
25079 (eq (compare-strings
25080 log nil nil
25081 (org-element-property :drawer-name drawer) nil nil t)
25082 t)))))
25083 nil)
25085 (cl-case (org-element-type element)
25086 ((comment quote-section) t)
25087 (comment-block
25088 ;; Allow checks between block markers, not on them.
25089 (and (> (line-beginning-position) post-affiliated)
25090 (save-excursion
25091 (end-of-line)
25092 (skip-chars-forward " \r\t\n")
25093 (< (point) (org-element-property :end element)))))
25094 ;; Arbitrary list of keywords where checks are meaningful.
25095 ;; Make sure point is on the value part of the element.
25096 (keyword
25097 (and (member (org-element-property :key element)
25098 '("DESCRIPTION" "TITLE"))
25099 (save-excursion
25100 (search-backward ":" (line-beginning-position) t))))
25101 ;; Check is globally allowed in paragraphs verse blocks and
25102 ;; table rows (after affiliated keywords) but some objects
25103 ;; must not be affected.
25104 ((paragraph table-row verse-block)
25105 (let ((cbeg (org-element-property :contents-begin element))
25106 (cend (org-element-property :contents-end element)))
25107 (and cbeg (>= (point) cbeg) (< (point) cend)
25108 (org--flyspell-object-check-p element))))))))))
25109 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25111 (defun org-remove-flyspell-overlays-in (beg end)
25112 "Remove flyspell overlays in region."
25113 (and (bound-and-true-p flyspell-mode)
25114 (fboundp 'flyspell-delete-region-overlays)
25115 (flyspell-delete-region-overlays beg end)))
25117 (defvar flyspell-delayed-commands)
25118 (eval-after-load "flyspell"
25119 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25121 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25122 (eval-after-load "bookmark"
25123 '(if (boundp 'bookmark-after-jump-hook)
25124 ;; We can use the hook
25125 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25126 ;; Hook not available, use advice
25127 (defadvice bookmark-jump (after org-make-visible activate)
25128 "Make the position visible."
25129 (org-bookmark-jump-unhide))))
25131 ;; Make sure saveplace shows the location if it was hidden
25132 (eval-after-load "saveplace"
25133 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25134 "Make the position visible."
25135 (org-bookmark-jump-unhide)))
25137 ;; Make sure ecb shows the location if it was hidden
25138 (eval-after-load "ecb"
25139 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25140 "Make hierarchy visible when jumping into location from ECB tree buffer."
25141 (when (derived-mode-p 'org-mode)
25142 (org-show-context))))
25144 (defun org-bookmark-jump-unhide ()
25145 "Unhide the current position, to show the bookmark location."
25146 (and (derived-mode-p 'org-mode)
25147 (or (outline-invisible-p)
25148 (save-excursion (goto-char (max (point-min) (1- (point))))
25149 (outline-invisible-p)))
25150 (org-show-context 'bookmark-jump)))
25152 (defun org-mark-jump-unhide ()
25153 "Make the point visible with `org-show-context' after jumping to the mark."
25154 (when (and (derived-mode-p 'org-mode)
25155 (outline-invisible-p))
25156 (org-show-context 'mark-goto)))
25158 (eval-after-load "simple"
25159 '(defadvice pop-to-mark-command (after org-make-visible activate)
25160 "Make the point visible with `org-show-context'."
25161 (org-mark-jump-unhide)))
25163 (eval-after-load "simple"
25164 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25165 "Make the point visible with `org-show-context'."
25166 (org-mark-jump-unhide)))
25168 (eval-after-load "simple"
25169 '(defadvice pop-global-mark (after org-make-visible activate)
25170 "Make the point visible with `org-show-context'."
25171 (org-mark-jump-unhide)))
25173 ;; Make session.el ignore our circular variable
25174 (defvar session-globals-exclude)
25175 (eval-after-load "session"
25176 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25178 ;;;; Finish up
25180 (provide 'org)
25182 (run-hooks 'org-load-hook)
25184 ;;; org.el ends here