Backport commit f2caf08ca from Emacs
[org-mode/org-tableheadings.git] / lisp / org.el
blob34bf07738e59c544ebed681412044f61f247452e
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-2018 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: https://orgmode.org
10 ;; Version: 9.1.7
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
71 ;;;; Require other packages
73 (require 'cl-lib)
75 (eval-when-compile (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (or (eq this-command 'eval-buffer)
82 (condition-case nil
83 (load (concat (file-name-directory load-file-name)
84 "org-loaddefs.el")
85 nil t t t)
86 (error
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (sit-for 3)
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
90 (sit-for 3))))
92 (require 'org-macs)
93 (require 'org-compat)
95 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
96 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 ;; In Org buffers, the value of `outline-regexp' is that of
99 ;; `org-outline-regexp'. The only function still directly relying on
100 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
101 ;; job when `orgstruct-mode' is active.
102 (defvar org-outline-regexp "\\*+ "
103 "Regexp to match Org headlines.")
105 (defvar org-outline-regexp-bol "^\\*+ "
106 "Regexp to match Org headlines.
107 This is similar to `org-outline-regexp' but additionally makes
108 sure that we are at the beginning of the line.")
110 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
111 "Matches a headline, putting stars and text into groups.
112 Stars are put in group 1 and the trimmed body in group 2.")
114 (declare-function calendar-check-holidays "holidays" (date))
115 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
116 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
117 (declare-function org-add-archive-files "org-archive" (files))
118 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
119 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocking-buffer "org-clock" ())
133 (declare-function org-clocktable-shift "org-clock" (dir n))
134 (declare-function
135 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
136 (declare-function org-element-at-point "org-element" ())
137 (declare-function org-element-cache-refresh "org-element" (pos))
138 (declare-function org-element-cache-reset "org-element" (&optional all))
139 (declare-function org-element-contents "org-element" (element))
140 (declare-function org-element-context "org-element" (&optional element))
141 (declare-function org-element-copy "org-element" (datum))
142 (declare-function org-element-interpret-data "org-element" (data))
143 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
144 (declare-function org-element-link-parser "org-element" ())
145 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
146 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
147 (declare-function org-element-property "org-element" (property element))
148 (declare-function org-element-put-property "org-element" (element property value))
149 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
150 (declare-function org-element-type "org-element" (element))
151 (declare-function org-element-update-syntax "org-element" ())
152 (declare-function org-id-find-id-file "org-id" (id))
153 (declare-function org-id-get-create "org-id" (&optional force))
154 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
155 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
156 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
157 (declare-function org-plot/gnuplot "org-plot" (&optional params))
158 (declare-function org-table-align "org-table" ())
159 (declare-function org-table-begin "org-table" (&optional table-type))
160 (declare-function org-table-beginning-of-field "org-table" (&optional n))
161 (declare-function org-table-blank-field "org-table" ())
162 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
163 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
164 (declare-function org-table-cut-region "org-table" (beg end))
165 (declare-function org-table-edit-field "org-table" (arg))
166 (declare-function org-table-end "org-table" (&optional table-type))
167 (declare-function org-table-end-of-field "org-table" (&optional n))
168 (declare-function org-table-insert-row "org-table" (&optional arg))
169 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
170 (declare-function org-table-maybe-eval-formula "org-table" ())
171 (declare-function org-table-maybe-recalculate-line "org-table" ())
172 (declare-function org-table-next-row "org-table" ())
173 (declare-function org-table-paste-rectangle "org-table" ())
174 (declare-function org-table-recalculate "org-table" (&optional all noalign))
175 (declare-function
176 org-table-sort-lines "org-table"
177 (&optional with-case sorting-type getkey-func compare-func interactive?))
178 (declare-function org-table-wrap-region "org-table" (arg))
179 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
180 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
181 (declare-function orgtbl-mode "org-table" (&optional arg))
182 (declare-function org-export-get-backend "ox" (name))
183 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
184 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
186 (defvar ffap-url-regexp)
187 (defvar org-element-paragraph-separate)
189 (defsubst org-uniquify (list)
190 "Non-destructively remove duplicate elements from LIST."
191 (let ((res (copy-sequence list))) (delete-dups res)))
193 (defsubst org-get-at-bol (property)
194 "Get text property PROPERTY at the beginning of line."
195 (get-text-property (point-at-bol) property))
197 (defsubst org-trim (s &optional keep-lead)
198 "Remove whitespace at the beginning and the end of string S.
199 When optional argument KEEP-LEAD is non-nil, removing blank lines
200 at the beginning of the string does not affect leading indentation."
201 (replace-regexp-in-string
202 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
203 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
205 ;; load languages based on value of `org-babel-load-languages'
206 (defvar org-babel-load-languages)
208 ;;;###autoload
209 (defun org-babel-do-load-languages (sym value)
210 "Load the languages defined in `org-babel-load-languages'."
211 (set-default sym value)
212 (dolist (pair org-babel-load-languages)
213 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
214 (if active
215 (require (intern (concat "ob-" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-execute:" lang)))
218 (funcall 'fmakunbound
219 (intern (concat "org-babel-expand-body:" lang)))))))
221 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
222 ;;;###autoload
223 (defun org-babel-load-file (file &optional compile)
224 "Load Emacs Lisp source code blocks in the Org FILE.
225 This function exports the source code using `org-babel-tangle'
226 and then loads the resulting file using `load-file'. With prefix
227 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
228 file to byte-code before it is loaded."
229 (interactive "fFile to load: \nP")
230 (let* ((age (lambda (file)
231 (float-time
232 (time-subtract (current-time)
233 (nth 5 (or (file-attributes (file-truename file))
234 (file-attributes file)))))))
235 (base-name (file-name-sans-extension file))
236 (exported-file (concat base-name ".el")))
237 ;; tangle if the Org file is newer than the elisp file
238 (unless (and (file-exists-p exported-file)
239 (> (funcall age file) (funcall age exported-file)))
240 ;; Tangle-file traversal returns reversed list of tangled files
241 ;; and we want to evaluate the first target.
242 (setq exported-file
243 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
244 (message "%s %s"
245 (if compile
246 (progn (byte-compile-file exported-file 'load)
247 "Compiled and loaded")
248 (progn (load-file exported-file) "Loaded"))
249 exported-file)))
251 (defcustom org-babel-load-languages '((emacs-lisp . t))
252 "Languages which can be evaluated in Org buffers.
253 This list can be used to load support for any of the languages
254 below, note that each language will depend on a different set of
255 system executables and/or Emacs modes. When a language is
256 \"loaded\", then code blocks in that language can be evaluated
257 with `org-babel-execute-src-block' bound by default to C-c
258 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
259 be set to remove code block evaluation from the C-c C-c
260 keybinding. By default only Emacs Lisp (which has no
261 requirements) is loaded."
262 :group 'org-babel
263 :set 'org-babel-do-load-languages
264 :version "24.1"
265 :type '(alist :tag "Babel Languages"
266 :key-type
267 (choice
268 (const :tag "Awk" awk)
269 (const :tag "C" C)
270 (const :tag "R" R)
271 (const :tag "Asymptote" asymptote)
272 (const :tag "Calc" calc)
273 (const :tag "Clojure" clojure)
274 (const :tag "CSS" css)
275 (const :tag "Ditaa" ditaa)
276 (const :tag "Dot" dot)
277 (const :tag "Ebnf2ps" ebnf2ps)
278 (const :tag "Emacs Lisp" emacs-lisp)
279 (const :tag "Forth" forth)
280 (const :tag "Fortran" fortran)
281 (const :tag "Gnuplot" gnuplot)
282 (const :tag "Haskell" haskell)
283 (const :tag "hledger" hledger)
284 (const :tag "IO" io)
285 (const :tag "J" J)
286 (const :tag "Java" java)
287 (const :tag "Javascript" js)
288 (const :tag "LaTeX" latex)
289 (const :tag "Ledger" ledger)
290 (const :tag "Lilypond" lilypond)
291 (const :tag "Lisp" lisp)
292 (const :tag "Makefile" makefile)
293 (const :tag "Maxima" maxima)
294 (const :tag "Matlab" matlab)
295 (const :tag "Mscgen" mscgen)
296 (const :tag "Ocaml" ocaml)
297 (const :tag "Octave" octave)
298 (const :tag "Org" org)
299 (const :tag "Perl" perl)
300 (const :tag "Pico Lisp" picolisp)
301 (const :tag "PlantUML" plantuml)
302 (const :tag "Python" python)
303 (const :tag "Ruby" ruby)
304 (const :tag "Sass" sass)
305 (const :tag "Scala" scala)
306 (const :tag "Scheme" scheme)
307 (const :tag "Screen" screen)
308 (const :tag "Shell Script" shell)
309 (const :tag "Shen" shen)
310 (const :tag "Sql" sql)
311 (const :tag "Sqlite" sqlite)
312 (const :tag "Stan" stan)
313 (const :tag "Vala" vala))
314 :value-type (boolean :tag "Activate" :value t)))
316 ;;;; Customization variables
317 (defcustom org-clone-delete-id nil
318 "Remove ID property of clones of a subtree.
319 When non-nil, clones of a subtree don't inherit the ID property.
320 Otherwise they inherit the ID property with a new unique
321 identifier."
322 :type 'boolean
323 :version "24.1"
324 :group 'org-id)
326 ;;; Version
327 (org-check-version)
329 ;;;###autoload
330 (defun org-version (&optional here full message)
331 "Show the Org version.
332 Interactively, or when MESSAGE is non-nil, show it in echo area.
333 With prefix argument, or when HERE is non-nil, insert it at point.
334 In non-interactive uses, a reduced version string is output unless
335 FULL is given."
336 (interactive (list current-prefix-arg t (not current-prefix-arg)))
337 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
338 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
339 (load-suffixes (list ".el"))
340 (org-install-dir
341 (ignore-errors (org-find-library-dir "org-loaddefs"))))
342 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
343 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
344 (let* ((load-suffixes save-load-suffixes)
345 (release (org-release))
346 (git-version (org-git-version))
347 (version (format "Org mode version %s (%s @ %s)"
348 release
349 git-version
350 (if org-install-dir
351 (if (string= org-dir org-install-dir)
352 org-install-dir
353 (concat "mixed installation! "
354 org-install-dir
355 " and "
356 org-dir))
357 "org-loaddefs.el can not be found!")))
358 (version1 (if full version release)))
359 (when here (insert version1))
360 (when message (message "%s" version1))
361 version1)))
363 (defconst org-version (org-version))
366 ;;; Syntax Constants
368 ;;;; Block
370 (defconst org-block-regexp
371 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
372 "Regular expression for hiding blocks.")
374 (defconst org-dblock-start-re
375 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
376 "Matches the start line of a dynamic block, with parameters.")
378 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
379 "Matches the end of a dynamic block.")
381 ;;;; Clock and Planning
383 (defconst org-clock-string "CLOCK:"
384 "String used as prefix for timestamps clocking work hours on an item.")
386 (defvar org-closed-string "CLOSED:"
387 "String used as the prefix for timestamps logging closing a TODO entry.")
389 (defvar org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 \\<org-mode-map>
392 A deadline is this string, followed by a time stamp. It must be
393 a word, terminated by a colon. You can insert a schedule keyword
394 and a timestamp with `\\[org-deadline]'.")
396 (defvar org-scheduled-string "SCHEDULED:"
397 "String to mark scheduled TODO entries.
398 \\<org-mode-map>
399 A schedule is this string, followed by a time stamp. It must be
400 a word, terminated by a colon. You can insert a schedule keyword
401 and a timestamp with `\\[org-schedule]'.")
403 (defconst org-ds-keyword-length
404 (+ 2
405 (apply #'max
406 (mapcar #'length
407 (list org-deadline-string org-scheduled-string
408 org-clock-string org-closed-string))))
409 "Maximum length of the DEADLINE and SCHEDULED keywords.")
411 (defconst org-planning-line-re
412 (concat "^[ \t]*"
413 (regexp-opt
414 (list org-closed-string org-deadline-string org-scheduled-string)
416 "Matches a line with planning info.
417 Matched keyword is in group 1.")
419 (defconst org-clock-line-re
420 (concat "^[ \t]*" org-clock-string)
421 "Matches a line with clock info.")
423 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
424 "Matches the DEADLINE keyword.")
426 (defconst org-deadline-time-regexp
427 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
428 "Matches the DEADLINE keyword together with a time stamp.")
430 (defconst org-deadline-time-hour-regexp
431 (concat "\\<" org-deadline-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
435 (defconst org-deadline-line-regexp
436 (concat "\\<\\(" org-deadline-string "\\).*")
437 "Matches the DEADLINE keyword and the rest of the line.")
439 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
440 "Matches the SCHEDULED keyword.")
442 (defconst org-scheduled-time-regexp
443 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
444 "Matches the SCHEDULED keyword together with a time stamp.")
446 (defconst org-scheduled-time-hour-regexp
447 (concat "\\<" org-scheduled-string
448 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
449 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
451 (defconst org-closed-time-regexp
452 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
453 "Matches the CLOSED keyword together with a time stamp.")
455 (defconst org-keyword-time-regexp
456 (concat "\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 " *[[<]\\([^]>]+\\)[]>]")
462 "Matches any of the 4 keywords, together with the time stamp.")
464 (defconst org-keyword-time-not-clock-regexp
465 (concat
466 "\\<"
467 (regexp-opt
468 (list org-scheduled-string org-deadline-string org-closed-string) t)
469 " *[[<]\\([^]>]+\\)[]>]")
470 "Matches any of the 3 keywords, together with the time stamp.")
472 (defconst org-maybe-keyword-time-regexp
473 (concat "\\(\\<"
474 (regexp-opt
475 (list org-scheduled-string org-deadline-string org-closed-string
476 org-clock-string)
478 "\\)?"
479 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
480 "\\|"
481 "<%%([^\r\n>]*>\\)")
482 "Matches a timestamp, possibly preceded by a keyword.")
484 (defconst org-all-time-keywords
485 (mapcar (lambda (w) (substring w 0 -1))
486 (list org-scheduled-string org-deadline-string
487 org-clock-string org-closed-string))
488 "List of time keywords.")
490 ;;;; Drawer
492 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
493 "Matches first or last line of a hidden block.
494 Group 1 contains drawer's name or \"END\".")
496 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
497 "Regular expression matching the first line of a property drawer.")
499 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
500 "Regular expression matching the last line of a property drawer.")
502 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
503 "Regular expression matching the first line of a clock drawer.")
505 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
506 "Regular expression matching the last line of a clock drawer.")
508 (defconst org-property-drawer-re
509 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
510 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
511 "[ \t]*:END:[ \t]*$")
512 "Matches an entire property drawer.")
514 (defconst org-clock-drawer-re
515 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
516 org-clock-drawer-end-re "\\)\n?")
517 "Matches an entire clock drawer.")
519 ;;;; Headline
521 (defconst org-heading-keyword-regexp-format
522 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
523 "Printf format for a regexp matching a headline with some keyword.
524 This regexp will match the headline of any node which has the
525 exact keyword that is put into the format. The keyword isn't in
526 any group by default, but the stars and the body are.")
528 (defconst org-heading-keyword-maybe-regexp-format
529 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
530 "Printf format for a regexp matching a headline, possibly with some keyword.
531 This regexp can match any headline with the specified keyword, or
532 without a keyword. The keyword isn't in any group by default,
533 but the stars and the body are.")
535 (defconst org-archive-tag "ARCHIVE"
536 "The tag that marks a subtree as archived.
537 An archived subtree does not open during visibility cycling, and does
538 not contribute to the agenda listings.")
540 (eval-and-compile
541 (defconst org-comment-string "COMMENT"
542 "Entries starting with this keyword will never be exported.
543 \\<org-mode-map>
544 An entry can be toggled between COMMENT and normal with
545 `\\[org-toggle-comment]'."))
548 ;;;; LaTeX Environments and Fragments
550 (defconst org-latex-regexps
551 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
552 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
553 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
554 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
555 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
556 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
557 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
558 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
559 "Regular expressions for matching embedded LaTeX.")
561 ;;;; Node Property
563 (defconst org-effort-property "Effort"
564 "The property that is being used to keep track of effort estimates.
565 Effort estimates given in this property need to have the format H:MM.")
567 ;;;; Table
569 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
570 "Detect an org-type or table-type table.")
572 (defconst org-table-line-regexp "^[ \t]*|"
573 "Detect an org-type table line.")
575 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
576 "Detect an org-type table line.")
578 (defconst org-table-hline-regexp "^[ \t]*|-"
579 "Detect an org-type table hline.")
581 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
582 "Detect a table-type table hline.")
584 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
585 "Detect the first line outside a table when searching from within it.
586 This works for both table types.")
588 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
589 "Detect a #+TBLFM line.")
591 ;;;; Timestamp
593 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
594 "Regular expression for fast time stamp matching.")
596 (defconst org-ts-regexp-inactive
597 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
598 "Regular expression for fast inactive time stamp matching.")
600 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
601 "Regular expression for fast time stamp matching.")
603 (defconst org-ts-regexp0
604 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
605 "Regular expression matching time strings for analysis.
606 This one does not require the space after the date, so it can be used
607 on a string that terminates immediately after the date.")
609 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
610 "Regular expression matching time strings for analysis.")
612 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
613 "Regular expression matching time stamps, with groups.")
615 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
616 "Regular expression matching time stamps (also [..]), with groups.")
618 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tr-regexp-both
622 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
623 "Regular expression matching a time stamp range.")
625 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
626 org-ts-regexp "\\)?")
627 "Regular expression matching a time stamp or time stamp range.")
629 (defconst org-tsr-regexp-both
630 (concat org-ts-regexp-both "\\(--?-?"
631 org-ts-regexp-both "\\)?")
632 "Regular expression matching a time stamp or time stamp range.
633 The time stamps may be either active or inactive.")
635 (defconst org-repeat-re
636 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
637 "Regular expression for specifying repeated events.
638 After a match, group 1 contains the repeat expression.")
640 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
641 "Formats for `format-time-string' which are used for time stamps.")
644 ;;; The custom variables
646 (defgroup org nil
647 "Outline-based notes management and organizer."
648 :tag "Org"
649 :group 'outlines
650 :group 'calendar)
652 (defcustom org-mode-hook nil
653 "Mode hook for Org mode, run after the mode was turned on."
654 :group 'org
655 :type 'hook)
657 (defcustom org-load-hook nil
658 "Hook that is run after org.el has been loaded."
659 :group 'org
660 :type 'hook)
662 (defcustom org-log-buffer-setup-hook nil
663 "Hook that is run after an Org log buffer is created."
664 :group 'org
665 :version "24.1"
666 :type 'hook)
668 (defvar org-modules) ; defined below
669 (defvar org-modules-loaded nil
670 "Have the modules been loaded already?")
672 (defun org-load-modules-maybe (&optional force)
673 "Load all extensions listed in `org-modules'."
674 (when (or force (not org-modules-loaded))
675 (dolist (ext org-modules)
676 (condition-case nil (require ext)
677 (error (message "Problems while trying to load feature `%s'" ext))))
678 (setq org-modules-loaded t)))
680 (defun org-set-modules (var value)
681 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
682 (set var value)
683 (when (featurep 'org)
684 (org-load-modules-maybe 'force)
685 (org-element-cache-reset 'all)))
687 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
688 "Modules that should always be loaded together with org.el.
690 If a description starts with <C>, the file is not part of Emacs
691 and loading it will require that you have downloaded and properly
692 installed the Org mode distribution.
694 You can also use this system to load external packages (i.e. neither Org
695 core modules, nor modules from the CONTRIB directory). Just add symbols
696 to the end of the list. If the package is called org-xyz.el, then you need
697 to add the symbol `xyz', and the package must have a call to:
699 (provide \\='org-xyz)
701 For export specific modules, see also `org-export-backends'."
702 :group 'org
703 :set 'org-set-modules
704 :version "24.4"
705 :package-version '(Org . "8.0")
706 :type
707 '(set :greedy t
708 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
709 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
710 (const :tag " crypt: Encryption of subtrees" org-crypt)
711 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
712 (const :tag " docview: Links to doc-view buffers" org-docview)
713 (const :tag " eww: Store link to url of eww" org-eww)
714 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
715 (const :tag " habit: Track your consistency with habits" org-habit)
716 (const :tag " id: Global IDs for identifying entries" org-id)
717 (const :tag " info: Links to Info nodes" org-info)
718 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
719 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
720 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
721 (const :tag " mouse: Additional mouse support" org-mouse)
722 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
723 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
724 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
726 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
727 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
728 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
729 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
730 (const :tag "C collector: Collect properties into tables" org-collector)
731 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
732 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
733 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
734 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
735 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
736 (const :tag "C eval: Include command output as text" org-eval)
737 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
738 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
739 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
740 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
741 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
742 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
743 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
744 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
745 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
746 (const :tag "C man: Support for links to manpages in Org mode" org-man)
747 (const :tag "C mew: Links to Mew folders/messages" org-mew)
748 (const :tag "C mtags: Support for muse-like tags" org-mtags)
749 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
750 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
751 (const :tag "C registry: A registry for Org links" org-registry)
752 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
753 (const :tag "C secretary: Team management with Org" org-secretary)
754 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
755 (const :tag "C toc: Table of contents for Org buffer" org-toc)
756 (const :tag "C track: Keep up with Org mode development" org-track)
757 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
758 (const :tag "C vm: Links to VM folders/messages" org-vm)
759 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
760 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
761 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
763 (defvar org-export-registered-backends) ; From ox.el.
764 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
765 (declare-function org-export-backend-name "ox" (backend) t)
766 (defcustom org-export-backends '(ascii html icalendar latex odt)
767 "List of export back-ends that should be always available.
769 If a description starts with <C>, the file is not part of Emacs
770 and loading it will require that you have downloaded and properly
771 installed the Org mode distribution.
773 Unlike to `org-modules', libraries in this list will not be
774 loaded along with Org, but only once the export framework is
775 needed.
777 This variable needs to be set before org.el is loaded. If you
778 need to make a change while Emacs is running, use the customize
779 interface or run the following code, where VAL stands for the new
780 value of the variable, after updating it:
782 (progn
783 (setq org-export-registered-backends
784 (cl-remove-if-not
785 (lambda (backend)
786 (let ((name (org-export-backend-name backend)))
787 (or (memq name val)
788 (catch \\='parentp
789 (dolist (b val)
790 (and (org-export-derived-backend-p b name)
791 (throw \\='parentp t)))))))
792 org-export-registered-backends))
793 (let ((new-list (mapcar #\\='org-export-backend-name
794 org-export-registered-backends)))
795 (dolist (backend val)
796 (cond
797 ((not (load (format \"ox-%s\" backend) t t))
798 (message \"Problems while trying to load export back-end \\=`%s\\='\"
799 backend))
800 ((not (memq backend new-list)) (push backend new-list))))
801 (set-default \\='org-export-backends new-list)))
803 Adding a back-end to this list will also pull the back-end it
804 depends on, if any."
805 :group 'org
806 :group 'org-export
807 :version "26.1"
808 :package-version '(Org . "9.0")
809 :initialize 'custom-initialize-set
810 :set (lambda (var val)
811 (if (not (featurep 'ox)) (set-default var val)
812 ;; Any back-end not required anymore (not present in VAL and not
813 ;; a parent of any back-end in the new value) is removed from the
814 ;; list of registered back-ends.
815 (setq org-export-registered-backends
816 (cl-remove-if-not
817 (lambda (backend)
818 (let ((name (org-export-backend-name backend)))
819 (or (memq name val)
820 (catch 'parentp
821 (dolist (b val)
822 (and (org-export-derived-backend-p b name)
823 (throw 'parentp t)))))))
824 org-export-registered-backends))
825 ;; Now build NEW-LIST of both new back-ends and required
826 ;; parents.
827 (let ((new-list (mapcar #'org-export-backend-name
828 org-export-registered-backends)))
829 (dolist (backend val)
830 (cond
831 ((not (load (format "ox-%s" backend) t t))
832 (message "Problems while trying to load export back-end `%s'"
833 backend))
834 ((not (memq backend new-list)) (push backend new-list))))
835 ;; Set VAR to that list with fixed dependencies.
836 (set-default var new-list))))
837 :type '(set :greedy t
838 (const :tag " ascii Export buffer to ASCII format" ascii)
839 (const :tag " beamer Export buffer to Beamer presentation" beamer)
840 (const :tag " html Export buffer to HTML format" html)
841 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
842 (const :tag " latex Export buffer to LaTeX format" latex)
843 (const :tag " man Export buffer to MAN format" man)
844 (const :tag " md Export buffer to Markdown format" md)
845 (const :tag " odt Export buffer to ODT format" odt)
846 (const :tag " org Export buffer to Org format" org)
847 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
848 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
849 (const :tag "C deck Export buffer to deck.js presentations" deck)
850 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
851 (const :tag "C groff Export buffer to Groff format" groff)
852 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
853 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
854 (const :tag "C s5 Export buffer to s5 presentations" s5)
855 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
857 (eval-after-load 'ox
858 '(dolist (backend org-export-backends)
859 (condition-case nil (require (intern (format "ox-%s" backend)))
860 (error (message "Problems while trying to load export back-end `%s'"
861 backend)))))
863 (defcustom org-support-shift-select nil
864 "Non-nil means make shift-cursor commands select text when possible.
865 \\<org-mode-map>\
867 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
868 start selecting a region, or enlarge regions started in this way.
869 In Org mode, in special contexts, these same keys are used for
870 other purposes, important enough to compete with shift selection.
871 Org tries to balance these needs by supporting `shift-select-mode'
872 outside these special contexts, under control of this variable.
874 The default of this variable is nil, to avoid confusing behavior. Shifted
875 cursor keys will then execute Org commands in the following contexts:
876 - on a headline, changing TODO state (left/right) and priority (up/down)
877 - on a time stamp, changing the time
878 - in a plain list item, changing the bullet type
879 - in a property definition line, switching between allowed values
880 - in the BEGIN line of a clock table (changing the time block).
881 Outside these contexts, the commands will throw an error.
883 When this variable is t and the cursor is not in a special
884 context, Org mode will support shift-selection for making and
885 enlarging regions. To make this more effective, the bullet
886 cycling will no longer happen anywhere in an item line, but only
887 if the cursor is exactly on the bullet.
889 If you set this variable to the symbol `always', then the keys
890 will not be special in headlines, property lines, and item lines,
891 to make shift selection work there as well. If this is what you
892 want, you can use the following alternative commands:
893 `\\[org-todo]' and `\\[org-priority]' \
894 to change TODO state and priority,
895 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
896 can be used to switch TODO sets,
897 `\\[org-ctrl-c-minus]' to cycle item bullet types,
898 and properties can be edited by hand or in column view.
900 However, when the cursor is on a timestamp, shift-cursor commands
901 will still edit the time stamp - this is just too good to give up."
902 :group 'org
903 :type '(choice
904 (const :tag "Never" nil)
905 (const :tag "When outside special context" t)
906 (const :tag "Everywhere except timestamps" always)))
908 (defcustom org-loop-over-headlines-in-active-region nil
909 "Shall some commands act upon headlines in the active region?
911 When set to t, some commands will be performed in all headlines
912 within the active region.
914 When set to `start-level', some commands will be performed in all
915 headlines within the active region, provided that these headlines
916 are of the same level than the first one.
918 When set to a string, those commands will be performed on the
919 matching headlines within the active region. Such string must be
920 a tags/property/todo match as it is used in the agenda tags view.
922 The list of commands is: `org-schedule', `org-deadline',
923 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
924 `org-archive-to-archive-sibling'. The archiving commands skip
925 already archived entries."
926 :type '(choice (const :tag "Don't loop" nil)
927 (const :tag "All headlines in active region" t)
928 (const :tag "In active region, headlines at the same level than the first one" start-level)
929 (string :tag "Tags/Property/Todo matcher"))
930 :version "24.1"
931 :group 'org-todo
932 :group 'org-archive)
934 (defgroup org-startup nil
935 "Options concerning startup of Org mode."
936 :tag "Org Startup"
937 :group 'org)
939 (defcustom org-startup-folded t
940 "Non-nil means entering Org mode will switch to OVERVIEW.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
945 #+STARTUP: fold (or `overview', this is equivalent)
946 #+STARTUP: nofold (or `showall', this is equivalent)
947 #+STARTUP: content
948 #+STARTUP: showeverything
950 Set `org-agenda-inhibit-startup' to a non-nil value if you want
951 to ignore this option when Org opens agenda files for the first
952 time."
953 :group 'org-startup
954 :type '(choice
955 (const :tag "nofold: show all" nil)
956 (const :tag "fold: overview" t)
957 (const :tag "content: all headlines" content)
958 (const :tag "show everything, even drawers" showeverything)))
960 (defcustom org-startup-truncated t
961 "Non-nil means entering Org mode will set `truncate-lines'.
962 This is useful since some lines containing links can be very long and
963 uninteresting. Also tables look terrible when wrapped.
965 The variable `org-startup-truncated' allows to configure
966 truncation for Org mode different to the other modes that use the
967 variable `truncate-lines' and as a shortcut instead of putting
968 the variable `truncate-lines' into the `org-mode-hook'. If one
969 wants to configure truncation for Org mode not statically but
970 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
971 the variable `truncate-lines' has to be used because in such a
972 case it is too late to set the variable `org-startup-truncated'."
973 :group 'org-startup
974 :type 'boolean)
976 (defcustom org-startup-indented nil
977 "Non-nil means turn on `org-indent-mode' on startup.
978 This can also be configured on a per-file basis by adding one of
979 the following lines anywhere in the buffer:
981 #+STARTUP: indent
982 #+STARTUP: noindent"
983 :group 'org-structure
984 :type '(choice
985 (const :tag "Not" nil)
986 (const :tag "Globally (slow on startup in large files)" t)))
988 (defcustom org-use-sub-superscripts t
989 "Non-nil means interpret \"_\" and \"^\" for display.
991 If you want to control how Org exports those characters, see
992 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
993 used to be an alias for `org-export-with-sub-superscripts' in
994 Org <8.0, it is not anymore.
996 When this option is turned on, you can use TeX-like syntax for
997 sub- and superscripts within the buffer. Several characters after
998 \"_\" or \"^\" will be considered as a single item - so grouping
999 with {} is normally not needed. For example, the following things
1000 will be parsed as single sub- or superscripts:
1002 10^24 or 10^tau several digits will be considered 1 item.
1003 10^-12 or 10^-tau a leading sign with digits or a word
1004 x^2-y^3 will be read as x^2 - y^3, because items are
1005 terminated by almost any nonword/nondigit char.
1006 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1008 Still, ambiguity is possible. So when in doubt, use {} to enclose
1009 the sub/superscript. If you set this variable to the symbol `{}',
1010 the braces are *required* in order to trigger interpretations as
1011 sub/superscript. This can be helpful in documents that need \"_\"
1012 frequently in plain text."
1013 :group 'org-startup
1014 :version "24.4"
1015 :package-version '(Org . "8.0")
1016 :type '(choice
1017 (const :tag "Always interpret" t)
1018 (const :tag "Only with braces" {})
1019 (const :tag "Never interpret" nil)))
1021 (defcustom org-startup-with-beamer-mode nil
1022 "Non-nil means turn on `org-beamer-mode' on startup.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1026 #+STARTUP: beamer"
1027 :group 'org-startup
1028 :version "24.1"
1029 :type 'boolean)
1031 (defcustom org-startup-align-all-tables nil
1032 "Non-nil means align all tables when visiting a file.
1033 This is useful when the column width in tables is forced with <N> cookies
1034 in table fields. Such tables will look correct only after the first re-align.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: align
1038 #+STARTUP: noalign"
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-startup-with-inline-images nil
1043 "Non-nil means show inline images when loading a new Org file.
1044 This can also be configured on a per-file basis by adding one of
1045 the following lines anywhere in the buffer:
1046 #+STARTUP: inlineimages
1047 #+STARTUP: noinlineimages"
1048 :group 'org-startup
1049 :version "24.1"
1050 :type 'boolean)
1052 (defcustom org-startup-with-latex-preview nil
1053 "Non-nil means preview LaTeX fragments when loading a new Org file.
1055 This can also be configured on a per-file basis by adding one of
1056 the following lines anywhere in the buffer:
1057 #+STARTUP: latexpreview
1058 #+STARTUP: nolatexpreview"
1059 :group 'org-startup
1060 :version "24.4"
1061 :package-version '(Org . "8.0")
1062 :type 'boolean)
1064 (defcustom org-insert-mode-line-in-empty-file nil
1065 "Non-nil means insert the first line setting Org mode in empty files.
1066 When the function `org-mode' is called interactively in an empty file, this
1067 normally means that the file name does not automatically trigger Org mode.
1068 To ensure that the file will always be in Org mode in the future, a
1069 line enforcing Org mode will be inserted into the buffer, if this option
1070 has been set."
1071 :group 'org-startup
1072 :type 'boolean)
1074 (defcustom org-replace-disputed-keys nil
1075 "Non-nil means use alternative key bindings for some keys.
1076 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1077 These keys are also used by other packages like shift-selection-mode'
1078 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1079 If you want to use Org mode together with one of these other modes,
1080 or more generally if you would like to move some Org mode commands to
1081 other keys, set this variable and configure the keys with the variable
1082 `org-disputed-keys'.
1084 This option is only relevant at load-time of Org mode, and must be set
1085 *before* org.el is loaded. Changing it requires a restart of Emacs to
1086 become effective."
1087 :group 'org-startup
1088 :type 'boolean)
1090 (defcustom org-use-extra-keys nil
1091 "Non-nil means use extra key sequence definitions for certain commands.
1092 This happens automatically if `window-system' is nil. This
1093 variable lets you do the same manually. You must set it before
1094 loading Org."
1095 :group 'org-startup
1096 :type 'boolean)
1098 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1100 (defcustom org-disputed-keys
1101 '(([(shift up)] . [(meta p)])
1102 ([(shift down)] . [(meta n)])
1103 ([(shift left)] . [(meta -)])
1104 ([(shift right)] . [(meta +)])
1105 ([(control shift right)] . [(meta shift +)])
1106 ([(control shift left)] . [(meta shift -)]))
1107 "Keys for which Org mode and other modes compete.
1108 This is an alist, cars are the default keys, second element specifies
1109 the alternative to use when `org-replace-disputed-keys' is t.
1111 Keys can be specified in any syntax supported by `define-key'.
1112 The value of this option takes effect only at Org mode startup,
1113 therefore you'll have to restart Emacs to apply it after changing."
1114 :group 'org-startup
1115 :type 'alist)
1117 (defun org-key (key)
1118 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1119 Or return the original if not disputed."
1120 (when org-replace-disputed-keys
1121 (let* ((nkey (key-description key))
1122 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1123 org-disputed-keys)))
1124 (setq key (if x (cdr x) key))))
1125 key)
1127 (defun org-defkey (keymap key def)
1128 "Define a key, possibly translated, as returned by `org-key'."
1129 (define-key keymap (org-key key) def))
1131 (defcustom org-ellipsis nil
1132 "The ellipsis to use in the Org mode outline.
1134 When nil, just use the standard three dots. When a non-empty string,
1135 use that string instead.
1137 The change affects only Org mode (which will then use its own display table).
1138 Changing this requires executing `\\[org-mode]' in a buffer to become
1139 effective."
1140 :group 'org-startup
1141 :type '(choice (const :tag "Default" nil)
1142 (string :tag "String" :value "...#"))
1143 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1145 (defvar org-display-table nil
1146 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1148 (defgroup org-keywords nil
1149 "Keywords in Org mode."
1150 :tag "Org Keywords"
1151 :group 'org)
1153 (defcustom org-closed-keep-when-no-todo nil
1154 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1155 :group 'org-todo
1156 :group 'org-keywords
1157 :version "24.4"
1158 :package-version '(Org . "8.0")
1159 :type 'boolean)
1161 (defgroup org-structure nil
1162 "Options concerning the general structure of Org files."
1163 :tag "Org Structure"
1164 :group 'org)
1166 (defgroup org-reveal-location nil
1167 "Options about how to make context of a location visible."
1168 :tag "Org Reveal Location"
1169 :group 'org-structure)
1171 (defcustom org-show-context-detail '((agenda . local)
1172 (bookmark-jump . lineage)
1173 (isearch . lineage)
1174 (default . ancestors))
1175 "Alist between context and visibility span when revealing a location.
1177 \\<org-mode-map>Some actions may move point into invisible
1178 locations. As a consequence, Org always expose a neighborhood
1179 around point. How much is shown depends on the initial action,
1180 or context. Valid contexts are
1182 agenda when exposing an entry from the agenda
1183 org-goto when using the command `org-goto' (`\\[org-goto]')
1184 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1185 tags-tree when constructing a sparse tree based on tags matches
1186 link-search when exposing search matches associated with a link
1187 mark-goto when exposing the jump goal of a mark
1188 bookmark-jump when exposing a bookmark location
1189 isearch when exiting from an incremental search
1190 default default for all contexts not set explicitly
1192 Allowed visibility spans are
1194 minimal show current headline; if point is not on headline,
1195 also show entry
1197 local show current headline, entry and next headline
1199 ancestors show current headline and its direct ancestors; if
1200 point is not on headline, also show entry
1202 lineage show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and first child
1206 tree show current headline, its direct ancestors and all
1207 their children; if point is not on headline, also show
1208 entry and all children
1210 canonical show current headline, its direct ancestors along with
1211 their entries and children; if point is not located on
1212 the headline, also show current entry and all children
1214 As special cases, a nil or t value means show all contexts in
1215 `minimal' or `canonical' view, respectively.
1217 Some views can make displayed information very compact, but also
1218 make it harder to edit the location of the match. In such
1219 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1220 more context."
1221 :group 'org-reveal-location
1222 :version "26.1"
1223 :package-version '(Org . "9.0")
1224 :type '(choice
1225 (const :tag "Canonical" t)
1226 (const :tag "Minimal" nil)
1227 (repeat :greedy t :tag "Individual contexts"
1228 (cons
1229 (choice :tag "Context"
1230 (const agenda)
1231 (const org-goto)
1232 (const occur-tree)
1233 (const tags-tree)
1234 (const link-search)
1235 (const mark-goto)
1236 (const bookmark-jump)
1237 (const isearch)
1238 (const default))
1239 (choice :tag "Detail level"
1240 (const minimal)
1241 (const local)
1242 (const ancestors)
1243 (const lineage)
1244 (const tree)
1245 (const canonical))))))
1247 (defcustom org-indirect-buffer-display 'other-window
1248 "How should indirect tree buffers be displayed?
1250 This applies to indirect buffers created with the commands
1251 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1253 Valid values are:
1254 current-window Display in the current window
1255 other-window Just display in another window.
1256 dedicated-frame Create one new frame, and re-use it each time.
1257 new-frame Make a new frame each time. Note that in this case
1258 previously-made indirect buffers are kept, and you need to
1259 kill these buffers yourself."
1260 :group 'org-structure
1261 :group 'org-agenda-windows
1262 :type '(choice
1263 (const :tag "In current window" current-window)
1264 (const :tag "In current frame, other window" other-window)
1265 (const :tag "Each time a new frame" new-frame)
1266 (const :tag "One dedicated frame" dedicated-frame)))
1268 (defcustom org-use-speed-commands nil
1269 "Non-nil means activate single letter commands at beginning of a headline.
1270 This may also be a function to test for appropriate locations where speed
1271 commands should be active.
1273 For example, to activate speed commands when the point is on any
1274 star at the beginning of the headline, you can do this:
1276 (setq org-use-speed-commands
1277 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1278 :group 'org-structure
1279 :type '(choice
1280 (const :tag "Never" nil)
1281 (const :tag "At beginning of headline stars" t)
1282 (function)))
1284 (defcustom org-speed-commands-user nil
1285 "Alist of additional speed commands.
1286 This list will be checked before `org-speed-commands-default'
1287 when the variable `org-use-speed-commands' is non-nil
1288 and when the cursor is at the beginning of a headline.
1289 The car of each entry is a string with a single letter, which must
1290 be assigned to `self-insert-command' in the global map.
1291 The cdr is either a command to be called interactively, a function
1292 to be called, or a form to be evaluated.
1293 An entry that is just a list with a single string will be interpreted
1294 as a descriptive headline that will be added when listing the speed
1295 commands in the Help buffer using the `?' speed command."
1296 :group 'org-structure
1297 :type '(repeat :value ("k" . ignore)
1298 (choice :value ("k" . ignore)
1299 (list :tag "Descriptive Headline" (string :tag "Headline"))
1300 (cons :tag "Letter and Command"
1301 (string :tag "Command letter")
1302 (choice
1303 (function)
1304 (sexp))))))
1306 (defcustom org-bookmark-names-plist
1307 '(:last-capture "org-capture-last-stored"
1308 :last-refile "org-refile-last-stored"
1309 :last-capture-marker "org-capture-last-stored-marker")
1310 "Names for bookmarks automatically set by some Org commands.
1311 This can provide strings as names for a number of bookmarks Org sets
1312 automatically. The following keys are currently implemented:
1313 :last-capture
1314 :last-capture-marker
1315 :last-refile
1316 When a key does not show up in the property list, the corresponding bookmark
1317 is not set."
1318 :group 'org-structure
1319 :type 'plist)
1321 (defgroup org-cycle nil
1322 "Options concerning visibility cycling in Org mode."
1323 :tag "Org Cycle"
1324 :group 'org-structure)
1326 (defcustom org-cycle-skip-children-state-if-no-children t
1327 "Non-nil means skip CHILDREN state in entries that don't have any."
1328 :group 'org-cycle
1329 :type 'boolean)
1331 (defcustom org-cycle-max-level nil
1332 "Maximum level which should still be subject to visibility cycling.
1333 Levels higher than this will, for cycling, be treated as text, not a headline.
1334 When `org-odd-levels-only' is set, a value of N in this variable actually
1335 means 2N-1 stars as the limiting headline.
1336 When nil, cycle all levels.
1337 Note that the limiting level of cycling is also influenced by
1338 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1339 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1340 than its value."
1341 :group 'org-cycle
1342 :type '(choice
1343 (const :tag "No limit" nil)
1344 (integer :tag "Maximum level")))
1346 (defcustom org-hide-block-startup nil
1347 "Non-nil means entering Org mode will fold all blocks.
1348 This can also be set in on a per-file basis with
1350 #+STARTUP: hideblocks
1351 #+STARTUP: showblocks"
1352 :group 'org-startup
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-global-at-bob nil
1357 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1359 This makes it possible to do global cycling without having to use `S-TAB'
1360 or `\\[universal-argument] TAB'. For this special case to work, the first \
1361 line of the buffer
1362 must not be a headline -- it may be empty or some other text.
1364 When used in this way, `org-cycle-hook' is disabled temporarily to make
1365 sure the cursor stays at the beginning of the buffer.
1367 When this option is nil, don't do anything special at the beginning of
1368 the buffer."
1369 :group 'org-cycle
1370 :type 'boolean)
1372 (defcustom org-cycle-level-after-item/entry-creation t
1373 "Non-nil means cycle entry level or item indentation in new empty entries.
1375 When the cursor is at the end of an empty headline, i.e., with only stars
1376 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1377 and then all possible ancestor states, before returning to the original state.
1378 This makes data entry extremely fast: M-RET to create a new headline,
1379 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1381 When the cursor is at the end of an empty plain list item, one TAB will
1382 make it a subitem, two or more tabs will back up to make this an item
1383 higher up in the item hierarchy."
1384 :group 'org-cycle
1385 :type 'boolean)
1387 (defcustom org-cycle-emulate-tab t
1388 "Where should `org-cycle' emulate TAB.
1389 nil Never
1390 white Only in completely white lines
1391 whitestart Only at the beginning of lines, before the first non-white char
1392 t Everywhere except in headlines
1393 exc-hl-bol Everywhere except at the start of a headline
1394 If TAB is used in a place where it does not emulate TAB, the current subtree
1395 visibility is cycled."
1396 :group 'org-cycle
1397 :type '(choice (const :tag "Never" nil)
1398 (const :tag "Only in completely white lines" white)
1399 (const :tag "Before first char in a line" whitestart)
1400 (const :tag "Everywhere except in headlines" t)
1401 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1403 (defcustom org-cycle-separator-lines 2
1404 "Number of empty lines needed to keep an empty line between collapsed trees.
1405 If you leave an empty line between the end of a subtree and the following
1406 headline, this empty line is hidden when the subtree is folded.
1407 Org mode will leave (exactly) one empty line visible if the number of
1408 empty lines is equal or larger to the number given in this variable.
1409 So the default 2 means at least 2 empty lines after the end of a subtree
1410 are needed to produce free space between a collapsed subtree and the
1411 following headline.
1413 If the number is negative, and the number of empty lines is at least -N,
1414 all empty lines are shown.
1416 Special case: when 0, never leave empty lines in collapsed view."
1417 :group 'org-cycle
1418 :type 'integer)
1419 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1421 (defcustom org-pre-cycle-hook nil
1422 "Hook that is run before visibility cycling is happening.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that will be set right after running this hook. The
1425 argument is a symbol. Before a global state change, it can have the values
1426 `overview', `content', or `all'. Before a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook)
1431 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1432 org-cycle-hide-drawers
1433 org-cycle-show-empty-lines
1434 org-optimize-window-after-visibility-change)
1435 "Hook that is run after `org-cycle' has changed the buffer visibility.
1436 The function(s) in this hook must accept a single argument which indicates
1437 the new state that was set by the most recent `org-cycle' command. The
1438 argument is a symbol. After a global state change, it can have the values
1439 `overview', `contents', or `all'. After a local state change, it can have
1440 the values `folded', `children', or `subtree'."
1441 :group 'org-cycle
1442 :type 'hook
1443 :version "26.1"
1444 :package-version '(Org . "8.3"))
1446 (defgroup org-edit-structure nil
1447 "Options concerning structure editing in Org mode."
1448 :tag "Org Edit Structure"
1449 :group 'org-structure)
1451 (defcustom org-odd-levels-only nil
1452 "Non-nil means skip even levels and only use odd levels for the outline.
1453 This has the effect that two stars are being added/taken away in
1454 promotion/demotion commands. It also influences how levels are
1455 handled by the exporters.
1456 Changing it requires restart of `font-lock-mode' to become effective
1457 for fontification also in regions already fontified.
1458 You may also set this on a per-file basis by adding one of the following
1459 lines to the buffer:
1461 #+STARTUP: odd
1462 #+STARTUP: oddeven"
1463 :group 'org-edit-structure
1464 :group 'org-appearance
1465 :type 'boolean)
1467 (defcustom org-adapt-indentation t
1468 "Non-nil means adapt indentation to outline node level.
1470 When this variable is set, Org assumes that you write outlines by
1471 indenting text in each node to align with the headline (after the
1472 stars). The following issues are influenced by this variable:
1474 - The indentation is increased by one space in a demotion
1475 command, and decreased by one in a promotion command. However,
1476 in the latter case, if shifting some line in the entry body
1477 would alter document structure (e.g., insert a new headline),
1478 indentation is not changed at all.
1480 - Property drawers and planning information is inserted indented
1481 when this variable is set. When nil, they will not be indented.
1483 - TAB indents a line relative to current level. The lines below
1484 a headline will be indented when this variable is set.
1486 Note that this is all about true indentation, by adding and
1487 removing space characters. See also `org-indent.el' which does
1488 level-dependent indentation in a virtual way, i.e. at display
1489 time in Emacs."
1490 :group 'org-edit-structure
1491 :type 'boolean)
1493 (defcustom org-special-ctrl-a/e nil
1494 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1496 When t, `C-a' will bring back the cursor to the beginning of the
1497 headline text, i.e. after the stars and after a possible TODO
1498 keyword. In an item, this will be the position after bullet and
1499 check-box, if any. When the cursor is already at that position,
1500 another `C-a' will bring it to the beginning of the line.
1502 `C-e' will jump to the end of the headline, ignoring the presence
1503 of tags in the headline. A second `C-e' will then jump to the
1504 true end of the line, after any tags. This also means that, when
1505 this variable is non-nil, `C-e' also will never jump beyond the
1506 end of the heading of a folded section, i.e. not after the
1507 ellipses.
1509 When set to the symbol `reversed', the first `C-a' or `C-e' works
1510 normally, going to the true line boundary first. Only a directly
1511 following, identical keypress will bring the cursor to the
1512 special positions.
1514 This may also be a cons cell where the behavior for `C-a' and
1515 `C-e' is set separately."
1516 :group 'org-edit-structure
1517 :type '(choice
1518 (const :tag "off" nil)
1519 (const :tag "on: after stars/bullet and before tags first" t)
1520 (const :tag "reversed: true line boundary first" reversed)
1521 (cons :tag "Set C-a and C-e separately"
1522 (choice :tag "Special C-a"
1523 (const :tag "off" nil)
1524 (const :tag "on: after stars/bullet first" t)
1525 (const :tag "reversed: before stars/bullet first" reversed))
1526 (choice :tag "Special C-e"
1527 (const :tag "off" nil)
1528 (const :tag "on: before tags first" t)
1529 (const :tag "reversed: after tags first" reversed)))))
1530 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1532 (defcustom org-special-ctrl-k nil
1533 "Non-nil means `C-k' will behave specially in headlines.
1534 When nil, `C-k' will call the default `kill-line' command.
1535 When t, the following will happen while the cursor is in the headline:
1537 - When the cursor is at the beginning of a headline, kill the entire
1538 line and possible the folded subtree below the line.
1539 - When in the middle of the headline text, kill the headline up to the tags.
1540 - When after the headline text, kill the tags."
1541 :group 'org-edit-structure
1542 :type 'boolean)
1544 (defcustom org-ctrl-k-protect-subtree nil
1545 "Non-nil means, do not delete a hidden subtree with C-k.
1546 When set to the symbol `error', simply throw an error when C-k is
1547 used to kill (part-of) a headline that has hidden text behind it.
1548 Any other non-nil value will result in a query to the user, if it is
1549 OK to kill that hidden subtree. When nil, kill without remorse."
1550 :group 'org-edit-structure
1551 :version "24.1"
1552 :type '(choice
1553 (const :tag "Do not protect hidden subtrees" nil)
1554 (const :tag "Protect hidden subtrees with a security query" t)
1555 (const :tag "Never kill a hidden subtree with C-k" error)))
1557 (defcustom org-special-ctrl-o t
1558 "Non-nil means, make `C-o' insert a row in tables."
1559 :group 'org-edit-structure
1560 :type 'boolean)
1562 (defcustom org-catch-invisible-edits nil
1563 "Check if in invisible region before inserting or deleting a character.
1564 Valid values are:
1566 nil Do not check, so just do invisible edits.
1567 error Throw an error and do nothing.
1568 show Make point visible, and do the requested edit.
1569 show-and-error Make point visible, then throw an error and abort the edit.
1570 smart Make point visible, and do insertion/deletion if it is
1571 adjacent to visible text and the change feels predictable.
1572 Never delete a previously invisible character or add in the
1573 middle or right after an invisible region. Basically, this
1574 allows insertion and backward-delete right before ellipses.
1575 FIXME: maybe in this case we should not even show?"
1576 :group 'org-edit-structure
1577 :version "24.1"
1578 :type '(choice
1579 (const :tag "Do not check" nil)
1580 (const :tag "Throw error when trying to edit" error)
1581 (const :tag "Unhide, but do not do the edit" show-and-error)
1582 (const :tag "Show invisible part and do the edit" show)
1583 (const :tag "Be smart and do the right thing" smart)))
1585 (defcustom org-yank-folded-subtrees t
1586 "Non-nil means when yanking subtrees, fold them.
1587 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1588 it starts with a heading and all other headings in it are either children
1589 or siblings, then fold all the subtrees. However, do this only if no
1590 text after the yank would be swallowed into a folded tree by this action."
1591 :group 'org-edit-structure
1592 :type 'boolean)
1594 (defcustom org-yank-adjusted-subtrees nil
1595 "Non-nil means when yanking subtrees, adjust the level.
1596 With this setting, `org-paste-subtree' is used to insert the subtree, see
1597 this function for details."
1598 :group 'org-edit-structure
1599 :type 'boolean)
1601 (defcustom org-M-RET-may-split-line '((default . t))
1602 "Non-nil means M-RET will split the line at the cursor position.
1603 When nil, it will go to the end of the line before making a
1604 new line.
1605 You may also set this option in a different way for different
1606 contexts. Valid contexts are:
1608 headline when creating a new headline
1609 item when creating a new item
1610 table in a table field
1611 default the value to be used for all contexts not explicitly
1612 customized"
1613 :group 'org-structure
1614 :group 'org-table
1615 :type '(choice
1616 (const :tag "Always" t)
1617 (const :tag "Never" nil)
1618 (repeat :greedy t :tag "Individual contexts"
1619 (cons
1620 (choice :tag "Context"
1621 (const headline)
1622 (const item)
1623 (const table)
1624 (const default))
1625 (boolean)))))
1628 (defcustom org-insert-heading-respect-content nil
1629 "Non-nil means insert new headings after the current subtree.
1630 \\<org-mode-map>
1631 When nil, the new heading is created directly after the current line.
1632 The commands `\\[org-insert-heading-respect-content]' and \
1633 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1634 for the duration of the command."
1635 :group 'org-structure
1636 :type 'boolean)
1638 (defcustom org-blank-before-new-entry '((heading . auto)
1639 (plain-list-item . auto))
1640 "Should `org-insert-heading' leave a blank line before new heading/item?
1641 The value is an alist, with `heading' and `plain-list-item' as CAR,
1642 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1643 which case Org will look at the surrounding headings/items and try to
1644 make an intelligent decision whether to insert a blank line or not."
1645 :group 'org-edit-structure
1646 :type '(list
1647 (cons (const heading)
1648 (choice (const :tag "Never" nil)
1649 (const :tag "Always" t)
1650 (const :tag "Auto" auto)))
1651 (cons (const plain-list-item)
1652 (choice (const :tag "Never" nil)
1653 (const :tag "Always" t)
1654 (const :tag "Auto" auto)))))
1656 (defcustom org-insert-heading-hook nil
1657 "Hook being run after inserting a new heading."
1658 :group 'org-edit-structure
1659 :type 'hook)
1661 (defcustom org-enable-fixed-width-editor t
1662 "Non-nil means lines starting with \":\" are treated as fixed-width.
1663 This currently only means they are never auto-wrapped.
1664 When nil, such lines will be treated like ordinary lines."
1665 :group 'org-edit-structure
1666 :type 'boolean)
1668 (defcustom org-goto-auto-isearch t
1669 "Non-nil means typing characters in `org-goto' starts incremental search.
1670 When nil, you can use these keybindings to navigate the buffer:
1672 q Quit the org-goto interface
1673 n Go to the next visible heading
1674 p Go to the previous visible heading
1675 f Go one heading forward on same level
1676 b Go one heading backward on same level
1677 u Go one heading up"
1678 :group 'org-edit-structure
1679 :type 'boolean)
1681 (defgroup org-sparse-trees nil
1682 "Options concerning sparse trees in Org mode."
1683 :tag "Org Sparse Trees"
1684 :group 'org-structure)
1686 (defcustom org-highlight-sparse-tree-matches t
1687 "Non-nil means highlight all matches that define a sparse tree.
1688 The highlights will automatically disappear the next time the buffer is
1689 changed by an edit command."
1690 :group 'org-sparse-trees
1691 :type 'boolean)
1693 (defcustom org-remove-highlights-with-change t
1694 "Non-nil means any change to the buffer will remove temporary highlights.
1695 \\<org-mode-map>\
1696 Such highlights are created by `org-occur' and `org-clock-display'.
1697 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1698 to get rid of the highlights.
1699 The highlights created by `org-toggle-latex-fragment' always need
1700 `\\[org-toggle-latex-fragment]' to be removed."
1701 :group 'org-sparse-trees
1702 :group 'org-time
1703 :type 'boolean)
1705 (defcustom org-occur-case-fold-search t
1706 "Non-nil means `org-occur' should be case-insensitive.
1707 If set to `smart' the search will be case-insensitive only if it
1708 doesn't specify any upper case character."
1709 :group 'org-sparse-trees
1710 :version "26.1"
1711 :type '(choice
1712 (const :tag "Case-sensitive" nil)
1713 (const :tag "Case-insensitive" t)
1714 (const :tag "Case-insensitive for lower case searches only" smart)))
1716 (defcustom org-occur-hook '(org-first-headline-recenter)
1717 "Hook that is run after `org-occur' has constructed a sparse tree.
1718 This can be used to recenter the window to show as much of the structure
1719 as possible."
1720 :group 'org-sparse-trees
1721 :type 'hook)
1723 (defgroup org-imenu-and-speedbar nil
1724 "Options concerning imenu and speedbar in Org mode."
1725 :tag "Org Imenu and Speedbar"
1726 :group 'org-structure)
1728 (defcustom org-imenu-depth 2
1729 "The maximum level for Imenu access to Org headlines.
1730 This also applied for speedbar access."
1731 :group 'org-imenu-and-speedbar
1732 :type 'integer)
1734 (defgroup org-table nil
1735 "Options concerning tables in Org mode."
1736 :tag "Org Table"
1737 :group 'org)
1739 (defcustom org-self-insert-cluster-for-undo nil
1740 "Non-nil means cluster self-insert commands for undo when possible.
1741 If this is set, then, like in the Emacs command loop, 20 consecutive
1742 characters will be undone together.
1743 This is configurable, because there is some impact on typing performance."
1744 :group 'org-table
1745 :type 'boolean)
1747 (defcustom org-table-tab-recognizes-table.el t
1748 "Non-nil means TAB will automatically notice a table.el table.
1749 When it sees such a table, it moves point into it and - if necessary -
1750 calls `table-recognize-table'."
1751 :group 'org-table-editing
1752 :type 'boolean)
1754 (defgroup org-link nil
1755 "Options concerning links in Org mode."
1756 :tag "Org Link"
1757 :group 'org)
1759 (defvar-local org-link-abbrev-alist-local nil
1760 "Buffer-local version of `org-link-abbrev-alist', which see.
1761 The value of this is taken from the #+LINK lines.")
1763 (defcustom org-link-parameters
1764 '(("doi" :follow org--open-doi-link)
1765 ("elisp" :follow org--open-elisp-link)
1766 ("file" :complete org-file-complete-link)
1767 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1768 ("help" :follow org--open-help-link)
1769 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1770 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1771 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1772 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1773 ("shell" :follow org--open-shell-link))
1774 "An alist of properties that defines all the links in Org mode.
1775 The key in each association is a string of the link type.
1776 Subsequent optional elements make up a p-list of link properties.
1778 :follow - A function that takes the link path as an argument.
1780 :export - A function that takes the link path, description and
1781 export-backend as arguments.
1783 :store - A function responsible for storing the link. See the
1784 function `org-store-link-functions'.
1786 :complete - A function that inserts a link with completion. The
1787 function takes one optional prefix arg.
1789 :face - A face for the link, or a function that returns a face.
1790 The function takes one argument which is the link path. The
1791 default face is `org-link'.
1793 :mouse-face - The mouse-face. The default is `highlight'.
1795 :display - `full' will not fold the link in descriptive
1796 display. Default is `org-link'.
1798 :help-echo - A string or function that takes (window object position)
1799 as arguments and returns a string.
1801 :keymap - A keymap that is active on the link. The default is
1802 `org-mouse-map'.
1804 :htmlize-link - A function for the htmlize-link. Defaults
1805 to (list :uri \"type:path\")
1807 :activate-func - A function to run at the end of font-lock
1808 activation. The function must accept (link-start link-end path bracketp)
1809 as arguments."
1810 :group 'org-link
1811 :type '(alist :tag "Link display parameters"
1812 :value-type plist)
1813 :version "26.1"
1814 :package-version '(Org . "9.1"))
1816 (defun org-link-get-parameter (type key)
1817 "Get TYPE link property for KEY.
1818 TYPE is a string and KEY is a plist keyword."
1819 (plist-get
1820 (cdr (assoc type org-link-parameters))
1821 key))
1823 (defun org-link-set-parameters (type &rest parameters)
1824 "Set link TYPE properties to PARAMETERS.
1825 PARAMETERS should be :key val pairs."
1826 (let ((data (assoc type org-link-parameters)))
1827 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1828 (push (cons type parameters) org-link-parameters)
1829 (org-make-link-regexps)
1830 (org-element-update-syntax))))
1832 (defun org-link-types ()
1833 "Return a list of known link types."
1834 (mapcar #'car org-link-parameters))
1836 (defcustom org-link-abbrev-alist nil
1837 "Alist of link abbreviations.
1838 The car of each element is a string, to be replaced at the start of a link.
1839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1840 links in Org buffers can have an optional tag after a double colon, e.g.,
1842 [[linkkey:tag][description]]
1844 The `linkkey' must be a single word, starting with a letter, followed
1845 by letters, numbers, `-' or `_'.
1847 If REPLACE is a string, the tag will simply be appended to create the link.
1848 If the string contains \"%s\", the tag will be inserted there. If the string
1849 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1850 at that point (see the function `url-hexify-string'). If the string contains
1851 the specifier \"%(my-function)\", then the custom function `my-function' will
1852 be invoked: this function takes the tag as its only argument and must return
1853 a string.
1855 REPLACE may also be a function that will be called with the tag as the
1856 only argument to create the link, which should be returned as a string.
1858 See the manual for examples."
1859 :group 'org-link
1860 :type '(repeat
1861 (cons
1862 (string :tag "Protocol")
1863 (choice
1864 (string :tag "Format")
1865 (function)))))
1867 (defcustom org-descriptive-links t
1868 "Non-nil means Org will display descriptive links.
1869 E.g. [[https://orgmode.org][Org website]] will be displayed as
1870 \"Org Website\", hiding the link itself and just displaying its
1871 description. When set to nil, Org will display the full links
1872 literally.
1874 You can interactively set the value of this variable by calling
1875 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1876 :group 'org-link
1877 :type 'boolean)
1879 (defcustom org-link-file-path-type 'adaptive
1880 "How the path name in file links should be stored.
1881 Valid values are:
1883 relative Relative to the current directory, i.e. the directory of the file
1884 into which the link is being inserted.
1885 absolute Absolute path, if possible with ~ for home directory.
1886 noabbrev Absolute path, no abbreviation of home directory.
1887 adaptive Use relative path for files in the current directory and sub-
1888 directories of it. For other files, use an absolute path."
1889 :group 'org-link
1890 :type '(choice
1891 (const relative)
1892 (const absolute)
1893 (const noabbrev)
1894 (const adaptive)))
1896 (defvaralias 'org-activate-links 'org-highlight-links)
1897 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1898 "Types of links that should be highlighted in Org files.
1900 This is a list of symbols, each one of them leading to the
1901 highlighting of a certain link type.
1903 You can still open links that are not highlighted.
1905 In principle, it does not hurt to turn on highlighting for all
1906 link types. There may be a small gain when turning off unused
1907 link types. The types are:
1909 bracket The recommended [[link][description]] or [[link]] links with hiding.
1910 angle Links in angular brackets that may contain whitespace like
1911 <bbdb:Carsten Dominik>.
1912 plain Plain links in normal text, no whitespace, like http://google.com.
1913 radio Text that is matched by a radio target, see manual for details.
1914 tag Tag settings in a headline (link to tag search).
1915 date Time stamps (link to calendar).
1916 footnote Footnote labels.
1918 If you set this variable during an Emacs session, use `org-mode-restart'
1919 in the Org buffer so that the change takes effect."
1920 :group 'org-link
1921 :group 'org-appearance
1922 :type '(set :greedy t
1923 (const :tag "Double bracket links" bracket)
1924 (const :tag "Angular bracket links" angle)
1925 (const :tag "Plain text links" plain)
1926 (const :tag "Radio target matches" radio)
1927 (const :tag "Tags" tag)
1928 (const :tag "Timestamps" date)
1929 (const :tag "Footnotes" footnote)))
1931 (defcustom org-make-link-description-function nil
1932 "Function to use for generating link descriptions from links.
1933 This function must take two parameters: the first one is the
1934 link, the second one is the description generated by
1935 `org-insert-link'. The function should return the description to
1936 use."
1937 :group 'org-link
1938 :type '(choice (const nil) (function)))
1940 (defgroup org-link-store nil
1941 "Options concerning storing links in Org mode."
1942 :tag "Org Store Link"
1943 :group 'org-link)
1945 (defcustom org-url-hexify-p t
1946 "When non-nil, hexify URL when creating a link."
1947 :type 'boolean
1948 :version "24.3"
1949 :group 'org-link-store)
1951 (defcustom org-email-link-description-format "Email %c: %.30s"
1952 "Format of the description part of a link to an email or usenet message.
1953 The following %-escapes will be replaced by corresponding information:
1955 %F full \"From\" field
1956 %f name, taken from \"From\" field, address if no name
1957 %T full \"To\" field
1958 %t first name in \"To\" field, address if no name
1959 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1960 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1961 %s subject
1962 %d date
1963 %m message-id.
1965 You may use normal field width specification between the % and the letter.
1966 This is for example useful to limit the length of the subject.
1968 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1969 :group 'org-link-store
1970 :type 'string)
1972 (defcustom org-from-is-user-regexp
1973 (let (r1 r2)
1974 (when (and user-mail-address (not (string= user-mail-address "")))
1975 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1976 (when (and user-full-name (not (string= user-full-name "")))
1977 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1978 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1979 "Regexp matched against the \"From:\" header of an email or usenet message.
1980 It should match if the message is from the user him/herself."
1981 :group 'org-link-store
1982 :type 'regexp)
1984 (defcustom org-context-in-file-links t
1985 "Non-nil means file links from `org-store-link' contain context.
1986 \\<org-mode-map>
1987 A search string will be added to the file name with :: as separator
1988 and used to find the context when the link is activated by the command
1989 `org-open-at-point'. When this option is t, the entire active region
1990 will be placed in the search string of the file link. If set to a
1991 positive integer, only the first n lines of context will be stored.
1993 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1994 \\[org-store-link]')
1995 negates this setting for the duration of the command."
1996 :group 'org-link-store
1997 :type '(choice boolean integer))
1999 (defcustom org-keep-stored-link-after-insertion nil
2000 "Non-nil means keep link in list for entire session.
2001 \\<org-mode-map>
2002 The command `org-store-link' adds a link pointing to the current
2003 location to an internal list. These links accumulate during a session.
2004 The command `org-insert-link' can be used to insert links into any
2005 Org file (offering completion for all stored links).
2007 When this option is nil, every link which has been inserted once using
2008 `\\[org-insert-link]' will be removed from the list, to make completing the \
2009 unused
2010 links more efficient."
2011 :group 'org-link-store
2012 :type 'boolean)
2014 (defgroup org-link-follow nil
2015 "Options concerning following links in Org mode."
2016 :tag "Org Follow Link"
2017 :group 'org-link)
2019 (defcustom org-link-translation-function nil
2020 "Function to translate links with different syntax to Org syntax.
2021 This can be used to translate links created for example by the Planner
2022 or emacs-wiki packages to Org syntax.
2023 The function must accept two parameters, a TYPE containing the link
2024 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2025 which is everything after the link protocol. It should return a cons
2026 with possibly modified values of type and path.
2027 Org contains a function for this, so if you set this variable to
2028 `org-translate-link-from-planner', you should be able follow many
2029 links created by planner."
2030 :group 'org-link-follow
2031 :type '(choice (const nil) (function)))
2033 (defcustom org-follow-link-hook nil
2034 "Hook that is run after a link has been followed."
2035 :group 'org-link-follow
2036 :type 'hook)
2038 (defcustom org-tab-follows-link nil
2039 "Non-nil means on links TAB will follow the link.
2040 Needs to be set before org.el is loaded.
2041 This really should not be used, it does not make sense, and the
2042 implementation is bad."
2043 :group 'org-link-follow
2044 :type 'boolean)
2046 (defcustom org-return-follows-link nil
2047 "Non-nil means on links RET will follow the link.
2048 In tables, the special behavior of RET has precedence."
2049 :group 'org-link-follow
2050 :type 'boolean)
2052 (defcustom org-mouse-1-follows-link
2053 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2054 "Non-nil means mouse-1 on a link will follow the link.
2055 A longer mouse click will still set point. Needs to be set
2056 before org.el is loaded."
2057 :group 'org-link-follow
2058 :version "26.1"
2059 :package-version '(Org . "8.3")
2060 :type '(choice
2061 (const :tag "A double click follows the link" double)
2062 (const :tag "Unconditionally follow the link with mouse-1" t)
2063 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2065 (defcustom org-mark-ring-length 4
2066 "Number of different positions to be recorded in the ring.
2067 Changing this requires a restart of Emacs to work correctly."
2068 :group 'org-link-follow
2069 :type 'integer)
2071 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2072 "Non-nil means internal fuzzy links can only match headlines.
2074 When nil, the a fuzzy link may point to a target or a named
2075 construct in the document. When set to the special value
2076 `query-to-create', offer to create a new headline when none
2077 matched.
2079 Spaces and statistics cookies are ignored during heading searches."
2080 :group 'org-link-follow
2081 :version "24.1"
2082 :type '(choice
2083 (const :tag "Use fuzzy text search" nil)
2084 (const :tag "Match only exact headline" t)
2085 (const :tag "Match exact headline or query to create it"
2086 query-to-create))
2087 :safe #'symbolp)
2089 (defcustom org-link-frame-setup
2090 '((vm . vm-visit-folder-other-frame)
2091 (vm-imap . vm-visit-imap-folder-other-frame)
2092 (gnus . org-gnus-no-new-news)
2093 (file . find-file-other-window)
2094 (wl . wl-other-frame))
2095 "Setup the frame configuration for following links.
2096 When following a link with Emacs, it may often be useful to display
2097 this link in another window or frame. This variable can be used to
2098 set this up for the different types of links.
2099 For VM, use any of
2100 `vm-visit-folder'
2101 `vm-visit-folder-other-window'
2102 `vm-visit-folder-other-frame'
2103 For Gnus, use any of
2104 `gnus'
2105 `gnus-other-frame'
2106 `org-gnus-no-new-news'
2107 For FILE, use any of
2108 `find-file'
2109 `find-file-other-window'
2110 `find-file-other-frame'
2111 For Wanderlust use any of
2112 `wl'
2113 `wl-other-frame'
2114 For the calendar, use the variable `calendar-setup'.
2115 For BBDB, it is currently only possible to display the matches in
2116 another window."
2117 :group 'org-link-follow
2118 :type '(list
2119 (cons (const vm)
2120 (choice
2121 (const vm-visit-folder)
2122 (const vm-visit-folder-other-window)
2123 (const vm-visit-folder-other-frame)))
2124 (cons (const vm-imap)
2125 (choice
2126 (const vm-visit-imap-folder)
2127 (const vm-visit-imap-folder-other-window)
2128 (const vm-visit-imap-folder-other-frame)))
2129 (cons (const gnus)
2130 (choice
2131 (const gnus)
2132 (const gnus-other-frame)
2133 (const org-gnus-no-new-news)))
2134 (cons (const file)
2135 (choice
2136 (const find-file)
2137 (const find-file-other-window)
2138 (const find-file-other-frame)))
2139 (cons (const wl)
2140 (choice
2141 (const wl)
2142 (const wl-other-frame)))))
2144 (defcustom org-display-internal-link-with-indirect-buffer nil
2145 "Non-nil means use indirect buffer to display infile links.
2146 Activating internal links (from one location in a file to another location
2147 in the same file) normally just jumps to the location. When the link is
2148 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2149 is displayed in
2150 another window. When this option is set, the other window actually displays
2151 an indirect buffer clone of the current buffer, to avoid any visibility
2152 changes to the current buffer."
2153 :group 'org-link-follow
2154 :type 'boolean)
2156 (defcustom org-open-non-existing-files nil
2157 "Non-nil means `org-open-file' will open non-existing files.
2158 When nil, an error will be generated.
2159 This variable applies only to external applications because they
2160 might choke on non-existing files. If the link is to a file that
2161 will be opened in Emacs, the variable is ignored."
2162 :group 'org-link-follow
2163 :type 'boolean)
2165 (defcustom org-open-directory-means-index-dot-org nil
2166 "Non-nil means a link to a directory really means to index.org.
2167 When nil, following a directory link will run dired or open a finder/explorer
2168 window on that directory."
2169 :group 'org-link-follow
2170 :type 'boolean)
2172 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2173 "Non-nil means ask for confirmation before executing shell links.
2174 Shell links can be dangerous: just think about a link
2176 [[shell:rm -rf ~/*][Google Search]]
2178 This link would show up in your Org document as \"Google Search\",
2179 but really it would remove your entire home directory.
2180 Therefore we advise against setting this variable to nil.
2181 Just change it to `y-or-n-p' if you want to confirm with a
2182 single keystroke rather than having to type \"yes\"."
2183 :group 'org-link-follow
2184 :type '(choice
2185 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2186 (const :tag "with y-or-n (faster)" y-or-n-p)
2187 (const :tag "no confirmation (dangerous)" nil)))
2188 (put 'org-confirm-shell-link-function
2189 'safe-local-variable
2190 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2192 (defcustom org-confirm-shell-link-not-regexp ""
2193 "A regexp to skip confirmation for shell links."
2194 :group 'org-link-follow
2195 :version "24.1"
2196 :type 'regexp)
2198 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2199 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2200 Elisp links can be dangerous: just think about a link
2202 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2204 This link would show up in your Org document as \"Google Search\",
2205 but really it would remove your entire home directory.
2206 Therefore we advise against setting this variable to nil.
2207 Just change it to `y-or-n-p' if you want to confirm with a
2208 single keystroke rather than having to type \"yes\"."
2209 :group 'org-link-follow
2210 :type '(choice
2211 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2212 (const :tag "with y-or-n (faster)" y-or-n-p)
2213 (const :tag "no confirmation (dangerous)" nil)))
2214 (put 'org-confirm-shell-link-function
2215 'safe-local-variable
2216 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2218 (defcustom org-confirm-elisp-link-not-regexp ""
2219 "A regexp to skip confirmation for Elisp links."
2220 :group 'org-link-follow
2221 :version "24.1"
2222 :type 'regexp)
2224 (defconst org-file-apps-defaults-gnu
2225 '((remote . emacs)
2226 (system . mailcap)
2227 (t . mailcap))
2228 "Default file applications on a UNIX or GNU/Linux system.
2229 See `org-file-apps'.")
2231 (defconst org-file-apps-defaults-macosx
2232 '((remote . emacs)
2233 (system . "open %s")
2234 ("ps.gz" . "gv %s")
2235 ("eps.gz" . "gv %s")
2236 ("dvi" . "xdvi %s")
2237 ("fig" . "xfig %s")
2238 (t . "open %s"))
2239 "Default file applications on a macOS system.
2240 The system \"open\" is known as a default, but we use X11 applications
2241 for some files for which the OS does not have a good default.
2242 See `org-file-apps'.")
2244 (defconst org-file-apps-defaults-windowsnt
2245 (list '(remote . emacs)
2246 (cons 'system (lambda (file _path)
2247 (with-no-warnings (w32-shell-execute "open" file))))
2248 (cons t (lambda (file _path)
2249 (with-no-warnings (w32-shell-execute "open" file)))))
2250 "Default file applications on a Windows NT system.
2251 The system \"open\" is used for most files.
2252 See `org-file-apps'.")
2254 (defcustom org-file-apps
2255 '((auto-mode . emacs)
2256 ("\\.mm\\'" . default)
2257 ("\\.x?html?\\'" . default)
2258 ("\\.pdf\\'" . default))
2259 "External applications for opening `file:path' items in a document.
2260 \\<org-mode-map>\
2262 Org mode uses system defaults for different file types, but
2263 you can use this variable to set the application for a given file
2264 extension. The entries in this list are cons cells where the car identifies
2265 files and the cdr the corresponding command.
2267 Possible values for the file identifier are:
2269 \"string\" A string as a file identifier can be interpreted in different
2270 ways, depending on its contents:
2272 - Alphanumeric characters only:
2273 Match links with this file extension.
2274 Example: (\"pdf\" . \"evince %s\")
2275 to open PDFs with evince.
2277 - Regular expression: Match links where the
2278 filename matches the regexp. If you want to
2279 use groups here, use shy groups.
2281 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2282 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2283 to open *.html and *.xhtml with firefox.
2285 - Regular expression which contains (non-shy) groups:
2286 Match links where the whole link, including \"::\", and
2287 anything after that, matches the regexp.
2288 In a custom command string, %1, %2, etc. are replaced with
2289 the parts of the link that were matched by the groups.
2290 For backwards compatibility, if a command string is given
2291 that does not use any of the group matches, this case is
2292 handled identically to the second one (i.e. match against
2293 file name only).
2294 In a custom function, you can access the group matches with
2295 (match-string n link).
2297 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2298 \"evince -p %1 %s\")
2299 to open [[file:document.pdf::5]] with evince at page 5.
2301 `directory' Matches a directory
2302 `remote' Matches a remote file, accessible through tramp or efs.
2303 Remote files most likely should be visited through Emacs
2304 because external applications cannot handle such paths.
2305 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2306 so all files Emacs knows how to handle. Using this with
2307 command `emacs' will open most files in Emacs. Beware that this
2308 will also open html files inside Emacs, unless you add
2309 (\"html\" . default) to the list as well.
2310 `system' The system command to open files, like `open' on Windows
2311 and macOS, and mailcap under GNU/Linux. This is the command
2312 that will be selected if you call `org-open-at-point' with a
2313 double prefix argument (`\\[universal-argument] \
2314 \\[universal-argument] \\[org-open-at-point]').
2315 t Default for files not matched by any of the other options.
2317 Possible values for the command are:
2319 `emacs' The file will be visited by the current Emacs process.
2320 `default' Use the default application for this file type, which is the
2321 association for t in the list, most likely in the system-specific
2322 part. This can be used to overrule an unwanted setting in the
2323 system-specific variable.
2324 `system' Use the system command for opening files, like \"open\".
2325 This command is specified by the entry whose car is `system'.
2326 Most likely, the system-specific version of this variable
2327 does define this command, but you can overrule/replace it
2328 here.
2329 `mailcap' Use command specified in the mailcaps.
2330 string A command to be executed by a shell; %s will be replaced
2331 by the path to the file.
2332 function A Lisp function, which will be called with two arguments:
2333 the file path and the original link string, without the
2334 \"file:\" prefix.
2336 For more examples, see the system specific constants
2337 `org-file-apps-defaults-macosx'
2338 `org-file-apps-defaults-windowsnt'
2339 `org-file-apps-defaults-gnu'."
2340 :group 'org-link-follow
2341 :type '(repeat
2342 (cons (choice :value ""
2343 (string :tag "Extension")
2344 (const :tag "System command to open files" system)
2345 (const :tag "Default for unrecognized files" t)
2346 (const :tag "Remote file" remote)
2347 (const :tag "Links to a directory" directory)
2348 (const :tag "Any files that have Emacs modes"
2349 auto-mode))
2350 (choice :value ""
2351 (const :tag "Visit with Emacs" emacs)
2352 (const :tag "Use default" default)
2353 (const :tag "Use the system command" system)
2354 (string :tag "Command")
2355 (function :tag "Function")))))
2357 (defcustom org-doi-server-url "http://dx.doi.org/"
2358 "The URL of the DOI server."
2359 :type 'string
2360 :version "24.3"
2361 :group 'org-link-follow)
2363 (defgroup org-refile nil
2364 "Options concerning refiling entries in Org mode."
2365 :tag "Org Refile"
2366 :group 'org)
2368 (defcustom org-directory "~/org"
2369 "Directory with Org files.
2370 This is just a default location to look for Org files. There is no need
2371 at all to put your files into this directory. It is used in the
2372 following situations:
2374 1. When a capture template specifies a target file that is not an
2375 absolute path. The path will then be interpreted relative to
2376 `org-directory'
2377 2. When the value of variable `org-agenda-files' is a single file, any
2378 relative paths in this file will be taken as relative to
2379 `org-directory'."
2380 :group 'org-refile
2381 :group 'org-capture
2382 :type 'directory)
2384 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2385 "Default target for storing notes.
2386 Used as a fall back file for org-capture.el, for templates that
2387 do not specify a target file."
2388 :group 'org-refile
2389 :group 'org-capture
2390 :type 'file)
2392 (defcustom org-goto-interface 'outline
2393 "The default interface to be used for `org-goto'.
2394 Allowed values are:
2395 outline The interface shows an outline of the relevant file
2396 and the correct heading is found by moving through
2397 the outline or by searching with incremental search.
2398 outline-path-completion Headlines in the current buffer are offered via
2399 completion. This is the interface also used by
2400 the refile command."
2401 :group 'org-refile
2402 :type '(choice
2403 (const :tag "Outline" outline)
2404 (const :tag "Outline-path-completion" outline-path-completion)))
2406 (defcustom org-goto-max-level 5
2407 "Maximum target level when running `org-goto' with refile interface."
2408 :group 'org-refile
2409 :type 'integer)
2411 (defcustom org-reverse-note-order nil
2412 "Non-nil means store new notes at the beginning of a file or entry.
2413 When nil, new notes will be filed to the end of a file or entry.
2414 This can also be a list with cons cells of regular expressions that
2415 are matched against file names, and values."
2416 :group 'org-capture
2417 :group 'org-refile
2418 :type '(choice
2419 (const :tag "Reverse always" t)
2420 (const :tag "Reverse never" nil)
2421 (repeat :tag "By file name regexp"
2422 (cons regexp boolean))))
2424 (defcustom org-log-refile nil
2425 "Information to record when a task is refiled.
2427 Possible values are:
2429 nil Don't add anything
2430 time Add a time stamp to the task
2431 note Prompt for a note and add it with template `org-log-note-headings'
2433 This option can also be set with on a per-file-basis with
2435 #+STARTUP: nologrefile
2436 #+STARTUP: logrefile
2437 #+STARTUP: lognoterefile
2439 You can have local logging settings for a subtree by setting the LOGGING
2440 property to one or more of these keywords.
2442 When bulk-refiling from the agenda, the value `note' is forbidden and
2443 will temporarily be changed to `time'."
2444 :group 'org-refile
2445 :group 'org-progress
2446 :version "24.1"
2447 :type '(choice
2448 (const :tag "No logging" nil)
2449 (const :tag "Record timestamp" time)
2450 (const :tag "Record timestamp with note." note)))
2452 (defcustom org-refile-targets nil
2453 "Targets for refiling entries with `\\[org-refile]'.
2454 This is a list of cons cells. Each cell contains:
2455 - a specification of the files to be considered, either a list of files,
2456 or a symbol whose function or variable value will be used to retrieve
2457 a file name or a list of file names. If you use `org-agenda-files' for
2458 that, all agenda files will be scanned for targets. Nil means consider
2459 headings in the current buffer.
2460 - A specification of how to find candidate refile targets. This may be
2461 any of:
2462 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2463 This tag has to be present in all target headlines, inheritance will
2464 not be considered.
2465 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2466 todo keyword.
2467 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2468 headlines that are refiling targets.
2469 - a cons cell (:level . N). Any headline of level N is considered a target.
2470 Note that, when `org-odd-levels-only' is set, level corresponds to
2471 order in hierarchy, not to the number of stars.
2472 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2473 Note that, when `org-odd-levels-only' is set, level corresponds to
2474 order in hierarchy, not to the number of stars.
2476 Each element of this list generates a set of possible targets.
2477 The union of these sets is presented (with completion) to
2478 the user by `org-refile'.
2480 You can set the variable `org-refile-target-verify-function' to a function
2481 to verify each headline found by the simple criteria above.
2483 When this variable is nil, all top-level headlines in the current buffer
2484 are used, equivalent to the value `((nil . (:level . 1))'."
2485 :group 'org-refile
2486 :type '(repeat
2487 (cons
2488 (choice :value org-agenda-files
2489 (const :tag "All agenda files" org-agenda-files)
2490 (const :tag "Current buffer" nil)
2491 (function) (variable) (file))
2492 (choice :tag "Identify target headline by"
2493 (cons :tag "Specific tag" (const :value :tag) (string))
2494 (cons :tag "TODO keyword" (const :value :todo) (string))
2495 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2496 (cons :tag "Level number" (const :value :level) (integer))
2497 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2499 (defcustom org-refile-target-verify-function nil
2500 "Function to verify if the headline at point should be a refile target.
2501 The function will be called without arguments, with point at the
2502 beginning of the headline. It should return t and leave point
2503 where it is if the headline is a valid target for refiling.
2505 If the target should not be selected, the function must return nil.
2506 In addition to this, it may move point to a place from where the search
2507 should be continued. For example, the function may decide that the entire
2508 subtree of the current entry should be excluded and move point to the end
2509 of the subtree."
2510 :group 'org-refile
2511 :type '(choice
2512 (const nil)
2513 (function)))
2515 (defcustom org-refile-use-cache nil
2516 "Non-nil means cache refile targets to speed up the process.
2517 \\<org-mode-map>\
2518 The cache for a particular file will be updated automatically when
2519 the buffer has been killed, or when any of the marker used for flagging
2520 refile targets no longer points at a live buffer.
2521 If you have added new entries to a buffer that might themselves be targets,
2522 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2523 if you find that easier, \
2524 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2525 \\[org-refile]'."
2526 :group 'org-refile
2527 :version "24.1"
2528 :type 'boolean)
2530 (defcustom org-refile-use-outline-path nil
2531 "Non-nil means provide refile targets as paths.
2532 So a level 3 headline will be available as level1/level2/level3.
2534 When the value is `file', also include the file name (without directory)
2535 into the path. In this case, you can also stop the completion after
2536 the file name, to get entries inserted as top level in the file.
2538 When `full-file-path', include the full file path.
2540 When `buffer-name', use the buffer name."
2541 :group 'org-refile
2542 :type '(choice
2543 (const :tag "Not" nil)
2544 (const :tag "Yes" t)
2545 (const :tag "Start with file name" file)
2546 (const :tag "Start with full file path" full-file-path)
2547 (const :tag "Start with buffer name" buffer-name)))
2549 (defcustom org-outline-path-complete-in-steps t
2550 "Non-nil means complete the outline path in hierarchical steps.
2551 When Org uses the refile interface to select an outline path (see
2552 `org-refile-use-outline-path'), the completion of the path can be
2553 done in a single go, or it can be done in steps down the headline
2554 hierarchy. Going in steps is probably the best if you do not use
2555 a special completion package like `ido' or `icicles'. However,
2556 when using these packages, going in one step can be very fast,
2557 while still showing the whole path to the entry."
2558 :group 'org-refile
2559 :type 'boolean)
2561 (defcustom org-refile-allow-creating-parent-nodes nil
2562 "Non-nil means allow the creation of new nodes as refile targets.
2563 New nodes are then created by adding \"/new node name\" to the completion
2564 of an existing node. When the value of this variable is `confirm',
2565 new node creation must be confirmed by the user (recommended).
2566 When nil, the completion must match an existing entry.
2568 Note that, if the new heading is not seen by the criteria
2569 listed in `org-refile-targets', multiple instances of the same
2570 heading would be created by trying again to file under the new
2571 heading."
2572 :group 'org-refile
2573 :type '(choice
2574 (const :tag "Never" nil)
2575 (const :tag "Always" t)
2576 (const :tag "Prompt for confirmation" confirm)))
2578 (defcustom org-refile-active-region-within-subtree nil
2579 "Non-nil means also refile active region within a subtree.
2581 By default `org-refile' doesn't allow refiling regions if they
2582 don't contain a set of subtrees, but it might be convenient to
2583 do so sometimes: in that case, the first line of the region is
2584 converted to a headline before refiling."
2585 :group 'org-refile
2586 :version "24.1"
2587 :type 'boolean)
2589 (defgroup org-todo nil
2590 "Options concerning TODO items in Org mode."
2591 :tag "Org TODO"
2592 :group 'org)
2594 (defgroup org-progress nil
2595 "Options concerning Progress logging in Org mode."
2596 :tag "Org Progress"
2597 :group 'org-time)
2599 (defvar org-todo-interpretation-widgets
2600 '((:tag "Sequence (cycling hits every state)" sequence)
2601 (:tag "Type (cycling directly to DONE)" type))
2602 "The available interpretation symbols for customizing `org-todo-keywords'.
2603 Interested libraries should add to this list.")
2605 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2606 "List of TODO entry keyword sequences and their interpretation.
2607 \\<org-mode-map>This is a list of sequences.
2609 Each sequence starts with a symbol, either `sequence' or `type',
2610 indicating if the keywords should be interpreted as a sequence of
2611 action steps, or as different types of TODO items. The first
2612 keywords are states requiring action - these states will select a headline
2613 for inclusion into the global TODO list Org produces. If one of the
2614 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2615 signify that no further action is necessary. If \"|\" is not found,
2616 the last keyword is treated as the only DONE state of the sequence.
2618 The command `\\[org-todo]' cycles an entry through these states, and one
2619 additional state where no keyword is present. For details about this
2620 cycling, see the manual.
2622 TODO keywords and interpretation can also be set on a per-file basis with
2623 the special #+SEQ_TODO and #+TYP_TODO lines.
2625 Each keyword can optionally specify a character for fast state selection
2626 \(in combination with the variable `org-use-fast-todo-selection')
2627 and specifiers for state change logging, using the same syntax that
2628 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2629 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2630 indicates to record a time stamp each time this state is selected.
2632 Each keyword may also specify if a timestamp or a note should be
2633 recorded when entering or leaving the state, by adding additional
2634 characters in the parenthesis after the keyword. This looks like this:
2635 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2636 record only the time of the state change. With X and Y being either
2637 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2638 Y when leaving the state if and only if the *target* state does not
2639 define X. You may omit any of the fast-selection key or X or /Y,
2640 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2642 For backward compatibility, this variable may also be just a list
2643 of keywords. In this case the interpretation (sequence or type) will be
2644 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2645 :group 'org-todo
2646 :group 'org-keywords
2647 :type '(choice
2648 (repeat :tag "Old syntax, just keywords"
2649 (string :tag "Keyword"))
2650 (repeat :tag "New syntax"
2651 (cons
2652 (choice
2653 :tag "Interpretation"
2654 ;;Quick and dirty way to see
2655 ;;`org-todo-interpretations'. This takes the
2656 ;;place of item arguments
2657 :convert-widget
2658 (lambda (widget)
2659 (widget-put widget
2660 :args (mapcar
2661 (lambda (x)
2662 (widget-convert
2663 (cons 'const x)))
2664 org-todo-interpretation-widgets))
2665 widget))
2666 (repeat
2667 (string :tag "Keyword"))))))
2669 (defvar-local org-todo-keywords-1 nil
2670 "All TODO and DONE keywords active in a buffer.")
2671 (defvar org-todo-keywords-for-agenda nil)
2672 (defvar org-done-keywords-for-agenda nil)
2673 (defvar org-todo-keyword-alist-for-agenda nil)
2674 (defvar org-tag-alist-for-agenda nil
2675 "Alist of all tags from all agenda files.")
2676 (defvar org-tag-groups-alist-for-agenda nil
2677 "Alist of all groups tags from all current agenda files.")
2678 (defvar-local org-tag-groups-alist nil)
2679 (defvar org-agenda-contributing-files nil)
2680 (defvar-local org-current-tag-alist nil
2681 "Alist of all tag groups in current buffer.
2682 This variable takes into consideration `org-tag-alist',
2683 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2684 (defvar-local org-not-done-keywords nil)
2685 (defvar-local org-done-keywords nil)
2686 (defvar-local org-todo-heads nil)
2687 (defvar-local org-todo-sets nil)
2688 (defvar-local org-todo-log-states nil)
2689 (defvar-local org-todo-kwd-alist nil)
2690 (defvar-local org-todo-key-alist nil)
2691 (defvar-local org-todo-key-trigger nil)
2693 (defcustom org-todo-interpretation 'sequence
2694 "Controls how TODO keywords are interpreted.
2695 This variable is in principle obsolete and is only used for
2696 backward compatibility, if the interpretation of todo keywords is
2697 not given already in `org-todo-keywords'. See that variable for
2698 more information."
2699 :group 'org-todo
2700 :group 'org-keywords
2701 :type '(choice (const sequence)
2702 (const type)))
2704 (defcustom org-use-fast-todo-selection t
2705 "\\<org-mode-map>\
2706 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2707 This variable describes if and under what circumstances the cycling
2708 mechanism for TODO keywords will be replaced by a single-key, direct
2709 selection scheme.
2711 When nil, fast selection is never used.
2713 When the symbol `prefix', it will be used when `org-todo' is called
2714 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2715 in an Org buffer, and
2716 `\\[universal-argument] t' in an agenda buffer.
2718 When t, fast selection is used by default. In this case, the prefix
2719 argument forces cycling instead.
2721 In all cases, the special interface is only used if access keys have
2722 actually been assigned by the user, i.e. if keywords in the configuration
2723 are followed by a letter in parenthesis, like TODO(t)."
2724 :group 'org-todo
2725 :type '(choice
2726 (const :tag "Never" nil)
2727 (const :tag "By default" t)
2728 (const :tag "Only with C-u C-c C-t" prefix)))
2730 (defcustom org-provide-todo-statistics t
2731 "Non-nil means update todo statistics after insert and toggle.
2732 ALL-HEADLINES means update todo statistics by including headlines
2733 with no TODO keyword as well, counting them as not done.
2734 A list of TODO keywords means the same, but skip keywords that are
2735 not in this list.
2736 When set to a list of two lists, the first list contains keywords
2737 to consider as TODO keywords, the second list contains keywords
2738 to consider as DONE keywords.
2740 When this is set, todo statistics is updated in the parent of the
2741 current entry each time a todo state is changed."
2742 :group 'org-todo
2743 :type '(choice
2744 (const :tag "Yes, only for TODO entries" t)
2745 (const :tag "Yes, including all entries" all-headlines)
2746 (repeat :tag "Yes, for TODOs in this list"
2747 (string :tag "TODO keyword"))
2748 (list :tag "Yes, for TODOs and DONEs in these lists"
2749 (repeat (string :tag "TODO keyword"))
2750 (repeat (string :tag "DONE keyword")))
2751 (other :tag "No TODO statistics" nil)))
2753 (defcustom org-hierarchical-todo-statistics t
2754 "Non-nil means TODO statistics covers just direct children.
2755 When nil, all entries in the subtree are considered.
2756 This has only an effect if `org-provide-todo-statistics' is set.
2757 To set this to nil for only a single subtree, use a COOKIE_DATA
2758 property and include the word \"recursive\" into the value."
2759 :group 'org-todo
2760 :type 'boolean)
2762 (defcustom org-after-todo-state-change-hook nil
2763 "Hook which is run after the state of a TODO item was changed.
2764 The new state (a string with a TODO keyword, or nil) is available in the
2765 Lisp variable `org-state'."
2766 :group 'org-todo
2767 :type 'hook)
2769 (defvar org-blocker-hook nil
2770 "Hook for functions that are allowed to block a state change.
2772 Functions in this hook should not modify the buffer.
2773 Each function gets as its single argument a property list,
2774 see `org-trigger-hook' for more information about this list.
2776 If any of the functions in this hook returns nil, the state change
2777 is blocked.")
2779 (defvar org-trigger-hook nil
2780 "Hook for functions that are triggered by a state change.
2782 Each function gets as its single argument a property list with at
2783 least the following elements:
2785 (:type type-of-change :position pos-at-entry-start
2786 :from old-state :to new-state)
2788 Depending on the type, more properties may be present.
2790 This mechanism is currently implemented for:
2792 TODO state changes
2793 ------------------
2794 :type todo-state-change
2795 :from previous state (keyword as a string), or nil, or a symbol
2796 `todo' or `done', to indicate the general type of state.
2797 :to new state, like in :from")
2799 (defcustom org-enforce-todo-dependencies nil
2800 "Non-nil means undone TODO entries will block switching the parent to DONE.
2801 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2802 be blocked if any prior sibling is not yet done.
2803 Finally, if the parent is blocked because of ordered siblings of its own,
2804 the child will also be blocked."
2805 :set (lambda (var val)
2806 (set var val)
2807 (if val
2808 (add-hook 'org-blocker-hook
2809 'org-block-todo-from-children-or-siblings-or-parent)
2810 (remove-hook 'org-blocker-hook
2811 'org-block-todo-from-children-or-siblings-or-parent)))
2812 :group 'org-todo
2813 :type 'boolean)
2815 (defcustom org-enforce-todo-checkbox-dependencies nil
2816 "Non-nil means unchecked boxes will block switching the parent to DONE.
2817 When this is nil, checkboxes have no influence on switching TODO states.
2818 When non-nil, you first need to check off all check boxes before the TODO
2819 entry can be switched to DONE.
2820 This variable needs to be set before org.el is loaded, and you need to
2821 restart Emacs after a change to make the change effective. The only way
2822 to change is while Emacs is running is through the customize interface."
2823 :set (lambda (var val)
2824 (set var val)
2825 (if val
2826 (add-hook 'org-blocker-hook
2827 'org-block-todo-from-checkboxes)
2828 (remove-hook 'org-blocker-hook
2829 'org-block-todo-from-checkboxes)))
2830 :group 'org-todo
2831 :type 'boolean)
2833 (defcustom org-treat-insert-todo-heading-as-state-change nil
2834 "Non-nil means inserting a TODO heading is treated as state change.
2835 So when the command `\\[org-insert-todo-heading]' is used, state change
2836 logging will apply if appropriate. When nil, the new TODO item will
2837 be inserted directly, and no logging will take place."
2838 :group 'org-todo
2839 :type 'boolean)
2841 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2842 "Non-nil means switching TODO states with S-cursor counts as state change.
2843 This is the default behavior. However, setting this to nil allows a
2844 convenient way to select a TODO state and bypass any logging associated
2845 with that."
2846 :group 'org-todo
2847 :type 'boolean)
2849 (defcustom org-todo-state-tags-triggers nil
2850 "Tag changes that should be triggered by TODO state changes.
2851 This is a list. Each entry is
2853 (state-change (tag . flag) .......)
2855 State-change can be a string with a state, and empty string to indicate the
2856 state that has no TODO keyword, or it can be one of the symbols `todo'
2857 or `done', meaning any not-done or done state, respectively."
2858 :group 'org-todo
2859 :group 'org-tags
2860 :type '(repeat
2861 (cons (choice :tag "When changing to"
2862 (const :tag "Not-done state" todo)
2863 (const :tag "Done state" done)
2864 (string :tag "State"))
2865 (repeat
2866 (cons :tag "Tag action"
2867 (string :tag "Tag")
2868 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2870 (defcustom org-log-done nil
2871 "Information to record when a task moves to the DONE state.
2873 Possible values are:
2875 nil Don't add anything, just change the keyword
2876 time Add a time stamp to the task
2877 note Prompt for a note and add it with template `org-log-note-headings'
2879 This option can also be set with on a per-file-basis with
2881 #+STARTUP: nologdone
2882 #+STARTUP: logdone
2883 #+STARTUP: lognotedone
2885 You can have local logging settings for a subtree by setting the LOGGING
2886 property to one or more of these keywords."
2887 :group 'org-todo
2888 :group 'org-progress
2889 :type '(choice
2890 (const :tag "No logging" nil)
2891 (const :tag "Record CLOSED timestamp" time)
2892 (const :tag "Record CLOSED timestamp with note." note)))
2894 ;; Normalize old uses of org-log-done.
2895 (cond
2896 ((eq org-log-done t) (setq org-log-done 'time))
2897 ((and (listp org-log-done) (memq 'done org-log-done))
2898 (setq org-log-done 'note)))
2900 (defcustom org-log-reschedule nil
2901 "Information to record when the scheduling date of a tasks is modified.
2903 Possible values are:
2905 nil Don't add anything, just change the date
2906 time Add a time stamp to the task
2907 note Prompt for a note and add it with template `org-log-note-headings'
2909 This option can also be set with on a per-file-basis with
2911 #+STARTUP: nologreschedule
2912 #+STARTUP: logreschedule
2913 #+STARTUP: lognotereschedule"
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type '(choice
2917 (const :tag "No logging" nil)
2918 (const :tag "Record timestamp" time)
2919 (const :tag "Record timestamp with note." note)))
2921 (defcustom org-log-redeadline nil
2922 "Information to record when the deadline date of a tasks is modified.
2924 Possible values are:
2926 nil Don't add anything, just change the date
2927 time Add a time stamp to the task
2928 note Prompt for a note and add it with template `org-log-note-headings'
2930 This option can also be set with on a per-file-basis with
2932 #+STARTUP: nologredeadline
2933 #+STARTUP: logredeadline
2934 #+STARTUP: lognoteredeadline
2936 You can have local logging settings for a subtree by setting the LOGGING
2937 property to one or more of these keywords."
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type '(choice
2941 (const :tag "No logging" nil)
2942 (const :tag "Record timestamp" time)
2943 (const :tag "Record timestamp with note." note)))
2945 (defcustom org-log-note-clock-out nil
2946 "Non-nil means record a note when clocking out of an item.
2947 This can also be configured on a per-file basis by adding one of
2948 the following lines anywhere in the buffer:
2950 #+STARTUP: lognoteclock-out
2951 #+STARTUP: nolognoteclock-out"
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type 'boolean)
2956 (defcustom org-log-done-with-time t
2957 "Non-nil means the CLOSED time stamp will contain date and time.
2958 When nil, only the date will be recorded."
2959 :group 'org-progress
2960 :type 'boolean)
2962 (defcustom org-log-note-headings
2963 '((done . "CLOSING NOTE %t")
2964 (state . "State %-12s from %-12S %t")
2965 (note . "Note taken on %t")
2966 (reschedule . "Rescheduled from %S on %t")
2967 (delschedule . "Not scheduled, was %S on %t")
2968 (redeadline . "New deadline from %S on %t")
2969 (deldeadline . "Removed deadline, was %S on %t")
2970 (refile . "Refiled on %t")
2971 (clock-out . ""))
2972 "Headings for notes added to entries.
2974 The value is an alist, with the car being a symbol indicating the
2975 note context, and the cdr is the heading to be used. The heading
2976 may also be the empty string. The following placeholders can be
2977 used:
2979 %t a time stamp.
2980 %T an active time stamp instead the default inactive one
2981 %d a short-format time stamp.
2982 %D an active short-format time stamp.
2983 %s the new TODO state or time stamp (inactive), in double quotes.
2984 %S the old TODO state or time stamp (inactive), in double quotes.
2985 %u the user name.
2986 %U full user name.
2988 In fact, it is not a good idea to change the `state' entry,
2989 because Agenda Log mode depends on the format of these entries."
2990 :group 'org-todo
2991 :group 'org-progress
2992 :type '(list :greedy t
2993 (cons (const :tag "Heading when closing an item" done) string)
2994 (cons (const :tag
2995 "Heading when changing todo state (todo sequence only)"
2996 state) string)
2997 (cons (const :tag "Heading when just taking a note" note) string)
2998 (cons (const :tag "Heading when rescheduling" reschedule) string)
2999 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3000 (cons (const :tag "Heading when changing deadline" redeadline) string)
3001 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3002 (cons (const :tag "Heading when refiling" refile) string)
3003 (cons (const :tag "Heading when clocking out" clock-out) string)))
3005 (unless (assq 'note org-log-note-headings)
3006 (push '(note . "%t") org-log-note-headings))
3008 (defcustom org-log-into-drawer nil
3009 "Non-nil means insert state change notes and time stamps into a drawer.
3010 When nil, state changes notes will be inserted after the headline and
3011 any scheduling and clock lines, but not inside a drawer.
3013 The value of this variable should be the name of the drawer to use.
3014 LOGBOOK is proposed as the default drawer for this purpose, you can
3015 also set this to a string to define the drawer of your choice.
3017 A value of t is also allowed, representing \"LOGBOOK\".
3019 A value of t or nil can also be set with on a per-file-basis with
3021 #+STARTUP: logdrawer
3022 #+STARTUP: nologdrawer
3024 If this variable is set, `org-log-state-notes-insert-after-drawers'
3025 will be ignored.
3027 You can set the property LOG_INTO_DRAWER to overrule this setting for
3028 a subtree.
3030 Do not check directly this variable in a Lisp program. Call
3031 function `org-log-into-drawer' instead."
3032 :group 'org-todo
3033 :group 'org-progress
3034 :type '(choice
3035 (const :tag "Not into a drawer" nil)
3036 (const :tag "LOGBOOK" t)
3037 (string :tag "Other")))
3039 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3041 (defun org-log-into-drawer ()
3042 "Name of the log drawer, as a string, or nil.
3043 This is the value of `org-log-into-drawer'. However, if the
3044 current entry has or inherits a LOG_INTO_DRAWER property, it will
3045 be used instead of the default value."
3046 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3047 (cond ((equal p "nil") nil)
3048 ((equal p "t") "LOGBOOK")
3049 ((stringp p) p)
3050 (p "LOGBOOK")
3051 ((stringp org-log-into-drawer) org-log-into-drawer)
3052 (org-log-into-drawer "LOGBOOK"))))
3054 (defcustom org-log-state-notes-insert-after-drawers nil
3055 "Non-nil means insert state change notes after any drawers in entry.
3056 Only the drawers that *immediately* follow the headline and the
3057 deadline/scheduled line are skipped.
3058 When nil, insert notes right after the heading and perhaps the line
3059 with deadline/scheduling if present.
3061 This variable will have no effect if `org-log-into-drawer' is
3062 set."
3063 :group 'org-todo
3064 :group 'org-progress
3065 :type 'boolean)
3067 (defcustom org-log-states-order-reversed t
3068 "Non-nil means the latest state note will be directly after heading.
3069 When nil, the state change notes will be ordered according to time.
3071 This option can also be set with on a per-file-basis with
3073 #+STARTUP: logstatesreversed
3074 #+STARTUP: nologstatesreversed"
3075 :group 'org-todo
3076 :group 'org-progress
3077 :type 'boolean)
3079 (defcustom org-todo-repeat-to-state nil
3080 "The TODO state to which a repeater should return the repeating task.
3081 By default this is the first task in a TODO sequence, or the previous state
3082 in a TODO_TYP set. But you can specify another task here.
3083 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3084 :group 'org-todo
3085 :version "24.1"
3086 :type '(choice (const :tag "Head of sequence" nil)
3087 (string :tag "Specific state")))
3089 (defcustom org-log-repeat 'time
3090 "Non-nil means record moving through the DONE state when triggering repeat.
3091 An auto-repeating task is immediately switched back to TODO when
3092 marked DONE. If you are not logging state changes (by adding \"@\"
3093 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3094 record a closing note, there will be no record of the task moving
3095 through DONE. This variable forces taking a note anyway.
3097 nil Don't force a record
3098 time Record a time stamp
3099 note Prompt for a note and add it with template `org-log-note-headings'
3101 This option can also be set with on a per-file-basis with
3103 #+STARTUP: nologrepeat
3104 #+STARTUP: logrepeat
3105 #+STARTUP: lognoterepeat
3107 You can have local logging settings for a subtree by setting the LOGGING
3108 property to one or more of these keywords."
3109 :group 'org-todo
3110 :group 'org-progress
3111 :type '(choice
3112 (const :tag "Don't force a record" nil)
3113 (const :tag "Force recording the DONE state" time)
3114 (const :tag "Force recording a note with the DONE state" note)))
3117 (defgroup org-priorities nil
3118 "Priorities in Org mode."
3119 :tag "Org Priorities"
3120 :group 'org-todo)
3122 (defcustom org-enable-priority-commands t
3123 "Non-nil means priority commands are active.
3124 When nil, these commands will be disabled, so that you never accidentally
3125 set a priority."
3126 :group 'org-priorities
3127 :type 'boolean)
3129 (defcustom org-highest-priority ?A
3130 "The highest priority of TODO items. A character like ?A, ?B etc.
3131 Must have a smaller ASCII number than `org-lowest-priority'."
3132 :group 'org-priorities
3133 :type 'character)
3135 (defcustom org-lowest-priority ?C
3136 "The lowest priority of TODO items. A character like ?A, ?B etc.
3137 Must have a larger ASCII number than `org-highest-priority'."
3138 :group 'org-priorities
3139 :type 'character)
3141 (defcustom org-default-priority ?B
3142 "The default priority of TODO items.
3143 This is the priority an item gets if no explicit priority is given.
3144 When starting to cycle on an empty priority the first step in the cycle
3145 depends on `org-priority-start-cycle-with-default'. The resulting first
3146 step priority must not exceed the range from `org-highest-priority' to
3147 `org-lowest-priority' which means that `org-default-priority' has to be
3148 in this range exclusive or inclusive the range boundaries. Else the
3149 first step refuses to set the default and the second will fall back
3150 to (depending on the command used) the highest or lowest priority."
3151 :group 'org-priorities
3152 :type 'character)
3154 (defcustom org-priority-start-cycle-with-default t
3155 "Non-nil means start with default priority when starting to cycle.
3156 When this is nil, the first step in the cycle will be (depending on the
3157 command used) one higher or lower than the default priority.
3158 See also `org-default-priority'."
3159 :group 'org-priorities
3160 :type 'boolean)
3162 (defcustom org-get-priority-function nil
3163 "Function to extract the priority from a string.
3164 The string is normally the headline. If this is nil Org computes the
3165 priority from the priority cookie like [#A] in the headline. It returns
3166 an integer, increasing by 1000 for each priority level.
3167 The user can set a different function here, which should take a string
3168 as an argument and return the numeric priority."
3169 :group 'org-priorities
3170 :version "24.1"
3171 :type '(choice
3172 (const nil)
3173 (function)))
3175 (defgroup org-time nil
3176 "Options concerning time stamps and deadlines in Org mode."
3177 :tag "Org Time"
3178 :group 'org)
3180 (defcustom org-time-stamp-rounding-minutes '(0 5)
3181 "Number of minutes to round time stamps to.
3182 \\<org-mode-map>\
3183 These are two values, the first applies when first creating a time stamp.
3184 The second applies when changing it with the commands `S-up' and `S-down'.
3185 When changing the time stamp, this means that it will change in steps
3186 of N minutes, as given by the second value.
3188 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3189 numbers should be factors of 60, so for example 5, 10, 15.
3191 When this is larger than 1, you can still force an exact time stamp by using
3192 a double prefix argument to a time stamp command like \
3193 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3194 and by using a prefix arg to `S-up/down' to specify the exact number
3195 of minutes to shift."
3196 :group 'org-time
3197 :get (lambda (var) ; Make sure both elements are there
3198 (if (integerp (default-value var))
3199 (list (default-value var) 5)
3200 (default-value var)))
3201 :type '(list
3202 (integer :tag "when inserting times")
3203 (integer :tag "when modifying times")))
3205 ;; Normalize old customizations of this variable.
3206 (when (integerp org-time-stamp-rounding-minutes)
3207 (setq org-time-stamp-rounding-minutes
3208 (list org-time-stamp-rounding-minutes
3209 org-time-stamp-rounding-minutes)))
3211 (defcustom org-display-custom-times nil
3212 "Non-nil means overlay custom formats over all time stamps.
3213 The formats are defined through the variable `org-time-stamp-custom-formats'.
3214 To turn this on on a per-file basis, insert anywhere in the file:
3215 #+STARTUP: customtime"
3216 :group 'org-time
3217 :set 'set-default
3218 :type 'sexp)
3219 (make-variable-buffer-local 'org-display-custom-times)
3221 (defcustom org-time-stamp-custom-formats
3222 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3223 "Custom formats for time stamps. See `format-time-string' for the syntax.
3224 These are overlaid over the default ISO format if the variable
3225 `org-display-custom-times' is set. Time like %H:%M should be at the
3226 end of the second format. The custom formats are also honored by export
3227 commands, if custom time display is turned on at the time of export."
3228 :group 'org-time
3229 :type 'sexp)
3231 (defun org-time-stamp-format (&optional long inactive)
3232 "Get the right format for a time string."
3233 (let ((f (if long (cdr org-time-stamp-formats)
3234 (car org-time-stamp-formats))))
3235 (if inactive
3236 (concat "[" (substring f 1 -1) "]")
3237 f)))
3239 (defcustom org-deadline-warning-days 14
3240 "Number of days before expiration during which a deadline becomes active.
3241 This variable governs the display in sparse trees and in the agenda.
3242 When 0 or negative, it means use this number (the absolute value of it)
3243 even if a deadline has a different individual lead time specified.
3245 Custom commands can set this variable in the options section."
3246 :group 'org-time
3247 :group 'org-agenda-daily/weekly
3248 :type 'integer)
3250 (defcustom org-scheduled-delay-days 0
3251 "Number of days before a scheduled item becomes active.
3252 This variable governs the display in sparse trees and in the agenda.
3253 The default value (i.e. 0) means: don't delay scheduled item.
3254 When negative, it means use this number (the absolute value of it)
3255 even if a scheduled item has a different individual delay time
3256 specified.
3258 Custom commands can set this variable in the options section."
3259 :group 'org-time
3260 :group 'org-agenda-daily/weekly
3261 :version "24.4"
3262 :package-version '(Org . "8.0")
3263 :type 'integer)
3265 (defcustom org-read-date-prefer-future t
3266 "Non-nil means assume future for incomplete date input from user.
3267 This affects the following situations:
3268 1. The user gives a month but not a year.
3269 For example, if it is April and you enter \"feb 2\", this will be read
3270 as Feb 2, *next* year. \"May 5\", however, will be this year.
3271 2. The user gives a day, but no month.
3272 For example, if today is the 15th, and you enter \"3\", Org will read
3273 this as the third of *next* month. However, if you enter \"17\",
3274 it will be considered as *this* month.
3276 If you set this variable to the symbol `time', then also the following
3277 will work:
3279 3. If the user gives a time.
3280 If the time is before now, it will be interpreted as tomorrow.
3282 Currently none of this works for ISO week specifications.
3284 When this option is nil, the current day, month and year will always be
3285 used as defaults.
3287 See also `org-agenda-jump-prefer-future'."
3288 :group 'org-time
3289 :type '(choice
3290 (const :tag "Never" nil)
3291 (const :tag "Check month and day" t)
3292 (const :tag "Check month, day, and time" time)))
3294 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3295 "Should the agenda jump command prefer the future for incomplete dates?
3296 The default is to do the same as configured in `org-read-date-prefer-future'.
3297 But you can also set a deviating value here.
3298 This may t or nil, or the symbol `org-read-date-prefer-future'."
3299 :group 'org-agenda
3300 :group 'org-time
3301 :version "24.1"
3302 :type '(choice
3303 (const :tag "Use org-read-date-prefer-future"
3304 org-read-date-prefer-future)
3305 (const :tag "Never" nil)
3306 (const :tag "Always" t)))
3308 (defcustom org-read-date-force-compatible-dates t
3309 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3311 Depending on the system Emacs is running on, certain dates cannot
3312 be represented with the type used internally to represent time.
3313 Dates between 1970-1-1 and 2038-1-1 can always be represented
3314 correctly. Some systems allow for earlier dates, some for later,
3315 some for both. One way to find out it to insert any date into an
3316 Org buffer, putting the cursor on the year and hitting S-up and
3317 S-down to test the range.
3319 When this variable is set to t, the date/time prompt will not let
3320 you specify dates outside the 1970-2037 range, so it is certain that
3321 these dates will work in whatever version of Emacs you are
3322 running, and also that you can move a file from one Emacs implementation
3323 to another. WHenever Org is forcing the year for you, it will display
3324 a message and beep.
3326 When this variable is nil, Org will check if the date is
3327 representable in the specific Emacs implementation you are using.
3328 If not, it will force a year, usually the current year, and beep
3329 to remind you. Currently this setting is not recommended because
3330 the likelihood that you will open your Org files in an Emacs that
3331 has limited date range is not negligible.
3333 A workaround for this problem is to use diary sexp dates for time
3334 stamps outside of this range."
3335 :group 'org-time
3336 :version "24.1"
3337 :type 'boolean)
3339 (defcustom org-read-date-display-live t
3340 "Non-nil means display current interpretation of date prompt live.
3341 This display will be in an overlay, in the minibuffer."
3342 :group 'org-time
3343 :type 'boolean)
3345 (defcustom org-read-date-popup-calendar t
3346 "Non-nil means pop up a calendar when prompting for a date.
3347 In the calendar, the date can be selected with mouse-1. However, the
3348 minibuffer will also be active, and you can simply enter the date as well.
3349 When nil, only the minibuffer will be available."
3350 :group 'org-time
3351 :type 'boolean)
3352 (defvaralias 'org-popup-calendar-for-date-prompt
3353 'org-read-date-popup-calendar)
3355 (defcustom org-extend-today-until 0
3356 "The hour when your day really ends. Must be an integer.
3357 This has influence for the following applications:
3358 - When switching the agenda to \"today\". It it is still earlier than
3359 the time given here, the day recognized as TODAY is actually yesterday.
3360 - When a date is read from the user and it is still before the time given
3361 here, the current date and time will be assumed to be yesterday, 23:59.
3362 Also, timestamps inserted in capture templates follow this rule.
3364 IMPORTANT: This is a feature whose implementation is and likely will
3365 remain incomplete. Really, it is only here because past midnight seems to
3366 be the favorite working time of John Wiegley :-)"
3367 :group 'org-time
3368 :type 'integer)
3370 (defcustom org-use-effective-time nil
3371 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3372 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3373 \"effective time\" of any timestamps between midnight and 8am will be
3374 23:59 of the previous day."
3375 :group 'org-time
3376 :version "24.1"
3377 :type 'boolean)
3379 (defcustom org-use-last-clock-out-time-as-effective-time nil
3380 "When non-nil, use the last clock out time for `org-todo'.
3381 Note that this option has precedence over the combined use of
3382 `org-use-effective-time' and `org-extend-today-until'."
3383 :group 'org-time
3384 :version "24.4"
3385 :package-version '(Org . "8.0")
3386 :type 'boolean)
3388 (defcustom org-edit-timestamp-down-means-later nil
3389 "Non-nil means S-down will increase the time in a time stamp.
3390 When nil, S-up will increase."
3391 :group 'org-time
3392 :type 'boolean)
3394 (defcustom org-calendar-follow-timestamp-change t
3395 "Non-nil means make the calendar window follow timestamp changes.
3396 When a timestamp is modified and the calendar window is visible, it will be
3397 moved to the new date."
3398 :group 'org-time
3399 :type 'boolean)
3401 (defgroup org-tags nil
3402 "Options concerning tags in Org mode."
3403 :tag "Org Tags"
3404 :group 'org)
3406 (defcustom org-tag-alist nil
3407 "Default tags available in Org files.
3409 The value of this variable is an alist. Associations either:
3411 (TAG)
3412 (TAG . SELECT)
3413 (SPECIAL)
3415 where TAG is a tag as a string, SELECT is character, used to
3416 select that tag through the fast tag selection interface, and
3417 SPECIAL is one of the following keywords: `:startgroup',
3418 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3419 `:newline'. These keywords are used to define a hierarchy of
3420 tags. See manual for details.
3422 When this variable is nil, Org mode bases tag input on what is
3423 already in the buffer. The value can be overridden locally by
3424 using a TAGS keyword, e.g.,
3426 #+TAGS: tag1 tag2
3428 See also `org-tag-persistent-alist' to sidestep this behavior."
3429 :group 'org-tags
3430 :type '(repeat
3431 (choice
3432 (cons :tag "Tag with key"
3433 (string :tag "Tag name")
3434 (character :tag "Access char"))
3435 (list :tag "Tag" (string :tag "Tag name"))
3436 (const :tag "Start radio group" (:startgroup))
3437 (const :tag "Start tag group, non distinct" (:startgrouptag))
3438 (const :tag "Group tags delimiter" (:grouptags))
3439 (const :tag "End radio group" (:endgroup))
3440 (const :tag "End tag group, non distinct" (:endgrouptag))
3441 (const :tag "New line" (:newline)))))
3443 (defcustom org-tag-persistent-alist nil
3444 "Tags always available in Org files.
3446 The value of this variable is an alist. Associations either:
3448 (TAG)
3449 (TAG . SELECT)
3450 (SPECIAL)
3452 where TAG is a tag as a string, SELECT is a character, used to
3453 select that tag through the fast tag selection interface, and
3454 SPECIAL is one of the following keywords: `:startgroup',
3455 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3456 `:newline'. These keywords are used to define a hierarchy of
3457 tags. See manual for details.
3459 Unlike to `org-tag-alist', tags defined in this variable do not
3460 depend on a local TAGS keyword. Instead, to disable these tags
3461 on a per-file basis, insert anywhere in the file:
3463 #+STARTUP: noptag"
3464 :group 'org-tags
3465 :type '(repeat
3466 (choice
3467 (cons :tag "Tag with key"
3468 (string :tag "Tag name")
3469 (character :tag "Access char"))
3470 (list :tag "Tag" (string :tag "Tag name"))
3471 (const :tag "Start radio group" (:startgroup))
3472 (const :tag "Start tag group, non distinct" (:startgrouptag))
3473 (const :tag "Group tags delimiter" (:grouptags))
3474 (const :tag "End radio group" (:endgroup))
3475 (const :tag "End tag group, non distinct" (:endgrouptag))
3476 (const :tag "New line" (:newline)))))
3478 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3479 "If non-nil, always offer completion for all tags of all agenda files.
3480 Instead of customizing this variable directly, you might want to
3481 set it locally for capture buffers, because there no list of
3482 tags in that file can be created dynamically (there are none).
3484 (add-hook \\='org-capture-mode-hook
3485 (lambda ()
3486 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3487 :group 'org-tags
3488 :version "24.1"
3489 :type 'boolean)
3491 (defvar org-file-tags nil
3492 "List of tags that can be inherited by all entries in the file.
3493 The tags will be inherited if the variable `org-use-tag-inheritance'
3494 says they should be.
3495 This variable is populated from #+FILETAGS lines.")
3497 (defcustom org-use-fast-tag-selection 'auto
3498 "Non-nil means use fast tag selection scheme.
3499 This is a special interface to select and deselect tags with single keys.
3500 When nil, fast selection is never used.
3501 When the symbol `auto', fast selection is used if and only if selection
3502 characters for tags have been configured, either through the variable
3503 `org-tag-alist' or through a #+TAGS line in the buffer.
3504 When t, fast selection is always used and selection keys are assigned
3505 automatically if necessary."
3506 :group 'org-tags
3507 :type '(choice
3508 (const :tag "Always" t)
3509 (const :tag "Never" nil)
3510 (const :tag "When selection characters are configured" auto)))
3512 (defcustom org-fast-tag-selection-single-key nil
3513 "Non-nil means fast tag selection exits after first change.
3514 When nil, you have to press RET to exit it.
3515 During fast tag selection, you can toggle this flag with `C-c'.
3516 This variable can also have the value `expert'. In this case, the window
3517 displaying the tags menu is not even shown, until you press C-c again."
3518 :group 'org-tags
3519 :type '(choice
3520 (const :tag "No" nil)
3521 (const :tag "Yes" t)
3522 (const :tag "Expert" expert)))
3524 (defvar org-fast-tag-selection-include-todo nil
3525 "Non-nil means fast tags selection interface will also offer TODO states.
3526 This is an undocumented feature, you should not rely on it.")
3528 (defcustom org-tags-column -77
3529 "The column to which tags should be indented in a headline.
3530 If this number is positive, it specifies the column. If it is negative,
3531 it means that the tags should be flushright to that column. For example,
3532 -80 works well for a normal 80 character screen.
3533 When 0, place tags directly after headline text, with only one space in
3534 between."
3535 :group 'org-tags
3536 :type 'integer)
3538 (defcustom org-auto-align-tags t
3539 "Non-nil keeps tags aligned when modifying headlines.
3540 Some operations (i.e. demoting) change the length of a headline and
3541 therefore shift the tags around. With this option turned on, after
3542 each such operation the tags are again aligned to `org-tags-column'."
3543 :group 'org-tags
3544 :type 'boolean)
3546 (defcustom org-use-tag-inheritance t
3547 "Non-nil means tags in levels apply also for sublevels.
3548 When nil, only the tags directly given in a specific line apply there.
3549 This may also be a list of tags that should be inherited, or a regexp that
3550 matches tags that should be inherited. Additional control is possible
3551 with the variable `org-tags-exclude-from-inheritance' which gives an
3552 explicit list of tags to be excluded from inheritance, even if the value of
3553 `org-use-tag-inheritance' would select it for inheritance.
3555 If this option is t, a match early-on in a tree can lead to a large
3556 number of matches in the subtree when constructing the agenda or creating
3557 a sparse tree. If you only want to see the first match in a tree during
3558 a search, check out the variable `org-tags-match-list-sublevels'."
3559 :group 'org-tags
3560 :type '(choice
3561 (const :tag "Not" nil)
3562 (const :tag "Always" t)
3563 (repeat :tag "Specific tags" (string :tag "Tag"))
3564 (regexp :tag "Tags matched by regexp")))
3566 (defcustom org-tags-exclude-from-inheritance nil
3567 "List of tags that should never be inherited.
3568 This is a way to exclude a few tags from inheritance. For way to do
3569 the opposite, to actively allow inheritance for selected tags,
3570 see the variable `org-use-tag-inheritance'."
3571 :group 'org-tags
3572 :type '(repeat (string :tag "Tag")))
3574 (defun org-tag-inherit-p (tag)
3575 "Check if TAG is one that should be inherited."
3576 (cond
3577 ((member tag org-tags-exclude-from-inheritance) nil)
3578 ((eq org-use-tag-inheritance t) t)
3579 ((not org-use-tag-inheritance) nil)
3580 ((stringp org-use-tag-inheritance)
3581 (string-match org-use-tag-inheritance tag))
3582 ((listp org-use-tag-inheritance)
3583 (member tag org-use-tag-inheritance))
3584 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3586 (defcustom org-tags-match-list-sublevels t
3587 "Non-nil means list also sublevels of headlines matching a search.
3588 This variable applies to tags/property searches, and also to stuck
3589 projects because this search is based on a tags match as well.
3591 When set to the symbol `indented', sublevels are indented with
3592 leading dots.
3594 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3595 the sublevels of a headline matching a tag search often also match
3596 the same search. Listing all of them can create very long lists.
3597 Setting this variable to nil causes subtrees of a match to be skipped.
3599 This variable is semi-obsolete and probably should always be true. It
3600 is better to limit inheritance to certain tags using the variables
3601 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3602 :group 'org-tags
3603 :type '(choice
3604 (const :tag "No, don't list them" nil)
3605 (const :tag "Yes, do list them" t)
3606 (const :tag "List them, indented with leading dots" indented)))
3608 (defcustom org-tags-sort-function nil
3609 "When set, tags are sorted using this function as a comparator."
3610 :group 'org-tags
3611 :type '(choice
3612 (const :tag "No sorting" nil)
3613 (const :tag "Alphabetical" string<)
3614 (const :tag "Reverse alphabetical" string>)
3615 (function :tag "Custom function" nil)))
3617 (defvar org-tags-history nil
3618 "History of minibuffer reads for tags.")
3619 (defvar org-last-tags-completion-table nil
3620 "The last used completion table for tags.")
3621 (defvar org-after-tags-change-hook nil
3622 "Hook that is run after the tags in a line have changed.")
3624 (defgroup org-properties nil
3625 "Options concerning properties in Org mode."
3626 :tag "Org Properties"
3627 :group 'org)
3629 (defcustom org-property-format "%-10s %s"
3630 "How property key/value pairs should be formatted by `indent-line'.
3631 When `indent-line' hits a property definition, it will format the line
3632 according to this format, mainly to make sure that the values are
3633 lined-up with respect to each other."
3634 :group 'org-properties
3635 :type 'string)
3637 (defcustom org-properties-postprocess-alist nil
3638 "Alist of properties and functions to adjust inserted values.
3639 Elements of this alist must be of the form
3641 ([string] [function])
3643 where [string] must be a property name and [function] must be a
3644 lambda expression: this lambda expression must take one argument,
3645 the value to adjust, and return the new value as a string.
3647 For example, this element will allow the property \"Remaining\"
3648 to be updated wrt the relation between the \"Effort\" property
3649 and the clock summary:
3651 ((\"Remaining\" (lambda(value)
3652 (let ((clocksum (org-clock-sum-current-item))
3653 (effort (org-duration-to-minutes
3654 (org-entry-get (point) \"Effort\"))))
3655 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3656 :group 'org-properties
3657 :version "24.1"
3658 :type '(alist :key-type (string :tag "Property")
3659 :value-type (function :tag "Function")))
3661 (defcustom org-use-property-inheritance nil
3662 "Non-nil means properties apply also for sublevels.
3664 This setting is chiefly used during property searches. Turning it on can
3665 cause significant overhead when doing a search, which is why it is not
3666 on by default.
3668 When nil, only the properties directly given in the current entry count.
3669 When t, every property is inherited. The value may also be a list of
3670 properties that should have inheritance, or a regular expression matching
3671 properties that should be inherited.
3673 However, note that some special properties use inheritance under special
3674 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3675 and the properties ending in \"_ALL\" when they are used as descriptor
3676 for valid values of a property.
3678 Note for programmers:
3679 When querying an entry with `org-entry-get', you can control if inheritance
3680 should be used. By default, `org-entry-get' looks only at the local
3681 properties. You can request inheritance by setting the inherit argument
3682 to t (to force inheritance) or to `selective' (to respect the setting
3683 in this variable)."
3684 :group 'org-properties
3685 :type '(choice
3686 (const :tag "Not" nil)
3687 (const :tag "Always" t)
3688 (repeat :tag "Specific properties" (string :tag "Property"))
3689 (regexp :tag "Properties matched by regexp")))
3691 (defun org-property-inherit-p (property)
3692 "Return a non-nil value if PROPERTY should be inherited."
3693 (cond
3694 ((eq org-use-property-inheritance t) t)
3695 ((not org-use-property-inheritance) nil)
3696 ((stringp org-use-property-inheritance)
3697 (string-match org-use-property-inheritance property))
3698 ((listp org-use-property-inheritance)
3699 (member-ignore-case property org-use-property-inheritance))
3700 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3702 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3703 "The default column format, if no other format has been defined.
3704 This variable can be set on the per-file basis by inserting a line
3706 #+COLUMNS: %25ITEM ....."
3707 :group 'org-properties
3708 :type 'string)
3710 (defcustom org-columns-ellipses ".."
3711 "The ellipses to be used when a field in column view is truncated.
3712 When this is the empty string, as many characters as possible are shown,
3713 but then there will be no visual indication that the field has been truncated.
3714 When this is a string of length N, the last N characters of a truncated
3715 field are replaced by this string. If the column is narrower than the
3716 ellipses string, only part of the ellipses string will be shown."
3717 :group 'org-properties
3718 :type 'string)
3720 (defconst org-global-properties-fixed
3721 '(("VISIBILITY_ALL" . "folded children content all")
3722 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3723 "List of property/value pairs that can be inherited by any entry.
3725 These are fixed values, for the preset properties. The user variable
3726 that can be used to add to this list is `org-global-properties'.
3728 The entries in this list are cons cells where the car is a property
3729 name and cdr is a string with the value. If the value represents
3730 multiple items like an \"_ALL\" property, separate the items by
3731 spaces.")
3733 (defcustom org-global-properties nil
3734 "List of property/value pairs that can be inherited by any entry.
3736 This list will be combined with the constant `org-global-properties-fixed'.
3738 The entries in this list are cons cells where the car is a property
3739 name and cdr is a string with the value.
3741 You can set buffer-local values for the same purpose in the variable
3742 `org-file-properties' this by adding lines like
3744 #+PROPERTY: NAME VALUE"
3745 :group 'org-properties
3746 :type '(repeat
3747 (cons (string :tag "Property")
3748 (string :tag "Value"))))
3750 (defvar-local org-file-properties nil
3751 "List of property/value pairs that can be inherited by any entry.
3752 Valid for the current buffer.
3753 This variable is populated from #+PROPERTY lines.")
3755 (defgroup org-agenda nil
3756 "Options concerning agenda views in Org mode."
3757 :tag "Org Agenda"
3758 :group 'org)
3760 (defvar-local org-category nil
3761 "Variable used by Org files to set a category for agenda display.
3762 Such files should use a file variable to set it, for example
3764 # -*- mode: org; org-category: \"ELisp\"
3766 or contain a special line
3768 #+CATEGORY: ELisp
3770 If the file does not specify a category, then file's base name
3771 is used instead.")
3772 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3774 (defcustom org-agenda-files nil
3775 "The files to be used for agenda display.
3777 If an entry is a directory, all files in that directory that are matched
3778 by `org-agenda-file-regexp' will be part of the file list.
3780 If the value of the variable is not a list but a single file name, then
3781 the list of agenda files is actually stored and maintained in that file,
3782 one agenda file per line. In this file paths can be given relative to
3783 `org-directory'. Tilde expansion and environment variable substitution
3784 are also made.
3786 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3787 and removed with `\\[org-remove-file]'."
3788 :group 'org-agenda
3789 :type '(choice
3790 (repeat :tag "List of files and directories" file)
3791 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3793 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3794 "Regular expression to match files for `org-agenda-files'.
3795 If any element in the list in that variable contains a directory instead
3796 of a normal file, all files in that directory that are matched by this
3797 regular expression will be included."
3798 :group 'org-agenda
3799 :type 'regexp)
3801 (defcustom org-agenda-text-search-extra-files nil
3802 "List of extra files to be searched by text search commands.
3803 These files will be searched in addition to the agenda files by the
3804 commands `org-search-view' (`\\[org-agenda] s') \
3805 and `org-occur-in-agenda-files'.
3806 Note that these files will only be searched for text search commands,
3807 not for the other agenda views like todo lists, tag searches or the weekly
3808 agenda. This variable is intended to list notes and possibly archive files
3809 that should also be searched by these two commands.
3810 In fact, if the first element in the list is the symbol `agenda-archives',
3811 then all archive files of all agenda files will be added to the search
3812 scope."
3813 :group 'org-agenda
3814 :type '(set :greedy t
3815 (const :tag "Agenda Archives" agenda-archives)
3816 (repeat :inline t (file))))
3818 (defvaralias 'org-agenda-multi-occur-extra-files
3819 'org-agenda-text-search-extra-files)
3821 (defcustom org-agenda-skip-unavailable-files nil
3822 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3823 A nil value means to remove them, after a query, from the list."
3824 :group 'org-agenda
3825 :type 'boolean)
3827 (defcustom org-calendar-to-agenda-key [?c]
3828 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3829 The command `org-calendar-goto-agenda' will be bound to this key. The
3830 default is the character `c' because then `c' can be used to switch back and
3831 forth between agenda and calendar."
3832 :group 'org-agenda
3833 :type 'sexp)
3835 (defcustom org-calendar-insert-diary-entry-key [?i]
3836 "The key to be installed in `calendar-mode-map' for adding diary entries.
3837 This option is irrelevant until `org-agenda-diary-file' has been configured
3838 to point to an Org file. When that is the case, the command
3839 `org-agenda-diary-entry' will be bound to the key given here, by default
3840 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3841 if you want to continue doing this, you need to change this to a different
3842 key."
3843 :group 'org-agenda
3844 :type 'sexp)
3846 (defcustom org-agenda-diary-file 'diary-file
3847 "File to which to add new entries with the `i' key in agenda and calendar.
3848 When this is the symbol `diary-file', the functionality in the Emacs
3849 calendar will be used to add entries to the `diary-file'. But when this
3850 points to a file, `org-agenda-diary-entry' will be used instead."
3851 :group 'org-agenda
3852 :type '(choice
3853 (const :tag "The standard Emacs diary file" diary-file)
3854 (file :tag "Special Org file diary entries")))
3856 (eval-after-load "calendar"
3857 '(progn
3858 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3859 'org-calendar-goto-agenda)
3860 (add-hook 'calendar-mode-hook
3861 (lambda ()
3862 (unless (eq org-agenda-diary-file 'diary-file)
3863 (define-key calendar-mode-map
3864 org-calendar-insert-diary-entry-key
3865 'org-agenda-diary-entry))))))
3867 (defgroup org-latex nil
3868 "Options for embedding LaTeX code into Org mode."
3869 :tag "Org LaTeX"
3870 :group 'org)
3872 (defcustom org-format-latex-options
3873 '(:foreground default :background default :scale 1.0
3874 :html-foreground "Black" :html-background "Transparent"
3875 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3876 "Options for creating images from LaTeX fragments.
3877 This is a property list with the following properties:
3878 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3879 `default' means use the foreground of the default face.
3880 `auto' means use the foreground from the text face.
3881 :background the background color, or \"Transparent\".
3882 `default' means use the background of the default face.
3883 `auto' means use the background from the text face.
3884 :scale a scaling factor for the size of the images, to get more pixels
3885 :html-foreground, :html-background, :html-scale
3886 the same numbers for HTML export.
3887 :matchers a list indicating which matchers should be used to
3888 find LaTeX fragments. Valid members of this list are:
3889 \"begin\" find environments
3890 \"$1\" find single characters surrounded by $.$
3891 \"$\" find math expressions surrounded by $...$
3892 \"$$\" find math expressions surrounded by $$....$$
3893 \"\\(\" find math expressions surrounded by \\(...\\)
3894 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3895 :group 'org-latex
3896 :type 'plist)
3898 (defcustom org-format-latex-signal-error t
3899 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3900 When nil, just push out a message."
3901 :group 'org-latex
3902 :version "24.1"
3903 :type 'boolean)
3905 (defcustom org-latex-to-mathml-jar-file nil
3906 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3907 Use this to specify additional executable file say a jar file.
3909 When using MathToWeb as the converter, specify the full-path to
3910 your mathtoweb.jar file."
3911 :group 'org-latex
3912 :version "24.1"
3913 :type '(choice
3914 (const :tag "None" nil)
3915 (file :tag "JAR file" :must-match t)))
3917 (defcustom org-latex-to-mathml-convert-command nil
3918 "Command to convert LaTeX fragments to MathML.
3919 Replace format-specifiers in the command as noted below and use
3920 `shell-command' to convert LaTeX to MathML.
3921 %j: Executable file in fully expanded form as specified by
3922 `org-latex-to-mathml-jar-file'.
3923 %I: Input LaTeX file in fully expanded form.
3924 %i: The latex fragment to be converted.
3925 %o: Output MathML file.
3927 This command is used by `org-create-math-formula'.
3929 When using MathToWeb as the converter, set this option to
3930 \"java -jar %j -unicode -force -df %o %I\".
3932 When using LaTeXML set this option to
3933 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3934 :group 'org-latex
3935 :version "24.1"
3936 :type '(choice
3937 (const :tag "None" nil)
3938 (string :tag "\nShell command")))
3940 (defcustom org-preview-latex-default-process 'dvipng
3941 "The default process to convert LaTeX fragments to image files.
3942 All available processes and theirs documents can be found in
3943 `org-preview-latex-process-alist', which see."
3944 :group 'org-latex
3945 :version "26.1"
3946 :package-version '(Org . "9.0")
3947 :type 'symbol)
3949 (defcustom org-preview-latex-process-alist
3950 '((dvipng
3951 :programs ("latex" "dvipng")
3952 :description "dvi > png"
3953 :message "you need to install the programs: latex and dvipng."
3954 :image-input-type "dvi"
3955 :image-output-type "png"
3956 :image-size-adjust (1.0 . 1.0)
3957 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3958 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3959 (dvisvgm
3960 :programs ("latex" "dvisvgm")
3961 :description "dvi > svg"
3962 :message "you need to install the programs: latex and dvisvgm."
3963 :use-xcolor t
3964 :image-input-type "dvi"
3965 :image-output-type "svg"
3966 :image-size-adjust (1.7 . 1.5)
3967 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3968 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3969 (imagemagick
3970 :programs ("latex" "convert")
3971 :description "pdf > png"
3972 :message "you need to install the programs: latex and imagemagick."
3973 :use-xcolor t
3974 :image-input-type "pdf"
3975 :image-output-type "png"
3976 :image-size-adjust (1.0 . 1.0)
3977 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3978 :image-converter
3979 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3980 "Definitions of external processes for LaTeX previewing.
3981 Org mode can use some external commands to generate TeX snippet's images for
3982 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3983 `org-create-formula-image' how to call them.
3985 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3986 PROPERTIES accepts the following attributes:
3988 :programs list of strings, required programs.
3989 :description string, describe the process.
3990 :message string, message it when required programs cannot be found.
3991 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3992 :image-output-type string, output file type of image converter (e.g., \"png\").
3993 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3994 deal with background and foreground color of image.
3995 Otherwise, dvipng style background and foreground color
3996 format are generated. You may then refer to them in
3997 command options with \"%F\" and \"%B\".
3998 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3999 image size showed in buffer and the cdr element is for
4000 HTML file. This option is only useful for process
4001 developers, users should use variable
4002 `org-format-latex-options' instead.
4003 :post-clean list of strings, files matched are to be cleaned up once
4004 the image is generated. When nil, the files with \".dvi\",
4005 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4006 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4007 be cleaned up.
4008 :latex-header list of strings, the LaTeX header of the snippet file.
4009 When nil, the fallback value is used instead, which is
4010 controlled by `org-format-latex-header',
4011 `org-latex-default-packages-alist' and
4012 `org-latex-packages-alist', which see.
4013 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4014 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4015 replaced with values defined below.
4016 :image-converter list of image converter commands strings. Each of them is
4017 given to the shell and supports any of the following
4018 place-holders defined below.
4020 Place-holders used by `:image-converter' and `:latex-compiler':
4022 %f input file name
4023 %b base name of input file
4024 %o base directory of input file
4025 %O absolute output file name
4027 Place-holders only used by `:image-converter':
4029 %F foreground of image
4030 %B background of image
4031 %D dpi, which is used to adjust image size by some processing commands.
4032 %S the image size scale ratio, which is used to adjust image size by some
4033 processing commands."
4034 :group 'org-latex
4035 :version "26.1"
4036 :package-version '(Org . "9.0")
4037 :type '(alist :tag "LaTeX to image backends"
4038 :value-type (plist)))
4040 (defcustom org-preview-latex-image-directory "ltximg/"
4041 "Path to store latex preview images.
4042 A relative path here creates many directories relative to the
4043 processed Org files paths. An absolute path puts all preview
4044 images at the same place."
4045 :group 'org-latex
4046 :version "26.1"
4047 :package-version '(Org . "9.0")
4048 :type 'string)
4050 (defun org-format-latex-mathml-available-p ()
4051 "Return t if `org-latex-to-mathml-convert-command' is usable."
4052 (save-match-data
4053 (when (and (boundp 'org-latex-to-mathml-convert-command)
4054 org-latex-to-mathml-convert-command)
4055 (let ((executable (car (split-string
4056 org-latex-to-mathml-convert-command))))
4057 (when (executable-find executable)
4058 (if (string-match
4059 "%j" org-latex-to-mathml-convert-command)
4060 (file-readable-p org-latex-to-mathml-jar-file)
4061 t))))))
4063 (defcustom org-format-latex-header "\\documentclass{article}
4064 \\usepackage[usenames]{color}
4065 \[PACKAGES]
4066 \[DEFAULT-PACKAGES]
4067 \\pagestyle{empty} % do not remove
4068 % The settings below are copied from fullpage.sty
4069 \\setlength{\\textwidth}{\\paperwidth}
4070 \\addtolength{\\textwidth}{-3cm}
4071 \\setlength{\\oddsidemargin}{1.5cm}
4072 \\addtolength{\\oddsidemargin}{-2.54cm}
4073 \\setlength{\\evensidemargin}{\\oddsidemargin}
4074 \\setlength{\\textheight}{\\paperheight}
4075 \\addtolength{\\textheight}{-\\headheight}
4076 \\addtolength{\\textheight}{-\\headsep}
4077 \\addtolength{\\textheight}{-\\footskip}
4078 \\addtolength{\\textheight}{-3cm}
4079 \\setlength{\\topmargin}{1.5cm}
4080 \\addtolength{\\topmargin}{-2.54cm}"
4081 "The document header used for processing LaTeX fragments.
4082 It is imperative that this header make sure that no page number
4083 appears on the page. The package defined in the variables
4084 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4085 will either replace the placeholder \"[PACKAGES]\" in this
4086 header, or they will be appended."
4087 :group 'org-latex
4088 :type 'string)
4090 (defun org-set-packages-alist (var val)
4091 "Set the packages alist and make sure it has 3 elements per entry."
4092 (set var (mapcar (lambda (x)
4093 (if (and (consp x) (= (length x) 2))
4094 (list (car x) (nth 1 x) t)
4096 val)))
4098 (defun org-get-packages-alist (var)
4099 "Get the packages alist and make sure it has 3 elements per entry."
4100 (mapcar (lambda (x)
4101 (if (and (consp x) (= (length x) 2))
4102 (list (car x) (nth 1 x) t)
4104 (default-value var)))
4106 (defcustom org-latex-default-packages-alist
4107 '(("AUTO" "inputenc" t ("pdflatex"))
4108 ("T1" "fontenc" t ("pdflatex"))
4109 ("" "graphicx" t)
4110 ("" "grffile" t)
4111 ("" "longtable" nil)
4112 ("" "wrapfig" nil)
4113 ("" "rotating" nil)
4114 ("normalem" "ulem" t)
4115 ("" "amsmath" t)
4116 ("" "textcomp" t)
4117 ("" "amssymb" t)
4118 ("" "capt-of" nil)
4119 ("" "hyperref" nil))
4120 "Alist of default packages to be inserted in the header.
4122 Change this only if one of the packages here causes an
4123 incompatibility with another package you are using.
4125 The packages in this list are needed by one part or another of
4126 Org mode to function properly:
4128 - inputenc, fontenc: for basic font and character selection
4129 - graphicx: for including images
4130 - grffile: allow periods and spaces in graphics file names
4131 - longtable: For multipage tables
4132 - wrapfig: for figure placement
4133 - rotating: for sideways figures and tables
4134 - ulem: for underline and strike-through
4135 - amsmath: for subscript and superscript and math environments
4136 - textcomp, amssymb: for various symbols used
4137 for interpreting the entities in `org-entities'. You can skip
4138 some of these packages if you don't use any of their symbols.
4139 - capt-of: for captions outside of floats
4140 - hyperref: for cross references
4142 Therefore you should not modify this variable unless you know
4143 what you are doing. The one reason to change it anyway is that
4144 you might be loading some other package that conflicts with one
4145 of the default packages. Each element is either a cell or
4146 a string.
4148 A cell is of the format
4150 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4152 If SNIPPET-FLAG is non-nil, the package also needs to be included
4153 when compiling LaTeX snippets into images for inclusion into
4154 non-LaTeX output. COMPILERS is a list of compilers that should
4155 include the package, see `org-latex-compiler'. If the document
4156 compiler is not in the list, and the list is non-nil, the package
4157 will not be inserted in the final document.
4159 A string will be inserted as-is in the header of the document."
4160 :group 'org-latex
4161 :group 'org-export-latex
4162 :set 'org-set-packages-alist
4163 :get 'org-get-packages-alist
4164 :version "26.1"
4165 :package-version '(Org . "8.3")
4166 :type '(repeat
4167 (choice
4168 (list :tag "options/package pair"
4169 (string :tag "options")
4170 (string :tag "package")
4171 (boolean :tag "Snippet")
4172 (choice
4173 (const :tag "For all compilers" nil)
4174 (repeat :tag "Allowed compiler" string)))
4175 (string :tag "A line of LaTeX"))))
4177 (defcustom org-latex-packages-alist nil
4178 "Alist of packages to be inserted in every LaTeX header.
4180 These will be inserted after `org-latex-default-packages-alist'.
4181 Each element is either a cell or a string.
4183 A cell is of the format:
4185 (\"options\" \"package\" SNIPPET-FLAG)
4187 SNIPPET-FLAG, when non-nil, indicates that this package is also
4188 needed when turning LaTeX snippets into images for inclusion into
4189 non-LaTeX output.
4191 A string will be inserted as-is in the header of the document.
4193 Make sure that you only list packages here which:
4195 - you want in every file;
4196 - do not conflict with the setup in `org-format-latex-header';
4197 - do not conflict with the default packages in
4198 `org-latex-default-packages-alist'."
4199 :group 'org-latex
4200 :group 'org-export-latex
4201 :set 'org-set-packages-alist
4202 :get 'org-get-packages-alist
4203 :type '(repeat
4204 (choice
4205 (list :tag "options/package pair"
4206 (string :tag "options")
4207 (string :tag "package")
4208 (boolean :tag "Snippet"))
4209 (string :tag "A line of LaTeX"))))
4211 (defgroup org-appearance nil
4212 "Settings for Org mode appearance."
4213 :tag "Org Appearance"
4214 :group 'org)
4216 (defcustom org-level-color-stars-only nil
4217 "Non-nil means fontify only the stars in each headline.
4218 When nil, the entire headline is fontified.
4219 Changing it requires restart of `font-lock-mode' to become effective
4220 also in regions already fontified."
4221 :group 'org-appearance
4222 :type 'boolean)
4224 (defcustom org-hide-leading-stars nil
4225 "Non-nil means hide the first N-1 stars in a headline.
4226 This works by using the face `org-hide' for these stars. This
4227 face is white for a light background, and black for a dark
4228 background. You may have to customize the face `org-hide' to
4229 make this work.
4230 Changing it requires restart of `font-lock-mode' to become effective
4231 also in regions already fontified.
4232 You may also set this on a per-file basis by adding one of the following
4233 lines to the buffer:
4235 #+STARTUP: hidestars
4236 #+STARTUP: showstars"
4237 :group 'org-appearance
4238 :type 'boolean)
4240 (defcustom org-hidden-keywords nil
4241 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4242 For example, a value \\='(title) for this list makes the document's title
4243 appear in the buffer without the initial \"#+TITLE:\" part."
4244 :group 'org-appearance
4245 :version "24.1"
4246 :type '(set (const :tag "#+AUTHOR" author)
4247 (const :tag "#+DATE" date)
4248 (const :tag "#+EMAIL" email)
4249 (const :tag "#+TITLE" title)))
4251 (defcustom org-custom-properties nil
4252 "List of properties (as strings) with a special meaning.
4253 The default use of these custom properties is to let the user
4254 hide them with `org-toggle-custom-properties-visibility'."
4255 :group 'org-properties
4256 :group 'org-appearance
4257 :version "24.3"
4258 :type '(repeat (string :tag "Property Name")))
4260 (defcustom org-fontify-done-headline nil
4261 "Non-nil means change the face of a headline if it is marked DONE.
4262 Normally, only the TODO/DONE keyword indicates the state of a headline.
4263 When this is non-nil, the headline after the keyword is set to the
4264 `org-headline-done' as an additional indication."
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-fontify-emphasized-text t
4269 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4270 Changing this variable requires a restart of Emacs to take effect."
4271 :group 'org-appearance
4272 :type 'boolean)
4274 (defcustom org-fontify-whole-heading-line nil
4275 "Non-nil means fontify the whole line for headings.
4276 This is useful when setting a background color for the
4277 org-level-* faces."
4278 :group 'org-appearance
4279 :type 'boolean)
4281 (defcustom org-highlight-latex-and-related nil
4282 "Non-nil means highlight LaTeX related syntax in the buffer.
4283 When non nil, the value should be a list containing any of the
4284 following symbols:
4285 `latex' Highlight LaTeX snippets and environments.
4286 `script' Highlight subscript and superscript.
4287 `entities' Highlight entities."
4288 :group 'org-appearance
4289 :version "24.4"
4290 :package-version '(Org . "8.0")
4291 :type '(choice
4292 (const :tag "No highlighting" nil)
4293 (set :greedy t :tag "Highlight"
4294 (const :tag "LaTeX snippets and environments" latex)
4295 (const :tag "Subscript and superscript" script)
4296 (const :tag "Entities" entities))))
4298 (defcustom org-hide-emphasis-markers nil
4299 "Non-nil mean font-lock should hide the emphasis marker characters."
4300 :group 'org-appearance
4301 :type 'boolean)
4303 (defcustom org-hide-macro-markers nil
4304 "Non-nil mean font-lock should hide the brackets marking macro calls."
4305 :group 'org-appearance
4306 :type 'boolean)
4308 (defcustom org-pretty-entities nil
4309 "Non-nil means show entities as UTF8 characters.
4310 When nil, the \\name form remains in the buffer."
4311 :group 'org-appearance
4312 :version "24.1"
4313 :type 'boolean)
4315 (defcustom org-pretty-entities-include-sub-superscripts t
4316 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4317 :group 'org-appearance
4318 :version "24.1"
4319 :type 'boolean)
4321 (defvar org-emph-re nil
4322 "Regular expression for matching emphasis.
4323 After a match, the match groups contain these elements:
4324 0 The match of the full regular expression, including the characters
4325 before and after the proper match
4326 1 The character before the proper match, or empty at beginning of line
4327 2 The proper match, including the leading and trailing markers
4328 3 The leading marker like * or /, indicating the type of highlighting
4329 4 The text between the emphasis markers, not including the markers
4330 5 The character after the match, empty at the end of a line")
4332 (defvar org-verbatim-re nil
4333 "Regular expression for matching verbatim text.")
4335 (defvar org-emphasis-regexp-components) ; defined just below
4336 (defvar org-emphasis-alist) ; defined just below
4337 (defun org-set-emph-re (var val)
4338 "Set variable and compute the emphasis regular expression."
4339 (set var val)
4340 (when (and (boundp 'org-emphasis-alist)
4341 (boundp 'org-emphasis-regexp-components)
4342 org-emphasis-alist org-emphasis-regexp-components)
4343 (pcase-let*
4344 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4345 (body (if (<= nl 0) body
4346 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4347 (template
4348 (format (concat "\\([%s]\\|^\\)" ;before markers
4349 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4350 "\\([%s]\\|$\\)") ;after markers
4351 pre border border body border post)))
4352 (setq org-emph-re (format template "*/_+"))
4353 (setq org-verbatim-re (format template "=~")))))
4355 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4356 ;; set this option proved cumbersome. See this message/thread:
4357 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4358 (defvar org-emphasis-regexp-components
4359 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4360 "Components used to build the regular expression for emphasis.
4361 This is a list with five entries. Terminology: In an emphasis string
4362 like \" *strong word* \", we call the initial space PREMATCH, the final
4363 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4364 and \"trong wor\" is the body. The different components in this variable
4365 specify what is allowed/forbidden in each part:
4367 pre Chars allowed as prematch. Beginning of line will be allowed too.
4368 post Chars allowed as postmatch. End of line will be allowed too.
4369 border The chars *forbidden* as border characters.
4370 body-regexp A regexp like \".\" to match a body character. Don't use
4371 non-shy groups here, and don't allow newline here.
4372 newline The maximum number of newlines allowed in an emphasis exp.
4374 You need to reload Org or to restart Emacs after customizing this.")
4376 (defcustom org-emphasis-alist
4377 '(("*" bold)
4378 ("/" italic)
4379 ("_" underline)
4380 ("=" org-verbatim verbatim)
4381 ("~" org-code verbatim)
4382 ("+" (:strike-through t)))
4383 "Alist of characters and faces to emphasize text.
4384 Text starting and ending with a special character will be emphasized,
4385 for example *bold*, _underlined_ and /italic/. This variable sets the
4386 marker characters and the face to be used by font-lock for highlighting
4387 in Org buffers.
4389 You need to reload Org or to restart Emacs after customizing this."
4390 :group 'org-appearance
4391 :set 'org-set-emph-re
4392 :version "24.4"
4393 :package-version '(Org . "8.0")
4394 :type '(repeat
4395 (list
4396 (string :tag "Marker character")
4397 (choice
4398 (face :tag "Font-lock-face")
4399 (plist :tag "Face property list"))
4400 (option (const verbatim)))))
4402 (defvar org-protecting-blocks '("src" "example" "export")
4403 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4404 This is needed for font-lock setup.")
4406 ;;; Functions and variables from their packages
4407 ;; Declared here to avoid compiler warnings
4408 (defvar mark-active)
4410 ;; Various packages
4411 (declare-function calc-eval "calc" (str &optional separator &rest args))
4412 (declare-function calendar-forward-day "cal-move" (arg))
4413 (declare-function calendar-goto-date "cal-move" (date))
4414 (declare-function calendar-goto-today "cal-move" ())
4415 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4416 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4417 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4418 (declare-function cdlatex-tab "ext:cdlatex" ())
4419 (declare-function dired-get-filename
4420 "dired"
4421 (&optional localp no-error-if-not-filep))
4422 (declare-function iswitchb-read-buffer
4423 "iswitchb"
4424 (prompt &optional
4425 default require-match _predicate start matches-set))
4426 (declare-function org-agenda-change-all-lines
4427 "org-agenda"
4428 (newhead hdmarker &optional fixface just-this))
4429 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4430 "org-agenda"
4431 (&optional end))
4432 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4433 (declare-function org-agenda-format-item
4434 "org-agenda"
4435 (extra txt &optional level category tags dotime
4436 remove-re habitp))
4437 (declare-function org-agenda-maybe-redo "org-agenda" ())
4438 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4439 (declare-function org-agenda-save-markers-for-cut-and-paste
4440 "org-agenda"
4441 (beg end))
4442 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4443 (declare-function org-agenda-skip "org-agenda" ())
4444 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4445 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4446 (declare-function org-indent-mode "org-indent" (&optional arg))
4447 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4448 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4449 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4450 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4451 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4452 (declare-function parse-time-string "parse-time" (string))
4453 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4455 (defvar align-mode-rules-list)
4456 (defvar calc-embedded-close-formula)
4457 (defvar calc-embedded-open-formula)
4458 (defvar calc-embedded-open-mode)
4459 (defvar font-lock-unfontify-region-function)
4460 (defvar iswitchb-temp-buflist)
4461 (defvar org-agenda-tags-todo-honor-ignore-options)
4462 (defvar remember-data-file)
4463 (defvar texmathp-why)
4465 ;;;###autoload
4466 (defun turn-on-orgtbl ()
4467 "Unconditionally turn on `orgtbl-mode'."
4468 (require 'org-table)
4469 (orgtbl-mode 1))
4471 (defun org-at-table-p (&optional table-type)
4472 "Non-nil if the cursor is inside an Org table.
4473 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4474 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4475 (or (not (derived-mode-p 'org-mode))
4476 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4477 (and e (or table-type
4478 (eq 'org (org-element-property :type e))))))))
4480 (defun org-at-table.el-p ()
4481 "Non-nil when point is at a table.el table."
4482 (and (org-match-line "[ \t]*[|+]")
4483 (let ((element (org-element-at-point)))
4484 (and (eq (org-element-type element) 'table)
4485 (eq (org-element-property :type element) 'table.el)))))
4487 (defun org-at-table-hline-p ()
4488 "Non-nil when point is inside a hline in a table.
4489 Assume point is already in a table."
4490 (org-match-line org-table-hline-regexp))
4492 (defun org-table-map-tables (function &optional quietly)
4493 "Apply FUNCTION to the start of all tables in the buffer."
4494 (org-with-wide-buffer
4495 (goto-char (point-min))
4496 (while (re-search-forward org-table-any-line-regexp nil t)
4497 (unless quietly
4498 (message "Mapping tables: %d%%"
4499 (floor (* 100.0 (point)) (buffer-size))))
4500 (beginning-of-line 1)
4501 (when (and (looking-at org-table-line-regexp)
4502 ;; Exclude tables in src/example/verbatim/clocktable blocks
4503 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4504 (save-excursion (funcall function))
4505 (or (looking-at org-table-line-regexp)
4506 (forward-char 1)))
4507 (re-search-forward org-table-any-border-regexp nil 1)))
4508 (unless quietly (message "Mapping tables: done")))
4510 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4511 (declare-function org-clock-update-mode-line "org-clock" ())
4512 (declare-function org-resolve-clocks "org-clock"
4513 (&optional also-non-dangling-p prompt last-valid))
4515 (defun org-at-TBLFM-p (&optional pos)
4516 "Non-nil when point (or POS) is in #+TBLFM line."
4517 (save-excursion
4518 (goto-char (or pos (point)))
4519 (beginning-of-line)
4520 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4521 (eq (org-element-type (org-element-at-point)) 'table))))
4523 (defvar org-clock-start-time)
4524 (defvar org-clock-marker (make-marker)
4525 "Marker recording the last clock-in.")
4526 (defvar org-clock-hd-marker (make-marker)
4527 "Marker recording the last clock-in, but the headline position.")
4528 (defvar org-clock-heading ""
4529 "The heading of the current clock entry.")
4530 (defun org-clock-is-active ()
4531 "Return the buffer where the clock is currently running.
4532 Return nil if no clock is running."
4533 (marker-buffer org-clock-marker))
4535 (defun org-check-running-clock ()
4536 "Check if the current buffer contains the running clock.
4537 If yes, offer to stop it and to save the buffer with the changes."
4538 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4539 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4540 (buffer-name))))
4541 (org-clock-out)
4542 (when (y-or-n-p "Save changed buffer?")
4543 (save-buffer))))
4545 (defun org-clocktable-try-shift (dir n)
4546 "Check if this line starts a clock table, if yes, shift the time block."
4547 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4548 (org-clocktable-shift dir n)))
4550 ;;;###autoload
4551 (defun org-clock-persistence-insinuate ()
4552 "Set up hooks for clock persistence."
4553 (require 'org-clock)
4554 (add-hook 'org-mode-hook 'org-clock-load)
4555 (add-hook 'kill-emacs-hook 'org-clock-save))
4557 (defgroup org-archive nil
4558 "Options concerning archiving in Org mode."
4559 :tag "Org Archive"
4560 :group 'org-structure)
4562 (defcustom org-archive-location "%s_archive::"
4563 "The location where subtrees should be archived.
4565 The value of this variable is a string, consisting of two parts,
4566 separated by a double-colon. The first part is a filename and
4567 the second part is a headline.
4569 When the filename is omitted, archiving happens in the same file.
4570 %s in the filename will be replaced by the current file
4571 name (without the directory part). Archiving to a different file
4572 is useful to keep archived entries from contributing to the
4573 Org Agenda.
4575 The archived entries will be filed as subtrees of the specified
4576 headline. When the headline is omitted, the subtrees are simply
4577 filed away at the end of the file, as top-level entries. Also in
4578 the heading you can use %s to represent the file name, this can be
4579 useful when using the same archive for a number of different files.
4581 Here are a few examples:
4582 \"%s_archive::\"
4583 If the current file is Projects.org, archive in file
4584 Projects.org_archive, as top-level trees. This is the default.
4586 \"::* Archived Tasks\"
4587 Archive in the current file, under the top-level headline
4588 \"* Archived Tasks\".
4590 \"~/org/archive.org::\"
4591 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4593 \"~/org/archive.org::* From %s\"
4594 Archive in file ~/org/archive.org (absolute path), under headlines
4595 \"From FILENAME\" where file name is the current file name.
4597 \"~/org/datetree.org::datetree/* Finished Tasks\"
4598 The \"datetree/\" string is special, signifying to archive
4599 items to the datetree. Items are placed in either the CLOSED
4600 date of the item, or the current date if there is no CLOSED date.
4601 The heading will be a subentry to the current date. There doesn't
4602 need to be a heading, but there always needs to be a slash after
4603 datetree. For example, to store archived items directly in the
4604 datetree, use \"~/org/datetree.org::datetree/\".
4606 \"basement::** Finished Tasks\"
4607 Archive in file ./basement (relative path), as level 3 trees
4608 below the level 2 heading \"** Finished Tasks\".
4610 You may set this option on a per-file basis by adding to the buffer a
4611 line like
4613 #+ARCHIVE: basement::** Finished Tasks
4615 You may also define it locally for a subtree by setting an ARCHIVE property
4616 in the entry. If such a property is found in an entry, or anywhere up
4617 the hierarchy, it will be used."
4618 :group 'org-archive
4619 :type 'string)
4621 (defcustom org-agenda-skip-archived-trees t
4622 "Non-nil means the agenda will skip any items located in archived trees.
4623 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4624 variable is no longer recommended, you should leave it at the value t.
4625 Instead, use the key `v' to cycle the archives-mode in the agenda."
4626 :group 'org-archive
4627 :group 'org-agenda-skip
4628 :type 'boolean)
4630 (defcustom org-columns-skip-archived-trees t
4631 "Non-nil means ignore archived trees when creating column view."
4632 :group 'org-archive
4633 :group 'org-properties
4634 :type 'boolean)
4636 (defcustom org-cycle-open-archived-trees nil
4637 "Non-nil means `org-cycle' will open archived trees.
4638 An archived tree is a tree marked with the tag ARCHIVE.
4639 When nil, archived trees will stay folded. You can still open them with
4640 normal outline commands like `show-all', but not with the cycling commands."
4641 :group 'org-archive
4642 :group 'org-cycle
4643 :type 'boolean)
4645 (defcustom org-sparse-tree-open-archived-trees nil
4646 "Non-nil means sparse tree construction shows matches in archived trees.
4647 When nil, matches in these trees are highlighted, but the trees are kept in
4648 collapsed state."
4649 :group 'org-archive
4650 :group 'org-sparse-trees
4651 :type 'boolean)
4653 (defcustom org-sparse-tree-default-date-type nil
4654 "The default date type when building a sparse tree.
4655 When this is nil, a date is a scheduled or a deadline timestamp.
4656 Otherwise, these types are allowed:
4658 all: all timestamps
4659 active: only active timestamps (<...>)
4660 inactive: only inactive timestamps ([...])
4661 scheduled: only scheduled timestamps
4662 deadline: only deadline timestamps"
4663 :type '(choice (const :tag "Scheduled or deadline" nil)
4664 (const :tag "All timestamps" all)
4665 (const :tag "Only active timestamps" active)
4666 (const :tag "Only inactive timestamps" inactive)
4667 (const :tag "Only scheduled timestamps" scheduled)
4668 (const :tag "Only deadline timestamps" deadline)
4669 (const :tag "Only closed timestamps" closed))
4670 :version "26.1"
4671 :package-version '(Org . "8.3")
4672 :group 'org-sparse-trees)
4674 (defun org-cycle-hide-archived-subtrees (state)
4675 "Re-hide all archived subtrees after a visibility state change.
4676 STATE should be one of the symbols listed in the docstring of
4677 `org-cycle-hook'."
4678 (when (and (not org-cycle-open-archived-trees)
4679 (not (memq state '(overview folded))))
4680 (save-excursion
4681 (let* ((globalp (memq state '(contents all)))
4682 (beg (if globalp (point-min) (point)))
4683 (end (if globalp (point-max) (org-end-of-subtree t))))
4684 (org-hide-archived-subtrees beg end)
4685 (goto-char beg)
4686 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4687 (message "%s" (substitute-command-keys
4688 "Subtree is archived and stays closed. Use \
4689 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4691 (defun org-force-cycle-archived ()
4692 "Cycle subtree even if it is archived."
4693 (interactive)
4694 (setq this-command 'org-cycle)
4695 (let ((org-cycle-open-archived-trees t))
4696 (call-interactively 'org-cycle)))
4698 (defun org-hide-archived-subtrees (beg end)
4699 "Re-hide all archived subtrees after a visibility state change."
4700 (org-with-wide-buffer
4701 (let ((case-fold-search nil)
4702 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4703 (goto-char beg)
4704 ;; Include headline point is currently on.
4705 (beginning-of-line)
4706 (while (and (< (point) end) (re-search-forward re end t))
4707 (when (member org-archive-tag (org-get-tags))
4708 (org-flag-subtree t)
4709 (org-end-of-subtree t))))))
4711 (declare-function outline-end-of-heading "outline" ())
4712 (declare-function outline-flag-region "outline" (from to flag))
4713 (defun org-flag-subtree (flag)
4714 (save-excursion
4715 (org-back-to-heading t)
4716 (outline-end-of-heading)
4717 (outline-flag-region (point)
4718 (progn (org-end-of-subtree t) (point))
4719 flag)))
4721 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4723 ;; Declare Column View Code
4725 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4726 (declare-function org-columns-compute "org-colview" (property))
4728 ;; Declare ID code
4730 (declare-function org-id-store-link "org-id")
4731 (declare-function org-id-locations-load "org-id")
4732 (declare-function org-id-locations-save "org-id")
4733 (defvar org-id-track-globally)
4735 ;;; Variables for pre-computed regular expressions, all buffer local
4737 (defvar-local org-todo-regexp nil
4738 "Matches any of the TODO state keywords.
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-not-done-regexp nil
4743 "Matches any of the TODO state keywords except the last one.
4744 Since TODO keywords are case-sensitive, `case-fold-search' is
4745 expected to be bound to nil when matching against this regexp.")
4747 (defvar-local org-not-done-heading-regexp nil
4748 "Matches a TODO headline that is not done.
4749 Since TODO keywords are case-sensitive, `case-fold-search' is
4750 expected to be bound to nil when matching against this regexp.")
4752 (defvar-local org-todo-line-regexp nil
4753 "Matches a headline and puts TODO state into group 2 if present.
4754 Since TODO keywords are case-sensitive, `case-fold-search' is
4755 expected to be bound to nil when matching against this regexp.")
4757 (defvar-local org-complex-heading-regexp nil
4758 "Matches a headline and puts everything into groups:
4760 group 1: Stars
4761 group 2: The TODO keyword, maybe
4762 group 3: Priority cookie
4763 group 4: True headline
4764 group 5: Tags
4766 Since TODO keywords are case-sensitive, `case-fold-search' is
4767 expected to be bound to nil when matching against this regexp.")
4769 (defvar-local org-complex-heading-regexp-format nil
4770 "Printf format to make regexp to match an exact headline.
4771 This regexp will match the headline of any node which has the
4772 exact headline text that is put into the format, but may have any
4773 TODO state, priority and tags.")
4775 (defvar-local org-todo-line-tags-regexp nil
4776 "Matches a headline and puts TODO state into group 2 if present.
4777 Also put tags into group 4 if tags are present.")
4779 (defconst org-plain-time-of-day-regexp
4780 (concat
4781 "\\(\\<[012]?[0-9]"
4782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4783 "\\(--?"
4784 "\\(\\<[012]?[0-9]"
4785 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4786 "\\)?")
4787 "Regular expression to match a plain time or time range.
4788 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4789 groups carry important information:
4790 0 the full match
4791 1 the first time, range or not
4792 8 the second time, if it is a range.")
4794 (defconst org-plain-time-extension-regexp
4795 (concat
4796 "\\(\\<[012]?[0-9]"
4797 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4798 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4799 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4800 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4801 groups carry important information:
4802 0 the full match
4803 7 hours of duration
4804 9 minutes of duration")
4806 (defconst org-stamp-time-of-day-regexp
4807 (concat
4808 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4809 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4810 "\\(--?"
4811 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4812 "Regular expression to match a timestamp time or time range.
4813 After a match, the following groups carry important information:
4814 0 the full match
4815 1 date plus weekday, for back referencing to make sure both times are on the same day
4816 2 the first time, range or not
4817 4 the second time, if it is a range.")
4819 (defconst org-startup-options
4820 '(("fold" org-startup-folded t)
4821 ("overview" org-startup-folded t)
4822 ("nofold" org-startup-folded nil)
4823 ("showall" org-startup-folded nil)
4824 ("showeverything" org-startup-folded showeverything)
4825 ("content" org-startup-folded content)
4826 ("indent" org-startup-indented t)
4827 ("noindent" org-startup-indented nil)
4828 ("hidestars" org-hide-leading-stars t)
4829 ("showstars" org-hide-leading-stars nil)
4830 ("odd" org-odd-levels-only t)
4831 ("oddeven" org-odd-levels-only nil)
4832 ("align" org-startup-align-all-tables t)
4833 ("noalign" org-startup-align-all-tables nil)
4834 ("inlineimages" org-startup-with-inline-images t)
4835 ("noinlineimages" org-startup-with-inline-images nil)
4836 ("latexpreview" org-startup-with-latex-preview t)
4837 ("nolatexpreview" org-startup-with-latex-preview nil)
4838 ("customtime" org-display-custom-times t)
4839 ("logdone" org-log-done time)
4840 ("lognotedone" org-log-done note)
4841 ("nologdone" org-log-done nil)
4842 ("lognoteclock-out" org-log-note-clock-out t)
4843 ("nolognoteclock-out" org-log-note-clock-out nil)
4844 ("logrepeat" org-log-repeat state)
4845 ("lognoterepeat" org-log-repeat note)
4846 ("logdrawer" org-log-into-drawer t)
4847 ("nologdrawer" org-log-into-drawer nil)
4848 ("logstatesreversed" org-log-states-order-reversed t)
4849 ("nologstatesreversed" org-log-states-order-reversed nil)
4850 ("nologrepeat" org-log-repeat nil)
4851 ("logreschedule" org-log-reschedule time)
4852 ("lognotereschedule" org-log-reschedule note)
4853 ("nologreschedule" org-log-reschedule nil)
4854 ("logredeadline" org-log-redeadline time)
4855 ("lognoteredeadline" org-log-redeadline note)
4856 ("nologredeadline" org-log-redeadline nil)
4857 ("logrefile" org-log-refile time)
4858 ("lognoterefile" org-log-refile note)
4859 ("nologrefile" org-log-refile nil)
4860 ("fninline" org-footnote-define-inline t)
4861 ("nofninline" org-footnote-define-inline nil)
4862 ("fnlocal" org-footnote-section nil)
4863 ("fnauto" org-footnote-auto-label t)
4864 ("fnprompt" org-footnote-auto-label nil)
4865 ("fnconfirm" org-footnote-auto-label confirm)
4866 ("fnplain" org-footnote-auto-label plain)
4867 ("fnadjust" org-footnote-auto-adjust t)
4868 ("nofnadjust" org-footnote-auto-adjust nil)
4869 ("constcgs" constants-unit-system cgs)
4870 ("constSI" constants-unit-system SI)
4871 ("noptag" org-tag-persistent-alist nil)
4872 ("hideblocks" org-hide-block-startup t)
4873 ("nohideblocks" org-hide-block-startup nil)
4874 ("beamer" org-startup-with-beamer-mode t)
4875 ("entitiespretty" org-pretty-entities t)
4876 ("entitiesplain" org-pretty-entities nil))
4877 "Variable associated with STARTUP options for Org.
4878 Each element is a list of three items: the startup options (as written
4879 in the #+STARTUP line), the corresponding variable, and the value to set
4880 this variable to if the option is found. An optional forth element PUSH
4881 means to push this value onto the list in the variable.")
4883 (defcustom org-group-tags t
4884 "When non-nil (the default), use group tags.
4885 This can be turned on/off through `org-toggle-tags-groups'."
4886 :group 'org-tags
4887 :group 'org-startup
4888 :type 'boolean)
4890 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4892 (defun org-toggle-tags-groups ()
4893 "Toggle support for group tags.
4894 Support for group tags is controlled by the option
4895 `org-group-tags', which is non-nil by default."
4896 (interactive)
4897 (setq org-group-tags (not org-group-tags))
4898 (cond ((and (derived-mode-p 'org-agenda-mode)
4899 org-group-tags)
4900 (org-agenda-redo))
4901 ((derived-mode-p 'org-mode)
4902 (let ((org-inhibit-startup t)) (org-mode))))
4903 (message "Groups tags support has been turned %s"
4904 (if org-group-tags "on" "off")))
4906 (defun org-set-regexps-and-options (&optional tags-only)
4907 "Precompute regular expressions used in the current buffer.
4908 When optional argument TAGS-ONLY is non-nil, only compute tags
4909 related expressions."
4910 (when (derived-mode-p 'org-mode)
4911 (let ((alist (org--setup-collect-keywords
4912 (org-make-options-regexp
4913 (append '("FILETAGS" "TAGS" "SETUPFILE")
4914 (and (not tags-only)
4915 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4916 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4917 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4918 ;; Startup options. Get this early since it does change
4919 ;; behavior for other options (e.g., tags).
4920 (let ((startup (cdr (assq 'startup alist))))
4921 (dolist (option startup)
4922 (let ((entry (assoc-string option org-startup-options t)))
4923 (when entry
4924 (let ((var (nth 1 entry))
4925 (val (nth 2 entry)))
4926 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4927 (unless (listp (symbol-value var))
4928 (set (make-local-variable var) nil))
4929 (add-to-list var val)))))))
4930 (setq-local org-file-tags
4931 (mapcar #'org-add-prop-inherited
4932 (cdr (assq 'filetags alist))))
4933 (setq org-current-tag-alist
4934 (append org-tag-persistent-alist
4935 (let ((tags (cdr (assq 'tags alist))))
4936 (if tags (org-tag-string-to-alist tags)
4937 org-tag-alist))))
4938 (setq org-tag-groups-alist
4939 (org-tag-alist-to-groups org-current-tag-alist))
4940 (unless tags-only
4941 ;; File properties.
4942 (setq-local org-file-properties (cdr (assq 'property alist)))
4943 ;; Archive location.
4944 (let ((archive (cdr (assq 'archive alist))))
4945 (when archive (setq-local org-archive-location archive)))
4946 ;; Category.
4947 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4948 (when cat
4949 (setq-local org-category (intern cat))
4950 (setq-local org-file-properties
4951 (org--update-property-plist
4952 "CATEGORY" cat org-file-properties))))
4953 ;; Columns.
4954 (let ((column (cdr (assq 'columns alist))))
4955 (when column (setq-local org-columns-default-format column)))
4956 ;; Constants.
4957 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4958 ;; Link abbreviations.
4959 (let ((links (cdr (assq 'link alist))))
4960 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4961 ;; Priorities.
4962 (let ((priorities (cdr (assq 'priorities alist))))
4963 (when priorities
4964 (setq-local org-highest-priority (nth 0 priorities))
4965 (setq-local org-lowest-priority (nth 1 priorities))
4966 (setq-local org-default-priority (nth 2 priorities))))
4967 ;; Scripts.
4968 (let ((scripts (assq 'scripts alist)))
4969 (when scripts
4970 (setq-local org-use-sub-superscripts (cdr scripts))))
4971 ;; TODO keywords.
4972 (setq-local org-todo-kwd-alist nil)
4973 (setq-local org-todo-key-alist nil)
4974 (setq-local org-todo-key-trigger nil)
4975 (setq-local org-todo-keywords-1 nil)
4976 (setq-local org-done-keywords nil)
4977 (setq-local org-todo-heads nil)
4978 (setq-local org-todo-sets nil)
4979 (setq-local org-todo-log-states nil)
4980 (let ((todo-sequences
4981 (or (nreverse (cdr (assq 'todo alist)))
4982 (let ((d (default-value 'org-todo-keywords)))
4983 (if (not (stringp (car d))) d
4984 ;; XXX: Backward compatibility code.
4985 (list (cons org-todo-interpretation d)))))))
4986 (dolist (sequence todo-sequences)
4987 (let* ((sequence (or (run-hook-with-args-until-success
4988 'org-todo-setup-filter-hook sequence)
4989 sequence))
4990 (sequence-type (car sequence))
4991 (keywords (cdr sequence))
4992 (sep (member "|" keywords))
4993 names alist)
4994 (dolist (k (remove "|" keywords))
4995 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4997 (error "Invalid TODO keyword %s" k))
4998 (let ((name (match-string 1 k))
4999 (key (match-string 2 k))
5000 (log (org-extract-log-state-settings k)))
5001 (push name names)
5002 (push (cons name (and key (string-to-char key))) alist)
5003 (when log (push log org-todo-log-states))))
5004 (let* ((names (nreverse names))
5005 (done (if sep (org-remove-keyword-keys (cdr sep))
5006 (last names)))
5007 (head (car names))
5008 (tail (list sequence-type head (car done) (org-last done))))
5009 (add-to-list 'org-todo-heads head 'append)
5010 (push names org-todo-sets)
5011 (setq org-done-keywords (append org-done-keywords done nil))
5012 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5013 (setq org-todo-key-alist
5014 (append org-todo-key-alist
5015 (and alist
5016 (append '((:startgroup))
5017 (nreverse alist)
5018 '((:endgroup))))))
5019 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5020 (setq org-todo-sets (nreverse org-todo-sets)
5021 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5022 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5023 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5024 ;; Compute the regular expressions and other local variables.
5025 ;; Using `org-outline-regexp-bol' would complicate them much,
5026 ;; because of the fixed white space at the end of that string.
5027 (unless org-done-keywords
5028 (setq org-done-keywords
5029 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5030 (setq org-not-done-keywords
5031 (org-delete-all org-done-keywords
5032 (copy-sequence org-todo-keywords-1))
5033 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5034 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5035 org-not-done-heading-regexp
5036 (format org-heading-keyword-regexp-format org-not-done-regexp)
5037 org-todo-line-regexp
5038 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5039 org-complex-heading-regexp
5040 (concat "^\\(\\*+\\)"
5041 "\\(?: +" org-todo-regexp "\\)?"
5042 "\\(?: +\\(\\[#.\\]\\)\\)?"
5043 "\\(?: +\\(.*?\\)\\)??"
5044 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5045 "[ \t]*$")
5046 org-complex-heading-regexp-format
5047 (concat "^\\(\\*+\\)"
5048 "\\(?: +" org-todo-regexp "\\)?"
5049 "\\(?: +\\(\\[#.\\]\\)\\)?"
5050 "\\(?: +"
5051 ;; Stats cookies can be stuck to body.
5052 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5053 "\\(%s\\)"
5054 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5055 "\\)"
5056 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5057 "[ \t]*$")
5058 org-todo-line-tags-regexp
5059 (concat "^\\(\\*+\\)"
5060 "\\(?: +" org-todo-regexp "\\)?"
5061 "\\(?: +\\(.*?\\)\\)??"
5062 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5063 "[ \t]*$"))
5064 (org-compute-latex-and-related-regexp)))))
5066 (defun org--setup-collect-keywords (regexp &optional files alist)
5067 "Return setup keywords values as an alist.
5069 REGEXP matches a subset of setup keywords. FILES is a list of
5070 file names already visited. It is used to avoid circular setup
5071 files. ALIST, when non-nil, is the alist computed so far.
5073 Return value contains the following keys: `archive', `category',
5074 `columns', `constants', `filetags', `link', `priorities',
5075 `property', `scripts', `startup', `tags' and `todo'."
5076 (org-with-wide-buffer
5077 (goto-char (point-min))
5078 (let ((case-fold-search t))
5079 (while (re-search-forward regexp nil t)
5080 (let ((element (org-element-at-point)))
5081 (when (eq (org-element-type element) 'keyword)
5082 (let ((key (org-element-property :key element))
5083 (value (org-element-property :value element)))
5084 (cond
5085 ((equal key "ARCHIVE")
5086 (when (org-string-nw-p value)
5087 (push (cons 'archive value) alist)))
5088 ((equal key "CATEGORY") (push (cons 'category value) alist))
5089 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5090 ((equal key "CONSTANTS")
5091 (let* ((constants (assq 'constants alist))
5092 (store (cdr constants)))
5093 (dolist (pair (split-string value))
5094 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5095 pair)
5096 (let* ((name (match-string 1 pair))
5097 (value (match-string 2 pair))
5098 (old (assoc name store)))
5099 (if old (setcdr old value)
5100 (push (cons name value) store)))))
5101 (if constants (setcdr constants store)
5102 (push (cons 'constants store) alist))))
5103 ((equal key "FILETAGS")
5104 (when (org-string-nw-p value)
5105 (let ((old (assq 'filetags alist))
5106 (new (apply #'nconc
5107 (mapcar (lambda (x) (org-split-string x ":"))
5108 (split-string value)))))
5109 (if old (setcdr old (append new (cdr old)))
5110 (push (cons 'filetags new) alist)))))
5111 ((equal key "LINK")
5112 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5113 (let ((links (assq 'link alist))
5114 (pair (cons (match-string-no-properties 1 value)
5115 (match-string-no-properties 2 value))))
5116 (if links (push pair (cdr links))
5117 (push (list 'link pair) alist)))))
5118 ((equal key "OPTIONS")
5119 (when (and (org-string-nw-p value)
5120 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5121 (push (cons 'scripts (read (match-string 1 value))) alist)))
5122 ((equal key "PRIORITIES")
5123 (push (cons 'priorities
5124 (let ((prio (split-string value)))
5125 (if (< (length prio) 3) '(?A ?C ?B)
5126 (mapcar #'string-to-char prio))))
5127 alist))
5128 ((equal key "PROPERTY")
5129 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5130 (let* ((property (assq 'property alist))
5131 (value (org--update-property-plist
5132 (match-string-no-properties 1 value)
5133 (match-string-no-properties 2 value)
5134 (cdr property))))
5135 (if property (setcdr property value)
5136 (push (cons 'property value) alist)))))
5137 ((equal key "STARTUP")
5138 (let ((startup (assq 'startup alist)))
5139 (if startup
5140 (setcdr startup
5141 (append (cdr startup) (split-string value)))
5142 (push (cons 'startup (split-string value)) alist))))
5143 ((equal key "TAGS")
5144 (let ((tag-cell (assq 'tags alist)))
5145 (if tag-cell
5146 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5147 (push (cons 'tags value) alist))))
5148 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5149 (let ((todo (assq 'todo alist))
5150 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5151 (split-string value))))
5152 (if todo (push value (cdr todo))
5153 (push (list 'todo value) alist))))
5154 ((equal key "SETUPFILE")
5155 (unless buffer-read-only ; Do not check in Gnus messages.
5156 (let ((f (and (org-string-nw-p value)
5157 (expand-file-name
5158 (org-unbracket-string "\"" "\"" value)))))
5159 (when (and f (file-readable-p f) (not (member f files)))
5160 (with-temp-buffer
5161 (setq default-directory (file-name-directory f))
5162 (insert-file-contents f)
5163 (setq alist
5164 ;; Fake Org mode to benefit from cache
5165 ;; without recurring needlessly.
5166 (let ((major-mode 'org-mode))
5167 (org--setup-collect-keywords
5168 regexp (cons f files) alist)))))))))))))))
5169 alist)
5171 (defun org-tag-string-to-alist (s)
5172 "Return tag alist associated to string S.
5173 S is a value for TAGS keyword or produced with
5174 `org-tag-alist-to-string'. Return value is an alist suitable for
5175 `org-tag-alist' or `org-tag-persistent-alist'."
5176 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5177 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5178 "\\|{.+?}\\)" ; regular expression
5179 "\\(?:(\\(.\\))\\)?\\'"))
5180 alist group-flag)
5181 (dolist (tokens lines (cdr (nreverse alist)))
5182 (push '(:newline) alist)
5183 (while tokens
5184 (let ((token (pop tokens)))
5185 (pcase token
5186 ("{"
5187 (push '(:startgroup) alist)
5188 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5189 ("}"
5190 (push '(:endgroup) alist)
5191 (setq group-flag nil))
5192 ("["
5193 (push '(:startgrouptag) alist)
5194 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5195 ("]"
5196 (push '(:endgrouptag) alist)
5197 (setq group-flag nil))
5198 (":"
5199 (push '(:grouptags) alist))
5200 ((guard (string-match tag-re token))
5201 (let ((tag (match-string 1 token))
5202 (key (and (match-beginning 2)
5203 (string-to-char (match-string 2 token)))))
5204 ;; Push all tags in groups, no matter if they already
5205 ;; appear somewhere else in the list.
5206 (when (or group-flag (not (assoc tag alist)))
5207 (push (cons tag key) alist))))))))))
5209 (defun org-tag-alist-to-string (alist &optional skip-key)
5210 "Return tag string associated to ALIST.
5212 ALIST is an alist, as defined in `org-tag-alist' or
5213 `org-tag-persistent-alist', or produced with
5214 `org-tag-string-to-alist'.
5216 Return value is a string suitable as a value for \"TAGS\"
5217 keyword.
5219 When optional argument SKIP-KEY is non-nil, skip selection keys
5220 next to tags."
5221 (mapconcat (lambda (token)
5222 (pcase token
5223 (`(:startgroup) "{")
5224 (`(:endgroup) "}")
5225 (`(:startgrouptag) "[")
5226 (`(:endgrouptag) "]")
5227 (`(:grouptags) ":")
5228 (`(:newline) "\\n")
5229 ((and
5230 (guard (not skip-key))
5231 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5232 (format "%s(%c)" tag key))
5233 (`(,(and tag (pred stringp)) . ,_) tag)
5234 (_ (user-error "Invalid tag token: %S" token))))
5235 alist
5236 " "))
5238 (defun org-tag-alist-to-groups (alist)
5239 "Return group alist from tag ALIST.
5240 ALIST is an alist, as defined in `org-tag-alist' or
5241 `org-tag-persistent-alist', or produced with
5242 `org-tag-string-to-alist'. Return value is an alist following
5243 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5244 a string, summarizing TAGS, as a list of strings."
5245 (let (groups group-status current-group)
5246 (dolist (token alist (nreverse groups))
5247 (pcase token
5248 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5249 (`(,(or :endgroup :endgrouptag))
5250 (when (eq group-status 'append)
5251 (push (nreverse current-group) groups))
5252 (setq group-status nil))
5253 (`(:grouptags) (setq group-status 'append))
5254 ((and `(,tag . ,_) (guard group-status))
5255 (if (eq group-status 'append) (push tag current-group)
5256 (setq current-group (list tag))))
5257 (_ nil)))))
5259 (defvar org--file-cache (make-hash-table :test #'equal)
5260 "Hash table to store contents of files referenced via a URL.
5261 This is the cache of file URLs read using `org-file-contents'.")
5263 (defun org-reset-file-cache ()
5264 "Reset the cache of files downloaded by `org-file-contents'."
5265 (clrhash org--file-cache))
5267 (defun org-file-url-p (file)
5268 "Non-nil if FILE is a URL."
5269 (require 'ffap)
5270 (string-match-p ffap-url-regexp file))
5272 (defun org-file-contents (file &optional noerror nocache)
5273 "Return the contents of FILE, as a string.
5275 FILE can be a file name or URL.
5277 If FILE is a URL, download the contents. If the URL contents are
5278 already cached in the `org--file-cache' hash table, the download step
5279 is skipped.
5281 If NOERROR is non-nil, ignore the error when unable to read the FILE
5282 from file or URL.
5284 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5285 is available. This option applies only if FILE is a URL."
5286 (let* ((is-url (org-file-url-p file))
5287 (cache (and is-url
5288 (not nocache)
5289 (gethash file org--file-cache))))
5290 (cond
5291 (cache)
5292 (is-url
5293 (with-current-buffer (url-retrieve-synchronously file)
5294 (goto-char (point-min))
5295 ;; Move point to after the url-retrieve header.
5296 (search-forward "\n\n" nil :move)
5297 ;; Search for the success code only in the url-retrieve header.
5298 (if (save-excursion
5299 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5300 ;; Update the cache `org--file-cache' and return contents.
5301 (puthash file
5302 (buffer-substring-no-properties (point) (point-max))
5303 org--file-cache)
5304 (funcall (if noerror #'message #'user-error)
5305 "Unable to fetch file from %S"
5306 file))))
5308 (with-temp-buffer
5309 (condition-case nil
5310 (progn
5311 (insert-file-contents file)
5312 (buffer-string))
5313 (file-error
5314 (funcall (if noerror #'message #'user-error)
5315 "Unable to read file %S"
5316 file))))))))
5318 (defun org-extract-log-state-settings (x)
5319 "Extract the log state setting from a TODO keyword string.
5320 This will extract info from a string like \"WAIT(w@/!)\"."
5321 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5322 (let ((kw (match-string 1 x))
5323 (log1 (and (match-end 3) (match-string 3 x)))
5324 (log2 (and (match-end 4) (match-string 4 x))))
5325 (and (or log1 log2)
5326 (list kw
5327 (and log1 (if (equal log1 "!") 'time 'note))
5328 (and log2 (if (equal log2 "!") 'time 'note)))))))
5330 (defun org-remove-keyword-keys (list)
5331 "Remove a pair of parenthesis at the end of each string in LIST."
5332 (mapcar (lambda (x)
5333 (if (string-match "(.*)$" x)
5334 (substring x 0 (match-beginning 0))
5336 list))
5338 (defun org-assign-fast-keys (alist)
5339 "Assign fast keys to a keyword-key alist.
5340 Respect keys that are already there."
5341 (let (new e (alt ?0))
5342 (while (setq e (pop alist))
5343 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5344 (cdr e)) ;; Key already assigned.
5345 (push e new)
5346 (let ((clist (string-to-list (downcase (car e))))
5347 (used (append new alist)))
5348 (when (= (car clist) ?@)
5349 (pop clist))
5350 (while (and clist (rassoc (car clist) used))
5351 (pop clist))
5352 (unless clist
5353 (while (rassoc alt used)
5354 (cl-incf alt)))
5355 (push (cons (car e) (or (car clist) alt)) new))))
5356 (nreverse new)))
5358 ;;; Some variables used in various places
5360 (defvar org-window-configuration nil
5361 "Used in various places to store a window configuration.")
5362 (defvar org-selected-window nil
5363 "Used in various places to store a window configuration.")
5364 (defvar org-finish-function nil
5365 "Function to be called when `C-c C-c' is used.
5366 This is for getting out of special buffers like capture.")
5367 (defvar org-last-state)
5369 ;; Defined somewhere in this file, but used before definition.
5370 (defvar org-entities) ;; defined in org-entities.el
5371 (defvar org-struct-menu)
5372 (defvar org-org-menu)
5373 (defvar org-tbl-menu)
5375 ;;;; Define the Org mode
5377 ;; We use a before-change function to check if a table might need
5378 ;; an update.
5379 (defvar org-table-may-need-update t
5380 "Indicates that a table might need an update.
5381 This variable is set by `org-before-change-function'.
5382 `org-table-align' sets it back to nil.")
5383 (defun org-before-change-function (_beg _end)
5384 "Every change indicates that a table might need an update."
5385 (setq org-table-may-need-update t))
5386 (defvar org-mode-map)
5387 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5388 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5389 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5390 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5391 (defvar org-table-buffer-is-an nil)
5393 (defvar bidi-paragraph-direction)
5394 (defvar buffer-face-mode-face)
5396 (require 'outline)
5398 ;; Other stuff we need.
5399 (require 'time-date)
5400 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5401 (require 'easymenu)
5402 (autoload 'easy-menu-add "easymenu")
5403 (require 'overlay)
5405 ;; (require 'org-macs) moved higher up in the file before it is first used
5406 (require 'org-entities)
5407 ;; (require 'org-compat) moved higher up in the file before it is first used
5408 (require 'org-faces)
5409 (require 'org-list)
5410 (require 'org-pcomplete)
5411 (require 'org-src)
5412 (require 'org-footnote)
5413 (require 'org-macro)
5415 ;; babel
5416 (require 'ob)
5418 ;;;###autoload
5419 (define-derived-mode org-mode outline-mode "Org"
5420 "Outline-based notes management and organizer, alias
5421 \"Carsten's outline-mode for keeping track of everything.\"
5423 Org mode develops organizational tasks around a NOTES file which
5424 contains information about projects as plain text. Org mode is
5425 implemented on top of Outline mode, which is ideal to keep the content
5426 of large files well structured. It supports ToDo items, deadlines and
5427 time stamps, which magically appear in the diary listing of the Emacs
5428 calendar. Tables are easily created with a built-in table editor.
5429 Plain text URL-like links connect to websites, emails (VM), Usenet
5430 messages (Gnus), BBDB entries, and any files related to the project.
5431 For printing and sharing of notes, an Org file (or a part of it)
5432 can be exported as a structured ASCII or HTML file.
5434 The following commands are available:
5436 \\{org-mode-map}"
5438 ;; Get rid of Outline menus, they are not needed
5439 ;; Need to do this here because define-derived-mode sets up
5440 ;; the keymap so late. Still, it is a waste to call this each time
5441 ;; we switch another buffer into Org mode.
5442 (define-key org-mode-map [menu-bar headings] 'undefined)
5443 (define-key org-mode-map [menu-bar hide] 'undefined)
5444 (define-key org-mode-map [menu-bar show] 'undefined)
5446 (org-load-modules-maybe)
5447 (org-install-agenda-files-menu)
5448 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5449 (add-to-invisibility-spec '(org-cwidth))
5450 (add-to-invisibility-spec '(org-hide-block . t))
5451 (setq-local outline-regexp org-outline-regexp)
5452 (setq-local outline-level 'org-outline-level)
5453 (setq bidi-paragraph-direction 'left-to-right)
5454 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5455 (unless org-display-table
5456 (setq org-display-table (make-display-table)))
5457 (set-display-table-slot
5458 org-display-table 4
5459 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5460 org-ellipsis)))
5461 (setq buffer-display-table org-display-table))
5462 (org-set-regexps-and-options)
5463 (org-set-font-lock-defaults)
5464 (when (and org-tag-faces (not org-tags-special-faces-re))
5465 ;; tag faces set outside customize.... force initialization.
5466 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5467 ;; Calc embedded
5468 (setq-local calc-embedded-open-mode "# ")
5469 ;; Modify a few syntax entries
5470 (modify-syntax-entry ?@ "w")
5471 (modify-syntax-entry ?\" "\"")
5472 (modify-syntax-entry ?\\ "_")
5473 (modify-syntax-entry ?~ "_")
5474 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5475 ;; Activate before-change-function
5476 (setq-local org-table-may-need-update t)
5477 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5478 ;; Check for running clock before killing a buffer
5479 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5480 ;; Initialize macros templates.
5481 (org-macro-initialize-templates)
5482 ;; Initialize radio targets.
5483 (org-update-radio-target-regexp)
5484 ;; Indentation.
5485 (setq-local indent-line-function 'org-indent-line)
5486 (setq-local indent-region-function 'org-indent-region)
5487 ;; Filling and auto-filling.
5488 (org-setup-filling)
5489 ;; Comments.
5490 (org-setup-comments-handling)
5491 ;; Initialize cache.
5492 (org-element-cache-reset)
5493 ;; Beginning/end of defun
5494 (setq-local beginning-of-defun-function 'org-backward-element)
5495 (setq-local end-of-defun-function
5496 (lambda ()
5497 (if (not (org-at-heading-p))
5498 (org-forward-element)
5499 (org-forward-element)
5500 (forward-char -1))))
5501 ;; Next error for sparse trees
5502 (setq-local next-error-function 'org-occur-next-match)
5503 ;; Make sure dependence stuff works reliably, even for users who set it
5504 ;; too late :-(
5505 (if org-enforce-todo-dependencies
5506 (add-hook 'org-blocker-hook
5507 'org-block-todo-from-children-or-siblings-or-parent)
5508 (remove-hook 'org-blocker-hook
5509 'org-block-todo-from-children-or-siblings-or-parent))
5510 (if org-enforce-todo-checkbox-dependencies
5511 (add-hook 'org-blocker-hook
5512 'org-block-todo-from-checkboxes)
5513 (remove-hook 'org-blocker-hook
5514 'org-block-todo-from-checkboxes))
5516 ;; Align options lines
5517 (setq-local
5518 align-mode-rules-list
5519 '((org-in-buffer-settings
5520 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5521 (modes . '(org-mode)))))
5523 ;; Imenu
5524 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5526 ;; Make isearch reveal context
5527 (setq-local outline-isearch-open-invisible-function
5528 (lambda (&rest _) (org-show-context 'isearch)))
5530 ;; Setup the pcomplete hooks
5531 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5532 (setq-local pcomplete-command-name-function 'org-command-at-point)
5533 (setq-local pcomplete-default-completion-function 'ignore)
5534 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5535 (setq-local pcomplete-termination-string "")
5536 (setq-local buffer-face-mode-face 'org-default)
5538 ;; If empty file that did not turn on Org mode automatically, make
5539 ;; it to.
5540 (when (and org-insert-mode-line-in-empty-file
5541 (called-interactively-p 'any)
5542 (= (point-min) (point-max)))
5543 (insert "# -*- mode: org -*-\n\n"))
5544 (unless org-inhibit-startup
5545 (org-unmodified
5546 (when org-startup-with-beamer-mode (org-beamer-mode))
5547 (when org-startup-align-all-tables
5548 (org-table-map-tables #'org-table-align t))
5549 (when org-startup-with-inline-images (org-display-inline-images))
5550 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5551 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5552 (when org-startup-truncated (setq truncate-lines t))
5553 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5554 (org-refresh-effort-properties)))
5555 ;; Try to set `org-hide' face correctly.
5556 (let ((foreground (org-find-invisible-foreground)))
5557 (when foreground
5558 (set-face-foreground 'org-hide foreground))))
5560 ;; Update `customize-package-emacs-version-alist'
5561 (add-to-list 'customize-package-emacs-version-alist
5562 '(Org ("8.0" . "24.4")
5563 ("8.1" . "24.4")
5564 ("8.2" . "24.4")
5565 ("8.2.7" . "24.4")
5566 ("8.3" . "26.1")
5567 ("9.0" . "26.1")
5568 ("9.1" . "26.1")))
5570 (defvar org-mode-transpose-word-syntax-table
5571 (let ((st (make-syntax-table text-mode-syntax-table)))
5572 (dolist (c org-emphasis-alist st)
5573 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5575 (when (fboundp 'abbrev-table-put)
5576 (abbrev-table-put org-mode-abbrev-table
5577 :parents (list text-mode-abbrev-table)))
5579 (defun org-find-invisible-foreground ()
5580 (let ((candidates (remove
5581 "unspecified-bg"
5582 (nconc
5583 (list (face-background 'default)
5584 (face-background 'org-default))
5585 (mapcar
5586 (lambda (alist)
5587 (when (boundp alist)
5588 (cdr (assq 'background-color (symbol-value alist)))))
5589 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5590 (list (face-foreground 'org-hide))))))
5591 (car (remove nil candidates))))
5593 (defun org-current-time (&optional rounding-minutes past)
5594 "Current time, possibly rounded to ROUNDING-MINUTES.
5595 When ROUNDING-MINUTES is not an integer, fall back on the car of
5596 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5597 the rounding returns a past time."
5598 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5599 (car org-time-stamp-rounding-minutes)))
5600 (time (decode-time)) res)
5601 (if (< r 1)
5602 (current-time)
5603 (setq res
5604 (apply 'encode-time
5605 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5606 (nthcdr 2 time))))
5607 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5608 (seconds-to-time (- (float-time res) (* r 60)))
5609 res))))
5611 (defun org-today ()
5612 "Return today date, considering `org-extend-today-until'."
5613 (time-to-days
5614 (time-subtract (current-time)
5615 (list 0 (* 3600 org-extend-today-until) 0))))
5617 ;;;; Font-Lock stuff, including the activators
5619 (defvar org-mouse-map (make-sparse-keymap))
5620 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5621 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5622 (when org-mouse-1-follows-link
5623 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5624 (when org-tab-follows-link
5625 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5626 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5628 (require 'font-lock)
5630 (defconst org-non-link-chars "]\t\n\r<>")
5631 (defvar org-link-types-re nil
5632 "Matches a link that has a url-like prefix like \"http:\"")
5633 (defvar org-link-re-with-space nil
5634 "Matches a link with spaces, optional angular brackets around it.")
5635 (defvar org-link-re-with-space2 nil
5636 "Matches a link with spaces, optional angular brackets around it.")
5637 (defvar org-link-re-with-space3 nil
5638 "Matches a link with spaces, only for internal part in bracket links.")
5639 (defvar org-angle-link-re nil
5640 "Matches link with angular brackets, spaces are allowed.")
5641 (defvar org-plain-link-re nil
5642 "Matches plain link, without spaces.")
5643 (defvar org-bracket-link-regexp nil
5644 "Matches a link in double brackets.")
5645 (defvar org-bracket-link-analytic-regexp nil
5646 "Regular expression used to analyze links.
5647 Here is what the match groups contain after a match:
5648 1: http:
5649 2: http
5650 3: path
5651 4: [desc]
5652 5: desc")
5653 (defvar org-bracket-link-analytic-regexp++ nil
5654 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5655 (defvar org-any-link-re nil
5656 "Regular expression matching any link.")
5658 (defconst org-match-sexp-depth 3
5659 "Number of stacked braces for sub/superscript matching.")
5661 (defun org-create-multibrace-regexp (left right n)
5662 "Create a regular expression which will match a balanced sexp.
5663 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5664 as single character strings.
5665 The regexp returned will match the entire expression including the
5666 delimiters. It will also define a single group which contains the
5667 match except for the outermost delimiters. The maximum depth of
5668 stacked delimiters is N. Escaping delimiters is not possible."
5669 (let* ((nothing (concat "[^" left right "]*?"))
5670 (or "\\|")
5671 (re nothing)
5672 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5673 (while (> n 1)
5674 (setq n (1- n)
5675 re (concat re or next)
5676 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5677 (concat left "\\(" re "\\)" right)))
5679 (defconst org-match-substring-regexp
5680 (concat
5681 "\\(\\S-\\)\\([_^]\\)\\("
5682 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5683 "\\|"
5684 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5685 "\\|"
5686 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5687 "The regular expression matching a sub- or superscript.")
5689 (defconst org-match-substring-with-braces-regexp
5690 (concat
5691 "\\(\\S-\\)\\([_^]\\)"
5692 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5693 "The regular expression matching a sub- or superscript, forcing braces.")
5695 (defun org-make-link-regexps ()
5696 "Update the link regular expressions.
5697 This should be called after the variable `org-link-parameters' has changed."
5698 (let ((types-re (regexp-opt (org-link-types) t)))
5699 (setq org-link-types-re
5700 (concat "\\`" types-re ":")
5701 org-link-re-with-space
5702 (concat "<?" types-re ":"
5703 "\\([^" org-non-link-chars " ]"
5704 "[^" org-non-link-chars "]*"
5705 "[^" org-non-link-chars " ]\\)>?")
5706 org-link-re-with-space2
5707 (concat "<?" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^\t\n\r]*"
5710 "[^" org-non-link-chars " ]\\)>?")
5711 org-link-re-with-space3
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^\t\n\r]*\\)")
5715 org-angle-link-re
5716 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5717 types-re)
5718 org-plain-link-re
5719 (concat
5720 "\\<" types-re ":"
5721 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5722 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5723 org-bracket-link-regexp
5724 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5725 org-bracket-link-analytic-regexp
5726 (concat
5727 "\\[\\["
5728 "\\(" types-re ":\\)?"
5729 "\\([^]]+\\)"
5730 "\\]"
5731 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5732 "\\]")
5733 org-bracket-link-analytic-regexp++
5734 (concat
5735 "\\[\\["
5736 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5737 "\\([^]]+\\)"
5738 "\\]"
5739 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5740 "\\]")
5741 org-any-link-re
5742 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5743 org-angle-link-re "\\)\\|\\("
5744 org-plain-link-re "\\)"))))
5746 (org-make-link-regexps)
5748 (defvar org-emph-face nil)
5750 (defun org-do-emphasis-faces (limit)
5751 "Run through the buffer and emphasize strings."
5752 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5753 (car org-emphasis-regexp-components))))
5754 (catch :exit
5755 (while (re-search-forward quick-re limit t)
5756 (let* ((marker (match-string 2))
5757 (verbatim? (member marker '("~" "="))))
5758 (when (save-excursion
5759 (goto-char (match-beginning 0))
5760 (and
5761 ;; Do not match table hlines.
5762 (not (and (equal marker "+")
5763 (org-match-line
5764 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5765 ;; Do not match headline stars. Do not consider
5766 ;; stars of a headline as closing marker for bold
5767 ;; markup either.
5768 (not (and (equal marker "*")
5769 (save-excursion
5770 (forward-char)
5771 (skip-chars-backward "*")
5772 (looking-at-p org-outline-regexp-bol))))
5773 ;; Match full emphasis markup regexp.
5774 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5775 ;; Do not span over paragraph boundaries.
5776 (not (string-match-p org-element-paragraph-separate
5777 (match-string 2)))
5778 ;; Do not span over cells in table rows.
5779 (not (and (save-match-data (org-match-line "[ \t]*|"))
5780 (string-match-p "|" (match-string 4))))))
5781 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5782 (font-lock-prepend-text-property
5783 (match-beginning 2) (match-end 2) 'face face)
5784 (when verbatim?
5785 (org-remove-flyspell-overlays-in
5786 (match-beginning 0) (match-end 0)))
5787 (add-text-properties (match-beginning 2) (match-end 2)
5788 '(font-lock-multiline t org-emphasis t))
5789 (when org-hide-emphasis-markers
5790 (add-text-properties (match-end 4) (match-beginning 5)
5791 '(invisible org-link))
5792 (add-text-properties (match-beginning 3) (match-end 3)
5793 '(invisible org-link)))
5794 (throw :exit t))))))))
5796 (defun org-emphasize (&optional char)
5797 "Insert or change an emphasis, i.e. a font like bold or italic.
5798 If there is an active region, change that region to a new emphasis.
5799 If there is no region, just insert the marker characters and position
5800 the cursor between them.
5801 CHAR should be the marker character. If it is a space, it means to
5802 remove the emphasis of the selected region.
5803 If CHAR is not given (for example in an interactive call) it will be
5804 prompted for."
5805 (interactive)
5806 (let ((erc org-emphasis-regexp-components)
5807 (string "") beg end move s)
5808 (if (org-region-active-p)
5809 (setq beg (region-beginning)
5810 end (region-end)
5811 string (buffer-substring beg end))
5812 (setq move t))
5814 (unless char
5815 (message "Emphasis marker or tag: [%s]"
5816 (mapconcat #'car org-emphasis-alist ""))
5817 (setq char (read-char-exclusive)))
5818 (if (equal char ?\s)
5819 (setq s ""
5820 move nil)
5821 (unless (assoc (char-to-string char) org-emphasis-alist)
5822 (user-error "No such emphasis marker: \"%c\"" char))
5823 (setq s (char-to-string char)))
5824 (while (and (> (length string) 1)
5825 (equal (substring string 0 1) (substring string -1))
5826 (assoc (substring string 0 1) org-emphasis-alist))
5827 (setq string (substring string 1 -1)))
5828 (setq string (concat s string s))
5829 (when beg (delete-region beg end))
5830 (unless (or (bolp)
5831 (string-match (concat "[" (nth 0 erc) "\n]")
5832 (char-to-string (char-before (point)))))
5833 (insert " "))
5834 (unless (or (eobp)
5835 (string-match (concat "[" (nth 1 erc) "\n]")
5836 (char-to-string (char-after (point)))))
5837 (insert " ") (backward-char 1))
5838 (insert string)
5839 (and move (backward-char 1))))
5841 (defconst org-nonsticky-props
5842 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5844 (defsubst org-rear-nonsticky-at (pos)
5845 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5847 (defun org-activate-links (limit)
5848 "Add link properties to links.
5849 This includes angle, plain, and bracket links."
5850 (catch :exit
5851 (while (re-search-forward org-any-link-re limit t)
5852 (let* ((start (match-beginning 0))
5853 (end (match-end 0))
5854 (style (cond ((eq ?< (char-after start)) 'angle)
5855 ((eq ?\[ (char-after (1+ start))) 'bracket)
5856 (t 'plain))))
5857 (when (and (memq style org-highlight-links)
5858 ;; Do not confuse plain links with tags.
5859 (not (and (eq style 'plain)
5860 (let ((face (get-text-property
5861 (max (1- start) (point-min)) 'face)))
5862 (if (consp face) (memq 'org-tag face)
5863 (eq 'org-tag face))))))
5864 (let* ((link-object (save-excursion
5865 (goto-char start)
5866 (save-match-data (org-element-link-parser))))
5867 (link (org-element-property :raw-link link-object))
5868 (type (org-element-property :type link-object))
5869 (path (org-element-property :path link-object))
5870 (properties ;for link's visible part
5871 (list
5872 'face (pcase (org-link-get-parameter type :face)
5873 ((and (pred functionp) face) (funcall face path))
5874 ((and (pred facep) face) face)
5875 ((and (pred consp) face) face) ;anonymous
5876 (_ 'org-link))
5877 'mouse-face (or (org-link-get-parameter type :mouse-face)
5878 'highlight)
5879 'keymap (or (org-link-get-parameter type :keymap)
5880 org-mouse-map)
5881 'help-echo (pcase (org-link-get-parameter type :help-echo)
5882 ((and (pred stringp) echo) echo)
5883 ((and (pred functionp) echo) echo)
5884 (_ (concat "LINK: " link)))
5885 'htmlize-link (pcase (org-link-get-parameter type
5886 :htmlize-link)
5887 ((and (pred functionp) f) (funcall f))
5888 (_ `(:uri ,link)))
5889 'font-lock-multiline t)))
5890 (org-remove-flyspell-overlays-in start end)
5891 (org-rear-nonsticky-at end)
5892 (if (not (eq 'bracket style))
5893 (add-text-properties start end properties)
5894 ;; Handle invisible parts in bracket links.
5895 (remove-text-properties start end '(invisible nil))
5896 (let ((hidden
5897 (append `(invisible
5898 ,(or (org-link-get-parameter type :display)
5899 'org-link))
5900 properties))
5901 (visible-start (or (match-beginning 4) (match-beginning 2)))
5902 (visible-end (or (match-end 4) (match-end 2))))
5903 (add-text-properties start visible-start hidden)
5904 (add-text-properties visible-start visible-end properties)
5905 (add-text-properties visible-end end hidden)
5906 (org-rear-nonsticky-at visible-start)
5907 (org-rear-nonsticky-at visible-end)))
5908 (let ((f (org-link-get-parameter type :activate-func)))
5909 (when (functionp f)
5910 (funcall f start end path (eq style 'bracket))))
5911 (throw :exit t))))) ;signal success
5912 nil))
5914 (defun org-activate-code (limit)
5915 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5916 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5917 (remove-text-properties (match-beginning 0) (match-end 0)
5918 '(display t invisible t intangible t))
5921 (defcustom org-src-fontify-natively t
5922 "When non-nil, fontify code in code blocks.
5923 See also the `org-block' face."
5924 :type 'boolean
5925 :version "26.1"
5926 :package-version '(Org . "8.3")
5927 :group 'org-appearance
5928 :group 'org-babel)
5930 (defcustom org-allow-promoting-top-level-subtree nil
5931 "When non-nil, allow promoting a top level subtree.
5932 The leading star of the top level headline will be replaced
5933 by a #."
5934 :type 'boolean
5935 :version "24.1"
5936 :group 'org-appearance)
5938 (defun org-fontify-meta-lines-and-blocks (limit)
5939 (condition-case nil
5940 (org-fontify-meta-lines-and-blocks-1 limit)
5941 (error (message "Org mode fontification error in %S at %d"
5942 (current-buffer)
5943 (line-number-at-pos)))))
5945 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5946 "Fontify #+ lines and blocks."
5947 (let ((case-fold-search t))
5948 (when (re-search-forward
5949 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5950 limit t)
5951 (let ((beg (match-beginning 0))
5952 (block-start (match-end 0))
5953 (block-end nil)
5954 (lang (match-string 7))
5955 (beg1 (line-beginning-position 2))
5956 (dc1 (downcase (match-string 2)))
5957 (dc3 (downcase (match-string 3)))
5958 end end1 quoting block-type)
5959 (cond
5960 ((and (match-end 4) (equal dc3 "+begin"))
5961 ;; Truly a block
5962 (setq block-type (downcase (match-string 5))
5963 quoting (member block-type org-protecting-blocks))
5964 (when (re-search-forward
5965 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5966 nil t) ;; on purpose, we look further than LIMIT
5967 (setq end (min (point-max) (match-end 0))
5968 end1 (min (point-max) (1- (match-beginning 0))))
5969 (setq block-end (match-beginning 0))
5970 (when quoting
5971 (org-remove-flyspell-overlays-in beg1 end1)
5972 (remove-text-properties beg end
5973 '(display t invisible t intangible t)))
5974 (add-text-properties
5975 beg end '(font-lock-fontified t font-lock-multiline t))
5976 (add-text-properties beg beg1 '(face org-meta-line))
5977 (org-remove-flyspell-overlays-in beg beg1)
5978 (add-text-properties ; For end_src
5979 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5980 (org-remove-flyspell-overlays-in end1 end)
5981 (cond
5982 ((and lang (not (string= lang "")) org-src-fontify-natively)
5983 (org-src-font-lock-fontify-block lang block-start block-end)
5984 (add-text-properties beg1 block-end '(src-block t)))
5985 (quoting
5986 (add-text-properties beg1 (min (point-max) (1+ end1))
5987 (list 'face
5988 (list :inherit
5989 (let ((face-name
5990 (intern (format "org-block-%s" lang))))
5991 (append (and (facep face-name) (list face-name))
5992 '(org-block))))))) ; end of source block
5993 ((not org-fontify-quote-and-verse-blocks))
5994 ((string= block-type "quote")
5995 (add-face-text-property
5996 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5997 ((string= block-type "verse")
5998 (add-face-text-property
5999 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6000 (add-text-properties beg beg1 '(face org-block-begin-line))
6001 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6002 '(face org-block-end-line))
6004 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6005 (org-remove-flyspell-overlays-in
6006 (match-beginning 0)
6007 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6008 (add-text-properties
6009 beg (match-end 3)
6010 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6011 '(font-lock-fontified t invisible t)
6012 '(font-lock-fontified t face org-document-info-keyword)))
6013 (add-text-properties
6014 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6015 (if (string-equal dc1 "+title:")
6016 '(font-lock-fontified t face org-document-title)
6017 '(font-lock-fontified t face org-document-info))))
6018 ((string-prefix-p "+caption" dc1)
6019 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6020 (remove-text-properties (match-beginning 0) (match-end 0)
6021 '(display t invisible t intangible t))
6022 ;; Handle short captions.
6023 (save-excursion
6024 (beginning-of-line)
6025 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6026 (add-text-properties (line-beginning-position) (match-end 1)
6027 '(font-lock-fontified t face org-meta-line))
6028 (add-text-properties (match-end 0) (line-end-position)
6029 '(font-lock-fontified t face org-block))
6031 ((member dc3 '(" " ""))
6032 (org-remove-flyspell-overlays-in beg (match-end 0))
6033 (add-text-properties
6034 beg (match-end 0)
6035 '(font-lock-fontified t face font-lock-comment-face)))
6036 (t ;; just any other in-buffer setting, but not indented
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6038 (remove-text-properties (match-beginning 0) (match-end 0)
6039 '(display t invisible t intangible t))
6040 (add-text-properties beg (match-end 0)
6041 '(font-lock-fontified t face org-meta-line))
6042 t))))))
6044 (defun org-fontify-drawers (limit)
6045 "Fontify drawers."
6046 (when (re-search-forward org-drawer-regexp limit t)
6047 (add-text-properties
6048 (match-beginning 0) (match-end 0)
6049 '(font-lock-fontified t face org-special-keyword))
6050 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6053 (defun org-fontify-macros (limit)
6054 "Fontify macros."
6055 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6056 (let ((begin (match-beginning 0))
6057 (opening-end (match-beginning 1)))
6058 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6059 (match-string 1))
6060 (let ((end (match-end 1))
6061 (closing-start (match-beginning 1)))
6062 (add-text-properties
6063 begin end
6064 '(font-lock-multiline t font-lock-fontified t face org-macro))
6065 (org-remove-flyspell-overlays-in begin end)
6066 (when org-hide-macro-markers
6067 (add-text-properties begin opening-end '(invisible t))
6068 (add-text-properties closing-start end '(invisible t)))
6069 t)))))
6071 (defun org-activate-footnote-links (limit)
6072 "Add text properties for footnotes."
6073 (let ((fn (org-footnote-next-reference-or-definition limit)))
6074 (when fn
6075 (let* ((beg (nth 1 fn))
6076 (end (nth 2 fn))
6077 (label (car fn))
6078 (referencep (/= (line-beginning-position) beg)))
6079 (when (and referencep (nth 3 fn))
6080 (save-excursion
6081 (goto-char beg)
6082 (search-forward (or label "fn:"))
6083 (org-remove-flyspell-overlays-in beg (match-end 0))))
6084 (add-text-properties beg end
6085 (list 'mouse-face 'highlight
6086 'keymap org-mouse-map
6087 'help-echo
6088 (if referencep "Footnote reference"
6089 "Footnote definition")
6090 'font-lock-fontified t
6091 'font-lock-multiline t
6092 'face 'org-footnote))))))
6094 (defun org-activate-dates (limit)
6095 "Add text properties for dates."
6096 (when (and (re-search-forward org-tsr-regexp-both limit t)
6097 (not (equal (char-before (match-beginning 0)) 91)))
6098 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6099 (add-text-properties (match-beginning 0) (match-end 0)
6100 (list 'mouse-face 'highlight
6101 'keymap org-mouse-map))
6102 (org-rear-nonsticky-at (match-end 0))
6103 (when org-display-custom-times
6104 ;; If it's a date range, activate custom time for second date.
6105 (when (match-end 3)
6106 (org-display-custom-time (match-beginning 3) (match-end 3)))
6107 (org-display-custom-time (match-beginning 1) (match-end 1)))
6110 (defvar-local org-target-link-regexp nil
6111 "Regular expression matching radio targets in plain text.")
6113 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6114 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6115 border border border))
6116 "Regular expression matching a link target.")
6118 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6119 "Regular expression matching a radio target.")
6121 (defconst org-any-target-regexp
6122 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6123 "Regular expression matching any target.")
6125 (defun org-activate-target-links (limit)
6126 "Add text properties for target matches."
6127 (when org-target-link-regexp
6128 (let ((case-fold-search t))
6129 (when (re-search-forward org-target-link-regexp limit t)
6130 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'mouse-face 'highlight
6133 'keymap org-mouse-map
6134 'help-echo "Radio target link"
6135 'org-linked-text t))
6136 (org-rear-nonsticky-at (match-end 1))
6137 t))))
6139 (defun org-update-radio-target-regexp ()
6140 "Find all radio targets in this file and update the regular expression.
6141 Also refresh fontification if needed."
6142 (interactive)
6143 (let ((old-regexp org-target-link-regexp)
6144 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6145 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6146 (targets
6147 (org-with-wide-buffer
6148 (goto-char (point-min))
6149 (let (rtn)
6150 (while (re-search-forward org-radio-target-regexp nil t)
6151 ;; Make sure point is really within the object.
6152 (backward-char)
6153 (let ((obj (org-element-context)))
6154 (when (eq (org-element-type obj) 'radio-target)
6155 (cl-pushnew (org-element-property :value obj) rtn
6156 :test #'equal))))
6157 rtn))))
6158 (setq org-target-link-regexp
6159 (and targets
6160 (concat before-re
6161 (mapconcat
6162 (lambda (x)
6163 (replace-regexp-in-string
6164 " +" "\\s-+" (regexp-quote x) t t))
6165 targets
6166 "\\|")
6167 after-re)))
6168 (unless (equal old-regexp org-target-link-regexp)
6169 ;; Clean-up cache.
6170 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6171 ((not org-target-link-regexp) old-regexp)
6173 (concat before-re
6174 (mapconcat
6175 (lambda (re)
6176 (substring re (length before-re)
6177 (- (length after-re))))
6178 (list old-regexp org-target-link-regexp)
6179 "\\|")
6180 after-re)))))
6181 (org-with-wide-buffer
6182 (goto-char (point-min))
6183 (while (re-search-forward regexp nil t)
6184 (org-element-cache-refresh (match-beginning 1)))))
6185 ;; Re fontify buffer.
6186 (when (memq 'radio org-highlight-links)
6187 (org-restart-font-lock)))))
6189 (defun org-hide-wide-columns (limit)
6190 (let (s e)
6191 (setq s (text-property-any (point) (or limit (point-max))
6192 'org-cwidth t))
6193 (when s
6194 (setq e (next-single-property-change s 'org-cwidth))
6195 (add-text-properties s e '(invisible org-cwidth))
6196 (goto-char e)
6197 t)))
6199 (defvar org-latex-and-related-regexp nil
6200 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6202 (defun org-compute-latex-and-related-regexp ()
6203 "Compute regular expression for LaTeX, entities and sub/superscript.
6204 Result depends on variable `org-highlight-latex-and-related'."
6205 (setq-local
6206 org-latex-and-related-regexp
6207 (let* ((re-sub
6208 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6209 ((eq org-use-sub-superscripts '{})
6210 (list org-match-substring-with-braces-regexp))
6211 (org-use-sub-superscripts (list org-match-substring-regexp))))
6212 (re-latex
6213 (when (memq 'latex org-highlight-latex-and-related)
6214 (let ((matchers (plist-get org-format-latex-options :matchers)))
6215 (delq nil
6216 (mapcar (lambda (x)
6217 (and (member (car x) matchers) (nth 1 x)))
6218 org-latex-regexps)))))
6219 (re-entities
6220 (when (memq 'entities org-highlight-latex-and-related)
6221 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6222 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6224 (defun org-do-latex-and-related (limit)
6225 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6226 LIMIT bounds the search for syntax to highlight. Stop at first
6227 highlighted object, if any. Return t if some highlighting was
6228 done, nil otherwise."
6229 (when (org-string-nw-p org-latex-and-related-regexp)
6230 (catch 'found
6231 (while (re-search-forward org-latex-and-related-regexp limit t)
6232 (unless
6233 (cl-some
6234 (lambda (f)
6235 (memq f '(org-code org-verbatim underline org-special-keyword)))
6236 (save-excursion
6237 (goto-char (1+ (match-beginning 0)))
6238 (face-at-point nil t)))
6239 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6240 '(?_ ?^))
6242 0)))
6243 (font-lock-prepend-text-property
6244 (+ offset (match-beginning 0)) (match-end 0)
6245 'face 'org-latex-and-related)
6246 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6247 '(font-lock-multiline t)))
6248 (throw 'found t)))
6249 nil)))
6251 (defun org-restart-font-lock ()
6252 "Restart `font-lock-mode', to force refontification."
6253 (when (and (boundp 'font-lock-mode) font-lock-mode)
6254 (font-lock-mode -1)
6255 (font-lock-mode 1)))
6257 (defun org-activate-tags (limit)
6258 (when (re-search-forward
6259 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6260 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6261 (add-text-properties (match-beginning 1) (match-end 1)
6262 (list 'mouse-face 'highlight
6263 'keymap org-mouse-map))
6264 (org-rear-nonsticky-at (match-end 1))
6267 (defun org-outline-level ()
6268 "Compute the outline level of the heading at point.
6270 If this is called at a normal headline, the level is the number
6271 of stars. Use `org-reduced-level' to remove the effect of
6272 `org-odd-levels'. Unlike to `org-current-level', this function
6273 takes into consideration inlinetasks."
6274 (org-with-wide-buffer
6275 (end-of-line)
6276 (if (re-search-backward org-outline-regexp-bol nil t)
6277 (1- (- (match-end 0) (match-beginning 0)))
6278 0)))
6280 (defvar org-font-lock-keywords nil)
6282 (defsubst org-re-property (property &optional literal allow-null value)
6283 "Return a regexp matching a PROPERTY line.
6285 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6286 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6287 non-nil, match properties even without a value.
6289 Match group 3 is set to the value when it exists. If there is no
6290 value and ALLOW-NULL is non-nil, it is set to the empty string.
6292 With optional argument VALUE, match only property lines with
6293 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6294 unless LITERAL is non-nil."
6295 (concat
6296 "^\\(?4:[ \t]*\\)"
6297 (format "\\(?1::\\(?2:%s\\):\\)"
6298 (if literal property (regexp-quote property)))
6299 (cond (value
6300 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6301 (if literal value (regexp-quote value))))
6302 (allow-null
6303 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6305 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6307 (defconst org-property-re
6308 (org-re-property "\\S-+" 'literal t)
6309 "Regular expression matching a property line.
6310 There are four matching groups:
6311 1: :PROPKEY: including the leading and trailing colon,
6312 2: PROPKEY without the leading and trailing colon,
6313 3: PROPVAL without leading or trailing spaces,
6314 4: the indentation of the current line,
6315 5: trailing whitespace.")
6317 (defvar org-font-lock-hook nil
6318 "Functions to be called for special font lock stuff.")
6320 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6322 (defvar org-font-lock-set-keywords-hook nil
6323 "Functions that can manipulate `org-font-lock-extra-keywords'.
6324 This is called after `org-font-lock-extra-keywords' is defined, but before
6325 it is installed to be used by font lock. This can be useful if something
6326 needs to be inserted at a specific position in the font-lock sequence.")
6328 (defun org-font-lock-hook (limit)
6329 "Run `org-font-lock-hook' within LIMIT."
6330 (run-hook-with-args 'org-font-lock-hook limit))
6332 (defun org-set-font-lock-defaults ()
6333 "Set font lock defaults for the current buffer."
6334 (let* ((em org-fontify-emphasized-text)
6335 (lk org-highlight-links)
6336 (org-font-lock-extra-keywords
6337 (list
6338 ;; Call the hook
6339 '(org-font-lock-hook)
6340 ;; Headlines
6341 `(,(if org-fontify-whole-heading-line
6342 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6343 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6344 (1 (org-get-level-face 1))
6345 (2 (org-get-level-face 2))
6346 (3 (org-get-level-face 3)))
6347 ;; Table lines
6348 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6349 (1 'org-table t))
6350 ;; Table internals
6351 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6352 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6353 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6354 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6355 ;; Drawers
6356 '(org-fontify-drawers)
6357 ;; Properties
6358 (list org-property-re
6359 '(1 'org-special-keyword t)
6360 '(3 'org-property-value t))
6361 ;; Link related fontification.
6362 '(org-activate-links)
6363 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6364 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6365 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6366 (when (memq 'footnote lk) '(org-activate-footnote-links))
6367 ;; Targets.
6368 (list org-any-target-regexp '(0 'org-target t))
6369 ;; Diary sexps.
6370 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6371 ;; Macro
6372 '(org-fontify-macros)
6373 '(org-hide-wide-columns (0 nil append))
6374 ;; TODO keyword
6375 (list (format org-heading-keyword-regexp-format
6376 org-todo-regexp)
6377 '(2 (org-get-todo-face 2) t))
6378 ;; DONE
6379 (if org-fontify-done-headline
6380 (list (format org-heading-keyword-regexp-format
6381 (concat
6382 "\\(?:"
6383 (mapconcat 'regexp-quote org-done-keywords "\\|")
6384 "\\)"))
6385 '(2 'org-headline-done t))
6386 nil)
6387 ;; Priorities
6388 '(org-font-lock-add-priority-faces)
6389 ;; Tags
6390 '(org-font-lock-add-tag-faces)
6391 ;; Tags groups
6392 (when (and org-group-tags org-tag-groups-alist)
6393 (list (concat org-outline-regexp-bol ".+\\(:"
6394 (regexp-opt (mapcar 'car org-tag-groups-alist))
6395 ":\\).*$")
6396 '(1 'org-tag-group prepend)))
6397 ;; Special keywords
6398 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6399 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6400 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6401 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6402 ;; Emphasis
6403 (when em '(org-do-emphasis-faces))
6404 ;; Checkboxes
6405 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6406 1 'org-checkbox prepend)
6407 (when (cdr (assq 'checkbox org-list-automatic-rules))
6408 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6409 (0 (org-get-checkbox-statistics-face) t)))
6410 ;; Description list items
6411 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6412 1 'org-list-dt prepend)
6413 ;; ARCHIVEd headings
6414 (list (concat
6415 org-outline-regexp-bol
6416 "\\(.*:" org-archive-tag ":.*\\)")
6417 '(1 'org-archived prepend))
6418 ;; Specials
6419 '(org-do-latex-and-related)
6420 '(org-fontify-entities)
6421 '(org-raise-scripts)
6422 ;; Code
6423 '(org-activate-code (1 'org-code t))
6424 ;; COMMENT
6425 (list (format
6426 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6427 org-todo-regexp
6428 org-comment-string)
6429 '(9 'org-special-keyword t))
6430 ;; Blocks and meta lines
6431 '(org-fontify-meta-lines-and-blocks))))
6432 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6433 (run-hooks 'org-font-lock-set-keywords-hook)
6434 ;; Now set the full font-lock-keywords
6435 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6436 (setq-local font-lock-defaults
6437 '(org-font-lock-keywords t nil nil backward-paragraph))
6438 (kill-local-variable 'font-lock-keywords)
6439 nil))
6441 (defun org-toggle-pretty-entities ()
6442 "Toggle the composition display of entities as UTF8 characters."
6443 (interactive)
6444 (setq-local org-pretty-entities (not org-pretty-entities))
6445 (org-restart-font-lock)
6446 (if org-pretty-entities
6447 (message "Entities are now displayed as UTF8 characters")
6448 (save-restriction
6449 (widen)
6450 (decompose-region (point-min) (point-max))
6451 (message "Entities are now displayed as plain text"))))
6453 (defvar-local org-custom-properties-overlays nil
6454 "List of overlays used for custom properties.")
6456 (defun org-toggle-custom-properties-visibility ()
6457 "Display or hide properties in `org-custom-properties'."
6458 (interactive)
6459 (if org-custom-properties-overlays
6460 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6461 (setq org-custom-properties-overlays nil))
6462 (when org-custom-properties
6463 (org-with-wide-buffer
6464 (goto-char (point-min))
6465 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6466 (while (re-search-forward regexp nil t)
6467 (let ((end (cdr (save-match-data (org-get-property-block)))))
6468 (when (and end (< (point) end))
6469 ;; Hide first custom property in current drawer.
6470 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6471 (overlay-put o 'invisible t)
6472 (overlay-put o 'org-custom-property t)
6473 (push o org-custom-properties-overlays))
6474 ;; Hide additional custom properties in the same drawer.
6475 (while (re-search-forward regexp end t)
6476 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6477 (overlay-put o 'invisible t)
6478 (overlay-put o 'org-custom-property t)
6479 (push o org-custom-properties-overlays)))))
6480 ;; Each entry is limited to a single property drawer.
6481 (outline-next-heading)))))))
6483 (defun org-fontify-entities (limit)
6484 "Find an entity to fontify."
6485 (let (ee)
6486 (when org-pretty-entities
6487 (catch 'match
6488 ;; "\_ "-family is left out on purpose. Only the first one,
6489 ;; i.e., "\_ ", could be fontified anyway, and it would be
6490 ;; confusing when adding a second white space character.
6491 (while (re-search-forward
6492 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6493 limit t)
6494 (when (and (not (org-at-comment-p))
6495 (setq ee (org-entity-get (match-string 1)))
6496 (= (length (nth 6 ee)) 1))
6497 (let* ((end (if (equal (match-string 2) "{}")
6498 (match-end 2)
6499 (match-end 1))))
6500 (add-text-properties
6501 (match-beginning 0) end
6502 (list 'font-lock-fontified t))
6503 (compose-region (match-beginning 0) end
6504 (nth 6 ee) nil)
6505 (backward-char 1)
6506 (throw 'match t))))
6507 nil))))
6509 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6510 "Fontify string S like in Org mode."
6511 (with-temp-buffer
6512 (insert s)
6513 (let ((org-odd-levels-only odd-levels))
6514 (org-mode)
6515 (org-font-lock-ensure)
6516 (buffer-string))))
6518 (defvar org-m nil)
6519 (defvar org-l nil)
6520 (defvar org-f nil)
6521 (defun org-get-level-face (n)
6522 "Get the right face for match N in font-lock matching of headlines."
6523 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6524 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6525 (if org-cycle-level-faces
6526 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6527 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6528 (cond
6529 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6530 ((eq n 2) org-f)
6531 (t (unless org-level-color-stars-only org-f))))
6533 (defun org-face-from-face-or-color (context inherit face-or-color)
6534 "Create a face list that inherits INHERIT, but sets the foreground color.
6535 When FACE-OR-COLOR is not a string, just return it."
6536 (if (stringp face-or-color)
6537 (list :inherit inherit
6538 (cdr (assoc context org-faces-easy-properties))
6539 face-or-color)
6540 face-or-color))
6542 (defun org-get-todo-face (kwd)
6543 "Get the right face for a TODO keyword KWD.
6544 If KWD is a number, get the corresponding match group."
6545 (when (numberp kwd) (setq kwd (match-string kwd)))
6546 (or (org-face-from-face-or-color
6547 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6548 (and (member kwd org-done-keywords) 'org-done)
6549 'org-todo))
6551 (defun org-get-priority-face (priority)
6552 "Get the right face for PRIORITY.
6553 PRIORITY is a character."
6554 (or (org-face-from-face-or-color
6555 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6556 'org-priority))
6558 (defun org-get-tag-face (tag)
6559 "Get the right face for TAG.
6560 If TAG is a number, get the corresponding match group."
6561 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6562 (or (org-face-from-face-or-color
6563 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6564 'org-tag)))
6566 (defun org-font-lock-add-priority-faces (limit)
6567 "Add the special priority faces."
6568 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6569 (add-text-properties
6570 (match-beginning 1) (match-end 1)
6571 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6572 'font-lock-fontified t))))
6574 (defun org-font-lock-add-tag-faces (limit)
6575 "Add the special tag faces."
6576 (when (and org-tag-faces org-tags-special-faces-re)
6577 (while (re-search-forward org-tags-special-faces-re limit t)
6578 (add-text-properties (match-beginning 1) (match-end 1)
6579 (list 'face (org-get-tag-face 1)
6580 'font-lock-fontified t))
6581 (backward-char 1))))
6583 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6584 "Remove fontification and activation overlays from links."
6585 (font-lock-default-unfontify-region beg end)
6586 (let* ((buffer-undo-list t)
6587 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6588 (inhibit-modification-hooks t)
6589 deactivate-mark buffer-file-name buffer-file-truename)
6590 (decompose-region beg end)
6591 (remove-text-properties beg end
6592 '(mouse-face t keymap t org-linked-text t
6593 invisible t intangible t
6594 org-emphasis t))
6595 (org-remove-font-lock-display-properties beg end)))
6597 (defconst org-script-display '(((raise -0.3) (height 0.7))
6598 ((raise 0.3) (height 0.7))
6599 ((raise -0.5))
6600 ((raise 0.5)))
6601 "Display properties for showing superscripts and subscripts.")
6603 (defun org-remove-font-lock-display-properties (beg end)
6604 "Remove specific display properties that have been added by font lock.
6605 The will remove the raise properties that are used to show superscripts
6606 and subscripts."
6607 (let (next prop)
6608 (while (< beg end)
6609 (setq next (next-single-property-change beg 'display nil end)
6610 prop (get-text-property beg 'display))
6611 (when (member prop org-script-display)
6612 (put-text-property beg next 'display nil))
6613 (setq beg next))))
6615 (defun org-raise-scripts (limit)
6616 "Add raise properties to sub/superscripts."
6617 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6618 (re-search-forward
6619 (if (eq org-use-sub-superscripts t)
6620 org-match-substring-regexp
6621 org-match-substring-with-braces-regexp)
6622 limit t))
6623 (let* ((pos (point)) table-p comment-p
6624 (mpos (match-beginning 3))
6625 (emph-p (get-text-property mpos 'org-emphasis))
6626 (link-p (get-text-property mpos 'mouse-face))
6627 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6628 (goto-char (point-at-bol))
6629 (setq table-p (looking-at-p org-table-dataline-regexp)
6630 comment-p (looking-at-p "^[ \t]*#[ +]"))
6631 (goto-char pos)
6632 ;; Handle a_b^c
6633 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6634 (unless (or comment-p emph-p link-p keyw-p)
6635 (put-text-property (match-beginning 3) (match-end 0)
6636 'display
6637 (if (equal (char-after (match-beginning 2)) ?^)
6638 (nth (if table-p 3 1) org-script-display)
6639 (nth (if table-p 2 0) org-script-display)))
6640 (add-text-properties (match-beginning 2) (match-end 2)
6641 (list 'invisible t))
6642 (when (and (eq (char-after (match-beginning 3)) ?{)
6643 (eq (char-before (match-end 3)) ?}))
6644 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6645 (list 'invisible t))
6646 (add-text-properties (1- (match-end 3)) (match-end 3)
6647 (list 'invisible t))))
6648 t)))
6650 ;;;; Visibility cycling, including org-goto and indirect buffer
6652 ;;; Cycling
6654 (defvar-local org-cycle-global-status nil)
6655 (put 'org-cycle-global-status 'org-state t)
6656 (defvar-local org-cycle-subtree-status nil)
6657 (put 'org-cycle-subtree-status 'org-state t)
6659 (defvar org-inlinetask-min-level)
6661 (defun org-unlogged-message (&rest args)
6662 "Display a message, but avoid logging it in the *Messages* buffer."
6663 (let ((message-log-max nil))
6664 (apply 'message args)))
6666 ;;;###autoload
6667 (defun org-cycle (&optional arg)
6668 "TAB-action and visibility cycling for Org mode.
6670 This is the command invoked in Org mode by the `TAB' key. Its main
6671 purpose is outline visibility cycling, but it also invokes other actions
6672 in special contexts.
6674 When this function is called with a `\\[universal-argument]' prefix, rotate \
6675 the entire
6676 buffer through 3 states (global cycling)
6677 1. OVERVIEW: Show only top-level headlines.
6678 2. CONTENTS: Show all headlines of all levels, but no body text.
6679 3. SHOW ALL: Show everything.
6681 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6682 switch to the startup visibility,
6683 determined by the variable `org-startup-folded', and by any VISIBILITY
6684 properties in the buffer.
6686 With a `\\[universal-argument] \\[universal-argument] \
6687 \\[universal-argument]' prefix argument, show the entire buffer, including
6688 any drawers.
6690 When inside a table, re-align the table and move to the next field.
6692 When point is at the beginning of a headline, rotate the subtree started
6693 by this line through 3 different states (local cycling)
6694 1. FOLDED: Only the main headline is shown.
6695 2. CHILDREN: The main headline and the direct children are shown.
6696 From this state, you can move to one of the children
6697 and zoom in further.
6698 3. SUBTREE: Show the entire subtree, including body text.
6699 If there is no subtree, switch directly from CHILDREN to FOLDED.
6701 When point is at the beginning of an empty headline and the variable
6702 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6703 of the headline by demoting and promoting it to likely levels. This
6704 speeds up creation document structure by pressing `TAB' once or several
6705 times right after creating a new headline.
6707 When there is a numeric prefix, go up to a heading with level ARG, do
6708 a `show-subtree' and return to the previous cursor position. If ARG
6709 is negative, go up that many levels.
6711 When point is not at the beginning of a headline, execute the global
6712 binding for `TAB', which is re-indenting the line. See the option
6713 `org-cycle-emulate-tab' for details.
6715 As a special case, if point is at the beginning of the buffer and there is
6716 no headline in line 1, this function will act as if called with prefix arg
6717 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6718 prefix arg, but only
6719 if the variable `org-cycle-global-at-bob' is t."
6720 (interactive "P")
6721 (org-load-modules-maybe)
6722 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6723 (and org-cycle-level-after-item/entry-creation
6724 (or (org-cycle-level)
6725 (org-cycle-item-indentation))))
6726 (let* ((limit-level
6727 (or org-cycle-max-level
6728 (and (boundp 'org-inlinetask-min-level)
6729 org-inlinetask-min-level
6730 (1- org-inlinetask-min-level))))
6731 (nstars (and limit-level
6732 (if org-odd-levels-only
6733 (and limit-level (1- (* limit-level 2)))
6734 limit-level)))
6735 (org-outline-regexp
6736 (if (not (derived-mode-p 'org-mode))
6737 outline-regexp
6738 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6739 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6740 (not (looking-at org-outline-regexp))))
6741 (org-cycle-hook
6742 (if bob-special
6743 (delq 'org-optimize-window-after-visibility-change
6744 (copy-sequence org-cycle-hook))
6745 org-cycle-hook))
6746 (pos (point)))
6748 (cond
6750 ((equal arg '(16))
6751 (setq last-command 'dummy)
6752 (org-set-startup-visibility)
6753 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6755 ((equal arg '(64))
6756 (outline-show-all)
6757 (org-unlogged-message "Entire buffer visible, including drawers"))
6759 ((equal arg '(4)) (org-cycle-internal-global))
6761 ;; Try hiding block at point.
6762 ((org-hide-block-toggle-maybe))
6764 ;; Try cdlatex TAB completion
6765 ((org-try-cdlatex-tab))
6767 ;; Table: enter it or move to the next field.
6768 ((org-at-table-p 'any)
6769 (if (org-at-table.el-p)
6770 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6771 Use `\\[org-edit-special]' to edit table.el tables"))
6772 (if arg (org-table-edit-field t)
6773 (org-table-justify-field-maybe)
6774 (call-interactively 'org-table-next-field))))
6776 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6778 ;; Global cycling: delegate to `org-cycle-internal-global'.
6779 (bob-special (org-cycle-internal-global))
6781 ;; Drawers: delegate to `org-flag-drawer'.
6782 ((save-excursion
6783 (beginning-of-line 1)
6784 (looking-at org-drawer-regexp))
6785 (org-flag-drawer ; toggle block visibility
6786 (not (get-char-property (match-end 0) 'invisible))))
6788 ;; Show-subtree, ARG levels up from here.
6789 ((integerp arg)
6790 (save-excursion
6791 (org-back-to-heading)
6792 (outline-up-heading (if (< arg 0) (- arg)
6793 (- (funcall outline-level) arg)))
6794 (org-show-subtree)))
6796 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6797 ((and (featurep 'org-inlinetask)
6798 (org-inlinetask-at-task-p)
6799 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6800 (org-inlinetask-toggle-visibility))
6802 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6803 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6804 (save-excursion (move-beginning-of-line 1)
6805 (looking-at org-outline-regexp)))
6806 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6807 (org-cycle-internal-local))
6809 ;; From there: TAB emulation and template completion.
6810 (buffer-read-only (org-back-to-heading))
6812 ((run-hook-with-args-until-success
6813 'org-tab-after-check-for-cycling-hook))
6815 ((org-try-structure-completion))
6817 ((run-hook-with-args-until-success
6818 'org-tab-before-tab-emulation-hook))
6820 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6821 (or (not (bolp))
6822 (not (looking-at org-outline-regexp))))
6823 (call-interactively (global-key-binding "\t")))
6825 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6826 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6827 (or (and (eq org-cycle-emulate-tab 'white)
6828 (= (match-end 0) (point-at-eol)))
6829 (and (eq org-cycle-emulate-tab 'whitestart)
6830 (>= (match-end 0) pos))))
6832 (eq org-cycle-emulate-tab t))
6833 (call-interactively (global-key-binding "\t")))
6835 (t (save-excursion
6836 (org-back-to-heading)
6837 (org-cycle)))))))
6839 (defun org-cycle-internal-global ()
6840 "Do the global cycling action."
6841 ;; Hack to avoid display of messages for .org attachments in Gnus
6842 (let ((ga (string-match "\\*fontification" (buffer-name))))
6843 (cond
6844 ((and (eq last-command this-command)
6845 (eq org-cycle-global-status 'overview))
6846 ;; We just created the overview - now do table of contents
6847 ;; This can be slow in very large buffers, so indicate action
6848 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6849 (unless ga (org-unlogged-message "CONTENTS..."))
6850 (org-content)
6851 (unless ga (org-unlogged-message "CONTENTS...done"))
6852 (setq org-cycle-global-status 'contents)
6853 (run-hook-with-args 'org-cycle-hook 'contents))
6855 ((and (eq last-command this-command)
6856 (eq org-cycle-global-status 'contents))
6857 ;; We just showed the table of contents - now show everything
6858 (run-hook-with-args 'org-pre-cycle-hook 'all)
6859 (outline-show-all)
6860 (unless ga (org-unlogged-message "SHOW ALL"))
6861 (setq org-cycle-global-status 'all)
6862 (run-hook-with-args 'org-cycle-hook 'all))
6865 ;; Default action: go to overview
6866 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6867 (org-overview)
6868 (unless ga (org-unlogged-message "OVERVIEW"))
6869 (setq org-cycle-global-status 'overview)
6870 (run-hook-with-args 'org-cycle-hook 'overview)))))
6872 (defvar org-called-with-limited-levels nil
6873 "Non-nil when `org-with-limited-levels' is currently active.")
6875 (defun org-invisible-p (&optional pos)
6876 "Non-nil if the character after POS is invisible.
6877 If POS is nil, use `point' instead."
6878 (get-char-property (or pos (point)) 'invisible))
6880 (defun org-cycle-internal-local ()
6881 "Do the local cycling action."
6882 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6883 ;; First, determine end of headline (EOH), end of subtree or item
6884 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6885 (save-excursion
6886 (if (org-at-item-p)
6887 (progn
6888 (beginning-of-line)
6889 (setq struct (org-list-struct))
6890 (setq eoh (point-at-eol))
6891 (setq eos (org-list-get-item-end-before-blank (point) struct))
6892 (setq has-children (org-list-has-child-p (point) struct)))
6893 (org-back-to-heading)
6894 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6895 (setq eos (save-excursion (org-end-of-subtree t t)
6896 (when (bolp) (backward-char)) (point)))
6897 (setq has-children
6898 (or (save-excursion
6899 (let ((level (funcall outline-level)))
6900 (outline-next-heading)
6901 (and (org-at-heading-p t)
6902 (> (funcall outline-level) level))))
6903 (save-excursion
6904 (org-list-search-forward (org-item-beginning-re) eos t)))))
6905 ;; Determine end invisible part of buffer (EOL)
6906 (beginning-of-line 2)
6907 (while (and (not (eobp)) ;This is like `next-line'.
6908 (get-char-property (1- (point)) 'invisible))
6909 (goto-char (next-single-char-property-change (point) 'invisible))
6910 (and (eolp) (beginning-of-line 2)))
6911 (setq eol (point)))
6912 ;; Find out what to do next and set `this-command'
6913 (cond
6914 ((= eos eoh)
6915 ;; Nothing is hidden behind this heading
6916 (unless (org-before-first-heading-p)
6917 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6918 (org-unlogged-message "EMPTY ENTRY")
6919 (setq org-cycle-subtree-status nil)
6920 (save-excursion
6921 (goto-char eos)
6922 (outline-next-heading)
6923 (when (org-invisible-p) (org-flag-heading nil))))
6924 ((and (or (>= eol eos)
6925 (not (string-match "\\S-" (buffer-substring eol eos))))
6926 (or has-children
6927 (not (setq children-skipped
6928 org-cycle-skip-children-state-if-no-children))))
6929 ;; Entire subtree is hidden in one line: children view
6930 (unless (org-before-first-heading-p)
6931 (run-hook-with-args 'org-pre-cycle-hook 'children))
6932 (if (org-at-item-p)
6933 (org-list-set-item-visibility (point-at-bol) struct 'children)
6934 (org-show-entry)
6935 (org-with-limited-levels (org-show-children))
6936 (org-show-set-visibility 'canonical)
6937 ;; FIXME: This slows down the func way too much.
6938 ;; How keep drawers hidden in subtree anyway?
6939 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6940 ;; (org-cycle-hide-drawers 'subtree))
6942 ;; Fold every list in subtree to top-level items.
6943 (when (eq org-cycle-include-plain-lists 'integrate)
6944 (save-excursion
6945 (org-back-to-heading)
6946 (while (org-list-search-forward (org-item-beginning-re) eos t)
6947 (beginning-of-line 1)
6948 (let* ((struct (org-list-struct))
6949 (prevs (org-list-prevs-alist struct))
6950 (end (org-list-get-bottom-point struct)))
6951 (dolist (e (org-list-get-all-items (point) struct prevs))
6952 (org-list-set-item-visibility e struct 'folded))
6953 (goto-char (if (< end eos) end eos)))))))
6954 (org-unlogged-message "CHILDREN")
6955 (save-excursion
6956 (goto-char eos)
6957 (outline-next-heading)
6958 (when (org-invisible-p) (org-flag-heading nil)))
6959 (setq org-cycle-subtree-status 'children)
6960 (unless (org-before-first-heading-p)
6961 (run-hook-with-args 'org-cycle-hook 'children)))
6962 ((or children-skipped
6963 (and (eq last-command this-command)
6964 (eq org-cycle-subtree-status 'children)))
6965 ;; We just showed the children, or no children are there,
6966 ;; now show everything.
6967 (unless (org-before-first-heading-p)
6968 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6969 (outline-flag-region eoh eos nil)
6970 (org-unlogged-message
6971 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6972 (setq org-cycle-subtree-status 'subtree)
6973 (unless (org-before-first-heading-p)
6974 (run-hook-with-args 'org-cycle-hook 'subtree)))
6976 ;; Default action: hide the subtree.
6977 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6978 (outline-flag-region eoh eos t)
6979 (org-unlogged-message "FOLDED")
6980 (setq org-cycle-subtree-status 'folded)
6981 (unless (org-before-first-heading-p)
6982 (run-hook-with-args 'org-cycle-hook 'folded))))))
6984 ;;;###autoload
6985 (defun org-global-cycle (&optional arg)
6986 "Cycle the global visibility. For details see `org-cycle'.
6987 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6988 With a numeric prefix, show all headlines up to that level."
6989 (interactive "P")
6990 (let ((org-cycle-include-plain-lists
6991 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6992 (cond
6993 ((integerp arg)
6994 (outline-show-all)
6995 (outline-hide-sublevels arg)
6996 (setq org-cycle-global-status 'contents))
6997 ((equal arg '(4))
6998 (org-set-startup-visibility)
6999 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7001 (org-cycle '(4))))))
7003 (defun org-set-startup-visibility ()
7004 "Set the visibility required by startup options and properties."
7005 (cond
7006 ((eq org-startup-folded t)
7007 (org-overview))
7008 ((eq org-startup-folded 'content)
7009 (org-content))
7010 ((or (eq org-startup-folded 'showeverything)
7011 (eq org-startup-folded nil))
7012 (outline-show-all)))
7013 (unless (eq org-startup-folded 'showeverything)
7014 (when org-hide-block-startup (org-hide-block-all))
7015 (org-set-visibility-according-to-property 'no-cleanup)
7016 (org-cycle-hide-archived-subtrees 'all)
7017 (org-cycle-hide-drawers 'all)
7018 (org-cycle-show-empty-lines t)))
7020 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7021 "Switch subtree visibilities according to :VISIBILITY: property."
7022 (interactive)
7023 (org-with-wide-buffer
7024 (goto-char (point-min))
7025 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7026 (if (not (org-at-property-p)) (outline-next-heading)
7027 (let ((state (match-string 3)))
7028 (save-excursion
7029 (org-back-to-heading t)
7030 (outline-hide-subtree)
7031 (org-reveal))
7032 (cond
7033 ((equal state "folded")
7034 (outline-hide-subtree)
7035 (org-end-of-subtree t t))
7036 ((equal state "children")
7037 (org-show-hidden-entry)
7038 (org-show-children))
7039 ((equal state "content")
7040 (save-excursion
7041 (save-restriction
7042 (org-narrow-to-subtree)
7043 (org-content)))
7044 (org-end-of-subtree t t))
7045 ((member state '("all" "showall"))
7046 (outline-show-subtree))))))
7047 (unless no-cleanup
7048 (org-cycle-hide-archived-subtrees 'all)
7049 (org-cycle-hide-drawers 'all)
7050 (org-cycle-show-empty-lines 'all))))
7052 ;; This function uses outline-regexp instead of the more fundamental
7053 ;; org-outline-regexp so that org-cycle-global works outside of Org
7054 ;; buffers, where outline-regexp is needed.
7055 (defun org-overview ()
7056 "Switch to overview mode, showing only top-level headlines.
7057 This shows all headlines with a level equal or greater than the level
7058 of the first headline in the buffer. This is important, because if the
7059 first headline is not level one, then (hide-sublevels 1) gives confusing
7060 results."
7061 (interactive)
7062 (save-excursion
7063 (let ((level
7064 (save-excursion
7065 (goto-char (point-min))
7066 (when (re-search-forward (concat "^" outline-regexp) nil t)
7067 (goto-char (match-beginning 0))
7068 (funcall outline-level)))))
7069 (and level (outline-hide-sublevels level)))))
7071 (defun org-content (&optional arg)
7072 "Show all headlines in the buffer, like a table of contents.
7073 With numerical argument N, show content up to level N."
7074 (interactive "P")
7075 (org-overview)
7076 (save-excursion
7077 ;; Visit all headings and show their offspring
7078 (and (integerp arg) (org-overview))
7079 (goto-char (point-max))
7080 (catch 'exit
7081 (while (and (progn (condition-case nil
7082 (outline-previous-visible-heading 1)
7083 (error (goto-char (point-min))))
7085 (looking-at org-outline-regexp))
7086 (if (integerp arg)
7087 (org-show-children (1- arg))
7088 (outline-show-branches))
7089 (when (bobp) (throw 'exit nil))))))
7091 (defun org-optimize-window-after-visibility-change (state)
7092 "Adjust the window after a change in outline visibility.
7093 This function is the default value of the hook `org-cycle-hook'."
7094 (when (get-buffer-window (current-buffer))
7095 (cond
7096 ((eq state 'content) nil)
7097 ((eq state 'all) nil)
7098 ((eq state 'folded) nil)
7099 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7100 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7102 (defun org-remove-empty-overlays-at (pos)
7103 "Remove outline overlays that do not contain non-white stuff."
7104 (dolist (o (overlays-at pos))
7105 (and (eq 'outline (overlay-get o 'invisible))
7106 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7107 (overlay-end o))))
7108 (delete-overlay o))))
7110 (defun org-clean-visibility-after-subtree-move ()
7111 "Fix visibility issues after moving a subtree."
7112 ;; First, find a reasonable region to look at:
7113 ;; Start two siblings above, end three below
7114 (let* ((beg (save-excursion
7115 (and (org-get-last-sibling)
7116 (org-get-last-sibling))
7117 (point)))
7118 (end (save-excursion
7119 (and (org-get-next-sibling)
7120 (org-get-next-sibling)
7121 (org-get-next-sibling))
7122 (if (org-at-heading-p)
7123 (point-at-eol)
7124 (point))))
7125 (level (looking-at "\\*+"))
7126 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7127 (save-excursion
7128 (save-restriction
7129 (narrow-to-region beg end)
7130 (when re
7131 ;; Properly fold already folded siblings
7132 (goto-char (point-min))
7133 (while (re-search-forward re nil t)
7134 (when (and (not (org-invisible-p))
7135 (save-excursion
7136 (goto-char (point-at-eol)) (org-invisible-p)))
7137 (outline-hide-entry))))
7138 (org-cycle-show-empty-lines 'overview)
7139 (org-cycle-hide-drawers 'overview)))))
7141 (defun org-cycle-show-empty-lines (state)
7142 "Show empty lines above all visible headlines.
7143 The region to be covered depends on STATE when called through
7144 `org-cycle-hook'. Lisp program can use t for STATE to get the
7145 entire buffer covered. Note that an empty line is only shown if there
7146 are at least `org-cycle-separator-lines' empty lines before the headline."
7147 (when (/= org-cycle-separator-lines 0)
7148 (save-excursion
7149 (let* ((n (abs org-cycle-separator-lines))
7150 (re (cond
7151 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7152 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7153 (t (let ((ns (number-to-string (- n 2))))
7154 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7155 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7156 beg end)
7157 (cond
7158 ((memq state '(overview contents t))
7159 (setq beg (point-min) end (point-max)))
7160 ((memq state '(children folded))
7161 (setq beg (point)
7162 end (progn (org-end-of-subtree t t)
7163 (line-beginning-position 2)))))
7164 (when beg
7165 (goto-char beg)
7166 (while (re-search-forward re end t)
7167 (unless (get-char-property (match-end 1) 'invisible)
7168 (let ((e (match-end 1))
7169 (b (if (>= org-cycle-separator-lines 0)
7170 (match-beginning 1)
7171 (save-excursion
7172 (goto-char (match-beginning 0))
7173 (skip-chars-backward " \t\n")
7174 (line-end-position)))))
7175 (outline-flag-region b e nil))))))))
7176 ;; Never hide empty lines at the end of the file.
7177 (save-excursion
7178 (goto-char (point-max))
7179 (outline-previous-heading)
7180 (outline-end-of-heading)
7181 (when (and (looking-at "[ \t\n]+")
7182 (= (match-end 0) (point-max)))
7183 (outline-flag-region (point) (match-end 0) nil))))
7185 (defun org-show-empty-lines-in-parent ()
7186 "Move to the parent and re-show empty lines before visible headlines."
7187 (save-excursion
7188 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7189 (org-cycle-show-empty-lines context))))
7191 (defun org-files-list ()
7192 "Return `org-agenda-files' list, plus all open Org files.
7193 This is useful for operations that need to scan all of a user's
7194 open and agenda-wise Org files."
7195 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7196 (dolist (buf (buffer-list))
7197 (with-current-buffer buf
7198 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7199 (cl-pushnew (expand-file-name (buffer-file-name)) files
7200 :test #'equal))))
7201 files))
7203 (defsubst org-entry-beginning-position ()
7204 "Return the beginning position of the current entry."
7205 (save-excursion (org-back-to-heading t) (point)))
7207 (defsubst org-entry-end-position ()
7208 "Return the end position of the current entry."
7209 (save-excursion (outline-next-heading) (point)))
7211 (defun org-cycle-hide-drawers (state &optional exceptions)
7212 "Re-hide all drawers after a visibility state change.
7213 STATE should be one of the symbols listed in the docstring of
7214 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7215 a list of strings specifying which drawers should not be hidden."
7216 (when (and (derived-mode-p 'org-mode)
7217 (not (memq state '(overview folded contents))))
7218 (save-excursion
7219 (let* ((globalp (eq state 'all))
7220 (beg (if globalp (point-min) (point)))
7221 (end (if globalp (point-max)
7222 (if (eq state 'children)
7223 (save-excursion (outline-next-heading) (point))
7224 (org-end-of-subtree t)))))
7225 (goto-char beg)
7226 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7227 (unless (member-ignore-case (match-string 1) exceptions)
7228 (let ((drawer (org-element-at-point)))
7229 (when (memq (org-element-type drawer) '(drawer property-drawer))
7230 (org-flag-drawer t drawer)
7231 ;; Make sure to skip drawer entirely or we might flag
7232 ;; it another time when matching its ending line with
7233 ;; `org-drawer-regexp'.
7234 (goto-char (org-element-property :end drawer))))))))))
7236 (defun org-flag-drawer (flag &optional element)
7237 "When FLAG is non-nil, hide the drawer we are at.
7238 Otherwise make it visible. When optional argument ELEMENT is
7239 a parsed drawer, as returned by `org-element-at-point', hide or
7240 show that drawer instead."
7241 (let ((drawer (or element
7242 (and (save-excursion
7243 (beginning-of-line)
7244 (looking-at-p org-drawer-regexp))
7245 (org-element-at-point)))))
7246 (when (memq (org-element-type drawer) '(drawer property-drawer))
7247 (let ((post (org-element-property :post-affiliated drawer)))
7248 (save-excursion
7249 (outline-flag-region
7250 (progn (goto-char post) (line-end-position))
7251 (progn (goto-char (org-element-property :end drawer))
7252 (skip-chars-backward " \r\t\n")
7253 (line-end-position))
7254 flag))
7255 ;; When the drawer is hidden away, make sure point lies in
7256 ;; a visible part of the buffer.
7257 (when (and flag (> (line-beginning-position) post))
7258 (goto-char post))))))
7260 (defun org-subtree-end-visible-p ()
7261 "Is the end of the current subtree visible?"
7262 (pos-visible-in-window-p
7263 (save-excursion (org-end-of-subtree t) (point))))
7265 (defun org-first-headline-recenter ()
7266 "Move cursor to the first headline and recenter the headline."
7267 (let ((window (get-buffer-window)))
7268 (when window
7269 (goto-char (point-min))
7270 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7271 (set-window-start window (line-beginning-position))))))
7273 ;;; Saving and restoring visibility
7275 (defun org-outline-overlay-data (&optional use-markers)
7276 "Return a list of the locations of all outline overlays.
7277 These are overlays with the `invisible' property value `outline'.
7278 The return value is a list of cons cells, with start and stop
7279 positions for each overlay.
7280 If USE-MARKERS is set, return the positions as markers."
7281 (let (beg end)
7282 (org-with-wide-buffer
7283 (delq nil
7284 (mapcar (lambda (o)
7285 (when (eq (overlay-get o 'invisible) 'outline)
7286 (setq beg (overlay-start o)
7287 end (overlay-end o))
7288 (and beg end (> end beg)
7289 (if use-markers
7290 (cons (copy-marker beg)
7291 (copy-marker end t))
7292 (cons beg end)))))
7293 (overlays-in (point-min) (point-max)))))))
7295 (defun org-set-outline-overlay-data (data)
7296 "Create visibility overlays for all positions in DATA.
7297 DATA should have been made by `org-outline-overlay-data'."
7298 (org-with-wide-buffer
7299 (outline-show-all)
7300 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7302 ;;; Folding of blocks
7304 (defvar-local org-hide-block-overlays nil
7305 "Overlays hiding blocks.")
7307 (defun org-block-map (function &optional start end)
7308 "Call FUNCTION at the head of all source blocks in the current buffer.
7309 Optional arguments START and END can be used to limit the range."
7310 (let ((start (or start (point-min)))
7311 (end (or end (point-max))))
7312 (save-excursion
7313 (goto-char start)
7314 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7315 (save-excursion
7316 (save-match-data
7317 (goto-char (match-beginning 0))
7318 (funcall function)))))))
7320 (defun org-hide-block-toggle-all ()
7321 "Toggle the visibility of all blocks in the current buffer."
7322 (org-block-map 'org-hide-block-toggle))
7324 (defun org-hide-block-all ()
7325 "Fold all blocks in the current buffer."
7326 (interactive)
7327 (org-show-block-all)
7328 (org-block-map 'org-hide-block-toggle-maybe))
7330 (defun org-show-block-all ()
7331 "Unfold all blocks in the current buffer."
7332 (interactive)
7333 (mapc #'delete-overlay org-hide-block-overlays)
7334 (setq org-hide-block-overlays nil))
7336 (defun org-hide-block-toggle-maybe ()
7337 "Toggle visibility of block at point.
7338 Unlike to `org-hide-block-toggle', this function does not throw
7339 an error. Return a non-nil value when toggling is successful."
7340 (interactive)
7341 (ignore-errors (org-hide-block-toggle)))
7343 (defun org-hide-block-toggle (&optional force)
7344 "Toggle the visibility of the current block.
7345 When optional argument FORCE is `off', make block visible. If it
7346 is non-nil, hide it unconditionally. Throw an error when not at
7347 a block. Return a non-nil value when toggling is successful."
7348 (interactive)
7349 (let ((element (org-element-at-point)))
7350 (unless (memq (org-element-type element)
7351 '(center-block comment-block dynamic-block example-block
7352 export-block quote-block special-block
7353 src-block verse-block))
7354 (user-error "Not at a block"))
7355 (let* ((start (save-excursion
7356 (goto-char (org-element-property :post-affiliated element))
7357 (line-end-position)))
7358 (end (save-excursion
7359 (goto-char (org-element-property :end element))
7360 (skip-chars-backward " \r\t\n")
7361 (line-end-position)))
7362 (overlays (overlays-at start)))
7363 (cond
7364 ;; Do nothing when not before or at the block opening line or
7365 ;; at the block closing line.
7366 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7367 ((and (not (eq force 'off))
7368 (not (memq t (mapcar
7369 (lambda (o)
7370 (eq (overlay-get o 'invisible) 'org-hide-block))
7371 overlays))))
7372 (let ((ov (make-overlay start end)))
7373 (overlay-put ov 'invisible 'org-hide-block)
7374 ;; Make the block accessible to `isearch'.
7375 (overlay-put
7376 ov 'isearch-open-invisible
7377 (lambda (ov)
7378 (when (memq ov org-hide-block-overlays)
7379 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7380 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7381 (delete-overlay ov))))
7382 (push ov org-hide-block-overlays)
7383 ;; When the block is hidden away, make sure point is left in
7384 ;; a visible part of the buffer.
7385 (when (> (line-beginning-position) start)
7386 (goto-char start)
7387 (beginning-of-line))
7388 ;; Signal successful toggling.
7390 ((or (not force) (eq force 'off))
7391 (dolist (ov overlays t)
7392 (when (memq ov org-hide-block-overlays)
7393 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7394 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7395 (delete-overlay ov))))))))
7397 ;; Remove overlays when changing major mode
7398 (add-hook 'org-mode-hook
7399 (lambda () (add-hook 'change-major-mode-hook
7400 'org-show-block-all 'append 'local)))
7402 ;;; Org-goto
7404 (defvar org-goto-window-configuration nil)
7405 (defvar org-goto-marker nil)
7406 (defvar org-goto-map)
7407 (defun org-goto-map ()
7408 "Set the keymap `org-goto'."
7409 (setq org-goto-map
7410 (let ((map (make-sparse-keymap)))
7411 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7412 mouse-drag-region universal-argument org-occur)))
7413 (dolist (cmd cmds)
7414 (substitute-key-definition cmd cmd map global-map)))
7415 (suppress-keymap map)
7416 (org-defkey map "\C-m" 'org-goto-ret)
7417 (org-defkey map [(return)] 'org-goto-ret)
7418 (org-defkey map [(left)] 'org-goto-left)
7419 (org-defkey map [(right)] 'org-goto-right)
7420 (org-defkey map [(control ?g)] 'org-goto-quit)
7421 (org-defkey map "\C-i" 'org-cycle)
7422 (org-defkey map [(tab)] 'org-cycle)
7423 (org-defkey map [(down)] 'outline-next-visible-heading)
7424 (org-defkey map [(up)] 'outline-previous-visible-heading)
7425 (if org-goto-auto-isearch
7426 (if (fboundp 'define-key-after)
7427 (define-key-after map [t] 'org-goto-local-auto-isearch)
7428 nil)
7429 (org-defkey map "q" 'org-goto-quit)
7430 (org-defkey map "n" 'outline-next-visible-heading)
7431 (org-defkey map "p" 'outline-previous-visible-heading)
7432 (org-defkey map "f" 'outline-forward-same-level)
7433 (org-defkey map "b" 'outline-backward-same-level)
7434 (org-defkey map "u" 'outline-up-heading))
7435 (org-defkey map "/" 'org-occur)
7436 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7437 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7438 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7439 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7440 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7441 map)))
7443 (defconst org-goto-help
7444 "Browse buffer copy, to find location or copy text.%s
7445 RET=jump to location C-g=quit and return to previous location
7446 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7448 (defvar org-goto-start-pos) ; dynamically scoped parameter
7450 (defun org-goto (&optional alternative-interface)
7451 "Look up a different location in the current file, keeping current visibility.
7453 When you want look-up or go to a different location in a
7454 document, the fastest way is often to fold the entire buffer and
7455 then dive into the tree. This method has the disadvantage, that
7456 the previous location will be folded, which may not be what you
7457 want.
7459 This command works around this by showing a copy of the current
7460 buffer in an indirect buffer, in overview mode. You can dive
7461 into the tree in that copy, use org-occur and incremental search
7462 to find a location. When pressing RET or `Q', the command
7463 returns to the original buffer in which the visibility is still
7464 unchanged. After RET it will also jump to the location selected
7465 in the indirect buffer and expose the headline hierarchy above.
7467 With a prefix argument, use the alternative interface: e.g., if
7468 `org-goto-interface' is `outline' use `outline-path-completion'."
7469 (interactive "P")
7470 (org-goto-map)
7471 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7472 (org-refile-use-outline-path t)
7473 (org-refile-target-verify-function nil)
7474 (interface
7475 (if (not alternative-interface)
7476 org-goto-interface
7477 (if (eq org-goto-interface 'outline)
7478 'outline-path-completion
7479 'outline)))
7480 (org-goto-start-pos (point))
7481 (selected-point
7482 (if (eq interface 'outline)
7483 (car (org-get-location (current-buffer) org-goto-help))
7484 (let ((pa (org-refile-get-location "Goto")))
7485 (org-refile-check-position pa)
7486 (nth 3 pa)))))
7487 (if selected-point
7488 (progn
7489 (org-mark-ring-push org-goto-start-pos)
7490 (goto-char selected-point)
7491 (when (or (org-invisible-p) (org-invisible-p2))
7492 (org-show-context 'org-goto)))
7493 (message "Quit"))))
7495 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7496 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7497 (defvar org-goto-local-auto-isearch-map) ; defined below
7499 (defun org-get-location (_buf help)
7500 "Let the user select a location in current buffer.
7501 This function uses a recursive edit. It returns the selected position
7502 or nil."
7503 (org-no-popups
7504 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7505 (isearch-hide-immediately nil)
7506 (isearch-search-fun-function
7507 (lambda () 'org-goto-local-search-headings))
7508 (org-goto-selected-point org-goto-exit-command))
7509 (save-excursion
7510 (save-window-excursion
7511 (delete-other-windows)
7512 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7513 (pop-to-buffer-same-window
7514 (condition-case nil
7515 (make-indirect-buffer (current-buffer) "*org-goto*")
7516 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7517 (with-output-to-temp-buffer "*Org Help*"
7518 (princ (format help (if org-goto-auto-isearch
7519 " Just type for auto-isearch."
7520 " n/p/f/b/u to navigate, q to quit."))))
7521 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7522 (setq buffer-read-only nil)
7523 (let ((org-startup-truncated t)
7524 (org-startup-folded nil)
7525 (org-startup-align-all-tables nil))
7526 (org-mode)
7527 (org-overview))
7528 (setq buffer-read-only t)
7529 (if (and (boundp 'org-goto-start-pos)
7530 (integer-or-marker-p org-goto-start-pos))
7531 (progn (goto-char org-goto-start-pos)
7532 (when (org-invisible-p)
7533 (org-show-set-visibility 'lineage)))
7534 (goto-char (point-min)))
7535 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7536 (message "Select location and press RET")
7537 (use-local-map org-goto-map)
7538 (recursive-edit)))
7539 (kill-buffer "*org-goto*")
7540 (cons org-goto-selected-point org-goto-exit-command))))
7542 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7543 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7544 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7545 (if (fboundp 'isearch-other-control-char)
7546 (progn
7547 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7548 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7549 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7550 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7551 (define-key org-goto-local-auto-isearch-map [return] nil))
7553 (defun org-goto-local-search-headings (string bound noerror)
7554 "Search and make sure that any matches are in headlines."
7555 (catch 'return
7556 (while (if isearch-forward
7557 (search-forward string bound noerror)
7558 (search-backward string bound noerror))
7559 (when (save-match-data
7560 (and (save-excursion
7561 (beginning-of-line)
7562 (looking-at org-complex-heading-regexp))
7563 (or (not (match-beginning 5))
7564 (< (point) (match-beginning 5)))))
7565 (throw 'return (point))))))
7567 (defun org-goto-local-auto-isearch ()
7568 "Start isearch."
7569 (interactive)
7570 (goto-char (point-min))
7571 (let ((keys (this-command-keys)))
7572 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7573 (isearch-mode t)
7574 (isearch-process-search-char (string-to-char keys)))))
7576 (defun org-goto-ret (&optional _arg)
7577 "Finish `org-goto' by going to the new location."
7578 (interactive "P")
7579 (setq org-goto-selected-point (point))
7580 (setq org-goto-exit-command 'return)
7581 (throw 'exit nil))
7583 (defun org-goto-left ()
7584 "Finish `org-goto' by going to the new location."
7585 (interactive)
7586 (if (org-at-heading-p)
7587 (progn
7588 (beginning-of-line 1)
7589 (setq org-goto-selected-point (point)
7590 org-goto-exit-command 'left)
7591 (throw 'exit nil))
7592 (user-error "Not on a heading")))
7594 (defun org-goto-right ()
7595 "Finish `org-goto' by going to the new location."
7596 (interactive)
7597 (if (org-at-heading-p)
7598 (progn
7599 (setq org-goto-selected-point (point)
7600 org-goto-exit-command 'right)
7601 (throw 'exit nil))
7602 (user-error "Not on a heading")))
7604 (defun org-goto-quit ()
7605 "Finish `org-goto' without cursor motion."
7606 (interactive)
7607 (setq org-goto-selected-point nil)
7608 (setq org-goto-exit-command 'quit)
7609 (throw 'exit nil))
7611 ;;; Indirect buffer display of subtrees
7613 (defvar org-indirect-dedicated-frame nil
7614 "This is the frame being used for indirect tree display.")
7615 (defvar org-last-indirect-buffer nil)
7617 (defun org-tree-to-indirect-buffer (&optional arg)
7618 "Create indirect buffer and narrow it to current subtree.
7620 With a numerical prefix ARG, go up to this level and then take that tree.
7621 If ARG is negative, go up that many levels.
7623 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7624 indirect buffer previously made with this command, to avoid proliferation of
7625 indirect buffers. However, when you call the command with a \
7626 `\\[universal-argument]' prefix, or
7627 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7628 so that you can work with several indirect buffers at the same time. If
7629 `org-indirect-buffer-display' is `dedicated-frame', the \
7630 `\\[universal-argument]' prefix also
7631 requests that a new frame be made for the new buffer, so that the dedicated
7632 frame is not changed."
7633 (interactive "P")
7634 (let ((cbuf (current-buffer))
7635 (cwin (selected-window))
7636 (pos (point))
7637 beg end level heading ibuf)
7638 (save-excursion
7639 (org-back-to-heading t)
7640 (when (numberp arg)
7641 (setq level (org-outline-level))
7642 (when (< arg 0) (setq arg (+ level arg)))
7643 (while (> (setq level (org-outline-level)) arg)
7644 (org-up-heading-safe)))
7645 (setq beg (point)
7646 heading (org-get-heading 'no-tags))
7647 (org-end-of-subtree t t)
7648 (when (org-at-heading-p) (backward-char 1))
7649 (setq end (point)))
7650 (when (and (buffer-live-p org-last-indirect-buffer)
7651 (not (eq org-indirect-buffer-display 'new-frame))
7652 (not arg))
7653 (kill-buffer org-last-indirect-buffer))
7654 (setq ibuf (org-get-indirect-buffer cbuf heading)
7655 org-last-indirect-buffer ibuf)
7656 (cond
7657 ((or (eq org-indirect-buffer-display 'new-frame)
7658 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7659 (select-frame (make-frame))
7660 (delete-other-windows)
7661 (pop-to-buffer-same-window ibuf)
7662 (org-set-frame-title heading))
7663 ((eq org-indirect-buffer-display 'dedicated-frame)
7664 (raise-frame
7665 (select-frame (or (and org-indirect-dedicated-frame
7666 (frame-live-p org-indirect-dedicated-frame)
7667 org-indirect-dedicated-frame)
7668 (setq org-indirect-dedicated-frame (make-frame)))))
7669 (delete-other-windows)
7670 (pop-to-buffer-same-window ibuf)
7671 (org-set-frame-title (concat "Indirect: " heading)))
7672 ((eq org-indirect-buffer-display 'current-window)
7673 (pop-to-buffer-same-window ibuf))
7674 ((eq org-indirect-buffer-display 'other-window)
7675 (pop-to-buffer ibuf))
7676 (t (error "Invalid value")))
7677 (narrow-to-region beg end)
7678 (outline-show-all)
7679 (goto-char pos)
7680 (run-hook-with-args 'org-cycle-hook 'all)
7681 (and (window-live-p cwin) (select-window cwin))))
7683 (defun org-get-indirect-buffer (&optional buffer heading)
7684 (setq buffer (or buffer (current-buffer)))
7685 (let ((n 1) (base (buffer-name buffer)) bname)
7686 (while (buffer-live-p
7687 (get-buffer
7688 (setq bname
7689 (concat base "-"
7690 (if heading (concat heading "-" (number-to-string n))
7691 (number-to-string n))))))
7692 (setq n (1+ n)))
7693 (condition-case nil
7694 (make-indirect-buffer buffer bname 'clone)
7695 (error (make-indirect-buffer buffer bname)))))
7697 (defun org-set-frame-title (title)
7698 "Set the title of the current frame to the string TITLE."
7699 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7701 ;;;; Structure editing
7703 ;;; Inserting headlines
7705 (defun org--line-empty-p (n)
7706 "Is the Nth next line empty?
7708 Counts the current line as N = 1 and the previous line as N = 0;
7709 see `beginning-of-line'."
7710 (save-excursion
7711 (and (not (bobp))
7712 (or (beginning-of-line n) t)
7713 (save-match-data
7714 (looking-at "[ \t]*$")))))
7716 (defun org-previous-line-empty-p ()
7717 "Is the previous line a blank line?
7718 When NEXT is non-nil, check the next line instead."
7719 (org--line-empty-p 0))
7721 (defun org-next-line-empty-p ()
7722 "Is the previous line a blank line?
7723 When NEXT is non-nil, check the next line instead."
7724 (org--line-empty-p 2))
7726 (defun org--blank-before-heading-p (&optional parent)
7727 "Non-nil when an empty line should precede a new heading here.
7728 When optional argument PARENT is non-nil, consider parent
7729 headline instead of current one."
7730 (pcase (assq 'heading org-blank-before-new-entry)
7731 (`(heading . auto)
7732 (save-excursion
7733 (org-with-limited-levels
7734 (unless (and (org-before-first-heading-p)
7735 (not (outline-next-heading)))
7736 (org-back-to-heading t)
7737 (when parent (org-up-heading-safe))
7738 (cond ((not (bobp))
7739 (org-previous-line-empty-p))
7740 ((outline-next-heading)
7741 (org-previous-line-empty-p))
7742 ;; Ignore trailing spaces on last buffer line.
7743 ((progn (skip-chars-backward " \t") (bolp))
7744 (org-previous-line-empty-p))
7745 (t nil))))))
7746 (`(heading . ,value) value)
7747 (_ nil)))
7749 (defun org-insert-heading (&optional arg invisible-ok top)
7750 "Insert a new heading or an item with the same depth at point.
7752 If point is at the beginning of a heading, insert a new heading
7753 or a new headline above the current one. When at the beginning
7754 of a regular line of text, turn it into a heading.
7756 If point is in the middle of a line, split it and create a new
7757 headline with the text in the current line after point (see
7758 `org-M-RET-may-split-line' on how to modify this behavior). As
7759 a special case, on a headline, splitting can only happen on the
7760 title itself. E.g., this excludes breaking stars or tags.
7762 With a `\\[universal-argument]' prefix, set \
7763 `org-insert-heading-respect-content' to
7764 a non-nil value for the duration of the command. This forces the
7765 insertion of a heading after the current subtree, independently
7766 on the location of point.
7768 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7769 insert the heading at the end of the tree
7770 above the current heading. For example, if point is within a
7771 2nd-level heading, then it will insert a 2nd-level heading at
7772 the end of the 1st-level parent subtree.
7774 When INVISIBLE-OK is set, stop at invisible headlines when going
7775 back. This is important for non-interactive uses of the
7776 command.
7778 When optional argument TOP is non-nil, insert a level 1 heading,
7779 unconditionally."
7780 (interactive "P")
7781 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7782 (level (org-current-level))
7783 (stars (make-string (if (and level (not top)) level 1) ?*)))
7784 (cond
7785 ((or org-insert-heading-respect-content
7786 (member arg '((4) (16)))
7787 (and (not invisible-ok)
7788 (invisible-p (max (1- (point)) (point-min)))))
7789 ;; Position point at the location of insertion.
7790 (if (not level) ;before first headline
7791 (org-with-limited-levels (outline-next-heading))
7792 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7793 ;; is nil.
7794 (org-with-limited-levels (org-back-to-heading invisible-ok))
7795 (cond ((equal arg '(16))
7796 (org-up-heading-safe)
7797 (org-end-of-subtree t t))
7799 (org-end-of-subtree t t))))
7800 (unless (bolp) (insert "\n")) ;ensure final newline
7801 (unless (and blank? (org-previous-line-empty-p))
7802 (org-N-empty-lines-before-current (if blank? 1 0)))
7803 (insert stars " \n")
7804 (forward-char -1))
7805 ;; At a headline...
7806 ((org-at-heading-p)
7807 (cond ((bolp)
7808 (when blank? (save-excursion (insert "\n")))
7809 (save-excursion (insert stars " \n"))
7810 (unless (and blank? (org-previous-line-empty-p))
7811 (org-N-empty-lines-before-current (if blank? 1 0)))
7812 (end-of-line))
7813 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7814 (org-match-line org-complex-heading-regexp)
7815 (org-pos-in-match-range (point) 4))
7816 ;; Grab the text that should moved to the new headline.
7817 ;; Preserve tags.
7818 (let ((split (delete-and-extract-region (point) (match-end 4))))
7819 (if (looking-at "[ \t]*$") (replace-match "")
7820 (org-set-tags nil t))
7821 (end-of-line)
7822 (when blank? (insert "\n"))
7823 (insert "\n" stars " ")
7824 (when (org-string-nw-p split) (insert split))
7825 (when (eobp) (save-excursion (insert "\n")))))
7827 (end-of-line)
7828 (when blank? (insert "\n"))
7829 (insert "\n" stars " ")
7830 (when (eobp) (save-excursion (insert "\n"))))))
7831 ;; On regular text, turn line into a headline or split, if
7832 ;; appropriate.
7833 ((bolp)
7834 (insert stars " ")
7835 (unless (and blank? (org-previous-line-empty-p))
7836 (org-N-empty-lines-before-current (if blank? 1 0))))
7838 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7839 (end-of-line))
7840 (insert "\n" stars " ")
7841 (unless (and blank? (org-previous-line-empty-p))
7842 (org-N-empty-lines-before-current (if blank? 1 0))))))
7843 (run-hooks 'org-insert-heading-hook))
7845 (defun org-N-empty-lines-before-current (n)
7846 "Make the number of empty lines before current exactly N.
7847 So this will delete or add empty lines."
7848 (let ((column (current-column)))
7849 (beginning-of-line)
7850 (unless (bobp)
7851 (let ((start (save-excursion
7852 (skip-chars-backward " \r\t\n")
7853 (line-end-position))))
7854 (delete-region start (line-end-position 0))))
7855 (insert (make-string n ?\n))
7856 (move-to-column column)))
7858 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7859 "Return the heading of the current entry, without the stars.
7860 When NO-TAGS is non-nil, don't include tags.
7861 When NO-TODO is non-nil, don't include TODO keywords.
7862 When NO-PRIORITY is non-nil, don't include priority cookie.
7863 When NO-COMMENT is non-nil, don't include COMMENT string."
7864 (save-excursion
7865 (org-back-to-heading t)
7866 (let ((case-fold-search nil))
7867 (looking-at org-complex-heading-regexp)
7868 (let ((todo (and (not no-todo) (match-string 2)))
7869 (priority (and (not no-priority) (match-string 3)))
7870 (headline (pcase (match-string 4)
7871 (`nil "")
7872 ((and (guard no-comment) h)
7873 (replace-regexp-in-string
7874 (eval-when-compile
7875 (format "\\`%s[ \t]+" org-comment-string))
7876 "" h))
7877 (h h)))
7878 (tags (and (not no-tags) (match-string 5))))
7879 (mapconcat #'identity
7880 (delq nil (list todo priority headline tags))
7881 " ")))))
7883 (defvar orgstruct-mode) ; defined below
7885 (defun org-heading-components ()
7886 "Return the components of the current heading.
7887 This is a list with the following elements:
7888 - the level as an integer
7889 - the reduced level, different if `org-odd-levels-only' is set.
7890 - the TODO keyword, or nil
7891 - the priority character, like ?A, or nil if no priority is given
7892 - the headline text itself, or the tags string if no headline text
7893 - the tags string, or nil."
7894 (save-excursion
7895 (org-back-to-heading t)
7896 (when (let (case-fold-search)
7897 (looking-at
7898 (if orgstruct-mode
7899 org-heading-regexp
7900 org-complex-heading-regexp)))
7901 (if orgstruct-mode
7902 (list (length (match-string 1))
7903 (org-reduced-level (length (match-string 1)))
7906 (match-string 2)
7907 nil)
7908 (list (length (match-string 1))
7909 (org-reduced-level (length (match-string 1)))
7910 (match-string-no-properties 2)
7911 (and (match-end 3) (aref (match-string 3) 2))
7912 (match-string-no-properties 4)
7913 (match-string-no-properties 5))))))
7915 (defun org-get-entry ()
7916 "Get the entry text, after heading, entire subtree."
7917 (save-excursion
7918 (org-back-to-heading t)
7919 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7921 (defun org-edit-headline (&optional heading)
7922 "Edit the current headline.
7923 Set it to HEADING when provided."
7924 (interactive)
7925 (org-with-wide-buffer
7926 (org-back-to-heading t)
7927 (let ((case-fold-search nil))
7928 (when (looking-at org-complex-heading-regexp)
7929 (let* ((old (match-string-no-properties 4))
7930 (new (save-match-data
7931 (org-trim (or heading (read-string "Edit: " old))))))
7932 (unless (equal old new)
7933 (if old (replace-match new t t nil 4)
7934 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7935 (insert " " new))
7936 (org-set-tags nil t)
7937 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7939 (defun org-insert-heading-after-current ()
7940 "Insert a new heading with same level as current, after current subtree."
7941 (interactive)
7942 (org-back-to-heading)
7943 (org-insert-heading)
7944 (org-move-subtree-down)
7945 (end-of-line 1))
7947 (defun org-insert-heading-respect-content (&optional invisible-ok)
7948 "Insert heading with `org-insert-heading-respect-content' set to t."
7949 (interactive)
7950 (org-insert-heading '(4) invisible-ok))
7952 (defun org-insert-todo-heading-respect-content (&optional force-state)
7953 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7954 (interactive)
7955 (org-insert-todo-heading force-state '(4)))
7957 (defun org-insert-todo-heading (arg &optional force-heading)
7958 "Insert a new heading with the same level and TODO state as current heading.
7960 If the heading has no TODO state, or if the state is DONE, use
7961 the first state (TODO by default). Also with one prefix arg,
7962 force first state. With two prefix args, force inserting at the
7963 end of the parent subtree.
7965 When called at a plain list item, insert a new item with an
7966 unchecked check box."
7967 (interactive "P")
7968 (when (or force-heading (not (org-insert-item 'checkbox)))
7969 (org-insert-heading (or (and (equal arg '(16)) '(16))
7970 force-heading))
7971 (save-excursion
7972 (org-forward-heading-same-level -1)
7973 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7974 (let* ((new-mark-x
7975 (if (or (equal arg '(4))
7976 (not (match-beginning 2))
7977 (member (match-string 2) org-done-keywords))
7978 (car org-todo-keywords-1)
7979 (match-string 2)))
7980 (new-mark
7982 (run-hook-with-args-until-success
7983 'org-todo-get-default-hook new-mark-x nil)
7984 new-mark-x)))
7985 (beginning-of-line 1)
7986 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7987 (if org-treat-insert-todo-heading-as-state-change
7988 (org-todo new-mark)
7989 (insert new-mark " "))))
7990 (when org-provide-todo-statistics
7991 (org-update-parent-todo-statistics))))
7993 (defun org-insert-subheading (arg)
7994 "Insert a new subheading and demote it.
7995 Works for outline headings and for plain lists alike."
7996 (interactive "P")
7997 (org-insert-heading arg)
7998 (cond
7999 ((org-at-heading-p) (org-do-demote))
8000 ((org-at-item-p) (org-indent-item))))
8002 (defun org-insert-todo-subheading (arg)
8003 "Insert a new subheading with TODO keyword or checkbox and demote it.
8004 Works for outline headings and for plain lists alike."
8005 (interactive "P")
8006 (org-insert-todo-heading arg)
8007 (cond
8008 ((org-at-heading-p) (org-do-demote))
8009 ((org-at-item-p) (org-indent-item))))
8011 ;;; Promotion and Demotion
8013 (defvar org-after-demote-entry-hook nil
8014 "Hook run after an entry has been demoted.
8015 The cursor will be at the beginning of the entry.
8016 When a subtree is being demoted, the hook will be called for each node.")
8018 (defvar org-after-promote-entry-hook nil
8019 "Hook run after an entry has been promoted.
8020 The cursor will be at the beginning of the entry.
8021 When a subtree is being promoted, the hook will be called for each node.")
8023 (defun org-promote-subtree ()
8024 "Promote the entire subtree.
8025 See also `org-promote'."
8026 (interactive)
8027 (save-excursion
8028 (org-with-limited-levels (org-map-tree 'org-promote)))
8029 (org-fix-position-after-promote))
8031 (defun org-demote-subtree ()
8032 "Demote the entire subtree.
8033 See `org-demote' and `org-promote'."
8034 (interactive)
8035 (save-excursion
8036 (org-with-limited-levels (org-map-tree 'org-demote)))
8037 (org-fix-position-after-promote))
8039 (defun org-do-promote ()
8040 "Promote the current heading higher up the tree.
8041 If the region is active in `transient-mark-mode', promote all
8042 headings in the region."
8043 (interactive)
8044 (save-excursion
8045 (if (org-region-active-p)
8046 (org-map-region 'org-promote (region-beginning) (region-end))
8047 (org-promote)))
8048 (org-fix-position-after-promote))
8050 (defun org-do-demote ()
8051 "Demote the current heading lower down the tree.
8052 If the region is active in `transient-mark-mode', demote all
8053 headings in the region."
8054 (interactive)
8055 (save-excursion
8056 (if (org-region-active-p)
8057 (org-map-region 'org-demote (region-beginning) (region-end))
8058 (org-demote)))
8059 (org-fix-position-after-promote))
8061 (defun org-fix-position-after-promote ()
8062 "Fix cursor position and indentation after demoting/promoting."
8063 (let ((pos (point)))
8064 (when (save-excursion
8065 (beginning-of-line)
8066 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8067 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8068 (cond ((eobp) (insert " "))
8069 ((eolp) (insert " "))
8070 ((equal (char-after) ?\s) (forward-char 1))))))
8072 (defun org-current-level ()
8073 "Return the level of the current entry, or nil if before the first headline.
8074 The level is the number of stars at the beginning of the
8075 headline. Use `org-reduced-level' to remove the effect of
8076 `org-odd-levels'. Unlike to `org-outline-level', this function
8077 ignores inlinetasks."
8078 (let ((level (org-with-limited-levels (org-outline-level))))
8079 (and (> level 0) level)))
8081 (defun org-get-previous-line-level ()
8082 "Return the outline depth of the last headline before the current line.
8083 Returns 0 for the first headline in the buffer, and nil if before the
8084 first headline."
8085 (and (org-current-level)
8086 (or (and (/= (line-beginning-position) (point-min))
8087 (save-excursion (beginning-of-line 0) (org-current-level)))
8088 0)))
8090 (defun org-reduced-level (l)
8091 "Compute the effective level of a heading.
8092 This takes into account the setting of `org-odd-levels-only'."
8093 (cond
8094 ((zerop l) 0)
8095 (org-odd-levels-only (1+ (floor (/ l 2))))
8096 (t l)))
8098 (defun org-level-increment ()
8099 "Return the number of stars that will be added or removed at a
8100 time to headlines when structure editing, based on the value of
8101 `org-odd-levels-only'."
8102 (if org-odd-levels-only 2 1))
8104 (defun org-get-valid-level (level &optional change)
8105 "Rectify a level change under the influence of `org-odd-levels-only'.
8106 LEVEL is a current level, CHANGE is by how much the level should
8107 be modified. Even if CHANGE is nil, LEVEL may be returned
8108 modified because even level numbers will become the next higher
8109 odd number. Returns values greater than 0."
8110 (if org-odd-levels-only
8111 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8112 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8113 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8114 (max 1 (+ level (or change 0)))))
8116 (defun org-promote ()
8117 "Promote the current heading higher up the tree."
8118 (org-with-wide-buffer
8119 (org-back-to-heading t)
8120 (let* ((after-change-functions (remq 'flyspell-after-change-function
8121 after-change-functions))
8122 (level (save-match-data (funcall outline-level)))
8123 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8124 (diff (abs (- level (length up-head) -1))))
8125 (cond
8126 ((and (= level 1) org-allow-promoting-top-level-subtree)
8127 (replace-match "# " nil t))
8128 ((= level 1)
8129 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8130 (t (replace-match up-head nil t)))
8131 (unless (= level 1)
8132 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8133 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8134 (run-hooks 'org-after-promote-entry-hook))))
8136 (defun org-demote ()
8137 "Demote the current heading lower down the tree."
8138 (org-with-wide-buffer
8139 (org-back-to-heading t)
8140 (let* ((after-change-functions (remq 'flyspell-after-change-function
8141 after-change-functions))
8142 (level (save-match-data (funcall outline-level)))
8143 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8144 (diff (abs (- level (length down-head) -1))))
8145 (replace-match down-head nil t)
8146 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8147 (when org-adapt-indentation (org-fixup-indentation diff))
8148 (run-hooks 'org-after-demote-entry-hook))))
8150 (defun org-cycle-level ()
8151 "Cycle the level of an empty headline through possible states.
8152 This goes first to child, then to parent, level, then up the hierarchy.
8153 After top level, it switches back to sibling level."
8154 (interactive)
8155 (let ((org-adapt-indentation nil))
8156 (when (org-point-at-end-of-empty-headline)
8157 (setq this-command 'org-cycle-level) ; Only needed for caching
8158 (let ((cur-level (org-current-level))
8159 (prev-level (org-get-previous-line-level)))
8160 (cond
8161 ;; If first headline in file, promote to top-level.
8162 ((= prev-level 0)
8163 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8164 do (org-do-promote)))
8165 ;; If same level as prev, demote one.
8166 ((= prev-level cur-level)
8167 (org-do-demote))
8168 ;; If parent is top-level, promote to top level if not already.
8169 ((= prev-level 1)
8170 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8171 do (org-do-promote)))
8172 ;; If top-level, return to prev-level.
8173 ((= cur-level 1)
8174 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8175 do (org-do-demote)))
8176 ;; If less than prev-level, promote one.
8177 ((< cur-level prev-level)
8178 (org-do-promote))
8179 ;; If deeper than prev-level, promote until higher than
8180 ;; prev-level.
8181 ((> cur-level prev-level)
8182 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8183 do (org-do-promote))))
8184 t))))
8186 (defun org-map-tree (fun)
8187 "Call FUN for every heading underneath the current one."
8188 (org-back-to-heading t)
8189 (let ((level (funcall outline-level)))
8190 (save-excursion
8191 (funcall fun)
8192 (while (and (progn
8193 (outline-next-heading)
8194 (> (funcall outline-level) level))
8195 (not (eobp)))
8196 (funcall fun)))))
8198 (defun org-map-region (fun beg end)
8199 "Call FUN for every heading between BEG and END."
8200 (let ((org-ignore-region t))
8201 (save-excursion
8202 (setq end (copy-marker end))
8203 (goto-char beg)
8204 (when (and (re-search-forward org-outline-regexp-bol nil t)
8205 (< (point) end))
8206 (funcall fun))
8207 (while (and (progn
8208 (outline-next-heading)
8209 (< (point) end))
8210 (not (eobp)))
8211 (funcall fun)))))
8213 (defun org-fixup-indentation (diff)
8214 "Change the indentation in the current entry by DIFF.
8216 DIFF is an integer. Indentation is done according to the
8217 following rules:
8219 - Planning information and property drawers are always indented
8220 according to the new level of the headline;
8222 - Footnote definitions and their contents are ignored;
8224 - Inlinetasks' boundaries are not shifted;
8226 - Empty lines are ignored;
8228 - Other lines' indentation are shifted by DIFF columns, unless
8229 it would introduce a structural change in the document, in
8230 which case no shifting is done at all.
8232 Assume point is at a heading or an inlinetask beginning."
8233 (org-with-wide-buffer
8234 (narrow-to-region (line-beginning-position)
8235 (save-excursion
8236 (if (org-with-limited-levels (org-at-heading-p))
8237 (org-with-limited-levels (outline-next-heading))
8238 (org-inlinetask-goto-end))
8239 (point)))
8240 (forward-line)
8241 ;; Indent properly planning info and property drawer.
8242 (when (looking-at-p org-planning-line-re)
8243 (org-indent-line)
8244 (forward-line))
8245 (when (looking-at org-property-drawer-re)
8246 (goto-char (match-end 0))
8247 (forward-line)
8248 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8249 (catch 'no-shift
8250 (when (zerop diff) (throw 'no-shift nil))
8251 ;; If DIFF is negative, first check if a shift is possible at all
8252 ;; (e.g., it doesn't break structure). This can only happen if
8253 ;; some contents are not properly indented.
8254 (let ((case-fold-search t))
8255 (when (< diff 0)
8256 (let ((diff (- diff))
8257 (forbidden-re (concat org-outline-regexp
8258 "\\|"
8259 (substring org-footnote-definition-re 1))))
8260 (save-excursion
8261 (while (not (eobp))
8262 (cond
8263 ((looking-at-p "[ \t]*$") (forward-line))
8264 ((and (looking-at-p org-footnote-definition-re)
8265 (let ((e (org-element-at-point)))
8266 (and (eq (org-element-type e) 'footnote-definition)
8267 (goto-char (org-element-property :end e))))))
8268 ((looking-at-p org-outline-regexp) (forward-line))
8269 ;; Give up if shifting would move before column 0 or
8270 ;; if it would introduce a headline or a footnote
8271 ;; definition.
8273 (skip-chars-forward " \t")
8274 (let ((ind (current-column)))
8275 (when (or (< ind diff)
8276 (and (= ind diff) (looking-at-p forbidden-re)))
8277 (throw 'no-shift nil)))
8278 ;; Ignore contents of example blocks and source
8279 ;; blocks if their indentation is meant to be
8280 ;; preserved. Jump to block's closing line.
8281 (beginning-of-line)
8282 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8283 (let ((e (org-element-at-point)))
8284 (and (memq (org-element-type e)
8285 '(example-block src-block))
8286 (or org-src-preserve-indentation
8287 (org-element-property :preserve-indent e))
8288 (goto-char (org-element-property :end e))
8289 (progn (skip-chars-backward " \r\t\n")
8290 (beginning-of-line)
8291 t))))
8292 (forward-line))))))))
8293 ;; Shift lines but footnote definitions, inlinetasks boundaries
8294 ;; by DIFF. Also skip contents of source or example blocks
8295 ;; when indentation is meant to be preserved.
8296 (while (not (eobp))
8297 (cond
8298 ((and (looking-at-p org-footnote-definition-re)
8299 (let ((e (org-element-at-point)))
8300 (and (eq (org-element-type e) 'footnote-definition)
8301 (goto-char (org-element-property :end e))))))
8302 ((looking-at-p org-outline-regexp) (forward-line))
8303 ((looking-at-p "[ \t]*$") (forward-line))
8305 (indent-line-to (+ (org-get-indentation) diff))
8306 (beginning-of-line)
8307 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8308 (let ((e (org-element-at-point)))
8309 (and (memq (org-element-type e)
8310 '(example-block src-block))
8311 (or org-src-preserve-indentation
8312 (org-element-property :preserve-indent e))
8313 (goto-char (org-element-property :end e))
8314 (progn (skip-chars-backward " \r\t\n")
8315 (beginning-of-line)
8316 t))))
8317 (forward-line)))))))))
8319 (defun org-convert-to-odd-levels ()
8320 "Convert an Org file with all levels allowed to one with odd levels.
8321 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8322 level 5 etc."
8323 (interactive)
8324 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8325 (let ((outline-level 'org-outline-level)
8326 (org-odd-levels-only nil) n)
8327 (save-excursion
8328 (goto-char (point-min))
8329 (while (re-search-forward "^\\*\\*+ " nil t)
8330 (setq n (- (length (match-string 0)) 2))
8331 (while (>= (setq n (1- n)) 0)
8332 (org-demote))
8333 (end-of-line 1))))))
8335 (defun org-convert-to-oddeven-levels ()
8336 "Convert an Org file with only odd levels to one with odd/even levels.
8337 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8338 file contains a section with an even level, conversion would
8339 destroy the structure of the file. An error is signaled in this
8340 case."
8341 (interactive)
8342 (goto-char (point-min))
8343 ;; First check if there are no even levels
8344 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8345 (org-show-set-visibility 'canonical)
8346 (error "Not all levels are odd in this file. Conversion not possible"))
8347 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8348 (let ((outline-regexp org-outline-regexp)
8349 (outline-level 'org-outline-level)
8350 (org-odd-levels-only nil) n)
8351 (save-excursion
8352 (goto-char (point-min))
8353 (while (re-search-forward "^\\*\\*+ " nil t)
8354 (setq n (/ (1- (length (match-string 0))) 2))
8355 (while (>= (setq n (1- n)) 0)
8356 (org-promote))
8357 (end-of-line 1))))))
8359 (defun org-tr-level (n)
8360 "Make N odd if required."
8361 (if org-odd-levels-only (1+ (/ n 2)) n))
8363 ;;; Vertical tree motion, cutting and pasting of subtrees
8365 (defun org-move-subtree-up (&optional arg)
8366 "Move the current subtree up past ARG headlines of the same level."
8367 (interactive "p")
8368 (org-move-subtree-down (- (prefix-numeric-value arg))))
8370 (defun org-move-subtree-down (&optional arg)
8371 "Move the current subtree down past ARG headlines of the same level."
8372 (interactive "p")
8373 (setq arg (prefix-numeric-value arg))
8374 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8375 'org-get-last-sibling))
8376 (ins-point (make-marker))
8377 (cnt (abs arg))
8378 (col (current-column))
8379 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8380 ;; Select the tree
8381 (org-back-to-heading)
8382 (setq beg0 (point))
8383 (save-excursion
8384 (setq ne-beg (org-back-over-empty-lines))
8385 (setq beg (point)))
8386 (save-match-data
8387 (save-excursion (outline-end-of-heading)
8388 (setq folded (org-invisible-p)))
8389 (progn (org-end-of-subtree nil t)
8390 (unless (eobp) (backward-char))))
8391 (outline-next-heading)
8392 (setq ne-end (org-back-over-empty-lines))
8393 (setq end (point))
8394 (goto-char beg0)
8395 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8396 ;; include less whitespace
8397 (save-excursion
8398 (goto-char beg)
8399 (forward-line (- ne-beg ne-end))
8400 (setq beg (point))))
8401 ;; Find insertion point, with error handling
8402 (while (> cnt 0)
8403 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8404 (progn (goto-char beg0)
8405 (user-error "Cannot move past superior level or buffer limit")))
8406 (setq cnt (1- cnt)))
8407 (when (> arg 0)
8408 ;; Moving forward - still need to move over subtree
8409 (org-end-of-subtree t t)
8410 (save-excursion
8411 (org-back-over-empty-lines)
8412 (or (bolp) (newline))))
8413 (setq ne-ins (org-back-over-empty-lines))
8414 (move-marker ins-point (point))
8415 (setq txt (buffer-substring beg end))
8416 (org-save-markers-in-region beg end)
8417 (delete-region beg end)
8418 (org-remove-empty-overlays-at beg)
8419 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8420 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8421 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8422 (let ((bbb (point)))
8423 (insert-before-markers txt)
8424 (org-reinstall-markers-in-region bbb)
8425 (move-marker ins-point bbb))
8426 (or (bolp) (insert "\n"))
8427 (setq ins-end (point))
8428 (goto-char ins-point)
8429 (org-skip-whitespace)
8430 (when (and (< arg 0)
8431 (org-first-sibling-p)
8432 (> ne-ins ne-beg))
8433 ;; Move whitespace back to beginning
8434 (save-excursion
8435 (goto-char ins-end)
8436 (let ((kill-whole-line t))
8437 (kill-line (- ne-ins ne-beg)) (point)))
8438 (insert (make-string (- ne-ins ne-beg) ?\n)))
8439 (move-marker ins-point nil)
8440 (if folded
8441 (outline-hide-subtree)
8442 (org-show-entry)
8443 (org-show-children)
8444 (org-cycle-hide-drawers 'children))
8445 (org-clean-visibility-after-subtree-move)
8446 ;; move back to the initial column we were at
8447 (move-to-column col)))
8449 (defvar org-subtree-clip ""
8450 "Clipboard for cut and paste of subtrees.
8451 This is actually only a copy of the kill, because we use the normal kill
8452 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8454 (defvar org-subtree-clip-folded nil
8455 "Was the last copied subtree folded?
8456 This is used to fold the tree back after pasting.")
8458 (defun org-cut-subtree (&optional n)
8459 "Cut the current subtree into the clipboard.
8460 With prefix arg N, cut this many sequential subtrees.
8461 This is a short-hand for marking the subtree and then cutting it."
8462 (interactive "p")
8463 (org-copy-subtree n 'cut))
8465 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8466 "Copy the current subtree into the clipboard.
8467 With prefix arg N, copy this many sequential subtrees.
8468 This is a short-hand for marking the subtree and then copying it.
8469 If CUT is non-nil, actually cut the subtree.
8470 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8471 of some markers in the region, even if CUT is non-nil. This is
8472 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8473 (interactive "p")
8474 (let (beg end folded (beg0 (point)))
8475 (if (called-interactively-p 'any)
8476 (org-back-to-heading nil) ; take what looks like a subtree
8477 (org-back-to-heading t)) ; take what is really there
8478 (setq beg (point))
8479 (skip-chars-forward " \t\r\n")
8480 (save-match-data
8481 (if nosubtrees
8482 (outline-next-heading)
8483 (save-excursion (outline-end-of-heading)
8484 (setq folded (org-invisible-p)))
8485 (ignore-errors (org-forward-heading-same-level (1- n) t))
8486 (org-end-of-subtree t t)))
8487 ;; Include the end of an inlinetask
8488 (when (and (featurep 'org-inlinetask)
8489 (looking-at-p (concat (org-inlinetask-outline-regexp)
8490 "END[ \t]*$")))
8491 (end-of-line))
8492 (setq end (point))
8493 (goto-char beg0)
8494 (when (> end beg)
8495 (setq org-subtree-clip-folded folded)
8496 (when (or cut force-store-markers)
8497 (org-save-markers-in-region beg end))
8498 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8499 (setq org-subtree-clip (current-kill 0))
8500 (message "%s: Subtree(s) with %d characters"
8501 (if cut "Cut" "Copied")
8502 (length org-subtree-clip)))))
8504 (defun org-paste-subtree (&optional level tree for-yank remove)
8505 "Paste the clipboard as a subtree, with modification of headline level.
8506 The entire subtree is promoted or demoted in order to match a new headline
8507 level.
8509 If the cursor is at the beginning of a headline, the same level as
8510 that headline is used to paste the tree.
8512 If not, the new level is derived from the *visible* headings
8513 before and after the insertion point, and taken to be the inferior headline
8514 level of the two. So if the previous visible heading is level 3 and the
8515 next is level 4 (or vice versa), level 4 will be used for insertion.
8516 This makes sure that the subtree remains an independent subtree and does
8517 not swallow low level entries.
8519 You can also force a different level, either by using a numeric prefix
8520 argument, or by inserting the heading marker by hand. For example, if the
8521 cursor is after \"*****\", then the tree will be shifted to level 5.
8523 If optional TREE is given, use this text instead of the kill ring.
8525 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8526 move back over whitespace before inserting, and move point to the end of
8527 the inserted text when done.
8529 When REMOVE is non-nil, remove the subtree from the clipboard."
8530 (interactive "P")
8531 (setq tree (or tree (and kill-ring (current-kill 0))))
8532 (unless (org-kill-is-subtree-p tree)
8533 (user-error "%s"
8534 (substitute-command-keys
8535 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8536 (org-with-limited-levels
8537 (let* ((visp (not (org-invisible-p)))
8538 (txt tree)
8539 (old-level (if (string-match org-outline-regexp-bol txt)
8540 (- (match-end 0) (match-beginning 0) 1)
8541 -1))
8542 (force-level (cond (level (prefix-numeric-value level))
8543 ((and (looking-at "[ \t]*$")
8544 (string-match
8545 "^\\*+$" (buffer-substring
8546 (point-at-bol) (point))))
8547 (- (match-end 0) (match-beginning 0)))
8548 ((and (bolp)
8549 (looking-at org-outline-regexp))
8550 (- (match-end 0) (point) 1))))
8551 (previous-level (save-excursion
8552 (condition-case nil
8553 (progn
8554 (outline-previous-visible-heading 1)
8555 (if (looking-at org-outline-regexp-bol)
8556 (- (match-end 0) (match-beginning 0) 1)
8558 (error 1))))
8559 (next-level (save-excursion
8560 (condition-case nil
8561 (progn
8562 (or (looking-at org-outline-regexp)
8563 (outline-next-visible-heading 1))
8564 (if (looking-at org-outline-regexp-bol)
8565 (- (match-end 0) (match-beginning 0) 1)
8567 (error 1))))
8568 (new-level (or force-level (max previous-level next-level)))
8569 (shift (if (or (= old-level -1)
8570 (= new-level -1)
8571 (= old-level new-level))
8573 (- new-level old-level)))
8574 (delta (if (> shift 0) -1 1))
8575 (func (if (> shift 0) 'org-demote 'org-promote))
8576 (org-odd-levels-only nil)
8577 beg end newend)
8578 ;; Remove the forced level indicator
8579 (when force-level
8580 (delete-region (point-at-bol) (point)))
8581 ;; Paste
8582 (beginning-of-line (if (bolp) 1 2))
8583 (setq beg (point))
8584 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8585 (insert-before-markers txt)
8586 (unless (string-suffix-p "\n" txt) (insert "\n"))
8587 (setq newend (point))
8588 (org-reinstall-markers-in-region beg)
8589 (setq end (point))
8590 (goto-char beg)
8591 (skip-chars-forward " \t\n\r")
8592 (setq beg (point))
8593 (when (and (org-invisible-p) visp)
8594 (save-excursion (outline-show-heading)))
8595 ;; Shift if necessary
8596 (unless (= shift 0)
8597 (save-restriction
8598 (narrow-to-region beg end)
8599 (while (not (= shift 0))
8600 (org-map-region func (point-min) (point-max))
8601 (setq shift (+ delta shift)))
8602 (goto-char (point-min))
8603 (setq newend (point-max))))
8604 (when (or (called-interactively-p 'interactive) for-yank)
8605 (message "Clipboard pasted as level %d subtree" new-level))
8606 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8607 kill-ring
8608 (eq org-subtree-clip (current-kill 0))
8609 org-subtree-clip-folded)
8610 ;; The tree was folded before it was killed/copied
8611 (outline-hide-subtree))
8612 (and for-yank (goto-char newend))
8613 (and remove (setq kill-ring (cdr kill-ring))))))
8615 (defun org-kill-is-subtree-p (&optional txt)
8616 "Check if the current kill is an outline subtree, or a set of trees.
8617 Returns nil if kill does not start with a headline, or if the first
8618 headline level is not the largest headline level in the tree.
8619 So this will actually accept several entries of equal levels as well,
8620 which is OK for `org-paste-subtree'.
8621 If optional TXT is given, check this string instead of the current kill."
8622 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8623 (re (org-get-limited-outline-regexp))
8624 (^re (concat "^" re))
8625 (start-level (and kill
8626 (string-match
8627 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8628 kill)
8629 (- (match-end 2) (match-beginning 2) 1)))
8630 (start (1+ (or (match-beginning 2) -1))))
8631 (if (not start-level)
8632 (progn
8633 nil) ;; does not even start with a heading
8634 (catch 'exit
8635 (while (setq start (string-match ^re kill (1+ start)))
8636 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8637 (throw 'exit nil)))
8638 t))))
8640 (defvar org-markers-to-move nil
8641 "Markers that should be moved with a cut-and-paste operation.
8642 Those markers are stored together with their positions relative to
8643 the start of the region.")
8645 (defun org-save-markers-in-region (beg end)
8646 "Check markers in region.
8647 If these markers are between BEG and END, record their position relative
8648 to BEG, so that after moving the block of text, we can put the markers back
8649 into place.
8650 This function gets called just before an entry or tree gets cut from the
8651 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8652 called immediately, to move the markers with the entries."
8653 (setq org-markers-to-move nil)
8654 (when (featurep 'org-clock)
8655 (org-clock-save-markers-for-cut-and-paste beg end))
8656 (when (featurep 'org-agenda)
8657 (org-agenda-save-markers-for-cut-and-paste beg end)))
8659 (defun org-check-and-save-marker (marker beg end)
8660 "Check if MARKER is between BEG and END.
8661 If yes, remember the marker and the distance to BEG."
8662 (when (and (marker-buffer marker)
8663 (equal (marker-buffer marker) (current-buffer))
8664 (>= marker beg) (< marker end))
8665 (push (cons marker (- marker beg)) org-markers-to-move)))
8667 (defun org-reinstall-markers-in-region (beg)
8668 "Move all remembered markers to their position relative to BEG."
8669 (dolist (x org-markers-to-move)
8670 (move-marker (car x) (+ beg (cdr x))))
8671 (setq org-markers-to-move nil))
8673 (defun org-narrow-to-subtree ()
8674 "Narrow buffer to the current subtree."
8675 (interactive)
8676 (save-excursion
8677 (save-match-data
8678 (org-with-limited-levels
8679 (narrow-to-region
8680 (progn (org-back-to-heading t) (point))
8681 (progn (org-end-of-subtree t t)
8682 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8683 (point)))))))
8685 (defun org-narrow-to-block ()
8686 "Narrow buffer to the current block."
8687 (interactive)
8688 (let* ((case-fold-search t)
8689 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8690 "^[ \t]*#\\+end_.*")))
8691 (if blockp
8692 (narrow-to-region (car blockp) (cdr blockp))
8693 (user-error "Not in a block"))))
8695 (defun org-clone-subtree-with-time-shift (n &optional shift)
8696 "Clone the task (subtree) at point N times.
8697 The clones will be inserted as siblings.
8699 In interactive use, the user will be prompted for the number of
8700 clones to be produced. If the entry has a timestamp, the user
8701 will also be prompted for a time shift, which may be a repeater
8702 as used in time stamps, for example `+3d'. To disable this,
8703 you can call the function with a universal prefix argument.
8705 When a valid repeater is given and the entry contains any time
8706 stamps, the clones will become a sequence in time, with time
8707 stamps in the subtree shifted for each clone produced. If SHIFT
8708 is nil or the empty string, time stamps will be left alone. The
8709 ID property of the original subtree is removed.
8711 In each clone, all the CLOCK entries will be removed. This
8712 prevents Org from considering that the clocked times overlap.
8714 If the original subtree did contain time stamps with a repeater,
8715 the following will happen:
8716 - the repeater will be removed in each clone
8717 - an additional clone will be produced, with the current, unshifted
8718 date(s) in the entry.
8719 - the original entry will be placed *after* all the clones, with
8720 repeater intact.
8721 - the start days in the repeater in the original entry will be shifted
8722 to past the last clone.
8723 In this way you can spell out a number of instances of a repeating task,
8724 and still retain the repeater to cover future instances of the task.
8726 As described above, N+1 clones are produced when the original
8727 subtree has a repeater. Setting N to 0, then, can be used to
8728 remove the repeater from a subtree and create a shifted clone
8729 with the original repeater."
8730 (interactive "nNumber of clones to produce: ")
8731 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8732 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8733 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8734 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8735 (shift
8736 (or shift
8737 (if (and (not (equal current-prefix-arg '(4)))
8738 (save-excursion
8739 (goto-char beg)
8740 (re-search-forward org-ts-regexp-both end-of-tree t)))
8741 (read-from-minibuffer
8742 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8743 ""))) ;No time shift
8744 (doshift
8745 (and (org-string-nw-p shift)
8746 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8747 shift)
8748 (user-error "Invalid shift specification %s" shift)))))
8749 (goto-char end-of-tree)
8750 (unless (bolp) (insert "\n"))
8751 (let* ((end (point))
8752 (template (buffer-substring beg end))
8753 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8754 (shift-what (pcase (and doshift (match-string 2 shift))
8755 (`nil nil)
8756 ("d" 'day)
8757 ("w" (setq shift-n (* 7 shift-n)) 'day)
8758 ("m" 'month)
8759 ("y" 'year)
8760 (_ (error "Unsupported time unit"))))
8761 (nmin 1)
8762 (nmax n)
8763 (n-no-remove -1)
8764 (idprop (org-entry-get nil "ID")))
8765 (when (and doshift
8766 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8767 template))
8768 (delete-region beg end)
8769 (setq end beg)
8770 (setq nmin 0)
8771 (setq nmax (1+ nmax))
8772 (setq n-no-remove nmax))
8773 (goto-char end)
8774 (cl-loop for n from nmin to nmax do
8775 (insert
8776 ;; Prepare clone.
8777 (with-temp-buffer
8778 (insert template)
8779 (org-mode)
8780 (goto-char (point-min))
8781 (org-show-subtree)
8782 (and idprop (if org-clone-delete-id
8783 (org-entry-delete nil "ID")
8784 (org-id-get-create t)))
8785 (unless (= n 0)
8786 (while (re-search-forward org-clock-line-re nil t)
8787 (delete-region (line-beginning-position)
8788 (line-beginning-position 2)))
8789 (goto-char (point-min))
8790 (while (re-search-forward org-drawer-regexp nil t)
8791 (org-remove-empty-drawer-at (point))))
8792 (goto-char (point-min))
8793 (when doshift
8794 (while (re-search-forward org-ts-regexp-both nil t)
8795 (org-timestamp-change (* n shift-n) shift-what))
8796 (unless (= n n-no-remove)
8797 (goto-char (point-min))
8798 (while (re-search-forward org-ts-regexp nil t)
8799 (save-excursion
8800 (goto-char (match-beginning 0))
8801 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8802 (delete-region (match-beginning 1) (match-end 1)))))))
8803 (buffer-string)))))
8804 (goto-char beg)))
8806 ;;; Outline Sorting
8808 (defun org-sort (&optional with-case)
8809 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8810 Optional argument WITH-CASE means sort case-sensitively."
8811 (interactive "P")
8812 (org-call-with-arg
8813 (cond ((org-at-table-p) #'org-table-sort-lines)
8814 ((org-at-item-p) #'org-sort-list)
8815 (t #'org-sort-entries))
8816 with-case))
8818 (defun org-sort-remove-invisible (s)
8819 "Remove invisible part of links and emphasis markers from string S."
8820 (remove-text-properties 0 (length s) org-rm-props s)
8821 (replace-regexp-in-string
8822 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8823 (replace-regexp-in-string
8824 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8825 (org-link-display-format s)
8826 t t) t t))
8828 (defvar org-priority-regexp) ; defined later in the file
8830 (defvar org-after-sorting-entries-or-items-hook nil
8831 "Hook that is run after a bunch of entries or items have been sorted.
8832 When children are sorted, the cursor is in the parent line when this
8833 hook gets called. When a region or a plain list is sorted, the cursor
8834 will be in the first entry of the sorted region/list.")
8836 (defun org-sort-entries
8837 (&optional with-case sorting-type getkey-func compare-func property
8838 interactive?)
8839 "Sort entries on a certain level of an outline tree.
8840 If there is an active region, the entries in the region are sorted.
8841 Else, if the cursor is before the first entry, sort the top-level items.
8842 Else, the children of the entry at point are sorted.
8844 Sorting can be alphabetically, numerically, by date/time as given by
8845 a time stamp, by a property, by priority order, or by a custom function.
8847 The command prompts for the sorting type unless it has been given to the
8848 function through the SORTING-TYPE argument, which needs to be a character,
8849 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8850 the precise meaning of each character:
8852 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8853 c By creation time, which is assumed to be the first inactive time stamp
8854 at the beginning of a line.
8855 d By deadline date/time.
8856 k By clocking time.
8857 n Numerically, by converting the beginning of the entry/item to a number.
8858 o By order of TODO keywords.
8859 p By priority according to the cookie.
8860 r By the value of a property.
8861 s By scheduled date/time.
8862 t By date/time, either the first active time stamp in the entry, or, if
8863 none exist, by the first inactive one.
8865 Capital letters will reverse the sort order.
8867 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8868 called with point at the beginning of the record. It must return a
8869 value that is compatible with COMPARE-FUNC, the function used to
8870 compare entries.
8872 Comparing entries ignores case by default. However, with an optional argument
8873 WITH-CASE, the sorting considers case as well.
8875 Sorting is done against the visible part of the headlines, it ignores hidden
8876 links.
8878 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8880 A non-nil value for INTERACTIVE? is used to signal that this
8881 function is being called interactively."
8882 (interactive (list current-prefix-arg nil nil nil nil t))
8883 (let ((case-func (if with-case 'identity 'downcase))
8884 start beg end stars re re2
8885 txt what tmp)
8886 ;; Find beginning and end of region to sort
8887 (cond
8888 ((org-region-active-p)
8889 ;; we will sort the region
8890 (setq end (region-end)
8891 what "region")
8892 (goto-char (region-beginning))
8893 (unless (org-at-heading-p) (outline-next-heading))
8894 (setq start (point)))
8895 ((or (org-at-heading-p)
8896 (ignore-errors (progn (org-back-to-heading) t)))
8897 ;; we will sort the children of the current headline
8898 (org-back-to-heading)
8899 (setq start (point)
8900 end (progn (org-end-of-subtree t t)
8901 (or (bolp) (insert "\n"))
8902 (when (>= (org-back-over-empty-lines) 1)
8903 (forward-line 1))
8904 (point))
8905 what "children")
8906 (goto-char start)
8907 (outline-show-subtree)
8908 (outline-next-heading))
8910 ;; we will sort the top-level entries in this file
8911 (goto-char (point-min))
8912 (or (org-at-heading-p) (outline-next-heading))
8913 (setq start (point))
8914 (goto-char (point-max))
8915 (beginning-of-line 1)
8916 (when (looking-at ".*?\\S-")
8917 ;; File ends in a non-white line
8918 (end-of-line 1)
8919 (insert "\n"))
8920 (setq end (point-max))
8921 (setq what "top-level")
8922 (goto-char start)
8923 (outline-show-all)))
8925 (setq beg (point))
8926 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8928 (looking-at "\\(\\*+\\)")
8929 (setq stars (match-string 1)
8930 re (concat "^" (regexp-quote stars) " +")
8931 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8932 txt (buffer-substring beg end))
8933 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8934 (when (and (not (equal stars "*")) (string-match re2 txt))
8935 (user-error "Region to sort contains a level above the first entry"))
8937 (unless sorting-type
8938 (message
8939 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8940 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8941 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8942 what)
8943 (setq sorting-type (read-char-exclusive)))
8945 (unless getkey-func
8946 (and (= (downcase sorting-type) ?f)
8947 (setq getkey-func
8948 (or (and interactive?
8949 (org-read-function
8950 "Function for extracting keys: "))
8951 (error "Missing key extractor")))))
8953 (and (= (downcase sorting-type) ?r)
8954 (not property)
8955 (setq property
8956 (completing-read "Property: "
8957 (mapcar #'list (org-buffer-property-keys t))
8958 nil t)))
8960 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8961 (message "Sorting entries...")
8963 (save-restriction
8964 (narrow-to-region start end)
8965 (let ((restore-clock?
8966 ;; The clock marker is lost when using `sort-subr'; mark
8967 ;; the clock with temporary `:org-clock-marker-backup'
8968 ;; text property.
8969 (when (and (eq (org-clock-is-active) (current-buffer))
8970 (<= start (marker-position org-clock-marker))
8971 (>= end (marker-position org-clock-marker)))
8972 (org-with-silent-modifications
8973 (put-text-property (1- org-clock-marker) org-clock-marker
8974 :org-clock-marker-backup t))
8976 (dcst (downcase sorting-type))
8977 (case-fold-search nil)
8978 (now (current-time)))
8979 (sort-subr
8980 (/= dcst sorting-type)
8981 ;; This function moves to the beginning character of the "record" to
8982 ;; be sorted.
8983 (lambda nil
8984 (if (re-search-forward re nil t)
8985 (goto-char (match-beginning 0))
8986 (goto-char (point-max))))
8987 ;; This function moves to the last character of the "record" being
8988 ;; sorted.
8989 (lambda nil
8990 (save-match-data
8991 (condition-case nil
8992 (outline-forward-same-level 1)
8993 (error
8994 (goto-char (point-max))))))
8995 ;; This function returns the value that gets sorted against.
8996 (lambda nil
8997 (cond
8998 ((= dcst ?n)
8999 (if (looking-at org-complex-heading-regexp)
9000 (string-to-number (org-sort-remove-invisible (match-string 4)))
9001 nil))
9002 ((= dcst ?a)
9003 (if (looking-at org-complex-heading-regexp)
9004 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9005 nil))
9006 ((= dcst ?k)
9007 (or (get-text-property (point) :org-clock-minutes) 0))
9008 ((= dcst ?t)
9009 (let ((end (save-excursion (outline-next-heading) (point))))
9010 (if (or (re-search-forward org-ts-regexp end t)
9011 (re-search-forward org-ts-regexp-both end t))
9012 (org-time-string-to-seconds (match-string 0))
9013 (float-time now))))
9014 ((= dcst ?c)
9015 (let ((end (save-excursion (outline-next-heading) (point))))
9016 (if (re-search-forward
9017 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9018 end t)
9019 (org-time-string-to-seconds (match-string 0))
9020 (float-time now))))
9021 ((= dcst ?s)
9022 (let ((end (save-excursion (outline-next-heading) (point))))
9023 (if (re-search-forward org-scheduled-time-regexp end t)
9024 (org-time-string-to-seconds (match-string 1))
9025 (float-time now))))
9026 ((= dcst ?d)
9027 (let ((end (save-excursion (outline-next-heading) (point))))
9028 (if (re-search-forward org-deadline-time-regexp end t)
9029 (org-time-string-to-seconds (match-string 1))
9030 (float-time now))))
9031 ((= dcst ?p)
9032 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9033 (string-to-char (match-string 2))
9034 org-default-priority))
9035 ((= dcst ?r)
9036 (or (org-entry-get nil property) ""))
9037 ((= dcst ?o)
9038 (when (looking-at org-complex-heading-regexp)
9039 (let* ((m (match-string 2))
9040 (s (if (member m org-done-keywords) '- '+)))
9041 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9042 ((= dcst ?f)
9043 (if getkey-func
9044 (progn
9045 (setq tmp (funcall getkey-func))
9046 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9047 tmp)
9048 (error "Invalid key function `%s'" getkey-func)))
9049 (t (error "Invalid sorting type `%c'" sorting-type))))
9051 (cond
9052 ((= dcst ?a) 'string<)
9053 ((= dcst ?f)
9054 (or compare-func
9055 (and interactive?
9056 (org-read-function
9057 (concat "Function for comparing keys "
9058 "(empty for default `sort-subr' predicate): ")
9059 'allow-empty))))
9060 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9061 (when restore-clock?
9062 (move-marker org-clock-marker
9063 (1+ (next-single-property-change
9064 start :org-clock-marker-backup)))
9065 (remove-text-properties (1- org-clock-marker) org-clock-marker
9066 '(:org-clock-marker-backup t)))))
9067 (run-hooks 'org-after-sorting-entries-or-items-hook)
9068 (message "Sorting entries...done")))
9070 ;;; The orgstruct minor mode
9072 ;; Define a minor mode which can be used in other modes in order to
9073 ;; integrate the Org mode structure editing commands.
9075 ;; This is really a hack, because the Org mode structure commands use
9076 ;; keys which normally belong to the major mode. Here is how it
9077 ;; works: The minor mode defines all the keys necessary to operate the
9078 ;; structure commands, but wraps the commands into a function which
9079 ;; tests if the cursor is currently at a headline or a plain list
9080 ;; item. If that is the case, the structure command is used,
9081 ;; temporarily setting many Org mode variables like regular
9082 ;; expressions for filling etc. However, when any of those keys is
9083 ;; used at a different location, function uses `key-binding' to look
9084 ;; up if the key has an associated command in another currently active
9085 ;; keymap (minor modes, major mode, global), and executes that
9086 ;; command. There might be problems if any of the keys is otherwise
9087 ;; used as a prefix key.
9089 (defcustom orgstruct-heading-prefix-regexp ""
9090 "Regexp that matches the custom prefix of Org headlines in
9091 orgstruct(++)-mode."
9092 :group 'org
9093 :version "26.1"
9094 :package-version '(Org . "8.3")
9095 :type 'regexp)
9096 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9098 (defcustom orgstruct-setup-hook nil
9099 "Hook run after orgstruct-mode-map is filled."
9100 :group 'org
9101 :version "24.4"
9102 :package-version '(Org . "8.0")
9103 :type 'hook)
9105 (defvar orgstruct-initialized nil)
9107 (defvar org-local-vars nil
9108 "List of local variables, for use by `orgstruct-mode'.")
9110 ;;;###autoload
9111 (define-minor-mode orgstruct-mode
9112 "Toggle the minor mode `orgstruct-mode'.
9113 This mode is for using Org mode structure commands in other
9114 modes. The following keys behave as if Org mode were active, if
9115 the cursor is on a headline, or on a plain list item (both as
9116 defined by Org mode)."
9117 nil " OrgStruct" (make-sparse-keymap)
9118 (funcall (if orgstruct-mode
9119 'add-to-invisibility-spec
9120 'remove-from-invisibility-spec)
9121 '(outline . t))
9122 (when orgstruct-mode
9123 (org-load-modules-maybe)
9124 (unless orgstruct-initialized
9125 (orgstruct-setup)
9126 (setq orgstruct-initialized t))))
9128 ;;;###autoload
9129 (defun turn-on-orgstruct ()
9130 "Unconditionally turn on `orgstruct-mode'."
9131 (orgstruct-mode 1))
9133 (defvar-local orgstruct-is-++ nil
9134 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9135 (defvar-local org-fb-vars nil)
9136 (defun orgstruct++-mode (&optional arg)
9137 "Toggle `orgstruct-mode', the enhanced version of it.
9138 In addition to setting orgstruct-mode, this also exports all
9139 indentation and autofilling variables from Org mode into the
9140 buffer. It will also recognize item context in multiline items."
9141 (interactive "P")
9142 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9143 (if (< arg 1)
9144 (progn (orgstruct-mode -1)
9145 (dolist (v org-fb-vars)
9146 (set (make-local-variable (car v))
9147 (if (eq (car-safe (cadr v)) 'quote)
9148 (cl-cadadr v)
9149 (nth 1 v)))))
9150 (orgstruct-mode 1)
9151 (setq org-fb-vars nil)
9152 (unless org-local-vars
9153 (setq org-local-vars (org-get-local-variables)))
9154 (let (var val)
9155 (dolist (x org-local-vars)
9156 (when (string-match
9157 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9158 \\|fill-prefix\\|indent-\\)"
9159 (symbol-name (car x)))
9160 (setq var (car x) val (nth 1 x))
9161 (push (list var `(quote ,(eval var))) org-fb-vars)
9162 (set (make-local-variable var)
9163 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9164 (setq-local orgstruct-is-++ t))))
9166 ;;;###autoload
9167 (defun turn-on-orgstruct++ ()
9168 "Unconditionally turn on `orgstruct++-mode'."
9169 (orgstruct++-mode 1))
9171 (defun orgstruct-error ()
9172 "Error when there is no default binding for a structure key."
9173 (interactive)
9174 (funcall (if (fboundp 'user-error)
9175 'user-error
9176 'error)
9177 "This key has no function outside structure elements"))
9179 (defun orgstruct-setup ()
9180 "Setup orgstruct keymap."
9181 (dolist (cell '((org-demote . t)
9182 (org-metaleft . t)
9183 (org-metaright . t)
9184 (org-promote . t)
9185 (org-shiftmetaleft . t)
9186 (org-shiftmetaright . t)
9187 org-backward-element
9188 org-backward-heading-same-level
9189 org-ctrl-c-ret
9190 org-ctrl-c-minus
9191 org-ctrl-c-star
9192 org-cycle
9193 org-force-cycle-archived
9194 org-forward-heading-same-level
9195 org-insert-heading
9196 org-insert-heading-respect-content
9197 org-kill-note-or-show-branches
9198 org-mark-subtree
9199 org-meta-return
9200 org-metadown
9201 org-metaup
9202 org-narrow-to-subtree
9203 org-promote-subtree
9204 org-reveal
9205 org-shiftdown
9206 org-shiftleft
9207 org-shiftmetadown
9208 org-shiftmetaup
9209 org-shiftright
9210 org-shifttab
9211 org-shifttab
9212 org-shiftup
9213 org-show-children
9214 org-show-subtree
9215 org-sort
9216 org-up-element
9217 outline-demote
9218 outline-next-visible-heading
9219 outline-previous-visible-heading
9220 outline-promote
9221 outline-up-heading))
9222 (let ((f (or (car-safe cell) cell))
9223 (disable-when-heading-prefix (cdr-safe cell)))
9224 (when (fboundp f)
9225 (let ((new-bindings))
9226 (dolist (binding (nconc (where-is-internal f org-mode-map)
9227 (where-is-internal f outline-mode-map)))
9228 (push binding new-bindings)
9229 ;; TODO use local-function-key-map
9230 (dolist (rep '(("<tab>" . "TAB")
9231 ("<return>" . "RET")
9232 ("<escape>" . "ESC")
9233 ("<delete>" . "DEL")))
9234 (setq binding (read-kbd-macro
9235 (let ((case-fold-search))
9236 (replace-regexp-in-string
9237 (regexp-quote (cdr rep))
9238 (car rep)
9239 (key-description binding)))))
9240 (cl-pushnew binding new-bindings :test 'equal)))
9241 (dolist (binding new-bindings)
9242 (let ((key (lookup-key orgstruct-mode-map binding)))
9243 (when (or (not key) (numberp key))
9244 (ignore-errors
9245 (org-defkey orgstruct-mode-map
9246 binding
9247 (orgstruct-make-binding
9248 f binding disable-when-heading-prefix))))))))))
9249 (run-hooks 'orgstruct-setup-hook))
9251 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9252 "Create a function for binding in the structure minor mode.
9253 FUN is the command to call inside a table. KEY is the key that
9254 should be checked in for a command to execute outside of tables.
9255 Non-nil `disable-when-heading-prefix' means to disable the command
9256 if `orgstruct-heading-prefix-regexp' is not empty."
9257 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9258 (let ((nname name)
9259 (i 0))
9260 (while (fboundp (intern nname))
9261 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9262 (setq name (intern nname)))
9263 (eval
9264 (let ((bindings '((org-heading-regexp
9265 (concat "^"
9266 orgstruct-heading-prefix-regexp
9267 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9268 (org-outline-regexp
9269 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9270 (org-outline-regexp-bol
9271 (concat "^" org-outline-regexp))
9272 (outline-regexp org-outline-regexp)
9273 (outline-heading-end-regexp "\n")
9274 (outline-level 'org-outline-level)
9275 (outline-heading-alist))))
9276 `(defun ,name (arg)
9277 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9278 "Outside of structure, run the binding of `"
9279 (key-description key) "'."
9280 (when disable-when-heading-prefix
9281 (concat
9282 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9283 "back to the default binding due to limitations of Org's implementation of\n"
9284 "`" (symbol-name fun) "'.")))
9285 (interactive "p")
9286 (let* ((disable
9287 ,(and disable-when-heading-prefix
9288 '(not (string= orgstruct-heading-prefix-regexp ""))))
9289 (fallback
9290 (or disable
9291 (not
9292 (let* ,bindings
9293 (org-context-p 'headline 'item
9294 ,(when (memq fun
9295 '(org-insert-heading
9296 org-insert-heading-respect-content
9297 org-meta-return))
9298 '(when orgstruct-is-++
9299 'item-body))))))))
9300 (if fallback
9301 (let* ((orgstruct-mode)
9302 (binding
9303 (let ((key ,key))
9304 (catch 'exit
9305 (dolist
9306 (rep
9307 '(nil
9308 ("<\\([^>]*\\)tab>" . "\\1TAB")
9309 ("<\\([^>]*\\)return>" . "\\1RET")
9310 ("<\\([^>]*\\)escape>" . "\\1ESC")
9311 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9312 nil)
9313 (when rep
9314 (setq key (read-kbd-macro
9315 (let ((case-fold-search))
9316 (replace-regexp-in-string
9317 (car rep)
9318 (cdr rep)
9319 (key-description key))))))
9320 (when (key-binding key)
9321 (throw 'exit (key-binding key))))))))
9322 (if (keymapp binding)
9323 (org-set-transient-map binding)
9324 (let ((func (or binding
9325 (unless disable
9326 'orgstruct-error))))
9327 (when func
9328 (call-interactively func)))))
9329 (org-run-like-in-org-mode
9330 (lambda ()
9331 (interactive)
9332 (let* ,bindings
9333 (call-interactively ',fun)))))))))
9334 name))
9336 (defun org-contextualize-keys (alist contexts)
9337 "Return valid elements in ALIST depending on CONTEXTS.
9339 `org-agenda-custom-commands' or `org-capture-templates' are the
9340 values used for ALIST, and `org-agenda-custom-commands-contexts'
9341 or `org-capture-templates-contexts' are the associated contexts
9342 definitions."
9343 (let ((contexts
9344 ;; normalize contexts
9345 (mapcar
9346 (lambda(c) (cond ((listp (cadr c))
9347 (list (car c) (car c) (nth 1 c)))
9348 ((string= "" (cadr c))
9349 (list (car c) (car c) (nth 2 c)))
9350 (t c)))
9351 contexts))
9352 (a alist) r s)
9353 ;; loop over all commands or templates
9354 (dolist (c a)
9355 (let (vrules repl)
9356 (cond
9357 ((not (assoc (car c) contexts))
9358 (push c r))
9359 ((and (assoc (car c) contexts)
9360 (setq vrules (org-contextualize-validate-key
9361 (car c) contexts)))
9362 (mapc (lambda (vr)
9363 (unless (equal (car vr) (cadr vr))
9364 (setq repl vr)))
9365 vrules)
9366 (if (not repl) (push c r)
9367 (push (cadr repl) s)
9368 (push
9369 (cons (car c)
9370 (cdr (or (assoc (cadr repl) alist)
9371 (error "Undefined key `%s' as contextual replacement for `%s'"
9372 (cadr repl) (car c)))))
9373 r))))))
9374 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9375 (delq
9377 (delete-dups
9378 (mapcar (lambda (x)
9379 (let ((tpl (car x)))
9380 (unless (delq
9382 (mapcar (lambda (y)
9383 (equal y tpl))
9385 x)))
9386 (reverse r))))))
9388 (defun org-contextualize-validate-key (key contexts)
9389 "Check CONTEXTS for agenda or capture KEY."
9390 (let (res)
9391 (dolist (r contexts)
9392 (dolist (rr (car (last r)))
9393 (when
9394 (and (equal key (car r))
9395 (if (functionp rr) (funcall rr)
9396 (or (and (eq (car rr) 'in-file)
9397 (buffer-file-name)
9398 (string-match (cdr rr) (buffer-file-name)))
9399 (and (eq (car rr) 'in-mode)
9400 (string-match (cdr rr) (symbol-name major-mode)))
9401 (and (eq (car rr) 'in-buffer)
9402 (string-match (cdr rr) (buffer-name)))
9403 (when (and (eq (car rr) 'not-in-file)
9404 (buffer-file-name))
9405 (not (string-match (cdr rr) (buffer-file-name))))
9406 (when (eq (car rr) 'not-in-mode)
9407 (not (string-match (cdr rr) (symbol-name major-mode))))
9408 (when (eq (car rr) 'not-in-buffer)
9409 (not (string-match (cdr rr) (buffer-name)))))))
9410 (push r res))))
9411 (delete-dups (delq nil res))))
9413 (defun org-context-p (&rest contexts)
9414 "Check if local context is any of CONTEXTS.
9415 Possible values in the list of contexts are `table', `headline', and `item'."
9416 (let ((pos (point)))
9417 (goto-char (point-at-bol))
9418 (prog1 (or (and (memq 'table contexts)
9419 (looking-at "[ \t]*|"))
9420 (and (memq 'headline contexts)
9421 (looking-at org-outline-regexp))
9422 (and (memq 'item contexts)
9423 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9424 (and (memq 'item-body contexts)
9425 (org-in-item-p)))
9426 (goto-char pos))))
9428 ;;;###autoload
9429 (defun org-run-like-in-org-mode (cmd)
9430 "Run a command, pretending that the current buffer is in Org mode.
9431 This will temporarily bind local variables that are typically bound in
9432 Org mode to the values they have in Org mode, and then interactively
9433 call CMD."
9434 (org-load-modules-maybe)
9435 (unless org-local-vars
9436 (setq org-local-vars (org-get-local-variables)))
9437 (let (binds)
9438 (dolist (var org-local-vars)
9439 (when (or (not (boundp (car var)))
9440 (eq (symbol-value (car var))
9441 (default-value (car var))))
9442 (push (list (car var) `(quote ,(cadr var))) binds)))
9443 (eval `(let ,binds
9444 (call-interactively (quote ,cmd))))))
9446 (defun org-get-category (&optional pos force-refresh)
9447 "Get the category applying to position POS."
9448 (save-match-data
9449 (when force-refresh (org-refresh-category-properties))
9450 (let ((pos (or pos (point))))
9451 (or (get-text-property pos 'org-category)
9452 (progn (org-refresh-category-properties)
9453 (get-text-property pos 'org-category))))))
9455 ;;; Refresh properties
9457 (defun org-refresh-properties (dprop tprop)
9458 "Refresh buffer text properties.
9459 DPROP is the drawer property and TPROP is either the
9460 corresponding text property to set, or an alist with each element
9461 being a text property (as a symbol) and a function to apply to
9462 the value of the drawer property."
9463 (let* ((case-fold-search t)
9464 (inhibit-read-only t)
9465 (inherit? (org-property-inherit-p dprop))
9466 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9467 (global (and inherit? (org--property-global-value dprop nil))))
9468 (org-with-silent-modifications
9469 (org-with-point-at 1
9470 ;; Set global values (e.g., values defined through
9471 ;; "#+PROPERTY:" keywords) to the whole buffer.
9472 (when global (put-text-property (point-min) (point-max) tprop global))
9473 ;; Set local values.
9474 (while (re-search-forward property-re nil t)
9475 (when (org-at-property-p)
9476 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9477 (outline-next-heading))))))
9479 (defun org-refresh-property (tprop p &optional inherit)
9480 "Refresh the buffer text property TPROP from the drawer property P.
9481 The refresh happens only for the current headline, or the whole
9482 sub-tree if optional argument INHERIT is non-nil."
9483 (unless (org-before-first-heading-p)
9484 (save-excursion
9485 (org-back-to-heading t)
9486 (let ((start (point))
9487 (end (save-excursion
9488 (if inherit (org-end-of-subtree t t)
9489 (or (outline-next-heading) (point-max))))))
9490 (if (symbolp tprop)
9491 ;; TPROP is a text property symbol.
9492 (put-text-property start end tprop p)
9493 ;; TPROP is an alist with (property . function) elements.
9494 (pcase-dolist (`(,prop . ,f) tprop)
9495 (put-text-property start end prop (funcall f p))))))))
9497 (defun org-refresh-category-properties ()
9498 "Refresh category text properties in the buffer."
9499 (let ((case-fold-search t)
9500 (inhibit-read-only t)
9501 (default-category
9502 (cond ((null org-category)
9503 (if buffer-file-name
9504 (file-name-sans-extension
9505 (file-name-nondirectory buffer-file-name))
9506 "???"))
9507 ((symbolp org-category) (symbol-name org-category))
9508 (t org-category))))
9509 (org-with-silent-modifications
9510 (org-with-wide-buffer
9511 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9512 ;; This is the default category for the buffer. If none is
9513 ;; found, fall-back to `org-category' or buffer file name.
9514 (put-text-property
9515 (point-min) (point-max)
9516 'org-category
9517 (catch 'buffer-category
9518 (goto-char (point-max))
9519 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9520 (let ((element (org-element-at-point)))
9521 (when (eq (org-element-type element) 'keyword)
9522 (throw 'buffer-category
9523 (org-element-property :value element)))))
9524 default-category))
9525 ;; Set sub-tree specific categories.
9526 (goto-char (point-min))
9527 (let ((regexp (org-re-property "CATEGORY")))
9528 (while (re-search-forward regexp nil t)
9529 (let ((value (match-string-no-properties 3)))
9530 (when (org-at-property-p)
9531 (put-text-property
9532 (save-excursion (org-back-to-heading t) (point))
9533 (save-excursion (org-end-of-subtree t t) (point))
9534 'org-category
9535 value)))))))))
9537 (defun org-refresh-stats-properties ()
9538 "Refresh stats text properties in the buffer."
9539 (org-with-silent-modifications
9540 (org-with-point-at 1
9541 (let ((regexp (concat org-outline-regexp-bol
9542 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9543 (while (re-search-forward regexp nil t)
9544 (let* ((numerator (string-to-number (match-string 1)))
9545 (denominator (and (match-end 2)
9546 (string-to-number (match-string 2))))
9547 (stats (cond ((not denominator) numerator) ;percent
9548 ((= denominator 0) 0)
9549 (t (/ (* numerator 100) denominator)))))
9550 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9551 'org-stats stats)))))))
9553 (defun org-refresh-effort-properties ()
9554 "Refresh effort properties"
9555 (org-refresh-properties
9556 org-effort-property
9557 '((effort . identity)
9558 (effort-minutes . org-duration-to-minutes))))
9560 ;;;; Link Stuff
9562 ;;; Link abbreviations
9564 (defun org-link-expand-abbrev (link)
9565 "Apply replacements as defined in `org-link-abbrev-alist'."
9566 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9567 (let* ((key (match-string 1 link))
9568 (as (or (assoc key org-link-abbrev-alist-local)
9569 (assoc key org-link-abbrev-alist)))
9570 (tag (and (match-end 2) (match-string 3 link)))
9571 rpl)
9572 (if (not as)
9573 link
9574 (setq rpl (cdr as))
9575 (cond
9576 ((symbolp rpl) (funcall rpl tag))
9577 ((string-match "%(\\([^)]+\\))" rpl)
9578 (replace-match
9579 (save-match-data
9580 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9581 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9582 ((string-match "%h" rpl)
9583 (replace-match (url-hexify-string (or tag "")) t t rpl))
9584 (t (concat rpl tag)))))
9585 link))
9587 ;;; Storing and inserting links
9589 (defvar org-insert-link-history nil
9590 "Minibuffer history for links inserted with `org-insert-link'.")
9592 (defvar org-stored-links nil
9593 "Contains the links stored with `org-store-link'.")
9595 (defvar org-store-link-plist nil
9596 "Plist with info about the most recently link created with `org-store-link'.")
9598 (defun org-store-link-functions ()
9599 "Return a list of functions that are called to create and store a link.
9600 The functions defined in the :store property of
9601 `org-link-parameters'.
9603 Each function will be called in turn until one returns a non-nil
9604 value. Each function should check if it is responsible for
9605 creating this link (for example by looking at the major mode).
9606 If not, it must exit and return nil. If yes, it should return
9607 a non-nil value after calling `org-store-link-props' with a list
9608 of properties and values. Special properties are:
9610 :type The link prefix, like \"http\". This must be given.
9611 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9612 This is obligatory as well.
9613 :description Optional default description for the second pair
9614 of brackets in an Org mode link. The user can still change
9615 this when inserting this link into an Org mode buffer.
9617 In addition to these, any additional properties can be specified
9618 and then used in capture templates."
9619 (cl-loop for link in org-link-parameters
9620 with store-func
9621 do (setq store-func (org-link-get-parameter (car link) :store))
9622 if store-func
9623 collect store-func))
9625 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9626 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9628 ;;;###autoload
9629 (defun org-store-link (arg)
9630 "Store an org-link to the current location.
9631 \\<org-mode-map>
9632 This link is added to `org-stored-links' and can later be inserted
9633 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9635 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9636 A single
9637 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9638 `org-gnus-prefer-web-links' for links to Usenet articles.
9640 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9641 skipping storing functions that are not
9642 part of Org core.
9644 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9645 prefix ARG forces storing a link for each line in the
9646 active region."
9647 (interactive "P")
9648 (org-load-modules-maybe)
9649 (if (and (equal arg '(64)) (org-region-active-p))
9650 (save-excursion
9651 (let ((end (region-end)))
9652 (goto-char (region-beginning))
9653 (set-mark (point))
9654 (while (< (point-at-eol) end)
9655 (move-end-of-line 1) (activate-mark)
9656 (let (current-prefix-arg)
9657 (call-interactively 'org-store-link))
9658 (move-beginning-of-line 2)
9659 (set-mark (point)))))
9660 (setq org-store-link-plist nil)
9661 (let (link cpltxt desc description search txt custom-id agenda-link)
9662 (cond
9663 ;; Store a link using an external link type, if any function is
9664 ;; available. If more than one can generate a link from current
9665 ;; location, ask which one to use.
9666 ((and (not (equal arg '(16)))
9667 (let ((results-alist nil))
9668 (dolist (f (org-store-link-functions))
9669 (when (funcall f)
9670 ;; XXX: return value is not link's plist, so we
9671 ;; store the new value before it is modified. It
9672 ;; would be cleaner to ask store link functions to
9673 ;; return the plist instead.
9674 (push (cons f (copy-sequence org-store-link-plist))
9675 results-alist)))
9676 (pcase results-alist
9677 (`nil nil)
9678 (`((,_ . ,_)) t) ;single choice: nothing to do
9679 (`((,name . ,_) . ,_)
9680 ;; Reinstate link plist associated to the chosen
9681 ;; function.
9682 (apply #'org-store-link-props
9683 (cdr (assoc-string
9684 (completing-read
9685 "Which function for creating the link? "
9686 (mapcar #'car results-alist)
9687 nil t (symbol-name name))
9688 results-alist)))
9689 t))))
9690 (setq link (plist-get org-store-link-plist :link))
9691 (setq desc (or (plist-get org-store-link-plist :description)
9692 link)))
9694 ;; Store a link from a source code buffer.
9695 ((org-src-edit-buffer-p)
9696 (let ((coderef-format (org-src-coderef-format)))
9697 (cond ((save-excursion
9698 (beginning-of-line)
9699 (looking-at (org-src-coderef-regexp coderef-format)))
9700 (setq link (format "(%s)" (match-string-no-properties 3))))
9701 ((called-interactively-p 'any)
9702 (let ((label (read-string "Code line label: ")))
9703 (end-of-line)
9704 (setq link (format coderef-format label))
9705 (let ((gc (- 79 (length link))))
9706 (if (< (current-column) gc)
9707 (org-move-to-column gc t)
9708 (insert " ")))
9709 (insert link)
9710 (setq link (concat "(" label ")"))
9711 (setq desc nil)))
9712 (t (setq link nil)))))
9714 ;; We are in the agenda, link to referenced location
9715 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9716 (let ((m (or (get-text-property (point) 'org-hd-marker)
9717 (get-text-property (point) 'org-marker))))
9718 (when m
9719 (org-with-point-at m
9720 (setq agenda-link
9721 (if (called-interactively-p 'any)
9722 (call-interactively 'org-store-link)
9723 (org-store-link nil)))))))
9725 ((eq major-mode 'calendar-mode)
9726 (let ((cd (calendar-cursor-to-date)))
9727 (setq link
9728 (format-time-string
9729 (car org-time-stamp-formats)
9730 (apply 'encode-time
9731 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9732 nil nil nil))))
9733 (org-store-link-props :type "calendar" :date cd)))
9735 ((eq major-mode 'help-mode)
9736 (setq link (concat "help:" (save-excursion
9737 (goto-char (point-min))
9738 (looking-at "^[^ ]+")
9739 (match-string 0))))
9740 (org-store-link-props :type "help"))
9742 ((eq major-mode 'w3-mode)
9743 (setq cpltxt (if (and (buffer-name)
9744 (not (string-match "Untitled" (buffer-name))))
9745 (buffer-name)
9746 (url-view-url t))
9747 link (url-view-url t))
9748 (org-store-link-props :type "w3" :url (url-view-url t)))
9750 ((eq major-mode 'image-mode)
9751 (setq cpltxt (concat "file:"
9752 (abbreviate-file-name buffer-file-name))
9753 link cpltxt)
9754 (org-store-link-props :type "image" :file buffer-file-name))
9756 ;; In dired, store a link to the file of the current line
9757 ((derived-mode-p 'dired-mode)
9758 (let ((file (dired-get-filename nil t)))
9759 (setq file (if file
9760 (abbreviate-file-name
9761 (expand-file-name (dired-get-filename nil t)))
9762 ;; otherwise, no file so use current directory.
9763 default-directory))
9764 (setq cpltxt (concat "file:" file)
9765 link cpltxt)))
9767 ((setq search (run-hook-with-args-until-success
9768 'org-create-file-search-functions))
9769 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9770 "::" search))
9771 (setq cpltxt (or description link)))
9773 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9774 (org-with-limited-levels
9775 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9776 (cond
9777 ;; Store a link using the target at point
9778 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9779 (setq cpltxt
9780 (concat "file:"
9781 (abbreviate-file-name
9782 (buffer-file-name (buffer-base-buffer)))
9783 "::" (match-string 1))
9784 link cpltxt))
9785 ((and (featurep 'org-id)
9786 (or (eq org-id-link-to-org-use-id t)
9787 (and (called-interactively-p 'any)
9788 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9789 (and (eq org-id-link-to-org-use-id
9790 'create-if-interactive-and-no-custom-id)
9791 (not custom-id))))
9792 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9793 ;; Store a link using the ID at point
9794 (setq link (condition-case nil
9795 (prog1 (org-id-store-link)
9796 (setq desc (or (plist-get org-store-link-plist
9797 :description)
9798 "")))
9799 (error
9800 ;; Probably before first headline, link only to file
9801 (concat "file:"
9802 (abbreviate-file-name
9803 (buffer-file-name (buffer-base-buffer))))))))
9805 ;; Just link to current headline
9806 (setq cpltxt (concat "file:"
9807 (abbreviate-file-name
9808 (buffer-file-name (buffer-base-buffer)))))
9809 ;; Add a context search string
9810 (when (org-xor org-context-in-file-links
9811 (equal arg '(4)))
9812 (let* ((element (org-element-at-point))
9813 (name (org-element-property :name element)))
9814 (setq txt (cond
9815 ((org-at-heading-p) nil)
9816 (name)
9817 ((org-region-active-p)
9818 (buffer-substring (region-beginning) (region-end)))))
9819 (when (or (null txt) (string-match "\\S-" txt))
9820 (setq cpltxt
9821 (concat cpltxt "::"
9822 (condition-case nil
9823 (org-make-org-heading-search-string txt)
9824 (error "")))
9825 desc (or name
9826 (nth 4 (ignore-errors (org-heading-components)))
9827 "NONE")))))
9828 (when (string-match "::\\'" cpltxt)
9829 (setq cpltxt (substring cpltxt 0 -2)))
9830 (setq link cpltxt)))))
9832 ((buffer-file-name (buffer-base-buffer))
9833 ;; Just link to this file here.
9834 (setq cpltxt (concat "file:"
9835 (abbreviate-file-name
9836 (buffer-file-name (buffer-base-buffer)))))
9837 ;; Add a context string.
9838 (when (org-xor org-context-in-file-links
9839 (equal arg '(4)))
9840 (setq txt (if (org-region-active-p)
9841 (buffer-substring (region-beginning) (region-end))
9842 (buffer-substring (point-at-bol) (point-at-eol))))
9843 ;; Only use search option if there is some text.
9844 (when (string-match "\\S-" txt)
9845 (setq cpltxt
9846 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9847 desc "NONE")))
9848 (setq link cpltxt))
9850 ((called-interactively-p 'interactive)
9851 (user-error "No method for storing a link from this buffer"))
9853 (t (setq link nil)))
9855 ;; We're done setting link and desc, clean up
9856 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9857 (setq link (or link cpltxt)
9858 desc (or desc cpltxt))
9859 (cond ((not desc))
9860 ((equal desc "NONE") (setq desc nil))
9861 (t (setq desc
9862 (replace-regexp-in-string
9863 org-bracket-link-analytic-regexp
9864 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9865 desc))))
9866 ;; Return the link
9867 (if (not (and (or (called-interactively-p 'any)
9868 executing-kbd-macro)
9869 link))
9870 (or agenda-link (and link (org-make-link-string link desc)))
9871 (push (list link desc) org-stored-links)
9872 (message "Stored: %s" (or desc link))
9873 (when custom-id
9874 (setq link (concat "file:" (abbreviate-file-name
9875 (buffer-file-name)) "::#" custom-id))
9876 (push (list link desc) org-stored-links))
9877 (car org-stored-links)))))
9879 (defun org-store-link-props (&rest plist)
9880 "Store link properties.
9881 The properties are pre-processed by extracting names, addresses
9882 and dates."
9883 (let ((x (plist-get plist :from)))
9884 (when x
9885 (let ((adr (mail-extract-address-components x)))
9886 (setq plist (plist-put plist :fromname (car adr)))
9887 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9888 (let ((x (plist-get plist :to)))
9889 (when x
9890 (let ((adr (mail-extract-address-components x)))
9891 (setq plist (plist-put plist :toname (car adr)))
9892 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9893 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9894 (when x
9895 (setq plist (plist-put plist :date-timestamp
9896 (format-time-string
9897 (org-time-stamp-format t) x)))
9898 (setq plist (plist-put plist :date-timestamp-inactive
9899 (format-time-string
9900 (org-time-stamp-format t t) x)))))
9901 (let ((from (plist-get plist :from))
9902 (to (plist-get plist :to)))
9903 (when (and from to org-from-is-user-regexp)
9904 (setq plist
9905 (plist-put plist :fromto
9906 (if (string-match org-from-is-user-regexp from)
9907 (concat "to %t")
9908 (concat "from %f"))))))
9909 (setq org-store-link-plist plist))
9911 (defun org-add-link-props (&rest plist)
9912 "Add these properties to the link property list."
9913 (let (key value)
9914 (while plist
9915 (setq key (pop plist) value (pop plist))
9916 (setq org-store-link-plist
9917 (plist-put org-store-link-plist key value)))))
9919 (defun org-email-link-description (&optional fmt)
9920 "Return the description part of an email link.
9921 This takes information from `org-store-link-plist' and formats it
9922 according to FMT (default from `org-email-link-description-format')."
9923 (setq fmt (or fmt org-email-link-description-format))
9924 (let* ((p org-store-link-plist)
9925 (to (plist-get p :toaddress))
9926 (from (plist-get p :fromaddress))
9927 (table
9928 (list
9929 (cons "%c" (plist-get p :fromto))
9930 (cons "%F" (plist-get p :from))
9931 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9932 (cons "%T" (plist-get p :to))
9933 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9934 (cons "%s" (plist-get p :subject))
9935 (cons "%d" (plist-get p :date))
9936 (cons "%m" (plist-get p :message-id)))))
9937 (when (string-match "%c" fmt)
9938 ;; Check if the user wrote this message
9939 (if (and org-from-is-user-regexp from to
9940 (save-match-data (string-match org-from-is-user-regexp from)))
9941 (setq fmt (replace-match "to %t" t t fmt))
9942 (setq fmt (replace-match "from %f" t t fmt))))
9943 (org-replace-escapes fmt table)))
9945 (defun org-make-org-heading-search-string (&optional string)
9946 "Make search string for the current headline or STRING."
9947 (let ((s (or string
9948 (and (derived-mode-p 'org-mode)
9949 (save-excursion
9950 (org-back-to-heading t)
9951 (org-element-property :raw-value (org-element-at-point))))))
9952 (lines org-context-in-file-links))
9953 (unless string (setq s (concat "*" s))) ;Add * for headlines
9954 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9955 (when (and string (integerp lines) (> lines 0))
9956 (let ((slines (org-split-string s "\n")))
9957 (when (< lines (length slines))
9958 (setq s (mapconcat
9959 'identity
9960 (reverse (nthcdr (- (length slines) lines)
9961 (reverse slines))) "\n")))))
9962 (mapconcat #'identity (split-string s) " ")))
9964 (defconst org-link-escape-chars
9965 ;;%20 %5B %5D %25
9966 '(?\s ?\[ ?\] ?%)
9967 "List of characters that should be escaped in a link when stored to Org.
9968 This is the list that is used for internal purposes.")
9970 (defun org-make-link-string (link &optional description)
9971 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9972 (unless (org-string-nw-p link) (error "Empty link"))
9973 (let ((uri (cond ((string-match org-link-types-re link)
9974 (concat (match-string 1 link)
9975 (org-link-escape (substring link (match-end 1)))))
9976 ((or (file-name-absolute-p link)
9977 (string-match-p "\\`\\.\\.?/" link))
9978 (org-link-escape link))
9979 ;; For readability, do not encode space characters
9980 ;; in fuzzy links.
9981 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9982 (description
9983 (and (org-string-nw-p description)
9984 ;; Remove brackets from description, as they are fatal.
9985 (replace-regexp-in-string
9986 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9987 (org-trim description)))))
9988 (format "[[%s]%s]"
9990 (if description (format "[%s]" description) ""))))
9992 (defun org-link-escape (text &optional table merge)
9993 "Return percent escaped representation of TEXT.
9994 TEXT is a string with the text to escape.
9995 Optional argument TABLE is a list with characters that should be
9996 escaped. When nil, `org-link-escape-chars' is used.
9997 If optional argument MERGE is set, merge TABLE into
9998 `org-link-escape-chars'."
9999 (let ((characters-to-encode
10000 (cond ((null table) org-link-escape-chars)
10001 (merge (append org-link-escape-chars table))
10002 (t table))))
10003 (mapconcat
10004 (lambda (c)
10005 (if (or (memq c characters-to-encode)
10006 (and org-url-hexify-p (or (< c 32) (> c 126))))
10007 (mapconcat (lambda (e) (format "%%%.2X" e))
10008 (or (encode-coding-char c 'utf-8)
10009 (error "Unable to percent escape character: %c" c))
10011 (char-to-string c)))
10012 text "")))
10014 (defun org-link-unescape (str)
10015 "Unhex hexified Unicode parts in string STR.
10016 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10017 reciprocal of `org-link-escape', which see."
10018 (if (org-string-nw-p str)
10019 (replace-regexp-in-string
10020 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10021 str))
10023 (defun org-link-unescape-compound (hex)
10024 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10025 Note: this function also decodes single byte encodings like
10026 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10027 (save-match-data
10028 (let* ((bytes (cdr (split-string hex "%")))
10029 (ret "")
10030 (eat 0)
10031 (sum 0))
10032 (while bytes
10033 (let* ((val (string-to-number (pop bytes) 16))
10034 (shift-xor
10035 (if (= 0 eat)
10036 (cond
10037 ((>= val 252) (cons 6 252))
10038 ((>= val 248) (cons 5 248))
10039 ((>= val 240) (cons 4 240))
10040 ((>= val 224) (cons 3 224))
10041 ((>= val 192) (cons 2 192))
10042 (t (cons 0 0)))
10043 (cons 6 128))))
10044 (when (>= val 192) (setq eat (car shift-xor)))
10045 (setq val (logxor val (cdr shift-xor)))
10046 (setq sum (+ (lsh sum (car shift-xor)) val))
10047 (when (> eat 0) (setq eat (- eat 1)))
10048 (cond
10049 ((= 0 eat) ;multi byte
10050 (setq ret (concat ret (char-to-string sum)))
10051 (setq sum 0))
10052 ((not bytes) ; single byte(s)
10053 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10054 ret)))
10056 (defun org-link-unescape-single-byte-sequence (hex)
10057 "Unhexify hex-encoded single byte character sequences."
10058 (mapconcat (lambda (byte)
10059 (char-to-string (string-to-number byte 16)))
10060 (cdr (split-string hex "%")) ""))
10062 (defun org-xor (a b)
10063 "Exclusive or."
10064 (if a (not b) b))
10066 (defun org-fixup-message-id-for-http (s)
10067 "Replace special characters in a message id, so it can be used in an http query."
10068 (when (string-match "%" s)
10069 (setq s (mapconcat (lambda (c)
10070 (if (eq c ?%)
10071 "%25"
10072 (char-to-string c)))
10073 s "")))
10074 (while (string-match "<" s)
10075 (setq s (replace-match "%3C" t t s)))
10076 (while (string-match ">" s)
10077 (setq s (replace-match "%3E" t t s)))
10078 (while (string-match "@" s)
10079 (setq s (replace-match "%40" t t s)))
10082 (defun org-link-prettify (link)
10083 "Return a human-readable representation of LINK.
10084 The car of LINK must be a raw link.
10085 The cdr of LINK must be either a link description or nil."
10086 (let ((desc (or (cadr link) "<no description>")))
10087 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10088 "<" (car link) ">")))
10090 ;;;###autoload
10091 (defun org-insert-link-global ()
10092 "Insert a link like Org mode does.
10093 This command can be called in any mode to insert a link in Org syntax."
10094 (interactive)
10095 (org-load-modules-maybe)
10096 (org-run-like-in-org-mode 'org-insert-link))
10098 (defun org-insert-all-links (arg &optional pre post)
10099 "Insert all links in `org-stored-links'.
10100 When a universal prefix, do not delete the links from `org-stored-links'.
10101 When `ARG' is a number, insert the last N link(s).
10102 `PRE' and `POST' are optional arguments to define a string to
10103 prepend or to append."
10104 (interactive "P")
10105 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10106 (links (copy-sequence org-stored-links))
10107 (pr (or pre "- "))
10108 (po (or post "\n"))
10109 (cnt 1) l)
10110 (if (null org-stored-links)
10111 (message "No link to insert")
10112 (while (and (or (listp arg) (>= arg cnt))
10113 (setq l (if (listp arg)
10114 (pop links)
10115 (pop org-stored-links))))
10116 (setq cnt (1+ cnt))
10117 (insert pr)
10118 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10119 (insert po)))))
10121 (defun org-insert-last-stored-link (arg)
10122 "Insert the last link stored in `org-stored-links'."
10123 (interactive "p")
10124 (org-insert-all-links arg "" "\n"))
10126 (defun org-link-fontify-links-to-this-file ()
10127 "Fontify links to the current file in `org-stored-links'."
10128 (let ((f (buffer-file-name)) a b)
10129 (setq a (mapcar (lambda(l)
10130 (let ((ll (car l)))
10131 (when (and (string-match "^file:\\(.+\\)::" ll)
10132 (equal f (expand-file-name (match-string 1 ll))))
10133 ll)))
10134 org-stored-links))
10135 (when (featurep 'org-id)
10136 (setq b (mapcar (lambda(l)
10137 (let ((ll (car l)))
10138 (when (and (string-match "^id:\\(.+\\)$" ll)
10139 (equal f (expand-file-name
10140 (or (org-id-find-id-file
10141 (match-string 1 ll)) ""))))
10142 ll)))
10143 org-stored-links)))
10144 (mapcar (lambda(l)
10145 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10146 (delq nil (append a b)))))
10148 (defvar org--links-history nil)
10149 (defun org-insert-link (&optional complete-file link-location default-description)
10150 "Insert a link. At the prompt, enter the link.
10152 Completion can be used to insert any of the link protocol prefixes in use.
10154 The history can be used to select a link previously stored with
10155 `org-store-link'. When the empty string is entered (i.e. if you just
10156 press `RET' at the prompt), the link defaults to the most recently
10157 stored link. As `SPC' triggers completion in the minibuffer, you need to
10158 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10160 You will also be prompted for a description, and if one is given, it will
10161 be displayed in the buffer instead of the link.
10163 If there is already a link at point, this command will allow you to edit
10164 link and description parts.
10166 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10167 file name can be
10168 selected using completion. The path to the file will be relative to the
10169 current directory if the file is in the current directory or a subdirectory.
10170 Otherwise, the link will be the absolute path as completed in the minibuffer
10171 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10172 option `org-link-file-path-type'.
10174 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10175 absolute path even if the file is in
10176 the current directory or below.
10178 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10179 prefix negates `org-keep-stored-link-after-insertion'.
10181 If the LINK-LOCATION parameter is non-nil, this value will be used as
10182 the link location instead of reading one interactively.
10184 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10185 be used as the default description. Otherwise, if
10186 `org-make-link-description-function' is non-nil, this function
10187 will be called with the link target, and the result will be the
10188 default link description."
10189 (interactive "P")
10190 (let* ((wcf (current-window-configuration))
10191 (origbuf (current-buffer))
10192 (region (when (org-region-active-p)
10193 (buffer-substring (region-beginning) (region-end))))
10194 (remove (and region (list (region-beginning) (region-end))))
10195 (desc region)
10196 (link link-location)
10197 (abbrevs org-link-abbrev-alist-local)
10198 entry all-prefixes auto-desc)
10199 (cond
10200 (link-location) ; specified by arg, just use it.
10201 ((org-in-regexp org-bracket-link-regexp 1)
10202 ;; We do have a link at point, and we are going to edit it.
10203 (setq remove (list (match-beginning 0) (match-end 0)))
10204 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10205 (setq link (read-string "Link: "
10206 (org-link-unescape
10207 (match-string-no-properties 1)))))
10208 ((or (org-in-regexp org-angle-link-re)
10209 (org-in-regexp org-plain-link-re))
10210 ;; Convert to bracket link
10211 (setq remove (list (match-beginning 0) (match-end 0))
10212 link (read-string "Link: "
10213 (org-unbracket-string "<" ">" (match-string 0)))))
10214 ((member complete-file '((4) (16)))
10215 ;; Completing read for file names.
10216 (setq link (org-file-complete-link complete-file)))
10218 ;; Read link, with completion for stored links.
10219 (org-link-fontify-links-to-this-file)
10220 (org-switch-to-buffer-other-window "*Org Links*")
10221 (with-current-buffer "*Org Links*"
10222 (erase-buffer)
10223 (insert "Insert a link.
10224 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10225 (when org-stored-links
10226 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10227 (insert (mapconcat 'org-link-prettify
10228 (reverse org-stored-links) "\n")))
10229 (goto-char (point-min)))
10230 (let ((cw (selected-window)))
10231 (select-window (get-buffer-window "*Org Links*" 'visible))
10232 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10233 (unless (pos-visible-in-window-p (point-max))
10234 (org-fit-window-to-buffer))
10235 (and (window-live-p cw) (select-window cw)))
10236 (setq all-prefixes (append (mapcar 'car abbrevs)
10237 (mapcar 'car org-link-abbrev-alist)
10238 (org-link-types)))
10239 (unwind-protect
10240 ;; Fake a link history, containing the stored links.
10241 (let ((org--links-history
10242 (append (mapcar #'car org-stored-links)
10243 org-insert-link-history)))
10244 (setq link
10245 (org-completing-read
10246 "Link: "
10247 (append
10248 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10249 (mapcar #'car org-stored-links))
10250 nil nil nil
10251 'org--links-history
10252 (caar org-stored-links)))
10253 (unless (org-string-nw-p link) (user-error "No link selected"))
10254 (dolist (l org-stored-links)
10255 (when (equal link (cadr l))
10256 (setq link (car l))
10257 (setq auto-desc t)))
10258 (when (or (member link all-prefixes)
10259 (and (equal ":" (substring link -1))
10260 (member (substring link 0 -1) all-prefixes)
10261 (setq link (substring link 0 -1))))
10262 (setq link (with-current-buffer origbuf
10263 (org-link-try-special-completion link)))))
10264 (set-window-configuration wcf)
10265 (kill-buffer "*Org Links*"))
10266 (setq entry (assoc link org-stored-links))
10267 (or entry (push link org-insert-link-history))
10268 (setq desc (or desc (nth 1 entry)))))
10270 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10271 (not org-keep-stored-link-after-insertion))
10272 (setq org-stored-links (delq (assoc link org-stored-links)
10273 org-stored-links)))
10275 (when (and (string-match org-plain-link-re link)
10276 (not (string-match org-ts-regexp link)))
10277 ;; URL-like link, normalize the use of angular brackets.
10278 (setq link (org-unbracket-string "<" ">" link)))
10280 ;; Check if we are linking to the current file with a search
10281 ;; option If yes, simplify the link by using only the search
10282 ;; option.
10283 (when (and buffer-file-name
10284 (let ((case-fold-search nil))
10285 (string-match "\\`file:\\(.+?\\)::" link)))
10286 (let ((path (match-string-no-properties 1 link))
10287 (search (substring-no-properties link (match-end 0))))
10288 (save-match-data
10289 (when (equal (file-truename buffer-file-name) (file-truename path))
10290 ;; We are linking to this same file, with a search option
10291 (setq link search)))))
10293 ;; Check if we can/should use a relative path. If yes, simplify
10294 ;; the link.
10295 (let ((case-fold-search nil))
10296 (when (string-match "\\`\\(file\\|docview\\):" link)
10297 (let* ((type (match-string-no-properties 0 link))
10298 (path-start (match-end 0))
10299 (search (and (string-match "::\\(.*\\)\\'" link)
10300 (match-string 1 link)))
10301 (path
10302 (if search
10303 (substring-no-properties
10304 link path-start (match-beginning 0))
10305 (substring-no-properties link (match-end 0))))
10306 (origpath path))
10307 (cond
10308 ((or (eq org-link-file-path-type 'absolute)
10309 (equal complete-file '(16)))
10310 (setq path (abbreviate-file-name (expand-file-name path))))
10311 ((eq org-link-file-path-type 'noabbrev)
10312 (setq path (expand-file-name path)))
10313 ((eq org-link-file-path-type 'relative)
10314 (setq path (file-relative-name path)))
10316 (save-match-data
10317 (if (string-match (concat "^" (regexp-quote
10318 (expand-file-name
10319 (file-name-as-directory
10320 default-directory))))
10321 (expand-file-name path))
10322 ;; We are linking a file with relative path name.
10323 (setq path (substring (expand-file-name path)
10324 (match-end 0)))
10325 (setq path (abbreviate-file-name (expand-file-name path)))))))
10326 (setq link (concat type path (and search (concat "::" search))))
10327 (when (equal desc origpath)
10328 (setq desc path)))))
10330 (unless auto-desc
10331 (let ((initial-input
10332 (cond
10333 (default-description)
10334 ((not org-make-link-description-function) desc)
10335 (t (condition-case nil
10336 (funcall org-make-link-description-function link desc)
10337 (error
10338 (message "Can't get link description from `%s'"
10339 (symbol-name org-make-link-description-function))
10340 (sit-for 2)
10341 nil))))))
10342 (setq desc (read-string "Description: " initial-input))))
10344 (unless (string-match "\\S-" desc) (setq desc nil))
10345 (when remove (apply 'delete-region remove))
10346 (insert (org-make-link-string link desc))
10347 ;; Redisplay so as the new link has proper invisible characters.
10348 (sit-for 0)))
10350 (defun org-link-try-special-completion (type)
10351 "If there is completion support for link type TYPE, offer it."
10352 (let ((fun (org-link-get-parameter type :complete)))
10353 (if (functionp fun)
10354 (funcall fun)
10355 (read-string "Link (no completion support): " (concat type ":")))))
10357 (defun org-file-complete-link (&optional arg)
10358 "Create a file link using completion."
10359 (let ((file (read-file-name "File: "))
10360 (pwd (file-name-as-directory (expand-file-name ".")))
10361 (pwd1 (file-name-as-directory (abbreviate-file-name
10362 (expand-file-name ".")))))
10363 (cond ((equal arg '(16))
10364 (concat "file:"
10365 (abbreviate-file-name (expand-file-name file))))
10366 ((string-match
10367 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10368 (concat "file:" (match-string 1 file)))
10369 ((string-match
10370 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10371 (expand-file-name file))
10372 (concat "file:"
10373 (match-string 1 (expand-file-name file))))
10374 (t (concat "file:" file)))))
10376 (defun org-completing-read (&rest args)
10377 "Completing-read with SPACE being a normal character."
10378 (let ((enable-recursive-minibuffers t)
10379 (minibuffer-local-completion-map
10380 (copy-keymap minibuffer-local-completion-map)))
10381 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10382 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10383 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10384 'org-time-stamp-inactive)
10385 (apply #'completing-read args)))
10387 ;;; Opening/following a link
10389 (defvar org-link-search-failed nil)
10391 (defvar org-open-link-functions nil
10392 "Hook for functions finding a plain text link.
10393 These functions must take a single argument, the link content.
10394 They will be called for links that look like [[link text][description]]
10395 when LINK TEXT does not have a protocol like \"http:\" and does not look
10396 like a filename (e.g. \"./blue.png\").
10398 These functions will be called *before* Org attempts to resolve the
10399 link by doing text searches in the current buffer - so if you want a
10400 link \"[[target]]\" to still find \"<<target>>\", your function should
10401 handle this as a special case.
10403 When the function does handle the link, it must return a non-nil value.
10404 If it decides that it is not responsible for this link, it must return
10405 nil to indicate that that Org can continue with other options like
10406 exact and fuzzy text search.")
10408 (defun org-next-link (&optional search-backward)
10409 "Move forward to the next link.
10410 If the link is in hidden text, expose it."
10411 (interactive "P")
10412 (when (and org-link-search-failed (eq this-command last-command))
10413 (goto-char (point-min))
10414 (message "Link search wrapped back to beginning of buffer"))
10415 (setq org-link-search-failed nil)
10416 (let* ((pos (point))
10417 (ct (org-context))
10418 (a (assq :link ct))
10419 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10420 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10421 ((looking-at org-any-link-re)
10422 ;; Don't stay stuck at link without an org-link face
10423 (forward-char (if search-backward -1 1))))
10424 (if (funcall srch-fun org-any-link-re nil t)
10425 (progn
10426 (goto-char (match-beginning 0))
10427 (when (org-invisible-p) (org-show-context)))
10428 (goto-char pos)
10429 (setq org-link-search-failed t)
10430 (message "No further link found"))))
10432 (defun org-previous-link ()
10433 "Move backward to the previous link.
10434 If the link is in hidden text, expose it."
10435 (interactive)
10436 (funcall 'org-next-link t))
10438 (defun org-translate-link (s)
10439 "Translate a link string if a translation function has been defined."
10440 (with-temp-buffer
10441 (insert (org-trim s))
10442 (org-trim (org-element-interpret-data (org-element-context)))))
10444 (defun org-translate-link-from-planner (type path)
10445 "Translate a link from Emacs Planner syntax so that Org can follow it.
10446 This is still an experimental function, your mileage may vary."
10447 (cond
10448 ((member type '("http" "https" "news" "ftp"))
10449 ;; standard Internet links are the same.
10450 nil)
10451 ((and (equal type "irc") (string-match "^//" path))
10452 ;; Planner has two / at the beginning of an irc link, we have 1.
10453 ;; We should have zero, actually....
10454 (setq path (substring path 1)))
10455 ((and (equal type "lisp") (string-match "^/" path))
10456 ;; Planner has a slash, we do not.
10457 (setq type "elisp" path (substring path 1)))
10458 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10459 ;; A typical message link. Planner has the id after the final slash,
10460 ;; we separate it with a hash mark
10461 (setq path (concat (match-string 1 path) "#"
10462 (org-unbracket-string "<" ">" (match-string 2 path))))))
10463 (cons type path))
10465 (defun org-find-file-at-mouse (ev)
10466 "Open file link or URL at mouse."
10467 (interactive "e")
10468 (mouse-set-point ev)
10469 (org-open-at-point 'in-emacs))
10471 (defun org-open-at-mouse (ev)
10472 "Open file link or URL at mouse.
10473 See the docstring of `org-open-file' for details."
10474 (interactive "e")
10475 (mouse-set-point ev)
10476 (when (eq major-mode 'org-agenda-mode)
10477 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10478 (org-open-at-point))
10480 (defvar org-window-config-before-follow-link nil
10481 "The window configuration before following a link.
10482 This is saved in case the need arises to restore it.")
10484 ;;;###autoload
10485 (defun org-open-at-point-global ()
10486 "Follow a link or time-stamp like Org mode does.
10487 This command can be called in any mode to follow an external link
10488 or a time-stamp that has Org mode syntax. Its behavior is
10489 undefined when called on internal links (e.g., fuzzy links).
10490 Raise an error when there is nothing to follow. "
10491 (interactive)
10492 (cond ((org-in-regexp org-any-link-re)
10493 (org-open-link-from-string (match-string-no-properties 0)))
10494 ((or (org-in-regexp org-ts-regexp-both nil t)
10495 (org-in-regexp org-tsr-regexp-both nil t))
10496 (org-follow-timestamp-link))
10497 (t (user-error "No link found"))))
10499 ;;;###autoload
10500 (defun org-open-link-from-string (s &optional arg reference-buffer)
10501 "Open a link in the string S, as if it was in Org mode."
10502 (interactive "sLink: \nP")
10503 (let ((reference-buffer (or reference-buffer (current-buffer))))
10504 (with-temp-buffer
10505 (let ((org-inhibit-startup (not reference-buffer)))
10506 (org-mode)
10507 (insert s)
10508 (goto-char (point-min))
10509 (when reference-buffer
10510 (setq org-link-abbrev-alist-local
10511 (with-current-buffer reference-buffer
10512 org-link-abbrev-alist-local)))
10513 (org-open-at-point arg reference-buffer)))))
10515 (defvar org-open-at-point-functions nil
10516 "Hook that is run when following a link at point.
10518 Functions in this hook must return t if they identify and follow
10519 a link at point. If they don't find anything interesting at point,
10520 they must return nil.")
10522 (defvar org-link-search-inhibit-query nil)
10523 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10524 (defun org--open-doi-link (path)
10525 "Open a \"doi\" type link.
10526 PATH is a the path to search for, as a string."
10527 (browse-url (url-encode-url (concat org-doi-server-url path))))
10529 (defun org--open-elisp-link (path)
10530 "Open a \"elisp\" type link.
10531 PATH is the sexp to evaluate, as a string."
10532 (let ((cmd path))
10533 (if (or (and (org-string-nw-p
10534 org-confirm-elisp-link-not-regexp)
10535 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10536 (not org-confirm-elisp-link-function)
10537 (funcall org-confirm-elisp-link-function
10538 (format "Execute \"%s\" as elisp? "
10539 (org-add-props cmd nil 'face 'org-warning))))
10540 (message "%s => %s" cmd
10541 (if (eq (string-to-char cmd) ?\()
10542 (eval (read cmd))
10543 (call-interactively (read cmd))))
10544 (user-error "Abort"))))
10546 (defun org--open-help-link (path)
10547 "Open a \"help\" type link.
10548 PATH is a symbol name, as a string."
10549 (pcase (intern path)
10550 ((and (pred fboundp) variable) (describe-function variable))
10551 ((and (pred boundp) function) (describe-variable function))
10552 (name (user-error "Unknown function or variable: %s" name))))
10554 (defun org--open-shell-link (path)
10555 "Open a \"shell\" type link.
10556 PATH is the command to execute, as a string."
10557 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10558 (cmd path))
10559 (if (or (and (org-string-nw-p
10560 org-confirm-shell-link-not-regexp)
10561 (string-match
10562 org-confirm-shell-link-not-regexp cmd))
10563 (not org-confirm-shell-link-function)
10564 (funcall org-confirm-shell-link-function
10565 (format "Execute \"%s\" in shell? "
10566 (org-add-props cmd nil
10567 'face 'org-warning))))
10568 (progn
10569 (message "Executing %s" cmd)
10570 (shell-command cmd buf)
10571 (when (featurep 'midnight)
10572 (setq clean-buffer-list-kill-buffer-names
10573 (cons (buffer-name buf)
10574 clean-buffer-list-kill-buffer-names))))
10575 (user-error "Abort"))))
10577 (defun org-open-at-point (&optional arg reference-buffer)
10578 "Open link, timestamp, footnote or tags at point.
10580 When point is on a link, follow it. Normally, files will be
10581 opened by an appropriate application. If the optional prefix
10582 argument ARG is non-nil, Emacs will visit the file. With
10583 a double prefix argument, try to open outside of Emacs, in the
10584 application the system uses for this file type.
10586 When point is on a timestamp, open the agenda at the day
10587 specified.
10589 When point is a footnote definition, move to the first reference
10590 found. If it is on a reference, move to the associated
10591 definition.
10593 When point is on a headline, display a list of every link in the
10594 entry, so it is possible to pick one, or all, of them. If point
10595 is on a tag, call `org-tags-view' instead.
10597 When optional argument REFERENCE-BUFFER is non-nil, it should
10598 specify a buffer from where the link search should happen. This
10599 is used internally by `org-open-link-from-string'.
10601 On top of syntactically correct links, this function will also
10602 try to open links and time-stamps in comments, example
10603 blocks... i.e., whenever point is on something looking like
10604 a timestamp or a link."
10605 (interactive "P")
10606 ;; On a code block, open block's results.
10607 (unless (call-interactively 'org-babel-open-src-block-result)
10608 (org-load-modules-maybe)
10609 (setq org-window-config-before-follow-link (current-window-configuration))
10610 (org-remove-occur-highlights nil nil t)
10611 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10612 (let* ((context
10613 ;; Only consider supported types, even if they are not
10614 ;; the closest one.
10615 (org-element-lineage
10616 (org-element-context)
10617 '(clock footnote-definition footnote-reference headline
10618 inlinetask link timestamp)
10620 (type (org-element-type context))
10621 (value (org-element-property :value context)))
10622 (cond
10623 ;; On a headline or an inlinetask, but not on a timestamp,
10624 ;; a link, a footnote reference.
10625 ((memq type '(headline inlinetask))
10626 (org-match-line org-complex-heading-regexp)
10627 (if (and (match-beginning 5)
10628 (>= (point) (match-beginning 5))
10629 (< (point) (match-end 5)))
10630 ;; On tags.
10631 (org-tags-view arg (substring (match-string 5) 0 -1))
10632 ;; Not on tags.
10633 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10634 (`(nil . ,_)
10635 (require 'org-attach)
10636 (org-attach-reveal 'if-exists))
10637 (`(,links . ,links-end)
10638 (dolist (link (if (stringp links) (list links) links))
10639 (search-forward link nil links-end)
10640 (goto-char (match-beginning 0))
10641 (org-open-at-point))))))
10642 ;; On a footnote reference or at definition's label.
10643 ((or (eq type 'footnote-reference)
10644 (and (eq type 'footnote-definition)
10645 (save-excursion
10646 ;; Do not validate action when point is on the
10647 ;; spaces right after the footnote label, in
10648 ;; order to be on par with behavior on links.
10649 (skip-chars-forward " \t")
10650 (let ((begin
10651 (org-element-property :contents-begin context)))
10652 (if begin (< (point) begin)
10653 (= (org-element-property :post-affiliated context)
10654 (line-beginning-position)))))))
10655 (org-footnote-action))
10656 ;; No valid context. Ignore catch-all types like `headline'.
10657 ;; If point is on something looking like a link or
10658 ;; a time-stamp, try opening it. It may be useful in
10659 ;; comments, example blocks...
10660 ((memq type '(footnote-definition headline inlinetask nil))
10661 (call-interactively #'org-open-at-point-global))
10662 ;; On a clock line, make sure point is on the timestamp
10663 ;; before opening it.
10664 ((and (eq type 'clock)
10665 value
10666 (>= (point) (org-element-property :begin value))
10667 (<= (point) (org-element-property :end value)))
10668 (org-follow-timestamp-link))
10669 ;; Do nothing on white spaces after an object.
10670 ((>= (point)
10671 (save-excursion
10672 (goto-char (org-element-property :end context))
10673 (skip-chars-backward " \t")
10674 (point)))
10675 (user-error "No link found"))
10676 ((eq type 'timestamp) (org-follow-timestamp-link))
10677 ((eq type 'link)
10678 (let ((type (org-element-property :type context))
10679 (path (org-link-unescape (org-element-property :path context))))
10680 ;; Switch back to REFERENCE-BUFFER needed when called in
10681 ;; a temporary buffer through `org-open-link-from-string'.
10682 (with-current-buffer (or reference-buffer (current-buffer))
10683 (cond
10684 ((equal type "file")
10685 (if (string-match "[*?{]" (file-name-nondirectory path))
10686 (dired path)
10687 ;; Look into `org-link-parameters' in order to find
10688 ;; a DEDICATED-FUNCTION to open file. The function
10689 ;; will be applied on raw link instead of parsed
10690 ;; link due to the limitation in `org-add-link-type'
10691 ;; ("open" function called with a single argument).
10692 ;; If no such function is found, fallback to
10693 ;; `org-open-file'.
10694 (let* ((option (org-element-property :search-option context))
10695 (app (org-element-property :application context))
10696 (dedicated-function
10697 (org-link-get-parameter
10698 (if app (concat type "+" app) type)
10699 :follow)))
10700 (if dedicated-function
10701 (funcall dedicated-function
10702 (concat path
10703 (and option (concat "::" option))))
10704 (apply #'org-open-file
10705 path
10706 (cond (arg)
10707 ((equal app "emacs") 'emacs)
10708 ((equal app "sys") 'system))
10709 (cond ((not option) nil)
10710 ((string-match-p "\\`[0-9]+\\'" option)
10711 (list (string-to-number option)))
10712 (t (list nil
10713 (org-link-unescape option)))))))))
10714 ((functionp (org-link-get-parameter type :follow))
10715 (funcall (org-link-get-parameter type :follow) path))
10716 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10717 (unless (run-hook-with-args-until-success
10718 'org-open-link-functions path)
10719 (if (not arg) (org-mark-ring-push)
10720 (switch-to-buffer-other-window
10721 (org-get-buffer-for-internal-link (current-buffer))))
10722 (let ((destination
10723 (org-with-wide-buffer
10724 (if (equal type "radio")
10725 (org-search-radio-target
10726 (org-element-property :path context))
10727 (org-link-search
10728 (if (member type '("custom-id" "coderef"))
10729 (org-element-property :raw-link context)
10730 path)
10731 ;; Prevent fuzzy links from matching
10732 ;; themselves.
10733 (and (equal type "fuzzy")
10734 (+ 2 (org-element-property :begin context)))))
10735 (point))))
10736 (unless (and (<= (point-min) destination)
10737 (>= (point-max) destination))
10738 (widen))
10739 (goto-char destination))))
10740 (t (browse-url-at-point))))))
10741 (t (user-error "No link found")))))
10742 (run-hook-with-args 'org-follow-link-hook)))
10744 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10745 "Offer links in the current entry and return the selected link.
10746 If there is only one link, return it.
10747 If NTH is an integer, return the NTH link found.
10748 If ZERO is a string, check also this string for a link, and if
10749 there is one, return it."
10750 (with-current-buffer buffer
10751 (org-with-wide-buffer
10752 (goto-char marker)
10753 (let ((cnt ?0)
10754 have-zero end links link c)
10755 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10756 (push (match-string 0 zero) links)
10757 (setq cnt (1- cnt) have-zero t))
10758 (save-excursion
10759 (org-back-to-heading t)
10760 (setq end (save-excursion (outline-next-heading) (point)))
10761 (while (re-search-forward org-any-link-re end t)
10762 (push (match-string 0) links))
10763 (setq links (org-uniquify (reverse links))))
10764 (cond
10765 ((null links)
10766 (message "No links"))
10767 ((equal (length links) 1)
10768 (setq link (car links)))
10769 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10770 (setq link (nth (if have-zero nth (1- nth)) links)))
10771 (t ; we have to select a link
10772 (save-excursion
10773 (save-window-excursion
10774 (delete-other-windows)
10775 (with-output-to-temp-buffer "*Select Link*"
10776 (dolist (l links)
10777 (cond
10778 ((not (string-match org-bracket-link-regexp l))
10779 (princ (format "[%c] %s\n" (cl-incf cnt)
10780 (org-unbracket-string "<" ">" l))))
10781 ((match-end 3)
10782 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10783 (match-string 3 l) (match-string 1 l))))
10784 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10785 (match-string 1 l)))))))
10786 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10787 (message "Select link to open, RET to open all:")
10788 (setq c (read-char-exclusive))
10789 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10790 (when (equal c ?q) (user-error "Abort"))
10791 (if (equal c ?\C-m)
10792 (setq link links)
10793 (setq nth (- c ?0))
10794 (when have-zero (setq nth (1+ nth)))
10795 (unless (and (integerp nth) (>= (length links) nth))
10796 (user-error "Invalid link selection"))
10797 (setq link (nth (1- nth) links)))))
10798 (cons link end)))))
10800 ;; TODO: These functions are deprecated since `org-open-at-point'
10801 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10802 (defun org-open-file-with-system (path)
10803 "Open file at PATH using the system way of opening it."
10804 (org-open-file path 'system))
10805 (defun org-open-file-with-emacs (path)
10806 "Open file at PATH in Emacs."
10807 (org-open-file path 'emacs))
10810 ;;; File search
10812 (defvar org-create-file-search-functions nil
10813 "List of functions to construct the right search string for a file link.
10814 These functions are called in turn with point at the location to
10815 which the link should point.
10817 A function in the hook should first test if it would like to
10818 handle this file type, for example by checking the `major-mode'
10819 or the file extension. If it decides not to handle this file, it
10820 should just return nil to give other functions a chance. If it
10821 does handle the file, it must return the search string to be used
10822 when following the link. The search string will be part of the
10823 file link, given after a double colon, and `org-open-at-point'
10824 will automatically search for it. If special measures must be
10825 taken to make the search successful, another function should be
10826 added to the companion hook `org-execute-file-search-functions',
10827 which see.
10829 A function in this hook may also use `setq' to set the variable
10830 `description' to provide a suggestion for the descriptive text to
10831 be used for this link when it gets inserted into an Org buffer
10832 with \\[org-insert-link].")
10834 (defvar org-execute-file-search-functions nil
10835 "List of functions to execute a file search triggered by a link.
10837 Functions added to this hook must accept a single argument, the
10838 search string that was part of the file link, the part after the
10839 double colon. The function must first check if it would like to
10840 handle this search, for example by checking the `major-mode' or
10841 the file extension. If it decides not to handle this search, it
10842 should just return nil to give other functions a chance. If it
10843 does handle the search, it must return a non-nil value to keep
10844 other functions from trying.
10846 Each function can access the current prefix argument through the
10847 variable `current-prefix-arg'. Note that a single prefix is used
10848 to force opening a link in Emacs, so it may be good to only use a
10849 numeric or double prefix to guide the search function.
10851 In case this is needed, a function in this hook can also restore
10852 the window configuration before `org-open-at-point' was called using:
10854 (set-window-configuration org-window-config-before-follow-link)")
10856 (defun org-search-radio-target (target)
10857 "Search a radio target matching TARGET in current buffer.
10858 White spaces are not significant."
10859 (let ((re (format "<<<%s>>>"
10860 (mapconcat #'regexp-quote
10861 (split-string target)
10862 "[ \t]+\\(?:\n[ \t]*\\)?")))
10863 (origin (point)))
10864 (goto-char (point-min))
10865 (catch :radio-match
10866 (while (re-search-forward re nil t)
10867 (backward-char)
10868 (let ((object (org-element-context)))
10869 (when (eq (org-element-type object) 'radio-target)
10870 (goto-char (org-element-property :begin object))
10871 (org-show-context 'link-search)
10872 (throw :radio-match nil))))
10873 (goto-char origin)
10874 (user-error "No match for radio target: %s" target))))
10876 (defun org-link-search (s &optional avoid-pos stealth)
10877 "Search for a search string S.
10879 If S starts with \"#\", it triggers a custom ID search.
10881 If S is enclosed within parenthesis, it initiates a coderef
10882 search.
10884 If S is surrounded by forward slashes, it is interpreted as
10885 a regular expression. In Org mode files, this will create an
10886 `org-occur' sparse tree. In ordinary files, `occur' will be used
10887 to list matches. If the current buffer is in `dired-mode', grep
10888 will be used to search in all files.
10890 When AVOID-POS is given, ignore matches near that position.
10892 When optional argument STEALTH is non-nil, do not modify
10893 visibility around point, thus ignoring `org-show-context-detail'
10894 variable.
10896 Search is case-insensitive and ignores white spaces. Return type
10897 of matched result, which is either `dedicated' or `fuzzy'."
10898 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10899 (let* ((case-fold-search t)
10900 (origin (point))
10901 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10902 (starred (eq (string-to-char normalized) ?*))
10903 (words (split-string (if starred (substring s 1) s)))
10904 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10905 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10906 type)
10907 (cond
10908 ;; Check if there are any special search functions.
10909 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10910 ((eq (string-to-char s) ?#)
10911 ;; Look for a custom ID S if S starts with "#".
10912 (let* ((id (substring normalized 1))
10913 (match (org-find-property "CUSTOM_ID" id)))
10914 (if match (progn (goto-char match) (setf type 'dedicated))
10915 (error "No match for custom ID: %s" id))))
10916 ((string-match "\\`(\\(.*\\))\\'" normalized)
10917 ;; Look for coderef targets if S is enclosed within parenthesis.
10918 (let ((coderef (match-string-no-properties 1 normalized))
10919 (re (substring s-single-re 1 -1)))
10920 (goto-char (point-min))
10921 (catch :coderef-match
10922 (while (re-search-forward re nil t)
10923 (let ((element (org-element-at-point)))
10924 (when (and (memq (org-element-type element)
10925 '(example-block src-block))
10926 ;; Build proper regexp according to current
10927 ;; block's label format.
10928 (let ((label-fmt
10929 (regexp-quote
10930 (or (org-element-property :label-fmt element)
10931 org-coderef-label-format))))
10932 (save-excursion
10933 (beginning-of-line)
10934 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10935 (format label-fmt coderef))))))
10936 (setq type 'dedicated)
10937 (goto-char (match-beginning 1))
10938 (throw :coderef-match nil))))
10939 (goto-char origin)
10940 (error "No match for coderef: %s" coderef))))
10941 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10942 ;; Look for a regular expression.
10943 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10944 (match-string 1 s)))
10945 ;; From here, we handle fuzzy links.
10947 ;; Look for targets, only if not in a headline search.
10948 ((and (not starred)
10949 (let ((target (format "<<%s>>" s-multi-re)))
10950 (catch :target-match
10951 (goto-char (point-min))
10952 (while (re-search-forward target nil t)
10953 (backward-char)
10954 (let ((context (org-element-context)))
10955 (when (eq (org-element-type context) 'target)
10956 (setq type 'dedicated)
10957 (goto-char (org-element-property :begin context))
10958 (throw :target-match t))))
10959 nil))))
10960 ;; Look for elements named after S, only if not in a headline
10961 ;; search.
10962 ((and (not starred)
10963 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10964 (catch :name-match
10965 (goto-char (point-min))
10966 (while (re-search-forward name nil t)
10967 (let ((element (org-element-at-point)))
10968 (when (equal words
10969 (split-string
10970 (org-element-property :name element)))
10971 (setq type 'dedicated)
10972 (beginning-of-line)
10973 (throw :name-match t))))
10974 nil))))
10975 ;; Regular text search. Prefer headlines in Org mode buffers.
10976 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10977 ;; statistics cookies and tags.
10978 ((and (derived-mode-p 'org-mode)
10979 (let ((title-re
10980 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10981 org-outline-regexp-bol
10982 org-comment-string
10983 (mapconcat #'regexp-quote words ".+")))
10984 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10985 (comment-re (eval-when-compile
10986 (format "\\`%s[ \t]+" org-comment-string))))
10987 (goto-char (point-min))
10988 (catch :found
10989 (while (re-search-forward title-re nil t)
10990 (when (equal words
10991 (split-string
10992 (replace-regexp-in-string
10993 cookie-re ""
10994 (replace-regexp-in-string
10995 comment-re "" (org-get-heading t t t)))))
10996 (throw :found t)))
10997 nil)))
10998 (beginning-of-line)
10999 (setq type 'dedicated))
11000 ;; Offer to create non-existent headline depending on
11001 ;; `org-link-search-must-match-exact-headline'.
11002 ((and (derived-mode-p 'org-mode)
11003 (not org-link-search-inhibit-query)
11004 (eq org-link-search-must-match-exact-headline 'query-to-create)
11005 (yes-or-no-p "No match - create this as a new heading? "))
11006 (goto-char (point-max))
11007 (unless (bolp) (newline))
11008 (org-insert-heading nil t t)
11009 (insert s "\n")
11010 (beginning-of-line 0))
11011 ;; Only headlines are looked after. No need to process
11012 ;; further: throw an error.
11013 ((and (derived-mode-p 'org-mode)
11014 (or starred org-link-search-must-match-exact-headline))
11015 (goto-char origin)
11016 (error "No match for fuzzy expression: %s" normalized))
11017 ;; Regular text search.
11018 ((catch :fuzzy-match
11019 (goto-char (point-min))
11020 (while (re-search-forward s-multi-re nil t)
11021 ;; Skip match if it contains AVOID-POS or it is included in
11022 ;; a link with a description but outside the description.
11023 (unless (or (and avoid-pos
11024 (<= (match-beginning 0) avoid-pos)
11025 (> (match-end 0) avoid-pos))
11026 (and (save-match-data
11027 (org-in-regexp org-bracket-link-regexp))
11028 (match-beginning 3)
11029 (or (> (match-beginning 3) (point))
11030 (<= (match-end 3) (point)))
11031 (org-element-lineage
11032 (save-match-data (org-element-context))
11033 '(link) t)))
11034 (goto-char (match-beginning 0))
11035 (setq type 'fuzzy)
11036 (throw :fuzzy-match t)))
11037 nil))
11038 ;; All failed. Throw an error.
11039 (t (goto-char origin)
11040 (error "No match for fuzzy expression: %s" normalized)))
11041 ;; Disclose surroundings of match, if appropriate.
11042 (when (and (derived-mode-p 'org-mode) (not stealth))
11043 (org-show-context 'link-search))
11044 type))
11046 (defun org-get-buffer-for-internal-link (buffer)
11047 "Return a buffer to be used for displaying the link target of internal links."
11048 (cond
11049 ((not org-display-internal-link-with-indirect-buffer)
11050 buffer)
11051 ((string-suffix-p "(Clone)" (buffer-name buffer))
11052 (message "Buffer is already a clone, not making another one")
11053 ;; we also do not modify visibility in this case
11054 buffer)
11055 (t ; make a new indirect buffer for displaying the link
11056 (let* ((bn (buffer-name buffer))
11057 (ibn (concat bn "(Clone)"))
11058 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11059 (with-current-buffer ib (org-overview))
11060 ib))))
11062 (defun org-do-occur (regexp &optional cleanup)
11063 "Call the Emacs command `occur'.
11064 If CLEANUP is non-nil, remove the printout of the regular expression
11065 in the *Occur* buffer. This is useful if the regex is long and not useful
11066 to read."
11067 (occur regexp)
11068 (when cleanup
11069 (let ((cwin (selected-window)) win beg end)
11070 (when (setq win (get-buffer-window "*Occur*"))
11071 (select-window win))
11072 (goto-char (point-min))
11073 (when (re-search-forward "match[a-z]+" nil t)
11074 (setq beg (match-end 0))
11075 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11076 (setq end (1- (match-beginning 0)))))
11077 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11078 (goto-char (point-min))
11079 (select-window cwin))))
11081 ;;; The mark ring for links jumps
11083 (defvar org-mark-ring nil
11084 "Mark ring for positions before jumps in Org mode.")
11085 (defvar org-mark-ring-last-goto nil
11086 "Last position in the mark ring used to go back.")
11087 ;; Fill and close the ring
11088 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11089 (dotimes (_ org-mark-ring-length)
11090 (push (make-marker) org-mark-ring))
11091 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11092 org-mark-ring)
11094 (defun org-mark-ring-push (&optional pos buffer)
11095 "Put the current position or POS into the mark ring and rotate it."
11096 (interactive)
11097 (setq pos (or pos (point)))
11098 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11099 (move-marker (car org-mark-ring)
11100 (or pos (point))
11101 (or buffer (current-buffer)))
11102 (message "%s"
11103 (substitute-command-keys
11104 "Position saved to mark ring, go back with \
11105 `\\[org-mark-ring-goto]'.")))
11107 (defun org-mark-ring-goto (&optional n)
11108 "Jump to the previous position in the mark ring.
11109 With prefix arg N, jump back that many stored positions. When
11110 called several times in succession, walk through the entire ring.
11111 Org mode commands jumping to a different position in the current file,
11112 or to another Org file, automatically push the old position onto the ring."
11113 (interactive "p")
11114 (let (p m)
11115 (if (eq last-command this-command)
11116 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11117 (setq p org-mark-ring))
11118 (setq org-mark-ring-last-goto p)
11119 (setq m (car p))
11120 (pop-to-buffer-same-window (marker-buffer m))
11121 (goto-char m)
11122 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11124 (defun org-add-angle-brackets (s)
11125 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11126 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11129 ;;; Following specific links
11131 (defvar org-agenda-buffer-tmp-name)
11132 (defvar org-agenda-start-on-weekday)
11133 (defun org-follow-timestamp-link ()
11134 "Open an agenda view for the time-stamp date/range at point."
11135 (cond
11136 ((org-at-date-range-p t)
11137 (let ((org-agenda-start-on-weekday)
11138 (t1 (match-string 1))
11139 (t2 (match-string 2)) tt1 tt2)
11140 (setq tt1 (time-to-days (org-time-string-to-time t1))
11141 tt2 (time-to-days (org-time-string-to-time t2)))
11142 (let ((org-agenda-buffer-tmp-name
11143 (format "*Org Agenda(a:%s)"
11144 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11145 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11146 ((org-at-timestamp-p 'lax)
11147 (let ((org-agenda-buffer-tmp-name
11148 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11149 (org-agenda-list nil (time-to-days (org-time-string-to-time
11150 (substring (match-string 1) 0 10)))
11151 1)))
11152 (t (error "This should not happen"))))
11155 ;;; Following file links
11156 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11157 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11158 (declare-function mailcap-mime-info
11159 "mailcap" (string &optional request no-decode))
11160 (defvar org-wait nil)
11161 (defun org-open-file (path &optional in-emacs line search)
11162 "Open the file at PATH.
11163 First, this expands any special file name abbreviations. Then the
11164 configuration variable `org-file-apps' is checked if it contains an
11165 entry for this file type, and if yes, the corresponding command is launched.
11167 If no application is found, Emacs simply visits the file.
11169 With optional prefix argument IN-EMACS, Emacs will visit the file.
11170 With a double \\[universal-argument] \\[universal-argument] \
11171 prefix arg, Org tries to avoid opening in Emacs
11172 and to use an external application to visit the file.
11174 Optional LINE specifies a line to go to, optional SEARCH a string
11175 to search for. If LINE or SEARCH is given, the file will be
11176 opened in Emacs, unless an entry from org-file-apps that makes
11177 use of groups in a regexp matches.
11179 If you want to change the way frames are used when following a
11180 link, please customize `org-link-frame-setup'.
11182 If the file does not exist, an error is thrown."
11183 (let* ((file (if (equal path "")
11184 buffer-file-name
11185 (substitute-in-file-name (expand-file-name path))))
11186 (file-apps (append org-file-apps (org-default-apps)))
11187 (apps (cl-remove-if
11188 'org-file-apps-entry-match-against-dlink-p file-apps))
11189 (apps-dlink (cl-remove-if-not
11190 'org-file-apps-entry-match-against-dlink-p file-apps))
11191 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11192 (dirp (unless remp (file-directory-p file)))
11193 (file (if (and dirp org-open-directory-means-index-dot-org)
11194 (concat (file-name-as-directory file) "index.org")
11195 file))
11196 (a-m-a-p (assq 'auto-mode apps))
11197 (dfile (downcase file))
11198 ;; Reconstruct the original link from the PATH, LINE and
11199 ;; SEARCH args.
11200 (link (cond (line (concat file "::" (number-to-string line)))
11201 (search (concat file "::" search))
11202 (t file)))
11203 (dlink (downcase link))
11204 (ext
11205 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11206 (match-string 1 dfile)))
11207 (save-position-maybe
11208 (let ((old-buffer (current-buffer))
11209 (old-pos (point))
11210 (old-mode major-mode))
11211 (lambda ()
11212 (and (derived-mode-p 'org-mode)
11213 (eq old-mode 'org-mode)
11214 (or (not (eq old-buffer (current-buffer)))
11215 (not (eq old-pos (point))))
11216 (org-mark-ring-push old-pos old-buffer)))))
11217 cmd link-match-data)
11218 (cond
11219 ((member in-emacs '((16) system))
11220 (setq cmd (cdr (assq 'system apps))))
11221 (in-emacs (setq cmd 'emacs))
11223 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11224 (and dirp (cdr (assq 'directory apps)))
11225 ;; First, try matching against apps-dlink if we
11226 ;; get a match here, store the match data for
11227 ;; later.
11228 (let ((match (assoc-default dlink apps-dlink
11229 'string-match)))
11230 (if match
11231 (progn (setq link-match-data (match-data))
11232 match)
11233 (progn (setq in-emacs (or in-emacs line search))
11234 nil))) ; if we have no match in apps-dlink,
11235 ; always open the file in emacs if line or search
11236 ; is given (for backwards compatibility)
11237 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11238 'string-match)
11239 (cdr (assoc ext apps))
11240 (cdr (assq t apps))))))
11241 (when (eq cmd 'system)
11242 (setq cmd (cdr (assq 'system apps))))
11243 (when (eq cmd 'default)
11244 (setq cmd (cdr (assoc t apps))))
11245 (when (eq cmd 'mailcap)
11246 (require 'mailcap)
11247 (mailcap-parse-mailcaps)
11248 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11249 (command (mailcap-mime-info mime-type)))
11250 (if (stringp command)
11251 (setq cmd command)
11252 (setq cmd 'emacs))))
11253 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11254 (not (file-exists-p file))
11255 (not org-open-non-existing-files))
11256 (user-error "No such file: %s" file))
11257 (cond
11258 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11259 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11260 (while (string-match "['\"]%s['\"]" cmd)
11261 (setq cmd (replace-match "%s" t t cmd)))
11262 (setq cmd (replace-regexp-in-string
11263 "%s"
11264 (shell-quote-argument (convert-standard-filename file))
11266 nil t))
11268 ;; Replace "%1", "%2" etc. in command with group matches from regex
11269 (save-match-data
11270 (let ((match-index 1)
11271 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11272 (set-match-data link-match-data)
11273 (while (<= match-index number-of-groups)
11274 (let ((regex (concat "%" (number-to-string match-index)))
11275 (replace-with (match-string match-index dlink)))
11276 (while (string-match regex cmd)
11277 (setq cmd (replace-match replace-with t t cmd))))
11278 (setq match-index (+ match-index 1)))))
11280 (save-window-excursion
11281 (message "Running %s...done" cmd)
11282 (start-process-shell-command cmd nil cmd)
11283 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11284 ((or (stringp cmd)
11285 (eq cmd 'emacs))
11286 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11287 (widen)
11288 (cond (line (org-goto-line line)
11289 (when (derived-mode-p 'org-mode) (org-reveal)))
11290 (search (condition-case err
11291 (org-link-search search)
11292 ;; Save position before error-ing out so user
11293 ;; can easily move back to the original buffer.
11294 (error (funcall save-position-maybe)
11295 (error (nth 1 err)))))))
11296 ((functionp cmd)
11297 (save-match-data
11298 (set-match-data link-match-data)
11299 (condition-case nil
11300 (funcall cmd file link)
11301 ;; FIXME: Remove this check when most default installations
11302 ;; of Emacs have at least Org 9.0.
11303 ((debug wrong-number-of-arguments wrong-type-argument
11304 invalid-function)
11305 (user-error "Please see Org News for version 9.0 about \
11306 `org-file-apps'--Lisp error: %S" cmd)))))
11307 ((consp cmd)
11308 ;; FIXME: Remove this check when most default installations of
11309 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11310 ;; fall back to `org-link-frame-setup' for an old usage of
11311 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11312 (user-error "Please see Org News for version 9.0 about \
11313 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11314 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11315 (funcall save-position-maybe)))
11317 (defun org-file-apps-entry-match-against-dlink-p (entry)
11318 "This function returns non-nil if `entry' uses a regular
11319 expression which should be matched against the whole link by
11320 org-open-file.
11322 It assumes that is the case when the entry uses a regular
11323 expression which has at least one grouping construct and the
11324 action is either a lisp form or a command string containing
11325 `%1', i.e. using at least one subexpression match as a
11326 parameter."
11327 (let ((selector (car entry))
11328 (action (cdr entry)))
11329 (if (stringp selector)
11330 (and (> (regexp-opt-depth selector) 0)
11331 (or (and (stringp action)
11332 (string-match "%[0-9]" action))
11333 (consp action)))
11334 nil)))
11336 (defun org-default-apps ()
11337 "Return the default applications for this operating system."
11338 (cond
11339 ((eq system-type 'darwin)
11340 org-file-apps-defaults-macosx)
11341 ((eq system-type 'windows-nt)
11342 org-file-apps-defaults-windowsnt)
11343 (t org-file-apps-defaults-gnu)))
11345 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11346 "Convert extensions to regular expressions in the cars of LIST.
11347 Also, weed out any non-string entries, because the return value is used
11348 only for regexp matching.
11349 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11350 point to the symbol `emacs', indicating that the file should
11351 be opened in Emacs."
11352 (append
11353 (delq nil
11354 (mapcar (lambda (x)
11355 (unless (not (stringp (car x)))
11356 (if (string-match "\\W" (car x))
11358 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11359 list))
11360 (when add-auto-mode
11361 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11363 (defvar ange-ftp-name-format)
11364 (defun org-file-remote-p (file)
11365 "Test whether FILE specifies a location on a remote system.
11366 Return non-nil if the location is indeed remote.
11368 For example, the filename \"/user@host:/foo\" specifies a location
11369 on the system \"/user@host:\"."
11370 (cond ((fboundp 'file-remote-p)
11371 (file-remote-p file))
11372 ((fboundp 'tramp-handle-file-remote-p)
11373 (tramp-handle-file-remote-p file))
11374 ((and (boundp 'ange-ftp-name-format)
11375 (string-match (car ange-ftp-name-format) file))
11376 t)))
11379 ;;;; Refiling
11381 (defun org-get-org-file ()
11382 "Read a filename, with default directory `org-directory'."
11383 (let ((default (or org-default-notes-file remember-data-file)))
11384 (read-file-name (format "File name [%s]: " default)
11385 (file-name-as-directory org-directory)
11386 default)))
11388 (defun org-notes-order-reversed-p ()
11389 "Check if the current file should receive notes in reversed order."
11390 (cond
11391 ((not org-reverse-note-order) nil)
11392 ((eq t org-reverse-note-order) t)
11393 ((not (listp org-reverse-note-order)) nil)
11394 (t (catch 'exit
11395 (dolist (entry org-reverse-note-order)
11396 (when (string-match (car entry) buffer-file-name)
11397 (throw 'exit (cdr entry))))))))
11399 (defvar org-refile-target-table nil
11400 "The list of refile targets, created by `org-refile'.")
11402 (defvar org-agenda-new-buffers nil
11403 "Buffers created to visit agenda files.")
11405 (defvar org-refile-cache nil
11406 "Cache for refile targets.")
11408 (defvar org-refile-markers nil
11409 "All the markers used for caching refile locations.")
11411 (defun org-refile-marker (pos)
11412 "Get a new refile marker, but only if caching is in use."
11413 (if (not org-refile-use-cache)
11415 (let ((m (make-marker)))
11416 (move-marker m pos)
11417 (push m org-refile-markers)
11418 m)))
11420 (defun org-refile-cache-clear ()
11421 "Clear the refile cache and disable all the markers."
11422 (dolist (m org-refile-markers) (move-marker m nil))
11423 (setq org-refile-markers nil)
11424 (setq org-refile-cache nil)
11425 (message "Refile cache has been cleared"))
11427 (defun org-refile-cache-check-set (set)
11428 "Check if all the markers in the cache still have live buffers."
11429 (let (marker)
11430 (catch 'exit
11431 (while (and set (setq marker (nth 3 (pop set))))
11432 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11433 (when (and marker (null (marker-buffer marker)))
11434 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11435 (sit-for 3)
11436 (throw 'exit nil)))
11437 t)))
11439 (defun org-refile-cache-put (set &rest identifiers)
11440 "Push the refile targets SET into the cache, under IDENTIFIERS."
11441 (let* ((key (sha1 (prin1-to-string identifiers)))
11442 (entry (assoc key org-refile-cache)))
11443 (if entry
11444 (setcdr entry set)
11445 (push (cons key set) org-refile-cache))))
11447 (defun org-refile-cache-get (&rest identifiers)
11448 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11449 (cond
11450 ((not org-refile-cache) nil)
11451 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11453 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11454 org-refile-cache))))
11455 (and set (org-refile-cache-check-set set) set)))))
11457 (defvar org-outline-path-cache nil
11458 "Alist between buffer positions and outline paths.
11459 It value is an alist (POSITION . PATH) where POSITION is the
11460 buffer position at the beginning of an entry and PATH is a list
11461 of strings describing the outline path for that entry, in reverse
11462 order.")
11464 (defun org-refile-get-targets (&optional default-buffer)
11465 "Produce a table with refile targets."
11466 (let ((case-fold-search nil)
11467 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11468 (entries (or org-refile-targets '((nil . (:level . 1)))))
11469 targets tgs files desc descre)
11470 (message "Getting targets...")
11471 (with-current-buffer (or default-buffer (current-buffer))
11472 (dolist (entry entries)
11473 (setq files (car entry) desc (cdr entry))
11474 (cond
11475 ((null files) (setq files (list (current-buffer))))
11476 ((eq files 'org-agenda-files)
11477 (setq files (org-agenda-files 'unrestricted)))
11478 ((and (symbolp files) (fboundp files))
11479 (setq files (funcall files)))
11480 ((and (symbolp files) (boundp files))
11481 (setq files (symbol-value files))))
11482 (when (stringp files) (setq files (list files)))
11483 (cond
11484 ((eq (car desc) :tag)
11485 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11486 ((eq (car desc) :todo)
11487 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11488 ((eq (car desc) :regexp)
11489 (setq descre (cdr desc)))
11490 ((eq (car desc) :level)
11491 (setq descre (concat "^\\*\\{" (number-to-string
11492 (if org-odd-levels-only
11493 (1- (* 2 (cdr desc)))
11494 (cdr desc)))
11495 "\\}[ \t]")))
11496 ((eq (car desc) :maxlevel)
11497 (setq descre (concat "^\\*\\{1," (number-to-string
11498 (if org-odd-levels-only
11499 (1- (* 2 (cdr desc)))
11500 (cdr desc)))
11501 "\\}[ \t]")))
11502 (t (error "Bad refiling target description %s" desc)))
11503 (dolist (f files)
11504 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11506 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11507 (progn
11508 (when (bufferp f)
11509 (setq f (buffer-file-name (buffer-base-buffer f))))
11510 (setq f (and f (expand-file-name f)))
11511 (when (eq org-refile-use-outline-path 'file)
11512 (push (list (file-name-nondirectory f) f nil nil) tgs))
11513 (when (eq org-refile-use-outline-path 'buffer-name)
11514 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11515 (when (eq org-refile-use-outline-path 'full-file-path)
11516 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11517 (org-with-wide-buffer
11518 (goto-char (point-min))
11519 (setq org-outline-path-cache nil)
11520 (while (re-search-forward descre nil t)
11521 (beginning-of-line)
11522 (let ((case-fold-search nil))
11523 (looking-at org-complex-heading-regexp))
11524 (let ((begin (point))
11525 (heading (match-string-no-properties 4)))
11526 (unless (or (and
11527 org-refile-target-verify-function
11528 (not
11529 (funcall org-refile-target-verify-function)))
11530 (not heading))
11531 (let ((re (format org-complex-heading-regexp-format
11532 (regexp-quote heading)))
11533 (target
11534 (if (not org-refile-use-outline-path) heading
11535 (mapconcat
11536 #'identity
11537 (append
11538 (pcase org-refile-use-outline-path
11539 (`file (list (file-name-nondirectory
11540 (buffer-file-name
11541 (buffer-base-buffer)))))
11542 (`full-file-path
11543 (list (buffer-file-name
11544 (buffer-base-buffer))))
11545 (`buffer-name
11546 (list (buffer-name
11547 (buffer-base-buffer))))
11548 (_ nil))
11549 (mapcar (lambda (s) (replace-regexp-in-string
11550 "/" "\\/" s nil t))
11551 (org-get-outline-path t t)))
11552 "/"))))
11553 (push (list target f re (org-refile-marker (point)))
11554 tgs)))
11555 (when (= (point) begin)
11556 ;; Verification function has not moved point.
11557 (end-of-line)))))))
11558 (when org-refile-use-cache
11559 (org-refile-cache-put tgs (buffer-file-name) descre))
11560 (setq targets (append tgs targets))))))
11561 (message "Getting targets...done")
11562 (delete-dups (nreverse targets))))
11564 (defun org--get-outline-path-1 (&optional use-cache)
11565 "Return outline path to current headline.
11567 Outline path is a list of strings, in reverse order. When
11568 optional argument USE-CACHE is non-nil, make use of a cache. See
11569 `org-get-outline-path' for details.
11571 Assume buffer is widened and point is on a headline."
11572 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11573 (let ((p (point))
11574 (heading (let ((case-fold-search nil))
11575 (looking-at org-complex-heading-regexp)
11576 (if (not (match-end 4)) ""
11577 ;; Remove statistics cookies.
11578 (org-trim
11579 (org-link-display-format
11580 (replace-regexp-in-string
11581 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11582 (match-string-no-properties 4))))))))
11583 (if (org-up-heading-safe)
11584 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11585 (when use-cache
11586 (push (cons p path) org-outline-path-cache))
11587 path)
11588 ;; This is a new root node. Since we assume we are moving
11589 ;; forward, we can drop previous cache so as to limit number
11590 ;; of associations there.
11591 (let ((path (list heading)))
11592 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11593 path)))))
11595 (defun org-get-outline-path (&optional with-self use-cache)
11596 "Return the outline path to the current entry.
11598 An outline path is a list of ancestors for current headline, as
11599 a list of strings. Statistics cookies are removed and links are
11600 replaced with their description, if any, or their path otherwise.
11602 When optional argument WITH-SELF is non-nil, the path also
11603 includes the current headline.
11605 When optional argument USE-CACHE is non-nil, cache outline paths
11606 between calls to this function so as to avoid backtracking. This
11607 argument is useful when planning to find more than one outline
11608 path in the same document. In that case, there are two
11609 conditions to satisfy:
11610 - `org-outline-path-cache' is set to nil before starting the
11611 process;
11612 - outline paths are computed by increasing buffer positions."
11613 (org-with-wide-buffer
11614 (and (or (and with-self (org-back-to-heading t))
11615 (org-up-heading-safe))
11616 (reverse (org--get-outline-path-1 use-cache)))))
11618 (defun org-format-outline-path (path &optional width prefix separator)
11619 "Format the outline path PATH for display.
11620 WIDTH is the maximum number of characters that is available.
11621 PREFIX is a prefix to be included in the returned string,
11622 such as the file name.
11623 SEPARATOR is inserted between the different parts of the path,
11624 the default is \"/\"."
11625 (setq width (or width 79))
11626 (setq path (delq nil path))
11627 (unless (> width 0)
11628 (user-error "Argument `width' must be positive"))
11629 (setq separator (or separator "/"))
11630 (let* ((org-odd-levels-only nil)
11631 (fpath (concat
11632 prefix (and prefix path separator)
11633 (mapconcat
11634 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11635 (cl-loop for head in path
11636 for n from 0
11637 collect (org-add-props
11638 head nil 'face
11639 (nth (% n org-n-level-faces) org-level-faces)))
11640 separator))))
11641 (when (> (length fpath) width)
11642 (if (< width 7)
11643 ;; It's unlikely that `width' will be this small, but don't
11644 ;; waste characters by adding ".." if it is.
11645 (setq fpath (substring fpath 0 width))
11646 (setf (substring fpath (- width 2)) "..")))
11647 fpath))
11649 (defun org-display-outline-path (&optional file current separator just-return-string)
11650 "Display the current outline path in the echo area.
11652 If FILE is non-nil, prepend the output with the file name.
11653 If CURRENT is non-nil, append the current heading to the output.
11654 SEPARATOR is passed through to `org-format-outline-path'. It separates
11655 the different parts of the path and defaults to \"/\".
11656 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11657 (interactive "P")
11658 (let* (case-fold-search
11659 (bfn (buffer-file-name (buffer-base-buffer)))
11660 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11661 res)
11662 (when current (setq path (append path
11663 (save-excursion
11664 (org-back-to-heading t)
11665 (when (looking-at org-complex-heading-regexp)
11666 (list (match-string 4)))))))
11667 (setq res
11668 (org-format-outline-path
11669 path
11670 (1- (frame-width))
11671 (and file bfn (concat (file-name-nondirectory bfn) separator))
11672 separator))
11673 (if just-return-string
11674 (org-no-properties res)
11675 (org-unlogged-message "%s" res))))
11677 (defvar org-refile-history nil
11678 "History for refiling operations.")
11680 (defvar org-after-refile-insert-hook nil
11681 "Hook run after `org-refile' has inserted its stuff at the new location.
11682 Note that this is still *before* the stuff will be removed from
11683 the *old* location.")
11685 (defvar org-capture-last-stored-marker)
11686 (defvar org-refile-keep nil
11687 "Non-nil means `org-refile' will copy instead of refile.")
11689 (defun org-copy ()
11690 "Like `org-refile', but copy."
11691 (interactive)
11692 (let ((org-refile-keep t))
11693 (funcall 'org-refile nil nil nil "Copy")))
11695 (defun org-refile (&optional arg default-buffer rfloc msg)
11696 "Move the entry or entries at point to another heading.
11698 The list of target headings is compiled using the information in
11699 `org-refile-targets', which see.
11701 At the target location, the entry is filed as a subitem of the
11702 target heading. Depending on `org-reverse-note-order', the new
11703 subitem will either be the first or the last subitem.
11705 If there is an active region, all entries in that region will be
11706 refiled. However, the region must fulfill the requirement that
11707 the first heading sets the top-level of the moved text.
11709 With a `\\[universal-argument]' ARG, the command will only visit the target \
11710 location
11711 and not actually move anything.
11713 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11714 location where the last
11715 refiling operation has put the subtree.
11717 With a numeric prefix argument of `2', refile to the running clock.
11719 With a numeric prefix argument of `3', emulate `org-refile-keep'
11720 being set to t and copy to the target location, don't move it.
11721 Beware that keeping refiled entries may result in duplicated ID
11722 properties.
11724 RFLOC can be a refile location obtained in a different way.
11726 MSG is a string to replace \"Refile\" in the default prompt with
11727 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11729 See also `org-refile-use-outline-path'.
11731 If you are using target caching (see `org-refile-use-cache'), you
11732 have to clear the target cache in order to find new targets.
11733 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11734 prefix argument (`C-u C-u C-u C-c C-w')."
11735 (interactive "P")
11736 (if (member arg '(0 (64)))
11737 (org-refile-cache-clear)
11738 (let* ((actionmsg (cond (msg msg)
11739 ((equal arg 3) "Refile (and keep)")
11740 (t "Refile")))
11741 (regionp (org-region-active-p))
11742 (region-start (and regionp (region-beginning)))
11743 (region-end (and regionp (region-end)))
11744 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11745 pos it nbuf file level reversed)
11746 (setq last-command nil)
11747 (when regionp
11748 (goto-char region-start)
11749 (or (bolp) (goto-char (point-at-bol)))
11750 (setq region-start (point))
11751 (unless (or (org-kill-is-subtree-p
11752 (buffer-substring region-start region-end))
11753 (prog1 org-refile-active-region-within-subtree
11754 (let ((s (point-at-eol)))
11755 (org-toggle-heading)
11756 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11757 (user-error "The region is not a (sequence of) subtree(s)")))
11758 (if (equal arg '(16))
11759 (org-refile-goto-last-stored)
11760 (when (or
11761 (and (equal arg 2)
11762 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11763 (prog1
11764 (setq it (list (or org-clock-heading "running clock")
11765 (buffer-file-name
11766 (marker-buffer org-clock-hd-marker))
11768 (marker-position org-clock-hd-marker)))
11769 (setq arg nil)))
11770 (setq it
11771 (or rfloc
11772 (let (heading-text)
11773 (save-excursion
11774 (unless (and arg (listp arg))
11775 (org-back-to-heading t)
11776 (setq heading-text
11777 (replace-regexp-in-string
11778 org-bracket-link-regexp
11779 "\\3"
11780 (or (nth 4 (org-heading-components))
11781 ""))))
11782 (org-refile-get-location
11783 (cond ((and arg (listp arg)) "Goto")
11784 (regionp (concat actionmsg " region to"))
11785 (t (concat actionmsg " subtree \""
11786 heading-text "\" to")))
11787 default-buffer
11788 (and (not (equal '(4) arg))
11789 org-refile-allow-creating-parent-nodes)))))))
11790 (setq file (nth 1 it)
11791 pos (nth 3 it))
11792 (when (and (not arg)
11794 (equal (buffer-file-name) file)
11795 (if regionp
11796 (and (>= pos region-start)
11797 (<= pos region-end))
11798 (and (>= pos (point))
11799 (< pos (save-excursion
11800 (org-end-of-subtree t t))))))
11801 (error "Cannot refile to position inside the tree or region"))
11802 (setq nbuf (or (find-buffer-visiting file)
11803 (find-file-noselect file)))
11804 (if (and arg (not (equal arg 3)))
11805 (progn
11806 (pop-to-buffer-same-window nbuf)
11807 (goto-char (cond (pos)
11808 ((org-notes-order-reversed-p) (point-min))
11809 (t (point-max))))
11810 (org-show-context 'org-goto))
11811 (if regionp
11812 (progn
11813 (org-kill-new (buffer-substring region-start region-end))
11814 (org-save-markers-in-region region-start region-end))
11815 (org-copy-subtree 1 nil t))
11816 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11817 (find-file-noselect file)))
11818 (setq reversed (org-notes-order-reversed-p))
11819 (org-with-wide-buffer
11820 (if pos
11821 (progn
11822 (goto-char pos)
11823 (setq level (org-get-valid-level (funcall outline-level) 1))
11824 (goto-char
11825 (if reversed
11826 (or (outline-next-heading) (point-max))
11827 (or (save-excursion (org-get-next-sibling))
11828 (org-end-of-subtree t t)
11829 (point-max)))))
11830 (setq level 1)
11831 (if (not reversed)
11832 (goto-char (point-max))
11833 (goto-char (point-min))
11834 (or (outline-next-heading) (goto-char (point-max)))))
11835 (unless (bolp) (newline))
11836 (org-paste-subtree level nil nil t)
11837 (when org-log-refile
11838 (org-add-log-setup 'refile nil nil org-log-refile)
11839 (unless (eq org-log-refile 'note)
11840 (save-excursion (org-add-log-note))))
11841 (and org-auto-align-tags
11842 (let ((org-loop-over-headlines-in-active-region nil))
11843 (org-set-tags nil t)))
11844 (let ((bookmark-name (plist-get org-bookmark-names-plist
11845 :last-refile)))
11846 (when bookmark-name
11847 (with-demoted-errors
11848 (bookmark-set bookmark-name))))
11849 ;; If we are refiling for capture, make sure that the
11850 ;; last-capture pointers point here
11851 (when (bound-and-true-p org-capture-is-refiling)
11852 (let ((bookmark-name (plist-get org-bookmark-names-plist
11853 :last-capture-marker)))
11854 (when bookmark-name
11855 (with-demoted-errors
11856 (bookmark-set bookmark-name))))
11857 (move-marker org-capture-last-stored-marker (point)))
11858 (when (fboundp 'deactivate-mark) (deactivate-mark))
11859 (run-hooks 'org-after-refile-insert-hook)))
11860 (unless org-refile-keep
11861 (if regionp
11862 (delete-region (point) (+ (point) (- region-end region-start)))
11863 (delete-region
11864 (and (org-back-to-heading t) (point))
11865 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11866 (when (featurep 'org-inlinetask)
11867 (org-inlinetask-remove-END-maybe))
11868 (setq org-markers-to-move nil)
11869 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11871 (defun org-refile-goto-last-stored ()
11872 "Go to the location where the last refile was stored."
11873 (interactive)
11874 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11875 (message "This is the location of the last refile"))
11877 (defun org-refile--get-location (refloc tbl)
11878 "When user refile to REFLOC, find the associated target in TBL.
11879 Also check `org-refile-target-table'."
11880 (car (delq
11882 (mapcar
11883 (lambda (r) (or (assoc r tbl)
11884 (assoc r org-refile-target-table)))
11885 (list (replace-regexp-in-string "/$" "" refloc)
11886 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11888 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11889 "Prompt the user for a refile location, using PROMPT.
11890 PROMPT should not be suffixed with a colon and a space, because
11891 this function appends the default value from
11892 `org-refile-history' automatically, if that is not empty."
11893 (let ((org-refile-targets org-refile-targets)
11894 (org-refile-use-outline-path org-refile-use-outline-path))
11895 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11896 (unless org-refile-target-table
11897 (user-error "No refile targets"))
11898 (let* ((cbuf (current-buffer))
11899 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11900 (cfunc (if (and org-refile-use-outline-path
11901 org-outline-path-complete-in-steps)
11902 #'org-olpath-completing-read
11903 #'completing-read))
11904 (extra (if org-refile-use-outline-path "/" ""))
11905 (cbnex (concat (buffer-name) extra))
11906 (filename (and cfn (expand-file-name cfn)))
11907 (tbl (mapcar
11908 (lambda (x)
11909 (if (and (not (member org-refile-use-outline-path
11910 '(file full-file-path)))
11911 (not (equal filename (nth 1 x))))
11912 (cons (concat (car x) extra " ("
11913 (file-name-nondirectory (nth 1 x)) ")")
11914 (cdr x))
11915 (cons (concat (car x) extra) (cdr x))))
11916 org-refile-target-table))
11917 (completion-ignore-case t)
11918 cdef
11919 (prompt (concat prompt
11920 (or (and (car org-refile-history)
11921 (concat " (default " (car org-refile-history) ")"))
11922 (and (assoc cbnex tbl) (setq cdef cbnex)
11923 (concat " (default " cbnex ")"))) ": "))
11924 pa answ parent-target child parent old-hist)
11925 (setq old-hist org-refile-history)
11926 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11927 nil 'org-refile-history (or cdef (car org-refile-history))))
11928 (if (setq pa (org-refile--get-location answ tbl))
11929 (progn
11930 (org-refile-check-position pa)
11931 (when (or (not org-refile-history)
11932 (not (eq old-hist org-refile-history))
11933 (not (equal (car pa) (car org-refile-history))))
11934 (setq org-refile-history
11935 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11936 org-refile-history
11937 (cdr org-refile-history))))
11938 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11939 (pop org-refile-history)))
11941 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11942 (progn
11943 (setq parent (match-string 1 answ)
11944 child (match-string 2 answ))
11945 (setq parent-target (org-refile--get-location parent tbl))
11946 (when (and parent-target
11947 (or (eq new-nodes t)
11948 (and (eq new-nodes 'confirm)
11949 (y-or-n-p (format "Create new node \"%s\"? "
11950 child)))))
11951 (org-refile-new-child parent-target child)))
11952 (user-error "Invalid target location")))))
11954 (declare-function org-string-nw-p "org-macs" (s))
11955 (defun org-refile-check-position (refile-pointer)
11956 "Check if the refile pointer matches the headline to which it points."
11957 (let* ((file (nth 1 refile-pointer))
11958 (re (nth 2 refile-pointer))
11959 (pos (nth 3 refile-pointer))
11960 buffer)
11961 (if (and (not (markerp pos)) (not file))
11962 (user-error "Please indicate a target file in the refile path")
11963 (when (org-string-nw-p re)
11964 (setq buffer (if (markerp pos)
11965 (marker-buffer pos)
11966 (or (find-buffer-visiting file)
11967 (find-file-noselect file))))
11968 (with-current-buffer buffer
11969 (org-with-wide-buffer
11970 (goto-char pos)
11971 (beginning-of-line 1)
11972 (unless (looking-at-p re)
11973 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11975 (defun org-refile-new-child (parent-target child)
11976 "Use refile target PARENT-TARGET to add new CHILD below it."
11977 (unless parent-target
11978 (error "Cannot find parent for new node"))
11979 (let ((file (nth 1 parent-target))
11980 (pos (nth 3 parent-target))
11981 level)
11982 (with-current-buffer (or (find-buffer-visiting file)
11983 (find-file-noselect file))
11984 (org-with-wide-buffer
11985 (if pos
11986 (goto-char pos)
11987 (goto-char (point-max))
11988 (unless (bolp) (newline)))
11989 (when (looking-at org-outline-regexp)
11990 (setq level (funcall outline-level))
11991 (org-end-of-subtree t t))
11992 (org-back-over-empty-lines)
11993 (insert "\n" (make-string
11994 (if pos (org-get-valid-level level 1) 1) ?*)
11995 " " child "\n")
11996 (beginning-of-line 0)
11997 (list (concat (car parent-target) "/" child) file "" (point))))))
11999 (defun org-olpath-completing-read (prompt collection &rest args)
12000 "Read an outline path like a file name."
12001 (let ((thetable collection))
12002 (apply #'completing-read
12003 prompt
12004 (lambda (string predicate &optional flag)
12005 (cond
12006 ((eq flag nil) (try-completion string thetable))
12007 ((eq flag t)
12008 (let ((l (length string)))
12009 (mapcar (lambda (x)
12010 (let ((r (substring x l))
12011 (f (if (string-match " ([^)]*)$" x)
12012 (match-string 0 x)
12013 "")))
12014 (if (string-match "/" r)
12015 (concat string (substring r 0 (match-end 0)) f)
12016 x)))
12017 (all-completions string thetable predicate))))
12018 ;; Exact match?
12019 ((eq flag 'lambda) (assoc string thetable))))
12020 args)))
12022 ;;;; Dynamic blocks
12024 (defun org-find-dblock (name)
12025 "Find the first dynamic block with name NAME in the buffer.
12026 If not found, stay at current position and return nil."
12027 (let ((case-fold-search t) pos)
12028 (save-excursion
12029 (goto-char (point-min))
12030 (setq pos (and (re-search-forward
12031 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12032 (match-beginning 0))))
12033 (when pos (goto-char pos))
12034 pos))
12036 (defun org-create-dblock (plist)
12037 "Create a dynamic block section, with parameters taken from PLIST.
12038 PLIST must contain a :name entry which is used as the name of the block."
12039 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12040 (end-of-line 1)
12041 (newline))
12042 (let ((col (current-column))
12043 (name (plist-get plist :name)))
12044 (insert "#+BEGIN: " name)
12045 (while plist
12046 (if (eq (car plist) :name)
12047 (setq plist (cddr plist))
12048 (insert " " (prin1-to-string (pop plist)))))
12049 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12050 (beginning-of-line -2)))
12052 (defun org-prepare-dblock ()
12053 "Prepare dynamic block for refresh.
12054 This empties the block, puts the cursor at the insert position and returns
12055 the property list including an extra property :name with the block name."
12056 (unless (looking-at org-dblock-start-re)
12057 (user-error "Not at a dynamic block"))
12058 (let* ((begdel (1+ (match-end 0)))
12059 (name (org-no-properties (match-string 1)))
12060 (params (append (list :name name)
12061 (read (concat "(" (match-string 3) ")")))))
12062 (save-excursion
12063 (beginning-of-line 1)
12064 (skip-chars-forward " \t")
12065 (setq params (plist-put params :indentation-column (current-column))))
12066 (unless (re-search-forward org-dblock-end-re nil t)
12067 (error "Dynamic block not terminated"))
12068 (setq params
12069 (append params
12070 (list :content (buffer-substring
12071 begdel (match-beginning 0)))))
12072 (delete-region begdel (match-beginning 0))
12073 (goto-char begdel)
12074 (open-line 1)
12075 params))
12077 (defun org-map-dblocks (&optional command)
12078 "Apply COMMAND to all dynamic blocks in the current buffer.
12079 If COMMAND is not given, use `org-update-dblock'."
12080 (let ((cmd (or command 'org-update-dblock)))
12081 (save-excursion
12082 (goto-char (point-min))
12083 (while (re-search-forward org-dblock-start-re nil t)
12084 (goto-char (match-beginning 0))
12085 (save-excursion
12086 (condition-case nil
12087 (funcall cmd)
12088 (error (message "Error during update of dynamic block"))))
12089 (unless (re-search-forward org-dblock-end-re nil t)
12090 (error "Dynamic block not terminated"))))))
12092 (defun org-dblock-update (&optional arg)
12093 "User command for updating dynamic blocks.
12094 Update the dynamic block at point. With prefix ARG, update all dynamic
12095 blocks in the buffer."
12096 (interactive "P")
12097 (if arg
12098 (org-update-all-dblocks)
12099 (or (looking-at org-dblock-start-re)
12100 (org-beginning-of-dblock))
12101 (org-update-dblock)))
12103 (defun org-update-dblock ()
12104 "Update the dynamic block at point.
12105 This means to empty the block, parse for parameters and then call
12106 the correct writing function."
12107 (interactive)
12108 (save-excursion
12109 (let* ((win (selected-window))
12110 (pos (point))
12111 (line (org-current-line))
12112 (params (org-prepare-dblock))
12113 (name (plist-get params :name))
12114 (indent (plist-get params :indentation-column))
12115 (cmd (intern (concat "org-dblock-write:" name))))
12116 (message "Updating dynamic block `%s' at line %d..." name line)
12117 (funcall cmd params)
12118 (message "Updating dynamic block `%s' at line %d...done" name line)
12119 (goto-char pos)
12120 (when (and indent (> indent 0))
12121 (setq indent (make-string indent ?\ ))
12122 (save-excursion
12123 (select-window win)
12124 (org-beginning-of-dblock)
12125 (forward-line 1)
12126 (while (not (looking-at org-dblock-end-re))
12127 (insert indent)
12128 (beginning-of-line 2))
12129 (when (looking-at org-dblock-end-re)
12130 (and (looking-at "[ \t]+")
12131 (replace-match ""))
12132 (insert indent)))))))
12134 (defun org-beginning-of-dblock ()
12135 "Find the beginning of the dynamic block at point.
12136 Error if there is no such block at point."
12137 (let ((pos (point))
12138 beg)
12139 (end-of-line 1)
12140 (if (and (re-search-backward org-dblock-start-re nil t)
12141 (setq beg (match-beginning 0))
12142 (re-search-forward org-dblock-end-re nil t)
12143 (> (match-end 0) pos))
12144 (goto-char beg)
12145 (goto-char pos)
12146 (error "Not in a dynamic block"))))
12148 (defun org-update-all-dblocks ()
12149 "Update all dynamic blocks in the buffer.
12150 This function can be used in a hook."
12151 (interactive)
12152 (when (derived-mode-p 'org-mode)
12153 (org-map-dblocks 'org-update-dblock)))
12156 ;;;; Completion
12158 (declare-function org-export-backend-options "ox" (cl-x) t)
12159 (defun org-get-export-keywords ()
12160 "Return a list of all currently understood export keywords.
12161 Export keywords include options, block names, attributes and
12162 keywords relative to each registered export back-end."
12163 (let (keywords)
12164 (dolist (backend
12165 (bound-and-true-p org-export-registered-backends)
12166 (delq nil keywords))
12167 ;; Back-end name (for keywords, like #+LATEX:)
12168 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12169 (dolist (option-entry (org-export-backend-options backend))
12170 ;; Back-end options.
12171 (push (nth 1 option-entry) keywords)))))
12173 (defconst org-options-keywords
12174 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12175 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12176 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12177 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12178 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12180 (defcustom org-structure-template-alist
12181 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12182 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12183 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12184 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12185 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12186 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12187 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12188 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12189 ("L" "#+LaTeX: ")
12190 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12191 ("H" "#+HTML: ")
12192 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12193 ("A" "#+ASCII: ")
12194 ("i" "#+INDEX: ?")
12195 ("I" "#+INCLUDE: %file ?"))
12196 "Structure completion elements.
12197 This is a list of abbreviation keys and values. The value gets inserted
12198 if you type `<' followed by the key and then press the completion key,
12199 usually `TAB'. %file will be replaced by a file name after prompting
12200 for the file using completion. The cursor will be placed at the position
12201 of the `?' in the template.
12202 There are two templates for each key, the first uses the original Org syntax,
12203 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12204 the default when the /org-mtags.el/ module has been loaded. See also the
12205 variable `org-mtags-prefer-muse-templates'."
12206 :group 'org-edit-structure
12207 :type '(repeat
12208 (list
12209 (string :tag "Key")
12210 (string :tag "Template")))
12211 :version "26.1"
12212 :package-version '(Org . "8.3"))
12214 (defun org-try-structure-completion ()
12215 "Try to complete a structure template before point.
12216 This looks for strings like \"<e\" on an otherwise empty line and
12217 expands them."
12218 (let ((l (buffer-substring (point-at-bol) (point)))
12220 (when (and (looking-at "[ \t]*$")
12221 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12222 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12223 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12224 (match-beginning 1)) a)
12225 t)))
12227 (defun org-complete-expand-structure-template (start cell)
12228 "Expand a structure template."
12229 (let ((rpl (nth 1 cell))
12230 (ind ""))
12231 (delete-region start (point))
12232 (when (string-match "\\`[ \t]*#\\+" rpl)
12233 (cond
12234 ((bolp))
12235 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12236 (setq ind (buffer-substring (point-at-bol) (point))))
12237 (t (newline))))
12238 (setq start (point))
12239 (when (string-match "%file" rpl)
12240 (setq rpl (replace-match
12241 (concat
12242 "\""
12243 (save-match-data
12244 (abbreviate-file-name (read-file-name "Include file: ")))
12245 "\"")
12246 t t rpl)))
12247 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12248 (concat "\n" ind)))
12249 (insert rpl)
12250 (when (re-search-backward "\\?" start t) (delete-char 1))))
12252 ;;;; TODO, DEADLINE, Comments
12254 (defun org-toggle-comment ()
12255 "Change the COMMENT state of an entry."
12256 (interactive)
12257 (save-excursion
12258 (org-back-to-heading)
12259 (let ((case-fold-search nil))
12260 (looking-at org-complex-heading-regexp))
12261 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12262 (skip-chars-forward " \t")
12263 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12264 (if (org-in-commented-heading-p t)
12265 (delete-region (point)
12266 (progn (search-forward " " (line-end-position) 'move)
12267 (skip-chars-forward " \t")
12268 (point)))
12269 (insert org-comment-string)
12270 (unless (eolp) (insert " ")))))
12272 (defvar org-last-todo-state-is-todo nil
12273 "This is non-nil when the last TODO state change led to a TODO state.
12274 If the last change removed the TODO tag or switched to DONE, then
12275 this is nil.")
12277 (defvar org-setting-tags nil) ; dynamically skipped
12279 (defvar org-todo-setup-filter-hook nil
12280 "Hook for functions that pre-filter todo specs.
12281 Each function takes a todo spec and returns either nil or the spec
12282 transformed into canonical form." )
12284 (defvar org-todo-get-default-hook nil
12285 "Hook for functions that get a default item for todo.
12286 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12287 nil or a string to be used for the todo mark." )
12289 (defvar org-agenda-headline-snapshot-before-repeat)
12291 (defun org-current-effective-time ()
12292 "Return current time adjusted for `org-extend-today-until' variable."
12293 (let* ((ct (org-current-time))
12294 (dct (decode-time ct))
12295 (ct1
12296 (cond
12297 (org-use-last-clock-out-time-as-effective-time
12298 (or (org-clock-get-last-clock-out-time) ct))
12299 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12300 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12301 (t ct))))
12302 ct1))
12304 (defun org-todo-yesterday (&optional arg)
12305 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12306 (interactive "P")
12307 (if (eq major-mode 'org-agenda-mode)
12308 (apply 'org-agenda-todo-yesterday arg)
12309 (let* ((org-use-effective-time t)
12310 (hour (nth 2 (decode-time (org-current-time))))
12311 (org-extend-today-until (1+ hour)))
12312 (org-todo arg))))
12314 (defvar org-block-entry-blocking ""
12315 "First entry preventing the TODO state change.")
12317 (defun org-cancel-repeater ()
12318 "Cancel a repeater by setting its numeric value to zero."
12319 (interactive)
12320 (save-excursion
12321 (org-back-to-heading t)
12322 (let ((bound1 (point))
12323 (bound0 (save-excursion (outline-next-heading) (point))))
12324 (when (and (re-search-forward
12325 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12326 org-deadline-time-regexp "\\)\\|\\("
12327 org-ts-regexp "\\)")
12328 bound0 t)
12329 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12330 bound1 t))
12331 (replace-match "0" t nil nil 1)))))
12333 (defvar org-state)
12334 (defvar org-blocked-by-checkboxes)
12335 (defun org-todo (&optional arg)
12336 "Change the TODO state of an item.
12338 The state of an item is given by a keyword at the start of the heading,
12339 like
12340 *** TODO Write paper
12341 *** DONE Call mom
12343 The different keywords are specified in the variable `org-todo-keywords'.
12344 By default the available states are \"TODO\" and \"DONE\". So, for this
12345 example: when the item starts with TODO, it is changed to DONE.
12346 When it starts with DONE, the DONE is removed. And when neither TODO nor
12347 DONE are present, add TODO at the beginning of the heading.
12349 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12350 state.
12351 With numeric prefix ARG, switch to that state.
12352 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12353 next set of TODO \
12354 keywords (nextset).
12355 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12356 prefix, circumvent any state blocking.
12357 With a numeric prefix arg of 0, inhibit note taking for the change.
12358 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12360 When called through ELisp, arg is also interpreted in the following way:
12361 `none' -> empty state
12362 \"\" -> switch to empty state
12363 `done' -> switch to DONE
12364 `nextset' -> switch to the next set of keywords
12365 `previousset' -> switch to the previous set of keywords
12366 \"WAITING\" -> switch to the specified keyword, but only if it
12367 really is a member of `org-todo-keywords'."
12368 (interactive "P")
12369 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12370 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12371 'region-start-level 'region))
12372 org-loop-over-headlines-in-active-region)
12373 (org-map-entries
12374 `(org-todo ,arg)
12375 org-loop-over-headlines-in-active-region
12376 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12377 (when (equal arg '(16)) (setq arg 'nextset))
12378 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12379 (let ((org-blocker-hook org-blocker-hook)
12380 commentp
12381 case-fold-search)
12382 (when (equal arg '(64))
12383 (setq arg nil org-blocker-hook nil))
12384 (when (and org-blocker-hook
12385 (or org-inhibit-blocking
12386 (org-entry-get nil "NOBLOCKING")))
12387 (setq org-blocker-hook nil))
12388 (save-excursion
12389 (catch 'exit
12390 (org-back-to-heading t)
12391 (when (org-in-commented-heading-p t)
12392 (org-toggle-comment)
12393 (setq commentp t))
12394 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12395 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12396 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12397 (let* ((match-data (match-data))
12398 (startpos (copy-marker (line-beginning-position)))
12399 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12400 (org-log-done org-log-done)
12401 (org-log-repeat org-log-repeat)
12402 (org-todo-log-states org-todo-log-states)
12403 (org-inhibit-logging
12404 (if (equal arg 0)
12405 (progn (setq arg nil) 'note) org-inhibit-logging))
12406 (this (match-string 1))
12407 (hl-pos (match-beginning 0))
12408 (head (org-get-todo-sequence-head this))
12409 (ass (assoc head org-todo-kwd-alist))
12410 (interpret (nth 1 ass))
12411 (done-word (nth 3 ass))
12412 (final-done-word (nth 4 ass))
12413 (org-last-state (or this ""))
12414 (completion-ignore-case t)
12415 (member (member this org-todo-keywords-1))
12416 (tail (cdr member))
12417 (org-state (cond
12418 ((and org-todo-key-trigger
12419 (or (and (equal arg '(4))
12420 (eq org-use-fast-todo-selection 'prefix))
12421 (and (not arg) org-use-fast-todo-selection
12422 (not (eq org-use-fast-todo-selection
12423 'prefix)))))
12424 ;; Use fast selection.
12425 (org-fast-todo-selection))
12426 ((and (equal arg '(4))
12427 (or (not org-use-fast-todo-selection)
12428 (not org-todo-key-trigger)))
12429 ;; Read a state with completion.
12430 (completing-read
12431 "State: " (mapcar #'list org-todo-keywords-1)
12432 nil t))
12433 ((eq arg 'right)
12434 (if this
12435 (if tail (car tail) nil)
12436 (car org-todo-keywords-1)))
12437 ((eq arg 'left)
12438 (unless (equal member org-todo-keywords-1)
12439 (if this
12440 (nth (- (length org-todo-keywords-1)
12441 (length tail) 2)
12442 org-todo-keywords-1)
12443 (org-last org-todo-keywords-1))))
12444 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12445 (setq arg nil))) ;hack to fall back to cycling
12446 (arg
12447 ;; User or caller requests a specific state.
12448 (cond
12449 ((equal arg "") nil)
12450 ((eq arg 'none) nil)
12451 ((eq arg 'done) (or done-word (car org-done-keywords)))
12452 ((eq arg 'nextset)
12453 (or (car (cdr (member head org-todo-heads)))
12454 (car org-todo-heads)))
12455 ((eq arg 'previousset)
12456 (let ((org-todo-heads (reverse org-todo-heads)))
12457 (or (car (cdr (member head org-todo-heads)))
12458 (car org-todo-heads))))
12459 ((car (member arg org-todo-keywords-1)))
12460 ((stringp arg)
12461 (user-error "State `%s' not valid in this file" arg))
12462 ((nth (1- (prefix-numeric-value arg))
12463 org-todo-keywords-1))))
12464 ((null member) (or head (car org-todo-keywords-1)))
12465 ((equal this final-done-word) nil) ;-> make empty
12466 ((null tail) nil) ;-> first entry
12467 ((memq interpret '(type priority))
12468 (if (eq this-command last-command)
12469 (car tail)
12470 (if (> (length tail) 0)
12471 (or done-word (car org-done-keywords))
12472 nil)))
12474 (car tail))))
12475 (org-state (or
12476 (run-hook-with-args-until-success
12477 'org-todo-get-default-hook org-state org-last-state)
12478 org-state))
12479 (next (if org-state (concat " " org-state " ") " "))
12480 (change-plist (list :type 'todo-state-change :from this :to org-state
12481 :position startpos))
12482 dolog now-done-p)
12483 (when org-blocker-hook
12484 (let (org-blocked-by-checkboxes block-reason)
12485 (setq org-last-todo-state-is-todo
12486 (not (member this org-done-keywords)))
12487 (unless (save-excursion
12488 (save-match-data
12489 (org-with-wide-buffer
12490 (run-hook-with-args-until-failure
12491 'org-blocker-hook change-plist))))
12492 (setq block-reason (if org-blocked-by-checkboxes
12493 "contained checkboxes"
12494 (format "\"%s\"" org-block-entry-blocking)))
12495 (if (called-interactively-p 'interactive)
12496 (user-error "TODO state change from %s to %s blocked (by %s)"
12497 this org-state block-reason)
12498 ;; Fail silently.
12499 (message "TODO state change from %s to %s blocked (by %s)"
12500 this org-state block-reason)
12501 (throw 'exit nil)))))
12502 (store-match-data match-data)
12503 (replace-match next t t)
12504 (cond ((equal this org-state)
12505 (message "TODO state was already %s" (org-trim next)))
12506 ((not (pos-visible-in-window-p hl-pos))
12507 (message "TODO state changed to %s" (org-trim next))))
12508 (unless head
12509 (setq head (org-get-todo-sequence-head org-state)
12510 ass (assoc head org-todo-kwd-alist)
12511 interpret (nth 1 ass)
12512 done-word (nth 3 ass)
12513 final-done-word (nth 4 ass)))
12514 (when (memq arg '(nextset previousset))
12515 (message "Keyword-Set %d/%d: %s"
12516 (- (length org-todo-sets) -1
12517 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12518 (length org-todo-sets)
12519 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12520 (setq org-last-todo-state-is-todo
12521 (not (member org-state org-done-keywords)))
12522 (setq now-done-p (and (member org-state org-done-keywords)
12523 (not (member this org-done-keywords))))
12524 (and logging (org-local-logging logging))
12525 (when (and (or org-todo-log-states org-log-done)
12526 (not (eq org-inhibit-logging t))
12527 (not (memq arg '(nextset previousset))))
12528 ;; We need to look at recording a time and note.
12529 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12530 (nth 2 (assoc this org-todo-log-states))))
12531 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12532 (setq dolog 'time))
12533 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12534 (and org-state
12535 (member org-state org-not-done-keywords)
12536 (not (member this org-not-done-keywords))))
12537 ;; This is now a todo state and was not one before
12538 ;; If there was a CLOSED time stamp, get rid of it.
12539 (org-add-planning-info nil nil 'closed))
12540 (when (and now-done-p org-log-done)
12541 ;; It is now done, and it was not done before.
12542 (org-add-planning-info 'closed (org-current-effective-time))
12543 (when (and (not dolog) (eq 'note org-log-done))
12544 (org-add-log-setup 'done org-state this 'note)))
12545 (when (and org-state dolog)
12546 ;; This is a non-nil state, and we need to log it.
12547 (org-add-log-setup 'state org-state this dolog)))
12548 ;; Fixup tag positioning.
12549 (org-todo-trigger-tag-changes org-state)
12550 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12551 (when org-provide-todo-statistics
12552 (org-update-parent-todo-statistics))
12553 (run-hooks 'org-after-todo-state-change-hook)
12554 (when (and arg (not (member org-state org-done-keywords)))
12555 (setq head (org-get-todo-sequence-head org-state)))
12556 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12557 ;; Do we need to trigger a repeat?
12558 (when now-done-p
12559 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12560 ;; This is for the agenda, take a snapshot of the headline.
12561 (save-match-data
12562 (setq org-agenda-headline-snapshot-before-repeat
12563 (org-get-heading))))
12564 (org-auto-repeat-maybe org-state))
12565 ;; Fixup cursor location if close to the keyword.
12566 (when (and (outline-on-heading-p)
12567 (not (bolp))
12568 (save-excursion (beginning-of-line 1)
12569 (looking-at org-todo-line-regexp))
12570 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12571 (goto-char (or (match-end 2) (match-end 1)))
12572 (and (looking-at " ") (just-one-space)))
12573 (when org-trigger-hook
12574 (save-excursion
12575 (run-hook-with-args 'org-trigger-hook change-plist)))
12576 (when commentp (org-toggle-comment))))))))
12578 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12579 "Block turning an entry into a TODO, using the hierarchy.
12580 This checks whether the current task should be blocked from state
12581 changes. Such blocking occurs when:
12583 1. The task has children which are not all in a completed state.
12585 2. A task has a parent with the property :ORDERED:, and there
12586 are siblings prior to the current task with incomplete
12587 status.
12589 3. The parent of the task is blocked because it has siblings that should
12590 be done first, or is child of a block grandparent TODO entry."
12592 (if (not org-enforce-todo-dependencies)
12593 t ; if locally turned off don't block
12594 (catch 'dont-block
12595 ;; If this is not a todo state change, or if this entry is already DONE,
12596 ;; do not block
12597 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12598 (member (plist-get change-plist :from)
12599 (cons 'done org-done-keywords))
12600 (member (plist-get change-plist :to)
12601 (cons 'todo org-not-done-keywords))
12602 (not (plist-get change-plist :to)))
12603 (throw 'dont-block t))
12604 ;; If this task has children, and any are undone, it's blocked
12605 (save-excursion
12606 (org-back-to-heading t)
12607 (let ((this-level (funcall outline-level)))
12608 (outline-next-heading)
12609 (let ((child-level (funcall outline-level)))
12610 (while (and (not (eobp))
12611 (> child-level this-level))
12612 ;; this todo has children, check whether they are all
12613 ;; completed
12614 (when (and (not (org-entry-is-done-p))
12615 (org-entry-is-todo-p))
12616 (setq org-block-entry-blocking (org-get-heading))
12617 (throw 'dont-block nil))
12618 (outline-next-heading)
12619 (setq child-level (funcall outline-level))))))
12620 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12621 ;; any previous siblings are undone, it's blocked
12622 (save-excursion
12623 (org-back-to-heading t)
12624 (let* ((pos (point))
12625 (parent-pos (and (org-up-heading-safe) (point)))
12626 (case-fold-search nil))
12627 (unless parent-pos (throw 'dont-block t)) ; no parent
12628 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12629 (forward-line 1)
12630 (re-search-forward org-not-done-heading-regexp pos t))
12631 (setq org-block-entry-blocking (match-string 0))
12632 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12633 ;; Search further up the hierarchy, to see if an ancestor is blocked
12634 (while t
12635 (goto-char parent-pos)
12636 (unless (looking-at org-not-done-heading-regexp)
12637 (throw 'dont-block t)) ; do not block, parent is not a TODO
12638 (setq pos (point))
12639 (setq parent-pos (and (org-up-heading-safe) (point)))
12640 (unless parent-pos (throw 'dont-block t)) ; no parent
12641 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12642 (forward-line 1)
12643 (re-search-forward org-not-done-heading-regexp pos t)
12644 (setq org-block-entry-blocking (org-get-heading)))
12645 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12647 (defcustom org-track-ordered-property-with-tag nil
12648 "Should the ORDERED property also be shown as a tag?
12649 The ORDERED property decides if an entry should require subtasks to be
12650 completed in sequence. Since a property is not very visible, setting
12651 this option means that toggling the ORDERED property with the command
12652 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12653 not relevant for the behavior, but it makes things more visible.
12655 Note that toggling the tag with tags commands will not change the property
12656 and therefore not influence behavior!
12658 This can be t, meaning the tag ORDERED should be used, It can also be a
12659 string to select a different tag for this task."
12660 :group 'org-todo
12661 :type '(choice
12662 (const :tag "No tracking" nil)
12663 (const :tag "Track with ORDERED tag" t)
12664 (string :tag "Use other tag")))
12666 (defun org-toggle-ordered-property ()
12667 "Toggle the ORDERED property of the current entry.
12668 For better visibility, you can track the value of this property with a tag.
12669 See variable `org-track-ordered-property-with-tag'."
12670 (interactive)
12671 (let* ((t1 org-track-ordered-property-with-tag)
12672 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12673 (save-excursion
12674 (org-back-to-heading)
12675 (if (org-entry-get nil "ORDERED")
12676 (progn
12677 (org-delete-property "ORDERED")
12678 (and tag (org-toggle-tag tag 'off))
12679 (message "Subtasks can be completed in arbitrary order"))
12680 (org-entry-put nil "ORDERED" "t")
12681 (and tag (org-toggle-tag tag 'on))
12682 (message "Subtasks must be completed in sequence")))))
12684 (defun org-block-todo-from-checkboxes (change-plist)
12685 "Block turning an entry into a TODO, using checkboxes.
12686 This checks whether the current task should be blocked from state
12687 changes because there are unchecked boxes in this entry."
12688 (if (not org-enforce-todo-checkbox-dependencies)
12689 t ; if locally turned off don't block
12690 (catch 'dont-block
12691 ;; If this is not a todo state change, or if this entry is already DONE,
12692 ;; do not block
12693 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12694 (member (plist-get change-plist :from)
12695 (cons 'done org-done-keywords))
12696 (member (plist-get change-plist :to)
12697 (cons 'todo org-not-done-keywords))
12698 (not (plist-get change-plist :to)))
12699 (throw 'dont-block t))
12700 ;; If this task has checkboxes that are not checked, it's blocked
12701 (save-excursion
12702 (org-back-to-heading t)
12703 (let ((beg (point)) end)
12704 (outline-next-heading)
12705 (setq end (point))
12706 (goto-char beg)
12707 (when (org-list-search-forward
12708 (concat (org-item-beginning-re)
12709 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12710 "\\[[- ]\\]")
12711 end t)
12712 (when (boundp 'org-blocked-by-checkboxes)
12713 (setq org-blocked-by-checkboxes t))
12714 (throw 'dont-block nil))))
12715 t))) ; do not block
12717 (defun org-entry-blocked-p ()
12718 "Non-nil if entry at point is blocked."
12719 (and (not (org-entry-get nil "NOBLOCKING"))
12720 (member (org-entry-get nil "TODO") org-not-done-keywords)
12721 (not (run-hook-with-args-until-failure
12722 'org-blocker-hook
12723 (list :type 'todo-state-change
12724 :position (point)
12725 :from 'todo
12726 :to 'done)))))
12728 (defun org-update-statistics-cookies (all)
12729 "Update the statistics cookie, either from TODO or from checkboxes.
12730 This should be called with the cursor in a line with a statistics
12731 cookie. When called with a \\[universal-argument] prefix, update
12732 all statistics cookies in the buffer."
12733 (interactive "P")
12734 (if all
12735 (progn
12736 (org-update-checkbox-count 'all)
12737 (org-map-entries 'org-update-parent-todo-statistics))
12738 (if (not (org-at-heading-p))
12739 (org-update-checkbox-count)
12740 (let ((pos (point-marker))
12741 end l1 l2)
12742 (ignore-errors (org-back-to-heading t))
12743 (if (not (org-at-heading-p))
12744 (org-update-checkbox-count)
12745 (setq l1 (org-outline-level))
12746 (setq end (save-excursion
12747 (outline-next-heading)
12748 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12749 (point)))
12750 (if (and (save-excursion
12751 (re-search-forward
12752 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12753 (not (save-excursion (re-search-forward
12754 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12755 (org-update-checkbox-count)
12756 (if (and l2 (> l2 l1))
12757 (progn
12758 (goto-char end)
12759 (org-update-parent-todo-statistics))
12760 (goto-char pos)
12761 (beginning-of-line 1)
12762 (while (re-search-forward
12763 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12764 (point-at-eol) t)
12765 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12766 (goto-char pos)
12767 (move-marker pos nil)))))
12769 (defvar org-entry-property-inherited-from) ;; defined below
12770 (defun org-update-parent-todo-statistics ()
12771 "Update any statistics cookie in the parent of the current headline.
12772 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12773 the entire subtree and this will travel up the hierarchy and update
12774 statistics everywhere."
12775 (let* ((prop (save-excursion (org-up-heading-safe)
12776 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12777 (recursive (or (not org-hierarchical-todo-statistics)
12778 (and prop (string-match "\\<recursive\\>" prop))))
12779 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12781 (first t)
12782 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12783 level ltoggle l1 new ndel
12784 (cnt-all 0) (cnt-done 0) is-percent kwd
12785 checkbox-beg cookie-present)
12786 (catch 'exit
12787 (save-excursion
12788 (beginning-of-line 1)
12789 (setq ltoggle (funcall outline-level))
12790 ;; Three situations are to consider:
12792 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12793 ;; to the top-level ancestor on the headline;
12795 ;; 2. If parent has "recursive" property, repeat up to the
12796 ;; headline setting that property, taking inheritance into
12797 ;; account;
12799 ;; 3. Else, move up to direct parent and proceed only once.
12800 (while (and (setq level (org-up-heading-safe))
12801 (or recursive first)
12802 (>= (point) lim))
12803 (setq first nil cookie-present nil)
12804 (unless (and level
12805 (not (string-match
12806 "\\<checkbox\\>"
12807 (downcase (or (org-entry-get nil "COOKIE_DATA")
12808 "")))))
12809 (throw 'exit nil))
12810 (while (re-search-forward box-re (point-at-eol) t)
12811 (setq cnt-all 0 cnt-done 0 cookie-present t)
12812 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12813 (save-match-data
12814 (unless (outline-next-heading) (throw 'exit nil))
12815 (while (and (looking-at org-complex-heading-regexp)
12816 (> (setq l1 (length (match-string 1))) level))
12817 (setq kwd (and (or recursive (= l1 ltoggle))
12818 (match-string 2)))
12819 (if (or (eq org-provide-todo-statistics 'all-headlines)
12820 (and (eq org-provide-todo-statistics t)
12821 (or (member kwd org-done-keywords)))
12822 (and (listp org-provide-todo-statistics)
12823 (stringp (car org-provide-todo-statistics))
12824 (or (member kwd org-provide-todo-statistics)
12825 (member kwd org-done-keywords)))
12826 (and (listp org-provide-todo-statistics)
12827 (listp (car org-provide-todo-statistics))
12828 (or (member kwd (car org-provide-todo-statistics))
12829 (and (member kwd org-done-keywords)
12830 (member kwd (cadr org-provide-todo-statistics))))))
12831 (setq cnt-all (1+ cnt-all))
12832 (and (eq org-provide-todo-statistics t)
12834 (setq cnt-all (1+ cnt-all))))
12835 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12836 (member kwd org-done-keywords))
12837 (and (listp org-provide-todo-statistics)
12838 (listp (car org-provide-todo-statistics))
12839 (member kwd org-done-keywords)
12840 (member kwd (cadr org-provide-todo-statistics)))
12841 (and (listp org-provide-todo-statistics)
12842 (stringp (car org-provide-todo-statistics))
12843 (member kwd org-done-keywords)))
12844 (setq cnt-done (1+ cnt-done)))
12845 (outline-next-heading)))
12846 (setq new
12847 (if is-percent
12848 (format "[%d%%]" (floor (* 100.0 cnt-done)
12849 (max 1 cnt-all)))
12850 (format "[%d/%d]" cnt-done cnt-all))
12851 ndel (- (match-end 0) checkbox-beg))
12852 (goto-char checkbox-beg)
12853 (insert new)
12854 (delete-region (point) (+ (point) ndel))
12855 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12856 (when cookie-present
12857 (run-hook-with-args 'org-after-todo-statistics-hook
12858 cnt-done (- cnt-all cnt-done))))))
12859 (run-hooks 'org-todo-statistics-hook)))
12861 (defvar org-after-todo-statistics-hook nil
12862 "Hook that is called after a TODO statistics cookie has been updated.
12863 Each function is called with two arguments: the number of not-done entries
12864 and the number of done entries.
12866 For example, the following function, when added to this hook, will switch
12867 an entry to DONE when all children are done, and back to TODO when new
12868 entries are set to a TODO status. Note that this hook is only called
12869 when there is a statistics cookie in the headline!
12871 (defun org-summary-todo (n-done n-not-done)
12872 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12873 (let (org-log-done org-log-states) ; turn off logging
12874 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12877 (defvar org-todo-statistics-hook nil
12878 "Hook that is run whenever Org thinks TODO statistics should be updated.
12879 This hook runs even if there is no statistics cookie present, in which case
12880 `org-after-todo-statistics-hook' would not run.")
12882 (defun org-todo-trigger-tag-changes (state)
12883 "Apply the changes defined in `org-todo-state-tags-triggers'."
12884 (let ((l org-todo-state-tags-triggers)
12885 changes)
12886 (when (or (not state) (equal state ""))
12887 (setq changes (append changes (cdr (assoc "" l)))))
12888 (when (and (stringp state) (> (length state) 0))
12889 (setq changes (append changes (cdr (assoc state l)))))
12890 (when (member state org-not-done-keywords)
12891 (setq changes (append changes (cdr (assq 'todo l)))))
12892 (when (member state org-done-keywords)
12893 (setq changes (append changes (cdr (assq 'done l)))))
12894 (dolist (c changes)
12895 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12897 (defun org-local-logging (value)
12898 "Get logging settings from a property VALUE."
12899 ;; Directly set the variables, they are already local.
12900 (setq org-log-done nil
12901 org-log-repeat nil
12902 org-todo-log-states nil)
12903 (dolist (w (split-string value))
12904 (let (a)
12905 (cond
12906 ((setq a (assoc w org-startup-options))
12907 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12908 (set (nth 1 a) (nth 2 a))))
12909 ((setq a (org-extract-log-state-settings w))
12910 (and (member (car a) org-todo-keywords-1)
12911 (push a org-todo-log-states)))))))
12913 (defun org-get-todo-sequence-head (kwd)
12914 "Return the head of the TODO sequence to which KWD belongs.
12915 If KWD is not set, check if there is a text property remembering the
12916 right sequence."
12917 (let (p)
12918 (cond
12919 ((not kwd)
12920 (or (get-text-property (point-at-bol) 'org-todo-head)
12921 (progn
12922 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12923 nil (point-at-eol)))
12924 (get-text-property p 'org-todo-head))))
12925 ((not (member kwd org-todo-keywords-1))
12926 (car org-todo-keywords-1))
12927 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12929 (defun org-fast-todo-selection ()
12930 "Fast TODO keyword selection with single keys.
12931 Returns the new TODO keyword, or nil if no state change should occur."
12932 (let* ((fulltable org-todo-key-alist)
12933 (done-keywords org-done-keywords) ;; needed for the faces.
12934 (maxlen (apply 'max (mapcar
12935 (lambda (x)
12936 (if (stringp (car x)) (string-width (car x)) 0))
12937 fulltable)))
12938 (expert nil)
12939 (fwidth (+ maxlen 3 1 3))
12940 (ncol (/ (- (window-width) 4) fwidth))
12941 tg cnt e c tbl
12942 groups ingroup)
12943 (save-excursion
12944 (save-window-excursion
12945 (if expert
12946 (set-buffer (get-buffer-create " *Org todo*"))
12947 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12948 (erase-buffer)
12949 (setq-local org-done-keywords done-keywords)
12950 (setq tbl fulltable cnt 0)
12951 (while (setq e (pop tbl))
12952 (cond
12953 ((equal e '(:startgroup))
12954 (push '() groups) (setq ingroup t)
12955 (unless (= cnt 0)
12956 (setq cnt 0)
12957 (insert "\n"))
12958 (insert "{ "))
12959 ((equal e '(:endgroup))
12960 (setq ingroup nil cnt 0)
12961 (insert "}\n"))
12962 ((equal e '(:newline))
12963 (unless (= cnt 0)
12964 (setq cnt 0)
12965 (insert "\n")
12966 (setq e (car tbl))
12967 (while (equal (car tbl) '(:newline))
12968 (insert "\n")
12969 (setq tbl (cdr tbl)))))
12971 (setq tg (car e) c (cdr e))
12972 (when ingroup (push tg (car groups)))
12973 (setq tg (org-add-props tg nil 'face
12974 (org-get-todo-face tg)))
12975 (when (and (= cnt 0) (not ingroup)) (insert " "))
12976 (insert "[" c "] " tg (make-string
12977 (- fwidth 4 (length tg)) ?\ ))
12978 (when (= (setq cnt (1+ cnt)) ncol)
12979 (insert "\n")
12980 (when ingroup (insert " "))
12981 (setq cnt 0)))))
12982 (insert "\n")
12983 (goto-char (point-min))
12984 (unless expert (org-fit-window-to-buffer))
12985 (message "[a-z..]:Set [SPC]:clear")
12986 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12987 (cond
12988 ((or (= c ?\C-g)
12989 (and (= c ?q) (not (rassoc c fulltable))))
12990 (setq quit-flag t))
12991 ((= c ?\ ) nil)
12992 ((setq e (rassoc c fulltable) tg (car e))
12994 (t (setq quit-flag t)))))))
12996 (defun org-entry-is-todo-p ()
12997 (member (org-get-todo-state) org-not-done-keywords))
12999 (defun org-entry-is-done-p ()
13000 (member (org-get-todo-state) org-done-keywords))
13002 (defun org-get-todo-state ()
13003 "Return the TODO keyword of the current subtree."
13004 (save-excursion
13005 (org-back-to-heading t)
13006 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13007 (match-end 2)
13008 (match-string 2))))
13010 (defun org-at-date-range-p (&optional inactive-ok)
13011 "Non-nil if point is inside a date range.
13013 When optional argument INACTIVE-OK is non-nil, also consider
13014 inactive time ranges.
13016 When this function returns a non-nil value, match data is set
13017 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13018 on INACTIVE-OK."
13019 (interactive)
13020 (save-excursion
13021 (catch 'exit
13022 (let ((pos (point)))
13023 (skip-chars-backward "^[<\r\n")
13024 (skip-chars-backward "<[")
13025 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13026 (>= (match-end 0) pos)
13027 (throw 'exit t))
13028 (skip-chars-backward "^<[\r\n")
13029 (skip-chars-backward "<[")
13030 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13031 (>= (match-end 0) pos)
13032 (throw 'exit t)))
13033 nil)))
13035 (defun org-get-repeat (&optional timestamp)
13036 "Check if there is a time-stamp with repeater in this entry.
13038 Return the repeater, as a string, or nil. Also return nil when
13039 this function is called before first heading.
13041 When optional argument TIMESTAMP is a string, extract the
13042 repeater from there instead."
13043 (save-match-data
13044 (cond (timestamp
13045 (and (string-match org-repeat-re timestamp)
13046 (match-string-no-properties 1 timestamp)))
13047 ((org-before-first-heading-p) nil)
13049 (save-excursion
13050 (org-back-to-heading t)
13051 (let ((end (org-entry-end-position)))
13052 (catch :repeat
13053 (while (re-search-forward org-repeat-re end t)
13054 (when (save-match-data (org-at-timestamp-p 'agenda))
13055 (throw :repeat (match-string-no-properties 1)))))))))))
13057 (defvar org-last-changed-timestamp)
13058 (defvar org-last-inserted-timestamp)
13059 (defvar org-log-post-message)
13060 (defvar org-log-note-purpose)
13061 (defvar org-log-note-how nil)
13062 (defvar org-log-note-extra)
13063 (defun org-auto-repeat-maybe (done-word)
13064 "Check if the current headline contains a repeated time-stamp.
13066 If yes, set TODO state back to what it was and change the base date
13067 of repeating deadline/scheduled time stamps to new date.
13069 This function is run automatically after each state change to a DONE state."
13070 (let* ((repeat (org-get-repeat))
13071 (aa (assoc org-last-state org-todo-kwd-alist))
13072 (interpret (nth 1 aa))
13073 (head (nth 2 aa))
13074 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13075 (msg "Entry repeats: ")
13076 (org-log-done nil)
13077 (org-todo-log-states nil)
13078 (end (copy-marker (org-entry-end-position))))
13079 (unwind-protect
13080 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13081 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13082 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13083 org-todo-repeat-to-state)))
13084 (org-todo (cond
13085 ((and to-state (member to-state org-todo-keywords-1))
13086 to-state)
13087 ((eq interpret 'type) org-last-state)
13088 (head)
13089 (t 'none))))
13090 (org-back-to-heading t)
13091 (org-add-planning-info nil nil 'closed)
13092 ;; When `org-log-repeat' is non-nil or entry contains
13093 ;; a clock, set LAST_REPEAT property.
13094 (when (or org-log-repeat
13095 (catch :clock
13096 (save-excursion
13097 (while (re-search-forward org-clock-line-re end t)
13098 (when (org-at-clock-log-p) (throw :clock t))))))
13099 (org-entry-put nil "LAST_REPEAT" (format-time-string
13100 (org-time-stamp-format t t)
13101 (current-time))))
13102 (when org-log-repeat
13103 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13104 (memq 'org-add-log-note post-command-hook))
13105 ;; We are already setup for some record.
13106 (when (eq org-log-repeat 'note)
13107 ;; Make sure we take a note, not only a time stamp.
13108 (setq org-log-note-how 'note))
13109 ;; Set up for taking a record.
13110 (org-add-log-setup 'state
13111 (or done-word (car org-done-keywords))
13112 org-last-state
13113 org-log-repeat)))
13114 (let ((planning-re (regexp-opt
13115 (list org-scheduled-string org-deadline-string))))
13116 (while (re-search-forward org-ts-regexp end t)
13117 (let* ((ts (match-string 0))
13118 (planning? (org-at-planning-p))
13119 (type (if (not planning?) "Plain:"
13120 (save-excursion
13121 (re-search-backward
13122 planning-re (line-beginning-position) t)
13123 (match-string 0)))))
13124 (cond
13125 ;; Ignore fake time-stamps (e.g., within comments).
13126 ((not (org-at-timestamp-p 'agenda)))
13127 ;; Time-stamps without a repeater are usually
13128 ;; skipped. However, a SCHEDULED time-stamp without
13129 ;; one is removed, as they are no longer relevant.
13130 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13131 ts))
13132 (when (equal type org-scheduled-string)
13133 (org-remove-timestamp-with-keyword type)))
13135 (let ((n (string-to-number (match-string 2 ts)))
13136 (what (match-string 3 ts)))
13137 (when (equal what "w") (setq n (* n 7) what "d"))
13138 (when (and (equal what "h")
13139 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13140 ts)))
13141 (user-error
13142 "Cannot repeat in Repeat in %d hour(s) because no hour \
13143 has been set"
13145 ;; Preparation, see if we need to modify the start
13146 ;; date for the change.
13147 (when (match-end 1)
13148 (let ((time (save-match-data
13149 (org-time-string-to-time ts))))
13150 (cond
13151 ((equal (match-string 1 ts) ".")
13152 ;; Shift starting date to today
13153 (org-timestamp-change
13154 (- (org-today) (time-to-days time))
13155 'day))
13156 ((equal (match-string 1 ts) "+")
13157 (let ((nshiftmax 10)
13158 (nshift 0))
13159 (while (or (= nshift 0)
13160 (not (time-less-p (current-time) time)))
13161 (when (= (cl-incf nshift) nshiftmax)
13162 (or (y-or-n-p
13163 (format "%d repeater intervals were not \
13164 enough to shift date past today. Continue? "
13165 nshift))
13166 (user-error "Abort")))
13167 (org-timestamp-change n (cdr (assoc what whata)))
13168 (org-in-regexp org-ts-regexp3)
13169 (setq ts (match-string 1))
13170 (setq time
13171 (save-match-data
13172 (org-time-string-to-time ts)))))
13173 (org-timestamp-change (- n) (cdr (assoc what whata)))
13174 ;; Rematch, so that we have everything in place
13175 ;; for the real shift.
13176 (org-in-regexp org-ts-regexp3)
13177 (setq ts (match-string 1))
13178 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13179 ts)))))
13180 (save-excursion
13181 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13182 (setq msg
13183 (concat
13184 msg type " " org-last-changed-timestamp " "))))))))
13185 (setq org-log-post-message msg)
13186 (message "%s" msg))
13187 (set-marker end nil))))
13189 (defun org-show-todo-tree (arg)
13190 "Make a compact tree which shows all headlines marked with TODO.
13191 The tree will show the lines where the regexp matches, and all higher
13192 headlines above the match.
13193 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13194 With a numeric prefix N, construct a sparse tree for the Nth element
13195 of `org-todo-keywords-1'."
13196 (interactive "P")
13197 (let ((case-fold-search nil)
13198 (kwd-re
13199 (cond ((null arg) org-not-done-regexp)
13200 ((equal arg '(4))
13201 (let ((kwd
13202 (completing-read "Keyword (or KWD1|KWD2|...): "
13203 (mapcar #'list org-todo-keywords-1))))
13204 (concat "\\("
13205 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13206 "\\)\\>")))
13207 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13208 (regexp-quote (nth (1- (prefix-numeric-value arg))
13209 org-todo-keywords-1)))
13210 (t (user-error "Invalid prefix argument: %s" arg)))))
13211 (message "%d TODO entries found"
13212 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13214 (defun org--deadline-or-schedule (arg type time)
13215 "Insert DEADLINE or SCHEDULE information in current entry.
13216 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13217 `org-schedule' for information about ARG and TIME arguments."
13218 (let* ((deadline? (eq type 'deadline))
13219 (keyword (if deadline? org-deadline-string org-scheduled-string))
13220 (log (if deadline? org-log-redeadline org-log-reschedule))
13221 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13222 (old-date-time (and old-date (org-time-string-to-time old-date)))
13223 ;; Save repeater cookie from either TIME or current scheduled
13224 ;; time stamp. We are going to insert it back at the end of
13225 ;; the process.
13226 (repeater (or (and (org-string-nw-p time)
13227 ;; We use `org-repeat-re' because we need
13228 ;; to tell the difference between a real
13229 ;; repeater and a time delta, e.g. "+2d".
13230 (string-match org-repeat-re time)
13231 (match-string 1 time))
13232 (and (org-string-nw-p old-date)
13233 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13234 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13235 old-date)
13236 (match-string 1 old-date)))))
13237 (pcase arg
13238 (`(4)
13239 (when (and old-date log)
13240 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13241 nil old-date log))
13242 (org-remove-timestamp-with-keyword keyword)
13243 (message (if deadline? "Item no longer has a deadline."
13244 "Item is no longer scheduled.")))
13245 (`(16)
13246 (save-excursion
13247 (org-back-to-heading t)
13248 (let ((regexp (if deadline? org-deadline-time-regexp
13249 org-scheduled-time-regexp)))
13250 (if (not (re-search-forward regexp (line-end-position 2) t))
13251 (user-error (if deadline? "No deadline information to update"
13252 "No scheduled information to update"))
13253 (let* ((rpl0 (match-string 1))
13254 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13255 (msg (if deadline? "Warn starting from" "Delay until")))
13256 (replace-match
13257 (concat keyword
13258 " <" rpl
13259 (format " -%dd"
13260 (abs (- (time-to-days
13261 (save-match-data
13262 (org-read-date
13263 nil t nil msg old-date-time)))
13264 (time-to-days old-date-time))))
13265 ">") t t))))))
13267 (org-add-planning-info type time 'closed)
13268 (when (and old-date
13270 (not (equal old-date org-last-inserted-timestamp)))
13271 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13272 org-last-inserted-timestamp
13273 old-date
13274 log))
13275 (when repeater
13276 (save-excursion
13277 (org-back-to-heading t)
13278 (when (re-search-forward
13279 (concat keyword " " org-last-inserted-timestamp)
13280 (line-end-position 2)
13282 (goto-char (1- (match-end 0)))
13283 (insert " " repeater)
13284 (setq org-last-inserted-timestamp
13285 (concat (substring org-last-inserted-timestamp 0 -1)
13286 " " repeater
13287 (substring org-last-inserted-timestamp -1))))))
13288 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13289 org-last-inserted-timestamp)))))
13291 (defun org-deadline (arg &optional time)
13292 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13293 With one universal prefix argument, remove any deadline from the item.
13294 With two universal prefix arguments, prompt for a warning delay.
13295 With argument TIME, set the deadline at the corresponding date. TIME
13296 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13297 (interactive "P")
13298 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13299 (org-map-entries
13300 (lambda () (org--deadline-or-schedule arg 'deadline time))
13302 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13303 'region-start-level
13304 'region)
13305 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13306 (org--deadline-or-schedule arg 'deadline time)))
13308 (defun org-schedule (arg &optional time)
13309 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13310 With one universal prefix argument, remove any scheduling date from the item.
13311 With two universal prefix arguments, prompt for a delay cookie.
13312 With argument TIME, scheduled at the corresponding date. TIME can
13313 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13314 (interactive "P")
13315 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13316 (org-map-entries
13317 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13319 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13320 'region-start-level
13321 'region)
13322 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13323 (org--deadline-or-schedule arg 'scheduled time)))
13325 (defun org-get-scheduled-time (pom &optional inherit)
13326 "Get the scheduled time as a time tuple, of a format suitable
13327 for calling org-schedule with, or if there is no scheduling,
13328 returns nil."
13329 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13330 (when time
13331 (apply 'encode-time (org-parse-time-string time)))))
13333 (defun org-get-deadline-time (pom &optional inherit)
13334 "Get the deadline as a time tuple, of a format suitable for
13335 calling org-deadline with, or if there is no scheduling, returns
13336 nil."
13337 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13338 (when time
13339 (apply 'encode-time (org-parse-time-string time)))))
13341 (defun org-remove-timestamp-with-keyword (keyword)
13342 "Remove all time stamps with KEYWORD in the current entry."
13343 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13344 beg)
13345 (save-excursion
13346 (org-back-to-heading t)
13347 (setq beg (point))
13348 (outline-next-heading)
13349 (while (re-search-backward re beg t)
13350 (replace-match "")
13351 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13352 (equal (char-before) ?\ ))
13353 (backward-delete-char 1)
13354 (when (string-match "^[ \t]*$" (buffer-substring
13355 (point-at-bol) (point-at-eol)))
13356 (delete-region (point-at-bol)
13357 (min (point-max) (1+ (point-at-eol))))))))))
13359 (defvar org-time-was-given) ; dynamically scoped parameter
13360 (defvar org-end-time-was-given) ; dynamically scoped parameter
13362 (defun org-at-planning-p ()
13363 "Non-nil when point is on a planning info line."
13364 ;; This is as accurate and faster than `org-element-at-point' since
13365 ;; planning info location is fixed in the section.
13366 (org-with-wide-buffer
13367 (beginning-of-line)
13368 (and (looking-at-p org-planning-line-re)
13369 (eq (point)
13370 (ignore-errors
13371 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13372 (org-back-to-heading t)
13373 (org-with-limited-levels (org-back-to-heading t)))
13374 (line-beginning-position 2))))))
13376 (defun org-add-planning-info (what &optional time &rest remove)
13377 "Insert new timestamp with keyword in the planning line.
13378 WHAT indicates what kind of time stamp to add. It is a symbol
13379 among `closed', `deadline', `scheduled' and nil. TIME indicates
13380 the time to use. If none is given, the user is prompted for
13381 a date. REMOVE indicates what kind of entries to remove. An old
13382 WHAT entry will also be removed."
13383 (let (org-time-was-given org-end-time-was-given default-time default-input)
13384 (catch 'exit
13385 (when (and (memq what '(scheduled deadline))
13386 (or (not time)
13387 (and (stringp time)
13388 (string-match "^[-+]+[0-9]" time))))
13389 ;; Try to get a default date/time from existing timestamp
13390 (save-excursion
13391 (org-back-to-heading t)
13392 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13393 (when (re-search-forward (if (eq what 'scheduled)
13394 org-scheduled-time-regexp
13395 org-deadline-time-regexp)
13396 end t)
13397 (setq ts (match-string 1)
13398 default-time (apply 'encode-time (org-parse-time-string ts))
13399 default-input (and ts (org-get-compact-tod ts)))))))
13400 (when what
13401 (setq time
13402 (if (stringp time)
13403 ;; This is a string (relative or absolute), set
13404 ;; proper date.
13405 (apply #'encode-time
13406 (org-read-date-analyze
13407 time default-time (decode-time default-time)))
13408 ;; If necessary, get the time from the user
13409 (or time (org-read-date nil 'to-time nil nil
13410 default-time default-input)))))
13412 (org-with-wide-buffer
13413 (org-back-to-heading t)
13414 (forward-line)
13415 (unless (bolp) (insert "\n"))
13416 (cond ((looking-at-p org-planning-line-re)
13417 ;; Move to current indentation.
13418 (skip-chars-forward " \t")
13419 ;; Check if we have to remove something.
13420 (dolist (type (if what (cons what remove) remove))
13421 (save-excursion
13422 (when (re-search-forward
13423 (cl-case type
13424 (closed org-closed-time-regexp)
13425 (deadline org-deadline-time-regexp)
13426 (scheduled org-scheduled-time-regexp)
13427 (otherwise
13428 (error "Invalid planning type: %s" type)))
13429 (line-end-position) t)
13430 ;; Delete until next keyword or end of line.
13431 (delete-region
13432 (match-beginning 0)
13433 (if (re-search-forward org-keyword-time-not-clock-regexp
13434 (line-end-position)
13436 (match-beginning 0)
13437 (line-end-position))))))
13438 ;; If there is nothing more to add and no more keyword
13439 ;; is left, remove the line completely.
13440 (if (and (looking-at-p "[ \t]*$") (not what))
13441 (delete-region (line-beginning-position)
13442 (line-beginning-position 2))
13443 ;; If we removed last keyword, do not leave trailing
13444 ;; white space at the end of line.
13445 (let ((p (point)))
13446 (save-excursion
13447 (end-of-line)
13448 (unless (= (skip-chars-backward " \t" p) 0)
13449 (delete-region (point) (line-end-position)))))))
13450 ((not what) (throw 'exit nil)) ; Nothing to do.
13451 (t (insert-before-markers "\n")
13452 (backward-char 1)
13453 (when org-adapt-indentation
13454 (indent-to-column (1+ (org-outline-level))))))
13455 (when what
13456 ;; Insert planning keyword.
13457 (insert (cl-case what
13458 (closed org-closed-string)
13459 (deadline org-deadline-string)
13460 (scheduled org-scheduled-string)
13461 (otherwise (error "Invalid planning type: %s" what)))
13462 " ")
13463 ;; Insert associated timestamp.
13464 (let ((ts (org-insert-time-stamp
13465 time
13466 (or org-time-was-given
13467 (and (eq what 'closed) org-log-done-with-time))
13468 (eq what 'closed)
13469 nil nil (list org-end-time-was-given))))
13470 (unless (eolp) (insert " "))
13471 ts))))))
13473 (defvar org-log-note-marker (make-marker)
13474 "Marker pointing at the entry where the note is to be inserted.")
13475 (defvar org-log-note-purpose nil)
13476 (defvar org-log-note-state nil)
13477 (defvar org-log-note-previous-state nil)
13478 (defvar org-log-note-extra nil)
13479 (defvar org-log-note-window-configuration nil)
13480 (defvar org-log-note-return-to (make-marker))
13481 (defvar org-log-note-effective-time nil
13482 "Remembered current time so that dynamically scoped
13483 `org-extend-today-until' affects timestamps in state change log")
13485 (defvar org-log-post-message nil
13486 "Message to be displayed after a log note has been stored.
13487 The auto-repeater uses this.")
13489 (defun org-add-note ()
13490 "Add a note to the current entry.
13491 This is done in the same way as adding a state change note."
13492 (interactive)
13493 (org-add-log-setup 'note))
13495 (defun org-log-beginning (&optional create)
13496 "Return expected start of log notes in current entry.
13497 When optional argument CREATE is non-nil, the function creates
13498 a drawer to store notes, if necessary. Returned position ignores
13499 narrowing."
13500 (org-with-wide-buffer
13501 (let ((drawer (org-log-into-drawer)))
13502 (cond
13503 (drawer
13504 (org-end-of-meta-data)
13505 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13506 (end (if (org-at-heading-p) (point)
13507 (save-excursion (outline-next-heading) (point))))
13508 (case-fold-search t))
13509 (catch 'exit
13510 ;; Try to find existing drawer.
13511 (while (re-search-forward regexp end t)
13512 (let ((element (org-element-at-point)))
13513 (when (eq (org-element-type element) 'drawer)
13514 (let ((cend (org-element-property :contents-end element)))
13515 (when (and (not org-log-states-order-reversed) cend)
13516 (goto-char cend)))
13517 (throw 'exit nil))))
13518 ;; No drawer found. Create one, if permitted.
13519 (when create
13520 (unless (bolp) (insert "\n"))
13521 (let ((beg (point)))
13522 (insert ":" drawer ":\n:END:\n")
13523 (org-indent-region beg (point)))
13524 (end-of-line -1)))))
13526 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13527 (skip-chars-forward " \t\n")
13528 (beginning-of-line)
13529 (unless org-log-states-order-reversed
13530 (org-skip-over-state-notes)
13531 (skip-chars-backward " \t\n")
13532 (forward-line)))))
13533 (if (bolp) (point) (line-beginning-position 2))))
13535 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13536 "Set up the post command hook to take a note.
13537 If this is about to TODO state change, the new state is expected in STATE.
13538 HOW is an indicator what kind of note should be created.
13539 EXTRA is additional text that will be inserted into the notes buffer."
13540 (move-marker org-log-note-marker (point))
13541 (setq org-log-note-purpose purpose
13542 org-log-note-state state
13543 org-log-note-previous-state prev-state
13544 org-log-note-how how
13545 org-log-note-extra extra
13546 org-log-note-effective-time (org-current-effective-time))
13547 (add-hook 'post-command-hook 'org-add-log-note 'append))
13549 (defun org-skip-over-state-notes ()
13550 "Skip past the list of State notes in an entry."
13551 (when (ignore-errors (goto-char (org-in-item-p)))
13552 (let* ((struct (org-list-struct))
13553 (prevs (org-list-prevs-alist struct))
13554 (regexp
13555 (concat "[ \t]*- +"
13556 (replace-regexp-in-string
13557 " +" " +"
13558 (org-replace-escapes
13559 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13560 `(("%d" . ,org-ts-regexp-inactive)
13561 ("%D" . ,org-ts-regexp)
13562 ("%s" . "\"\\S-+\"")
13563 ("%S" . "\"\\S-+\"")
13564 ("%t" . ,org-ts-regexp-inactive)
13565 ("%T" . ,org-ts-regexp)
13566 ("%u" . ".*?")
13567 ("%U" . ".*?")))))))
13568 (while (looking-at-p regexp)
13569 (goto-char (or (org-list-get-next-item (point) struct prevs)
13570 (org-list-get-item-end (point) struct)))))))
13572 (defun org-add-log-note (&optional _purpose)
13573 "Pop up a window for taking a note, and add this note later."
13574 (remove-hook 'post-command-hook 'org-add-log-note)
13575 (setq org-log-note-window-configuration (current-window-configuration))
13576 (delete-other-windows)
13577 (move-marker org-log-note-return-to (point))
13578 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13579 (goto-char org-log-note-marker)
13580 (org-switch-to-buffer-other-window "*Org Note*")
13581 (erase-buffer)
13582 (if (memq org-log-note-how '(time state))
13583 (org-store-log-note)
13584 (let ((org-inhibit-startup t)) (org-mode))
13585 (insert (format "# Insert note for %s.
13586 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13587 (cond
13588 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13589 ((eq org-log-note-purpose 'done) "closed todo item")
13590 ((eq org-log-note-purpose 'state)
13591 (format "state change from \"%s\" to \"%s\""
13592 (or org-log-note-previous-state "")
13593 (or org-log-note-state "")))
13594 ((eq org-log-note-purpose 'reschedule)
13595 "rescheduling")
13596 ((eq org-log-note-purpose 'delschedule)
13597 "no longer scheduled")
13598 ((eq org-log-note-purpose 'redeadline)
13599 "changing deadline")
13600 ((eq org-log-note-purpose 'deldeadline)
13601 "removing deadline")
13602 ((eq org-log-note-purpose 'refile)
13603 "refiling")
13604 ((eq org-log-note-purpose 'note)
13605 "this entry")
13606 (t (error "This should not happen")))))
13607 (when org-log-note-extra (insert org-log-note-extra))
13608 (setq-local org-finish-function 'org-store-log-note)
13609 (run-hooks 'org-log-buffer-setup-hook)))
13611 (defvar org-note-abort nil) ; dynamically scoped
13612 (defun org-store-log-note ()
13613 "Finish taking a log note, and insert it to where it belongs."
13614 (let ((txt (prog1 (buffer-string)
13615 (kill-buffer)))
13616 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13617 lines)
13618 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13619 (setq txt (replace-match "" t t txt)))
13620 (when (string-match "\\s-+\\'" txt)
13621 (setq txt (replace-match "" t t txt)))
13622 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13623 (when (org-string-nw-p note)
13624 (setq note
13625 (org-replace-escapes
13626 note
13627 (list (cons "%u" (user-login-name))
13628 (cons "%U" user-full-name)
13629 (cons "%t" (format-time-string
13630 (org-time-stamp-format 'long 'inactive)
13631 org-log-note-effective-time))
13632 (cons "%T" (format-time-string
13633 (org-time-stamp-format 'long nil)
13634 org-log-note-effective-time))
13635 (cons "%d" (format-time-string
13636 (org-time-stamp-format nil 'inactive)
13637 org-log-note-effective-time))
13638 (cons "%D" (format-time-string
13639 (org-time-stamp-format nil nil)
13640 org-log-note-effective-time))
13641 (cons "%s" (cond
13642 ((not org-log-note-state) "")
13643 ((string-match-p org-ts-regexp
13644 org-log-note-state)
13645 (format "\"[%s]\""
13646 (substring org-log-note-state 1 -1)))
13647 (t (format "\"%s\"" org-log-note-state))))
13648 (cons "%S"
13649 (cond
13650 ((not org-log-note-previous-state) "")
13651 ((string-match-p org-ts-regexp
13652 org-log-note-previous-state)
13653 (format "\"[%s]\""
13654 (substring
13655 org-log-note-previous-state 1 -1)))
13656 (t (format "\"%s\""
13657 org-log-note-previous-state)))))))
13658 (when lines (setq note (concat note " \\\\")))
13659 (push note lines))
13660 (when (and lines (not org-note-abort))
13661 (with-current-buffer (marker-buffer org-log-note-marker)
13662 (org-with-wide-buffer
13663 ;; Find location for the new note.
13664 (goto-char org-log-note-marker)
13665 (set-marker org-log-note-marker nil)
13666 ;; Note associated to a clock is to be located right after
13667 ;; the clock. Do not move point.
13668 (unless (eq org-log-note-purpose 'clock-out)
13669 (goto-char (org-log-beginning t)))
13670 ;; Make sure point is at the beginning of an empty line.
13671 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13672 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13673 ;; In an existing list, add a new item at the top level.
13674 ;; Otherwise, indent line like a regular one.
13675 (let ((itemp (org-in-item-p)))
13676 (if itemp
13677 (indent-line-to
13678 (let ((struct (save-excursion
13679 (goto-char itemp) (org-list-struct))))
13680 (org-list-get-ind (org-list-get-top-point struct) struct)))
13681 (org-indent-line)))
13682 (insert (org-list-bullet-string "-") (pop lines))
13683 (let ((ind (org-list-item-body-column (line-beginning-position))))
13684 (dolist (line lines)
13685 (insert "\n")
13686 (indent-line-to ind)
13687 (insert line)))
13688 (message "Note stored")
13689 (org-back-to-heading t)
13690 (org-cycle-hide-drawers 'children))
13691 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13692 ;; from within `org-add-log-note' because `buffer-undo-list'
13693 ;; is then modified outside of `org-with-remote-undo'.
13694 (when (eq this-command 'org-agenda-todo)
13695 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13696 ;; Don't add undo information when called from `org-agenda-todo'.
13697 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13698 (set-window-configuration org-log-note-window-configuration)
13699 (with-current-buffer (marker-buffer org-log-note-return-to)
13700 (goto-char org-log-note-return-to))
13701 (move-marker org-log-note-return-to nil)
13702 (when org-log-post-message (message "%s" org-log-post-message))))
13704 (defun org-remove-empty-drawer-at (pos)
13705 "Remove an empty drawer at position POS.
13706 POS may also be a marker."
13707 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13708 (org-with-wide-buffer
13709 (goto-char pos)
13710 (let ((drawer (org-element-at-point)))
13711 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13712 (not (org-element-property :contents-begin drawer)))
13713 (delete-region (org-element-property :begin drawer)
13714 (progn (goto-char (org-element-property :end drawer))
13715 (skip-chars-backward " \r\t\n")
13716 (forward-line)
13717 (point))))))))
13719 (defvar org-ts-type nil)
13720 (defun org-sparse-tree (&optional arg type)
13721 "Create a sparse tree, prompt for the details.
13722 This command can create sparse trees. You first need to select the type
13723 of match used to create the tree:
13725 t Show all TODO entries.
13726 T Show entries with a specific TODO keyword.
13727 m Show entries selected by a tags/property match.
13728 p Enter a property name and its value (both with completion on existing
13729 names/values) and show entries with that property.
13730 r Show entries matching a regular expression (`/' can be used as well).
13731 b Show deadlines and scheduled items before a date.
13732 a Show deadlines and scheduled items after a date.
13733 d Show deadlines due within `org-deadline-warning-days'.
13734 D Show deadlines and scheduled items between a date range."
13735 (interactive "P")
13736 (setq type (or type org-sparse-tree-default-date-type))
13737 (setq org-ts-type type)
13738 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13739 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13740 \[c]ycle through date types: %s"
13741 (cl-case type
13742 (all "all timestamps")
13743 (scheduled "only scheduled")
13744 (deadline "only deadline")
13745 (active "only active timestamps")
13746 (inactive "only inactive timestamps")
13747 (closed "with a closed time-stamp")
13748 (otherwise "scheduled/deadline")))
13749 (let ((answer (read-char-exclusive)))
13750 (cl-case answer
13752 (org-sparse-tree
13754 (cadr
13755 (memq type '(nil all scheduled deadline active inactive closed)))))
13756 (?d (call-interactively 'org-check-deadlines))
13757 (?b (call-interactively 'org-check-before-date))
13758 (?a (call-interactively 'org-check-after-date))
13759 (?D (call-interactively 'org-check-dates-range))
13760 (?t (call-interactively 'org-show-todo-tree))
13761 (?T (org-show-todo-tree '(4)))
13762 (?m (call-interactively 'org-match-sparse-tree))
13763 ((?p ?P)
13764 (let* ((kwd (completing-read
13765 "Property: " (mapcar #'list (org-buffer-property-keys))))
13766 (value (completing-read
13767 "Value: " (mapcar #'list (org-property-values kwd)))))
13768 (unless (string-match "\\`{.*}\\'" value)
13769 (setq value (concat "\"" value "\"")))
13770 (org-match-sparse-tree arg (concat kwd "=" value))))
13771 ((?r ?R ?/) (call-interactively 'org-occur))
13772 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13774 (defvar-local org-occur-highlights nil
13775 "List of overlays used for occur matches.")
13776 (defvar-local org-occur-parameters nil
13777 "Parameters of the active org-occur calls.
13778 This is a list, each call to org-occur pushes as cons cell,
13779 containing the regular expression and the callback, onto the list.
13780 The list can contain several entries if `org-occur' has been called
13781 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13782 will only contain one set of parameters. When the highlights are
13783 removed (for example with `C-c C-c', or with the next edit (depending
13784 on `org-remove-highlights-with-change'), this variable is emptied
13785 as well.")
13787 (defun org-occur (regexp &optional keep-previous callback)
13788 "Make a compact tree which shows all matches of REGEXP.
13790 The tree will show the lines where the regexp matches, and any other context
13791 defined in `org-show-context-detail', which see.
13793 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13794 done by a previous call to `org-occur' will be kept, to allow stacking of
13795 calls to this command.
13797 Optional argument CALLBACK can be a function of no argument. In this case,
13798 it is called with point at the end of the match, match data being set
13799 accordingly. Current match is shown only if the return value is non-nil.
13800 The function must neither move point nor alter narrowing."
13801 (interactive "sRegexp: \nP")
13802 (when (equal regexp "")
13803 (user-error "Regexp cannot be empty"))
13804 (unless keep-previous
13805 (org-remove-occur-highlights nil nil t))
13806 (push (cons regexp callback) org-occur-parameters)
13807 (let ((cnt 0))
13808 (save-excursion
13809 (goto-char (point-min))
13810 (when (or (not keep-previous) ; do not want to keep
13811 (not org-occur-highlights)) ; no previous matches
13812 ;; hide everything
13813 (org-overview))
13814 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13815 (isearch-no-upper-case-p regexp t)
13816 org-occur-case-fold-search)))
13817 (while (re-search-forward regexp nil t)
13818 (when (or (not callback)
13819 (save-match-data (funcall callback)))
13820 (setq cnt (1+ cnt))
13821 (when org-highlight-sparse-tree-matches
13822 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13823 (org-show-context 'occur-tree)))))
13824 (when org-remove-highlights-with-change
13825 (add-hook 'before-change-functions 'org-remove-occur-highlights
13826 nil 'local))
13827 (unless org-sparse-tree-open-archived-trees
13828 (org-hide-archived-subtrees (point-min) (point-max)))
13829 (run-hooks 'org-occur-hook)
13830 (when (called-interactively-p 'interactive)
13831 (message "%d match(es) for regexp %s" cnt regexp))
13832 cnt))
13834 (defun org-occur-next-match (&optional n _reset)
13835 "Function for `next-error-function' to find sparse tree matches.
13836 N is the number of matches to move, when negative move backwards.
13837 This function always goes back to the starting point when no
13838 match is found."
13839 (let* ((limit (if (< n 0) (point-min) (point-max)))
13840 (search-func (if (< n 0)
13841 'previous-single-char-property-change
13842 'next-single-char-property-change))
13843 (n (abs n))
13844 (pos (point))
13846 (catch 'exit
13847 (while (setq p1 (funcall search-func (point) 'org-type))
13848 (when (equal p1 limit)
13849 (goto-char pos)
13850 (user-error "No more matches"))
13851 (when (equal (get-char-property p1 'org-type) 'org-occur)
13852 (setq n (1- n))
13853 (when (= n 0)
13854 (goto-char p1)
13855 (throw 'exit (point))))
13856 (goto-char p1))
13857 (goto-char p1)
13858 (user-error "No more matches"))))
13860 (defun org-show-context (&optional key)
13861 "Make sure point and context are visible.
13862 Optional argument KEY, when non-nil, is a symbol. See
13863 `org-show-context-detail' for allowed values and how much is to
13864 be shown."
13865 (org-show-set-visibility
13866 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13867 ((cdr (assq key org-show-context-detail)))
13868 (t (cdr (assq 'default org-show-context-detail))))))
13870 (defun org-show-set-visibility (detail)
13871 "Set visibility around point according to DETAIL.
13872 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13873 `tree', `canonical' or t. See `org-show-context-detail' for more
13874 information."
13875 ;; Show current heading and possibly its entry, following headline
13876 ;; or all children.
13877 (if (and (org-at-heading-p) (not (eq detail 'local)))
13878 (org-flag-heading nil)
13879 (org-show-entry)
13880 ;; If point is hidden within a drawer or a block, make sure to
13881 ;; expose it.
13882 (dolist (o (overlays-at (point)))
13883 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13884 (delete-overlay o)))
13885 (unless (org-before-first-heading-p)
13886 (org-with-limited-levels
13887 (cl-case detail
13888 ((tree canonical t) (org-show-children))
13889 ((nil minimal ancestors))
13890 (t (save-excursion
13891 (outline-next-heading)
13892 (org-flag-heading nil)))))))
13893 ;; Show all siblings.
13894 (when (eq detail 'lineage) (org-show-siblings))
13895 ;; Show ancestors, possibly with their children.
13896 (when (memq detail '(ancestors lineage tree canonical t))
13897 (save-excursion
13898 (while (org-up-heading-safe)
13899 (org-flag-heading nil)
13900 (when (memq detail '(canonical t)) (org-show-entry))
13901 (when (memq detail '(tree canonical t)) (org-show-children))))))
13903 (defvar org-reveal-start-hook nil
13904 "Hook run before revealing a location.")
13906 (defun org-reveal (&optional siblings)
13907 "Show current entry, hierarchy above it, and the following headline.
13909 This can be used to show a consistent set of context around
13910 locations exposed with `org-show-context'.
13912 With optional argument SIBLINGS, on each level of the hierarchy all
13913 siblings are shown. This repairs the tree structure to what it would
13914 look like when opened with hierarchical calls to `org-cycle'.
13916 With a \\[universal-argument] \\[universal-argument] prefix, \
13917 go to the parent and show the entire tree."
13918 (interactive "P")
13919 (run-hooks 'org-reveal-start-hook)
13920 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13921 ((equal siblings '(16))
13922 (save-excursion
13923 (when (org-up-heading-safe)
13924 (org-show-subtree)
13925 (run-hook-with-args 'org-cycle-hook 'subtree))))
13926 (t (org-show-set-visibility 'lineage))))
13928 (defun org-highlight-new-match (beg end)
13929 "Highlight from BEG to END and mark the highlight is an occur headline."
13930 (let ((ov (make-overlay beg end)))
13931 (overlay-put ov 'face 'secondary-selection)
13932 (overlay-put ov 'org-type 'org-occur)
13933 (push ov org-occur-highlights)))
13935 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13936 "Remove the occur highlights from the buffer.
13937 BEG and END are ignored. If NOREMOVE is nil, remove this function
13938 from the `before-change-functions' in the current buffer."
13939 (interactive)
13940 (unless org-inhibit-highlight-removal
13941 (mapc #'delete-overlay org-occur-highlights)
13942 (setq org-occur-highlights nil)
13943 (setq org-occur-parameters nil)
13944 (unless noremove
13945 (remove-hook 'before-change-functions
13946 'org-remove-occur-highlights 'local))))
13948 ;;;; Priorities
13950 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13951 "Regular expression matching the priority indicator.")
13953 (defvar org-remove-priority-next-time nil)
13955 (defun org-priority-up ()
13956 "Increase the priority of the current item."
13957 (interactive)
13958 (org-priority 'up))
13960 (defun org-priority-down ()
13961 "Decrease the priority of the current item."
13962 (interactive)
13963 (org-priority 'down))
13965 (defun org-priority (&optional action _show)
13966 "Change the priority of an item.
13967 ACTION can be `set', `up', `down', or a character."
13968 (interactive "P")
13969 (if (equal action '(4))
13970 (org-show-priority)
13971 (unless org-enable-priority-commands
13972 (user-error "Priority commands are disabled"))
13973 (setq action (or action 'set))
13974 (let (current new news have remove)
13975 (save-excursion
13976 (org-back-to-heading t)
13977 (when (looking-at org-priority-regexp)
13978 (setq current (string-to-char (match-string 2))
13979 have t))
13980 (cond
13981 ((eq action 'remove)
13982 (setq remove t new ?\ ))
13983 ((or (eq action 'set)
13984 (integerp action))
13985 (if (not (eq action 'set))
13986 (setq new action)
13987 (message "Priority %c-%c, SPC to remove: "
13988 org-highest-priority org-lowest-priority)
13989 (save-match-data
13990 (setq new (read-char-exclusive))))
13991 (when (and (= (upcase org-highest-priority) org-highest-priority)
13992 (= (upcase org-lowest-priority) org-lowest-priority))
13993 (setq new (upcase new)))
13994 (cond ((equal new ?\ ) (setq remove t))
13995 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13996 (user-error "Priority must be between `%c' and `%c'"
13997 org-highest-priority org-lowest-priority))))
13998 ((eq action 'up)
13999 (setq new (if have
14000 (1- current) ; normal cycling
14001 ;; last priority was empty
14002 (if (eq last-command this-command)
14003 org-lowest-priority ; wrap around empty to lowest
14004 ;; default
14005 (if org-priority-start-cycle-with-default
14006 org-default-priority
14007 (1- org-default-priority))))))
14008 ((eq action 'down)
14009 (setq new (if have
14010 (1+ current) ; normal cycling
14011 ;; last priority was empty
14012 (if (eq last-command this-command)
14013 org-highest-priority ; wrap around empty to highest
14014 ;; default
14015 (if org-priority-start-cycle-with-default
14016 org-default-priority
14017 (1+ org-default-priority))))))
14018 (t (user-error "Invalid action")))
14019 (when (or (< (upcase new) org-highest-priority)
14020 (> (upcase new) org-lowest-priority))
14021 (if (and (memq action '(up down))
14022 (not have) (not (eq last-command this-command)))
14023 ;; `new' is from default priority
14024 (error
14025 "The default can not be set, see `org-default-priority' why")
14026 ;; normal cycling: `new' is beyond highest/lowest priority
14027 ;; and is wrapped around to the empty priority
14028 (setq remove t)))
14029 (setq news (format "%c" new))
14030 (if have
14031 (if remove
14032 (replace-match "" t t nil 1)
14033 (replace-match news t t nil 2))
14034 (if remove
14035 (user-error "No priority cookie found in line")
14036 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14037 (if (match-end 2)
14038 (progn
14039 (goto-char (match-end 2))
14040 (insert " [#" news "]"))
14041 (goto-char (match-beginning 3))
14042 (insert "[#" news "] "))))
14043 (org-set-tags nil 'align))
14044 (if remove
14045 (message "Priority removed")
14046 (message "Priority of current item set to %s" news)))))
14048 (defun org-show-priority ()
14049 "Show the priority of the current item.
14050 This priority is composed of the main priority given with the [#A] cookies,
14051 and by additional input from the age of a schedules or deadline entry."
14052 (interactive)
14053 (let ((pri (if (eq major-mode 'org-agenda-mode)
14054 (org-get-at-bol 'priority)
14055 (save-excursion
14056 (save-match-data
14057 (beginning-of-line)
14058 (and (looking-at org-heading-regexp)
14059 (org-get-priority (match-string 0))))))))
14060 (message "Priority is %d" (if pri pri -1000))))
14062 (defun org-get-priority (s)
14063 "Find priority cookie and return priority."
14064 (save-match-data
14065 (if (functionp org-get-priority-function)
14066 (funcall org-get-priority-function)
14067 (if (not (string-match org-priority-regexp s))
14068 (* 1000 (- org-lowest-priority org-default-priority))
14069 (* 1000 (- org-lowest-priority
14070 (string-to-char (match-string 2 s))))))))
14072 ;;;; Tags
14074 (defvar org-agenda-archives-mode)
14075 (defvar org-map-continue-from nil
14076 "Position from where mapping should continue.
14077 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14079 (defvar org-scanner-tags nil
14080 "The current tag list while the tags scanner is running.")
14082 (defvar org-trust-scanner-tags nil
14083 "Should `org-get-tags-at' use the tags for the scanner.
14084 This is for internal dynamical scoping only.
14085 When this is non-nil, the function `org-get-tags-at' will return the value
14086 of `org-scanner-tags' instead of building the list by itself. This
14087 can lead to large speed-ups when the tags scanner is used in a file with
14088 many entries, and when the list of tags is retrieved, for example to
14089 obtain a list of properties. Building the tags list for each entry in such
14090 a file becomes an N^2 operation - but with this variable set, it scales
14091 as N.")
14093 (defvar org--matcher-tags-todo-only nil)
14095 (defun org-scan-tags (action matcher todo-only &optional start-level)
14096 "Scan headline tags with inheritance and produce output ACTION.
14098 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14099 or `agenda' to produce an entry list for an agenda view. It can also be
14100 a Lisp form or a function that should be called at each matched headline, in
14101 this case the return value is a list of all return values from these calls.
14103 MATCHER is a function accepting three arguments, returning
14104 a non-nil value whenever a given set of tags qualifies a headline
14105 for inclusion. See `org-make-tags-matcher' for more information.
14106 As a special case, it can also be set to t (respectively nil) in
14107 order to match all (respectively none) headline.
14109 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14110 included in the output.
14112 START-LEVEL can be a string with asterisks, reducing the scope to
14113 headlines matching this string."
14114 (require 'org-agenda)
14115 (let* ((re (concat "^"
14116 (if start-level
14117 ;; Get the correct level to match
14118 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14119 org-outline-regexp)
14120 " *\\(\\<\\("
14121 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14122 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14123 (props (list 'face 'default
14124 'done-face 'org-agenda-done
14125 'undone-face 'default
14126 'mouse-face 'highlight
14127 'org-not-done-regexp org-not-done-regexp
14128 'org-todo-regexp org-todo-regexp
14129 'org-complex-heading-regexp org-complex-heading-regexp
14130 'help-echo
14131 (format "mouse-2 or RET jump to Org file %S"
14132 (abbreviate-file-name
14133 (or (buffer-file-name (buffer-base-buffer))
14134 (buffer-name (buffer-base-buffer)))))))
14135 (org-map-continue-from nil)
14136 lspos tags tags-list
14137 (tags-alist (list (cons 0 org-file-tags)))
14138 (llast 0) rtn rtn1 level category i txt
14139 todo marker entry priority
14140 ts-date ts-date-type ts-date-pair)
14141 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14142 (setq action (list 'lambda nil action)))
14143 (save-excursion
14144 (goto-char (point-min))
14145 (when (eq action 'sparse-tree)
14146 (org-overview)
14147 (org-remove-occur-highlights))
14148 (while (let (case-fold-search)
14149 (re-search-forward re nil t))
14150 (setq org-map-continue-from nil)
14151 (catch :skip
14152 (setq todo
14153 ;; TODO: is the 1-2 difference a bug?
14154 (when (match-end 1) (match-string-no-properties 2))
14155 tags (when (match-end 4) (match-string-no-properties 4)))
14156 (goto-char (setq lspos (match-beginning 0)))
14157 (setq level (org-reduced-level (org-outline-level))
14158 category (org-get-category))
14159 (when (eq action 'agenda)
14160 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14161 ts-date (car ts-date-pair)
14162 ts-date-type (cdr ts-date-pair)))
14163 (setq i llast llast level)
14164 ;; remove tag lists from same and sublevels
14165 (while (>= i level)
14166 (when (setq entry (assoc i tags-alist))
14167 (setq tags-alist (delete entry tags-alist)))
14168 (setq i (1- i)))
14169 ;; add the next tags
14170 (when tags
14171 (setq tags (org-split-string tags ":")
14172 tags-alist
14173 (cons (cons level tags) tags-alist)))
14174 ;; compile tags for current headline
14175 (setq tags-list
14176 (if org-use-tag-inheritance
14177 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14178 tags)
14179 org-scanner-tags tags-list)
14180 (when org-use-tag-inheritance
14181 (setcdr (car tags-alist)
14182 (mapcar (lambda (x)
14183 (setq x (copy-sequence x))
14184 (org-add-prop-inherited x))
14185 (cdar tags-alist))))
14186 (when (and tags org-use-tag-inheritance
14187 (or (not (eq t org-use-tag-inheritance))
14188 org-tags-exclude-from-inheritance))
14189 ;; Selective inheritance, remove uninherited ones.
14190 (setcdr (car tags-alist)
14191 (org-remove-uninherited-tags (cdar tags-alist))))
14192 (when (and
14194 ;; eval matcher only when the todo condition is OK
14195 (and (or (not todo-only) (member todo org-todo-keywords-1))
14196 (if (functionp matcher)
14197 (let ((case-fold-search t) (org-trust-scanner-tags t))
14198 (funcall matcher todo tags-list level))
14199 matcher))
14201 ;; Call the skipper, but return t if it does not
14202 ;; skip, so that the `and' form continues evaluating.
14203 (progn
14204 (unless (eq action 'sparse-tree) (org-agenda-skip))
14207 ;; Check if timestamps are deselecting this entry
14208 (or (not todo-only)
14209 (and (member todo org-todo-keywords-1)
14210 (or (not org-agenda-tags-todo-honor-ignore-options)
14211 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14213 ;; select this headline
14214 (cond
14215 ((eq action 'sparse-tree)
14216 (and org-highlight-sparse-tree-matches
14217 (org-get-heading) (match-end 0)
14218 (org-highlight-new-match
14219 (match-beginning 1) (match-end 1)))
14220 (org-show-context 'tags-tree))
14221 ((eq action 'agenda)
14222 (setq txt (org-agenda-format-item
14224 (concat
14225 (if (eq org-tags-match-list-sublevels 'indented)
14226 (make-string (1- level) ?.) "")
14227 (org-get-heading))
14228 (make-string level ?\s)
14229 category
14230 tags-list)
14231 priority (org-get-priority txt))
14232 (goto-char lspos)
14233 (setq marker (org-agenda-new-marker))
14234 (org-add-props txt props
14235 'org-marker marker 'org-hd-marker marker 'org-category category
14236 'todo-state todo
14237 'ts-date ts-date
14238 'priority priority
14239 'type (concat "tagsmatch" ts-date-type))
14240 (push txt rtn))
14241 ((functionp action)
14242 (setq org-map-continue-from nil)
14243 (save-excursion
14244 (setq rtn1 (funcall action))
14245 (push rtn1 rtn)))
14246 (t (user-error "Invalid action")))
14248 ;; if we are to skip sublevels, jump to end of subtree
14249 (unless org-tags-match-list-sublevels
14250 (org-end-of-subtree t)
14251 (backward-char 1))))
14252 ;; Get the correct position from where to continue
14253 (if org-map-continue-from
14254 (goto-char org-map-continue-from)
14255 (and (= (point) lspos) (end-of-line 1)))))
14256 (when (and (eq action 'sparse-tree)
14257 (not org-sparse-tree-open-archived-trees))
14258 (org-hide-archived-subtrees (point-min) (point-max)))
14259 (nreverse rtn)))
14261 (defun org-remove-uninherited-tags (tags)
14262 "Remove all tags that are not inherited from the list TAGS."
14263 (cond
14264 ((eq org-use-tag-inheritance t)
14265 (if org-tags-exclude-from-inheritance
14266 (org-delete-all org-tags-exclude-from-inheritance tags)
14267 tags))
14268 ((not org-use-tag-inheritance) nil)
14269 ((stringp org-use-tag-inheritance)
14270 (delq nil (mapcar
14271 (lambda (x)
14272 (if (and (string-match org-use-tag-inheritance x)
14273 (not (member x org-tags-exclude-from-inheritance)))
14274 x nil))
14275 tags)))
14276 ((listp org-use-tag-inheritance)
14277 (delq nil (mapcar
14278 (lambda (x)
14279 (if (member x org-use-tag-inheritance) x nil))
14280 tags)))))
14282 (defun org-match-sparse-tree (&optional todo-only match)
14283 "Create a sparse tree according to tags string MATCH.
14285 MATCH is a string with match syntax. It can contain a selection
14286 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14287 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14288 those. See the manual for details.
14290 If optional argument TODO-ONLY is non-nil, only select lines that
14291 are also TODO tasks."
14292 (interactive "P")
14293 (org-agenda-prepare-buffers (list (current-buffer)))
14294 (let ((org--matcher-tags-todo-only todo-only))
14295 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14296 org--matcher-tags-todo-only)))
14298 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14300 (defvar org-cached-props nil)
14301 (defun org-cached-entry-get (pom property)
14302 (if (or (eq t org-use-property-inheritance)
14303 (and (stringp org-use-property-inheritance)
14304 (let ((case-fold-search t))
14305 (string-match-p org-use-property-inheritance property)))
14306 (and (listp org-use-property-inheritance)
14307 (member-ignore-case property org-use-property-inheritance)))
14308 ;; Caching is not possible, check it directly.
14309 (org-entry-get pom property 'inherit)
14310 ;; Get all properties, so we can do complicated checks easily.
14311 (cdr (assoc-string property
14312 (or org-cached-props
14313 (setq org-cached-props (org-entry-properties pom)))
14314 t))))
14316 (defun org-global-tags-completion-table (&optional files)
14317 "Return the list of all tags in all agenda buffer/files.
14318 Optional FILES argument is a list of files which can be used
14319 instead of the agenda files."
14320 (save-excursion
14321 (org-uniquify
14322 (delq nil
14323 (apply #'append
14324 (mapcar
14325 (lambda (file)
14326 (set-buffer (find-file-noselect file))
14327 (mapcar (lambda (x)
14328 (and (stringp (car-safe x))
14329 (list (car-safe x))))
14330 (or org-current-tag-alist (org-get-buffer-tags))))
14331 (if (car-safe files) files
14332 (org-agenda-files))))))))
14334 (defun org-make-tags-matcher (match)
14335 "Create the TAGS/TODO matcher form for the selection string MATCH.
14337 Returns a cons of the selection string MATCH and a function
14338 implementing the matcher.
14340 The matcher is to be called at an Org entry, with point on the
14341 headline, and returns non-nil if the entry matches the selection
14342 string MATCH. It must be called with three arguments: the TODO
14343 keyword at the entry (or nil if none), the list of all tags at
14344 the entry including inherited ones and the reduced level of the
14345 headline. Additionally, the category of the entry, if any, must
14346 be specified as the text property `org-category' on the headline.
14348 This function sets the variable `org--matcher-tags-todo-only' to
14349 a non-nil value if the matcher restricts matching to TODO
14350 entries, otherwise it is not touched.
14352 See also `org-scan-tags'."
14353 (unless match
14354 ;; Get a new match request, with completion against the global
14355 ;; tags table and the local tags in current buffer.
14356 (let ((org-last-tags-completion-table
14357 (org-uniquify
14358 (delq nil (append (org-get-buffer-tags)
14359 (org-global-tags-completion-table))))))
14360 (setq match
14361 (completing-read
14362 "Match: "
14363 'org-tags-completion-function nil nil nil 'org-tags-history))))
14365 (let ((match0 match)
14366 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14367 (start 0)
14368 tagsmatch todomatch tagsmatcher todomatcher)
14370 ;; Expand group tags.
14371 (setq match (org-tags-expand match))
14373 ;; Check if there is a TODO part of this match, which would be the
14374 ;; part after a "/". To make sure that this slash is not part of
14375 ;; a property value to be matched against, we also check that
14376 ;; there is no / after that slash. First, find the last slash.
14377 (let ((s 0))
14378 (while (string-match "/+" match s)
14379 (setq start (match-beginning 0))
14380 (setq s (match-end 0))))
14381 (if (and (string-match "/+" match start)
14382 (not (string-match-p "\"" match start)))
14383 ;; Match contains also a TODO-matching request.
14384 (progn
14385 (setq tagsmatch (substring match 0 (match-beginning 0)))
14386 (setq todomatch (substring match (match-end 0)))
14387 (when (string-prefix-p "!" todomatch)
14388 (setq org--matcher-tags-todo-only t)
14389 (setq todomatch (substring todomatch 1)))
14390 (when (string-match "\\`\\s-*\\'" todomatch)
14391 (setq todomatch nil)))
14392 ;; Only matching tags.
14393 (setq tagsmatch match)
14394 (setq todomatch nil))
14396 ;; Make the tags matcher.
14397 (when (org-string-nw-p tagsmatch)
14398 (let ((orlist nil)
14399 (orterms (org-split-string tagsmatch "|"))
14400 term)
14401 (while (setq term (pop orterms))
14402 (while (and (equal (substring term -1) "\\") orterms)
14403 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14404 (while (string-match re term)
14405 (let* ((rest (substring term (match-end 0)))
14406 (minus (and (match-end 1)
14407 (equal (match-string 1 term) "-")))
14408 (tag (save-match-data
14409 (replace-regexp-in-string
14410 "\\\\-" "-" (match-string 2 term))))
14411 (regexp (eq (string-to-char tag) ?{))
14412 (levelp (match-end 4))
14413 (propp (match-end 5))
14415 (cond
14416 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14417 (levelp
14418 `(,(org-op-to-function (match-string 3 term))
14419 level
14420 ,(string-to-number (match-string 4 term))))
14421 (propp
14422 (let* ((gv (pcase (upcase (match-string 5 term))
14423 ("CATEGORY"
14424 '(get-text-property (point) 'org-category))
14425 ("TODO" 'todo)
14426 (p `(org-cached-entry-get nil ,p))))
14427 (pv (match-string 7 term))
14428 (regexp (eq (string-to-char pv) ?{))
14429 (strp (eq (string-to-char pv) ?\"))
14430 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14431 (po (org-op-to-function (match-string 6 term)
14432 (if timep 'time strp))))
14433 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14434 (when timep (setq pv (org-matcher-time pv)))
14435 (cond ((and regexp (eq po 'org<>))
14436 `(not (string-match ,pv (or ,gv ""))))
14437 (regexp `(string-match ,pv (or ,gv "")))
14438 (strp `(,po (or ,gv "") ,pv))
14440 `(,po
14441 (string-to-number (or ,gv ""))
14442 ,(string-to-number pv))))))
14443 (t `(member ,tag tags-list)))))
14444 (push (if minus `(not ,mm) mm) tagsmatcher)
14445 (setq term rest)))
14446 (push `(and ,@tagsmatcher) orlist)
14447 (setq tagsmatcher nil))
14448 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14450 ;; Make the TODO matcher.
14451 (when (org-string-nw-p todomatch)
14452 (let ((orlist nil))
14453 (dolist (term (org-split-string todomatch "|"))
14454 (while (string-match re term)
14455 (let* ((minus (and (match-end 1)
14456 (equal (match-string 1 term) "-")))
14457 (kwd (match-string 2 term))
14458 (regexp (eq (string-to-char kwd) ?{))
14459 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14460 `(equal todo ,kwd))))
14461 (push (if minus `(not ,mm) mm) todomatcher))
14462 (setq term (substring term (match-end 0))))
14463 (push (if (> (length todomatcher) 1)
14464 (cons 'and todomatcher)
14465 (car todomatcher))
14466 orlist)
14467 (setq todomatcher nil))
14468 (setq todomatcher (cons 'or orlist))))
14470 ;; Return the string and function of the matcher. If no
14471 ;; tags-specific or todo-specific matcher exists, match
14472 ;; everything.
14473 (let ((matcher (if (and tagsmatcher todomatcher)
14474 `(and ,tagsmatcher ,todomatcher)
14475 (or tagsmatcher todomatcher t))))
14476 (when org--matcher-tags-todo-only
14477 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14478 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14480 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14481 "Expand group tags in MATCH.
14483 This replaces every group tag in MATCH with a regexp tag search.
14484 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14485 will be replaced like this:
14487 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14488 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14489 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14491 Replacing by a regexp preserves the structure of the match.
14492 E.g., this expansion
14494 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14496 will match anything tagged with \"Lab\" and \"Home\", or tagged
14497 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14499 A group tag in MATCH can contain regular expressions of its own.
14500 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14501 will be replaced like this:
14503 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14505 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14506 assumed to be a single group tag, and the function will return
14507 the list of tags in this group.
14509 When DOWNCASE is non-nil, expand downcased TAGS."
14510 (if org-group-tags
14511 (let* ((case-fold-search t)
14512 (stable org-mode-syntax-table)
14513 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14514 (taggroups (if downcased
14515 (mapcar (lambda (tg) (mapcar #'downcase tg))
14516 taggroups)
14517 taggroups))
14518 (taggroups-keys (mapcar #'car taggroups))
14519 (return-match (if downcased (downcase match) match))
14520 (count 0)
14521 (work-already-expanded tags-already-expanded)
14522 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14523 ;; @ and _ are allowed as word-components in tags.
14524 (modify-syntax-entry ?@ "w" stable)
14525 (modify-syntax-entry ?_ "w" stable)
14526 ;; Temporarily replace regexp-expressions in the match-expression.
14527 (while (string-match "{.+?}" return-match)
14528 (cl-incf count)
14529 (push (match-string 0 return-match) regexps-in-match)
14530 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14531 (while (and taggroups-keys
14532 (with-syntax-table stable
14533 (string-match
14534 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14535 (regexp-opt taggroups-keys) "\\>\\)")
14536 return-match)))
14537 (let* ((dir (match-string 1 return-match))
14538 (tag (match-string 2 return-match))
14539 (tag (if downcased (downcase tag) tag)))
14540 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14541 (member tag work-already-expanded))
14542 (setq tags-in-group (assoc tag taggroups))
14543 (push tag work-already-expanded)
14544 ;; Recursively expand each tag in the group, if the tag hasn't
14545 ;; already been expanded. Restore the match-data after all recursive calls.
14546 (save-match-data
14547 (let (tags-expanded)
14548 (dolist (x (cdr tags-in-group))
14549 (if (and (member x taggroups-keys)
14550 (not (member x work-already-expanded)))
14551 (setq tags-expanded
14552 (delete-dups
14553 (append
14554 (org-tags-expand x t downcased
14555 work-already-expanded)
14556 tags-expanded)))
14557 (setq tags-expanded
14558 (append (list x) tags-expanded)))
14559 (setq work-already-expanded
14560 (delete-dups
14561 (append tags-expanded
14562 work-already-expanded))))
14563 (setq tags-in-group
14564 (delete-dups (cons (car tags-in-group)
14565 tags-expanded)))))
14566 ;; Filter tag-regexps from tags.
14567 (setq regexp-in-group-escaped
14568 (delq nil (mapcar (lambda (x)
14569 (if (stringp x)
14570 (and (equal "{" (substring x 0 1))
14571 (equal "}" (substring x -1))
14574 tags-in-group))
14575 regexp-in-group
14576 (mapcar (lambda (x)
14577 (substring x 1 -1))
14578 regexp-in-group-escaped)
14579 tags-in-group
14580 (delq nil (mapcar (lambda (x)
14581 (if (stringp x)
14582 (and (not (equal "{" (substring x 0 1)))
14583 (not (equal "}" (substring x -1)))
14586 tags-in-group)))
14587 ;; If single-as-list, do no more in the while-loop.
14588 (if (not single-as-list)
14589 (progn
14590 (when regexp-in-group
14591 (setq regexp-in-group
14592 (concat "\\|"
14593 (mapconcat 'identity regexp-in-group
14594 "\\|"))))
14595 (setq tags-in-group
14596 (concat dir
14597 "{\\<"
14598 (regexp-opt tags-in-group)
14599 "\\>"
14600 regexp-in-group
14601 "}"))
14602 (when (stringp tags-in-group)
14603 (org-add-props tags-in-group '(grouptag t)))
14604 (setq return-match
14605 (replace-match tags-in-group t t return-match)))
14606 (setq tags-in-group
14607 (append regexp-in-group-escaped tags-in-group))))
14608 (setq taggroups-keys (delete tag taggroups-keys))))
14609 ;; Add the regular expressions back into the match-expression again.
14610 (while regexps-in-match
14611 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14612 (pop regexps-in-match)
14613 return-match t t))
14614 (cl-decf count))
14615 (if single-as-list
14616 (if tags-in-group tags-in-group (list return-match))
14617 return-match))
14618 (if single-as-list
14619 (list (if downcased (downcase match) match))
14620 match)))
14622 (defun org-op-to-function (op &optional stringp)
14623 "Turn an operator into the appropriate function."
14624 (setq op
14625 (cond
14626 ((equal op "<" ) '(< string< org-time<))
14627 ((equal op ">" ) '(> org-string> org-time>))
14628 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14629 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14630 ((member op '("=" "==")) '(= string= org-time=))
14631 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14632 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14634 (defun org<> (a b) (not (= a b)))
14635 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14636 (defun org-string>= (a b) (not (string< a b)))
14637 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14638 (defun org-string<> (a b) (not (string= a b)))
14639 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14640 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14641 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14642 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14643 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14644 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14645 (defun org-2ft (s)
14646 "Convert S to a floating point time.
14647 If S is already a number, just return it. If it is a string, parse
14648 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14649 (cond
14650 ((numberp s) s)
14651 ((stringp s)
14652 (condition-case nil
14653 (float-time (apply #'encode-time (org-parse-time-string s)))
14654 (error 0.)))
14655 (t 0.)))
14657 (defun org-time-today ()
14658 "Time in seconds today at 0:00.
14659 Returns the float number of seconds since the beginning of the
14660 epoch to the beginning of today (00:00)."
14661 (float-time (apply 'encode-time
14662 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14664 (defun org-matcher-time (s)
14665 "Interpret a time comparison value."
14666 (save-match-data
14667 (cond
14668 ((string= s "<now>") (float-time))
14669 ((string= s "<today>") (org-time-today))
14670 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14671 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14672 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14673 (+ (org-time-today)
14674 (* (string-to-number (match-string 1 s))
14675 (cdr (assoc (match-string 2 s)
14676 '(("d" . 86400.0) ("w" . 604800.0)
14677 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14678 (t (org-2ft s)))))
14680 (defun org-match-any-p (re list)
14681 "Does re match any element of list?"
14682 (setq list (mapcar (lambda (x) (string-match re x)) list))
14683 (delq nil list))
14685 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14686 (defvar org-tags-overlay (make-overlay 1 1))
14687 (delete-overlay org-tags-overlay)
14689 (defun org-get-local-tags-at (&optional pos)
14690 "Get a list of tags defined in the current headline."
14691 (org-get-tags-at pos 'local))
14693 (defun org-get-local-tags ()
14694 "Get a list of tags defined in the current headline."
14695 (org-get-tags-at nil 'local))
14697 (defun org-get-tags-at (&optional pos local)
14698 "Get a list of all headline tags applicable at POS.
14699 POS defaults to point. If tags are inherited, the list contains
14700 the targets in the same sequence as the headlines appear, i.e.
14701 the tags of the current headline come last.
14702 When LOCAL is non-nil, only return tags from the current headline,
14703 ignore inherited ones."
14704 (interactive)
14705 (if (and org-trust-scanner-tags
14706 (or (not pos) (equal pos (point)))
14707 (not local))
14708 org-scanner-tags
14709 (let (tags ltags lastpos parent)
14710 (save-excursion
14711 (save-restriction
14712 (widen)
14713 (goto-char (or pos (point)))
14714 (save-match-data
14715 (catch 'done
14716 (condition-case nil
14717 (progn
14718 (org-back-to-heading t)
14719 (while (not (equal lastpos (point)))
14720 (setq lastpos (point))
14721 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14722 (setq ltags (org-split-string
14723 (match-string-no-properties 1) ":"))
14724 (when parent
14725 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14726 (setq tags (append
14727 (if parent
14728 (org-remove-uninherited-tags ltags)
14729 ltags)
14730 tags)))
14731 (or org-use-tag-inheritance (throw 'done t))
14732 (when local (throw 'done t))
14733 (or (org-up-heading-safe) (error nil))
14734 (setq parent t)))
14735 (error nil)))))
14736 (if local
14737 tags
14738 (reverse (delete-dups
14739 (reverse (append
14740 (org-remove-uninherited-tags
14741 org-file-tags)
14742 tags)))))))))
14744 (defun org-add-prop-inherited (s)
14745 (add-text-properties 0 (length s) '(inherited t) s)
14748 (defun org-toggle-tag (tag &optional onoff)
14749 "Toggle the tag TAG for the current line.
14750 If ONOFF is `on' or `off', don't toggle but set to this state."
14751 (save-excursion
14752 (org-back-to-heading t)
14753 (let ((current
14754 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14755 (line-end-position) t)
14756 (let ((tags (match-string 1)))
14757 ;; Clear current tags.
14758 (replace-match "")
14759 ;; Reverse the tags list so any new tag is appended to
14760 ;; the current list of tags.
14761 (nreverse (org-split-string tags ":")))))
14762 res)
14763 (pcase onoff
14764 (`off (setq current (delete tag current)))
14765 ((or `on (guard (not (member tag current))))
14766 (setq res t)
14767 (cl-pushnew tag current :test #'equal))
14768 (_ (setq current (delete tag current))))
14769 (end-of-line)
14770 (if current
14771 (progn
14772 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14773 (org-set-tags nil t))
14774 (delete-horizontal-space))
14775 (run-hooks 'org-after-tags-change-hook)
14776 res)))
14778 (defun org--align-tags-here (to-col)
14779 "Align tags on the current headline to TO-COL.
14780 Assume point is on a headline."
14781 (let ((pos (point)))
14782 (beginning-of-line)
14783 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14784 (>= pos (match-beginning 2)))
14785 ;; No tags or point within tags: do not align.
14786 (goto-char pos)
14787 (goto-char (match-beginning 1))
14788 (let ((shift (max (- (if (>= to-col 0) to-col
14789 (- (abs to-col) (string-width (match-string 2))))
14790 (current-column))
14791 1)))
14792 (replace-match (make-string shift ?\s) nil nil nil 1)
14793 ;; Preserve initial position, if possible. In any case, stop
14794 ;; before tags.
14795 (when (< pos (point)) (goto-char pos))))))
14797 (defun org-set-tags-command (&optional arg just-align)
14798 "Call the set-tags command for the current entry."
14799 (interactive "P")
14800 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14801 (org-set-tags arg just-align)
14802 (save-excursion
14803 (unless (and (org-region-active-p)
14804 org-loop-over-headlines-in-active-region)
14805 (org-back-to-heading t))
14806 (org-set-tags arg just-align))))
14808 (defun org-set-tags-to (data)
14809 "Set the tags of the current entry to DATA, replacing the current tags.
14810 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14811 If DATA is nil or the empty string, any tags will be removed."
14812 (interactive "sTags: ")
14813 (setq data
14814 (cond
14815 ((eq data nil) "")
14816 ((equal data "") "")
14817 ((stringp data)
14818 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14819 ":"))
14820 ((listp data)
14821 (concat ":" (mapconcat 'identity data ":") ":"))))
14822 (when data
14823 (save-excursion
14824 (org-back-to-heading t)
14825 (when (let ((case-fold-search nil))
14826 (looking-at org-complex-heading-regexp))
14827 (if (match-end 5)
14828 (progn
14829 (goto-char (match-beginning 5))
14830 (insert data)
14831 (delete-region (point) (point-at-eol))
14832 (org-set-tags nil 'align))
14833 (goto-char (point-at-eol))
14834 (insert " " data)
14835 (org-set-tags nil 'align)))
14836 (beginning-of-line 1)
14837 (when (looking-at ".*?\\([ \t]+\\)$")
14838 (delete-region (match-beginning 1) (match-end 1))))))
14840 (defun org-align-all-tags ()
14841 "Align the tags in all headings."
14842 (interactive)
14843 (save-excursion
14844 (or (ignore-errors (org-back-to-heading t))
14845 (outline-next-heading))
14846 (if (org-at-heading-p)
14847 (org-set-tags t)
14848 (message "No headings"))))
14850 (defvar org-indent-indentation-per-level)
14851 (defun org-set-tags (&optional arg just-align)
14852 "Set the tags for the current headline.
14853 With prefix ARG, realign all tags in headings in the current buffer.
14854 When JUST-ALIGN is non-nil, only align tags."
14855 (interactive "P")
14856 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14857 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14858 'region-start-level
14859 'region))
14860 org-loop-over-headlines-in-active-region)
14861 (org-map-entries
14862 ;; We don't use ARG and JUST-ALIGN here because these args
14863 ;; are not useful when looping over headlines.
14864 #'org-set-tags
14865 org-loop-over-headlines-in-active-region
14867 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14868 (let ((org-setting-tags t))
14869 (if arg
14870 (save-excursion
14871 (goto-char (point-min))
14872 (while (re-search-forward org-outline-regexp-bol nil t)
14873 (org-set-tags nil t)
14874 (end-of-line))
14875 (message "All tags realigned to column %d" org-tags-column))
14876 (let* ((current (org-get-tags-string))
14877 (tags
14878 (if just-align current
14879 ;; Get a new set of tags from the user.
14880 (save-excursion
14881 (let* ((seen)
14882 (table
14883 (setq
14884 org-last-tags-completion-table
14885 ;; Uniquify tags in alists, yet preserve
14886 ;; structure (i.e., keywords).
14887 (delq nil
14888 (mapcar
14889 (lambda (pair)
14890 (let ((head (car pair)))
14891 (cond ((symbolp head) pair)
14892 ((member head seen) nil)
14893 (t (push head seen)
14894 pair))))
14895 (append
14896 (or org-current-tag-alist
14897 (org-get-buffer-tags))
14898 (and
14899 org-complete-tags-always-offer-all-agenda-tags
14900 (org-global-tags-completion-table
14901 (org-agenda-files))))))))
14902 (current-tags (org-split-string current ":"))
14903 (inherited-tags
14904 (nreverse (nthcdr (length current-tags)
14905 (nreverse (org-get-tags-at))))))
14906 (replace-regexp-in-string
14907 "\\([-+&]+\\|,\\)"
14909 (if (or (eq t org-use-fast-tag-selection)
14910 (and org-use-fast-tag-selection
14911 (delq nil (mapcar #'cdr table))))
14912 (org-fast-tag-selection
14913 current-tags inherited-tags table
14914 (and org-fast-tag-selection-include-todo
14915 org-todo-key-alist))
14916 (let ((org-add-colon-after-tag-completion
14917 (< 1 (length table))))
14918 (org-trim
14919 (completing-read
14920 "Tags: "
14921 #'org-tags-completion-function
14922 nil nil current 'org-tags-history))))))))))
14924 (when org-tags-sort-function
14925 (setq tags
14926 (mapconcat
14927 #'identity
14928 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14929 org-tags-sort-function)
14930 ":")))
14932 (if (or (string= ":" tags)
14933 (string= "::" tags))
14934 (setq tags ""))
14935 (if (not (org-string-nw-p tags)) (setq tags "")
14936 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14937 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14939 ;; Insert new tags at the correct column.
14940 (unless (equal current tags)
14941 (save-excursion
14942 (beginning-of-line)
14943 (let ((case-fold-search nil))
14944 (looking-at org-complex-heading-regexp))
14945 ;; Remove current tags, if any.
14946 (when (match-end 5) (replace-match "" nil nil nil 5))
14947 ;; Insert new tags, if any. Otherwise, remove trailing
14948 ;; white spaces.
14949 (end-of-line)
14950 (if (not (equal tags ""))
14951 ;; When text is being inserted on an invisible
14952 ;; region boundary, it can be inadvertently sucked
14953 ;; into invisibility.
14954 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14955 (skip-chars-backward " \t")
14956 (delete-region (point) (line-end-position)))))
14957 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14958 ;; is on.
14959 (unless (equal tags "")
14960 (let* ((level (save-excursion
14961 (beginning-of-line)
14962 (skip-chars-forward "\\*")))
14963 (offset (if (bound-and-true-p org-indent-mode)
14964 (* (1- org-indent-indentation-per-level)
14965 (1- level))
14967 (tags-column
14968 (+ org-tags-column
14969 (if (> org-tags-column 0) (- offset) offset))))
14970 (org--align-tags-here tags-column))))
14971 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14973 (defun org-change-tag-in-region (beg end tag off)
14974 "Add or remove TAG for each entry in the region.
14975 This works in the agenda, and also in an Org buffer."
14976 (interactive
14977 (list (region-beginning) (region-end)
14978 (let ((org-last-tags-completion-table
14979 (if (derived-mode-p 'org-mode)
14980 (org-uniquify
14981 (delq nil (append (org-get-buffer-tags)
14982 (org-global-tags-completion-table))))
14983 (org-global-tags-completion-table))))
14984 (completing-read
14985 "Tag: " 'org-tags-completion-function nil nil nil
14986 'org-tags-history))
14987 (progn
14988 (message "[s]et or [r]emove? ")
14989 (equal (read-char-exclusive) ?r))))
14990 (when (fboundp 'deactivate-mark) (deactivate-mark))
14991 (let ((agendap (equal major-mode 'org-agenda-mode))
14992 l1 l2 m buf pos newhead (cnt 0))
14993 (goto-char end)
14994 (setq l2 (1- (org-current-line)))
14995 (goto-char beg)
14996 (setq l1 (org-current-line))
14997 (cl-loop for l from l1 to l2 do
14998 (org-goto-line l)
14999 (setq m (get-text-property (point) 'org-hd-marker))
15000 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15001 (and agendap m))
15002 (setq buf (if agendap (marker-buffer m) (current-buffer))
15003 pos (if agendap m (point)))
15004 (with-current-buffer buf
15005 (save-excursion
15006 (save-restriction
15007 (goto-char pos)
15008 (setq cnt (1+ cnt))
15009 (org-toggle-tag tag (if off 'off 'on))
15010 (setq newhead (org-get-heading)))))
15011 (and agendap (org-agenda-change-all-lines newhead m))))
15012 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15014 (defun org-tags-completion-function (string _predicate &optional flag)
15015 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15016 (confirm (lambda (x) (stringp (car x)))))
15017 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15018 (setq s1 (match-string 1 string)
15019 s2 (match-string 2 string))
15020 (setq s1 "" s2 string))
15021 (cond
15022 ((eq flag nil)
15023 ;; try completion
15024 (setq rtn (try-completion s2 ctable confirm))
15025 (when (stringp rtn)
15026 (setq rtn
15027 (concat s1 s2 (substring rtn (length s2))
15028 (if (and org-add-colon-after-tag-completion
15029 (assoc rtn ctable))
15030 ":" ""))))
15031 rtn)
15032 ((eq flag t)
15033 ;; all-completions
15034 (all-completions s2 ctable confirm))
15035 ((eq flag 'lambda)
15036 ;; exact match?
15037 (assoc s2 ctable)))))
15039 (defun org-fast-tag-insert (kwd tags face &optional end)
15040 "Insert KDW, and the TAGS, the latter with face FACE.
15041 Also insert END."
15042 (insert (format "%-12s" (concat kwd ":"))
15043 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15044 (or end "")))
15046 (defun org-fast-tag-show-exit (flag)
15047 (save-excursion
15048 (org-goto-line 3)
15049 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15050 (replace-match ""))
15051 (when flag
15052 (end-of-line 1)
15053 (org-move-to-column (- (window-width) 19) t)
15054 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15056 (defun org-set-current-tags-overlay (current prefix)
15057 "Add an overlay to CURRENT tag with PREFIX."
15058 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15059 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15060 (org-overlay-display org-tags-overlay (concat prefix s))))
15062 (defvar org-last-tag-selection-key nil)
15063 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15064 "Fast tag selection with single keys.
15065 CURRENT is the current list of tags in the headline, INHERITED is the
15066 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15067 possibly with grouping information. TODO-TABLE is a similar table with
15068 TODO keywords, should these have keys assigned to them.
15069 If the keys are nil, a-z are automatically assigned.
15070 Returns the new tags string, or nil to not change the current settings."
15071 (let* ((fulltable (append table todo-table))
15072 (maxlen (apply 'max (mapcar
15073 (lambda (x)
15074 (if (stringp (car x)) (string-width (car x)) 0))
15075 fulltable)))
15076 (buf (current-buffer))
15077 (expert (eq org-fast-tag-selection-single-key 'expert))
15078 (buffer-tags nil)
15079 (fwidth (+ maxlen 3 1 3))
15080 (ncol (/ (- (window-width) 4) fwidth))
15081 (i-face 'org-done)
15082 (c-face 'org-todo)
15083 tg cnt e c char c1 c2 ntable tbl rtn
15084 ov-start ov-end ov-prefix
15085 (exit-after-next org-fast-tag-selection-single-key)
15086 (done-keywords org-done-keywords)
15087 groups ingroup intaggroup)
15088 (save-excursion
15089 (beginning-of-line 1)
15090 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15091 (setq ov-start (match-beginning 1)
15092 ov-end (match-end 1)
15093 ov-prefix "")
15094 (setq ov-start (1- (point-at-eol))
15095 ov-end (1+ ov-start))
15096 (skip-chars-forward "^\n\r")
15097 (setq ov-prefix
15098 (concat
15099 (buffer-substring (1- (point)) (point))
15100 (if (> (current-column) org-tags-column)
15102 (make-string (- org-tags-column (current-column)) ?\ ))))))
15103 (move-overlay org-tags-overlay ov-start ov-end)
15104 (save-window-excursion
15105 (if expert
15106 (set-buffer (get-buffer-create " *Org tags*"))
15107 (delete-other-windows)
15108 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15109 (org-switch-to-buffer-other-window " *Org tags*"))
15110 (erase-buffer)
15111 (setq-local org-done-keywords done-keywords)
15112 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15113 (org-fast-tag-insert "Current" current c-face "\n\n")
15114 (org-fast-tag-show-exit exit-after-next)
15115 (org-set-current-tags-overlay current ov-prefix)
15116 (setq tbl fulltable char ?a cnt 0)
15117 (while (setq e (pop tbl))
15118 (cond
15119 ((eq (car e) :startgroup)
15120 (push '() groups) (setq ingroup t)
15121 (unless (zerop cnt)
15122 (setq cnt 0)
15123 (insert "\n"))
15124 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15125 ((eq (car e) :endgroup)
15126 (setq ingroup nil cnt 0)
15127 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15128 ((eq (car e) :startgrouptag)
15129 (setq intaggroup t)
15130 (unless (zerop cnt)
15131 (setq cnt 0)
15132 (insert "\n"))
15133 (insert "[ "))
15134 ((eq (car e) :endgrouptag)
15135 (setq intaggroup nil cnt 0)
15136 (insert "]\n"))
15137 ((equal e '(:newline))
15138 (unless (zerop cnt)
15139 (setq cnt 0)
15140 (insert "\n")
15141 (setq e (car tbl))
15142 (while (equal (car tbl) '(:newline))
15143 (insert "\n")
15144 (setq tbl (cdr tbl)))))
15145 ((equal e '(:grouptags)) (insert " : "))
15147 (setq tg (copy-sequence (car e)) c2 nil)
15148 (if (cdr e)
15149 (setq c (cdr e))
15150 ;; automatically assign a character.
15151 (setq c1 (string-to-char
15152 (downcase (substring
15153 tg (if (= (string-to-char tg) ?@) 1 0)))))
15154 (if (or (rassoc c1 ntable) (rassoc c1 table))
15155 (while (or (rassoc char ntable) (rassoc char table))
15156 (setq char (1+ char)))
15157 (setq c2 c1))
15158 (setq c (or c2 char)))
15159 (when ingroup (push tg (car groups)))
15160 (setq tg (org-add-props tg nil 'face
15161 (cond
15162 ((not (assoc tg table))
15163 (org-get-todo-face tg))
15164 ((member tg current) c-face)
15165 ((member tg inherited) i-face))))
15166 (when (equal (caar tbl) :grouptags)
15167 (org-add-props tg nil 'face 'org-tag-group))
15168 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15169 (insert "[" c "] " tg (make-string
15170 (- fwidth 4 (length tg)) ?\ ))
15171 (push (cons tg c) ntable)
15172 (when (= (cl-incf cnt) ncol)
15173 (insert "\n")
15174 (when (or ingroup intaggroup) (insert " "))
15175 (setq cnt 0)))))
15176 (setq ntable (nreverse ntable))
15177 (insert "\n")
15178 (goto-char (point-min))
15179 (unless expert (org-fit-window-to-buffer))
15180 (setq rtn
15181 (catch 'exit
15182 (while t
15183 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15184 (if (not groups) "no " "")
15185 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15186 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15187 (setq org-last-tag-selection-key c)
15188 (cond
15189 ((= c ?\r) (throw 'exit t))
15190 ((= c ?!)
15191 (setq groups (not groups))
15192 (goto-char (point-min))
15193 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15194 ((= c ?\C-c)
15195 (if (not expert)
15196 (org-fast-tag-show-exit
15197 (setq exit-after-next (not exit-after-next)))
15198 (setq expert nil)
15199 (delete-other-windows)
15200 (set-window-buffer (split-window-vertically) " *Org tags*")
15201 (org-switch-to-buffer-other-window " *Org tags*")
15202 (org-fit-window-to-buffer)))
15203 ((or (= c ?\C-g)
15204 (and (= c ?q) (not (rassoc c ntable))))
15205 (delete-overlay org-tags-overlay)
15206 (setq quit-flag t))
15207 ((= c ?\ )
15208 (setq current nil)
15209 (when exit-after-next (setq exit-after-next 'now)))
15210 ((= c ?\t)
15211 (condition-case nil
15212 (setq tg (completing-read
15213 "Tag: "
15214 (or buffer-tags
15215 (with-current-buffer buf
15216 (setq buffer-tags
15217 (org-get-buffer-tags))))))
15218 (quit (setq tg "")))
15219 (when (string-match "\\S-" tg)
15220 (cl-pushnew (list tg) buffer-tags :test #'equal)
15221 (if (member tg current)
15222 (setq current (delete tg current))
15223 (push tg current)))
15224 (when exit-after-next (setq exit-after-next 'now)))
15225 ((setq e (rassoc c todo-table) tg (car e))
15226 (with-current-buffer buf
15227 (save-excursion (org-todo tg)))
15228 (when exit-after-next (setq exit-after-next 'now)))
15229 ((setq e (rassoc c ntable) tg (car e))
15230 (if (member tg current)
15231 (setq current (delete tg current))
15232 (cl-loop for g in groups do
15233 (when (member tg g)
15234 (dolist (x g) (setq current (delete x current)))))
15235 (push tg current))
15236 (when exit-after-next (setq exit-after-next 'now))))
15238 ;; Create a sorted list
15239 (setq current
15240 (sort current
15241 (lambda (a b)
15242 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15243 (when (eq exit-after-next 'now) (throw 'exit t))
15244 (goto-char (point-min))
15245 (beginning-of-line 2)
15246 (delete-region (point) (point-at-eol))
15247 (org-fast-tag-insert "Current" current c-face)
15248 (org-set-current-tags-overlay current ov-prefix)
15249 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15250 (setq tg (match-string 1))
15251 (add-text-properties
15252 (match-beginning 1) (match-end 1)
15253 (list 'face
15254 (cond
15255 ((member tg current) c-face)
15256 ((member tg inherited) i-face)
15257 (t (get-text-property (match-beginning 1) 'face))))))
15258 (goto-char (point-min)))))
15259 (delete-overlay org-tags-overlay)
15260 (if rtn
15261 (mapconcat 'identity current ":")
15262 nil))))
15264 (defun org-get-tags-string ()
15265 "Get the TAGS string in the current headline."
15266 (unless (org-at-heading-p t)
15267 (user-error "Not on a heading"))
15268 (save-excursion
15269 (beginning-of-line 1)
15270 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15271 (match-string-no-properties 1)
15272 "")))
15274 (defun org-get-tags ()
15275 "Get the list of tags specified in the current headline."
15276 (org-split-string (org-get-tags-string) ":"))
15278 (defun org-get-buffer-tags ()
15279 "Get a table of all tags used in the buffer, for completion."
15280 (org-with-wide-buffer
15281 (goto-char (point-min))
15282 (let ((tag-re (concat org-outline-regexp-bol
15283 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15284 tags)
15285 (while (re-search-forward tag-re nil t)
15286 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15287 (push tag tags)))
15288 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15290 ;;;; The mapping API
15292 (defvar org-agenda-skip-comment-trees)
15293 (defvar org-agenda-skip-function)
15294 (defun org-map-entries (func &optional match scope &rest skip)
15295 "Call FUNC at each headline selected by MATCH in SCOPE.
15297 FUNC is a function or a lisp form. The function will be called without
15298 arguments, with the cursor positioned at the beginning of the headline.
15299 The return values of all calls to the function will be collected and
15300 returned as a list.
15302 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15303 does not need to preserve point. After evaluation, the cursor will be
15304 moved to the end of the line (presumably of the headline of the
15305 processed entry) and search continues from there. Under some
15306 circumstances, this may not produce the wanted results. For example,
15307 if you have removed (e.g. archived) the current (sub)tree it could
15308 mean that the next entry will be skipped entirely. In such cases, you
15309 can specify the position from where search should continue by making
15310 FUNC set the variable `org-map-continue-from' to the desired buffer
15311 position.
15313 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15314 Only headlines that are matched by this query will be considered during
15315 the iteration. When MATCH is nil or t, all headlines will be
15316 visited by the iteration.
15318 SCOPE determines the scope of this command. It can be any of:
15320 nil The current buffer, respecting the restriction if any
15321 tree The subtree started with the entry at point
15322 region The entries within the active region, if any
15323 region-start-level
15324 The entries within the active region, but only those at
15325 the same level than the first one.
15326 file The current buffer, without restriction
15327 file-with-archives
15328 The current buffer, and any archives associated with it
15329 agenda All agenda files
15330 agenda-with-archives
15331 All agenda files with any archive files associated with them
15332 \(file1 file2 ...)
15333 If this is a list, all files in the list will be scanned
15335 The remaining args are treated as settings for the skipping facilities of
15336 the scanner. The following items can be given here:
15338 archive skip trees with the archive tag
15339 comment skip trees with the COMMENT keyword
15340 function or Emacs Lisp form:
15341 will be used as value for `org-agenda-skip-function', so
15342 whenever the function returns a position, FUNC will not be
15343 called for that entry and search will continue from the
15344 position returned
15346 If your function needs to retrieve the tags including inherited tags
15347 at the *current* entry, you can use the value of the variable
15348 `org-scanner-tags' which will be much faster than getting the value
15349 with `org-get-tags-at'. If your function gets properties with
15350 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15351 to t around the call to `org-entry-properties' to get the same speedup.
15352 Note that if your function moves around to retrieve tags and properties at
15353 a *different* entry, you cannot use these techniques."
15354 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15355 (not (org-region-active-p)))
15356 (let* ((org-agenda-archives-mode nil) ; just to make sure
15357 (org-agenda-skip-archived-trees (memq 'archive skip))
15358 (org-agenda-skip-comment-trees (memq 'comment skip))
15359 (org-agenda-skip-function
15360 (car (org-delete-all '(comment archive) skip)))
15361 (org-tags-match-list-sublevels t)
15362 (start-level (eq scope 'region-start-level))
15363 matcher res
15364 org-todo-keywords-for-agenda
15365 org-done-keywords-for-agenda
15366 org-todo-keyword-alist-for-agenda
15367 org-tag-alist-for-agenda
15368 org--matcher-tags-todo-only)
15370 (cond
15371 ((eq match t) (setq matcher t))
15372 ((eq match nil) (setq matcher t))
15373 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15375 (save-excursion
15376 (save-restriction
15377 (cond ((eq scope 'tree)
15378 (org-back-to-heading t)
15379 (org-narrow-to-subtree)
15380 (setq scope nil))
15381 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15382 (org-region-active-p))
15383 ;; If needed, set start-level to a string like "2"
15384 (when start-level
15385 (save-excursion
15386 (goto-char (region-beginning))
15387 (unless (org-at-heading-p) (outline-next-heading))
15388 (setq start-level (org-current-level))))
15389 (narrow-to-region (region-beginning)
15390 (save-excursion
15391 (goto-char (region-end))
15392 (unless (and (bolp) (org-at-heading-p))
15393 (outline-next-heading))
15394 (point)))
15395 (setq scope nil)))
15397 (if (not scope)
15398 (progn
15399 (org-agenda-prepare-buffers
15400 (and buffer-file-name (list buffer-file-name)))
15401 (setq res
15402 (org-scan-tags
15403 func matcher org--matcher-tags-todo-only start-level)))
15404 ;; Get the right scope
15405 (cond
15406 ((and scope (listp scope) (symbolp (car scope)))
15407 (setq scope (eval scope)))
15408 ((eq scope 'agenda)
15409 (setq scope (org-agenda-files t)))
15410 ((eq scope 'agenda-with-archives)
15411 (setq scope (org-agenda-files t))
15412 (setq scope (org-add-archive-files scope)))
15413 ((eq scope 'file)
15414 (setq scope (and buffer-file-name (list buffer-file-name))))
15415 ((eq scope 'file-with-archives)
15416 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15417 (org-agenda-prepare-buffers scope)
15418 (dolist (file scope)
15419 (with-current-buffer (org-find-base-buffer-visiting file)
15420 (org-with-wide-buffer
15421 (goto-char (point-min))
15422 (setq res
15423 (append
15425 (org-scan-tags
15426 func matcher org--matcher-tags-todo-only)))))))))
15427 res)))
15429 ;;; Properties API
15431 (defconst org-special-properties
15432 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15433 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15434 "The special properties valid in Org mode.
15435 These are properties that are not defined in the property drawer,
15436 but in some other way.")
15438 (defconst org-default-properties
15439 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15440 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15441 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15442 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15443 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15444 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15445 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15446 "Some properties that are used by Org mode for various purposes.
15447 Being in this list makes sure that they are offered for completion.")
15449 (defun org--valid-property-p (property)
15450 "Non nil when string PROPERTY is a valid property name."
15451 (not
15452 (or (equal property "")
15453 (string-match-p "\\s-" property))))
15455 (defun org--update-property-plist (key val props)
15456 "Associate KEY to VAL in alist PROPS.
15457 Modifications are made by side-effect. Return new alist."
15458 (let* ((appending (string= (substring key -1) "+"))
15459 (key (if appending (substring key 0 -1) key))
15460 (old (assoc-string key props t)))
15461 (if (not old) (cons (cons key val) props)
15462 (setcdr old (if appending (concat (cdr old) " " val) val))
15463 props)))
15465 (defun org-get-property-block (&optional beg force)
15466 "Return the (beg . end) range of the body of the property drawer.
15467 BEG is the beginning of the current subtree, or of the part
15468 before the first headline. If it is not given, it will be found.
15469 If the drawer does not exist, create it if FORCE is non-nil, or
15470 return nil."
15471 (org-with-wide-buffer
15472 (when beg (goto-char beg))
15473 (unless (org-before-first-heading-p)
15474 (let ((beg (cond (beg)
15475 ((or (not (featurep 'org-inlinetask))
15476 (org-inlinetask-in-task-p))
15477 (org-back-to-heading t))
15478 (t (org-with-limited-levels (org-back-to-heading t))))))
15479 (forward-line)
15480 (when (looking-at-p org-planning-line-re) (forward-line))
15481 (cond ((looking-at org-property-drawer-re)
15482 (forward-line)
15483 (cons (point) (progn (goto-char (match-end 0))
15484 (line-beginning-position))))
15485 (force
15486 (goto-char beg)
15487 (org-insert-property-drawer)
15488 (let ((pos (save-excursion (search-forward ":END:")
15489 (line-beginning-position))))
15490 (cons pos pos))))))))
15492 (defun org-at-property-p ()
15493 "Non-nil when point is inside a property drawer.
15494 See `org-property-re' for match data, if applicable."
15495 (save-excursion
15496 (beginning-of-line)
15497 (and (looking-at org-property-re)
15498 (let ((property-drawer (save-match-data (org-get-property-block))))
15499 (and property-drawer
15500 (>= (point) (car property-drawer))
15501 (< (point) (cdr property-drawer)))))))
15503 (defun org-property-action ()
15504 "Do an action on properties."
15505 (interactive)
15506 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15507 (let ((c (read-char-exclusive)))
15508 (cl-case c
15509 (?s (call-interactively #'org-set-property))
15510 (?d (call-interactively #'org-delete-property))
15511 (?D (call-interactively #'org-delete-property-globally))
15512 (?c (call-interactively #'org-compute-property-at-point))
15513 (otherwise (user-error "No such property action %c" c)))))
15515 (defun org-inc-effort ()
15516 "Increment the value of the effort property in the current entry."
15517 (interactive)
15518 (org-set-effort nil t))
15520 (defvar org-clock-effort) ; Defined in org-clock.el.
15521 (defvar org-clock-current-task) ; Defined in org-clock.el.
15522 (defun org-set-effort (&optional value increment)
15523 "Set the effort property of the current entry.
15524 With numerical prefix arg, use the nth allowed value, 0 stands for the
15525 10th allowed value.
15527 When INCREMENT is non-nil, set the property to the next allowed value."
15528 (interactive "P")
15529 (when (equal value 0) (setq value 10))
15530 (let* ((completion-ignore-case t)
15531 (prop org-effort-property)
15532 (cur (org-entry-get nil prop))
15533 (allowed (org-property-get-allowed-values nil prop 'table))
15534 (existing (mapcar 'list (org-property-values prop)))
15535 (heading (nth 4 (org-heading-components)))
15537 (val (cond
15538 ((stringp value) value)
15539 ((and allowed (integerp value))
15540 (or (car (nth (1- value) allowed))
15541 (car (org-last allowed))))
15542 ((and allowed increment)
15543 (or (cl-caadr (member (list cur) allowed))
15544 (user-error "Allowed effort values are not set")))
15545 (allowed
15546 (message "Select 1-9,0, [RET%s]: %s"
15547 (if cur (concat "=" cur) "")
15548 (mapconcat 'car allowed " "))
15549 (setq rpl (read-char-exclusive))
15550 (if (equal rpl ?\r)
15552 (setq rpl (- rpl ?0))
15553 (when (equal rpl 0) (setq rpl 10))
15554 (if (and (> rpl 0) (<= rpl (length allowed)))
15555 (car (nth (1- rpl) allowed))
15556 (org-completing-read "Effort: " allowed nil))))
15558 (org-completing-read
15559 (concat "Effort" (and cur (string-match "\\S-" cur)
15560 (concat " [" cur "]"))
15561 ": ")
15562 existing nil nil "" nil cur)))))
15563 (unless (equal (org-entry-get nil prop) val)
15564 (org-entry-put nil prop val))
15565 (org-refresh-property
15566 '((effort . identity)
15567 (effort-minutes . org-duration-to-minutes))
15568 val)
15569 (when (equal heading (bound-and-true-p org-clock-current-task))
15570 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15571 (org-clock-update-mode-line))
15572 (message "%s is now %s" prop val)))
15574 (defun org-entry-properties (&optional pom which)
15575 "Get all properties of the current entry.
15577 When POM is a buffer position, get all properties from the entry
15578 there instead.
15580 This includes the TODO keyword, the tags, time strings for
15581 deadline, scheduled, and clocking, and any additional properties
15582 defined in the entry.
15584 If WHICH is nil or `all', get all properties. If WHICH is
15585 `special' or `standard', only get that subclass. If WHICH is
15586 a string, only get that property.
15588 Return value is an alist. Keys are properties, as upcased
15589 strings."
15590 (org-with-point-at pom
15591 (when (and (derived-mode-p 'org-mode)
15592 (ignore-errors (org-back-to-heading t)))
15593 (catch 'exit
15594 (let* ((beg (point))
15595 (specific (and (stringp which) (upcase which)))
15596 (which (cond ((not specific) which)
15597 ((member specific org-special-properties) 'special)
15598 (t 'standard)))
15599 props)
15600 ;; Get the special properties, like TODO and TAGS.
15601 (when (memq which '(nil all special))
15602 (when (or (not specific) (string= specific "CLOCKSUM"))
15603 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15604 (when clocksum
15605 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15606 props)))
15607 (when specific (throw 'exit props)))
15608 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15609 (let ((clocksumt (get-text-property (point)
15610 :org-clock-minutes-today)))
15611 (when clocksumt
15612 (push (cons "CLOCKSUM_T"
15613 (org-duration-from-minutes clocksumt))
15614 props)))
15615 (when specific (throw 'exit props)))
15616 (when (or (not specific) (string= specific "ITEM"))
15617 (let ((case-fold-search nil))
15618 (when (looking-at org-complex-heading-regexp)
15619 (push (cons "ITEM"
15620 (let ((title (match-string-no-properties 4)))
15621 (if (org-string-nw-p title)
15622 (org-remove-tabs title)
15623 "")))
15624 props)))
15625 (when specific (throw 'exit props)))
15626 (when (or (not specific) (string= specific "TODO"))
15627 (let ((case-fold-search nil))
15628 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15629 (push (cons "TODO" (match-string-no-properties 2)) props)))
15630 (when specific (throw 'exit props)))
15631 (when (or (not specific) (string= specific "PRIORITY"))
15632 (push (cons "PRIORITY"
15633 (if (looking-at org-priority-regexp)
15634 (match-string-no-properties 2)
15635 (char-to-string org-default-priority)))
15636 props)
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific) (string= specific "FILE"))
15639 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15640 props)
15641 (when specific (throw 'exit props)))
15642 (when (or (not specific) (string= specific "TAGS"))
15643 (let ((value (org-string-nw-p (org-get-tags-string))))
15644 (when value (push (cons "TAGS" value) props)))
15645 (when specific (throw 'exit props)))
15646 (when (or (not specific) (string= specific "ALLTAGS"))
15647 (let ((value (org-get-tags-at)))
15648 (when value
15649 (push (cons "ALLTAGS"
15650 (format ":%s:" (mapconcat #'identity value ":")))
15651 props)))
15652 (when specific (throw 'exit props)))
15653 (when (or (not specific) (string= specific "BLOCKED"))
15654 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15655 (when specific (throw 'exit props)))
15656 (when (or (not specific)
15657 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15658 (forward-line)
15659 (when (looking-at-p org-planning-line-re)
15660 (end-of-line)
15661 (let ((bol (line-beginning-position))
15662 ;; Backward compatibility: time keywords used to
15663 ;; be configurable (before 8.3). Make sure we
15664 ;; get the correct keyword.
15665 (key-assoc `(("CLOSED" . ,org-closed-string)
15666 ("DEADLINE" . ,org-deadline-string)
15667 ("SCHEDULED" . ,org-scheduled-string))))
15668 (dolist (pair (if specific (list (assoc specific key-assoc))
15669 key-assoc))
15670 (save-excursion
15671 (when (search-backward (cdr pair) bol t)
15672 (goto-char (match-end 0))
15673 (skip-chars-forward " \t")
15674 (and (looking-at org-ts-regexp-both)
15675 (push (cons (car pair)
15676 (match-string-no-properties 0))
15677 props)))))))
15678 (when specific (throw 'exit props)))
15679 (when (or (not specific)
15680 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15681 (let ((find-ts
15682 (lambda (end ts)
15683 ;; Fix next time-stamp before END. TS is the
15684 ;; list of time-stamps found so far.
15685 (let ((ts ts)
15686 (regexp (cond
15687 ((string= specific "TIMESTAMP")
15688 org-ts-regexp)
15689 ((string= specific "TIMESTAMP_IA")
15690 org-ts-regexp-inactive)
15691 ((assoc "TIMESTAMP_IA" ts)
15692 org-ts-regexp)
15693 ((assoc "TIMESTAMP" ts)
15694 org-ts-regexp-inactive)
15695 (t org-ts-regexp-both))))
15696 (catch 'next
15697 (while (re-search-forward regexp end t)
15698 (backward-char)
15699 (let ((object (org-element-context)))
15700 ;; Accept to match timestamps in node
15701 ;; properties, too.
15702 (when (memq (org-element-type object)
15703 '(node-property timestamp))
15704 (let ((type
15705 (org-element-property :type object)))
15706 (cond
15707 ((and (memq type '(active active-range))
15708 (not (equal specific "TIMESTAMP_IA")))
15709 (unless (assoc "TIMESTAMP" ts)
15710 (push (cons "TIMESTAMP"
15711 (org-element-property
15712 :raw-value object))
15714 (when specific (throw 'exit ts))))
15715 ((and (memq type '(inactive inactive-range))
15716 (not (string= specific "TIMESTAMP")))
15717 (unless (assoc "TIMESTAMP_IA" ts)
15718 (push (cons "TIMESTAMP_IA"
15719 (org-element-property
15720 :raw-value object))
15722 (when specific (throw 'exit ts))))))
15723 ;; Both timestamp types are found,
15724 ;; move to next part.
15725 (when (= (length ts) 2) (throw 'next ts)))))
15726 ts)))))
15727 (goto-char beg)
15728 ;; First look for timestamps within headline.
15729 (let ((ts (funcall find-ts (line-end-position) nil)))
15730 (if (= (length ts) 2) (setq props (nconc ts props))
15731 ;; Then find timestamps in the section, skipping
15732 ;; planning line.
15733 (let ((end (save-excursion (outline-next-heading))))
15734 (forward-line)
15735 (when (looking-at-p org-planning-line-re) (forward-line))
15736 (setq props (nconc (funcall find-ts end ts) props))))))))
15737 ;; Get the standard properties, like :PROP:.
15738 (when (memq which '(nil all standard))
15739 ;; If we are looking after a specific property, delegate
15740 ;; to `org-entry-get', which is faster. However, make an
15741 ;; exception for "CATEGORY", since it can be also set
15742 ;; through keywords (i.e. #+CATEGORY).
15743 (if (and specific (not (equal specific "CATEGORY")))
15744 (let ((value (org-entry-get beg specific nil t)))
15745 (throw 'exit (and value (list (cons specific value)))))
15746 (let ((range (org-get-property-block beg)))
15747 (when range
15748 (let ((end (cdr range)) seen-base)
15749 (goto-char (car range))
15750 ;; Unlike to `org--update-property-plist', we
15751 ;; handle the case where base values is found
15752 ;; after its extension. We also forbid standard
15753 ;; properties to be named as special properties.
15754 (while (re-search-forward org-property-re end t)
15755 (let* ((key (upcase (match-string-no-properties 2)))
15756 (extendp (string-match-p "\\+\\'" key))
15757 (key-base (if extendp (substring key 0 -1) key))
15758 (value (match-string-no-properties 3)))
15759 (cond
15760 ((member-ignore-case key-base org-special-properties))
15761 (extendp
15762 (setq props
15763 (org--update-property-plist key value props)))
15764 ((member key seen-base))
15765 (t (push key seen-base)
15766 (let ((p (assoc-string key props t)))
15767 (if p (setcdr p (concat value " " (cdr p)))
15768 (push (cons key value) props))))))))))))
15769 (unless (assoc "CATEGORY" props)
15770 (push (cons "CATEGORY" (org-get-category beg)) props)
15771 (when (string= specific "CATEGORY") (throw 'exit props)))
15772 ;; Return value.
15773 props)))))
15775 (defun org--property-local-values (property literal-nil)
15776 "Return value for PROPERTY in current entry.
15777 Value is a list whose car is the base value for PROPERTY and cdr
15778 a list of accumulated values. Return nil if neither is found in
15779 the entry. Also return nil when PROPERTY is set to \"nil\",
15780 unless LITERAL-NIL is non-nil."
15781 (let ((range (org-get-property-block)))
15782 (when range
15783 (goto-char (car range))
15784 (let* ((case-fold-search t)
15785 (end (cdr range))
15786 (value
15787 ;; Base value.
15788 (save-excursion
15789 (let ((v (and (re-search-forward
15790 (org-re-property property nil t) end t)
15791 (match-string-no-properties 3))))
15792 (list (if literal-nil v (org-not-nil v)))))))
15793 ;; Find additional values.
15794 (let* ((property+ (org-re-property (concat property "+") nil t)))
15795 (while (re-search-forward property+ end t)
15796 (push (match-string-no-properties 3) value)))
15797 ;; Return final values.
15798 (and (not (equal value '(nil))) (nreverse value))))))
15800 (defun org--property-global-value (property literal-nil)
15801 "Return value for PROPERTY in current buffer.
15802 Return value is a string. Return nil if property is not set
15803 globally. Also return nil when PROPERTY is set to \"nil\",
15804 unless LITERAL-NIL is non-nil."
15805 (let ((global
15806 (cdr (or (assoc-string property org-file-properties t)
15807 (assoc-string property org-global-properties t)
15808 (assoc-string property org-global-properties-fixed t)))))
15809 (if literal-nil global (org-not-nil global))))
15811 (defun org-entry-get (pom property &optional inherit literal-nil)
15812 "Get value of PROPERTY for entry or content at point-or-marker POM.
15814 If INHERIT is non-nil and the entry does not have the property,
15815 then also check higher levels of the hierarchy. If INHERIT is
15816 the symbol `selective', use inheritance only if the setting in
15817 `org-use-property-inheritance' selects PROPERTY for inheritance.
15819 If the property is present but empty, the return value is the
15820 empty string. If the property is not present at all, nil is
15821 returned. In any other case, return the value as a string.
15822 Search is case-insensitive.
15824 If LITERAL-NIL is set, return the string value \"nil\" as
15825 a string, do not interpret it as the list atom nil. This is used
15826 for inheritance when a \"nil\" value can supersede a non-nil
15827 value higher up the hierarchy."
15828 (org-with-point-at pom
15829 (cond
15830 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15831 ;; We need a special property. Use `org-entry-properties' to
15832 ;; retrieve it, but specify the wanted property.
15833 (cdr (assoc-string property (org-entry-properties nil property))))
15834 ((and inherit
15835 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15836 (org-entry-get-with-inheritance property literal-nil))
15838 (let* ((local (org--property-local-values property literal-nil))
15839 (value (and local (mapconcat #'identity (delq nil local) " "))))
15840 (if literal-nil value (org-not-nil value)))))))
15842 (defun org-property-or-variable-value (var &optional inherit)
15843 "Check if there is a property fixing the value of VAR.
15844 If yes, return this value. If not, return the current value of the variable."
15845 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15846 (if (and prop (stringp prop) (string-match "\\S-" prop))
15847 (read prop)
15848 (symbol-value var))))
15850 (defun org-entry-delete (pom property)
15851 "Delete PROPERTY from entry at point-or-marker POM.
15852 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15853 non-nil when a property was removed."
15854 (org-with-point-at pom
15855 (pcase (org-get-property-block)
15856 (`(,begin . ,origin)
15857 (let* ((end (copy-marker origin))
15858 (re (org-re-property
15859 (concat (regexp-quote property) "\\+?") t t)))
15860 (goto-char begin)
15861 (while (re-search-forward re end t)
15862 (delete-region (match-beginning 0) (line-beginning-position 2)))
15863 ;; If drawer is empty, remove it altogether.
15864 (when (= begin end)
15865 (delete-region (line-beginning-position 0)
15866 (line-beginning-position 2)))
15867 ;; Return non-nil if some property was removed.
15868 (prog1 (/= end origin) (set-marker end nil))))
15869 (_ nil))))
15871 ;; Multi-values properties are properties that contain multiple values
15872 ;; These values are assumed to be single words, separated by whitespace.
15873 (defun org-entry-add-to-multivalued-property (pom property value)
15874 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15875 (let* ((old (org-entry-get pom property))
15876 (values (and old (split-string old))))
15877 (setq value (org-entry-protect-space value))
15878 (unless (member value values)
15879 (setq values (append values (list value)))
15880 (org-entry-put pom property (mapconcat #'identity values " ")))))
15882 (defun org-entry-remove-from-multivalued-property (pom property value)
15883 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15884 (let* ((old (org-entry-get pom property))
15885 (values (and old (split-string old))))
15886 (setq value (org-entry-protect-space value))
15887 (when (member value values)
15888 (setq values (delete value values))
15889 (org-entry-put pom property (mapconcat #'identity values " ")))))
15891 (defun org-entry-member-in-multivalued-property (pom property value)
15892 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15893 (let* ((old (org-entry-get pom property))
15894 (values (and old (split-string old))))
15895 (setq value (org-entry-protect-space value))
15896 (member value values)))
15898 (defun org-entry-get-multivalued-property (pom property)
15899 "Return a list of values in a multivalued property."
15900 (let* ((value (org-entry-get pom property))
15901 (values (and value (split-string value))))
15902 (mapcar #'org-entry-restore-space values)))
15904 (defun org-entry-put-multivalued-property (pom property &rest values)
15905 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15906 VALUES should be a list of strings. Spaces will be protected."
15907 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15908 (let* ((value (org-entry-get pom property))
15909 (values (and value (split-string value))))
15910 (mapcar #'org-entry-restore-space values)))
15912 (defun org-entry-protect-space (s)
15913 "Protect spaces and newline in string S."
15914 (while (string-match " " s)
15915 (setq s (replace-match "%20" t t s)))
15916 (while (string-match "\n" s)
15917 (setq s (replace-match "%0A" t t s)))
15920 (defun org-entry-restore-space (s)
15921 "Restore spaces and newline in string S."
15922 (while (string-match "%20" s)
15923 (setq s (replace-match " " t t s)))
15924 (while (string-match "%0A" s)
15925 (setq s (replace-match "\n" t t s)))
15928 (defvar org-entry-property-inherited-from (make-marker)
15929 "Marker pointing to the entry from where a property was inherited.
15930 Each call to `org-entry-get-with-inheritance' will set this marker to the
15931 location of the entry where the inheritance search matched. If there was
15932 no match, the marker will point nowhere.
15933 Note that also `org-entry-get' calls this function, if the INHERIT flag
15934 is set.")
15936 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15937 "Get PROPERTY of entry or content at point, search higher levels if needed.
15938 The search will stop at the first ancestor which has the property defined.
15939 If the value found is \"nil\", return nil to show that the property
15940 should be considered as undefined (this is the meaning of nil here).
15941 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15942 (move-marker org-entry-property-inherited-from nil)
15943 (org-with-wide-buffer
15944 (let (value)
15945 (catch 'exit
15946 (while t
15947 (let ((v (org--property-local-values property literal-nil)))
15948 (when v
15949 (setq value
15950 (concat (mapconcat #'identity (delq nil v) " ")
15951 (and value " ")
15952 value)))
15953 (cond
15954 ((car v)
15955 (org-back-to-heading t)
15956 (move-marker org-entry-property-inherited-from (point))
15957 (throw 'exit nil))
15958 ((org-up-heading-safe))
15960 (let ((global (org--property-global-value property literal-nil)))
15961 (cond ((not global))
15962 (value (setq value (concat global " " value)))
15963 (t (setq value global))))
15964 (throw 'exit nil))))))
15965 (if literal-nil value (org-not-nil value)))))
15967 (defvar org-property-changed-functions nil
15968 "Hook called when the value of a property has changed.
15969 Each hook function should accept two arguments, the name of the property
15970 and the new value.")
15972 (defun org-entry-put (pom property value)
15973 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15975 If the value is nil, it is converted to the empty string. If it
15976 is not a string, an error is raised. Also raise an error on
15977 invalid property names.
15979 PROPERTY can be any regular property (see
15980 `org-special-properties'). It can also be \"TODO\",
15981 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15983 For the last two properties, VALUE may have any of the special
15984 values \"earlier\" and \"later\". The function then increases or
15985 decreases scheduled or deadline date by one day."
15986 (cond ((null value) (setq value ""))
15987 ((not (stringp value)) (error "Properties values should be strings"))
15988 ((not (org--valid-property-p property))
15989 (user-error "Invalid property name: \"%s\"" property)))
15990 (org-with-point-at pom
15991 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15992 (org-back-to-heading t)
15993 (org-with-limited-levels (org-back-to-heading t)))
15994 (let ((beg (point)))
15995 (cond
15996 ((equal property "TODO")
15997 (cond ((not (org-string-nw-p value)) (setq value 'none))
15998 ((not (member value org-todo-keywords-1))
15999 (user-error "\"%s\" is not a valid TODO state" value)))
16000 (org-todo value)
16001 (org-set-tags nil 'align))
16002 ((equal property "PRIORITY")
16003 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16004 (org-set-tags nil 'align))
16005 ((equal property "SCHEDULED")
16006 (forward-line)
16007 (if (and (looking-at-p org-planning-line-re)
16008 (re-search-forward
16009 org-scheduled-time-regexp (line-end-position) t))
16010 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16011 ((string= value "later") (org-timestamp-change 1 'day))
16012 ((string= value "") (org-schedule '(4)))
16013 (t (org-schedule nil value)))
16014 (if (member value '("earlier" "later" ""))
16015 (call-interactively #'org-schedule)
16016 (org-schedule nil value))))
16017 ((equal property "DEADLINE")
16018 (forward-line)
16019 (if (and (looking-at-p org-planning-line-re)
16020 (re-search-forward
16021 org-deadline-time-regexp (line-end-position) t))
16022 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16023 ((string= value "later") (org-timestamp-change 1 'day))
16024 ((string= value "") (org-deadline '(4)))
16025 (t (org-deadline nil value)))
16026 (if (member value '("earlier" "later" ""))
16027 (call-interactively #'org-deadline)
16028 (org-deadline nil value))))
16029 ((member property org-special-properties)
16030 (error "The %s property cannot be set with `org-entry-put'" property))
16032 (let* ((range (org-get-property-block beg 'force))
16033 (end (cdr range))
16034 (case-fold-search t))
16035 (goto-char (car range))
16036 (if (re-search-forward (org-re-property property nil t) end t)
16037 (progn (delete-region (match-beginning 0) (match-end 0))
16038 (goto-char (match-beginning 0)))
16039 (goto-char end)
16040 (insert "\n")
16041 (backward-char))
16042 (insert ":" property ":")
16043 (when value (insert " " value))
16044 (org-indent-line)))))
16045 (run-hook-with-args 'org-property-changed-functions property value)))
16047 (defun org-buffer-property-keys
16048 (&optional specials defaults columns ignore-malformed)
16049 "Get all property keys in the current buffer.
16051 When SPECIALS is non-nil, also list the special properties that
16052 reflect things like tags and TODO state.
16054 When DEFAULTS is non-nil, also include properties that has
16055 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16056 DESCRIPTION, LOCATION, and LOGGING and others.
16058 When COLUMNS in non-nil, also include property names given in
16059 COLUMN formats in the current buffer.
16061 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16062 automatically performed, such drawers will be silently ignored."
16063 (let ((case-fold-search t)
16064 (props (append
16065 (and specials org-special-properties)
16066 (and defaults (cons org-effort-property org-default-properties))
16067 nil)))
16068 (org-with-wide-buffer
16069 (goto-char (point-min))
16070 (while (re-search-forward org-property-start-re nil t)
16071 (let ((range (org-get-property-block)))
16072 (catch 'skip
16073 (unless range
16074 (when (and (not ignore-malformed)
16075 (not (org-before-first-heading-p))
16076 (y-or-n-p (format "Malformed drawer at %d, repair?"
16077 (line-beginning-position))))
16078 (org-get-property-block nil t))
16079 (throw 'skip nil))
16080 (goto-char (car range))
16081 (let ((begin (car range))
16082 (end (cdr range)))
16083 ;; Make sure that found property block is not located
16084 ;; before current point, as it would generate an infloop.
16085 ;; It can happen, for example, in the following
16086 ;; situation:
16088 ;; * Headline
16089 ;; :PROPERTIES:
16090 ;; ...
16091 ;; :END:
16092 ;; *************** Inlinetask
16093 ;; #+BEGIN_EXAMPLE
16094 ;; :PROPERTIES:
16095 ;; #+END_EXAMPLE
16097 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16098 (while (< (point) end)
16099 (let ((p (progn (looking-at org-property-re)
16100 (match-string-no-properties 2))))
16101 ;; Only add true property name, not extension symbol.
16102 (push (if (not (string-match-p "\\+\\'" p)) p
16103 (substring p 0 -1))
16104 props))
16105 (forward-line))))
16106 (outline-next-heading)))
16107 (when columns
16108 (goto-char (point-min))
16109 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16110 (let ((element (org-element-at-point)))
16111 (when (memq (org-element-type element) '(keyword node-property))
16112 (let ((value (org-element-property :value element))
16113 (start 0))
16114 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16115 \\(?:{[^}]+}\\)?"
16116 value start)
16117 (setq start (match-end 0))
16118 (let ((p (match-string-no-properties 1 value)))
16119 (unless (member-ignore-case p org-special-properties)
16120 (push p props))))))))))
16121 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16123 (defun org-property-values (key)
16124 "List all non-nil values of property KEY in current buffer."
16125 (org-with-wide-buffer
16126 (goto-char (point-min))
16127 (let ((case-fold-search t)
16128 (re (org-re-property key))
16129 values)
16130 (while (re-search-forward re nil t)
16131 (push (org-entry-get (point) key) values))
16132 (delete-dups values))))
16134 (defun org-insert-property-drawer ()
16135 "Insert a property drawer into the current entry."
16136 (org-with-wide-buffer
16137 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16138 (org-back-to-heading t)
16139 (org-with-limited-levels (org-back-to-heading t)))
16140 (forward-line)
16141 (when (looking-at-p org-planning-line-re) (forward-line))
16142 (unless (looking-at-p org-property-drawer-re)
16143 ;; Make sure we start editing a line from current entry, not from
16144 ;; next one. It prevents extending text properties or overlays
16145 ;; belonging to the latter.
16146 (when (bolp) (backward-char))
16147 (let ((begin (1+ (point)))
16148 (inhibit-read-only t))
16149 (insert "\n:PROPERTIES:\n:END:")
16150 (when (eobp) (insert "\n"))
16151 (org-indent-region begin (point))))))
16153 (defun org-insert-drawer (&optional arg drawer)
16154 "Insert a drawer at point.
16156 When optional argument ARG is non-nil, insert a property drawer.
16158 Optional argument DRAWER, when non-nil, is a string representing
16159 drawer's name. Otherwise, the user is prompted for a name.
16161 If a region is active, insert the drawer around that region
16162 instead.
16164 Point is left between drawer's boundaries."
16165 (interactive "P")
16166 (let* ((drawer (if arg "PROPERTIES"
16167 (or drawer (read-from-minibuffer "Drawer: ")))))
16168 (cond
16169 ;; With C-u, fall back on `org-insert-property-drawer'
16170 (arg (org-insert-property-drawer))
16171 ;; Check validity of suggested drawer's name.
16172 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16173 (user-error "Invalid drawer name"))
16174 ;; With an active region, insert a drawer at point.
16175 ((not (org-region-active-p))
16176 (progn
16177 (unless (bolp) (insert "\n"))
16178 (insert (format ":%s:\n\n:END:\n" drawer))
16179 (forward-line -2)))
16180 ;; Otherwise, insert the drawer at point
16182 (let ((rbeg (region-beginning))
16183 (rend (copy-marker (region-end))))
16184 (unwind-protect
16185 (progn
16186 (goto-char rbeg)
16187 (beginning-of-line)
16188 (when (save-excursion
16189 (re-search-forward org-outline-regexp-bol rend t))
16190 (user-error "Drawers cannot contain headlines"))
16191 ;; Position point at the beginning of the first
16192 ;; non-blank line in region. Insert drawer's opening
16193 ;; there, then indent it.
16194 (org-skip-whitespace)
16195 (beginning-of-line)
16196 (insert ":" drawer ":\n")
16197 (forward-line -1)
16198 (indent-for-tab-command)
16199 ;; Move point to the beginning of the first blank line
16200 ;; after the last non-blank line in region. Insert
16201 ;; drawer's closing, then indent it.
16202 (goto-char rend)
16203 (skip-chars-backward " \r\t\n")
16204 (insert "\n:END:")
16205 (deactivate-mark t)
16206 (indent-for-tab-command)
16207 (unless (eolp) (insert "\n")))
16208 ;; Clear marker, whatever the outcome of insertion is.
16209 (set-marker rend nil)))))))
16211 (defvar org-property-set-functions-alist nil
16212 "Property set function alist.
16213 Each entry should have the following format:
16215 (PROPERTY . READ-FUNCTION)
16217 The read function will be called with the same argument as
16218 `org-completing-read'.")
16220 (defun org-set-property-function (property)
16221 "Get the function that should be used to set PROPERTY.
16222 This is computed according to `org-property-set-functions-alist'."
16223 (or (cdr (assoc property org-property-set-functions-alist))
16224 'org-completing-read))
16226 (defun org-read-property-value (property)
16227 "Read PROPERTY value from user."
16228 (let* ((completion-ignore-case t)
16229 (allowed (org-property-get-allowed-values nil property 'table))
16230 (cur (org-entry-get nil property))
16231 (prompt (concat property " value"
16232 (if (and cur (string-match "\\S-" cur))
16233 (concat " [" cur "]") "") ": "))
16234 (set-function (org-set-property-function property))
16235 (val (if allowed
16236 (funcall set-function prompt allowed nil
16237 (not (get-text-property 0 'org-unrestricted
16238 (caar allowed))))
16239 (funcall set-function prompt
16240 (mapcar 'list (org-property-values property))
16241 nil nil "" nil cur))))
16242 (org-trim val)))
16244 (defvar org-last-set-property nil)
16245 (defvar org-last-set-property-value nil)
16246 (defun org-read-property-name ()
16247 "Read a property name."
16248 (let ((completion-ignore-case t)
16249 (default-prop (or (and (org-at-property-p)
16250 (match-string-no-properties 2))
16251 org-last-set-property)))
16252 (org-completing-read
16253 (concat "Property"
16254 (if default-prop (concat " [" default-prop "]") "")
16255 ": ")
16256 (mapcar #'list (org-buffer-property-keys nil t t))
16257 nil nil nil nil default-prop)))
16259 (defun org-set-property-and-value (use-last)
16260 "Allow to set [PROPERTY]: [value] direction from prompt.
16261 When use-default, don't even ask, just use the last
16262 \"[PROPERTY]: [value]\" string from the history."
16263 (interactive "P")
16264 (let* ((completion-ignore-case t)
16265 (pv (or (and use-last org-last-set-property-value)
16266 (org-completing-read
16267 "Enter a \"[Property]: [value]\" pair: "
16268 nil nil nil nil nil
16269 org-last-set-property-value)))
16270 prop val)
16271 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16272 (setq prop (match-string 1 pv)
16273 val (match-string 2 pv))
16274 (org-set-property prop val))))
16276 (defun org-set-property (property value)
16277 "In the current entry, set PROPERTY to VALUE.
16279 When called interactively, this will prompt for a property name, offering
16280 completion on existing and default properties. And then it will prompt
16281 for a value, offering completion either on allowed values (via an inherited
16282 xxx_ALL property) or on existing values in other instances of this property
16283 in the current file.
16285 Throw an error when trying to set a property with an invalid name."
16286 (interactive (list nil nil))
16287 (let ((property (or property (org-read-property-name))))
16288 ;; `org-entry-put' also makes the following check, but this one
16289 ;; avoids polluting `org-last-set-property' and
16290 ;; `org-last-set-property-value' needlessly.
16291 (unless (org--valid-property-p property)
16292 (user-error "Invalid property name: \"%s\"" property))
16293 (let ((value (or value (org-read-property-value property)))
16294 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16295 (setq org-last-set-property property)
16296 (setq org-last-set-property-value (concat property ": " value))
16297 ;; Possibly postprocess the inserted value:
16298 (when fn (setq value (funcall fn value)))
16299 (unless (equal (org-entry-get nil property) value)
16300 (org-entry-put nil property value)))))
16302 (defun org-find-property (property &optional value)
16303 "Find first entry in buffer that sets PROPERTY.
16305 When optional argument VALUE is non-nil, only consider an entry
16306 if it contains PROPERTY set to this value. If PROPERTY should be
16307 explicitly set to nil, use string \"nil\" for VALUE.
16309 Return position where the entry begins, or nil if there is no
16310 such entry. If narrowing is in effect, only search the visible
16311 part of the buffer."
16312 (save-excursion
16313 (goto-char (point-min))
16314 (let ((case-fold-search t)
16315 (re (org-re-property property nil (not value) value)))
16316 (catch 'exit
16317 (while (re-search-forward re nil t)
16318 (when (if value (org-at-property-p)
16319 (org-entry-get (point) property nil t))
16320 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16322 (defun org-delete-property (property)
16323 "In the current entry, delete PROPERTY."
16324 (interactive
16325 (let* ((completion-ignore-case t)
16326 (cat (org-entry-get (point) "CATEGORY"))
16327 (props0 (org-entry-properties nil 'standard))
16328 (props (if cat props0
16329 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16330 (prop (if (< 1 (length props))
16331 (completing-read "Property: " props nil t)
16332 (caar props))))
16333 (list prop)))
16334 (if (not property)
16335 (message "No property to delete in this entry")
16336 (org-entry-delete nil property)
16337 (message "Property \"%s\" deleted" property)))
16339 (defun org-delete-property-globally (property)
16340 "Remove PROPERTY globally, from all entries.
16341 This function ignores narrowing, if any."
16342 (interactive
16343 (let* ((completion-ignore-case t)
16344 (prop (completing-read
16345 "Globally remove property: "
16346 (mapcar #'list (org-buffer-property-keys)))))
16347 (list prop)))
16348 (org-with-wide-buffer
16349 (goto-char (point-min))
16350 (let ((count 0)
16351 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16352 (while (re-search-forward re nil t)
16353 (when (org-entry-delete (point) property) (cl-incf count)))
16354 (message "Property \"%s\" removed from %d entries" property count))))
16356 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16358 (defun org-compute-property-at-point ()
16359 "Compute the property at point.
16360 This looks for an enclosing column format, extracts the operator and
16361 then applies it to the property in the column format's scope."
16362 (interactive)
16363 (unless (org-at-property-p)
16364 (user-error "Not at a property"))
16365 (let ((prop (match-string-no-properties 2)))
16366 (org-columns-get-format-and-top-level)
16367 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16368 (user-error "No operator defined for property %s" prop))
16369 (org-columns-compute prop)))
16371 (defvar org-property-allowed-value-functions nil
16372 "Hook for functions supplying allowed values for a specific property.
16373 The functions must take a single argument, the name of the property, and
16374 return a flat list of allowed values. If \":ETC\" is one of
16375 the values, this means that these values are intended as defaults for
16376 completion, but that other values should be allowed too.
16377 The functions must return nil if they are not responsible for this
16378 property.")
16380 (defun org-property-get-allowed-values (pom property &optional table)
16381 "Get allowed values for the property PROPERTY.
16382 When TABLE is non-nil, return an alist that can directly be used for
16383 completion."
16384 (let (vals)
16385 (cond
16386 ((equal property "TODO")
16387 (setq vals (org-with-point-at pom
16388 (append org-todo-keywords-1 '("")))))
16389 ((equal property "PRIORITY")
16390 (let ((n org-lowest-priority))
16391 (while (>= n org-highest-priority)
16392 (push (char-to-string n) vals)
16393 (setq n (1- n)))))
16394 ((equal property "CATEGORY"))
16395 ((member property org-special-properties))
16396 ((setq vals (run-hook-with-args-until-success
16397 'org-property-allowed-value-functions property)))
16399 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16400 (when (and vals (string-match "\\S-" vals))
16401 (setq vals (car (read-from-string (concat "(" vals ")"))))
16402 (setq vals (mapcar (lambda (x)
16403 (cond ((stringp x) x)
16404 ((numberp x) (number-to-string x))
16405 ((symbolp x) (symbol-name x))
16406 (t "???")))
16407 vals)))))
16408 (when (member ":ETC" vals)
16409 (setq vals (remove ":ETC" vals))
16410 (org-add-props (car vals) '(org-unrestricted t)))
16411 (if table (mapcar 'list vals) vals)))
16413 (defun org-property-previous-allowed-value (&optional _previous)
16414 "Switch to the next allowed value for this property."
16415 (interactive)
16416 (org-property-next-allowed-value t))
16418 (defun org-property-next-allowed-value (&optional previous)
16419 "Switch to the next allowed value for this property."
16420 (interactive)
16421 (unless (org-at-property-p)
16422 (user-error "Not at a property"))
16423 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16424 (key (match-string 2))
16425 (value (match-string 3))
16426 (allowed (or (org-property-get-allowed-values (point) key)
16427 (and (member value '("[ ]" "[-]" "[X]"))
16428 '("[ ]" "[X]"))))
16429 (heading (save-match-data (nth 4 (org-heading-components))))
16430 nval)
16431 (unless allowed
16432 (user-error "Allowed values for this property have not been defined"))
16433 (when previous (setq allowed (reverse allowed)))
16434 (when (member value allowed)
16435 (setq nval (car (cdr (member value allowed)))))
16436 (setq nval (or nval (car allowed)))
16437 (when (equal nval value)
16438 (user-error "Only one allowed value for this property"))
16439 (org-at-property-p)
16440 (replace-match (concat " :" key ": " nval) t t)
16441 (org-indent-line)
16442 (beginning-of-line 1)
16443 (skip-chars-forward " \t")
16444 (when (equal prop org-effort-property)
16445 (org-refresh-property
16446 '((effort . identity)
16447 (effort-minutes . org-duration-to-minutes))
16448 nval)
16449 (when (string= org-clock-current-task heading)
16450 (setq org-clock-effort nval)
16451 (org-clock-update-mode-line)))
16452 (run-hook-with-args 'org-property-changed-functions key nval)))
16454 (defun org-find-olp (path &optional this-buffer)
16455 "Return a marker pointing to the entry at outline path OLP.
16456 If anything goes wrong, throw an error.
16457 You can wrap this call to catch the error like this:
16459 (condition-case msg
16460 (org-mobile-locate-entry (match-string 4))
16461 (error (nth 1 msg)))
16463 The return value will then be either a string with the error message,
16464 or a marker if everything is OK.
16466 If THIS-BUFFER is set, the outline path does not contain a file,
16467 only headings."
16468 (let* ((file (if this-buffer buffer-file-name (pop path)))
16469 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16470 (level 1)
16471 (lmin 1)
16472 (lmax 1)
16473 end found flevel)
16474 (unless buffer (error "File not found :%s" file))
16475 (with-current-buffer buffer
16476 (unless (derived-mode-p 'org-mode)
16477 (error "Buffer %s needs to be in Org mode" buffer))
16478 (org-with-wide-buffer
16479 (goto-char (point-min))
16480 (dolist (heading path)
16481 (let ((re (format org-complex-heading-regexp-format
16482 (regexp-quote heading)))
16483 (cnt 0))
16484 (while (re-search-forward re end t)
16485 (setq level (- (match-end 1) (match-beginning 1)))
16486 (when (and (>= level lmin) (<= level lmax))
16487 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16488 (when (= cnt 0)
16489 (error "Heading not found on level %d: %s" lmax heading))
16490 (when (> cnt 1)
16491 (error "Heading not unique on level %d: %s" lmax heading))
16492 (goto-char found)
16493 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16494 (setq end (save-excursion (org-end-of-subtree t t)))))
16495 (when (org-at-heading-p)
16496 (point-marker))))))
16498 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16499 "Find node HEADING in BUFFER.
16500 Return a marker to the heading if it was found, or nil if not.
16501 If POS-ONLY is set, return just the position instead of a marker.
16503 The heading text must match exact, but it may have a TODO keyword,
16504 a priority cookie and tags in the standard locations."
16505 (with-current-buffer (or buffer (current-buffer))
16506 (org-with-wide-buffer
16507 (goto-char (point-min))
16508 (let (case-fold-search)
16509 (when (re-search-forward
16510 (format org-complex-heading-regexp-format
16511 (regexp-quote heading)) nil t)
16512 (if pos-only
16513 (match-beginning 0)
16514 (move-marker (make-marker) (match-beginning 0))))))))
16516 (defun org-find-exact-heading-in-directory (heading &optional dir)
16517 "Find Org node headline HEADING in all \".org\" files in directory DIR.
16518 When the target headline is found, return a marker to this location."
16519 (let ((files (directory-files (or dir default-directory)
16520 t "\\`[^.#].*\\.org\\'"))
16521 visiting m buffer)
16522 (catch 'found
16523 (dolist (file files)
16524 (message "trying %s" file)
16525 (setq visiting (org-find-base-buffer-visiting file))
16526 (setq buffer (or visiting (find-file-noselect file)))
16527 (setq m (org-find-exact-headline-in-buffer
16528 heading buffer))
16529 (when (and (not m) (not visiting)) (kill-buffer buffer))
16530 (and m (throw 'found m))))))
16532 (defun org-find-entry-with-id (ident)
16533 "Locate the entry that contains the ID property with exact value IDENT.
16534 IDENT can be a string, a symbol or a number, this function will search for
16535 the string representation of it.
16536 Return the position where this entry starts, or nil if there is no such entry."
16537 (interactive "sID: ")
16538 (let ((id (cond
16539 ((stringp ident) ident)
16540 ((symbolp ident) (symbol-name ident))
16541 ((numberp ident) (number-to-string ident))
16542 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16543 (org-with-wide-buffer (org-find-property "ID" id))))
16545 ;;;; Timestamps
16547 (defvar org-last-changed-timestamp nil)
16548 (defvar org-last-inserted-timestamp nil
16549 "The last time stamp inserted with `org-insert-time-stamp'.")
16551 (defun org-time-stamp (arg &optional inactive)
16552 "Prompt for a date/time and insert a time stamp.
16554 If the user specifies a time like HH:MM or if this command is
16555 called with at least one prefix argument, the time stamp contains
16556 the date and the time. Otherwise, only the date is included.
16558 All parts of a date not specified by the user are filled in from
16559 the timestamp at point, if any, or the current date/time
16560 otherwise.
16562 If there is already a timestamp at the cursor, it is replaced.
16564 With two universal prefix arguments, insert an active timestamp
16565 with the current time without prompting the user.
16567 When called from lisp, the timestamp is inactive if INACTIVE is
16568 non-nil."
16569 (interactive "P")
16570 (let* ((ts (cond
16571 ((org-at-date-range-p t)
16572 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16573 ((org-at-timestamp-p 'lax) (match-string 0))))
16574 ;; Default time is either the timestamp at point or today.
16575 ;; When entering a range, only the range start is considered.
16576 (default-time (if (not ts) (current-time)
16577 (apply #'encode-time (org-parse-time-string ts))))
16578 (default-input (and ts (org-get-compact-tod ts)))
16579 (repeater (and ts
16580 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16581 (match-string 0 ts)))
16582 org-time-was-given
16583 org-end-time-was-given
16584 (time
16585 (and (if (equal arg '(16)) (current-time)
16586 ;; Preserve `this-command' and `last-command'.
16587 (let ((this-command this-command)
16588 (last-command last-command))
16589 (org-read-date
16590 arg 'totime nil nil default-time default-input
16591 inactive))))))
16592 (cond
16593 ((and ts
16594 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16595 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16596 (insert "--")
16597 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16599 ;; Make sure we're on a timestamp. When in the middle of a date
16600 ;; range, move arbitrarily to range end.
16601 (unless (org-at-timestamp-p 'lax)
16602 (skip-chars-forward "-")
16603 (org-at-timestamp-p 'lax))
16604 (replace-match "")
16605 (setq org-last-changed-timestamp
16606 (org-insert-time-stamp
16607 time (or org-time-was-given arg)
16608 inactive nil nil (list org-end-time-was-given)))
16609 (when repeater
16610 (backward-char)
16611 (insert " " repeater)
16612 (setq org-last-changed-timestamp
16613 (concat (substring org-last-inserted-timestamp 0 -1)
16614 " " repeater ">")))
16615 (message "Timestamp updated"))
16616 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16617 (t (org-insert-time-stamp
16618 time (or org-time-was-given arg) inactive nil nil
16619 (list org-end-time-was-given))))))
16621 ;; FIXME: can we use this for something else, like computing time differences?
16622 (defun org-get-compact-tod (s)
16623 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16624 (let* ((t1 (match-string 1 s))
16625 (h1 (string-to-number (match-string 2 s)))
16626 (m1 (string-to-number (match-string 3 s)))
16627 (t2 (and (match-end 4) (match-string 5 s)))
16628 (h2 (and t2 (string-to-number (match-string 6 s))))
16629 (m2 (and t2 (string-to-number (match-string 7 s))))
16630 dh dm)
16631 (if (not t2)
16633 (setq dh (- h2 h1) dm (- m2 m1))
16634 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16635 (concat t1 "+" (number-to-string dh)
16636 (and (/= 0 dm) (format ":%02d" dm)))))))
16638 (defun org-time-stamp-inactive (&optional arg)
16639 "Insert an inactive time stamp.
16640 An inactive time stamp is enclosed in square brackets instead of angle
16641 brackets. It is inactive in the sense that it does not trigger agenda entries,
16642 does not link to the calendar and cannot be changed with the S-cursor keys.
16643 So these are more for recording a certain time/date."
16644 (interactive "P")
16645 (org-time-stamp arg 'inactive))
16647 (defvar org-date-ovl (make-overlay 1 1))
16648 (overlay-put org-date-ovl 'face 'org-date-selected)
16649 (delete-overlay org-date-ovl)
16651 (defvar org-ans1) ; dynamically scoped parameter
16652 (defvar org-ans2) ; dynamically scoped parameter
16654 (defvar org-plain-time-of-day-regexp) ; defined below
16656 (defvar org-overriding-default-time nil) ; dynamically scoped
16657 (defvar org-read-date-overlay nil)
16658 (defvar org-dcst nil) ; dynamically scoped
16659 (defvar org-read-date-history nil)
16660 (defvar org-read-date-final-answer nil)
16661 (defvar org-read-date-analyze-futurep nil)
16662 (defvar org-read-date-analyze-forced-year nil)
16663 (defvar org-read-date-inactive)
16665 (defvar org-read-date-minibuffer-local-map
16666 (let* ((map (make-sparse-keymap)))
16667 (set-keymap-parent map minibuffer-local-map)
16668 (org-defkey map (kbd ".")
16669 (lambda () (interactive)
16670 ;; Are we at the beginning of the prompt?
16671 (if (looking-back "^[^:]+: "
16672 (let ((inhibit-field-text-motion t))
16673 (line-beginning-position)))
16674 (org-eval-in-calendar '(calendar-goto-today))
16675 (insert "."))))
16676 (org-defkey map (kbd "C-.")
16677 (lambda () (interactive)
16678 (org-eval-in-calendar '(calendar-goto-today))))
16679 (org-defkey map [(meta shift left)]
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(calendar-backward-month 1))))
16682 (org-defkey map [(meta shift right)]
16683 (lambda () (interactive)
16684 (org-eval-in-calendar '(calendar-forward-month 1))))
16685 (org-defkey map [(meta shift up)]
16686 (lambda () (interactive)
16687 (org-eval-in-calendar '(calendar-backward-year 1))))
16688 (org-defkey map [(meta shift down)]
16689 (lambda () (interactive)
16690 (org-eval-in-calendar '(calendar-forward-year 1))))
16691 (org-defkey map [?\e (shift left)]
16692 (lambda () (interactive)
16693 (org-eval-in-calendar '(calendar-backward-month 1))))
16694 (org-defkey map [?\e (shift right)]
16695 (lambda () (interactive)
16696 (org-eval-in-calendar '(calendar-forward-month 1))))
16697 (org-defkey map [?\e (shift up)]
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(calendar-backward-year 1))))
16700 (org-defkey map [?\e (shift down)]
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-forward-year 1))))
16703 (org-defkey map [(shift up)]
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(calendar-backward-week 1))))
16706 (org-defkey map [(shift down)]
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-forward-week 1))))
16709 (org-defkey map [(shift left)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-day 1))))
16712 (org-defkey map [(shift right)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-day 1))))
16715 (org-defkey map "!"
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(diary-view-entries))
16718 (message "")))
16719 (org-defkey map ">"
16720 (lambda () (interactive)
16721 (org-eval-in-calendar '(calendar-scroll-left 1))))
16722 (org-defkey map "<"
16723 (lambda () (interactive)
16724 (org-eval-in-calendar '(calendar-scroll-right 1))))
16725 (org-defkey map "\C-v"
16726 (lambda () (interactive)
16727 (org-eval-in-calendar
16728 '(calendar-scroll-left-three-months 1))))
16729 (org-defkey map "\M-v"
16730 (lambda () (interactive)
16731 (org-eval-in-calendar
16732 '(calendar-scroll-right-three-months 1))))
16733 map)
16734 "Keymap for minibuffer commands when using `org-read-date'.")
16736 (defvar org-def)
16737 (defvar org-defdecode)
16738 (defvar org-with-time)
16740 (defvar calendar-setup) ; Dynamically scoped.
16741 (defun org-read-date (&optional with-time to-time from-string prompt
16742 default-time default-input inactive)
16743 "Read a date, possibly a time, and make things smooth for the user.
16744 The prompt will suggest to enter an ISO date, but you can also enter anything
16745 which will at least partially be understood by `parse-time-string'.
16746 Unrecognized parts of the date will default to the current day, month, year,
16747 hour and minute. If this command is called to replace a timestamp at point,
16748 or to enter the second timestamp of a range, the default time is taken
16749 from the existing stamp. Furthermore, the command prefers the future,
16750 so if you are giving a date where the year is not given, and the day-month
16751 combination is already past in the current year, it will assume you
16752 mean next year. For details, see the manual. A few examples:
16754 3-2-5 --> 2003-02-05
16755 feb 15 --> currentyear-02-15
16756 2/15 --> currentyear-02-15
16757 sep 12 9 --> 2009-09-12
16758 12:45 --> today 12:45
16759 22 sept 0:34 --> currentyear-09-22 0:34
16760 12 --> currentyear-currentmonth-12
16761 Fri --> nearest Friday after today
16762 -Tue --> last Tuesday
16763 etc.
16765 Furthermore you can specify a relative date by giving, as the *first* thing
16766 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16767 change in days weeks, months, years.
16768 With a single plus or minus, the date is relative to today. With a double
16769 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16770 +4d --> four days from today
16771 +4 --> same as above
16772 +2w --> two weeks from today
16773 ++5 --> five days from default date
16775 The function understands only English month and weekday abbreviations.
16777 While prompting, a calendar is popped up - you can also select the
16778 date with the mouse (button 1). The calendar shows a period of three
16779 months. To scroll it to other months, use the keys `>' and `<'.
16780 If you don't like the calendar, turn it off with
16781 (setq org-read-date-popup-calendar nil)
16783 With optional argument TO-TIME, the date will immediately be converted
16784 to an internal time.
16785 With an optional argument WITH-TIME, the prompt will suggest to
16786 also insert a time. Note that when WITH-TIME is not set, you can
16787 still enter a time, and this function will inform the calling routine
16788 about this change. The calling routine may then choose to change the
16789 format used to insert the time stamp into the buffer to include the time.
16790 With optional argument FROM-STRING, read from this string instead from
16791 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16792 the time/date that is used for everything that is not specified by the
16793 user."
16794 (require 'parse-time)
16795 (let* ((org-with-time with-time)
16796 (org-time-stamp-rounding-minutes
16797 (if (equal org-with-time '(16))
16798 '(0 0)
16799 org-time-stamp-rounding-minutes))
16800 (org-dcst org-display-custom-times)
16801 (ct (org-current-time))
16802 (org-def (or org-overriding-default-time default-time ct))
16803 (org-defdecode (decode-time org-def))
16804 (cur-frame (selected-frame))
16805 (mouse-autoselect-window nil) ; Don't let the mouse jump
16806 (calendar-setup
16807 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16808 (calendar-move-hook nil)
16809 (calendar-view-diary-initially-flag nil)
16810 (calendar-view-holidays-initially-flag nil)
16811 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16812 ;; Rationalize `org-def' and `org-defdecode', if required.
16813 (when (< (nth 2 org-defdecode) org-extend-today-until)
16814 (setf (nth 2 org-defdecode) -1)
16815 (setf (nth 1 org-defdecode) 59)
16816 (setq org-def (apply #'encode-time org-defdecode))
16817 (setq org-defdecode (decode-time org-def)))
16818 (let* ((timestr (format-time-string
16819 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16820 org-def))
16821 (prompt (concat (if prompt (concat prompt " ") "")
16822 (format "Date+time [%s]: " timestr))))
16823 (cond
16824 (from-string (setq ans from-string))
16825 (org-read-date-popup-calendar
16826 (save-excursion
16827 (save-window-excursion
16828 (calendar)
16829 (when (eq calendar-setup 'calendar-only)
16830 (setq cal-frame
16831 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16832 (select-frame cal-frame))
16833 (org-eval-in-calendar '(setq cursor-type nil) t)
16834 (unwind-protect
16835 (progn
16836 (calendar-forward-day (- (time-to-days org-def)
16837 (calendar-absolute-from-gregorian
16838 (calendar-current-date))))
16839 (org-eval-in-calendar nil t)
16840 (let* ((old-map (current-local-map))
16841 (map (copy-keymap calendar-mode-map))
16842 (minibuffer-local-map
16843 (copy-keymap org-read-date-minibuffer-local-map)))
16844 (org-defkey map (kbd "RET") 'org-calendar-select)
16845 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16846 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16847 (unwind-protect
16848 (progn
16849 (use-local-map map)
16850 (setq org-read-date-inactive inactive)
16851 (add-hook 'post-command-hook 'org-read-date-display)
16852 (setq org-ans0
16853 (read-string prompt
16854 default-input
16855 'org-read-date-history
16856 nil))
16857 ;; org-ans0: from prompt
16858 ;; org-ans1: from mouse click
16859 ;; org-ans2: from calendar motion
16860 (setq ans
16861 (concat org-ans0 " " (or org-ans1 org-ans2))))
16862 (remove-hook 'post-command-hook 'org-read-date-display)
16863 (use-local-map old-map)
16864 (when org-read-date-overlay
16865 (delete-overlay org-read-date-overlay)
16866 (setq org-read-date-overlay nil)))))
16867 (bury-buffer "*Calendar*")
16868 (when cal-frame
16869 (delete-frame cal-frame)
16870 (select-frame-set-input-focus cur-frame))))))
16872 (t ; Naked prompt only
16873 (unwind-protect
16874 (setq ans (read-string prompt default-input
16875 'org-read-date-history timestr))
16876 (when org-read-date-overlay
16877 (delete-overlay org-read-date-overlay)
16878 (setq org-read-date-overlay nil))))))
16880 (setq final (org-read-date-analyze ans org-def org-defdecode))
16882 (when org-read-date-analyze-forced-year
16883 (message "Year was forced into %s"
16884 (if org-read-date-force-compatible-dates
16885 "compatible range (1970-2037)"
16886 "range representable on this machine"))
16887 (ding))
16889 ;; One round trip to get rid of 34th of August and stuff like that....
16890 (setq final (decode-time (apply 'encode-time final)))
16892 (setq org-read-date-final-answer ans)
16894 (if to-time
16895 (apply 'encode-time final)
16896 (if (and (boundp 'org-time-was-given) org-time-was-given)
16897 (format "%04d-%02d-%02d %02d:%02d"
16898 (nth 5 final) (nth 4 final) (nth 3 final)
16899 (nth 2 final) (nth 1 final))
16900 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16902 (defun org-read-date-display ()
16903 "Display the current date prompt interpretation in the minibuffer."
16904 (when org-read-date-display-live
16905 (when org-read-date-overlay
16906 (delete-overlay org-read-date-overlay))
16907 (when (minibufferp (current-buffer))
16908 (save-excursion
16909 (end-of-line 1)
16910 (while (not (equal (buffer-substring
16911 (max (point-min) (- (point) 4)) (point))
16912 " "))
16913 (insert " ")))
16914 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16915 " " (or org-ans1 org-ans2)))
16916 (org-end-time-was-given nil)
16917 (f (org-read-date-analyze ans org-def org-defdecode))
16918 (fmts (if org-dcst
16919 org-time-stamp-custom-formats
16920 org-time-stamp-formats))
16921 (fmt (if (or org-with-time
16922 (and (boundp 'org-time-was-given) org-time-was-given))
16923 (cdr fmts)
16924 (car fmts)))
16925 (txt (format-time-string fmt (apply 'encode-time f)))
16926 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16927 (txt (concat "=> " txt)))
16928 (when (and org-end-time-was-given
16929 (string-match org-plain-time-of-day-regexp txt))
16930 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16931 org-end-time-was-given
16932 (substring txt (match-end 0)))))
16933 (when org-read-date-analyze-futurep
16934 (setq txt (concat txt " (=>F)")))
16935 (setq org-read-date-overlay
16936 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16937 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16939 (defun org-read-date-analyze (ans def defdecode)
16940 "Analyze the combined answer of the date prompt."
16941 ;; FIXME: cleanup and comment
16942 ;; Pass `current-time' result to `decode-time' (instead of calling
16943 ;; without arguments) so that only `current-time' has to be
16944 ;; overridden in tests.
16945 (let ((org-def def)
16946 (org-defdecode defdecode)
16947 (nowdecode (decode-time (current-time)))
16948 delta deltan deltaw deltadef year month day
16949 hour minute second wday pm h2 m2 tl wday1
16950 iso-year iso-weekday iso-week iso-date futurep kill-year)
16951 (setq org-read-date-analyze-futurep nil
16952 org-read-date-analyze-forced-year nil)
16953 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16954 (setq ans "+0"))
16956 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16957 (setq ans (replace-match "" t t ans)
16958 deltan (car delta)
16959 deltaw (nth 1 delta)
16960 deltadef (nth 2 delta)))
16962 ;; Check if there is an iso week date in there. If yes, store the
16963 ;; info and postpone interpreting it until the rest of the parsing
16964 ;; is done.
16965 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16966 (setq iso-year (when (match-end 1)
16967 (org-small-year-to-year
16968 (string-to-number (match-string 1 ans))))
16969 iso-weekday (when (match-end 3)
16970 (string-to-number (match-string 3 ans)))
16971 iso-week (string-to-number (match-string 2 ans)))
16972 (setq ans (replace-match "" t t ans)))
16974 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16975 (when (string-match
16976 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16977 (setq year (if (match-end 2)
16978 (string-to-number (match-string 2 ans))
16979 (progn (setq kill-year t)
16980 (string-to-number (format-time-string "%Y"))))
16981 month (string-to-number (match-string 3 ans))
16982 day (string-to-number (match-string 4 ans)))
16983 (setq year (org-small-year-to-year year))
16984 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16985 t nil ans)))
16987 ;; Help matching dotted european dates
16988 (when (string-match
16989 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16990 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16991 (setq kill-year t)
16992 (string-to-number (format-time-string "%Y")))
16993 day (string-to-number (match-string 1 ans))
16994 month (string-to-number (match-string 2 ans))
16995 ans (replace-match (format "%04d-%02d-%02d" year month day)
16996 t nil ans)))
16998 ;; Help matching american dates, like 5/30 or 5/30/7
16999 (when (string-match
17000 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17001 (setq year (if (match-end 4)
17002 (string-to-number (match-string 4 ans))
17003 (progn (setq kill-year t)
17004 (string-to-number (format-time-string "%Y"))))
17005 month (string-to-number (match-string 1 ans))
17006 day (string-to-number (match-string 2 ans)))
17007 (setq year (org-small-year-to-year year))
17008 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17009 t nil ans)))
17010 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17011 ;; If there is a time with am/pm, and *no* time without it, we convert
17012 ;; so that matching will be successful.
17013 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17014 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17015 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17016 (setq hour (string-to-number (match-string 1 ans))
17017 minute (if (match-end 3)
17018 (string-to-number (match-string 3 ans))
17020 pm (equal ?p
17021 (string-to-char (downcase (match-string 4 ans)))))
17022 (if (and (= hour 12) (not pm))
17023 (setq hour 0)
17024 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17025 (setq ans (replace-match (format "%02d:%02d" hour minute)
17026 t t ans))))
17028 ;; Check if a time range is given as a duration
17029 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17030 (setq hour (string-to-number (match-string 1 ans))
17031 h2 (+ hour (string-to-number (match-string 3 ans)))
17032 minute (string-to-number (match-string 2 ans))
17033 m2 (+ minute (if (match-end 5) (string-to-number
17034 (match-string 5 ans))0)))
17035 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17036 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17037 t t ans)))
17039 ;; Check if there is a time range
17040 (when (boundp 'org-end-time-was-given)
17041 (setq org-time-was-given nil)
17042 (when (and (string-match org-plain-time-of-day-regexp ans)
17043 (match-end 8))
17044 (setq org-end-time-was-given (match-string 8 ans))
17045 (setq ans (concat (substring ans 0 (match-beginning 7))
17046 (substring ans (match-end 7))))))
17048 (setq tl (parse-time-string ans)
17049 day (or (nth 3 tl) (nth 3 org-defdecode))
17050 month
17051 (cond ((nth 4 tl))
17052 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17053 ;; Day was specified. Make sure DAY+MONTH
17054 ;; combination happens in the future.
17055 ((nth 3 tl)
17056 (setq futurep t)
17057 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17058 (nth 4 nowdecode)))
17059 (t (nth 4 org-defdecode)))
17060 year
17061 (cond ((and (not kill-year) (nth 5 tl)))
17062 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17063 ;; Month was guessed in the future and is at least
17064 ;; equal to NOWDECODE's. Fix year accordingly.
17065 (futurep
17066 (if (or (> month (nth 4 nowdecode))
17067 (>= day (nth 3 nowdecode)))
17068 (nth 5 nowdecode)
17069 (1+ (nth 5 nowdecode))))
17070 ;; Month was specified. Make sure MONTH+YEAR
17071 ;; combination happens in the future.
17072 ((nth 4 tl)
17073 (setq futurep t)
17074 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17075 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17076 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17077 (t (nth 5 nowdecode))))
17078 (t (nth 5 org-defdecode)))
17079 hour (or (nth 2 tl) (nth 2 org-defdecode))
17080 minute (or (nth 1 tl) (nth 1 org-defdecode))
17081 second (or (nth 0 tl) 0)
17082 wday (nth 6 tl))
17084 (when (and (eq org-read-date-prefer-future 'time)
17085 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17086 (equal day (nth 3 nowdecode))
17087 (equal month (nth 4 nowdecode))
17088 (equal year (nth 5 nowdecode))
17089 (nth 2 tl)
17090 (or (< (nth 2 tl) (nth 2 nowdecode))
17091 (and (= (nth 2 tl) (nth 2 nowdecode))
17092 (nth 1 tl)
17093 (< (nth 1 tl) (nth 1 nowdecode)))))
17094 (setq day (1+ day)
17095 futurep t))
17097 ;; Special date definitions below
17098 (cond
17099 (iso-week
17100 ;; There was an iso week
17101 (require 'cal-iso)
17102 (setq futurep nil)
17103 (setq year (or iso-year year)
17104 day (or iso-weekday wday 1)
17105 wday nil ; to make sure that the trigger below does not match
17106 iso-date (calendar-gregorian-from-absolute
17107 (calendar-iso-to-absolute
17108 (list iso-week day year))))
17109 ; FIXME: Should we also push ISO weeks into the future?
17110 ; (when (and org-read-date-prefer-future
17111 ; (not iso-year)
17112 ; (< (calendar-absolute-from-gregorian iso-date)
17113 ; (time-to-days (current-time))))
17114 ; (setq year (1+ year)
17115 ; iso-date (calendar-gregorian-from-absolute
17116 ; (calendar-iso-to-absolute
17117 ; (list iso-week day year)))))
17118 (setq month (car iso-date)
17119 year (nth 2 iso-date)
17120 day (nth 1 iso-date)))
17121 (deltan
17122 (setq futurep nil)
17123 (unless deltadef
17124 ;; Pass `current-time' result to `decode-time' (instead of
17125 ;; calling without arguments) so that only `current-time' has
17126 ;; to be overridden in tests.
17127 (let ((now (decode-time (current-time))))
17128 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17129 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17130 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17131 ((equal deltaw "m") (setq month (+ month deltan)))
17132 ((equal deltaw "y") (setq year (+ year deltan)))))
17133 ((and wday (not (nth 3 tl)))
17134 ;; Weekday was given, but no day, so pick that day in the week
17135 ;; on or after the derived date.
17136 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17137 (unless (equal wday wday1)
17138 (setq day (+ day (% (- wday wday1 -7) 7))))))
17139 (when (and (boundp 'org-time-was-given)
17140 (nth 2 tl))
17141 (setq org-time-was-given t))
17142 (when (< year 100) (setq year (+ 2000 year)))
17143 ;; Check of the date is representable
17144 (if org-read-date-force-compatible-dates
17145 (progn
17146 (when (< year 1970)
17147 (setq year 1970 org-read-date-analyze-forced-year t))
17148 (when (> year 2037)
17149 (setq year 2037 org-read-date-analyze-forced-year t)))
17150 (condition-case nil
17151 (ignore (encode-time second minute hour day month year))
17152 (error
17153 (setq year (nth 5 org-defdecode))
17154 (setq org-read-date-analyze-forced-year t))))
17155 (setq org-read-date-analyze-futurep futurep)
17156 (list second minute hour day month year)))
17158 (defvar parse-time-weekdays)
17159 (defun org-read-date-get-relative (s today default)
17160 "Check string S for special relative date string.
17161 TODAY and DEFAULT are internal times, for today and for a default.
17162 Return shift list (N what def-flag)
17163 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17164 N is the number of WHATs to shift.
17165 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17166 the DEFAULT date rather than TODAY."
17167 (require 'parse-time)
17168 (when (and
17169 (string-match
17170 (concat
17171 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17172 "\\([0-9]+\\)?"
17173 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17174 "\\([ \t]\\|$\\)") s)
17175 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17176 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17177 (string-to-char (substring (match-string 1 s) -1))
17178 ?+))
17179 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17180 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17181 (what (if (match-end 3) (match-string 3 s) "d"))
17182 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17183 (date (if rel default today))
17184 (wday (nth 6 (decode-time date)))
17185 delta)
17186 (if wday1
17187 (progn
17188 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17189 (when (= delta 0) (setq delta 7))
17190 (when (= dir ?-)
17191 (setq delta (- delta 7))
17192 (when (= delta 0) (setq delta -7)))
17193 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17194 (list delta "d" rel))
17195 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17197 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17198 "Turn a user-specified date into the internal representation.
17199 The internal representation needed by the calendar is (month day year).
17200 This is a wrapper to handle the brain-dead convention in calendar that
17201 user function argument order change dependent on argument order."
17202 (pcase calendar-date-style
17203 (`american (list arg1 arg2 arg3))
17204 (`european (list arg2 arg1 arg3))
17205 (`iso (list arg2 arg3 arg1))))
17207 (defun org-eval-in-calendar (form &optional keepdate)
17208 "Eval FORM in the calendar window and return to current window.
17209 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17210 (let ((sf (selected-frame))
17211 (sw (selected-window)))
17212 (select-window (get-buffer-window "*Calendar*" t))
17213 (eval form)
17214 (when (and (not keepdate) (calendar-cursor-to-date))
17215 (let* ((date (calendar-cursor-to-date))
17216 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17217 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17218 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17219 (select-window sw)
17220 (select-frame-set-input-focus sf)))
17222 (defun org-calendar-select ()
17223 "Return to `org-read-date' with the date currently selected.
17224 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17225 (interactive)
17226 (when (calendar-cursor-to-date)
17227 (let* ((date (calendar-cursor-to-date))
17228 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17229 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17230 (when (active-minibuffer-window) (exit-minibuffer))))
17232 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17233 "Insert a date stamp for the date given by the internal TIME.
17234 See `format-time-string' for the format of TIME.
17235 WITH-HM means use the stamp format that includes the time of the day.
17236 INACTIVE means use square brackets instead of angular ones, so that the
17237 stamp will not contribute to the agenda.
17238 PRE and POST are optional strings to be inserted before and after the
17239 stamp.
17240 The command returns the inserted time stamp."
17241 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17242 stamp)
17243 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17244 (insert-before-markers (or pre ""))
17245 (when (listp extra)
17246 (setq extra (car extra))
17247 (if (and (stringp extra)
17248 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17249 (setq extra (format "-%02d:%02d"
17250 (string-to-number (match-string 1 extra))
17251 (string-to-number (match-string 2 extra))))
17252 (setq extra nil)))
17253 (when extra
17254 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17255 (insert-before-markers (setq stamp (format-time-string fmt time)))
17256 (insert-before-markers (or post ""))
17257 (setq org-last-inserted-timestamp stamp)))
17259 (defun org-toggle-time-stamp-overlays ()
17260 "Toggle the use of custom time stamp formats."
17261 (interactive)
17262 (setq org-display-custom-times (not org-display-custom-times))
17263 (unless org-display-custom-times
17264 (let ((p (point-min)) (bmp (buffer-modified-p)))
17265 (while (setq p (next-single-property-change p 'display))
17266 (when (and (get-text-property p 'display)
17267 (eq (get-text-property p 'face) 'org-date))
17268 (remove-text-properties
17269 p (setq p (next-single-property-change p 'display))
17270 '(display t))))
17271 (set-buffer-modified-p bmp)))
17272 (org-restart-font-lock)
17273 (setq org-table-may-need-update t)
17274 (if org-display-custom-times
17275 (message "Time stamps are overlaid with custom format")
17276 (message "Time stamp overlays removed")))
17278 (defun org-display-custom-time (beg end)
17279 "Overlay modified time stamp format over timestamp between BEG and END."
17280 (let* ((ts (buffer-substring beg end))
17281 t1 with-hm tf time str (off 0))
17282 (save-match-data
17283 (setq t1 (org-parse-time-string ts t))
17284 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17285 (setq off (- (match-end 0) (match-beginning 0)))))
17286 (setq end (- end off))
17287 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17288 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17289 time (org-fix-decoded-time t1)
17290 str (org-add-props
17291 (format-time-string
17292 (substring tf 1 -1) (apply 'encode-time time))
17293 nil 'mouse-face 'highlight))
17294 (put-text-property beg end 'display str)))
17296 (defun org-fix-decoded-time (time)
17297 "Set 0 instead of nil for the first 6 elements of time.
17298 Don't touch the rest."
17299 (let ((n 0))
17300 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17302 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17303 "Difference between TIMESTAMP-STRING and now in days.
17304 If SECONDS is non-nil, return the difference in seconds."
17305 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17306 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17307 (funcall fdiff (current-time)))))
17309 (defun org-deadline-close-p (timestamp-string &optional ndays)
17310 "Is the time in TIMESTAMP-STRING close to the current date?"
17311 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17312 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17313 (not (org-entry-is-done-p))))
17315 (defun org-get-wdays (ts &optional delay zero-delay)
17316 "Get the deadline lead time appropriate for timestring TS.
17317 When DELAY is non-nil, get the delay time for scheduled items
17318 instead of the deadline lead time. When ZERO-DELAY is non-nil
17319 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17320 don't try to find the delay cookie in the scheduled timestamp."
17321 (let ((tv (if delay org-scheduled-delay-days
17322 org-deadline-warning-days)))
17323 (cond
17324 ((or (and delay (< tv 0))
17325 (and delay zero-delay (<= tv 0))
17326 (and (not delay) (<= tv 0)))
17327 ;; Enforce this value no matter what
17328 (- tv))
17329 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17330 ;; lead time is specified.
17331 (floor (* (string-to-number (match-string 1 ts))
17332 (cdr (assoc (match-string 2 ts)
17333 '(("d" . 1) ("w" . 7)
17334 ("m" . 30.4) ("y" . 365.25)
17335 ("h" . 0.041667)))))))
17336 ;; go for the default.
17337 (t tv))))
17339 (defun org-calendar-select-mouse (ev)
17340 "Return to `org-read-date' with the date currently selected.
17341 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17342 (interactive "e")
17343 (mouse-set-point ev)
17344 (when (calendar-cursor-to-date)
17345 (let* ((date (calendar-cursor-to-date))
17346 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17347 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17348 (when (active-minibuffer-window) (exit-minibuffer))))
17350 (defun org-check-deadlines (ndays)
17351 "Check if there are any deadlines due or past due.
17352 A deadline is considered due if it happens within `org-deadline-warning-days'
17353 days from today's date. If the deadline appears in an entry marked DONE,
17354 it is not shown. A numeric prefix argument NDAYS can be used to test that
17355 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17356 are shown."
17357 (interactive "P")
17358 (let* ((org-warn-days
17359 (cond
17360 ((equal ndays '(4)) 100000)
17361 (ndays (prefix-numeric-value ndays))
17362 (t (abs org-deadline-warning-days))))
17363 (case-fold-search nil)
17364 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17365 (callback
17366 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17367 (message "%d deadlines past-due or due within %d days"
17368 (org-occur regexp nil callback)
17369 org-warn-days)))
17371 (defsubst org-re-timestamp (type)
17372 "Return a regexp for timestamp TYPE.
17373 Allowed values for TYPE are:
17375 all: all timestamps
17376 active: only active timestamps (<...>)
17377 inactive: only inactive timestamps ([...])
17378 scheduled: only scheduled timestamps
17379 deadline: only deadline timestamps
17380 closed: only closed time-stamps
17382 When TYPE is nil, fall back on returning a regexp that matches
17383 both scheduled and deadline timestamps."
17384 (cl-case type
17385 (all org-ts-regexp-both)
17386 (active org-ts-regexp)
17387 (inactive org-ts-regexp-inactive)
17388 (scheduled org-scheduled-time-regexp)
17389 (deadline org-deadline-time-regexp)
17390 (closed org-closed-time-regexp)
17391 (otherwise
17392 (concat "\\<"
17393 (regexp-opt (list org-deadline-string org-scheduled-string))
17394 " *<\\([^>]+\\)>"))))
17396 (defun org-check-before-date (d)
17397 "Check if there are deadlines or scheduled entries before date D."
17398 (interactive (list (org-read-date)))
17399 (let* ((case-fold-search nil)
17400 (regexp (org-re-timestamp org-ts-type))
17401 (ts-type org-ts-type)
17402 (callback
17403 (lambda ()
17404 (let ((match (match-string 1)))
17405 (and (if (memq ts-type '(active inactive all))
17406 (eq (org-element-type (save-excursion
17407 (backward-char)
17408 (org-element-context)))
17409 'timestamp)
17410 (org-at-planning-p))
17411 (time-less-p
17412 (org-time-string-to-time match)
17413 (org-time-string-to-time d)))))))
17414 (message "%d entries before %s"
17415 (org-occur regexp nil callback)
17416 d)))
17418 (defun org-check-after-date (d)
17419 "Check if there are deadlines or scheduled entries after date D."
17420 (interactive (list (org-read-date)))
17421 (let* ((case-fold-search nil)
17422 (regexp (org-re-timestamp org-ts-type))
17423 (ts-type org-ts-type)
17424 (callback
17425 (lambda ()
17426 (let ((match (match-string 1)))
17427 (and (if (memq ts-type '(active inactive all))
17428 (eq (org-element-type (save-excursion
17429 (backward-char)
17430 (org-element-context)))
17431 'timestamp)
17432 (org-at-planning-p))
17433 (not (time-less-p
17434 (org-time-string-to-time match)
17435 (org-time-string-to-time d))))))))
17436 (message "%d entries after %s"
17437 (org-occur regexp nil callback)
17438 d)))
17440 (defun org-check-dates-range (start-date end-date)
17441 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17442 (interactive (list (org-read-date nil nil nil "Range starts")
17443 (org-read-date nil nil nil "Range end")))
17444 (let ((case-fold-search nil)
17445 (regexp (org-re-timestamp org-ts-type))
17446 (callback
17447 (let ((type org-ts-type))
17448 (lambda ()
17449 (let ((match (match-string 1)))
17450 (and
17451 (if (memq type '(active inactive all))
17452 (eq (org-element-type (save-excursion
17453 (backward-char)
17454 (org-element-context)))
17455 'timestamp)
17456 (org-at-planning-p))
17457 (not (time-less-p
17458 (org-time-string-to-time match)
17459 (org-time-string-to-time start-date)))
17460 (time-less-p
17461 (org-time-string-to-time match)
17462 (org-time-string-to-time end-date))))))))
17463 (message "%d entries between %s and %s"
17464 (org-occur regexp nil callback) start-date end-date)))
17466 (defun org-evaluate-time-range (&optional to-buffer)
17467 "Evaluate a time range by computing the difference between start and end.
17468 Normally the result is just printed in the echo area, but with prefix arg
17469 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17470 If the time range is actually in a table, the result is inserted into the
17471 next column.
17472 For time difference computation, a year is assumed to be exactly 365
17473 days in order to avoid rounding problems."
17474 (interactive "P")
17476 (org-clock-update-time-maybe)
17477 (save-excursion
17478 (unless (org-at-date-range-p t)
17479 (goto-char (point-at-bol))
17480 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17481 (unless (org-at-date-range-p t)
17482 (user-error "Not at a time-stamp range, and none found in current line")))
17483 (let* ((ts1 (match-string 1))
17484 (ts2 (match-string 2))
17485 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17486 (match-end (match-end 0))
17487 (time1 (org-time-string-to-time ts1))
17488 (time2 (org-time-string-to-time ts2))
17489 (t1 (float-time time1))
17490 (t2 (float-time time2))
17491 (diff (abs (- t2 t1)))
17492 (negative (< (- t2 t1) 0))
17493 ;; (ys (floor (* 365 24 60 60)))
17494 (ds (* 24 60 60))
17495 (hs (* 60 60))
17496 (fy "%dy %dd %02d:%02d")
17497 (fy1 "%dy %dd")
17498 (fd "%dd %02d:%02d")
17499 (fd1 "%dd")
17500 (fh "%02d:%02d")
17501 y d h m align)
17502 (if havetime
17503 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17505 d (floor (/ diff ds)) diff (mod diff ds)
17506 h (floor (/ diff hs)) diff (mod diff hs)
17507 m (floor (/ diff 60)))
17508 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17510 d (floor (+ (/ diff ds) 0.5))
17511 h 0 m 0))
17512 (if (not to-buffer)
17513 (message "%s" (org-make-tdiff-string y d h m))
17514 (if (org-at-table-p)
17515 (progn
17516 (goto-char match-end)
17517 (setq align t)
17518 (and (looking-at " *|") (goto-char (match-end 0))))
17519 (goto-char match-end))
17520 (when (looking-at
17521 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17522 (replace-match ""))
17523 (when negative (insert " -"))
17524 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17525 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17526 (insert " " (format fh h m))))
17527 (when align (org-table-align))
17528 (message "Time difference inserted")))))
17530 (defun org-make-tdiff-string (y d h m)
17531 (let ((fmt "")
17532 (l nil))
17533 (when (> y 0)
17534 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17535 (push y l))
17536 (when (> d 0)
17537 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17538 (push d l))
17539 (when (> h 0)
17540 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17541 (push h l))
17542 (when (> m 0)
17543 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17544 (push m l))
17545 (apply 'format fmt (nreverse l))))
17547 (defun org-time-string-to-time (s)
17548 "Convert timestamp string S into internal time."
17549 (apply #'encode-time (org-parse-time-string s)))
17551 (defun org-time-string-to-seconds (s)
17552 "Convert a timestamp string S into a number of seconds."
17553 (float-time (org-time-string-to-time s)))
17555 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17557 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17558 "Convert time stamp S to an absolute day number.
17560 If DAYNR in non-nil, and there is a specifier for a cyclic time
17561 stamp, get the closest date to DAYNR. If PREFER is
17562 `past' (respectively `future') return a date past (respectively
17563 after) or equal to DAYNR.
17565 POS is the location of time stamp S, as a buffer position in
17566 BUFFER.
17568 Diary sexp timestamps are matched against DAYNR, when non-nil.
17569 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17570 signaled."
17571 (cond
17572 ((string-match "\\`%%\\((.*)\\)" s)
17573 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17574 ;; only able to match individual dates. If it fails, raise an
17575 ;; error.
17576 (if (and daynr
17577 (org-diary-sexp-entry
17578 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17579 daynr
17580 (signal 'org-diary-sexp-no-match (list s))))
17581 (daynr (org-closest-date s daynr prefer))
17582 (t (time-to-days
17583 (condition-case errdata
17584 (apply #'encode-time (org-parse-time-string s))
17585 (error (error "Bad timestamp `%s'%s\nError was: %s"
17587 (if (not (and buffer pos)) ""
17588 (format-message " at %d in buffer `%s'" pos buffer))
17589 (cdr errdata))))))))
17591 (defun org-days-to-iso-week (days)
17592 "Return the iso week number."
17593 (require 'cal-iso)
17594 (car (calendar-iso-from-absolute days)))
17596 (defun org-small-year-to-year (year)
17597 "Convert 2-digit years into 4-digit years.
17598 YEAR is expanded into one of the 30 next years, if possible, or
17599 into a past one. Any year larger than 99 is returned unchanged."
17600 (if (>= year 100) year
17601 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17602 (century (/ current 100))
17603 (offset (- year (% current 100))))
17604 (cond ((> offset 30) (+ (* (1- century) 100) year))
17605 ((> offset -70) (+ (* century 100) year))
17606 (t (+ (* (1+ century) 100) year))))))
17608 (defun org-time-from-absolute (d)
17609 "Return the time corresponding to date D.
17610 D may be an absolute day number, or a calendar-type list (month day year)."
17611 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17612 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17614 (defvar org-agenda-current-date)
17615 (defun org-calendar-holiday ()
17616 "List of holidays, for Diary display in Org mode."
17617 (require 'holidays)
17618 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17619 (and hl (mapconcat #'identity hl "; "))))
17621 (defun org-diary-sexp-entry (sexp entry d)
17622 "Process a SEXP diary ENTRY for date D."
17623 (require 'diary-lib)
17624 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17625 ;; dynamically.
17626 (let* ((sexp `(let ((entry ,entry)
17627 (date ',d))
17628 ,(car (read-from-string sexp))))
17629 (result (if calendar-debug-sexp (eval sexp)
17630 (condition-case nil
17631 (eval sexp)
17632 (error
17633 (beep)
17634 (message "Bad sexp at line %d in %s: %s"
17635 (org-current-line)
17636 (buffer-file-name) sexp)
17637 (sleep-for 2))))))
17638 (cond ((stringp result) (split-string result "; "))
17639 ((and (consp result)
17640 (not (consp (cdr result)))
17641 (stringp (cdr result))) (cdr result))
17642 ((and (consp result)
17643 (stringp (car result))) result)
17644 (result entry))))
17646 (defun org-diary-to-ical-string (frombuf)
17647 "Get iCalendar entries from diary entries in buffer FROMBUF.
17648 This uses the icalendar.el library."
17649 (let* ((tmpdir temporary-file-directory)
17650 (tmpfile (make-temp-name
17651 (expand-file-name "orgics" tmpdir)))
17652 buf rtn b e)
17653 (with-current-buffer frombuf
17654 (icalendar-export-region (point-min) (point-max) tmpfile)
17655 (setq buf (find-buffer-visiting tmpfile))
17656 (set-buffer buf)
17657 (goto-char (point-min))
17658 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17659 (setq b (match-beginning 0)))
17660 (goto-char (point-max))
17661 (when (re-search-backward "^END:VEVENT" nil t)
17662 (setq e (match-end 0)))
17663 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17664 (kill-buffer buf)
17665 (delete-file tmpfile)
17666 rtn))
17668 (defun org-closest-date (start current prefer)
17669 "Return closest date to CURRENT starting from START.
17671 CURRENT and START are both time stamps.
17673 When PREFER is `past', return a date that is either CURRENT or
17674 past. When PREFER is `future', return a date that is either
17675 CURRENT or future.
17677 Only time stamps with a repeater are modified. Any other time
17678 stamp stay unchanged. In any case, return value is an absolute
17679 day number."
17680 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17681 ;; No repeater. Do not shift time stamp.
17682 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17683 (let ((value (string-to-number (match-string 1 start)))
17684 (type (match-string 2 start)))
17685 (if (= 0 value)
17686 ;; Repeater with a 0-value is considered as void.
17687 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17688 (let* ((base (org-date-to-gregorian start))
17689 (target (org-date-to-gregorian current))
17690 (sday (calendar-absolute-from-gregorian base))
17691 (cday (calendar-absolute-from-gregorian target))
17692 n1 n2)
17693 ;; If START is already past CURRENT, just return START.
17694 (if (<= cday sday) sday
17695 ;; Compute closest date before (N1) and closest date past
17696 ;; (N2) CURRENT.
17697 (pcase type
17698 ("h"
17699 (let ((missing-hours
17700 (mod (+ (- (* 24 (- cday sday))
17701 (nth 2 (org-parse-time-string start)))
17702 org-extend-today-until)
17703 value)))
17704 (setf n1 (if (= missing-hours 0) cday
17705 (- cday (1+ (/ missing-hours 24)))))
17706 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17707 ((or "d" "w")
17708 (let ((value (if (equal type "w") (* 7 value) value)))
17709 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17710 (setf n2 (+ n1 value))))
17711 ("m"
17712 (let* ((add-months
17713 (lambda (d n)
17714 ;; Add N months to gregorian date D, i.e.,
17715 ;; a list (MONTH DAY YEAR). Return a valid
17716 ;; gregorian date.
17717 (let ((m (+ (nth 0 d) n)))
17718 (list (mod m 12)
17719 (nth 1 d)
17720 (+ (/ m 12) (nth 2 d))))))
17721 (months ; Complete months to TARGET.
17722 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17723 (- (nth 0 target) (nth 0 base))
17724 ;; If START's day is greater than
17725 ;; TARGET's, remove incomplete month.
17726 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17727 value)
17728 value))
17729 (before (funcall add-months base months)))
17730 (setf n1 (calendar-absolute-from-gregorian before))
17731 (setf n2
17732 (calendar-absolute-from-gregorian
17733 (funcall add-months before value)))))
17735 (let* ((d (nth 1 base))
17736 (m (nth 0 base))
17737 (y (nth 2 base))
17738 (years ; Complete years to TARGET.
17739 (* (/ (- (nth 2 target)
17741 ;; If START's month and day are
17742 ;; greater than TARGET's, remove
17743 ;; incomplete year.
17744 (if (or (> (nth 0 target) m)
17745 (and (= (nth 0 target) m)
17746 (> (nth 1 target) d)))
17749 value)
17750 value))
17751 (before (list m d (+ y years))))
17752 (setf n1 (calendar-absolute-from-gregorian before))
17753 (setf n2 (calendar-absolute-from-gregorian
17754 (list m d (+ (nth 2 before) value)))))))
17755 ;; Handle PREFER parameter, if any.
17756 (cond
17757 ((eq prefer 'past) (if (= cday n2) n2 n1))
17758 ((eq prefer 'future) (if (= cday n1) n1 n2))
17759 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17761 (defun org-date-to-gregorian (d)
17762 "Turn any specification of date D into a Gregorian date for the calendar."
17763 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17764 ((and (listp d) (= (length d) 3)) d)
17765 ((stringp d)
17766 (let ((d (org-parse-time-string d)))
17767 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17768 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17770 (defun org-parse-time-string (s &optional nodefault)
17771 "Parse the standard Org time string.
17773 This should be a lot faster than the normal `parse-time-string'.
17775 If time is not given, defaults to 0:00. However, with optional
17776 NODEFAULT, hour and minute fields will be nil if not given."
17777 (cond ((string-match org-ts-regexp0 s)
17778 (list 0
17779 (when (or (match-beginning 8) (not nodefault))
17780 (string-to-number (or (match-string 8 s) "0")))
17781 (when (or (match-beginning 7) (not nodefault))
17782 (string-to-number (or (match-string 7 s) "0")))
17783 (string-to-number (match-string 4 s))
17784 (string-to-number (match-string 3 s))
17785 (string-to-number (match-string 2 s))
17786 nil nil nil))
17787 ((string-match "^<[^>]+>$" s)
17788 ;; FIXME: `decode-time' needs to be called with ZONE as its
17789 ;; second argument. However, this requires at least Emacs
17790 ;; 25.1. We can do it when we switch to this version as our
17791 ;; minimal requirement.
17792 (decode-time (seconds-to-time (org-matcher-time s))))
17793 (t (error "Not a standard Org time string: %s" s))))
17795 (defun org-timestamp-up (&optional arg)
17796 "Increase the date item at the cursor by one.
17797 If the cursor is on the year, change the year. If it is on the month,
17798 the day or the time, change that.
17799 With prefix ARG, change by that many units."
17800 (interactive "p")
17801 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17803 (defun org-timestamp-down (&optional arg)
17804 "Decrease the date item at the cursor by one.
17805 If the cursor is on the year, change the year. If it is on the month,
17806 the day or the time, change that.
17807 With prefix ARG, change by that many units."
17808 (interactive "p")
17809 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17811 (defun org-timestamp-up-day (&optional arg)
17812 "Increase the date in the time stamp by one day.
17813 With prefix ARG, change that many days."
17814 (interactive "p")
17815 (if (and (not (org-at-timestamp-p 'lax))
17816 (org-at-heading-p))
17817 (org-todo 'up)
17818 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17820 (defun org-timestamp-down-day (&optional arg)
17821 "Decrease the date in the time stamp by one day.
17822 With prefix ARG, change that many days."
17823 (interactive "p")
17824 (if (and (not (org-at-timestamp-p 'lax))
17825 (org-at-heading-p))
17826 (org-todo 'down)
17827 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17829 (defun org-at-timestamp-p (&optional extended)
17830 "Non-nil if point is inside a timestamp.
17832 By default, the function only consider syntactically valid active
17833 timestamps. However, the caller may have a broader definition
17834 for timestamps. As a consequence, optional argument EXTENDED can
17835 be set to the following values
17837 `inactive'
17839 Include also syntactically valid inactive timestamps.
17841 `agenda'
17843 Include timestamps allowed in Agenda, i.e., those in
17844 properties drawers, planning lines and clock lines.
17846 `lax'
17848 Ignore context. The function matches any part of the
17849 document looking like a timestamp. This includes comments,
17850 example blocks...
17852 For backward-compatibility with Org 9.0, every other non-nil
17853 value is equivalent to `inactive'.
17855 When at a timestamp, return the position of the point as a symbol
17856 among `bracket', `after', `year', `month', `hour', `minute',
17857 `day' or a number of character from the last know part of the
17858 time stamp.
17860 When matching, the match groups are the following:
17861 group 1: year
17862 group 2: month
17863 group 3: day number
17864 group 4: day name
17865 group 5: hours, if any
17866 group 6: minutes, if any"
17867 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17868 (pos (point))
17869 (match?
17870 (let ((boundaries (org-in-regexp regexp)))
17871 (save-match-data
17872 (cond ((null boundaries) nil)
17873 ((eq extended 'lax) t)
17875 (or (and (eq extended 'agenda)
17876 (or (org-at-planning-p)
17877 (org-at-property-p)
17878 (and (bound-and-true-p
17879 org-agenda-include-inactive-timestamps)
17880 (org-at-clock-log-p))))
17881 (eq 'timestamp
17882 (save-excursion
17883 (when (= pos (cdr boundaries)) (forward-char -1))
17884 (org-element-type (org-element-context)))))))))))
17885 (cond
17886 ((not match?) nil)
17887 ((= pos (match-beginning 0)) 'bracket)
17888 ;; Distinguish location right before the closing bracket from
17889 ;; right after it.
17890 ((= pos (1- (match-end 0))) 'bracket)
17891 ((= pos (match-end 0)) 'after)
17892 ((org-pos-in-match-range pos 2) 'year)
17893 ((org-pos-in-match-range pos 3) 'month)
17894 ((org-pos-in-match-range pos 7) 'hour)
17895 ((org-pos-in-match-range pos 8) 'minute)
17896 ((or (org-pos-in-match-range pos 4)
17897 (org-pos-in-match-range pos 5)) 'day)
17898 ((and (> pos (or (match-end 8) (match-end 5)))
17899 (< pos (match-end 0)))
17900 (- pos (or (match-end 8) (match-end 5))))
17901 (t 'day))))
17903 (defun org-toggle-timestamp-type ()
17904 "Toggle the type (<active> or [inactive]) of a time stamp."
17905 (interactive)
17906 (when (org-at-timestamp-p 'lax)
17907 (let ((beg (match-beginning 0)) (end (match-end 0))
17908 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17909 (save-excursion
17910 (goto-char beg)
17911 (while (re-search-forward "[][<>]" end t)
17912 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17913 t t)))
17914 (message "Timestamp is now %sactive"
17915 (if (equal (char-after beg) ?<) "" "in")))))
17917 (defun org-at-clock-log-p ()
17918 "Non-nil if point is on a clock log line."
17919 (and (org-match-line org-clock-line-re)
17920 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17922 (defvar org-clock-history) ; defined in org-clock.el
17923 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17924 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17925 "Change the date in the time stamp at point.
17926 The date will be changed by N times WHAT. WHAT can be `day', `month',
17927 `year', `minute', `second'. If WHAT is not given, the cursor position
17928 in the timestamp determines what will be changed.
17929 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17930 (let ((origin (point))
17931 (timestamp? (org-at-timestamp-p 'lax))
17932 origin-cat
17933 with-hm inactive
17934 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17935 extra rem
17936 ts time time0 fixnext clrgx)
17937 (unless timestamp? (user-error "Not at a timestamp"))
17938 (if (and (not what) (eq timestamp? 'bracket))
17939 (org-toggle-timestamp-type)
17940 ;; Point isn't on brackets. Remember the part of the time-stamp
17941 ;; the point was in. Indeed, size of time-stamps may change,
17942 ;; but point must be kept in the same category nonetheless.
17943 (setq origin-cat timestamp?)
17944 (when (and (not what) (not (eq timestamp? 'day))
17945 org-display-custom-times
17946 (get-text-property (point) 'display)
17947 (not (get-text-property (1- (point)) 'display)))
17948 (setq timestamp? 'day))
17949 (setq timestamp? (or what timestamp?)
17950 inactive (= (char-after (match-beginning 0)) ?\[)
17951 ts (match-string 0))
17952 (replace-match "")
17953 (when (string-match
17954 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17956 (setq extra (match-string 1 ts))
17957 (when suppress-tmp-delay
17958 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17959 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17960 (setq with-hm t))
17961 (setq time0 (org-parse-time-string ts))
17962 (when (and updown
17963 (eq timestamp? 'minute)
17964 (not current-prefix-arg))
17965 ;; This looks like s-up and s-down. Change by one rounding step.
17966 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17967 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17968 (setcar (cdr time0) (+ (nth 1 time0)
17969 (if (> n 0) (- rem) (- dm rem))))))
17970 (setq time
17971 (apply #'encode-time
17972 (or (car time0) 0)
17973 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17974 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17975 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17976 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17977 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17978 (nthcdr 6 time0)))
17979 (when (and (memq timestamp? '(hour minute))
17980 extra
17981 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17982 (setq extra (org-modify-ts-extra
17983 extra
17984 (if (eq timestamp? 'hour) 2 5)
17985 n dm)))
17986 (when (integerp timestamp?)
17987 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17988 (when (eq what 'calendar)
17989 (let ((cal-date (org-get-date-from-calendar)))
17990 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17991 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17992 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17993 (setcar time0 (or (car time0) 0))
17994 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17995 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17996 (setq time (apply 'encode-time time0))))
17997 ;; Insert the new time-stamp, and ensure point stays in the same
17998 ;; category as before (i.e. not after the last position in that
17999 ;; category).
18000 (let ((pos (point)))
18001 ;; Stay before inserted string. `save-excursion' is of no use.
18002 (setq org-last-changed-timestamp
18003 (org-insert-time-stamp time with-hm inactive nil nil extra))
18004 (goto-char pos))
18005 (save-match-data
18006 (looking-at org-ts-regexp3)
18007 (goto-char
18008 (pcase origin-cat
18009 ;; `day' category ends before `hour' if any, or at the end
18010 ;; of the day name.
18011 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18012 (`hour (min (match-end 7) origin))
18013 (`minute (min (1- (match-end 8)) origin))
18014 ((pred integerp) (min (1- (match-end 0)) origin))
18015 ;; Point was right after the time-stamp. However, the
18016 ;; time-stamp length might have changed, so refer to
18017 ;; (match-end 0) instead.
18018 (`after (match-end 0))
18019 ;; `year' and `month' have both fixed size: point couldn't
18020 ;; have moved into another part.
18021 (_ origin))))
18022 ;; Update clock if on a CLOCK line.
18023 (org-clock-update-time-maybe)
18024 ;; Maybe adjust the closest clock in `org-clock-history'
18025 (when org-clock-adjust-closest
18026 (if (not (and (org-at-clock-log-p)
18027 (< 1 (length (delq nil (mapcar 'marker-position
18028 org-clock-history))))))
18029 (message "No clock to adjust")
18030 (cond ((save-excursion ; fix previous clock?
18031 (re-search-backward org-ts-regexp0 nil t)
18032 (looking-back (concat org-clock-string " \\[")
18033 (line-beginning-position)))
18034 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18035 ((save-excursion ; fix next clock?
18036 (re-search-backward org-ts-regexp0 nil t)
18037 (looking-at (concat org-ts-regexp0 "\\] =>")))
18038 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18039 (save-window-excursion
18040 ;; Find closest clock to point, adjust the previous/next one in history
18041 (let* ((p (save-excursion (org-back-to-heading t)))
18042 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18043 (clfixnth
18044 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18045 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18046 (if (not clfixpos)
18047 (message "No clock to adjust")
18048 (save-excursion
18049 (org-goto-marker-or-bmk clfixpos)
18050 (org-show-subtree)
18051 (when (re-search-forward clrgx nil t)
18052 (goto-char (match-beginning 1))
18053 (let (org-clock-adjust-closest)
18054 (org-timestamp-change n timestamp? updown))
18055 (message "Clock adjusted in %s for heading: %s"
18056 (file-name-nondirectory (buffer-file-name))
18057 (org-get-heading t t)))))))))
18058 ;; Try to recenter the calendar window, if any.
18059 (when (and org-calendar-follow-timestamp-change
18060 (get-buffer-window "*Calendar*" t)
18061 (memq timestamp? '(day month year)))
18062 (org-recenter-calendar (time-to-days time))))))
18064 (defun org-modify-ts-extra (s pos n dm)
18065 "Change the different parts of the lead-time and repeat fields in timestamp."
18066 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18067 ng h m new rem)
18068 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18069 (cond
18070 ((or (org-pos-in-match-range pos 2)
18071 (org-pos-in-match-range pos 3))
18072 (setq m (string-to-number (match-string 3 s))
18073 h (string-to-number (match-string 2 s)))
18074 (if (org-pos-in-match-range pos 2)
18075 (setq h (+ h n))
18076 (setq n (* dm (with-no-warnings (signum n))))
18077 (unless (= 0 (setq rem (% m dm)))
18078 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18079 (setq m (+ m n)))
18080 (when (< m 0) (setq m (+ m 60) h (1- h)))
18081 (when (> m 59) (setq m (- m 60) h (1+ h)))
18082 (setq h (mod h 24))
18083 (setq ng 1 new (format "-%02d:%02d" h m)))
18084 ((org-pos-in-match-range pos 6)
18085 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18086 ((org-pos-in-match-range pos 5)
18087 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18089 ((org-pos-in-match-range pos 9)
18090 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18091 ((org-pos-in-match-range pos 8)
18092 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18094 (when ng
18095 (setq s (concat
18096 (substring s 0 (match-beginning ng))
18098 (substring s (match-end ng))))))
18101 (defun org-recenter-calendar (d)
18102 "If the calendar is visible, recenter it to date D."
18103 (let ((cwin (get-buffer-window "*Calendar*" t)))
18104 (when cwin
18105 (let ((calendar-move-hook nil))
18106 (with-selected-window cwin
18107 (calendar-goto-date
18108 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18110 (defun org-goto-calendar (&optional arg)
18111 "Go to the Emacs calendar at the current date.
18112 If there is a time stamp in the current line, go to that date.
18113 A prefix ARG can be used to force the current date."
18114 (interactive "P")
18115 (let ((calendar-move-hook nil)
18116 (calendar-view-holidays-initially-flag nil)
18117 (calendar-view-diary-initially-flag nil)
18118 diff)
18119 (when (or (org-at-timestamp-p 'lax)
18120 (org-match-line (concat ".*" org-ts-regexp)))
18121 (let ((d1 (time-to-days (current-time)))
18122 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18123 (setq diff (- d2 d1))))
18124 (calendar)
18125 (calendar-goto-today)
18126 (when (and diff (not arg)) (calendar-forward-day diff))))
18128 (defun org-get-date-from-calendar ()
18129 "Return a list (month day year) of date at point in calendar."
18130 (with-current-buffer "*Calendar*"
18131 (save-match-data
18132 (calendar-cursor-to-date))))
18134 (defun org-date-from-calendar ()
18135 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18136 If there is already a time stamp at the cursor position, update it."
18137 (interactive)
18138 (if (org-at-timestamp-p 'lax)
18139 (org-timestamp-change 0 'calendar)
18140 (let ((cal-date (org-get-date-from-calendar)))
18141 (org-insert-time-stamp
18142 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18144 (defcustom org-effort-durations
18145 `(("min" . 1)
18146 ("h" . 60)
18147 ("d" . ,(* 60 8))
18148 ("w" . ,(* 60 8 5))
18149 ("m" . ,(* 60 8 5 4))
18150 ("y" . ,(* 60 8 5 40)))
18151 "Conversion factor to minutes for an effort modifier.
18153 Each entry has the form (MODIFIER . MINUTES).
18155 In an effort string, a number followed by MODIFIER is multiplied
18156 by the specified number of MINUTES to obtain an effort in
18157 minutes.
18159 For example, if the value of this variable is ((\"hours\" . 60)), then an
18160 effort string \"2hours\" is equivalent to 120 minutes."
18161 :group 'org-agenda
18162 :version "26.1"
18163 :package-version '(Org . "8.3")
18164 :type '(alist :key-type (string :tag "Modifier")
18165 :value-type (number :tag "Minutes")))
18167 (defcustom org-image-actual-width t
18168 "Should we use the actual width of images when inlining them?
18170 When set to t, always use the image width.
18172 When set to a number, use imagemagick (when available) to set
18173 the image's width to this value.
18175 When set to a number in a list, try to get the width from any
18176 #+ATTR.* keyword if it matches a width specification like
18178 #+ATTR_HTML: :width 300px
18180 and fall back on that number if none is found.
18182 When set to nil, try to get the width from an #+ATTR.* keyword
18183 and fall back on the original width if none is found.
18185 This requires Emacs >= 24.1, build with imagemagick support."
18186 :group 'org-appearance
18187 :version "24.4"
18188 :package-version '(Org . "8.0")
18189 :type '(choice
18190 (const :tag "Use the image width" t)
18191 (integer :tag "Use a number of pixels")
18192 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18193 (const :tag "Use #+ATTR* or don't resize" nil)))
18195 (defcustom org-agenda-inhibit-startup nil
18196 "Inhibit startup when preparing agenda buffers.
18197 When this variable is t, the initialization of the Org agenda
18198 buffers is inhibited: e.g. the visibility state is not set, the
18199 tables are not re-aligned, etc."
18200 :type 'boolean
18201 :version "24.3"
18202 :group 'org-agenda)
18204 (defcustom org-agenda-ignore-properties nil
18205 "Avoid updating text properties when building the agenda.
18206 Properties are used to prepare buffers for effort estimates,
18207 appointments, statistics and subtree-local categories.
18208 If you don't use these in the agenda, you can add them to this
18209 list and agenda building will be a bit faster.
18210 The value is a list, with zero or more of the symbols `effort', `appt',
18211 `stats' or `category'."
18212 :type '(set :greedy t
18213 (const effort)
18214 (const appt)
18215 (const stats)
18216 (const category))
18217 :version "26.1"
18218 :package-version '(Org . "8.3")
18219 :group 'org-agenda)
18221 ;;;; Files
18223 (defun org-save-all-org-buffers ()
18224 "Save all Org buffers without user confirmation."
18225 (interactive)
18226 (message "Saving all Org buffers...")
18227 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18228 (when (featurep 'org-id) (org-id-locations-save))
18229 (message "Saving all Org buffers... done"))
18231 (defun org-revert-all-org-buffers ()
18232 "Revert all Org buffers.
18233 Prompt for confirmation when there are unsaved changes.
18234 Be sure you know what you are doing before letting this function
18235 overwrite your changes.
18237 This function is useful in a setup where one tracks Org files
18238 with a version control system, to revert on one machine after pulling
18239 changes from another. I believe the procedure must be like this:
18241 1. M-x org-save-all-org-buffers
18242 2. Pull changes from the other machine, resolve conflicts
18243 3. M-x org-revert-all-org-buffers"
18244 (interactive)
18245 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18246 (user-error "Abort"))
18247 (save-excursion
18248 (save-window-excursion
18249 (dolist (b (buffer-list))
18250 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18251 (with-current-buffer b buffer-file-name))
18252 (pop-to-buffer-same-window b)
18253 (revert-buffer t 'no-confirm)))
18254 (when (and (featurep 'org-id) org-id-track-globally)
18255 (org-id-locations-load)))))
18257 ;;;; Agenda files
18259 ;;;###autoload
18260 (defun org-switchb (&optional arg)
18261 "Switch between Org buffers.
18263 With `\\[universal-argument]' prefix, restrict available buffers to files.
18265 With `\\[universal-argument] \\[universal-argument]' \
18266 prefix, restrict available buffers to agenda files."
18267 (interactive "P")
18268 (let ((blist (org-buffer-list
18269 (cond ((equal arg '(4)) 'files)
18270 ((equal arg '(16)) 'agenda)))))
18271 (pop-to-buffer-same-window
18272 (completing-read "Org buffer: "
18273 (mapcar #'list (mapcar #'buffer-name blist))
18274 nil t))))
18276 (defun org-buffer-list (&optional predicate exclude-tmp)
18277 "Return a list of Org buffers.
18278 PREDICATE can be `export', `files' or `agenda'.
18280 export restrict the list to Export buffers.
18281 files restrict the list to buffers visiting Org files.
18282 agenda restrict the list to buffers visiting agenda files.
18284 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18285 (let* ((bfn nil)
18286 (agenda-files (and (eq predicate 'agenda)
18287 (mapcar 'file-truename (org-agenda-files t))))
18288 (filter
18289 (cond
18290 ((eq predicate 'files)
18291 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18292 ((eq predicate 'export)
18293 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18294 ((eq predicate 'agenda)
18295 (lambda (b)
18296 (with-current-buffer b
18297 (and (derived-mode-p 'org-mode)
18298 (setq bfn (buffer-file-name b))
18299 (member (file-truename bfn) agenda-files)))))
18300 (t (lambda (b) (with-current-buffer b
18301 (or (derived-mode-p 'org-mode)
18302 (string-match "\\*Org .*Export"
18303 (buffer-name b)))))))))
18304 (delq nil
18305 (mapcar
18306 (lambda(b)
18307 (if (and (funcall filter b)
18308 (or (not exclude-tmp)
18309 (not (string-match "tmp" (buffer-name b)))))
18311 nil))
18312 (buffer-list)))))
18314 (defun org-agenda-files (&optional unrestricted archives)
18315 "Get the list of agenda files.
18316 Optional UNRESTRICTED means return the full list even if a restriction
18317 is currently in place.
18318 When ARCHIVES is t, include all archive files that are really being
18319 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18320 `org-agenda-archives-mode' is t."
18321 (let ((files
18322 (cond
18323 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18324 ((stringp org-agenda-files) (org-read-agenda-file-list))
18325 ((listp org-agenda-files) org-agenda-files)
18326 (t (error "Invalid value of `org-agenda-files'")))))
18327 (setq files (apply 'append
18328 (mapcar (lambda (f)
18329 (if (file-directory-p f)
18330 (directory-files
18331 f t org-agenda-file-regexp)
18332 (list f)))
18333 files)))
18334 (when org-agenda-skip-unavailable-files
18335 (setq files (delq nil
18336 (mapcar (function
18337 (lambda (file)
18338 (and (file-readable-p file) file)))
18339 files))))
18340 (when (or (eq archives t)
18341 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18342 (setq files (org-add-archive-files files)))
18343 files))
18345 (defun org-agenda-file-p (&optional file)
18346 "Return non-nil, if FILE is an agenda file.
18347 If FILE is omitted, use the file associated with the current
18348 buffer."
18349 (let ((fname (or file (buffer-file-name))))
18350 (and fname
18351 (member (file-truename fname)
18352 (mapcar #'file-truename (org-agenda-files t))))))
18354 (defun org-edit-agenda-file-list ()
18355 "Edit the list of agenda files.
18356 Depending on setup, this either uses customize to edit the variable
18357 `org-agenda-files', or it visits the file that is holding the list. In the
18358 latter case, the buffer is set up in a way that saving it automatically kills
18359 the buffer and restores the previous window configuration."
18360 (interactive)
18361 (if (stringp org-agenda-files)
18362 (let ((cw (current-window-configuration)))
18363 (find-file org-agenda-files)
18364 (setq-local org-window-configuration cw)
18365 (add-hook 'after-save-hook
18366 (lambda ()
18367 (set-window-configuration
18368 (prog1 org-window-configuration
18369 (kill-buffer (current-buffer))))
18370 (org-install-agenda-files-menu)
18371 (message "New agenda file list installed"))
18372 nil 'local)
18373 (message "%s" (substitute-command-keys
18374 "Edit list and finish with \\[save-buffer]")))
18375 (customize-variable 'org-agenda-files)))
18377 (defun org-store-new-agenda-file-list (list)
18378 "Set new value for the agenda file list and save it correctly."
18379 (if (stringp org-agenda-files)
18380 (let ((fe (org-read-agenda-file-list t)) b u)
18381 (while (setq b (find-buffer-visiting org-agenda-files))
18382 (kill-buffer b))
18383 (with-temp-file org-agenda-files
18384 (insert
18385 (mapconcat
18386 (lambda (f) ;; Keep un-expanded entries.
18387 (if (setq u (assoc f fe))
18388 (cdr u)
18390 list "\n")
18391 "\n")))
18392 (let ((org-mode-hook nil) (org-inhibit-startup t)
18393 (org-insert-mode-line-in-empty-file nil))
18394 (setq org-agenda-files list)
18395 (customize-save-variable 'org-agenda-files org-agenda-files))))
18397 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18398 "Read the list of agenda files from a file.
18399 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18400 filenames, used by `org-store-new-agenda-file-list' to write back
18401 un-expanded file names."
18402 (when (file-directory-p org-agenda-files)
18403 (error "`org-agenda-files' cannot be a single directory"))
18404 (when (stringp org-agenda-files)
18405 (with-temp-buffer
18406 (insert-file-contents org-agenda-files)
18407 (mapcar
18408 (lambda (f)
18409 (let ((e (expand-file-name (substitute-in-file-name f)
18410 org-directory)))
18411 (if pair-with-expansion
18412 (cons e f)
18413 e)))
18414 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18416 ;;;###autoload
18417 (defun org-cycle-agenda-files ()
18418 "Cycle through the files in `org-agenda-files'.
18419 If the current buffer visits an agenda file, find the next one in the list.
18420 If the current buffer does not, find the first agenda file."
18421 (interactive)
18422 (let* ((fs (or (org-agenda-files t)
18423 (user-error "No agenda files")))
18424 (files (copy-sequence fs))
18425 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18426 file)
18427 (when tcf
18428 (while (and (setq file (pop files))
18429 (not (equal (file-truename file) tcf)))))
18430 (find-file (car (or files fs)))
18431 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18433 (defun org-agenda-file-to-front (&optional to-end)
18434 "Move/add the current file to the top of the agenda file list.
18435 If the file is not present in the list, it is added to the front. If it is
18436 present, it is moved there. With optional argument TO-END, add/move to the
18437 end of the list."
18438 (interactive "P")
18439 (let ((org-agenda-skip-unavailable-files nil)
18440 (file-alist (mapcar (lambda (x)
18441 (cons (file-truename x) x))
18442 (org-agenda-files t)))
18443 (ctf (file-truename
18444 (or buffer-file-name
18445 (user-error "Please save the current buffer to a file"))))
18446 x had)
18447 (setq x (assoc ctf file-alist) had x)
18449 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18450 (if to-end
18451 (setq file-alist (append (delq x file-alist) (list x)))
18452 (setq file-alist (cons x (delq x file-alist))))
18453 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18454 (org-install-agenda-files-menu)
18455 (message "File %s to %s of agenda file list"
18456 (if had "moved" "added") (if to-end "end" "front"))))
18458 (defun org-remove-file (&optional file)
18459 "Remove current file from the list of files in variable `org-agenda-files'.
18460 These are the files which are being checked for agenda entries.
18461 Optional argument FILE means use this file instead of the current."
18462 (interactive)
18463 (let* ((org-agenda-skip-unavailable-files nil)
18464 (file (or file buffer-file-name
18465 (user-error "Current buffer does not visit a file")))
18466 (true-file (file-truename file))
18467 (afile (abbreviate-file-name file))
18468 (files (delq nil (mapcar
18469 (lambda (x)
18470 (unless (equal true-file
18471 (file-truename x))
18473 (org-agenda-files t)))))
18474 (if (not (= (length files) (length (org-agenda-files t))))
18475 (progn
18476 (org-store-new-agenda-file-list files)
18477 (org-install-agenda-files-menu)
18478 (message "Removed from Org Agenda list: %s" afile))
18479 (message "File was not in list: %s (not removed)" afile))))
18481 (defun org-file-menu-entry (file)
18482 (vector file (list 'find-file file) t))
18484 (defun org-check-agenda-file (file)
18485 "Make sure FILE exists. If not, ask user what to do."
18486 (unless (file-exists-p file)
18487 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18488 (abbreviate-file-name file))
18489 (let ((r (downcase (read-char-exclusive))))
18490 (cond
18491 ((equal r ?r)
18492 (org-remove-file file)
18493 (throw 'nextfile t))
18494 (t (user-error "Abort"))))))
18496 (defun org-get-agenda-file-buffer (file)
18497 "Get an agenda buffer visiting FILE.
18498 If the buffer needs to be created, add it to the list of buffers
18499 which might be released later."
18500 (let ((buf (org-find-base-buffer-visiting file)))
18501 (if buf
18502 buf ; just return it
18503 ;; Make a new buffer and remember it
18504 (setq buf (find-file-noselect file))
18505 (when buf (push buf org-agenda-new-buffers))
18506 buf)))
18508 (defun org-release-buffers (blist)
18509 "Release all buffers in list, asking the user for confirmation when needed.
18510 When a buffer is unmodified, it is just killed. When modified, it is saved
18511 \(if the user agrees) and then killed."
18512 (let (file)
18513 (dolist (buf blist)
18514 (setq file (buffer-file-name buf))
18515 (when (and (buffer-modified-p buf)
18516 file
18517 (y-or-n-p (format "Save file %s? " file)))
18518 (with-current-buffer buf (save-buffer)))
18519 (kill-buffer buf))))
18521 (defun org-agenda-prepare-buffers (files)
18522 "Create buffers for all agenda files, protect archived trees and comments."
18523 (interactive)
18524 (let ((pa '(:org-archived t))
18525 (pc '(:org-comment t))
18526 (pall '(:org-archived t :org-comment t))
18527 (inhibit-read-only t)
18528 (org-inhibit-startup org-agenda-inhibit-startup)
18529 (rea (concat ":" org-archive-tag ":"))
18530 re pos)
18531 (setq org-tag-alist-for-agenda nil
18532 org-tag-groups-alist-for-agenda nil)
18533 (save-excursion
18534 (save-restriction
18535 (dolist (file files)
18536 (catch 'nextfile
18537 (if (bufferp file)
18538 (set-buffer file)
18539 (org-check-agenda-file file)
18540 (set-buffer (org-get-agenda-file-buffer file)))
18541 (widen)
18542 (org-set-regexps-and-options 'tags-only)
18543 (setq pos (point))
18544 (or (memq 'category org-agenda-ignore-properties)
18545 (org-refresh-category-properties))
18546 (or (memq 'stats org-agenda-ignore-properties)
18547 (org-refresh-stats-properties))
18548 (or (memq 'effort org-agenda-ignore-properties)
18549 (org-refresh-effort-properties))
18550 (or (memq 'appt org-agenda-ignore-properties)
18551 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18552 (setq org-todo-keywords-for-agenda
18553 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18554 (setq org-done-keywords-for-agenda
18555 (append org-done-keywords-for-agenda org-done-keywords))
18556 (setq org-todo-keyword-alist-for-agenda
18557 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18558 (setq org-tag-alist-for-agenda
18559 (org-uniquify
18560 (append org-tag-alist-for-agenda
18561 org-current-tag-alist)))
18562 ;; Merge current file's tag groups into global
18563 ;; `org-tag-groups-alist-for-agenda'.
18564 (when org-group-tags
18565 (dolist (alist org-tag-groups-alist)
18566 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18567 (if old
18568 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18569 (push alist org-tag-groups-alist-for-agenda)))))
18570 (org-with-silent-modifications
18571 (save-excursion
18572 (remove-text-properties (point-min) (point-max) pall)
18573 (when org-agenda-skip-archived-trees
18574 (goto-char (point-min))
18575 (while (re-search-forward rea nil t)
18576 (when (org-at-heading-p t)
18577 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18578 (goto-char (point-min))
18579 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18580 (while (re-search-forward re nil t)
18581 (when (save-match-data (org-in-commented-heading-p t))
18582 (add-text-properties
18583 (match-beginning 0) (org-end-of-subtree t) pc)))))
18584 (goto-char pos)))))
18585 (setq org-todo-keywords-for-agenda
18586 (org-uniquify org-todo-keywords-for-agenda))
18587 (setq org-todo-keyword-alist-for-agenda
18588 (org-uniquify org-todo-keyword-alist-for-agenda))))
18591 ;;;; CDLaTeX minor mode
18593 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18594 "Keymap for the minor `org-cdlatex-mode'.")
18596 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18597 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18598 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18599 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18600 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18602 (defvar org-cdlatex-texmathp-advice-is-done nil
18603 "Flag remembering if we have applied the advice to texmathp already.")
18605 (define-minor-mode org-cdlatex-mode
18606 "Toggle the minor `org-cdlatex-mode'.
18607 This mode supports entering LaTeX environment and math in LaTeX fragments
18608 in Org mode.
18609 \\{org-cdlatex-mode-map}"
18610 nil " OCDL" nil
18611 (when org-cdlatex-mode
18612 (require 'cdlatex)
18613 (run-hooks 'cdlatex-mode-hook)
18614 (cdlatex-compute-tables))
18615 (unless org-cdlatex-texmathp-advice-is-done
18616 (setq org-cdlatex-texmathp-advice-is-done t)
18617 (defadvice texmathp (around org-math-always-on activate)
18618 "Always return t in Org buffers.
18619 This is because we want to insert math symbols without dollars even outside
18620 the LaTeX math segments. If Org mode thinks that point is actually inside
18621 an embedded LaTeX fragment, let `texmathp' do its job.
18622 `\\[org-cdlatex-mode-map]'"
18623 (interactive)
18624 (let (p)
18625 (cond
18626 ((not (derived-mode-p 'org-mode)) ad-do-it)
18627 ((eq this-command 'cdlatex-math-symbol)
18628 (setq ad-return-value t
18629 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18631 (let ((p (org-inside-LaTeX-fragment-p)))
18632 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18633 (setq ad-return-value t
18634 texmathp-why '("Org mode embedded math" . 0))
18635 (when p ad-do-it)))))))))
18637 (defun turn-on-org-cdlatex ()
18638 "Unconditionally turn on `org-cdlatex-mode'."
18639 (org-cdlatex-mode 1))
18641 (defun org-try-cdlatex-tab ()
18642 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18643 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18644 - inside a LaTeX fragment, or
18645 - after the first word in a line, where an abbreviation expansion could
18646 insert a LaTeX environment."
18647 (when org-cdlatex-mode
18648 (cond
18649 ;; Before any word on the line: No expansion possible.
18650 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18651 ;; Just after first word on the line: Expand it. Make sure it
18652 ;; cannot happen on headlines, though.
18653 ((save-excursion
18654 (skip-chars-backward "a-zA-Z0-9*")
18655 (skip-chars-backward " \t")
18656 (and (bolp) (not (org-at-heading-p))))
18657 (cdlatex-tab) t)
18658 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18660 (defun org-cdlatex-underscore-caret (&optional _arg)
18661 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18662 Revert to the normal definition outside of these fragments."
18663 (interactive "P")
18664 (if (org-inside-LaTeX-fragment-p)
18665 (call-interactively 'cdlatex-sub-superscript)
18666 (let (org-cdlatex-mode)
18667 (call-interactively (key-binding (vector last-input-event))))))
18669 (defun org-cdlatex-math-modify (&optional _arg)
18670 "Execute `cdlatex-math-modify' in LaTeX fragments.
18671 Revert to the normal definition outside of these fragments."
18672 (interactive "P")
18673 (if (org-inside-LaTeX-fragment-p)
18674 (call-interactively 'cdlatex-math-modify)
18675 (let (org-cdlatex-mode)
18676 (call-interactively (key-binding (vector last-input-event))))))
18678 (defun org-cdlatex-environment-indent (&optional environment item)
18679 "Execute `cdlatex-environment' and indent the inserted environment.
18681 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18683 The inserted environment is indented to current indentation
18684 unless point is at the beginning of the line, in which the
18685 environment remains unintended."
18686 (interactive)
18687 ;; cdlatex-environment always return nil. Therefore, capture output
18688 ;; first and determine if an environment was selected.
18689 (let* ((beg (point-marker))
18690 (end (copy-marker (point) t))
18691 (inserted (progn
18692 (ignore-errors (cdlatex-environment environment item))
18693 (< beg end)))
18694 ;; Figure out how many lines to move forward after the
18695 ;; environment has been inserted.
18696 (lines (when inserted
18697 (save-excursion
18698 (- (cl-loop while (< beg (point))
18699 with x = 0
18700 do (forward-line -1)
18701 (cl-incf x)
18702 finally return x)
18703 (if (progn (goto-char beg)
18704 (and (progn (skip-chars-forward " \t") (eolp))
18705 (progn (skip-chars-backward " \t") (bolp))))
18706 1 0)))))
18707 (env (org-trim (delete-and-extract-region beg end))))
18708 (when inserted
18709 ;; Get indentation of next line unless at column 0.
18710 (let ((ind (if (bolp) 0
18711 (save-excursion
18712 (org-return-indent)
18713 (prog1 (org-get-indentation)
18714 (when (progn (skip-chars-forward " \t") (eolp))
18715 (delete-region beg (point)))))))
18716 (bol (progn (skip-chars-backward " \t") (bolp))))
18717 ;; Insert a newline before environment unless at column zero
18718 ;; to "escape" the current line. Insert a newline if
18719 ;; something is one the same line as \end{ENVIRONMENT}.
18720 (insert
18721 (concat (unless bol "\n") env
18722 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18723 (unless (zerop ind)
18724 (save-excursion
18725 (goto-char beg)
18726 (while (< (point) end)
18727 (unless (eolp) (indent-line-to ind))
18728 (forward-line))))
18729 (goto-char beg)
18730 (forward-line lines)
18731 (indent-line-to ind)))
18732 (set-marker beg nil)
18733 (set-marker end nil)))
18736 ;;;; LaTeX fragments
18738 (defun org-inside-LaTeX-fragment-p ()
18739 "Test if point is inside a LaTeX fragment.
18740 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18741 sequence appearing also before point.
18742 Even though the matchers for math are configurable, this function assumes
18743 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18744 delimiters are skipped when they have been removed by customization.
18745 The return value is nil, or a cons cell with the delimiter and the
18746 position of this delimiter.
18748 This function does a reasonably good job, but can locally be fooled by
18749 for example currency specifications. For example it will assume being in
18750 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18751 fragments that are properly closed, but during editing, we have to live
18752 with the uncertainty caused by missing closing delimiters. This function
18753 looks only before point, not after."
18754 (catch 'exit
18755 (let ((pos (point))
18756 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18757 (lim (save-excursion (org-backward-paragraph) (point)))
18758 dd-on str (start 0) m re)
18759 (goto-char pos)
18760 (when dodollar
18761 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18762 re (nth 1 (assoc "$" org-latex-regexps)))
18763 (while (string-match re str start)
18764 (cond
18765 ((= (match-end 0) (length str))
18766 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18767 ((= (match-end 0) (- (length str) 5))
18768 (throw 'exit nil))
18769 (t (setq start (match-end 0))))))
18770 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18771 (goto-char pos)
18772 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18773 (and (match-beginning 2) (throw 'exit nil))
18774 ;; count $$
18775 (while (re-search-backward "\\$\\$" lim t)
18776 (setq dd-on (not dd-on)))
18777 (goto-char pos)
18778 (when dd-on (cons "$$" m))))))
18780 (defun org-inside-latex-macro-p ()
18781 "Is point inside a LaTeX macro or its arguments?"
18782 (save-match-data
18783 (org-in-regexp
18784 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18786 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18787 "Build an overlay between BEG and END using IMAGE file.
18788 Argument IMAGETYPE is the extension of the displayed image,
18789 as a string. It defaults to \"png\"."
18790 (let ((ov (make-overlay beg end))
18791 (imagetype (or (intern imagetype) 'png)))
18792 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18793 (overlay-put ov 'evaporate t)
18794 (overlay-put ov
18795 'modification-hooks
18796 (list (lambda (o _flag _beg _end &optional _l)
18797 (delete-overlay o))))
18798 (overlay-put ov
18799 'display
18800 (list 'image :type imagetype :file image :ascent 'center))))
18802 (defun org--list-latex-overlays (&optional beg end)
18803 "List all Org LaTeX overlays in current buffer.
18804 Limit to overlays between BEG and END when those are provided."
18805 (cl-remove-if-not
18806 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18807 (overlays-in (or beg (point-min)) (or end (point-max)))))
18809 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18810 "Remove all overlays with LaTeX fragment images in current buffer.
18811 When optional arguments BEG and END are non-nil, remove all
18812 overlays between them instead. Return a non-nil value when some
18813 overlays were removed, nil otherwise."
18814 (let ((overlays (org--list-latex-overlays beg end)))
18815 (mapc #'delete-overlay overlays)
18816 overlays))
18818 (defun org-toggle-latex-fragment (&optional arg)
18819 "Preview the LaTeX fragment at point, or all locally or globally.
18821 If the cursor is on a LaTeX fragment, create the image and overlay
18822 it over the source code, if there is none. Remove it otherwise.
18823 If there is no fragment at point, display all fragments in the
18824 current section.
18826 With prefix ARG, preview or clear image for all fragments in the
18827 current subtree or in the whole buffer when used before the first
18828 headline. With a prefix ARG `\\[universal-argument] \
18829 \\[universal-argument]' preview or clear images
18830 for all fragments in the buffer."
18831 (interactive "P")
18832 (when (display-graphic-p)
18833 (catch 'exit
18834 (save-excursion
18835 (let (beg end msg)
18836 (cond
18837 ((or (equal arg '(16))
18838 (and (equal arg '(4))
18839 (org-with-limited-levels (org-before-first-heading-p))))
18840 (if (org-remove-latex-fragment-image-overlays)
18841 (progn (message "LaTeX fragments images removed from buffer")
18842 (throw 'exit nil))
18843 (setq msg "Creating images for buffer...")))
18844 ((equal arg '(4))
18845 (org-with-limited-levels (org-back-to-heading t))
18846 (setq beg (point))
18847 (setq end (progn (org-end-of-subtree t) (point)))
18848 (if (org-remove-latex-fragment-image-overlays beg end)
18849 (progn
18850 (message "LaTeX fragment images removed from subtree")
18851 (throw 'exit nil))
18852 (setq msg "Creating images for subtree...")))
18853 ((let ((datum (org-element-context)))
18854 (when (memq (org-element-type datum)
18855 '(latex-environment latex-fragment))
18856 (setq beg (org-element-property :begin datum))
18857 (setq end (org-element-property :end datum))
18858 (if (org-remove-latex-fragment-image-overlays beg end)
18859 (progn (message "LaTeX fragment image removed")
18860 (throw 'exit nil))
18861 (setq msg "Creating image...")))))
18863 (org-with-limited-levels
18864 (setq beg (if (org-at-heading-p) (line-beginning-position)
18865 (outline-previous-heading)
18866 (point)))
18867 (setq end (progn (outline-next-heading) (point)))
18868 (if (org-remove-latex-fragment-image-overlays beg end)
18869 (progn
18870 (message "LaTeX fragment images removed from section")
18871 (throw 'exit nil))
18872 (setq msg "Creating images for section...")))))
18873 (let ((file (buffer-file-name (buffer-base-buffer))))
18874 (org-format-latex
18875 (concat org-preview-latex-image-directory "org-ltximg")
18876 beg end
18877 ;; Emacs cannot overlay images from remote hosts. Create
18878 ;; it in `temporary-file-directory' instead.
18879 (if (or (not file) (file-remote-p file))
18880 temporary-file-directory
18881 default-directory)
18882 'overlays msg 'forbuffer org-preview-latex-default-process))
18883 (message (concat msg "done")))))))
18885 (defun org-format-latex
18886 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18887 "Replace LaTeX fragments with links to an image.
18889 The function takes care of creating the replacement image.
18891 Only consider fragments between BEG and END when those are
18892 provided.
18894 When optional argument OVERLAYS is non-nil, display the image on
18895 top of the fragment instead of replacing it.
18897 PROCESSING-TYPE is the conversion method to use, as a symbol.
18899 Some of the options can be changed using the variable
18900 `org-format-latex-options', which see."
18901 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18902 (unless (eq processing-type 'verbatim)
18903 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18904 (cnt 0)
18905 checkdir-flag)
18906 (goto-char (or beg (point-min)))
18907 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18908 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18909 (overlay-recenter (or end (point-max))))
18910 (while (re-search-forward math-regexp end t)
18911 (unless (and overlays
18912 (eq (get-char-property (point) 'org-overlay-type)
18913 'org-latex-overlay))
18914 (let* ((context (org-element-context))
18915 (type (org-element-type context)))
18916 (when (memq type '(latex-environment latex-fragment))
18917 (let ((block-type (eq type 'latex-environment))
18918 (value (org-element-property :value context))
18919 (beg (org-element-property :begin context))
18920 (end (save-excursion
18921 (goto-char (org-element-property :end context))
18922 (skip-chars-backward " \r\t\n")
18923 (point))))
18924 (cond
18925 ((eq processing-type 'mathjax)
18926 ;; Prepare for MathJax processing.
18927 (if (not (string-match "\\`\\$\\$?" value))
18928 (goto-char end)
18929 (delete-region beg end)
18930 (if (string= (match-string 0 value) "$$")
18931 (insert "\\[" (substring value 2 -2) "\\]")
18932 (insert "\\(" (substring value 1 -1) "\\)"))))
18933 ((assq processing-type org-preview-latex-process-alist)
18934 ;; Process to an image.
18935 (cl-incf cnt)
18936 (goto-char beg)
18937 (let* ((processing-info
18938 (cdr (assq processing-type org-preview-latex-process-alist)))
18939 (face (face-at-point))
18940 ;; Get the colors from the face at point.
18942 (let ((color (plist-get org-format-latex-options
18943 :foreground)))
18944 (if (and forbuffer (eq color 'auto))
18945 (face-attribute face :foreground nil 'default)
18946 color)))
18948 (let ((color (plist-get org-format-latex-options
18949 :background)))
18950 (if (and forbuffer (eq color 'auto))
18951 (face-attribute face :background nil 'default)
18952 color)))
18953 (hash (sha1 (prin1-to-string
18954 (list org-format-latex-header
18955 org-latex-default-packages-alist
18956 org-latex-packages-alist
18957 org-format-latex-options
18958 forbuffer value fg bg))))
18959 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18960 (absprefix (expand-file-name prefix dir))
18961 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18962 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18963 (sep (and block-type "\n\n"))
18964 (link (concat sep "[[file:" linkfile "]]" sep))
18965 (options
18966 (org-combine-plists
18967 org-format-latex-options
18968 `(:foreground ,fg :background ,bg))))
18969 (when msg (message msg cnt))
18970 (unless checkdir-flag ; Ensure the directory exists.
18971 (setq checkdir-flag t)
18972 (let ((todir (file-name-directory absprefix)))
18973 (unless (file-directory-p todir)
18974 (make-directory todir t))))
18975 (unless (file-exists-p movefile)
18976 (org-create-formula-image
18977 value movefile options forbuffer processing-type))
18978 (if overlays
18979 (progn
18980 (dolist (o (overlays-in beg end))
18981 (when (eq (overlay-get o 'org-overlay-type)
18982 'org-latex-overlay)
18983 (delete-overlay o)))
18984 (org--format-latex-make-overlay beg end movefile imagetype)
18985 (goto-char end))
18986 (delete-region beg end)
18987 (insert
18988 (org-add-props link
18989 (list 'org-latex-src
18990 (replace-regexp-in-string "\"" "" value)
18991 'org-latex-src-embed-type
18992 (if block-type 'paragraph 'character)))))))
18993 ((eq processing-type 'mathml)
18994 ;; Process to MathML.
18995 (unless (org-format-latex-mathml-available-p)
18996 (user-error "LaTeX to MathML converter not configured"))
18997 (cl-incf cnt)
18998 (when msg (message msg cnt))
18999 (goto-char beg)
19000 (delete-region beg end)
19001 (insert (org-format-latex-as-mathml
19002 value block-type prefix dir)))
19004 (error "Unknown conversion process %s for LaTeX fragments"
19005 processing-type)))))))))))
19007 (defun org-create-math-formula (latex-frag &optional mathml-file)
19008 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19009 Use `org-latex-to-mathml-convert-command'. If the conversion is
19010 sucessful, return the portion between \"<math...> </math>\"
19011 elements otherwise return nil. When MATHML-FILE is specified,
19012 write the results in to that file. When invoked as an
19013 interactive command, prompt for LATEX-FRAG, with initial value
19014 set to the current active region and echo the results for user
19015 inspection."
19016 (interactive (list (let ((frag (when (org-region-active-p)
19017 (buffer-substring-no-properties
19018 (region-beginning) (region-end)))))
19019 (read-string "LaTeX Fragment: " frag nil frag))))
19020 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19021 (let* ((tmp-in-file
19022 (let ((file (file-relative-name
19023 (make-temp-name (expand-file-name "ltxmathml-in")))))
19024 (write-region latex-frag nil file)
19025 file))
19026 (tmp-out-file (file-relative-name
19027 (make-temp-name (expand-file-name "ltxmathml-out"))))
19028 (cmd (format-spec
19029 org-latex-to-mathml-convert-command
19030 `((?j . ,(and org-latex-to-mathml-jar-file
19031 (shell-quote-argument
19032 (expand-file-name
19033 org-latex-to-mathml-jar-file))))
19034 (?I . ,(shell-quote-argument tmp-in-file))
19035 (?i . ,latex-frag)
19036 (?o . ,(shell-quote-argument tmp-out-file)))))
19037 mathml shell-command-output)
19038 (when (called-interactively-p 'any)
19039 (unless (org-format-latex-mathml-available-p)
19040 (user-error "LaTeX to MathML converter not configured")))
19041 (message "Running %s" cmd)
19042 (setq shell-command-output (shell-command-to-string cmd))
19043 (setq mathml
19044 (when (file-readable-p tmp-out-file)
19045 (with-current-buffer (find-file-noselect tmp-out-file t)
19046 (goto-char (point-min))
19047 (when (re-search-forward
19048 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19049 (regexp-quote
19050 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19051 nil t)
19052 (prog1 (match-string 0) (kill-buffer))))))
19053 (cond
19054 (mathml
19055 (setq mathml
19056 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19057 (when mathml-file
19058 (write-region mathml nil mathml-file))
19059 (when (called-interactively-p 'any)
19060 (message mathml)))
19061 ((message "LaTeX to MathML conversion failed")
19062 (message shell-command-output)))
19063 (delete-file tmp-in-file)
19064 (when (file-exists-p tmp-out-file)
19065 (delete-file tmp-out-file))
19066 mathml))
19068 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19069 prefix &optional dir)
19070 "Use `org-create-math-formula' but check local cache first."
19071 (let* ((absprefix (expand-file-name prefix dir))
19072 (print-length nil) (print-level nil)
19073 (formula-id (concat
19074 "formula-"
19075 (sha1
19076 (prin1-to-string
19077 (list latex-frag
19078 org-latex-to-mathml-convert-command)))))
19079 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19080 (formula-cache-dir (file-name-directory formula-cache)))
19082 (unless (file-directory-p formula-cache-dir)
19083 (make-directory formula-cache-dir t))
19085 (unless (file-exists-p formula-cache)
19086 (org-create-math-formula latex-frag formula-cache))
19088 (if (file-exists-p formula-cache)
19089 ;; Successful conversion. Return the link to MathML file.
19090 (org-add-props
19091 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19092 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19093 'org-latex-src-embed-type (if latex-frag-type
19094 'paragraph 'character)))
19095 ;; Failed conversion. Return the LaTeX fragment verbatim
19096 latex-frag)))
19098 (defun org--get-display-dpi ()
19099 "Get the DPI of the display.
19100 The function assumes that the display has the same pixel width in
19101 the horizontal and vertical directions."
19102 (if (display-graphic-p)
19103 (round (/ (display-pixel-height)
19104 (/ (display-mm-height) 25.4)))
19105 (error "Attempt to calculate the dpi of a non-graphic display")))
19107 (defun org-create-formula-image
19108 (string tofile options buffer &optional processing-type)
19109 "Create an image from LaTeX source using external processes.
19111 The LaTeX STRING is saved to a temporary LaTeX file, then
19112 converted to an image file by process PROCESSING-TYPE defined in
19113 `org-preview-latex-process-alist'. A nil value defaults to
19114 `org-preview-latex-default-process'.
19116 The generated image file is eventually moved to TOFILE.
19118 The OPTIONS argument controls the size, foreground color and
19119 background color of the generated image.
19121 When BUFFER non-nil, this function is used for LaTeX previewing.
19122 Otherwise, it is used to deal with LaTeX snippets showed in
19123 a HTML file."
19124 (let* ((processing-type (or processing-type
19125 org-preview-latex-default-process))
19126 (processing-info
19127 (cdr (assq processing-type org-preview-latex-process-alist)))
19128 (programs (plist-get processing-info :programs))
19129 (error-message (or (plist-get processing-info :message) ""))
19130 (use-xcolor (plist-get processing-info :use-xcolor))
19131 (image-input-type (plist-get processing-info :image-input-type))
19132 (image-output-type (plist-get processing-info :image-output-type))
19133 (post-clean (or (plist-get processing-info :post-clean)
19134 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19135 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19136 (latex-header
19137 (or (plist-get processing-info :latex-header)
19138 (org-latex-make-preamble
19139 (org-export-get-environment (org-export-get-backend 'latex))
19140 org-format-latex-header
19141 'snippet)))
19142 (latex-compiler (plist-get processing-info :latex-compiler))
19143 (image-converter (plist-get processing-info :image-converter))
19144 (tmpdir temporary-file-directory)
19145 (texfilebase (make-temp-name
19146 (expand-file-name "orgtex" tmpdir)))
19147 (texfile (concat texfilebase ".tex"))
19148 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19149 '(1.0 . 1.0)))
19150 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19151 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19152 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19153 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19154 "Black"))
19155 (bg (or (plist-get options (if buffer :background :html-background))
19156 "Transparent"))
19157 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19158 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19159 (dolist (program programs)
19160 (org-check-external-command program error-message))
19161 (if use-xcolor
19162 (progn (if (eq fg 'default)
19163 (setq fg (org-latex-color :foreground))
19164 (setq fg (org-latex-color-format fg)))
19165 (if (eq bg 'default)
19166 (setq bg (org-latex-color :background))
19167 (setq bg (org-latex-color-format
19168 (if (string= bg "Transparent") "white" bg))))
19169 (with-temp-file texfile
19170 (insert latex-header)
19171 (insert "\n\\begin{document}\n"
19172 "\\definecolor{fg}{rgb}{" fg "}\n"
19173 "\\definecolor{bg}{rgb}{" bg "}\n"
19174 "\n\\pagecolor{bg}\n"
19175 "\n{\\color{fg}\n"
19176 string
19177 "\n}\n"
19178 "\n\\end{document}\n")))
19179 (if (eq fg 'default)
19180 (setq fg (org-dvipng-color :foreground))
19181 (unless (string= fg "Transparent")
19182 (setq fg (org-dvipng-color-format fg))))
19183 (if (eq bg 'default)
19184 (setq bg (org-dvipng-color :background))
19185 (unless (string= bg "Transparent")
19186 (setq bg (org-dvipng-color-format bg))))
19187 (with-temp-file texfile
19188 (insert latex-header)
19189 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19191 (let* ((err-msg (format "Please adjust `%s' part of \
19192 `org-preview-latex-process-alist'."
19193 processing-type))
19194 (image-input-file
19195 (org-compile-file
19196 texfile latex-compiler image-input-type err-msg log-buf))
19197 (image-output-file
19198 (org-compile-file
19199 image-input-file image-converter image-output-type err-msg log-buf
19200 `((?F . ,(shell-quote-argument fg))
19201 (?B . ,(shell-quote-argument bg))
19202 (?D . ,(shell-quote-argument (format "%s" dpi)))
19203 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19204 (copy-file image-output-file tofile 'replace)
19205 (dolist (e post-clean)
19206 (when (file-exists-p (concat texfilebase e))
19207 (delete-file (concat texfilebase e))))
19208 image-output-file)))
19210 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19211 "Fill a LaTeX header template TPL.
19212 In the template, the following place holders will be recognized:
19214 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19215 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19216 [PACKAGES] \\usepackage statements for PKG
19217 [NO-PACKAGES] do not include PKG
19218 [EXTRA] the string EXTRA
19219 [NO-EXTRA] do not include EXTRA
19221 For backward compatibility, if both the positive and the negative place
19222 holder is missing, the positive one (without the \"NO-\") will be
19223 assumed to be present at the end of the template.
19224 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19225 EXTRA is a string.
19226 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19227 (let (rpl (end ""))
19228 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19229 (setq rpl (if (or (match-end 1) (not def-pkg))
19230 "" (org-latex-packages-to-string def-pkg snippets-p t))
19231 tpl (replace-match rpl t t tpl))
19232 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19234 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19235 (setq rpl (if (or (match-end 1) (not pkg))
19236 "" (org-latex-packages-to-string pkg snippets-p t))
19237 tpl (replace-match rpl t t tpl))
19238 (when pkg (setq end
19239 (concat end "\n"
19240 (org-latex-packages-to-string pkg snippets-p)))))
19242 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19243 (setq rpl (if (or (match-end 1) (not extra))
19244 "" (concat extra "\n"))
19245 tpl (replace-match rpl t t tpl))
19246 (when (and extra (string-match "\\S-" extra))
19247 (setq end (concat end "\n" extra))))
19249 (if (string-match "\\S-" end)
19250 (concat tpl "\n" end)
19251 tpl)))
19253 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19254 "Turn an alist of packages into a string with the \\usepackage macros."
19255 (setq pkg (mapconcat (lambda(p)
19256 (cond
19257 ((stringp p) p)
19258 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19259 (format "%% Package %s omitted" (cadr p)))
19260 ((equal "" (car p))
19261 (format "\\usepackage{%s}" (cadr p)))
19263 (format "\\usepackage[%s]{%s}"
19264 (car p) (cadr p)))))
19266 "\n"))
19267 (if newline (concat pkg "\n") pkg))
19269 (defun org-dvipng-color (attr)
19270 "Return a RGB color specification for dvipng."
19271 (org-dvipng-color-format (face-attribute 'default attr nil)))
19273 (defun org-dvipng-color-format (color-name)
19274 "Convert COLOR-NAME to a RGB color value for dvipng."
19275 (apply #'format "rgb %s %s %s"
19276 (mapcar 'org-normalize-color
19277 (color-values color-name))))
19279 (defun org-latex-color (attr)
19280 "Return a RGB color for the LaTeX color package."
19281 (org-latex-color-format (face-attribute 'default attr nil)))
19283 (defun org-latex-color-format (color-name)
19284 "Convert COLOR-NAME to a RGB color value."
19285 (apply #'format "%s,%s,%s"
19286 (mapcar 'org-normalize-color
19287 (color-values color-name))))
19289 (defun org-normalize-color (value)
19290 "Return string to be used as color value for an RGB component."
19291 (format "%g" (/ value 65535.0)))
19295 ;; Image display
19297 (defvar-local org-inline-image-overlays nil)
19299 (defun org-toggle-inline-images (&optional include-linked)
19300 "Toggle the display of inline images.
19301 INCLUDE-LINKED is passed to `org-display-inline-images'."
19302 (interactive "P")
19303 (if org-inline-image-overlays
19304 (progn
19305 (org-remove-inline-images)
19306 (when (called-interactively-p 'interactive)
19307 (message "Inline image display turned off")))
19308 (org-display-inline-images include-linked)
19309 (when (called-interactively-p 'interactive)
19310 (message (if org-inline-image-overlays
19311 (format "%d images displayed inline"
19312 (length org-inline-image-overlays))
19313 "No images to display inline")))))
19315 (defun org-redisplay-inline-images ()
19316 "Refresh the display of inline images."
19317 (interactive)
19318 (if (not org-inline-image-overlays)
19319 (org-toggle-inline-images)
19320 (org-toggle-inline-images)
19321 (org-toggle-inline-images)))
19323 (defun org-display-inline-images (&optional include-linked refresh beg end)
19324 "Display inline images.
19326 An inline image is a link which follows either of these
19327 conventions:
19329 1. Its path is a file with an extension matching return value
19330 from `image-file-name-regexp' and it has no contents.
19332 2. Its description consists in a single link of the previous
19333 type.
19335 When optional argument INCLUDE-LINKED is non-nil, also links with
19336 a text description part will be inlined. This can be nice for
19337 a quick look at those images, but it does not reflect what
19338 exported files will look like.
19340 When optional argument REFRESH is non-nil, refresh existing
19341 images between BEG and END. This will create new image displays
19342 only if necessary. BEG and END default to the buffer
19343 boundaries."
19344 (interactive "P")
19345 (when (display-graphic-p)
19346 (unless refresh
19347 (org-remove-inline-images)
19348 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19349 (org-with-wide-buffer
19350 (goto-char (or beg (point-min)))
19351 (let* ((case-fold-search t)
19352 (file-extension-re (image-file-name-regexp))
19353 (link-abbrevs (mapcar #'car
19354 (append org-link-abbrev-alist-local
19355 org-link-abbrev-alist)))
19356 ;; Check absolute, relative file names and explicit
19357 ;; "file:" links. Also check link abbreviations since
19358 ;; some might expand to "file" links.
19359 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19360 (if (not link-abbrevs) ""
19361 (format "\\|\\(?:%s:\\)"
19362 (regexp-opt link-abbrevs))))))
19363 (while (re-search-forward file-types-re end t)
19364 (let ((link (save-match-data (org-element-context))))
19365 ;; Check if we're at an inline image, i.e., an image file
19366 ;; link without a description (unless INCLUDE-LINKED is
19367 ;; non-nil).
19368 (when (and (equal "file" (org-element-property :type link))
19369 (or include-linked
19370 (null (org-element-contents link)))
19371 (string-match-p file-extension-re
19372 (org-element-property :path link)))
19373 (let ((file (expand-file-name
19374 (org-link-unescape
19375 (org-element-property :path link)))))
19376 (when (file-exists-p file)
19377 (let ((width
19378 ;; Apply `org-image-actual-width' specifications.
19379 (cond
19380 ((not (image-type-available-p 'imagemagick)) nil)
19381 ((eq org-image-actual-width t) nil)
19382 ((listp org-image-actual-width)
19384 ;; First try to find a width among
19385 ;; attributes associated to the paragraph
19386 ;; containing link.
19387 (let ((paragraph
19388 (let ((e link))
19389 (while (and (setq e (org-element-property
19390 :parent e))
19391 (not (eq (org-element-type e)
19392 'paragraph))))
19393 e)))
19394 (when paragraph
19395 (save-excursion
19396 (goto-char (org-element-property :begin paragraph))
19397 (when
19398 (re-search-forward
19399 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19400 (org-element-property
19401 :post-affiliated paragraph)
19403 (string-to-number (match-string 1))))))
19404 ;; Otherwise, fall-back to provided number.
19405 (car org-image-actual-width)))
19406 ((numberp org-image-actual-width)
19407 org-image-actual-width)))
19408 (old (get-char-property-and-overlay
19409 (org-element-property :begin link)
19410 'org-image-overlay)))
19411 (if (and (car-safe old) refresh)
19412 (image-refresh (overlay-get (cdr old) 'display))
19413 (let ((image (create-image file
19414 (and width 'imagemagick)
19416 :width width)))
19417 (when image
19418 (let ((ov (make-overlay
19419 (org-element-property :begin link)
19420 (progn
19421 (goto-char
19422 (org-element-property :end link))
19423 (skip-chars-backward " \t")
19424 (point)))))
19425 (overlay-put ov 'display image)
19426 (overlay-put ov 'face 'default)
19427 (overlay-put ov 'org-image-overlay t)
19428 (overlay-put
19429 ov 'modification-hooks
19430 (list 'org-display-inline-remove-overlay))
19431 (push ov org-inline-image-overlays)))))))))))))))
19433 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19434 "Remove inline-display overlay if a corresponding region is modified."
19435 (let ((inhibit-modification-hooks t))
19436 (when (and ov after)
19437 (delete ov org-inline-image-overlays)
19438 (delete-overlay ov))))
19440 (defun org-remove-inline-images ()
19441 "Remove inline display of images."
19442 (interactive)
19443 (mapc #'delete-overlay org-inline-image-overlays)
19444 (setq org-inline-image-overlays nil))
19446 ;;;; Key bindings
19448 (defun org-remap (map &rest commands)
19449 "In MAP, remap the functions given in COMMANDS.
19450 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19451 (let (new old)
19452 (while commands
19453 (setq old (pop commands) new (pop commands))
19454 (org-defkey map (vector 'remap old) new))))
19456 ;; Outline functions from `outline-mode-prefix-map'
19457 ;; that can be remapped in Org:
19458 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19459 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19460 (define-key org-mode-map [remap outline-forward-same-level]
19461 'org-forward-heading-same-level)
19462 (define-key org-mode-map [remap outline-backward-same-level]
19463 'org-backward-heading-same-level)
19464 (define-key org-mode-map [remap outline-show-branches]
19465 'org-kill-note-or-show-branches)
19466 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19467 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19468 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19469 (define-key org-mode-map [remap outline-next-visible-heading]
19470 'org-next-visible-heading)
19471 (define-key org-mode-map [remap outline-previous-visible-heading]
19472 'org-previous-visible-heading)
19473 (define-key org-mode-map [remap show-children] 'org-show-children)
19475 ;; Outline functions from `outline-mode-prefix-map' that can not
19476 ;; be remapped in Org:
19478 ;; - the column "key binding" shows whether the Outline function is still
19479 ;; available in Org mode on the same key that it has been bound to in
19480 ;; Outline mode:
19481 ;; - "overridden": key used for a different functionality in Org mode
19482 ;; - else: key still bound to the same Outline function in Org mode
19484 ;; | Outline function | key binding | Org replacement |
19485 ;; |------------------------------------+-------------+--------------------------|
19486 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19487 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19488 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19489 ;; | `show-entry' | overridden | no replacement |
19490 ;; | `show-branches' | `C-c C-k' | still same function |
19491 ;; | `show-subtree' | overridden | visibility cycling |
19492 ;; | `show-all' | overridden | no replacement |
19493 ;; | `hide-subtree' | overridden | visibility cycling |
19494 ;; | `hide-body' | overridden | no replacement |
19495 ;; | `hide-entry' | overridden | visibility cycling |
19496 ;; | `hide-leaves' | overridden | no replacement |
19497 ;; | `hide-sublevels' | overridden | no replacement |
19498 ;; | `hide-other' | overridden | no replacement |
19500 ;; Make `C-c C-x' a prefix key
19501 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19503 ;; TAB key with modifiers
19504 (org-defkey org-mode-map "\C-i" 'org-cycle)
19505 (org-defkey org-mode-map [(tab)] 'org-cycle)
19506 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19507 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19509 ;; The following line is necessary under Suse GNU/Linux
19510 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19511 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19512 (define-key org-mode-map [backtab] 'org-shifttab)
19514 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19515 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19516 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19518 ;; Cursor keys with modifiers
19519 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19520 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19521 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19522 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19524 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19525 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19526 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19527 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19528 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19529 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19531 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19532 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19533 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19534 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19536 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19537 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19538 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19539 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19541 ;; Babel keys
19542 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19543 (dolist (pair org-babel-key-bindings)
19544 (define-key org-babel-map (car pair) (cdr pair)))
19546 ;;; Extra keys for tty access.
19547 ;; We only set them when really needed because otherwise the
19548 ;; menus don't show the simple keys
19550 (when (or org-use-extra-keys (not window-system))
19551 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19552 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19553 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19554 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19555 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19556 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19557 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19558 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19559 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19560 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19561 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19562 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19563 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19564 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19565 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19566 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19567 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19568 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19569 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19570 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19571 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19572 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19573 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19574 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19575 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19576 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19577 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19578 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19580 ;; All the other keys
19581 (org-remap org-mode-map
19582 'self-insert-command 'org-self-insert-command
19583 'delete-char 'org-delete-char
19584 'delete-backward-char 'org-delete-backward-char)
19585 (org-defkey org-mode-map "|" 'org-force-self-insert)
19587 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19588 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19589 (if (boundp 'narrow-map)
19590 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19591 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19592 (if (boundp 'narrow-map)
19593 (org-defkey narrow-map "b" 'org-narrow-to-block)
19594 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19595 (if (boundp 'narrow-map)
19596 (org-defkey narrow-map "e" 'org-narrow-to-element)
19597 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19598 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19599 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19600 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19601 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19602 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19603 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19604 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19605 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19606 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19607 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19608 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19609 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19610 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19611 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19612 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19613 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19614 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19615 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19616 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19617 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19618 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19619 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19620 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19621 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19622 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19623 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19624 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19625 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19626 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19627 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19628 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19629 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19630 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19631 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19632 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19633 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19634 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19635 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19636 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19637 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19638 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19639 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19640 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19641 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19642 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19643 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19644 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19645 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19646 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19647 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19648 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19649 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19650 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19651 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19652 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19653 (org-defkey org-mode-map "\C-c^" 'org-sort)
19654 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19655 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19656 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19657 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19658 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19659 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19660 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19661 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19662 (org-defkey org-mode-map "\C-m" 'org-return)
19663 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19664 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19665 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19666 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19667 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19668 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19669 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19670 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19671 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19672 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19673 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19674 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19675 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19676 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19677 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19678 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19679 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19680 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19681 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19682 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19683 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19684 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19685 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19686 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19687 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19689 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19690 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19691 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19693 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19694 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19695 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19696 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19697 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19698 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19699 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19700 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19701 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19702 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19703 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19704 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19705 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19706 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19707 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19708 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19709 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19710 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19711 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19712 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19713 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19714 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19716 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19717 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19718 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19719 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19720 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19722 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19724 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19726 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19727 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19729 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19732 (defconst org-speed-commands-default
19734 ("Outline Navigation")
19735 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19736 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19737 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19738 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19739 ("F" . org-next-block)
19740 ("B" . org-previous-block)
19741 ("u" . (org-speed-move-safe 'outline-up-heading))
19742 ("j" . org-goto)
19743 ("g" . (org-refile t))
19744 ("Outline Visibility")
19745 ("c" . org-cycle)
19746 ("C" . org-shifttab)
19747 (" " . org-display-outline-path)
19748 ("s" . org-narrow-to-subtree)
19749 ("=" . org-columns)
19750 ("Outline Structure Editing")
19751 ("U" . org-metaup)
19752 ("D" . org-metadown)
19753 ("r" . org-metaright)
19754 ("l" . org-metaleft)
19755 ("R" . org-shiftmetaright)
19756 ("L" . org-shiftmetaleft)
19757 ("i" . (progn (forward-char 1) (call-interactively
19758 'org-insert-heading-respect-content)))
19759 ("^" . org-sort)
19760 ("w" . org-refile)
19761 ("a" . org-archive-subtree-default-with-confirmation)
19762 ("@" . org-mark-subtree)
19763 ("#" . org-toggle-comment)
19764 ("Clock Commands")
19765 ("I" . org-clock-in)
19766 ("O" . org-clock-out)
19767 ("Meta Data Editing")
19768 ("t" . org-todo)
19769 ("," . (org-priority))
19770 ("0" . (org-priority ?\ ))
19771 ("1" . (org-priority ?A))
19772 ("2" . (org-priority ?B))
19773 ("3" . (org-priority ?C))
19774 (":" . org-set-tags-command)
19775 ("e" . org-set-effort)
19776 ("E" . org-inc-effort)
19777 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19778 (org-entry-put (point) "APPT_WARNTIME" m)))
19779 ("Agenda Views etc")
19780 ("v" . org-agenda)
19781 ("/" . org-sparse-tree)
19782 ("Misc")
19783 ("o" . org-open-at-point)
19784 ("?" . org-speed-command-help)
19785 ("<" . (org-agenda-set-restriction-lock 'subtree))
19786 (">" . (org-agenda-remove-restriction-lock))
19788 "The default speed commands.")
19790 (defun org-print-speed-command (e)
19791 (if (> (length (car e)) 1)
19792 (progn
19793 (princ "\n")
19794 (princ (car e))
19795 (princ "\n")
19796 (princ (make-string (length (car e)) ?-))
19797 (princ "\n"))
19798 (princ (car e))
19799 (princ " ")
19800 (if (symbolp (cdr e))
19801 (princ (symbol-name (cdr e)))
19802 (prin1 (cdr e)))
19803 (princ "\n")))
19805 (defun org-speed-command-help ()
19806 "Show the available speed commands."
19807 (interactive)
19808 (if (not org-use-speed-commands)
19809 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19810 (with-output-to-temp-buffer "*Help*"
19811 (princ "User-defined Speed commands\n===========================\n")
19812 (mapc #'org-print-speed-command org-speed-commands-user)
19813 (princ "\n")
19814 (princ "Built-in Speed commands\n=======================\n")
19815 (mapc #'org-print-speed-command org-speed-commands-default))
19816 (with-current-buffer "*Help*"
19817 (setq truncate-lines t))))
19819 (defun org-speed-move-safe (cmd)
19820 "Execute CMD, but make sure that the cursor always ends up in a headline.
19821 If not, return to the original position and throw an error."
19822 (interactive)
19823 (let ((pos (point)))
19824 (call-interactively cmd)
19825 (unless (and (bolp) (org-at-heading-p))
19826 (goto-char pos)
19827 (error "Boundary reached while executing %s" cmd))))
19829 (defvar org-self-insert-command-undo-counter 0)
19831 (defvar org-table-auto-blank-field) ; defined in org-table.el
19832 (defvar org-speed-command nil)
19834 (defun org-speed-command-activate (keys)
19835 "Hook for activating single-letter speed commands.
19836 `org-speed-commands-default' specifies a minimal command set.
19837 Use `org-speed-commands-user' for further customization."
19838 (when (or (and (bolp) (looking-at org-outline-regexp))
19839 (and (functionp org-use-speed-commands)
19840 (funcall org-use-speed-commands)))
19841 (cdr (assoc keys (append org-speed-commands-user
19842 org-speed-commands-default)))))
19844 (defun org-babel-speed-command-activate (keys)
19845 "Hook for activating single-letter code block commands."
19846 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19847 (cdr (assoc keys org-babel-key-bindings))))
19849 (defcustom org-speed-command-hook
19850 '(org-speed-command-activate org-babel-speed-command-activate)
19851 "Hook for activating speed commands at strategic locations.
19852 Hook functions are called in sequence until a valid handler is
19853 found.
19855 Each hook takes a single argument, a user-pressed command key
19856 which is also a `self-insert-command' from the global map.
19858 Within the hook, examine the cursor position and the command key
19859 and return nil or a valid handler as appropriate. Handler could
19860 be one of an interactive command, a function, or a form.
19862 Set `org-use-speed-commands' to non-nil value to enable this
19863 hook. The default setting is `org-speed-command-activate'."
19864 :group 'org-structure
19865 :version "24.1"
19866 :type 'hook)
19868 (defun org-self-insert-command (N)
19869 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19870 If the cursor is in a table looking at whitespace, the whitespace is
19871 overwritten, and the table is not marked as requiring realignment."
19872 (interactive "p")
19873 (org-check-before-invisible-edit 'insert)
19874 (cond
19875 ((and org-use-speed-commands
19876 (let ((kv (this-command-keys-vector)))
19877 (setq org-speed-command
19878 (run-hook-with-args-until-success
19879 'org-speed-command-hook
19880 (make-string 1 (aref kv (1- (length kv))))))))
19881 (cond
19882 ((commandp org-speed-command)
19883 (setq this-command org-speed-command)
19884 (call-interactively org-speed-command))
19885 ((functionp org-speed-command)
19886 (funcall org-speed-command))
19887 ((and org-speed-command (listp org-speed-command))
19888 (eval org-speed-command))
19889 (t (let (org-use-speed-commands)
19890 (call-interactively 'org-self-insert-command)))))
19891 ((and
19892 (org-at-table-p)
19893 (eq N 1)
19894 (not (org-region-active-p))
19895 (progn
19896 ;; Check if we blank the field, and if that triggers align.
19897 (and (featurep 'org-table) org-table-auto-blank-field
19898 (memq last-command
19899 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19900 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19901 ;; Got extra space, this field does not determine
19902 ;; column width.
19903 (let (org-table-may-need-update) (org-table-blank-field))
19904 ;; No extra space, this field may determine column
19905 ;; width.
19906 (org-table-blank-field)))
19908 (looking-at "[^|\n]* \\( \\)|"))
19909 ;; There is room for insertion without re-aligning the table.
19910 (delete-region (match-beginning 1) (match-end 1))
19911 (self-insert-command N))
19913 (setq org-table-may-need-update t)
19914 (self-insert-command N)
19915 (org-fix-tags-on-the-fly)
19916 (when org-self-insert-cluster-for-undo
19917 (if (not (eq last-command 'org-self-insert-command))
19918 (setq org-self-insert-command-undo-counter 1)
19919 (if (>= org-self-insert-command-undo-counter 20)
19920 (setq org-self-insert-command-undo-counter 1)
19921 (and (> org-self-insert-command-undo-counter 0)
19922 buffer-undo-list (listp buffer-undo-list)
19923 (not (cadr buffer-undo-list)) ; remove nil entry
19924 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19925 (setq org-self-insert-command-undo-counter
19926 (1+ org-self-insert-command-undo-counter))))))))
19928 (defun org-check-before-invisible-edit (kind)
19929 "Check is editing if kind KIND would be dangerous with invisible text around.
19930 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19931 ;; First, try to get out of here as quickly as possible, to reduce overhead
19932 (when (and org-catch-invisible-edits
19933 (or (not (boundp 'visible-mode)) (not visible-mode))
19934 (or (get-char-property (point) 'invisible)
19935 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19936 ;; OK, we need to take a closer look. Do not consider
19937 ;; invisibility obtained through text properties (e.g., link
19938 ;; fontification), as it cannot be toggled.
19939 (let* ((invisible-at-point
19940 (pcase (get-char-property-and-overlay (point) 'invisible)
19941 (`(,_ . ,(and (pred overlayp) o)) o)))
19942 ;; Assume that point cannot land in the middle of an
19943 ;; overlay, or between two overlays.
19944 (invisible-before-point
19945 (and (not invisible-at-point)
19946 (not (bobp))
19947 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19948 (`(,_ . ,(and (pred overlayp) o)) o))))
19949 (border-and-ok-direction
19951 ;; Check if we are acting predictably before invisible
19952 ;; text.
19953 (and invisible-at-point
19954 (memq kind '(insert delete-backward)))
19955 ;; Check if we are acting predictably after invisible text
19956 ;; This works not well, and I have turned it off. It seems
19957 ;; better to always show and stop after invisible text.
19958 ;; (and (not invisible-at-point) invisible-before-point
19959 ;; (memq kind '(insert delete)))
19961 (when (or invisible-at-point invisible-before-point)
19962 (when (eq org-catch-invisible-edits 'error)
19963 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19964 (if (and org-custom-properties-overlays
19965 (y-or-n-p "Display invisible properties in this buffer? "))
19966 (org-toggle-custom-properties-visibility)
19967 ;; Make the area visible
19968 (save-excursion
19969 (when invisible-before-point
19970 (goto-char
19971 (previous-single-char-property-change (point) 'invisible)))
19972 ;; Remove whatever overlay is currently making yet-to-be
19973 ;; edited text invisible. Also remove nested invisibility
19974 ;; related overlays.
19975 (delete-overlay (or invisible-at-point invisible-before-point))
19976 (let ((origin (if invisible-at-point (point) (1- (point)))))
19977 (while (pcase (get-char-property-and-overlay origin 'invisible)
19978 (`(,_ . ,(and (pred overlayp) o))
19979 (delete-overlay o)
19980 t)))))
19981 (cond
19982 ((eq org-catch-invisible-edits 'show)
19983 ;; That's it, we do the edit after showing
19984 (message
19985 "Unfolding invisible region around point before editing")
19986 (sit-for 1))
19987 ((and (eq org-catch-invisible-edits 'smart)
19988 border-and-ok-direction)
19989 (message "Unfolding invisible region around point before editing"))
19991 ;; Don't do the edit, make the user repeat it in full visibility
19992 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19994 (defun org-fix-tags-on-the-fly ()
19995 "Align tags in headline at point.
19996 Unlike to `org-set-tags', it ignores region and sorting."
19997 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19998 (org-at-heading-p))
19999 (let ((org-ignore-region t)
20000 (org-tags-sort-function nil))
20001 (org-set-tags nil t))))
20003 (defun org-delete-backward-char (N)
20004 "Like `delete-backward-char', insert whitespace at field end in tables.
20005 When deleting backwards, in tables this function will insert whitespace in
20006 front of the next \"|\" separator, to keep the table aligned. The table will
20007 still be marked for re-alignment if the field did fill the entire column,
20008 because, in this case the deletion might narrow the column."
20009 (interactive "p")
20010 (save-match-data
20011 (org-check-before-invisible-edit 'delete-backward)
20012 (if (and (org-at-table-p)
20013 (eq N 1)
20014 (not (org-region-active-p))
20015 (string-match "|" (buffer-substring (point-at-bol) (point)))
20016 (looking-at ".*?|"))
20017 (let ((pos (point))
20018 (noalign (looking-at "[^|\n\r]* |"))
20019 (c org-table-may-need-update))
20020 (backward-delete-char N)
20021 (unless overwrite-mode
20022 (skip-chars-forward "^|")
20023 (insert " ")
20024 (goto-char (1- pos)))
20025 ;; noalign: if there were two spaces at the end, this field
20026 ;; does not determine the width of the column.
20027 (when noalign (setq org-table-may-need-update c)))
20028 (backward-delete-char N)
20029 (org-fix-tags-on-the-fly))))
20031 (defun org-delete-char (N)
20032 "Like `delete-char', but insert whitespace at field end in tables.
20033 When deleting characters, in tables this function will insert whitespace in
20034 front of the next \"|\" separator, to keep the table aligned. The table will
20035 still be marked for re-alignment if the field did fill the entire column,
20036 because, in this case the deletion might narrow the column."
20037 (interactive "p")
20038 (save-match-data
20039 (org-check-before-invisible-edit 'delete)
20040 (if (and (org-at-table-p)
20041 (not (bolp))
20042 (not (= (char-after) ?|))
20043 (eq N 1))
20044 (if (looking-at ".*?|")
20045 (let ((pos (point))
20046 (noalign (looking-at "[^|\n\r]* |"))
20047 (c org-table-may-need-update))
20048 (replace-match
20049 (concat (substring (match-string 0) 1 -1) " |") nil t)
20050 (goto-char pos)
20051 ;; noalign: if there were two spaces at the end, this field
20052 ;; does not determine the width of the column.
20053 (when noalign (setq org-table-may-need-update c)))
20054 (delete-char N))
20055 (delete-char N)
20056 (org-fix-tags-on-the-fly))))
20058 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20059 (put 'org-self-insert-command 'delete-selection
20060 (lambda ()
20061 (not (run-hook-with-args-until-success
20062 'self-insert-uses-region-functions))))
20063 (put 'orgtbl-self-insert-command 'delete-selection
20064 (lambda ()
20065 (not (run-hook-with-args-until-success
20066 'self-insert-uses-region-functions))))
20067 (put 'org-delete-char 'delete-selection 'supersede)
20068 (put 'org-delete-backward-char 'delete-selection 'supersede)
20069 (put 'org-yank 'delete-selection 'yank)
20071 ;; Make `flyspell-mode' delay after some commands
20072 (put 'org-self-insert-command 'flyspell-delayed t)
20073 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20074 (put 'org-delete-char 'flyspell-delayed t)
20075 (put 'org-delete-backward-char 'flyspell-delayed t)
20077 ;; Make pabbrev-mode expand after Org mode commands
20078 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20079 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20081 (defun org-transpose-words ()
20082 "Transpose words for Org.
20083 This uses the `org-mode-transpose-word-syntax-table' syntax
20084 table, which interprets characters in `org-emphasis-alist' as
20085 word constituents."
20086 (interactive)
20087 (with-syntax-table org-mode-transpose-word-syntax-table
20088 (call-interactively 'transpose-words)))
20089 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20091 (defvar org-ctrl-c-ctrl-c-hook nil
20092 "Hook for functions attaching themselves to `C-c C-c'.
20094 This can be used to add additional functionality to the C-c C-c
20095 key which executes context-dependent commands. This hook is run
20096 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20097 run after the last test.
20099 Each function will be called with no arguments. The function
20100 must check if the context is appropriate for it to act. If yes,
20101 it should do its thing and then return a non-nil value. If the
20102 context is wrong, just do nothing and return nil.")
20104 (defvar org-ctrl-c-ctrl-c-final-hook nil
20105 "Hook for functions attaching themselves to `C-c C-c'.
20107 This can be used to add additional functionality to the C-c C-c
20108 key which executes context-dependent commands. This hook is run
20109 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20110 before the first test.
20112 Each function will be called with no arguments. The function
20113 must check if the context is appropriate for it to act. If yes,
20114 it should do its thing and then return a non-nil value. If the
20115 context is wrong, just do nothing and return nil.")
20117 (defvar org-tab-first-hook nil
20118 "Hook for functions to attach themselves to TAB.
20119 See `org-ctrl-c-ctrl-c-hook' for more information.
20120 This hook runs as the first action when TAB is pressed, even before
20121 `org-cycle' messes around with the `outline-regexp' to cater for
20122 inline tasks and plain list item folding.
20123 If any function in this hook returns t, any other actions that
20124 would have been caused by TAB (such as table field motion or visibility
20125 cycling) will not occur.")
20127 (defvar org-tab-after-check-for-table-hook nil
20128 "Hook for functions to attach themselves to TAB.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.
20130 This hook runs after it has been established that the cursor is not in a
20131 table, but before checking if the cursor is in a headline or if global cycling
20132 should be done.
20133 If any function in this hook returns t, not other actions like visibility
20134 cycling will be done.")
20136 (defvar org-tab-after-check-for-cycling-hook nil
20137 "Hook for functions to attach themselves to TAB.
20138 See `org-ctrl-c-ctrl-c-hook' for more information.
20139 This hook runs after it has been established that not table field motion and
20140 not visibility should be done because of current context. This is probably
20141 the place where a package like yasnippets can hook in.")
20143 (defvar org-tab-before-tab-emulation-hook nil
20144 "Hook for functions to attach themselves to TAB.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.
20146 This hook runs after every other options for TAB have been exhausted, but
20147 before indentation and \t insertion takes place.")
20149 (defvar org-metaleft-hook nil
20150 "Hook for functions attaching themselves to `M-left'.
20151 See `org-ctrl-c-ctrl-c-hook' for more information.")
20152 (defvar org-metaright-hook nil
20153 "Hook for functions attaching themselves to `M-right'.
20154 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defvar org-metaup-hook nil
20156 "Hook for functions attaching themselves to `M-up'.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-metadown-hook nil
20159 "Hook for functions attaching themselves to `M-down'.
20160 See `org-ctrl-c-ctrl-c-hook' for more information.")
20161 (defvar org-shiftmetaleft-hook nil
20162 "Hook for functions attaching themselves to `M-S-left'.
20163 See `org-ctrl-c-ctrl-c-hook' for more information.")
20164 (defvar org-shiftmetaright-hook nil
20165 "Hook for functions attaching themselves to `M-S-right'.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.")
20167 (defvar org-shiftmetaup-hook nil
20168 "Hook for functions attaching themselves to `M-S-up'.
20169 See `org-ctrl-c-ctrl-c-hook' for more information.")
20170 (defvar org-shiftmetadown-hook nil
20171 "Hook for functions attaching themselves to `M-S-down'.
20172 See `org-ctrl-c-ctrl-c-hook' for more information.")
20173 (defvar org-metareturn-hook nil
20174 "Hook for functions attaching themselves to `M-RET'.
20175 See `org-ctrl-c-ctrl-c-hook' for more information.")
20176 (defvar org-shiftup-hook nil
20177 "Hook for functions attaching themselves to `S-up'.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defvar org-shiftup-final-hook nil
20180 "Hook for functions attaching themselves to `S-up'.
20181 This one runs after all other options except shift-select have been excluded.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-shiftdown-hook nil
20184 "Hook for functions attaching themselves to `S-down'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftdown-final-hook nil
20187 "Hook for functions attaching themselves to `S-down'.
20188 This one runs after all other options except shift-select have been excluded.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftleft-hook nil
20191 "Hook for functions attaching themselves to `S-left'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftleft-final-hook nil
20194 "Hook for functions attaching themselves to `S-left'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-shiftright-hook nil
20198 "Hook for functions attaching themselves to `S-right'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftright-final-hook nil
20201 "Hook for functions attaching themselves to `S-right'.
20202 This one runs after all other options except shift-select have been excluded.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20205 (defun org-modifier-cursor-error ()
20206 "Throw an error, a modified cursor command was applied in wrong context."
20207 (user-error "This command is active in special context like tables, headlines or items"))
20209 (defun org-shiftselect-error ()
20210 "Throw an error because Shift-Cursor command was applied in wrong context."
20211 (if (and (boundp 'shift-select-mode) shift-select-mode)
20212 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20213 (user-error "This command works only in special context like headlines or timestamps")))
20215 (defun org-call-for-shift-select (cmd)
20216 (let ((this-command-keys-shift-translated t))
20217 (call-interactively cmd)))
20219 (defun org-shifttab (&optional arg)
20220 "Global visibility cycling or move to previous table field.
20221 Call `org-table-previous-field' within a table.
20222 When ARG is nil, cycle globally through visibility states.
20223 When ARG is a numeric prefix, show contents of this level."
20224 (interactive "P")
20225 (cond
20226 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20227 ((integerp arg)
20228 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20229 (message "Content view to level: %d" arg)
20230 (org-content (prefix-numeric-value arg2))
20231 (org-cycle-show-empty-lines t)
20232 (setq org-cycle-global-status 'overview)))
20233 (t (call-interactively 'org-global-cycle))))
20235 (defun org-shiftmetaleft ()
20236 "Promote subtree or delete table column.
20237 Calls `org-promote-subtree', `org-outdent-item-tree', or
20238 `org-table-delete-column', depending on context. See the
20239 individual commands for more information."
20240 (interactive)
20241 (cond
20242 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20243 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20244 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20245 ((if (not (org-region-active-p)) (org-at-item-p)
20246 (save-excursion (goto-char (region-beginning))
20247 (org-at-item-p)))
20248 (call-interactively 'org-outdent-item-tree))
20249 (t (org-modifier-cursor-error))))
20251 (defun org-shiftmetaright ()
20252 "Demote subtree or insert table column.
20253 Calls `org-demote-subtree', `org-indent-item-tree', or
20254 `org-table-insert-column', depending on context. See the
20255 individual commands for more information."
20256 (interactive)
20257 (cond
20258 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20259 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20260 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20261 ((if (not (org-region-active-p)) (org-at-item-p)
20262 (save-excursion (goto-char (region-beginning))
20263 (org-at-item-p)))
20264 (call-interactively 'org-indent-item-tree))
20265 (t (org-modifier-cursor-error))))
20267 (defun org-shiftmetaup (&optional _arg)
20268 "Drag the line at point up.
20269 In a table, kill the current row.
20270 On a clock timestamp, update the value of the timestamp like `S-<up>'
20271 but also adjust the previous clocked item in the clock history.
20272 Everywhere else, drag the line at point up."
20273 (interactive "P")
20274 (cond
20275 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20276 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20277 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20278 (call-interactively 'org-timestamp-up)))
20279 (t (call-interactively 'org-drag-line-backward))))
20281 (defun org-shiftmetadown (&optional _arg)
20282 "Drag the line at point down.
20283 In a table, insert an empty row at the current line.
20284 On a clock timestamp, update the value of the timestamp like `S-<down>'
20285 but also adjust the previous clocked item in the clock history.
20286 Everywhere else, drag the line at point down."
20287 (interactive "P")
20288 (cond
20289 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20290 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20291 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20292 (call-interactively 'org-timestamp-down)))
20293 (t (call-interactively 'org-drag-line-forward))))
20295 (defsubst org-hidden-tree-error ()
20296 (user-error
20297 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20299 (defun org-metaleft (&optional _arg)
20300 "Promote heading, list item at point or move table column left.
20302 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20303 depending on context. With no specific context, calls the Emacs
20304 default `backward-word'. See the individual commands for more
20305 information.
20307 This function runs the hook `org-metaleft-hook' as a first step,
20308 and returns at first non-nil value."
20309 (interactive "P")
20310 (cond
20311 ((run-hook-with-args-until-success 'org-metaleft-hook))
20312 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20313 ((org-with-limited-levels
20314 (or (org-at-heading-p)
20315 (and (org-region-active-p)
20316 (save-excursion
20317 (goto-char (region-beginning))
20318 (org-at-heading-p)))))
20319 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20320 (call-interactively 'org-do-promote))
20321 ;; At an inline task.
20322 ((org-at-heading-p)
20323 (call-interactively 'org-inlinetask-promote))
20324 ((or (org-at-item-p)
20325 (and (org-region-active-p)
20326 (save-excursion
20327 (goto-char (region-beginning))
20328 (org-at-item-p))))
20329 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20330 (call-interactively 'org-outdent-item))
20331 (t (call-interactively 'backward-word))))
20333 (defun org-metaright (&optional _arg)
20334 "Demote heading, list item at point or move table column right.
20336 In front of a drawer or a block keyword, indent it correctly.
20338 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20339 `org-indent-drawer' or `org-indent-block' depending on context.
20340 With no specific context, calls the Emacs default `forward-word'.
20341 See the individual commands for more information.
20343 This function runs the hook `org-metaright-hook' as a first step,
20344 and returns at first non-nil value."
20345 (interactive "P")
20346 (cond
20347 ((run-hook-with-args-until-success 'org-metaright-hook))
20348 ((org-at-table-p) (call-interactively 'org-table-move-column))
20349 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20350 ((org-at-block-p) (call-interactively 'org-indent-block))
20351 ((org-with-limited-levels
20352 (or (org-at-heading-p)
20353 (and (org-region-active-p)
20354 (save-excursion
20355 (goto-char (region-beginning))
20356 (org-at-heading-p)))))
20357 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20358 (call-interactively 'org-do-demote))
20359 ;; At an inline task.
20360 ((org-at-heading-p)
20361 (call-interactively 'org-inlinetask-demote))
20362 ((or (org-at-item-p)
20363 (and (org-region-active-p)
20364 (save-excursion
20365 (goto-char (region-beginning))
20366 (org-at-item-p))))
20367 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20368 (call-interactively 'org-indent-item))
20369 (t (call-interactively 'forward-word))))
20371 (defun org-check-for-hidden (what)
20372 "Check if there are hidden headlines/items in the current visual line.
20373 WHAT can be either `headlines' or `items'. If the current line is
20374 an outline or item heading and it has a folded subtree below it,
20375 this function returns t, nil otherwise."
20376 (let ((re (cond
20377 ((eq what 'headlines) org-outline-regexp-bol)
20378 ((eq what 'items) (org-item-beginning-re))
20379 (t (error "This should not happen"))))
20380 beg end)
20381 (save-excursion
20382 (catch 'exit
20383 (unless (org-region-active-p)
20384 (setq beg (point-at-bol))
20385 (beginning-of-line 2)
20386 (while (and (not (eobp)) ;; this is like `next-line'
20387 (get-char-property (1- (point)) 'invisible))
20388 (beginning-of-line 2))
20389 (setq end (point))
20390 (goto-char beg)
20391 (goto-char (point-at-eol))
20392 (setq end (max end (point)))
20393 (while (re-search-forward re end t)
20394 (when (get-char-property (match-beginning 0) 'invisible)
20395 (throw 'exit t))))
20396 nil))))
20398 (defun org-metaup (&optional _arg)
20399 "Move subtree up or move table row up.
20400 Calls `org-move-subtree-up' or `org-table-move-row' or
20401 `org-move-item-up', depending on context. See the individual commands
20402 for more information."
20403 (interactive "P")
20404 (cond
20405 ((run-hook-with-args-until-success 'org-metaup-hook))
20406 ((org-region-active-p)
20407 (let* ((a (min (region-beginning) (region-end)))
20408 (b (1- (max (region-beginning) (region-end))))
20409 (c (save-excursion (goto-char a)
20410 (move-beginning-of-line 0)))
20411 (d (save-excursion (goto-char a)
20412 (move-end-of-line 0) (point))))
20413 (transpose-regions a b c d)
20414 (goto-char c)))
20415 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20416 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20417 ((org-at-item-p) (call-interactively 'org-move-item-up))
20418 (t (org-drag-element-backward))))
20420 (defun org-metadown (&optional _arg)
20421 "Move subtree down or move table row down.
20422 Calls `org-move-subtree-down' or `org-table-move-row' or
20423 `org-move-item-down', depending on context. See the individual
20424 commands for more information."
20425 (interactive "P")
20426 (cond
20427 ((run-hook-with-args-until-success 'org-metadown-hook))
20428 ((org-region-active-p)
20429 (let* ((a (min (region-beginning) (region-end)))
20430 (b (max (region-beginning) (region-end)))
20431 (c (save-excursion (goto-char b)
20432 (move-beginning-of-line 1)))
20433 (d (save-excursion (goto-char b)
20434 (move-end-of-line 1) (1+ (point)))))
20435 (transpose-regions a b c d)
20436 (goto-char d)))
20437 ((org-at-table-p) (call-interactively 'org-table-move-row))
20438 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20439 ((org-at-item-p) (call-interactively 'org-move-item-down))
20440 (t (org-drag-element-forward))))
20442 (defun org-shiftup (&optional arg)
20443 "Increase item in timestamp or increase priority of current headline.
20444 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20445 depending on context. See the individual commands for more information."
20446 (interactive "P")
20447 (cond
20448 ((run-hook-with-args-until-success 'org-shiftup-hook))
20449 ((and org-support-shift-select (org-region-active-p))
20450 (org-call-for-shift-select 'previous-line))
20451 ((org-at-timestamp-p 'lax)
20452 (call-interactively (if org-edit-timestamp-down-means-later
20453 'org-timestamp-down 'org-timestamp-up)))
20454 ((and (not (eq org-support-shift-select 'always))
20455 org-enable-priority-commands
20456 (org-at-heading-p))
20457 (call-interactively 'org-priority-up))
20458 ((and (not org-support-shift-select) (org-at-item-p))
20459 (call-interactively 'org-previous-item))
20460 ((org-clocktable-try-shift 'up arg))
20461 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20462 (org-support-shift-select
20463 (org-call-for-shift-select 'previous-line))
20464 (t (org-shiftselect-error))))
20466 (defun org-shiftdown (&optional arg)
20467 "Decrease item in timestamp or decrease priority of current headline.
20468 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20469 depending on context. See the individual commands for more information."
20470 (interactive "P")
20471 (cond
20472 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20473 ((and org-support-shift-select (org-region-active-p))
20474 (org-call-for-shift-select 'next-line))
20475 ((org-at-timestamp-p 'lax)
20476 (call-interactively (if org-edit-timestamp-down-means-later
20477 'org-timestamp-up 'org-timestamp-down)))
20478 ((and (not (eq org-support-shift-select 'always))
20479 org-enable-priority-commands
20480 (org-at-heading-p))
20481 (call-interactively 'org-priority-down))
20482 ((and (not org-support-shift-select) (org-at-item-p))
20483 (call-interactively 'org-next-item))
20484 ((org-clocktable-try-shift 'down arg))
20485 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20486 (org-support-shift-select
20487 (org-call-for-shift-select 'next-line))
20488 (t (org-shiftselect-error))))
20490 (defun org-shiftright (&optional arg)
20491 "Cycle the thing at point or in the current line, depending on context.
20492 Depending on context, this does one of the following:
20494 - switch a timestamp at point one day into the future
20495 - on a headline, switch to the next TODO keyword.
20496 - on an item, switch entire list to the next bullet type
20497 - on a property line, switch to the next allowed value
20498 - on a clocktable definition line, move time block into the future"
20499 (interactive "P")
20500 (cond
20501 ((run-hook-with-args-until-success 'org-shiftright-hook))
20502 ((and org-support-shift-select (org-region-active-p))
20503 (org-call-for-shift-select 'forward-char))
20504 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20505 ((and (not (eq org-support-shift-select 'always))
20506 (org-at-heading-p))
20507 (let ((org-inhibit-logging
20508 (not org-treat-S-cursor-todo-selection-as-state-change))
20509 (org-inhibit-blocking
20510 (not org-treat-S-cursor-todo-selection-as-state-change)))
20511 (org-call-with-arg 'org-todo 'right)))
20512 ((or (and org-support-shift-select
20513 (not (eq org-support-shift-select 'always))
20514 (org-at-item-bullet-p))
20515 (and (not org-support-shift-select) (org-at-item-p)))
20516 (org-call-with-arg 'org-cycle-list-bullet nil))
20517 ((and (not (eq org-support-shift-select 'always))
20518 (org-at-property-p))
20519 (call-interactively 'org-property-next-allowed-value))
20520 ((org-clocktable-try-shift 'right arg))
20521 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20522 (org-support-shift-select
20523 (org-call-for-shift-select 'forward-char))
20524 (t (org-shiftselect-error))))
20526 (defun org-shiftleft (&optional arg)
20527 "Cycle the thing at point or in the current line, depending on context.
20528 Depending on context, this does one of the following:
20530 - switch a timestamp at point one day into the past
20531 - on a headline, switch to the previous TODO keyword.
20532 - on an item, switch entire list to the previous bullet type
20533 - on a property line, switch to the previous allowed value
20534 - on a clocktable definition line, move time block into the past"
20535 (interactive "P")
20536 (cond
20537 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20538 ((and org-support-shift-select (org-region-active-p))
20539 (org-call-for-shift-select 'backward-char))
20540 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20541 ((and (not (eq org-support-shift-select 'always))
20542 (org-at-heading-p))
20543 (let ((org-inhibit-logging
20544 (not org-treat-S-cursor-todo-selection-as-state-change))
20545 (org-inhibit-blocking
20546 (not org-treat-S-cursor-todo-selection-as-state-change)))
20547 (org-call-with-arg 'org-todo 'left)))
20548 ((or (and org-support-shift-select
20549 (not (eq org-support-shift-select 'always))
20550 (org-at-item-bullet-p))
20551 (and (not org-support-shift-select) (org-at-item-p)))
20552 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20553 ((and (not (eq org-support-shift-select 'always))
20554 (org-at-property-p))
20555 (call-interactively 'org-property-previous-allowed-value))
20556 ((org-clocktable-try-shift 'left arg))
20557 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20558 (org-support-shift-select
20559 (org-call-for-shift-select 'backward-char))
20560 (t (org-shiftselect-error))))
20562 (defun org-shiftcontrolright ()
20563 "Switch to next TODO set."
20564 (interactive)
20565 (cond
20566 ((and org-support-shift-select (org-region-active-p))
20567 (org-call-for-shift-select 'forward-word))
20568 ((and (not (eq org-support-shift-select 'always))
20569 (org-at-heading-p))
20570 (org-call-with-arg 'org-todo 'nextset))
20571 (org-support-shift-select
20572 (org-call-for-shift-select 'forward-word))
20573 (t (org-shiftselect-error))))
20575 (defun org-shiftcontrolleft ()
20576 "Switch to previous TODO set."
20577 (interactive)
20578 (cond
20579 ((and org-support-shift-select (org-region-active-p))
20580 (org-call-for-shift-select 'backward-word))
20581 ((and (not (eq org-support-shift-select 'always))
20582 (org-at-heading-p))
20583 (org-call-with-arg 'org-todo 'previousset))
20584 (org-support-shift-select
20585 (org-call-for-shift-select 'backward-word))
20586 (t (org-shiftselect-error))))
20588 (defun org-shiftcontrolup (&optional n)
20589 "Change timestamps synchronously up in CLOCK log lines.
20590 Optional argument N tells to change by that many units."
20591 (interactive "P")
20592 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20593 (let (org-support-shift-select)
20594 (org-clock-timestamps-up n))
20595 (user-error "Not at a clock log")))
20597 (defun org-shiftcontroldown (&optional n)
20598 "Change timestamps synchronously down in CLOCK log lines.
20599 Optional argument N tells to change by that many units."
20600 (interactive "P")
20601 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20602 (let (org-support-shift-select)
20603 (org-clock-timestamps-down n))
20604 (user-error "Not at a clock log")))
20606 (defun org-increase-number-at-point (&optional inc)
20607 "Increment the number at point.
20608 With an optional prefix numeric argument INC, increment using
20609 this numeric value."
20610 (interactive "p")
20611 (if (not (number-at-point))
20612 (user-error "Not on a number")
20613 (unless inc (setq inc 1))
20614 (let ((pos (point))
20615 (beg (skip-chars-backward "-+^/*0-9eE."))
20616 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20617 (setq nap (buffer-substring-no-properties
20618 (+ pos beg) (+ pos beg end)))
20619 (delete-region (+ pos beg) (+ pos beg end))
20620 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20621 (when (org-at-table-p)
20622 (org-table-align)
20623 (org-table-end-of-field 1))))
20625 (defun org-decrease-number-at-point (&optional inc)
20626 "Decrement the number at point.
20627 With an optional prefix numeric argument INC, decrement using
20628 this numeric value."
20629 (interactive "p")
20630 (org-increase-number-at-point (- (or inc 1))))
20632 (defun org-ctrl-c-ret ()
20633 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20634 (interactive)
20635 (cond
20636 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20637 (t (call-interactively 'org-insert-heading))))
20639 (defun org-find-visible ()
20640 (let ((s (point)))
20641 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20642 (get-char-property s 'invisible)))
20644 (defun org-find-invisible ()
20645 (let ((s (point)))
20646 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20647 (not (get-char-property s 'invisible))))
20650 (defun org-copy-visible (beg end)
20651 "Copy the visible parts of the region."
20652 (interactive "r")
20653 (let ((result ""))
20654 (while (/= beg end)
20655 (when (get-char-property beg 'invisible)
20656 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20657 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20658 (setq result (concat result (buffer-substring beg next)))
20659 (setq beg next)))
20660 (kill-new result)))
20662 (defun org-copy-special ()
20663 "Copy region in table or copy current subtree.
20664 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20665 context. See the individual commands for more information."
20666 (interactive)
20667 (call-interactively
20668 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20670 (defun org-cut-special ()
20671 "Cut region in table or cut current subtree.
20672 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20673 context. See the individual commands for more information."
20674 (interactive)
20675 (call-interactively
20676 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20678 (defun org-paste-special (arg)
20679 "Paste rectangular region into table, or past subtree relative to level.
20680 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20681 See the individual commands for more information."
20682 (interactive "P")
20683 (if (org-at-table-p)
20684 (org-table-paste-rectangle)
20685 (org-paste-subtree arg)))
20687 (defun org-edit-special (&optional arg)
20688 "Call a special editor for the element at point.
20689 When at a table, call the formula editor with `org-table-edit-formulas'.
20690 When in a source code block, call `org-edit-src-code'.
20691 When in a fixed-width region, call `org-edit-fixed-width-region'.
20692 When in an export block, call `org-edit-export-block'.
20693 When in a LaTeX environment, call `org-edit-latex-environment'.
20694 When at an #+INCLUDE keyword, visit the included file.
20695 When at a footnote reference, call `org-edit-footnote-reference'
20696 On a link, call `ffap' to visit the link at point.
20697 Otherwise, return a user error."
20698 (interactive "P")
20699 (let ((element (org-element-at-point)))
20700 (barf-if-buffer-read-only)
20701 (pcase (org-element-type element)
20702 (`src-block
20703 (if (not arg) (org-edit-src-code)
20704 (let* ((info (org-babel-get-src-block-info))
20705 (lang (nth 0 info))
20706 (params (nth 2 info))
20707 (session (cdr (assq :session params))))
20708 (if (not session) (org-edit-src-code)
20709 ;; At a src-block with a session and function called with
20710 ;; an ARG: switch to the buffer related to the inferior
20711 ;; process.
20712 (switch-to-buffer
20713 (funcall (intern (concat "org-babel-prep-session:" lang))
20714 session params))))))
20715 (`keyword
20716 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20717 (org-open-link-from-string
20718 (format "[[%s]]"
20719 (expand-file-name
20720 (let ((value (org-element-property :value element)))
20721 (cond ((org-file-url-p value)
20722 (user-error "The file is specified as a URL, cannot be edited"))
20723 ((not (org-string-nw-p value))
20724 (user-error "No file to edit"))
20725 ((string-match "\\`\"\\(.*?\\)\"" value)
20726 (match-string 1 value))
20727 ((string-match "\\`[^ \t\"]\\S-*" value)
20728 (match-string 0 value))
20729 (t (user-error "No valid file specified")))))))
20730 (user-error "No special environment to edit here")))
20731 (`table
20732 (if (eq (org-element-property :type element) 'table.el)
20733 (org-edit-table.el)
20734 (call-interactively 'org-table-edit-formulas)))
20735 ;; Only Org tables contain `table-row' type elements.
20736 (`table-row (call-interactively 'org-table-edit-formulas))
20737 (`example-block (org-edit-src-code))
20738 (`export-block (org-edit-export-block))
20739 (`fixed-width (org-edit-fixed-width-region))
20740 (`latex-environment (org-edit-latex-environment))
20742 ;; No notable element at point. Though, we may be at a link or
20743 ;; a footnote reference, which are objects. Thus, scan deeper.
20744 (let ((context (org-element-context element)))
20745 (pcase (org-element-type context)
20746 (`footnote-reference (org-edit-footnote-reference))
20747 (`inline-src-block (org-edit-inline-src-code))
20748 (`link (call-interactively #'ffap))
20749 (_ (user-error "No special environment to edit here"))))))))
20751 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20752 (defun org-ctrl-c-ctrl-c (&optional arg)
20753 "Set tags in headline, or update according to changed information at point.
20755 This command does many different things, depending on context:
20757 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20758 this is what we do.
20760 - If the cursor is on a statistics cookie, update it.
20762 - If the cursor is in a headline, prompt for tags and insert them
20763 into the current line, aligned to `org-tags-column'. When called
20764 with prefix arg, realign all tags in the current buffer.
20766 - If the cursor is in one of the special #+KEYWORD lines, this
20767 triggers scanning the buffer for these lines and updating the
20768 information.
20770 - If the cursor is inside a table, realign the table. This command
20771 works even if the automatic table editor has been turned off.
20773 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20774 the entire table.
20776 - If the cursor is at a footnote reference or definition, jump to
20777 the corresponding definition or references, respectively.
20779 - If the cursor is a the beginning of a dynamic block, update it.
20781 - If the current buffer is a capture buffer, close note and file it.
20783 - If the cursor is on a <<<target>>>, update radio targets and
20784 corresponding links in this buffer.
20786 - If the cursor is on a numbered item in a plain list, renumber the
20787 ordered list.
20789 - If the cursor is on a checkbox, toggle it.
20791 - If the cursor is on a code block, evaluate it. The variable
20792 `org-confirm-babel-evaluate' can be used to control prompting
20793 before code block evaluation, by default every code block
20794 evaluation requires confirmation. Code block evaluation can be
20795 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20796 (interactive "P")
20797 (cond
20798 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20799 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20800 (org-remove-occur-highlights)
20801 (message "Temporary highlights/overlays removed from current buffer"))
20802 ((and (local-variable-p 'org-finish-function)
20803 (fboundp org-finish-function))
20804 (funcall org-finish-function))
20805 ((org-babel-hash-at-point))
20806 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20808 (let* ((context
20809 (org-element-lineage
20810 (org-element-context)
20811 ;; Limit to supported contexts.
20812 '(babel-call clock dynamic-block footnote-definition
20813 footnote-reference inline-babel-call inline-src-block
20814 inlinetask item keyword node-property paragraph
20815 plain-list planning property-drawer radio-target
20816 src-block statistics-cookie table table-cell table-row
20817 timestamp)
20819 (type (org-element-type context)))
20820 ;; For convenience: at the first line of a paragraph on the same
20821 ;; line as an item, apply function on that item instead.
20822 (when (eq type 'paragraph)
20823 (let ((parent (org-element-property :parent context)))
20824 (when (and (eq (org-element-type parent) 'item)
20825 (= (line-beginning-position)
20826 (org-element-property :begin parent)))
20827 (setq context parent)
20828 (setq type 'item))))
20829 ;; Act according to type of element or object at point.
20831 ;; Do nothing on a blank line, except if it is contained in
20832 ;; a src block. Hence, we first check if point is in such
20833 ;; a block and then if it is at a blank line.
20834 (pcase type
20835 ((or `inline-src-block `src-block)
20836 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20837 (org-babel-eval-wipe-error-buffer)
20838 (org-babel-execute-src-block
20839 current-prefix-arg (org-babel-get-src-block-info nil context))))
20840 ((guard (org-match-line "[ \t]*$"))
20841 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20842 (user-error
20843 (substitute-command-keys
20844 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20845 ((or `babel-call `inline-babel-call)
20846 (let ((info (org-babel-lob-get-info context)))
20847 (when info (org-babel-execute-src-block nil info))))
20848 (`clock (org-clock-update-time-maybe))
20849 (`dynamic-block
20850 (save-excursion
20851 (goto-char (org-element-property :post-affiliated context))
20852 (org-update-dblock)))
20853 (`footnote-definition
20854 (goto-char (org-element-property :post-affiliated context))
20855 (call-interactively 'org-footnote-action))
20856 (`footnote-reference (call-interactively #'org-footnote-action))
20857 ((or `headline `inlinetask)
20858 (save-excursion (goto-char (org-element-property :begin context))
20859 (call-interactively #'org-set-tags)))
20860 (`item
20861 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20862 ;; unconditionally, whereas `C-u' will toggle its presence.
20863 ;; Without a universal argument, if the item has a checkbox,
20864 ;; toggle it. Otherwise repair the list.
20865 (let* ((box (org-element-property :checkbox context))
20866 (struct (org-element-property :structure context))
20867 (old-struct (copy-tree struct))
20868 (parents (org-list-parents-alist struct))
20869 (prevs (org-list-prevs-alist struct))
20870 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20871 (org-list-set-checkbox
20872 (org-element-property :begin context) struct
20873 (cond ((equal arg '(16)) "[-]")
20874 ((and (not box) (equal arg '(4))) "[ ]")
20875 ((or (not box) (equal arg '(4))) nil)
20876 ((eq box 'on) "[ ]")
20877 (t "[X]")))
20878 ;; Mimic `org-list-write-struct' but with grabbing a return
20879 ;; value from `org-list-struct-fix-box'.
20880 (org-list-struct-fix-ind struct parents 2)
20881 (org-list-struct-fix-item-end struct)
20882 (org-list-struct-fix-bul struct prevs)
20883 (org-list-struct-fix-ind struct parents)
20884 (let ((block-item
20885 (org-list-struct-fix-box struct parents prevs orderedp)))
20886 (if (and box (equal struct old-struct))
20887 (if (equal arg '(16))
20888 (message "Checkboxes already reset")
20889 (user-error "Cannot toggle this checkbox: %s"
20890 (if (eq box 'on)
20891 "all subitems checked"
20892 "unchecked subitems")))
20893 (org-list-struct-apply-struct struct old-struct)
20894 (org-update-checkbox-count-maybe))
20895 (when block-item
20896 (message "Checkboxes were removed due to empty box at line %d"
20897 (org-current-line block-item))))))
20898 (`keyword
20899 (let ((org-inhibit-startup-visibility-stuff t)
20900 (org-startup-align-all-tables nil))
20901 (when (boundp 'org-table-coordinate-overlays)
20902 (mapc #'delete-overlay org-table-coordinate-overlays)
20903 (setq org-table-coordinate-overlays nil))
20904 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20905 (message "Local setup has been refreshed"))
20906 (`plain-list
20907 ;; At a plain list, with a double C-u argument, set
20908 ;; checkboxes of each item to "[-]", whereas a single one
20909 ;; will toggle their presence according to the state of the
20910 ;; first item in the list. Without an argument, repair the
20911 ;; list.
20912 (let* ((begin (org-element-property :contents-begin context))
20913 (beginm (move-marker (make-marker) begin))
20914 (struct (org-element-property :structure context))
20915 (old-struct (copy-tree struct))
20916 (first-box (save-excursion
20917 (goto-char begin)
20918 (looking-at org-list-full-item-re)
20919 (match-string-no-properties 3)))
20920 (new-box (cond ((equal arg '(16)) "[-]")
20921 ((equal arg '(4)) (unless first-box "[ ]"))
20922 ((equal first-box "[X]") "[ ]")
20923 (t "[X]"))))
20924 (cond
20925 (arg
20926 (dolist (pos
20927 (org-list-get-all-items
20928 begin struct (org-list-prevs-alist struct)))
20929 (org-list-set-checkbox pos struct new-box)))
20930 ((and first-box (eq (point) begin))
20931 ;; For convenience, when point is at bol on the first
20932 ;; item of the list and no argument is provided, simply
20933 ;; toggle checkbox of that item, if any.
20934 (org-list-set-checkbox begin struct new-box)))
20935 (org-list-write-struct
20936 struct (org-list-parents-alist struct) old-struct)
20937 (org-update-checkbox-count-maybe)
20938 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20939 ((or `property-drawer `node-property)
20940 (call-interactively #'org-property-action))
20941 (`radio-target
20942 (call-interactively #'org-update-radio-target-regexp))
20943 (`statistics-cookie
20944 (call-interactively #'org-update-statistics-cookies))
20945 ((or `table `table-cell `table-row)
20946 ;; At a table, recalculate every field and align it. Also
20947 ;; send the table if necessary. If the table has
20948 ;; a `table.el' type, just give up. At a table row or cell,
20949 ;; maybe recalculate line but always align table.
20950 (if (eq (org-element-property :type context) 'table.el)
20951 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20952 Use `\\[org-edit-special]' to edit table.el tables"))
20953 (if (or (eq type 'table)
20954 ;; Check if point is at a TBLFM line.
20955 (and (eq type 'table-row)
20956 (= (point) (org-element-property :end context))))
20957 (save-excursion
20958 (if (org-at-TBLFM-p)
20959 (progn (require 'org-table)
20960 (org-table-calc-current-TBLFM))
20961 (goto-char (org-element-property :contents-begin context))
20962 (org-call-with-arg 'org-table-recalculate (or arg t))
20963 (orgtbl-send-table 'maybe)))
20964 (org-table-maybe-eval-formula)
20965 (cond (arg (call-interactively #'org-table-recalculate))
20966 ((org-table-maybe-recalculate-line))
20967 (t (org-table-align))))))
20968 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20969 (org-timestamp-change 0 'day))
20970 ((and `nil (guard (org-at-heading-p)))
20971 ;; When point is on an unsupported object type, we can miss
20972 ;; the fact that it also is at a heading. Handle it here.
20973 (call-interactively #'org-set-tags))
20974 ((guard
20975 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20977 (user-error
20978 (substitute-command-keys
20979 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20981 (defun org-mode-restart ()
20982 (interactive)
20983 (let ((indent-status (bound-and-true-p org-indent-mode)))
20984 (funcall major-mode)
20985 (hack-local-variables)
20986 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20987 (org-indent-mode -1))
20988 (org-reset-file-cache))
20989 (message "%s restarted" major-mode))
20991 (defun org-kill-note-or-show-branches ()
20992 "Abort storing current note, or call `outline-show-branches'."
20993 (interactive)
20994 (if (not org-finish-function)
20995 (save-excursion
20996 (save-restriction
20997 (org-narrow-to-subtree)
20998 (org-flag-subtree t)
20999 (call-interactively 'outline-show-branches)
21000 (org-hide-archived-subtrees (point-min) (point-max))))
21001 (let ((org-note-abort t))
21002 (funcall org-finish-function))))
21004 (defun org-delete-indentation (&optional arg)
21005 "Join current line to previous and fix whitespace at join.
21007 If previous line is a headline add to headline title. Otherwise
21008 the function calls `delete-indentation'.
21010 With a non-nil optional argument, join it to the following one."
21011 (interactive "*P")
21012 (if (save-excursion
21013 (beginning-of-line (if arg 1 0))
21014 (let ((case-fold-search nil))
21015 (looking-at org-complex-heading-regexp)))
21016 ;; At headline.
21017 (let ((tags-column (when (match-beginning 5)
21018 (save-excursion (goto-char (match-beginning 5))
21019 (current-column))))
21020 (string (concat " " (progn (when arg (forward-line 1))
21021 (org-trim (delete-and-extract-region
21022 (line-beginning-position)
21023 (line-end-position)))))))
21024 (unless (bobp) (delete-region (point) (1- (point))))
21025 (goto-char (or (match-end 4)
21026 (match-beginning 5)
21027 (match-end 0)))
21028 (skip-chars-backward " \t")
21029 (save-excursion (insert string))
21030 ;; Adjust alignment of tags.
21031 (cond
21032 ((not tags-column)) ;no tags
21033 (org-auto-align-tags (org-set-tags nil t))
21034 (t (org--align-tags-here tags-column)))) ;preserve tags column
21035 (delete-indentation arg)))
21037 (defun org-open-line (n)
21038 "Insert a new row in tables, call `open-line' elsewhere.
21039 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21040 As a special case, when a document starts with a table, allow to
21041 call `open-line' on the very first character."
21042 (interactive "*p")
21043 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21044 (org-table-insert-row)
21045 (open-line n)))
21047 (defun org-return (&optional indent)
21048 "Goto next table row or insert a newline.
21050 Calls `org-table-next-row' or `newline', depending on context.
21052 When optional INDENT argument is non-nil, call
21053 `newline-and-indent' instead of `newline'.
21055 When `org-return-follows-link' is non-nil and point is on
21056 a timestamp or a link, call `org-open-at-point'. However, it
21057 will not happen if point is in a table or on a \"dead\"
21058 object (e.g., within a comment). In these case, you need to use
21059 `org-open-at-point' directly."
21060 (interactive)
21061 (let ((context (if org-return-follows-link (org-element-context)
21062 (org-element-at-point))))
21063 (cond
21064 ;; In a table, call `org-table-next-row'. However, before first
21065 ;; column or after last one, split the table.
21066 ((or (and (eq (org-element-type context) 'table)
21067 (>= (point) (org-element-property :contents-begin context))
21068 (< (point) (org-element-property :contents-end context)))
21069 (org-element-lineage context '(table-row table-cell) t))
21070 (if (or (looking-at-p "[ \t]*$")
21071 (save-excursion (skip-chars-backward " \t") (bolp)))
21072 (insert "\n")
21073 (org-table-justify-field-maybe)
21074 (call-interactively #'org-table-next-row)))
21075 ;; On a link or a timestamp, call `org-open-at-point' if
21076 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21077 ;; locations, e.g., in a comment, as `org-open-at-point'.
21078 ((and org-return-follows-link
21079 (or (org-in-regexp org-ts-regexp-both nil t)
21080 (org-in-regexp org-tsr-regexp-both nil t)
21081 (org-in-regexp org-any-link-re nil t)))
21082 (call-interactively #'org-open-at-point))
21083 ;; Insert newline in heading, but preserve tags.
21084 ((and (not (bolp))
21085 (save-excursion (beginning-of-line)
21086 (let ((case-fold-search nil))
21087 (looking-at org-complex-heading-regexp))))
21088 ;; At headline. Split line. However, if point is on keyword,
21089 ;; priority cookie or tags, do not break any of them: add
21090 ;; a newline after the headline instead.
21091 (let ((tags-column (and (match-beginning 5)
21092 (save-excursion (goto-char (match-beginning 5))
21093 (current-column))))
21094 (string
21095 (when (and (match-end 4) (org-point-in-group (point) 4))
21096 (delete-and-extract-region (point) (match-end 4)))))
21097 ;; Adjust tag alignment.
21098 (cond
21099 ((not (and tags-column string)))
21100 (org-auto-align-tags (org-set-tags nil t))
21101 (t (org--align-tags-here tags-column))) ;preserve tags column
21102 (end-of-line)
21103 (org-show-entry)
21104 (if indent (newline-and-indent) (newline))
21105 (when string (save-excursion (insert (org-trim string))))))
21106 ;; In a list, make sure indenting keeps trailing text within.
21107 ((and indent
21108 (not (eolp))
21109 (org-element-lineage context '(item)))
21110 (let ((trailing-data
21111 (delete-and-extract-region (point) (line-end-position))))
21112 (newline-and-indent)
21113 (save-excursion (insert trailing-data))))
21115 ;; Do not auto-fill when point is in an Org property drawer.
21116 (let ((auto-fill-function (and (not (org-at-property-p))
21117 auto-fill-function)))
21118 (if indent
21119 (newline-and-indent)
21120 (newline)))))))
21122 (defun org-return-indent ()
21123 "Goto next table row or insert a newline and indent.
21124 Calls `org-table-next-row' or `newline-and-indent', depending on
21125 context. See the individual commands for more information."
21126 (interactive)
21127 (org-return t))
21129 (defun org-ctrl-c-star ()
21130 "Compute table, or change heading status of lines.
21131 Calls `org-table-recalculate' or `org-toggle-heading',
21132 depending on context."
21133 (interactive)
21134 (cond
21135 ((org-at-table-p)
21136 (call-interactively 'org-table-recalculate))
21138 ;; Convert all lines in region to list items
21139 (call-interactively 'org-toggle-heading))))
21141 (defun org-ctrl-c-minus ()
21142 "Insert separator line in table or modify bullet status of line.
21143 Also turns a plain line or a region of lines into list items.
21144 Calls `org-table-insert-hline', `org-toggle-item', or
21145 `org-cycle-list-bullet', depending on context."
21146 (interactive)
21147 (cond
21148 ((org-at-table-p)
21149 (call-interactively 'org-table-insert-hline))
21150 ((org-region-active-p)
21151 (call-interactively 'org-toggle-item))
21152 ((org-in-item-p)
21153 (call-interactively 'org-cycle-list-bullet))
21155 (call-interactively 'org-toggle-item))))
21157 (defun org-toggle-heading (&optional nstars)
21158 "Convert headings to normal text, or items or text to headings.
21159 If there is no active region, only convert the current line.
21161 With a `\\[universal-argument]' prefix, convert the whole list at
21162 point into heading.
21164 In a region:
21166 - If the first non blank line is a headline, remove the stars
21167 from all headlines in the region.
21169 - If it is a normal line, turn each and every normal line (i.e.,
21170 not an heading or an item) in the region into headings. If you
21171 want to convert only the first line of this region, use one
21172 universal prefix argument.
21174 - If it is a plain list item, turn all plain list items into headings.
21176 When converting a line into a heading, the number of stars is chosen
21177 such that the lines become children of the current entry. However,
21178 when a numeric prefix argument is given, its value determines the
21179 number of stars to add."
21180 (interactive "P")
21181 (let ((skip-blanks
21182 (function
21183 ;; Return beginning of first non-blank line, starting from
21184 ;; line at POS.
21185 (lambda (pos)
21186 (save-excursion
21187 (goto-char pos)
21188 (while (org-at-comment-p) (forward-line))
21189 (skip-chars-forward " \r\t\n")
21190 (point-at-bol)))))
21191 beg end toggled)
21192 ;; Determine boundaries of changes. If a universal prefix has
21193 ;; been given, put the list in a region. If region ends at a bol,
21194 ;; do not consider the last line to be in the region.
21196 (when (and current-prefix-arg (org-at-item-p))
21197 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21198 (org-mark-element))
21200 (if (org-region-active-p)
21201 (setq beg (funcall skip-blanks (region-beginning))
21202 end (copy-marker (save-excursion
21203 (goto-char (region-end))
21204 (if (bolp) (point) (point-at-eol)))))
21205 (setq beg (funcall skip-blanks (point-at-bol))
21206 end (copy-marker (point-at-eol))))
21207 ;; Ensure inline tasks don't count as headings.
21208 (org-with-limited-levels
21209 (save-excursion
21210 (goto-char beg)
21211 (cond
21212 ;; Case 1. Started at an heading: de-star headings.
21213 ((org-at-heading-p)
21214 (while (< (point) end)
21215 (when (org-at-heading-p t)
21216 (looking-at org-outline-regexp) (replace-match "")
21217 (setq toggled t))
21218 (forward-line)))
21219 ;; Case 2. Started at an item: change items into headlines.
21220 ;; One star will be added by `org-list-to-subtree'.
21221 ((org-at-item-p)
21222 (while (< (point) end)
21223 (when (org-at-item-p)
21224 ;; Pay attention to cases when region ends before list.
21225 (let* ((struct (org-list-struct))
21226 (list-end
21227 (min (org-list-get-bottom-point struct) (1+ end))))
21228 (save-restriction
21229 (narrow-to-region (point) list-end)
21230 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21231 (setq toggled t))
21232 (forward-line)))
21233 ;; Case 3. Started at normal text: make every line an heading,
21234 ;; skipping headlines and items.
21235 (t (let* ((stars
21236 (make-string
21237 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21238 (add-stars
21239 (cond (nstars "") ; stars from prefix only
21240 ((equal stars "") "*") ; before first heading
21241 (org-odd-levels-only "**") ; inside heading, odd
21242 (t "*"))) ; inside heading, oddeven
21243 (rpl (concat stars add-stars " "))
21244 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21245 (while (< (point) (if (equal nstars '(4)) lend end))
21246 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21247 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21248 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21249 (forward-line)))))))
21250 (unless toggled (message "Cannot toggle heading from here"))))
21252 (defun org-meta-return (&optional arg)
21253 "Insert a new heading or wrap a region in a table.
21254 Calls `org-insert-heading', `org-insert-item' or
21255 `org-table-wrap-region', depending on context. When called with
21256 an argument, unconditionally call `org-insert-heading'."
21257 (interactive "P")
21258 (org-check-before-invisible-edit 'insert)
21259 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21260 (call-interactively (cond (arg #'org-insert-heading)
21261 ((org-at-table-p) #'org-table-wrap-region)
21262 ((org-in-item-p) #'org-insert-item)
21263 (t #'org-insert-heading)))))
21265 ;;; Menu entries
21267 (defsubst org-in-subtree-not-table-p ()
21268 "Are we in a subtree and not in a table?"
21269 (and (not (org-before-first-heading-p))
21270 (not (org-at-table-p))))
21272 ;; Define the Org mode menus
21273 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21274 '("Tbl"
21275 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21276 ["Next Field" org-cycle (org-at-table-p)]
21277 ["Previous Field" org-shifttab (org-at-table-p)]
21278 ["Next Row" org-return (org-at-table-p)]
21279 "--"
21280 ["Blank Field" org-table-blank-field (org-at-table-p)]
21281 ["Edit Field" org-table-edit-field (org-at-table-p)]
21282 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21283 "--"
21284 ("Column"
21285 ["Move Column Left" org-metaleft (org-at-table-p)]
21286 ["Move Column Right" org-metaright (org-at-table-p)]
21287 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21288 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21289 ("Row"
21290 ["Move Row Up" org-metaup (org-at-table-p)]
21291 ["Move Row Down" org-metadown (org-at-table-p)]
21292 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21293 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21294 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21295 "--"
21296 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21297 ("Rectangle"
21298 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21299 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21300 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21301 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21302 "--"
21303 ("Calculate"
21304 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21305 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21306 ["Edit Formulas" org-edit-special (org-at-table-p)]
21307 "--"
21308 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21309 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21310 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21311 "--"
21312 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21313 "--"
21314 ["Sum Column/Rectangle" org-table-sum
21315 (or (org-at-table-p) (org-region-active-p))]
21316 ["Which Column?" org-table-current-column (org-at-table-p)])
21317 ["Debug Formulas"
21318 org-table-toggle-formula-debugger
21319 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21320 ["Show Col/Row Numbers"
21321 org-table-toggle-coordinate-overlays
21322 :style toggle
21323 :selected (bound-and-true-p org-table-overlay-coordinates)]
21324 "--"
21325 ["Create" org-table-create (not (org-at-table-p))]
21326 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21327 ["Import from File" org-table-import (not (org-at-table-p))]
21328 ["Export to File" org-table-export (org-at-table-p)]
21329 "--"
21330 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21331 "--"
21332 ("Plot"
21333 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21334 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21336 (easy-menu-define org-org-menu org-mode-map "Org menu"
21337 '("Org"
21338 ("Show/Hide"
21339 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21340 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21341 ["Sparse Tree..." org-sparse-tree t]
21342 ["Reveal Context" org-reveal t]
21343 ["Show All" outline-show-all t]
21344 "--"
21345 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21346 "--"
21347 ["New Heading" org-insert-heading t]
21348 ("Navigate Headings"
21349 ["Up" outline-up-heading t]
21350 ["Next" outline-next-visible-heading t]
21351 ["Previous" outline-previous-visible-heading t]
21352 ["Next Same Level" outline-forward-same-level t]
21353 ["Previous Same Level" outline-backward-same-level t]
21354 "--"
21355 ["Jump" org-goto t])
21356 ("Edit Structure"
21357 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21358 "--"
21359 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21360 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21361 "--"
21362 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21363 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21364 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21365 "--"
21366 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21367 "--"
21368 ["Copy visible text" org-copy-visible t]
21369 "--"
21370 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21371 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21372 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21373 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21374 "--"
21375 ["Sort Region/Children" org-sort t]
21376 "--"
21377 ["Convert to odd levels" org-convert-to-odd-levels t]
21378 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21379 ("Editing"
21380 ["Emphasis..." org-emphasize t]
21381 ["Edit Source Example" org-edit-special t]
21382 "--"
21383 ["Footnote new/jump" org-footnote-action t]
21384 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21385 ("Archive"
21386 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21387 "--"
21388 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21389 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21390 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21392 "--"
21393 ("Hyperlinks"
21394 ["Store Link (Global)" org-store-link t]
21395 ["Find existing link to here" org-occur-link-in-agenda-files t]
21396 ["Insert Link" org-insert-link t]
21397 ["Follow Link" org-open-at-point t]
21398 "--"
21399 ["Next link" org-next-link t]
21400 ["Previous link" org-previous-link t]
21401 "--"
21402 ["Descriptive Links"
21403 org-toggle-link-display
21404 :style radio
21405 :selected org-descriptive-links
21407 ["Literal Links"
21408 org-toggle-link-display
21409 :style radio
21410 :selected (not org-descriptive-links)])
21411 "--"
21412 ("TODO Lists"
21413 ["TODO/DONE/-" org-todo t]
21414 ("Select keyword"
21415 ["Next keyword" org-shiftright (org-at-heading-p)]
21416 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21417 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21418 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21419 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21420 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21421 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21422 "--"
21423 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21424 :selected org-enforce-todo-dependencies :style toggle :active t]
21425 "Settings for tree at point"
21426 ["Do Children sequentially" org-toggle-ordered-property :style radio
21427 :selected (org-entry-get nil "ORDERED")
21428 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21429 ["Do Children parallel" org-toggle-ordered-property :style radio
21430 :selected (not (org-entry-get nil "ORDERED"))
21431 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21432 "--"
21433 ["Set Priority" org-priority t]
21434 ["Priority Up" org-shiftup t]
21435 ["Priority Down" org-shiftdown t]
21436 "--"
21437 ["Get news from all feeds" org-feed-update-all t]
21438 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21439 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21440 ("TAGS and Properties"
21441 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21442 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21443 "--"
21444 ["Set property" org-set-property (not (org-before-first-heading-p))]
21445 ["Column view of properties" org-columns t]
21446 ["Insert Column View DBlock" org-columns-insert-dblock t])
21447 ("Dates and Scheduling"
21448 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21449 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21450 ("Change Date"
21451 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21452 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21453 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21454 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21455 ["Compute Time Range" org-evaluate-time-range t]
21456 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21457 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21458 "--"
21459 ["Custom time format" org-toggle-time-stamp-overlays
21460 :style radio :selected org-display-custom-times]
21461 "--"
21462 ["Goto Calendar" org-goto-calendar t]
21463 ["Date from Calendar" org-date-from-calendar t]
21464 "--"
21465 ["Start/Restart Timer" org-timer-start t]
21466 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21467 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21468 ["Insert Timer String" org-timer t]
21469 ["Insert Timer Item" org-timer-item t])
21470 ("Logging work"
21471 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21472 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21473 ["Clock out" org-clock-out t]
21474 ["Clock cancel" org-clock-cancel t]
21475 "--"
21476 ["Mark as default task" org-clock-mark-default-task t]
21477 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21478 ["Goto running clock" org-clock-goto t]
21479 "--"
21480 ["Display times" org-clock-display t]
21481 ["Create clock table" org-clock-report t]
21482 "--"
21483 ["Record DONE time"
21484 (progn (setq org-log-done (not org-log-done))
21485 (message "Switching to %s will %s record a timestamp"
21486 (car org-done-keywords)
21487 (if org-log-done "automatically" "not")))
21488 :style toggle :selected org-log-done])
21489 "--"
21490 ["Agenda Command..." org-agenda t]
21491 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21492 ("File List for Agenda")
21493 ("Special views current file"
21494 ["TODO Tree" org-show-todo-tree t]
21495 ["Check Deadlines" org-check-deadlines t]
21496 ["Tags/Property tree" org-match-sparse-tree t])
21497 "--"
21498 ["Export/Publish..." org-export-dispatch t]
21499 ("LaTeX"
21500 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21501 :style toggle :selected org-cdlatex-mode]
21502 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21503 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21504 ["Modify math symbol" org-cdlatex-math-modify
21505 (org-inside-LaTeX-fragment-p)]
21506 ["Insert citation" org-reftex-citation t])
21507 "--"
21508 ("MobileOrg"
21509 ["Push Files and Views" org-mobile-push t]
21510 ["Get Captured and Flagged" org-mobile-pull t]
21511 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21512 "--"
21513 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21514 "--"
21515 ("Documentation"
21516 ["Show Version" org-version t]
21517 ["Info Documentation" org-info t])
21518 ("Customize"
21519 ["Browse Org Group" org-customize t]
21520 "--"
21521 ["Expand This Menu" org-create-customize-menu
21522 (fboundp 'customize-menu-create)])
21523 ["Send bug report" org-submit-bug-report t]
21524 "--"
21525 ("Refresh/Reload"
21526 ["Refresh setup current buffer" org-mode-restart t]
21527 ["Reload Org (after update)" org-reload t]
21528 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21531 (defun org-info (&optional node)
21532 "Read documentation for Org in the info system.
21533 With optional NODE, go directly to that node."
21534 (interactive)
21535 (info (format "(org)%s" (or node ""))))
21537 ;;;###autoload
21538 (defun org-submit-bug-report ()
21539 "Submit a bug report on Org via mail.
21541 Don't hesitate to report any problems or inaccurate documentation.
21543 If you don't have setup sending mail from (X)Emacs, please copy the
21544 output buffer into your mail program, as it gives us important
21545 information about your Org version and configuration."
21546 (interactive)
21547 (require 'reporter)
21548 (defvar reporter-prompt-for-summary-p)
21549 (org-load-modules-maybe)
21550 (org-require-autoloaded-modules)
21551 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21552 (reporter-submit-bug-report
21553 "emacs-orgmode@gnu.org"
21554 (org-version nil 'full)
21555 (let (list)
21556 (save-window-excursion
21557 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21558 (delete-other-windows)
21559 (erase-buffer)
21560 (insert "You are about to submit a bug report to the Org mailing list.
21562 We would like to add your full Org and Outline configuration to the
21563 bug report. This greatly simplifies the work of the maintainer and
21564 other experts on the mailing list.
21566 HOWEVER, some variables you have customized may contain private
21567 information. The names of customers, colleagues, or friends, might
21568 appear in the form of file names, tags, todo states, or search strings.
21569 If you answer yes to the prompt, you might want to check and remove
21570 such private information before sending the email.")
21571 (add-text-properties (point-min) (point-max) '(face org-warning))
21572 (when (yes-or-no-p "Include your Org configuration ")
21573 (mapatoms
21574 (lambda (v)
21575 (and (boundp v)
21576 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21577 (or (and (symbol-value v)
21578 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21579 (and
21580 (get v 'custom-type) (get v 'standard-value)
21581 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21582 (push v list)))))
21583 (kill-buffer (get-buffer "*Warn about privacy*"))
21584 list))
21585 nil nil
21586 "Remember to cover the basics, that is, what you expected to happen and
21587 what in fact did happen. You don't know how to make a good report? See
21589 https://orgmode.org/manual/Feedback.html#Feedback
21591 Your bug report will be posted to the Org mailing list.
21592 ------------------------------------------------------------------------")
21593 (save-excursion
21594 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21595 (replace-match "\\1Bug: \\3 [\\2]")))))
21598 (defun org-install-agenda-files-menu ()
21599 (let ((bl (buffer-list)))
21600 (save-excursion
21601 (while bl
21602 (set-buffer (pop bl))
21603 (when (derived-mode-p 'org-mode) (setq bl nil)))
21604 (when (derived-mode-p 'org-mode)
21605 (easy-menu-change
21606 '("Org") "File List for Agenda"
21607 (append
21608 (list
21609 ["Edit File List" (org-edit-agenda-file-list) t]
21610 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21611 ["Remove Current File from List" org-remove-file t]
21612 ["Cycle through agenda files" org-cycle-agenda-files t]
21613 ["Occur in all agenda files" org-occur-in-agenda-files t]
21614 "--")
21615 (mapcar 'org-file-menu-entry
21616 ;; Prevent initialization from failing.
21617 (ignore-errors (org-agenda-files t)))))))))
21619 ;;;; Documentation
21621 (defun org-require-autoloaded-modules ()
21622 (interactive)
21623 (mapc #'require
21624 '(org-agenda org-archive org-attach org-clock org-colview org-id
21625 org-table org-timer)))
21627 ;;;###autoload
21628 (defun org-reload (&optional uncompiled)
21629 "Reload all Org Lisp files.
21630 With prefix arg UNCOMPILED, load the uncompiled versions."
21631 (interactive "P")
21632 (require 'loadhist)
21633 (let* ((org-dir (org-find-library-dir "org"))
21634 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21635 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21636 (remove-re (format "\\`%s\\'"
21637 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21638 (feats (delete-dups
21639 (mapcar 'file-name-sans-extension
21640 (mapcar 'file-name-nondirectory
21641 (delq nil
21642 (mapcar 'feature-file
21643 features))))))
21644 (lfeat (append
21645 (sort
21646 (setq feats
21647 (delq nil (mapcar
21648 (lambda (f)
21649 (if (and (string-match feature-re f)
21650 (not (string-match remove-re f)))
21651 f nil))
21652 feats)))
21653 'string-lessp)
21654 (list "org-version" "org")))
21655 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21656 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21657 load-uncore load-misses)
21658 (setq load-misses
21659 (delq 't
21660 (mapcar (lambda (f)
21661 (or (org-load-noerror-mustsuffix (concat org-dir f))
21662 (and (string= org-dir contrib-dir)
21663 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21664 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21665 (add-to-list 'load-uncore f 'append)
21668 lfeat)))
21669 (when load-uncore
21670 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21671 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21672 (if load-misses
21673 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21674 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21675 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21677 ;;;###autoload
21678 (defun org-customize ()
21679 "Call the customize function with org as argument."
21680 (interactive)
21681 (org-load-modules-maybe)
21682 (org-require-autoloaded-modules)
21683 (customize-browse 'org))
21685 (defun org-create-customize-menu ()
21686 "Create a full customization menu for Org mode, insert it into the menu."
21687 (interactive)
21688 (org-load-modules-maybe)
21689 (org-require-autoloaded-modules)
21690 (if (fboundp 'customize-menu-create)
21691 (progn
21692 (easy-menu-change
21693 '("Org") "Customize"
21694 `(["Browse Org group" org-customize t]
21695 "--"
21696 ,(customize-menu-create 'org)
21697 ["Set" Custom-set t]
21698 ["Save" Custom-save t]
21699 ["Reset to Current" Custom-reset-current t]
21700 ["Reset to Saved" Custom-reset-saved t]
21701 ["Reset to Standard Settings" Custom-reset-standard t]))
21702 (message "\"Org\"-menu now contains full customization menu"))
21703 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21705 ;;;; Miscellaneous stuff
21707 ;;; Generally useful functions
21709 (defun org-get-at-eol (property n)
21710 "Get text property PROPERTY at the end of line less N characters."
21711 (get-text-property (- (point-at-eol) n) property))
21713 (defun org-find-text-property-in-string (prop s)
21714 "Return the first non-nil value of property PROP in string S."
21715 (or (get-text-property 0 prop s)
21716 (get-text-property (or (next-single-property-change 0 prop s) 0)
21717 prop s)))
21719 (defun org-display-warning (message)
21720 "Display the given MESSAGE as a warning."
21721 (display-warning 'org message :warning))
21723 (defun org-eval (form)
21724 "Eval FORM and return result."
21725 (condition-case error
21726 (eval form)
21727 (error (format "%%![Error: %s]" error))))
21729 (defun org-in-clocktable-p ()
21730 "Check if the cursor is in a clocktable."
21731 (let ((pos (point)) start)
21732 (save-excursion
21733 (end-of-line 1)
21734 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21735 (setq start (match-beginning 0))
21736 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21737 (>= (match-end 0) pos)
21738 start))))
21740 (defun org-in-verbatim-emphasis ()
21741 (save-match-data
21742 (and (org-in-regexp org-verbatim-re 2)
21743 (>= (point) (match-beginning 3))
21744 (<= (point) (match-end 4)))))
21746 (defun org-overlay-display (ovl text &optional face evap)
21747 "Make overlay OVL display TEXT with face FACE."
21748 (overlay-put ovl 'display text)
21749 (if face (overlay-put ovl 'face face))
21750 (if evap (overlay-put ovl 'evaporate t)))
21752 (defun org-overlay-before-string (ovl text &optional face evap)
21753 "Make overlay OVL display TEXT with face FACE."
21754 (if face (org-add-props text nil 'face face))
21755 (overlay-put ovl 'before-string text)
21756 (if evap (overlay-put ovl 'evaporate t)))
21758 (defun org-find-overlays (prop &optional pos delete)
21759 "Find all overlays specifying PROP at POS or point.
21760 If DELETE is non-nil, delete all those overlays."
21761 (let (found)
21762 (dolist (ov (overlays-at (or pos (point))) found)
21763 (cond ((not (overlay-get ov prop)))
21764 (delete (delete-overlay ov))
21765 (t (push ov found))))))
21767 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21768 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21769 (if (and marker (marker-buffer marker)
21770 (buffer-live-p (marker-buffer marker)))
21771 (progn
21772 (pop-to-buffer-same-window (marker-buffer marker))
21773 (when (or (> marker (point-max)) (< marker (point-min)))
21774 (widen))
21775 (goto-char marker)
21776 (org-show-context 'org-goto))
21777 (if bookmark
21778 (bookmark-jump bookmark)
21779 (error "Cannot find location"))))
21781 (defun org-quote-csv-field (s)
21782 "Quote field for inclusion in CSV material."
21783 (if (string-match "[\",]" s)
21784 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21787 (defun org-force-self-insert (N)
21788 "Needed to enforce self-insert under remapping."
21789 (interactive "p")
21790 (self-insert-command N))
21792 (defun org-shorten-string (s maxlength)
21793 "Shorten string S so that it is no longer than MAXLENGTH characters.
21794 If the string is shorter or has length MAXLENGTH, just return the
21795 original string. If it is longer, the functions finds a space in the
21796 string, breaks this string off at that locations and adds three dots
21797 as ellipsis. Including the ellipsis, the string will not be longer
21798 than MAXLENGTH. If finding a good breaking point in the string does
21799 not work, the string is just chopped off in the middle of a word
21800 if necessary."
21801 (if (<= (length s) maxlength)
21803 (let* ((n (max (- maxlength 4) 1))
21804 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21805 (if (string-match re s)
21806 (concat (match-string 1 s) "...")
21807 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21809 (defun org-get-indentation (&optional line)
21810 "Get the indentation of the current line, interpreting tabs.
21811 When LINE is given, assume it represents a line and compute its indentation."
21812 (if line
21813 (when (string-match "^ *" (org-remove-tabs line))
21814 (match-end 0))
21815 (save-excursion
21816 (beginning-of-line 1)
21817 (skip-chars-forward " \t")
21818 (current-column))))
21820 (defun org-get-string-indentation (s)
21821 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21822 (let ((n -1) (i 0) (w tab-width) c)
21823 (catch 'exit
21824 (while (< (setq n (1+ n)) (length s))
21825 (setq c (aref s n))
21826 (cond ((= c ?\ ) (setq i (1+ i)))
21827 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21828 (t (throw 'exit t)))))
21831 (defun org-remove-tabs (s &optional width)
21832 "Replace tabulators in S with spaces.
21833 Assumes that s is a single line, starting in column 0."
21834 (setq width (or width tab-width))
21835 (while (string-match "\t" s)
21836 (setq s (replace-match
21837 (make-string
21838 (- (* width (/ (+ (match-beginning 0) width) width))
21839 (match-beginning 0)) ?\ )
21840 t t s)))
21843 (defun org-fix-indentation (line ind)
21844 "Fix indentation in LINE.
21845 IND is a cons cell with target and minimum indentation.
21846 If the current indentation in LINE is smaller than the minimum,
21847 leave it alone. If it is larger than ind, set it to the target."
21848 (let* ((l (org-remove-tabs line))
21849 (i (org-get-indentation l))
21850 (i1 (car ind)) (i2 (cdr ind)))
21851 (when (>= i i2) (setq l (substring line i2)))
21852 (if (> i1 0)
21853 (concat (make-string i1 ?\ ) l)
21854 l)))
21856 (defun org-remove-indentation (code &optional n)
21857 "Remove maximum common indentation in string CODE and return it.
21858 N may optionally be the number of columns to remove. Return CODE
21859 as-is if removal failed."
21860 (with-temp-buffer
21861 (insert code)
21862 (if (org-do-remove-indentation n) (buffer-string) code)))
21864 (defun org-do-remove-indentation (&optional n)
21865 "Remove the maximum common indentation from the buffer.
21866 When optional argument N is a positive integer, remove exactly
21867 that much characters from indentation, if possible. Return nil
21868 if it fails."
21869 (catch :exit
21870 (goto-char (point-min))
21871 ;; Find maximum common indentation, if not specified.
21872 (let ((n (or n
21873 (let ((min-ind (point-max)))
21874 (save-excursion
21875 (while (re-search-forward "^[ \t]*\\S-" nil t)
21876 (let ((ind (1- (current-column))))
21877 (if (zerop ind) (throw :exit nil)
21878 (setq min-ind (min min-ind ind))))))
21879 min-ind))))
21880 (if (zerop n) (throw :exit nil)
21881 ;; Remove exactly N indentation, but give up if not possible.
21882 (while (not (eobp))
21883 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21884 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21885 ((< ind n) (throw :exit nil))
21886 (t (indent-line-to (- ind n))))
21887 (forward-line)))
21888 ;; Signal success.
21889 t))))
21891 (defun org-fill-template (template alist)
21892 "Find each %key of ALIST in TEMPLATE and replace it."
21893 (let ((case-fold-search nil))
21894 (dolist (entry (sort (copy-sequence alist)
21895 (lambda (a b) (< (length (car a)) (length (car b))))))
21896 (setq template
21897 (replace-regexp-in-string
21898 (concat "%" (regexp-quote (car entry)))
21899 (or (cdr entry) "") template t t)))
21900 template))
21902 (defun org-base-buffer (buffer)
21903 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21904 (if (not buffer)
21905 buffer
21906 (or (buffer-base-buffer buffer)
21907 buffer)))
21909 (defun org-wrap (string &optional width lines)
21910 "Wrap string to either a number of lines, or a width in characters.
21911 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21912 that costs. If there is a word longer than WIDTH, the text is actually
21913 wrapped to the length of that word.
21914 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21915 many lines, whatever width that takes.
21916 The return value is a list of lines, without newlines at the end."
21917 (let* ((words (split-string string))
21918 (maxword (apply 'max (mapcar 'org-string-width words)))
21919 w ll)
21920 (cond (width
21921 (org-do-wrap words (max maxword width)))
21922 (lines
21923 (setq w maxword)
21924 (setq ll (org-do-wrap words maxword))
21925 (if (<= (length ll) lines)
21927 (setq ll words)
21928 (while (> (length ll) lines)
21929 (setq w (1+ w))
21930 (setq ll (org-do-wrap words w)))
21931 ll))
21932 (t (error "Cannot wrap this")))))
21934 (defun org-do-wrap (words width)
21935 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21936 (let (lines line)
21937 (while words
21938 (setq line (pop words))
21939 (while (and words (< (+ (length line) (length (car words))) width))
21940 (setq line (concat line " " (pop words))))
21941 (setq lines (push line lines)))
21942 (nreverse lines)))
21944 (defun org-quote-vert (s)
21945 "Replace \"|\" with \"\\vert\"."
21946 (while (string-match "|" s)
21947 (setq s (replace-match "\\vert" t t s)))
21950 (defun org-uuidgen-p (s)
21951 "Is S an ID created by UUIDGEN?"
21952 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21954 (defun org-in-src-block-p (&optional inside)
21955 "Whether point is in a code source block.
21956 When INSIDE is non-nil, don't consider we are within a src block
21957 when point is at #+BEGIN_SRC or #+END_SRC."
21958 (let ((case-fold-search t))
21959 (or (and (eq (get-char-property (point) 'src-block) t))
21960 (and (not inside)
21961 (save-match-data
21962 (save-excursion
21963 (beginning-of-line)
21964 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21966 (defun org-context ()
21967 "Return a list of contexts of the current cursor position.
21968 If several contexts apply, all are returned.
21969 Each context entry is a list with a symbol naming the context, and
21970 two positions indicating start and end of the context. Possible
21971 contexts are:
21973 :headline anywhere in a headline
21974 :headline-stars on the leading stars in a headline
21975 :todo-keyword on a TODO keyword (including DONE) in a headline
21976 :tags on the TAGS in a headline
21977 :priority on the priority cookie in a headline
21978 :item on the first line of a plain list item
21979 :item-bullet on the bullet/number of a plain list item
21980 :checkbox on the checkbox in a plain list item
21981 :table in an Org table
21982 :table-special on a special filed in a table
21983 :table-table in a table.el table
21984 :clocktable in a clocktable
21985 :src-block in a source block
21986 :link on a hyperlink
21987 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21988 :target on a <<target>>
21989 :radio-target on a <<<radio-target>>>
21990 :latex-fragment on a LaTeX fragment
21991 :latex-preview on a LaTeX fragment with overlaid preview image
21993 This function expects the position to be visible because it uses font-lock
21994 faces as a help to recognize the following contexts: :table-special, :link,
21995 and :keyword."
21996 (let* ((f (get-text-property (point) 'face))
21997 (faces (if (listp f) f (list f)))
21998 (case-fold-search t)
21999 (p (point)) clist o)
22000 ;; First the large context
22001 (cond
22002 ((org-at-heading-p t)
22003 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22004 (when (progn
22005 (beginning-of-line 1)
22006 (looking-at org-todo-line-tags-regexp))
22007 (push (org-point-in-group p 1 :headline-stars) clist)
22008 (push (org-point-in-group p 2 :todo-keyword) clist)
22009 (push (org-point-in-group p 4 :tags) clist))
22010 (goto-char p)
22011 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22012 (when (looking-at "\\[#[A-Z0-9]\\]")
22013 (push (org-point-in-group p 0 :priority) clist)))
22015 ((org-at-item-p)
22016 (push (org-point-in-group p 2 :item-bullet) clist)
22017 (push (list :item (point-at-bol)
22018 (save-excursion (org-end-of-item) (point)))
22019 clist)
22020 (and (org-at-item-checkbox-p)
22021 (push (org-point-in-group p 0 :checkbox) clist)))
22023 ((org-at-table-p)
22024 (push (list :table (org-table-begin) (org-table-end)) clist)
22025 (when (memq 'org-formula faces)
22026 (push (list :table-special
22027 (previous-single-property-change p 'face)
22028 (next-single-property-change p 'face)) clist)))
22029 ((org-at-table-p 'any)
22030 (push (list :table-table) clist)))
22031 (goto-char p)
22033 (let ((case-fold-search t))
22034 ;; New the "medium" contexts: clocktables, source blocks
22035 (cond ((org-in-clocktable-p)
22036 (push (list :clocktable
22037 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22038 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22039 (match-beginning 1))
22040 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22041 (match-end 0))) clist))
22042 ((org-in-src-block-p)
22043 (push (list :src-block
22044 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22045 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22046 (match-beginning 1))
22047 (and (search-forward "#+END_SRC" nil t)
22048 (match-beginning 0))) clist))))
22049 (goto-char p)
22051 ;; Now the small context
22052 (cond
22053 ((org-at-timestamp-p)
22054 (push (org-point-in-group p 0 :timestamp) clist))
22055 ((memq 'org-link faces)
22056 (push (list :link
22057 (previous-single-property-change p 'face)
22058 (next-single-property-change p 'face)) clist))
22059 ((memq 'org-special-keyword faces)
22060 (push (list :keyword
22061 (previous-single-property-change p 'face)
22062 (next-single-property-change p 'face)) clist))
22063 ((org-at-target-p)
22064 (push (org-point-in-group p 0 :target) clist)
22065 (goto-char (1- (match-beginning 0)))
22066 (when (looking-at org-radio-target-regexp)
22067 (push (org-point-in-group p 0 :radio-target) clist))
22068 (goto-char p))
22069 ((setq o (cl-some
22070 (lambda (o)
22071 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22073 (overlays-at (point))))
22074 (push (list :latex-fragment
22075 (overlay-start o) (overlay-end o)) clist)
22076 (push (list :latex-preview
22077 (overlay-start o) (overlay-end o)) clist))
22078 ((org-inside-LaTeX-fragment-p)
22079 ;; FIXME: positions wrong.
22080 (push (list :latex-fragment (point) (point)) clist)))
22082 (setq clist (nreverse (delq nil clist)))
22083 clist))
22085 (defun org-in-regexp (regexp &optional nlines visually)
22086 "Check if point is inside a match of REGEXP.
22088 Normally only the current line is checked, but you can include
22089 NLINES extra lines around point into the search. If VISUALLY is
22090 set, require that the cursor is not after the match but really
22091 on, so that the block visually is on the match.
22093 Return nil or a cons cell (BEG . END) where BEG and END are,
22094 respectively, the positions at the beginning and the end of the
22095 match."
22096 (catch :exit
22097 (let ((pos (point))
22098 (eol (line-end-position (if nlines (1+ nlines) 1))))
22099 (save-excursion
22100 (beginning-of-line (- 1 (or nlines 0)))
22101 (while (and (re-search-forward regexp eol t)
22102 (<= (match-beginning 0) pos))
22103 (let ((end (match-end 0)))
22104 (when (or (> end pos) (and (= end pos) (not visually)))
22105 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22107 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22108 "Non-nil when point is between matches of START-RE and END-RE.
22110 Also return a non-nil value when point is on one of the matches.
22112 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22113 buffer positions. Default values are the positions of headlines
22114 surrounding the point.
22116 The functions returns a cons cell whose car (resp. cdr) is the
22117 position before START-RE (resp. after END-RE)."
22118 (save-match-data
22119 (let ((pos (point))
22120 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22121 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22122 beg end)
22123 (save-excursion
22124 ;; Point is on a block when on START-RE or if START-RE can be
22125 ;; found before it...
22126 (and (or (org-in-regexp start-re)
22127 (re-search-backward start-re limit-up t))
22128 (setq beg (match-beginning 0))
22129 ;; ... and END-RE after it...
22130 (goto-char (match-end 0))
22131 (re-search-forward end-re limit-down t)
22132 (> (setq end (match-end 0)) pos)
22133 ;; ... without another START-RE in-between.
22134 (goto-char (match-beginning 0))
22135 (not (re-search-backward start-re (1+ beg) t))
22136 ;; Return value.
22137 (cons beg end))))))
22139 (defun org-in-block-p (names)
22140 "Non-nil when point belongs to a block whose name belongs to NAMES.
22142 NAMES is a list of strings containing names of blocks.
22144 Return first block name matched, or nil. Beware that in case of
22145 nested blocks, the returned name may not belong to the closest
22146 block from point."
22147 (save-match-data
22148 (catch 'exit
22149 (let ((case-fold-search t)
22150 (lim-up (save-excursion (outline-previous-heading)))
22151 (lim-down (save-excursion (outline-next-heading))))
22152 (dolist (name names)
22153 (let ((n (regexp-quote name)))
22154 (when (org-between-regexps-p
22155 (concat "^[ \t]*#\\+begin_" n)
22156 (concat "^[ \t]*#\\+end_" n)
22157 lim-up lim-down)
22158 (throw 'exit n)))))
22159 nil)))
22161 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22162 "Call `multi-occur' with buffers for all agenda files."
22163 (interactive "sOrg-files matching: ")
22164 (let* ((files (org-agenda-files))
22165 (tnames (mapcar #'file-truename files))
22166 (extra org-agenda-text-search-extra-files))
22167 (when (eq (car extra) 'agenda-archives)
22168 (setq extra (cdr extra))
22169 (setq files (org-add-archive-files files)))
22170 (dolist (f extra)
22171 (unless (member (file-truename f) tnames)
22172 (unless (member f files) (setq files (append files (list f))))
22173 (setq tnames (append tnames (list (file-truename f))))))
22174 (multi-occur
22175 (mapcar (lambda (x)
22176 (with-current-buffer
22177 ;; FIXME: Why not just (find-file-noselect x)?
22178 ;; Is it to avoid the "revert buffer" prompt?
22179 (or (get-file-buffer x) (find-file-noselect x))
22180 (widen)
22181 (current-buffer)))
22182 files)
22183 regexp)))
22185 (add-hook 'occur-mode-find-occurrence-hook
22186 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22188 (defun org-occur-link-in-agenda-files ()
22189 "Create a link and search for it in the agendas.
22190 The link is not stored in `org-stored-links', it is just created
22191 for the search purpose."
22192 (interactive)
22193 (let ((link (condition-case nil
22194 (org-store-link nil)
22195 (error "Unable to create a link to here"))))
22196 (org-occur-in-agenda-files (regexp-quote link))))
22198 (defun org-reverse-string (string)
22199 "Return the reverse of STRING."
22200 (apply 'string (reverse (string-to-list string))))
22202 ;; defsubst org-uniquify must be defined before first use
22204 (defun org-uniquify-alist (alist)
22205 "Merge elements of ALIST with the same key.
22207 For example, in this alist:
22209 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22210 => \\='((a 1 3) (b 2))
22212 merge (a 1) and (a 3) into (a 1 3).
22214 The function returns the new ALIST."
22215 (let (rtn)
22216 (dolist (e alist rtn)
22217 (let (n)
22218 (if (not (assoc (car e) rtn))
22219 (push e rtn)
22220 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22221 (setq rtn (assq-delete-all (car e) rtn))
22222 (push n rtn))))))
22224 (defun org-delete-all (elts list)
22225 "Remove all elements in ELTS from LIST.
22226 Comparison is done with `equal'. It is a destructive operation
22227 that may remove elements by altering the list structure."
22228 (while elts
22229 (setq list (delete (pop elts) list)))
22230 list)
22232 (defun org-back-over-empty-lines ()
22233 "Move backwards over whitespace, to the beginning of the first empty line.
22234 Returns the number of empty lines passed."
22235 (let ((pos (point)))
22236 (if (cdr (assq 'heading org-blank-before-new-entry))
22237 (skip-chars-backward " \t\n\r")
22238 (unless (eobp)
22239 (forward-line -1)))
22240 (beginning-of-line 2)
22241 (goto-char (min (point) pos))
22242 (count-lines (point) pos)))
22244 (defun org-skip-whitespace ()
22245 (skip-chars-forward " \t\n\r"))
22247 (defun org-point-in-group (point group &optional context)
22248 "Check if POINT is in match-group GROUP.
22249 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22250 match. If the match group does not exist or point is not inside it,
22251 return nil."
22252 (and (match-beginning group)
22253 (>= point (match-beginning group))
22254 (<= point (match-end group))
22255 (if context
22256 (list context (match-beginning group) (match-end group))
22257 t)))
22259 (defun org-switch-to-buffer-other-window (&rest args)
22260 "Switch to buffer in a second window on the current frame.
22261 In particular, do not allow pop-up frames.
22262 Returns the newly created buffer."
22263 (org-no-popups
22264 (apply 'switch-to-buffer-other-window args)))
22266 (defun org-combine-plists (&rest plists)
22267 "Create a single property list from all plists in PLISTS.
22268 The process starts by copying the first list, and then setting properties
22269 from the other lists. Settings in the last list are the most significant
22270 ones and overrule settings in the other lists."
22271 (let ((rtn (copy-sequence (pop plists)))
22272 p v ls)
22273 (while plists
22274 (setq ls (pop plists))
22275 (while ls
22276 (setq p (pop ls) v (pop ls))
22277 (setq rtn (plist-put rtn p v))))
22278 rtn))
22280 (defun org-replace-escapes (string table)
22281 "Replace %-escapes in STRING with values in TABLE.
22282 TABLE is an association list with keys like \"%a\" and string values.
22283 The sequences in STRING may contain normal field width and padding information,
22284 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22285 so values can contain further %-escapes if they are define later in TABLE."
22286 (let ((tbl (copy-alist table))
22287 (case-fold-search nil)
22288 (pchg 0)
22289 re rpl)
22290 (dolist (e tbl)
22291 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22292 (when (and (cdr e) (string-match re (cdr e)))
22293 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22294 (safe "SREF"))
22295 (add-text-properties 0 3 (list 'sref sref) safe)
22296 (setcdr e (replace-match safe t t (cdr e)))))
22297 (while (string-match re string)
22298 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22299 (cdr e)))
22300 (setq string (replace-match rpl t t string))))
22301 (while (setq pchg (next-property-change pchg string))
22302 (let ((sref (get-text-property pchg 'sref string)))
22303 (when (and sref (string-match "SREF" string pchg))
22304 (setq string (replace-match sref t t string)))))
22305 string))
22307 (defun org-find-base-buffer-visiting (file)
22308 "Like `find-buffer-visiting' but always return the base buffer and
22309 not an indirect buffer."
22310 (let ((buf (or (get-file-buffer file)
22311 (find-buffer-visiting file))))
22312 (if buf
22313 (or (buffer-base-buffer buf) buf)
22314 nil)))
22316 ;;; TODO: Only called once, from ox-odt which should probably use
22317 ;;; org-export-inline-image-p or something.
22318 (defun org-file-image-p (file)
22319 "Return non-nil if FILE is an image."
22320 (save-match-data
22321 (string-match (image-file-name-regexp) file)))
22323 (defun org-get-cursor-date (&optional with-time)
22324 "Return the date at cursor in as a time.
22325 This works in the calendar and in the agenda, anywhere else it just
22326 returns the current time.
22327 If WITH-TIME is non-nil, returns the time of the event at point (in
22328 the agenda) or the current time of the day."
22329 (let (date day defd tp hod mod)
22330 (when with-time
22331 (setq tp (get-text-property (point) 'time))
22332 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22333 (setq hod (string-to-number (match-string 1 tp))
22334 mod (string-to-number (match-string 2 tp))))
22335 (or tp (let ((now (decode-time)))
22336 (setq hod (nth 2 now)
22337 mod (nth 1 now)))))
22338 (cond
22339 ((eq major-mode 'calendar-mode)
22340 (setq date (calendar-cursor-to-date)
22341 defd (encode-time 0 (or mod 0) (or hod 0)
22342 (nth 1 date) (nth 0 date) (nth 2 date))))
22343 ((eq major-mode 'org-agenda-mode)
22344 (setq day (get-text-property (point) 'day))
22345 (when day
22346 (setq date (calendar-gregorian-from-absolute day)
22347 defd (encode-time 0 (or mod 0) (or hod 0)
22348 (nth 1 date) (nth 0 date) (nth 2 date))))))
22349 (or defd (current-time))))
22351 (defun org-mark-subtree (&optional up)
22352 "Mark the current subtree.
22353 This puts point at the start of the current subtree, and mark at
22354 the end. If a numeric prefix UP is given, move up into the
22355 hierarchy of headlines by UP levels before marking the subtree."
22356 (interactive "P")
22357 (org-with-limited-levels
22358 (cond ((org-at-heading-p) (beginning-of-line))
22359 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22360 (t (outline-previous-visible-heading 1))))
22361 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22362 (if (called-interactively-p 'any)
22363 (call-interactively 'org-mark-element)
22364 (org-mark-element)))
22366 (defun org-file-newer-than-p (file time)
22367 "Non-nil if FILE is newer than TIME.
22368 FILE is a filename, as a string, TIME is a list of integers, as
22369 returned by, e.g., `current-time'."
22370 (and (file-exists-p file)
22371 ;; Only compare times up to whole seconds as some file-systems
22372 ;; (e.g. HFS+) do not retain any finer granularity. As
22373 ;; a consequence, make sure we return non-nil when the two
22374 ;; times are equal.
22375 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22376 (cl-subseq time 0 2)))))
22378 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22379 "Compile a SOURCE file using PROCESS.
22381 PROCESS is either a function or a list of shell commands, as
22382 strings. EXT is a file extension, without the leading dot, as
22383 a string. It is used to check if the process actually succeeded.
22385 PROCESS must create a file with the same base name and directory
22386 as SOURCE, but ending with EXT. The function then returns its
22387 filename. Otherwise, it raises an error. The error message can
22388 then be refined by providing string ERR-MSG, which is appended to
22389 the standard message.
22391 If PROCESS is a function, it is called with a single argument:
22392 the SOURCE file.
22394 If it is a list of commands, each of them is called using
22395 `shell-command'. By default, in each command, %b, %f, %F, %o and
22396 %O are replaced with, respectively, SOURCE base name, name, full
22397 name, directory and absolute output file name. It is possible,
22398 however, to use more place-holders by specifying them in optional
22399 argument SPEC, as an alist following the pattern
22401 (CHARACTER . REPLACEMENT-STRING).
22403 When PROCESS is a list of commands, optional argument LOG-BUF can
22404 be set to a buffer or a buffer name. `shell-command' then uses
22405 it for output."
22406 (let* ((base-name (file-name-base source))
22407 (full-name (file-truename source))
22408 (out-dir (or (file-name-directory source) "./"))
22409 (output (expand-file-name (concat base-name "." ext) out-dir))
22410 (time (current-time))
22411 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22412 (save-window-excursion
22413 (pcase process
22414 ((pred functionp) (funcall process (shell-quote-argument source)))
22415 ((pred consp)
22416 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22417 (spec (append spec
22418 `((?b . ,(shell-quote-argument base-name))
22419 (?f . ,(shell-quote-argument source))
22420 (?F . ,(shell-quote-argument full-name))
22421 (?o . ,(shell-quote-argument out-dir))
22422 (?O . ,(shell-quote-argument output))))))
22423 (dolist (command process)
22424 (shell-command (format-spec command spec) log-buf))
22425 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22426 (_ (error "No valid command to process %S%s" source err-msg))))
22427 ;; Check for process failure. Output file is expected to be
22428 ;; located in the same directory as SOURCE.
22429 (unless (org-file-newer-than-p output time)
22430 (error (format "File %S wasn't produced%s" output err-msg)))
22431 output))
22433 ;;; Indentation
22435 (defvar org-element-greater-elements)
22436 (defun org--get-expected-indentation (element contentsp)
22437 "Expected indentation column for current line, according to ELEMENT.
22438 ELEMENT is an element containing point. CONTENTSP is non-nil
22439 when indentation is to be computed according to contents of
22440 ELEMENT."
22441 (let ((type (org-element-type element))
22442 (start (org-element-property :begin element))
22443 (post-affiliated (org-element-property :post-affiliated element)))
22444 (org-with-wide-buffer
22445 (cond
22446 (contentsp
22447 (cl-case type
22448 ((diary-sexp footnote-definition) 0)
22449 ((headline inlinetask nil)
22450 (if (not org-adapt-indentation) 0
22451 (let ((level (org-current-level)))
22452 (if level (1+ level) 0))))
22453 ((item plain-list) (org-list-item-body-column post-affiliated))
22455 (goto-char start)
22456 (org-get-indentation))))
22457 ((memq type '(headline inlinetask nil))
22458 (if (org-match-line "[ \t]*$")
22459 (org--get-expected-indentation element t)
22461 ((memq type '(diary-sexp footnote-definition)) 0)
22462 ;; First paragraph of a footnote definition or an item.
22463 ;; Indent like parent.
22464 ((< (line-beginning-position) start)
22465 (org--get-expected-indentation
22466 (org-element-property :parent element) t))
22467 ;; At first line: indent according to previous sibling, if any,
22468 ;; ignoring footnote definitions and inline tasks, or parent's
22469 ;; contents.
22470 ((= (line-beginning-position) start)
22471 (catch 'exit
22472 (while t
22473 (if (= (point-min) start) (throw 'exit 0)
22474 (goto-char (1- start))
22475 (let* ((previous (org-element-at-point))
22476 (parent previous))
22477 (while (and parent (<= (org-element-property :end parent) start))
22478 (setq previous parent
22479 parent (org-element-property :parent parent)))
22480 (cond
22481 ((not previous) (throw 'exit 0))
22482 ((> (org-element-property :end previous) start)
22483 (throw 'exit (org--get-expected-indentation previous t)))
22484 ((memq (org-element-type previous)
22485 '(footnote-definition inlinetask))
22486 (setq start (org-element-property :begin previous)))
22487 (t (goto-char (org-element-property :begin previous))
22488 (throw 'exit
22489 (if (bolp) (org-get-indentation)
22490 ;; At first paragraph in an item or
22491 ;; a footnote definition.
22492 (org--get-expected-indentation
22493 (org-element-property :parent previous) t))))))))))
22494 ;; Otherwise, move to the first non-blank line above.
22496 (beginning-of-line)
22497 (let ((pos (point)))
22498 (skip-chars-backward " \r\t\n")
22499 (cond
22500 ;; Two blank lines end a footnote definition or a plain
22501 ;; list. When we indent an empty line after them, the
22502 ;; containing list or footnote definition is over, so it
22503 ;; qualifies as a previous sibling. Therefore, we indent
22504 ;; like its first line.
22505 ((and (memq type '(footnote-definition plain-list))
22506 (> (count-lines (point) pos) 2))
22507 (goto-char start)
22508 (org-get-indentation))
22509 ;; Line above is the first one of a paragraph at the
22510 ;; beginning of an item or a footnote definition. Indent
22511 ;; like parent.
22512 ((< (line-beginning-position) start)
22513 (org--get-expected-indentation
22514 (org-element-property :parent element) t))
22515 ;; Line above is the beginning of an element, i.e., point
22516 ;; was originally on the blank lines between element's start
22517 ;; and contents.
22518 ((= (line-beginning-position) post-affiliated)
22519 (org--get-expected-indentation element t))
22520 ;; POS is after contents in a greater element. Indent like
22521 ;; the beginning of the element.
22522 ((and (memq type org-element-greater-elements)
22523 (let ((cend (org-element-property :contents-end element)))
22524 (and cend (<= cend pos))))
22525 ;; As a special case, if point is at the end of a footnote
22526 ;; definition or an item, indent like the very last element
22527 ;; within. If that last element is an item, indent like
22528 ;; its contents.
22529 (if (memq type '(footnote-definition item plain-list))
22530 (let ((last (org-element-at-point)))
22531 (goto-char pos)
22532 (org--get-expected-indentation
22533 last (eq (org-element-type last) 'item)))
22534 (goto-char start)
22535 (org-get-indentation)))
22536 ;; In any other case, indent like the current line.
22537 (t (org-get-indentation)))))))))
22539 (defun org--align-node-property ()
22540 "Align node property at point.
22541 Alignment is done according to `org-property-format', which see."
22542 (when (save-excursion
22543 (beginning-of-line)
22544 (looking-at org-property-re))
22545 (replace-match
22546 (concat (match-string 4)
22547 (org-trim
22548 (format org-property-format (match-string 1) (match-string 3))))
22549 t t)))
22551 (defun org-indent-line ()
22552 "Indent line depending on context.
22554 Indentation is done according to the following rules:
22556 - Footnote definitions, diary sexps, headlines and inline tasks
22557 have to start at column 0.
22559 - On the very first line of an element, consider, in order, the
22560 next rules until one matches:
22562 1. If there's a sibling element before, ignoring footnote
22563 definitions and inline tasks, indent like its first line.
22565 2. If element has a parent, indent like its contents. More
22566 precisely, if parent is an item, indent after the
22567 description part, if any, or the bullet (see
22568 `org-list-description-max-indent'). Else, indent like
22569 parent's first line.
22571 3. Otherwise, indent relatively to current level, if
22572 `org-adapt-indentation' is non-nil, or to left margin.
22574 - On a blank line at the end of an element, indent according to
22575 the type of the element. More precisely
22577 1. If element is a plain list, an item, or a footnote
22578 definition, indent like the very last element within.
22580 2. If element is a paragraph, indent like its last non blank
22581 line.
22583 3. Otherwise, indent like its very first line.
22585 - In the code part of a source block, use language major mode
22586 to indent current line if `org-src-tab-acts-natively' is
22587 non-nil. If it is nil, do nothing.
22589 - Otherwise, indent like the first non-blank line above.
22591 The function doesn't indent an item as it could break the whole
22592 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22593 `\\[org-shiftmetaright]'.
22595 Also align node properties according to `org-property-format'."
22596 (interactive)
22597 (cond
22598 (orgstruct-is-++
22599 (let ((indent-line-function
22600 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22601 (indent-according-to-mode)))
22602 ((org-at-heading-p) 'noindent)
22604 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22605 (type (org-element-type element)))
22606 (cond ((and (memq type '(plain-list item))
22607 (= (line-beginning-position)
22608 (org-element-property :post-affiliated element)))
22609 'noindent)
22610 ((and (eq type 'latex-environment)
22611 (>= (point) (org-element-property :post-affiliated element))
22612 (< (point) (org-with-wide-buffer
22613 (goto-char (org-element-property :end element))
22614 (skip-chars-backward " \r\t\n")
22615 (line-beginning-position 2))))
22616 'noindent)
22617 ((and (eq type 'src-block)
22618 org-src-tab-acts-natively
22619 (> (line-beginning-position)
22620 (org-element-property :post-affiliated element))
22621 (< (line-beginning-position)
22622 (org-with-wide-buffer
22623 (goto-char (org-element-property :end element))
22624 (skip-chars-backward " \r\t\n")
22625 (line-beginning-position))))
22626 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22628 (let ((column (org--get-expected-indentation element nil)))
22629 ;; Preserve current column.
22630 (if (<= (current-column) (current-indentation))
22631 (indent-line-to column)
22632 (save-excursion (indent-line-to column))))
22633 ;; Align node property. Also preserve current column.
22634 (when (eq type 'node-property)
22635 (let ((column (current-column)))
22636 (org--align-node-property)
22637 (org-move-to-column column)))))))))
22639 (defun org-indent-region (start end)
22640 "Indent each non-blank line in the region.
22641 Called from a program, START and END specify the region to
22642 indent. The function will not indent contents of example blocks,
22643 verse blocks and export blocks as leading white spaces are
22644 assumed to be significant there."
22645 (interactive "r")
22646 (save-excursion
22647 (goto-char start)
22648 (skip-chars-forward " \r\t\n")
22649 (unless (eobp) (beginning-of-line))
22650 (let ((indent-to
22651 (lambda (ind pos)
22652 ;; Set IND as indentation for all lines between point and
22653 ;; POS. Blank lines are ignored. Leave point after POS
22654 ;; once done.
22655 (let ((limit (copy-marker pos)))
22656 (while (< (point) limit)
22657 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22658 (forward-line))
22659 (set-marker limit nil))))
22660 (end (copy-marker end)))
22661 (while (< (point) end)
22662 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22663 (let* ((element (org-element-at-point))
22664 (type (org-element-type element))
22665 (element-end (copy-marker (org-element-property :end element)))
22666 (ind (org--get-expected-indentation element nil)))
22667 (cond
22668 ;; Element indented as a single block. Example blocks
22669 ;; preserving indentation are a special case since the
22670 ;; "contents" must not be indented whereas the block
22671 ;; boundaries can.
22672 ((or (memq type '(export-block latex-environment))
22673 (and (eq type 'example-block)
22674 (not
22675 (or org-src-preserve-indentation
22676 (org-element-property :preserve-indent element)))))
22677 (let ((offset (- ind (org-get-indentation))))
22678 (unless (zerop offset)
22679 (indent-rigidly (org-element-property :begin element)
22680 (org-element-property :end element)
22681 offset)))
22682 (goto-char element-end))
22683 ;; Elements indented line wise. Be sure to exclude
22684 ;; example blocks (preserving indentation) and source
22685 ;; blocks from this category as they are treated
22686 ;; specially later.
22687 ((or (memq type '(paragraph table table-row))
22688 (not (or (org-element-property :contents-begin element)
22689 (memq type '(example-block src-block)))))
22690 (when (eq type 'node-property)
22691 (org--align-node-property)
22692 (beginning-of-line))
22693 (funcall indent-to ind (min element-end end)))
22694 ;; Elements consisting of three parts: before the
22695 ;; contents, the contents, and after the contents. The
22696 ;; contents are treated specially, according to the
22697 ;; element type, or not indented at all. Other parts are
22698 ;; indented as a single block.
22700 (let* ((post (copy-marker
22701 (org-element-property :post-affiliated element)))
22702 (cbeg
22703 (copy-marker
22704 (cond
22705 ((not (org-element-property :contents-begin element))
22706 ;; Fake contents for source blocks.
22707 (org-with-wide-buffer
22708 (goto-char post)
22709 (line-beginning-position 2)))
22710 ((memq type '(footnote-definition item plain-list))
22711 ;; Contents in these elements could start on
22712 ;; the same line as the beginning of the
22713 ;; element. Make sure we start indenting
22714 ;; from the second line.
22715 (org-with-wide-buffer
22716 (goto-char post)
22717 (end-of-line)
22718 (skip-chars-forward " \r\t\n")
22719 (if (eobp) (point) (line-beginning-position))))
22720 (t (org-element-property :contents-begin element)))))
22721 (cend (copy-marker
22722 (or (org-element-property :contents-end element)
22723 ;; Fake contents for source blocks.
22724 (org-with-wide-buffer
22725 (goto-char element-end)
22726 (skip-chars-backward " \r\t\n")
22727 (line-beginning-position)))
22728 t)))
22729 ;; Do not change items indentation individually as it
22730 ;; might break the list as a whole. On the other
22731 ;; hand, when at a plain list, indent it as a whole.
22732 (cond ((eq type 'plain-list)
22733 (let ((offset (- ind (org-get-indentation))))
22734 (unless (zerop offset)
22735 (indent-rigidly (org-element-property :begin element)
22736 (org-element-property :end element)
22737 offset))
22738 (goto-char cbeg)))
22739 ((eq type 'item) (goto-char cbeg))
22740 (t (funcall indent-to ind (min cbeg end))))
22741 (when (< (point) end)
22742 (cl-case type
22743 ((example-block verse-block))
22744 (src-block
22745 ;; In a source block, indent source code
22746 ;; according to language major mode, but only if
22747 ;; `org-src-tab-acts-natively' is non-nil.
22748 (when (and (< (point) end) org-src-tab-acts-natively)
22749 (ignore-errors
22750 (org-babel-do-in-edit-buffer
22751 (indent-region (point-min) (point-max))))))
22752 (t (org-indent-region (point) (min cend end))))
22753 (goto-char (min cend end))
22754 (when (< (point) end)
22755 (funcall indent-to ind (min element-end end))))
22756 (set-marker post nil)
22757 (set-marker cbeg nil)
22758 (set-marker cend nil))))
22759 (set-marker element-end nil))))
22760 (set-marker end nil))))
22762 (defun org-indent-drawer ()
22763 "Indent the drawer at point."
22764 (interactive)
22765 (unless (save-excursion
22766 (beginning-of-line)
22767 (looking-at-p org-drawer-regexp))
22768 (user-error "Not at a drawer"))
22769 (let ((element (org-element-at-point)))
22770 (unless (memq (org-element-type element) '(drawer property-drawer))
22771 (user-error "Not at a drawer"))
22772 (org-with-wide-buffer
22773 (org-indent-region (org-element-property :begin element)
22774 (org-element-property :end element))))
22775 (message "Drawer at point indented"))
22777 (defun org-indent-block ()
22778 "Indent the block at point."
22779 (interactive)
22780 (unless (save-excursion
22781 (beginning-of-line)
22782 (let ((case-fold-search t))
22783 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22784 (user-error "Not at a block"))
22785 (let ((element (org-element-at-point)))
22786 (unless (memq (org-element-type element)
22787 '(comment-block center-block dynamic-block example-block
22788 export-block quote-block special-block
22789 src-block verse-block))
22790 (user-error "Not at a block"))
22791 (org-with-wide-buffer
22792 (org-indent-region (org-element-property :begin element)
22793 (org-element-property :end element))))
22794 (message "Block at point indented"))
22797 ;;; Filling
22799 ;; We use our own fill-paragraph and auto-fill functions.
22801 ;; `org-fill-paragraph' relies on adaptive filling and context
22802 ;; checking. Appropriate `fill-prefix' is computed with
22803 ;; `org-adaptive-fill-function'.
22805 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22806 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22807 ;; `org-adaptive-fill-function' value. Internally,
22808 ;; `org-comment-line-break-function' breaks the line.
22810 ;; `org-setup-filling' installs filling and auto-filling related
22811 ;; variables during `org-mode' initialization.
22813 (defun org-setup-filling ()
22814 (require 'org-element)
22815 ;; Prevent auto-fill from inserting unwanted new items.
22816 (when (boundp 'fill-nobreak-predicate)
22817 (setq-local
22818 fill-nobreak-predicate
22819 (org-uniquify
22820 (append fill-nobreak-predicate
22821 '(org-fill-line-break-nobreak-p
22822 org-fill-n-macro-as-item-nobreak-p
22823 org-fill-paragraph-with-timestamp-nobreak-p)))))
22824 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22825 (setq-local paragraph-start paragraph-ending)
22826 (setq-local paragraph-separate paragraph-ending))
22827 (setq-local fill-paragraph-function 'org-fill-paragraph)
22828 (setq-local auto-fill-inhibit-regexp nil)
22829 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22830 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22831 (setq-local comment-line-break-function 'org-comment-line-break-function))
22833 (defun org-fill-line-break-nobreak-p ()
22834 "Non-nil when a new line at point would create an Org line break."
22835 (save-excursion
22836 (skip-chars-backward "[ \t]")
22837 (skip-chars-backward "\\\\")
22838 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22840 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22841 "Non-nil when a new line at point would split a timestamp."
22842 (and (org-at-timestamp-p 'lax)
22843 (not (looking-at org-ts-regexp-both))))
22845 (defun org-fill-n-macro-as-item-nobreak-p ()
22846 "Non-nil when a new line at point would create a new list."
22847 ;; During export, a "n" macro followed by a dot or a closing
22848 ;; parenthesis can end up being parsed as a new list item.
22849 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22851 (declare-function message-in-body-p "message" ())
22852 (defvar orgtbl-line-start-regexp) ; From org-table.el
22853 (defun org-adaptive-fill-function ()
22854 "Compute a fill prefix for the current line.
22855 Return fill prefix, as a string, or nil if current line isn't
22856 meant to be filled. For convenience, if `adaptive-fill-regexp'
22857 matches in paragraphs or comments, use it."
22858 (catch 'exit
22859 (when (derived-mode-p 'message-mode)
22860 (save-excursion
22861 (beginning-of-line)
22862 (cond ((not (message-in-body-p)) (throw 'exit nil))
22863 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22864 ((looking-at message-cite-prefix-regexp)
22865 (throw 'exit (match-string-no-properties 0)))
22866 ((looking-at org-outline-regexp)
22867 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22868 (org-with-wide-buffer
22869 (unless (org-at-heading-p)
22870 (let* ((p (line-beginning-position))
22871 (element (save-excursion
22872 (beginning-of-line)
22873 (org-element-at-point)))
22874 (type (org-element-type element))
22875 (post-affiliated (org-element-property :post-affiliated element)))
22876 (unless (< p post-affiliated)
22877 (cl-case type
22878 (comment
22879 (save-excursion
22880 (beginning-of-line)
22881 (looking-at "[ \t]*")
22882 (concat (match-string 0) "# ")))
22883 (footnote-definition "")
22884 ((item plain-list)
22885 (make-string (org-list-item-body-column post-affiliated) ?\s))
22886 (paragraph
22887 ;; Fill prefix is usually the same as the current line,
22888 ;; unless the paragraph is at the beginning of an item.
22889 (let ((parent (org-element-property :parent element)))
22890 (save-excursion
22891 (beginning-of-line)
22892 (cond ((eq (org-element-type parent) 'item)
22893 (make-string (org-list-item-body-column
22894 (org-element-property :begin parent))
22895 ?\s))
22896 ((and adaptive-fill-regexp
22897 ;; Locally disable
22898 ;; `adaptive-fill-function' to let
22899 ;; `fill-context-prefix' handle
22900 ;; `adaptive-fill-regexp' variable.
22901 (let (adaptive-fill-function)
22902 (fill-context-prefix
22903 post-affiliated
22904 (org-element-property :end element)))))
22905 ((looking-at "[ \t]+") (match-string 0))
22906 (t "")))))
22907 (comment-block
22908 ;; Only fill contents if P is within block boundaries.
22909 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22910 (forward-line)
22911 (point)))
22912 (cend (save-excursion
22913 (goto-char (org-element-property :end element))
22914 (skip-chars-backward " \r\t\n")
22915 (line-beginning-position))))
22916 (when (and (>= p cbeg) (< p cend))
22917 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22918 (match-string 0)
22919 "")))))))))))
22921 (declare-function message-goto-body "message" ())
22922 (defvar message-cite-prefix-regexp) ; From message.el
22924 (defun org-fill-element (&optional justify)
22925 "Fill element at point, when applicable.
22927 This function only applies to comment blocks, comments, example
22928 blocks and paragraphs. Also, as a special case, re-align table
22929 when point is at one.
22931 If JUSTIFY is non-nil (interactively, with prefix argument),
22932 justify as well. If `sentence-end-double-space' is non-nil, then
22933 period followed by one space does not end a sentence, so don't
22934 break a line there. The variable `fill-column' controls the
22935 width for filling.
22937 For convenience, when point is at a plain list, an item or
22938 a footnote definition, try to fill the first paragraph within."
22939 (with-syntax-table org-mode-transpose-word-syntax-table
22940 ;; Move to end of line in order to get the first paragraph within
22941 ;; a plain list or a footnote definition.
22942 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22943 ;; First check if point is in a blank line at the beginning of
22944 ;; the buffer. In that case, ignore filling.
22945 (cl-case (org-element-type element)
22946 ;; Use major mode filling function is src blocks.
22947 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22948 ;; Align Org tables, leave table.el tables as-is.
22949 (table-row (org-table-align) t)
22950 (table
22951 (when (eq (org-element-property :type element) 'org)
22952 (save-excursion
22953 (goto-char (org-element-property :post-affiliated element))
22954 (org-table-align)))
22956 (paragraph
22957 ;; Paragraphs may contain `line-break' type objects.
22958 (let ((beg (max (point-min)
22959 (org-element-property :contents-begin element)))
22960 (end (min (point-max)
22961 (org-element-property :contents-end element))))
22962 ;; Do nothing if point is at an affiliated keyword.
22963 (if (< (line-end-position) beg) t
22964 (when (derived-mode-p 'message-mode)
22965 ;; In `message-mode', do not fill following citation
22966 ;; in current paragraph nor text before message body.
22967 (let ((body-start (save-excursion (message-goto-body))))
22968 (when body-start (setq beg (max body-start beg))))
22969 (when (save-excursion
22970 (re-search-forward
22971 (concat "^" message-cite-prefix-regexp) end t))
22972 (setq end (match-beginning 0))))
22973 ;; Fill paragraph, taking line breaks into account.
22974 (save-excursion
22975 (goto-char beg)
22976 (let ((cuts (list beg)))
22977 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22978 (when (eq 'line-break
22979 (org-element-type
22980 (save-excursion (backward-char)
22981 (org-element-context))))
22982 (push (point) cuts)))
22983 (dolist (c (delq end cuts))
22984 (fill-region-as-paragraph c end justify)
22985 (setq end c))))
22986 t)))
22987 ;; Contents of `comment-block' type elements should be
22988 ;; filled as plain text, but only if point is within block
22989 ;; markers.
22990 (comment-block
22991 (let* ((case-fold-search t)
22992 (beg (save-excursion
22993 (goto-char (org-element-property :begin element))
22994 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22995 (forward-line)
22996 (point)))
22997 (end (save-excursion
22998 (goto-char (org-element-property :end element))
22999 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23000 (line-beginning-position))))
23001 (if (or (< (point) beg) (> (point) end)) t
23002 (fill-region-as-paragraph
23003 (save-excursion (end-of-line)
23004 (re-search-backward "^[ \t]*$" beg 'move)
23005 (line-beginning-position))
23006 (save-excursion (beginning-of-line)
23007 (re-search-forward "^[ \t]*$" end 'move)
23008 (line-beginning-position))
23009 justify))))
23010 ;; Fill comments.
23011 (comment
23012 (let ((begin (org-element-property :post-affiliated element))
23013 (end (org-element-property :end element)))
23014 (when (and (>= (point) begin) (<= (point) end))
23015 (let ((begin (save-excursion
23016 (end-of-line)
23017 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23018 (progn (forward-line) (point))
23019 begin)))
23020 (end (save-excursion
23021 (end-of-line)
23022 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23023 (1- (line-beginning-position))
23024 (skip-chars-backward " \r\t\n")
23025 (line-end-position)))))
23026 ;; Do not fill comments when at a blank line.
23027 (when (> end begin)
23028 (let ((fill-prefix
23029 (save-excursion
23030 (beginning-of-line)
23031 (looking-at "[ \t]*#")
23032 (let ((comment-prefix (match-string 0)))
23033 (goto-char (match-end 0))
23034 (if (looking-at adaptive-fill-regexp)
23035 (concat comment-prefix (match-string 0))
23036 (concat comment-prefix " "))))))
23037 (save-excursion
23038 (fill-region-as-paragraph begin end justify))))))
23040 ;; Ignore every other element.
23041 (otherwise t)))))
23043 (defun org-fill-paragraph (&optional justify region)
23044 "Fill element at point, when applicable.
23046 This function only applies to comment blocks, comments, example
23047 blocks and paragraphs. Also, as a special case, re-align table
23048 when point is at one.
23050 For convenience, when point is at a plain list, an item or
23051 a footnote definition, try to fill the first paragraph within.
23053 If JUSTIFY is non-nil (interactively, with prefix argument),
23054 justify as well. If `sentence-end-double-space' is non-nil, then
23055 period followed by one space does not end a sentence, so don't
23056 break a line there. The variable `fill-column' controls the
23057 width for filling.
23059 The REGION argument is non-nil if called interactively; in that
23060 case, if Transient Mark mode is enabled and the mark is active,
23061 fill each of the elements in the active region, instead of just
23062 filling the current element."
23063 (interactive (progn
23064 (barf-if-buffer-read-only)
23065 (list (if current-prefix-arg 'full) t)))
23066 (cond
23067 ((and (derived-mode-p 'message-mode)
23068 (or (not (message-in-body-p))
23069 (save-excursion (move-beginning-of-line 1)
23070 (looking-at message-cite-prefix-regexp))))
23071 ;; First ensure filling is correct in message-mode.
23072 (let ((fill-paragraph-function
23073 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23074 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23075 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23076 (paragraph-separate
23077 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23078 (fill-paragraph nil)))
23079 ((and region transient-mark-mode mark-active
23080 (not (eq (region-beginning) (region-end))))
23081 (let ((origin (point-marker))
23082 (start (region-beginning)))
23083 (unwind-protect
23084 (progn
23085 (goto-char (region-end))
23086 (while (> (point) start)
23087 (org-backward-paragraph)
23088 (org-fill-element justify)))
23089 (goto-char origin)
23090 (set-marker origin nil))))
23091 (t (org-fill-element justify))))
23092 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23094 (defun org-auto-fill-function ()
23095 "Auto-fill function."
23096 ;; Check if auto-filling is meaningful.
23097 (let ((fc (current-fill-column)))
23098 (when (and fc (> (current-column) fc))
23099 (let* ((fill-prefix (org-adaptive-fill-function))
23100 ;; Enforce empty fill prefix, if required. Otherwise, it
23101 ;; will be computed again.
23102 (adaptive-fill-mode (not (equal fill-prefix ""))))
23103 (when fill-prefix (do-auto-fill))))))
23105 (defun org-comment-line-break-function (&optional soft)
23106 "Break line at point and indent, continuing comment if within one.
23107 The inserted newline is marked hard if variable
23108 `use-hard-newlines' is true, unless optional argument SOFT is
23109 non-nil."
23110 (if soft (insert-and-inherit ?\n) (newline 1))
23111 (save-excursion (forward-char -1) (delete-horizontal-space))
23112 (delete-horizontal-space)
23113 (indent-to-left-margin)
23114 (insert-before-markers-and-inherit fill-prefix))
23117 ;;; Fixed Width Areas
23119 (defun org-toggle-fixed-width ()
23120 "Toggle fixed-width markup.
23122 Add or remove fixed-width markup on current line, whenever it
23123 makes sense. Return an error otherwise.
23125 If a region is active and if it contains only fixed-width areas
23126 or blank lines, remove all fixed-width markup in it. If the
23127 region contains anything else, convert all non-fixed-width lines
23128 to fixed-width ones.
23130 Blank lines at the end of the region are ignored unless the
23131 region only contains such lines."
23132 (interactive)
23133 (if (not (org-region-active-p))
23134 ;; No region:
23136 ;; Remove fixed width marker only in a fixed-with element.
23138 ;; Add fixed width maker in paragraphs, in blank lines after
23139 ;; elements or at the beginning of a headline or an inlinetask,
23140 ;; and before any one-line elements (e.g., a clock).
23141 (progn
23142 (beginning-of-line)
23143 (let* ((element (org-element-at-point))
23144 (type (org-element-type element)))
23145 (cond
23146 ((and (eq type 'fixed-width)
23147 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23148 (replace-match
23149 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23150 ((and (memq type '(babel-call clock comment diary-sexp headline
23151 horizontal-rule keyword paragraph
23152 planning))
23153 (<= (org-element-property :post-affiliated element) (point)))
23154 (skip-chars-forward " \t")
23155 (insert ": "))
23156 ((and (looking-at-p "[ \t]*$")
23157 (or (eq type 'inlinetask)
23158 (save-excursion
23159 (skip-chars-forward " \r\t\n")
23160 (<= (org-element-property :end element) (point)))))
23161 (delete-region (point) (line-end-position))
23162 (org-indent-line)
23163 (insert ": "))
23164 (t (user-error "Cannot insert a fixed-width line here")))))
23165 ;; Region active.
23166 (let* ((begin (save-excursion
23167 (goto-char (region-beginning))
23168 (line-beginning-position)))
23169 (end (copy-marker
23170 (save-excursion
23171 (goto-char (region-end))
23172 (unless (eolp) (beginning-of-line))
23173 (if (save-excursion (re-search-backward "\\S-" begin t))
23174 (progn (skip-chars-backward " \r\t\n") (point))
23175 (point)))))
23176 (all-fixed-width-p
23177 (catch 'not-all-p
23178 (save-excursion
23179 (goto-char begin)
23180 (skip-chars-forward " \r\t\n")
23181 (when (eobp) (throw 'not-all-p nil))
23182 (while (< (point) end)
23183 (let ((element (org-element-at-point)))
23184 (if (eq (org-element-type element) 'fixed-width)
23185 (goto-char (org-element-property :end element))
23186 (throw 'not-all-p nil))))
23187 t))))
23188 (if all-fixed-width-p
23189 (save-excursion
23190 (goto-char begin)
23191 (while (< (point) end)
23192 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23193 (replace-match
23194 "" nil nil nil
23195 (if (= (line-end-position) (match-end 0)) 0 1)))
23196 (forward-line)))
23197 (let ((min-ind (point-max)))
23198 ;; Find minimum indentation across all lines.
23199 (save-excursion
23200 (goto-char begin)
23201 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23202 (setq min-ind 0)
23203 (catch 'zerop
23204 (while (< (point) end)
23205 (unless (looking-at-p "[ \t]*$")
23206 (let ((ind (org-get-indentation)))
23207 (setq min-ind (min min-ind ind))
23208 (when (zerop ind) (throw 'zerop t))))
23209 (forward-line)))))
23210 ;; Loop over all lines and add fixed-width markup everywhere
23211 ;; but in fixed-width lines.
23212 (save-excursion
23213 (goto-char begin)
23214 (while (< (point) end)
23215 (cond
23216 ((org-at-heading-p)
23217 (insert ": ")
23218 (forward-line)
23219 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23220 (insert ":")
23221 (forward-line)))
23222 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23223 (let* ((element (org-element-at-point))
23224 (element-end (org-element-property :end element)))
23225 (if (eq (org-element-type element) 'fixed-width)
23226 (progn (goto-char element-end)
23227 (skip-chars-backward " \r\t\n")
23228 (forward-line))
23229 (let ((limit (min end element-end)))
23230 (while (< (point) limit)
23231 (org-move-to-column min-ind t)
23232 (insert ": ")
23233 (forward-line))))))
23235 (org-move-to-column min-ind t)
23236 (insert ": ")
23237 (forward-line)))))))
23238 (set-marker end nil))))
23241 ;;; Comments
23243 ;; Org comments syntax is quite complex. It requires the entire line
23244 ;; to be just a comment. Also, even with the right syntax at the
23245 ;; beginning of line, some elements (e.g., verse-block or
23246 ;; example-block) don't accept comments. Usual Emacs comment commands
23247 ;; cannot cope with those requirements. Therefore, Org replaces them.
23249 ;; Org still relies on `comment-dwim', but cannot trust
23250 ;; `comment-only-p'. So, `comment-region-function' and
23251 ;; `uncomment-region-function' both point
23252 ;; to`org-comment-or-uncomment-region'. Eventually,
23253 ;; `org-insert-comment' takes care of insertion of comments at the
23254 ;; beginning of line.
23256 ;; `org-setup-comments-handling' install comments related variables
23257 ;; during `org-mode' initialization.
23259 (defun org-setup-comments-handling ()
23260 (interactive)
23261 (setq-local comment-use-syntax nil)
23262 (setq-local comment-start "# ")
23263 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23264 (setq-local comment-insert-comment-function 'org-insert-comment)
23265 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23266 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23268 (defun org-insert-comment ()
23269 "Insert an empty comment above current line.
23270 If the line is empty, insert comment at its beginning. When
23271 point is within a source block, comment according to the related
23272 major mode."
23273 (if (let ((element (org-element-at-point)))
23274 (and (eq (org-element-type element) 'src-block)
23275 (< (save-excursion
23276 (goto-char (org-element-property :post-affiliated element))
23277 (line-end-position))
23278 (point))
23279 (> (save-excursion
23280 (goto-char (org-element-property :end element))
23281 (skip-chars-backward " \r\t\n")
23282 (line-beginning-position))
23283 (point))))
23284 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23285 (beginning-of-line)
23286 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23287 (open-line 1))
23288 (org-indent-line)
23289 (insert "# ")))
23291 (defvar comment-empty-lines) ; From newcomment.el.
23292 (defun org-comment-or-uncomment-region (beg end &rest _)
23293 "Comment or uncomment each non-blank line in the region.
23294 Uncomment each non-blank line between BEG and END if it only
23295 contains commented lines. Otherwise, comment them. If region is
23296 strictly within a source block, use appropriate comment syntax."
23297 (if (let ((element (org-element-at-point)))
23298 (and (eq (org-element-type element) 'src-block)
23299 (< (save-excursion
23300 (goto-char (org-element-property :post-affiliated element))
23301 (line-end-position))
23302 beg)
23303 (>= (save-excursion
23304 (goto-char (org-element-property :end element))
23305 (skip-chars-backward " \r\t\n")
23306 (line-beginning-position))
23307 end)))
23308 ;; Translate region boundaries for the Org buffer to the source
23309 ;; buffer.
23310 (let ((offset (- end beg)))
23311 (save-excursion
23312 (goto-char beg)
23313 (org-babel-do-in-edit-buffer
23314 (comment-or-uncomment-region (point) (+ offset (point))))))
23315 (save-restriction
23316 ;; Restrict region
23317 (narrow-to-region (save-excursion (goto-char beg)
23318 (skip-chars-forward " \r\t\n" end)
23319 (line-beginning-position))
23320 (save-excursion (goto-char end)
23321 (skip-chars-backward " \r\t\n" beg)
23322 (line-end-position)))
23323 (let ((uncommentp
23324 ;; UNCOMMENTP is non-nil when every non blank line between
23325 ;; BEG and END is a comment.
23326 (save-excursion
23327 (goto-char (point-min))
23328 (while (and (not (eobp))
23329 (let ((element (org-element-at-point)))
23330 (and (eq (org-element-type element) 'comment)
23331 (goto-char (min (point-max)
23332 (org-element-property
23333 :end element)))))))
23334 (eobp))))
23335 (if uncommentp
23336 ;; Only blank lines and comments in region: uncomment it.
23337 (save-excursion
23338 (goto-char (point-min))
23339 (while (not (eobp))
23340 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23341 (replace-match "" nil nil nil 1))
23342 (forward-line)))
23343 ;; Comment each line in region.
23344 (let ((min-indent (point-max)))
23345 ;; First find the minimum indentation across all lines.
23346 (save-excursion
23347 (goto-char (point-min))
23348 (while (and (not (eobp)) (not (zerop min-indent)))
23349 (unless (looking-at "[ \t]*$")
23350 (setq min-indent (min min-indent (current-indentation))))
23351 (forward-line)))
23352 ;; Then loop over all lines.
23353 (save-excursion
23354 (goto-char (point-min))
23355 (while (not (eobp))
23356 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23357 ;; Don't get fooled by invisible text (e.g. link path)
23358 ;; when moving to column MIN-INDENT.
23359 (let ((buffer-invisibility-spec nil))
23360 (org-move-to-column min-indent t))
23361 (insert comment-start))
23362 (forward-line)))))))))
23364 (defun org-comment-dwim (_arg)
23365 "Call `comment-dwim' within a source edit buffer if needed."
23366 (interactive "*P")
23367 (if (org-in-src-block-p)
23368 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23369 (call-interactively 'comment-dwim)))
23372 ;;; Timestamps API
23374 ;; This section contains tools to operate on timestamp objects, as
23375 ;; returned by, e.g. `org-element-context'.
23377 (defun org-timestamp--to-internal-time (timestamp &optional end)
23378 "Encode TIMESTAMP object into Emacs internal time.
23379 Use end of date range or time range when END is non-nil."
23380 (apply #'encode-time
23381 (cons 0
23382 (mapcar
23383 (lambda (prop) (or (org-element-property prop timestamp) 0))
23384 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23385 '(:minute-start :hour-start :day-start :month-start
23386 :year-start))))))
23388 (defun org-timestamp-has-time-p (timestamp)
23389 "Non-nil when TIMESTAMP has a time specified."
23390 (org-element-property :hour-start timestamp))
23392 (defun org-timestamp-format (timestamp format &optional end utc)
23393 "Format a TIMESTAMP object into a string.
23395 FORMAT is a format specifier to be passed to
23396 `format-time-string'.
23398 When optional argument END is non-nil, use end of date-range or
23399 time-range, if possible.
23401 When optional argument UTC is non-nil, time will be expressed as
23402 Universal Time."
23403 (format-time-string
23404 format (org-timestamp--to-internal-time timestamp end)
23405 (and utc t)))
23407 (defun org-timestamp-split-range (timestamp &optional end)
23408 "Extract a TIMESTAMP object from a date or time range.
23410 END, when non-nil, means extract the end of the range.
23411 Otherwise, extract its start.
23413 Return a new timestamp object."
23414 (let ((type (org-element-property :type timestamp)))
23415 (if (memq type '(active inactive diary)) timestamp
23416 (let ((split-ts (org-element-copy timestamp)))
23417 ;; Set new type.
23418 (org-element-put-property
23419 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23420 ;; Copy start properties over end properties if END is
23421 ;; non-nil. Otherwise, copy end properties over `start' ones.
23422 (let ((p-alist '((:minute-start . :minute-end)
23423 (:hour-start . :hour-end)
23424 (:day-start . :day-end)
23425 (:month-start . :month-end)
23426 (:year-start . :year-end))))
23427 (dolist (p-cell p-alist)
23428 (org-element-put-property
23429 split-ts
23430 (funcall (if end #'car #'cdr) p-cell)
23431 (org-element-property
23432 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23433 ;; Eventually refresh `:raw-value'.
23434 (org-element-put-property split-ts :raw-value nil)
23435 (org-element-put-property
23436 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23438 (defun org-timestamp-translate (timestamp &optional boundary)
23439 "Translate TIMESTAMP object to custom format.
23441 Format string is defined in `org-time-stamp-custom-formats',
23442 which see.
23444 When optional argument BOUNDARY is non-nil, it is either the
23445 symbol `start' or `end'. In this case, only translate the
23446 starting or ending part of TIMESTAMP if it is a date or time
23447 range. Otherwise, translate both parts.
23449 Return timestamp as-is if `org-display-custom-times' is nil or if
23450 it has a `diary' type."
23451 (let ((type (org-element-property :type timestamp)))
23452 (if (or (not org-display-custom-times) (eq type 'diary))
23453 (org-element-interpret-data timestamp)
23454 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23455 org-time-stamp-custom-formats)))
23456 (if (and (not boundary) (memq type '(active-range inactive-range)))
23457 (concat (org-timestamp-format timestamp fmt)
23458 "--"
23459 (org-timestamp-format timestamp fmt t))
23460 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23464 ;;; Other stuff.
23466 (defvar reftex-docstruct-symbol)
23467 (defvar org--rds)
23469 (defun org-reftex-citation ()
23470 "Use reftex-citation to insert a citation into the buffer.
23471 This looks for a line like
23473 #+BIBLIOGRAPHY: foo plain option:-d
23475 and derives from it that foo.bib is the bibliography file relevant
23476 for this document. It then installs the necessary environment for RefTeX
23477 to work in this buffer and calls `reftex-citation' to insert a citation
23478 into the buffer.
23480 Export of such citations to both LaTeX and HTML is handled by the contributed
23481 package ox-bibtex by Taru Karttunen."
23482 (interactive)
23483 (let ((reftex-docstruct-symbol 'org--rds)
23484 org--rds bib)
23485 (org-with-wide-buffer
23486 (let ((case-fold-search t)
23487 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23488 (if (not (save-excursion
23489 (or (re-search-forward re nil t)
23490 (re-search-backward re nil t))))
23491 (user-error "No bibliography defined in file")
23492 (setq bib (concat (match-string 1) ".bib")
23493 org--rds (list (list 'bib bib))))))
23494 (call-interactively 'reftex-citation)))
23496 ;;;; Functions extending outline functionality
23498 (defun org-beginning-of-line (&optional n)
23499 "Go to the beginning of the current visible line.
23501 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23502 tags on the first attempt, and only move to after the tags when
23503 the cursor is already beyond the end of the headline.
23505 With argument N not nil or 1, move forward N - 1 lines first."
23506 (interactive "^p")
23507 (let ((origin (point))
23508 (special (pcase org-special-ctrl-a/e
23509 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23510 deactivate-mark)
23511 ;; First move to a visible line.
23512 (if (bound-and-true-p visual-line-mode)
23513 (beginning-of-visual-line n)
23514 (move-beginning-of-line n)
23515 ;; `move-beginning-of-line' may leave point after invisible
23516 ;; characters if line starts with such of these (e.g., with
23517 ;; a link at column 0). Really move to the beginning of the
23518 ;; current visible line.
23519 (beginning-of-line))
23520 (cond
23521 ;; No special behavior. Point is already at the beginning of
23522 ;; a line, logical or visual.
23523 ((not special))
23524 ;; `beginning-of-visual-line' left point before logical beginning
23525 ;; of line: point is at the beginning of a visual line. Bail
23526 ;; out.
23527 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23528 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23529 ;; At a headline, special position is before the title, but
23530 ;; after any TODO keyword or priority cookie.
23531 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23532 (line-end-position)))
23533 (bol (point)))
23534 (if (eq special 'reversed)
23535 (when (and (= origin bol) (eq last-command this-command))
23536 (goto-char refpos))
23537 (when (or (> origin refpos) (= origin bol))
23538 (goto-char refpos)))))
23539 ((and (looking-at org-list-full-item-re)
23540 (memq (org-element-type (save-match-data (org-element-at-point)))
23541 '(item plain-list)))
23542 ;; Set special position at first white space character after
23543 ;; bullet, and check-box, if any.
23544 (let ((after-bullet
23545 (let ((box (match-end 3)))
23546 (cond ((not box) (match-end 1))
23547 ((eq (char-after box) ?\s) (1+ box))
23548 (t box)))))
23549 (if (eq special 'reversed)
23550 (when (and (= (point) origin) (eq last-command this-command))
23551 (goto-char after-bullet))
23552 (when (or (> origin after-bullet) (= (point) origin))
23553 (goto-char after-bullet)))))
23554 ;; No special context. Point is already at beginning of line.
23555 (t nil))))
23557 (defun org-end-of-line (&optional n)
23558 "Go to the end of the line, but before ellipsis, if any.
23560 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23561 tags on the first attempt, and only move to after the tags when
23562 the cursor is already beyond the end of the headline.
23564 With argument N not nil or 1, move forward N - 1 lines first."
23565 (interactive "^p")
23566 (let ((origin (point))
23567 (special (pcase org-special-ctrl-a/e
23568 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23569 deactivate-mark)
23570 ;; First move to a visible line.
23571 (if (bound-and-true-p visual-line-mode)
23572 (beginning-of-visual-line n)
23573 (move-beginning-of-line n))
23574 (cond
23575 ;; At a headline, with tags.
23576 ((and special
23577 (save-excursion
23578 (beginning-of-line)
23579 (let ((case-fold-search nil))
23580 (looking-at org-complex-heading-regexp)))
23581 (match-end 5))
23582 (let ((tags (save-excursion
23583 (goto-char (match-beginning 5))
23584 (skip-chars-backward " \t")
23585 (point)))
23586 (visual-end (and (bound-and-true-p visual-line-mode)
23587 (save-excursion
23588 (end-of-visual-line)
23589 (point)))))
23590 ;; If `end-of-visual-line' brings us before end of line or
23591 ;; even tags, i.e., the headline spans over multiple visual
23592 ;; lines, move there.
23593 (cond ((and visual-end
23594 (< visual-end tags)
23595 (<= origin visual-end))
23596 (goto-char visual-end))
23597 ((eq special 'reversed)
23598 (if (and (= origin (line-end-position))
23599 (eq this-command last-command))
23600 (goto-char tags)
23601 (end-of-line)))
23603 (if (or (< origin tags) (= origin (line-end-position)))
23604 (goto-char tags)
23605 (end-of-line))))))
23606 ((bound-and-true-p visual-line-mode)
23607 (let ((bol (line-beginning-position)))
23608 (end-of-visual-line)
23609 ;; If `end-of-visual-line' gets us past the ellipsis at the
23610 ;; end of a line, backtrack and use `end-of-line' instead.
23611 (when (/= bol (line-beginning-position))
23612 (goto-char bol)
23613 (end-of-line))))
23614 (t (end-of-line)))))
23616 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23617 (define-key org-mode-map "\C-e" 'org-end-of-line)
23619 (defun org-backward-sentence (&optional _arg)
23620 "Go to beginning of sentence, or beginning of table field.
23621 This will call `backward-sentence' or `org-table-beginning-of-field',
23622 depending on context."
23623 (interactive)
23624 (let* ((element (org-element-at-point))
23625 (contents-begin (org-element-property :contents-begin element))
23626 (table (org-element-lineage element '(table) t)))
23627 (if (and table
23628 (> (point) contents-begin)
23629 (<= (point) (org-element-property :contents-end table)))
23630 (call-interactively #'org-table-beginning-of-field)
23631 (save-restriction
23632 (when (and contents-begin
23633 (< (point-min) contents-begin)
23634 (> (point) contents-begin))
23635 (narrow-to-region contents-begin
23636 (org-element-property :contents-end element)))
23637 (call-interactively #'backward-sentence)))))
23639 (defun org-forward-sentence (&optional _arg)
23640 "Go to end of sentence, or end of table field.
23641 This will call `forward-sentence' or `org-table-end-of-field',
23642 depending on context."
23643 (interactive)
23644 (if (and (org-at-heading-p)
23645 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23646 (save-restriction
23647 (narrow-to-region (line-beginning-position) (line-end-position))
23648 (call-interactively #'forward-sentence))
23649 (let* ((element (org-element-at-point))
23650 (contents-end (org-element-property :contents-end element))
23651 (table (org-element-lineage element '(table) t)))
23652 (if (and table
23653 (>= (point) (org-element-property :contents-begin table))
23654 (< (point) contents-end))
23655 (call-interactively #'org-table-end-of-field)
23656 (save-restriction
23657 (when (and contents-end
23658 (> (point-max) contents-end)
23659 ;; Skip blank lines between elements.
23660 (< (org-element-property :end element)
23661 (save-excursion (goto-char contents-end)
23662 (skip-chars-forward " \r\t\n"))))
23663 (narrow-to-region (org-element-property :contents-begin element)
23664 contents-end))
23665 ;; End of heading is considered as the end of a sentence.
23666 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23667 (call-interactively #'forward-sentence)))))))
23669 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23670 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23672 (defun org-kill-line (&optional _arg)
23673 "Kill line, to tags or end of line."
23674 (interactive)
23675 (cond
23676 ((or (not org-special-ctrl-k)
23677 (bolp)
23678 (not (org-at-heading-p)))
23679 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23680 org-ctrl-k-protect-subtree
23681 (or (eq org-ctrl-k-protect-subtree 'error)
23682 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23683 (user-error "C-k aborted as it would kill a hidden subtree"))
23684 (call-interactively
23685 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23686 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23687 (kill-region (point) (match-beginning 1))
23688 (org-set-tags nil t))
23689 (t (kill-region (point) (point-at-eol)))))
23691 (define-key org-mode-map "\C-k" 'org-kill-line)
23693 (defun org-yank (&optional arg)
23694 "Yank. If the kill is a subtree, treat it specially.
23695 This command will look at the current kill and check if is a single
23696 subtree, or a series of subtrees[1]. If it passes the test, and if the
23697 cursor is at the beginning of a line or after the stars of a currently
23698 empty headline, then the yank is handled specially. How exactly depends
23699 on the value of the following variables.
23701 `org-yank-folded-subtrees'
23702 By default, this variable is non-nil, which results in
23703 subtree(s) being folded after insertion, except if doing so
23704 would swallow text after the yanked text.
23706 `org-yank-adjusted-subtrees'
23707 When non-nil (the default value is nil), the subtree will be
23708 promoted or demoted in order to fit into the local outline tree
23709 structure, which means that the level will be adjusted so that it
23710 becomes the smaller one of the two *visible* surrounding headings.
23712 Any prefix to this command will cause `yank' to be called directly with
23713 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23714 will just
23715 plainly yank the text as it is.
23717 \[1] The test checks if the first non-white line is a heading
23718 and if there are no other headings with fewer stars."
23719 (interactive "P")
23720 (org-yank-generic 'yank arg))
23722 (defun org-yank-generic (command arg)
23723 "Perform some yank-like command.
23725 This function implements the behavior described in the `org-yank'
23726 documentation. However, it has been generalized to work for any
23727 interactive command with similar behavior."
23729 ;; pretend to be command COMMAND
23730 (setq this-command command)
23732 (if arg
23733 (call-interactively command)
23735 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23736 (and (org-kill-is-subtree-p)
23737 (or (bolp)
23738 (and (looking-at "[ \t]*$")
23739 (string-match
23740 "\\`\\*+\\'"
23741 (buffer-substring (point-at-bol) (point)))))))
23742 swallowp)
23743 (cond
23744 ((and subtreep org-yank-folded-subtrees)
23745 (let ((beg (point))
23746 end)
23747 (if (and subtreep org-yank-adjusted-subtrees)
23748 (org-paste-subtree nil nil 'for-yank)
23749 (call-interactively command))
23751 (setq end (point))
23752 (goto-char beg)
23753 (when (and (bolp) subtreep
23754 (not (setq swallowp
23755 (org-yank-folding-would-swallow-text beg end))))
23756 (org-with-limited-levels
23757 (or (looking-at org-outline-regexp)
23758 (re-search-forward org-outline-regexp-bol end t))
23759 (while (and (< (point) end) (looking-at org-outline-regexp))
23760 (outline-hide-subtree)
23761 (org-cycle-show-empty-lines 'folded)
23762 (condition-case nil
23763 (outline-forward-same-level 1)
23764 (error (goto-char end))))))
23765 (when swallowp
23766 (message
23767 "Inserted text not folded because that would swallow text"))
23769 (goto-char end)
23770 (skip-chars-forward " \t\n\r")
23771 (beginning-of-line 1)
23772 (push-mark beg 'nomsg)))
23773 ((and subtreep org-yank-adjusted-subtrees)
23774 (let ((beg (point-at-bol)))
23775 (org-paste-subtree nil nil 'for-yank)
23776 (push-mark beg 'nomsg)))
23778 (call-interactively command))))))
23780 (defun org-yank-folding-would-swallow-text (beg end)
23781 "Would hide-subtree at BEG swallow any text after END?"
23782 (let (level)
23783 (org-with-limited-levels
23784 (save-excursion
23785 (goto-char beg)
23786 (when (or (looking-at org-outline-regexp)
23787 (re-search-forward org-outline-regexp-bol end t))
23788 (setq level (org-outline-level)))
23789 (goto-char end)
23790 (skip-chars-forward " \t\r\n\v\f")
23791 (not (or (eobp)
23792 (and (bolp) (looking-at-p org-outline-regexp)
23793 (<= (org-outline-level) level))))))))
23795 (define-key org-mode-map "\C-y" 'org-yank)
23797 (defun org-truely-invisible-p ()
23798 "Check if point is at a character currently not visible.
23799 This version does not only check the character property, but also
23800 `visible-mode'."
23801 (unless (bound-and-true-p visible-mode)
23802 (org-invisible-p)))
23804 (defun org-invisible-p2 ()
23805 "Check if point is at a character currently not visible.
23807 If the point is at EOL (and not at the beginning of a buffer too),
23808 move it back by one char before doing this check."
23809 (save-excursion
23810 (when (and (eolp) (not (bobp)))
23811 (backward-char 1))
23812 (org-invisible-p)))
23814 (defun org-back-to-heading (&optional invisible-ok)
23815 "Call `outline-back-to-heading', but provide a better error message."
23816 (condition-case nil
23817 (outline-back-to-heading invisible-ok)
23818 (error (error "Before first headline at position %d in buffer %s"
23819 (point) (current-buffer)))))
23821 (defun org-before-first-heading-p ()
23822 "Before first heading?"
23823 (save-excursion
23824 (end-of-line)
23825 (null (re-search-backward org-outline-regexp-bol nil t))))
23827 (defun org-at-heading-p (&optional ignored)
23828 (outline-on-heading-p t))
23830 (defun org-in-commented-heading-p (&optional no-inheritance)
23831 "Non-nil if point is under a commented heading.
23832 This function also checks ancestors of the current headline,
23833 unless optional argument NO-INHERITANCE is non-nil."
23834 (cond
23835 ((org-before-first-heading-p) nil)
23836 ((let ((headline (nth 4 (org-heading-components))))
23837 (and headline
23838 (let ((case-fold-search nil))
23839 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23840 headline)))))
23841 (no-inheritance nil)
23843 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23845 (defun org-at-comment-p nil
23846 "Is cursor in a commented line?"
23847 (save-excursion
23848 (save-match-data
23849 (beginning-of-line)
23850 (looking-at "^[ \t]*# "))))
23852 (defun org-at-drawer-p nil
23853 "Is cursor at a drawer keyword?"
23854 (save-excursion
23855 (move-beginning-of-line 1)
23856 (looking-at org-drawer-regexp)))
23858 (defun org-at-block-p nil
23859 "Is cursor at a block keyword?"
23860 (save-excursion
23861 (move-beginning-of-line 1)
23862 (looking-at org-block-regexp)))
23864 (defun org-point-at-end-of-empty-headline ()
23865 "If point is at the end of an empty headline, return t, else nil.
23866 If the heading only contains a TODO keyword, it is still still considered
23867 empty."
23868 (let ((case-fold-search nil))
23869 (and (looking-at "[ \t]*$")
23870 org-todo-line-regexp
23871 (save-excursion
23872 (beginning-of-line)
23873 (looking-at org-todo-line-regexp)
23874 (string= (match-string 3) "")))))
23876 (defun org-at-heading-or-item-p ()
23877 (or (org-at-heading-p) (org-at-item-p)))
23879 (defun org-at-target-p ()
23880 (or (org-in-regexp org-radio-target-regexp)
23881 (org-in-regexp org-target-regexp)))
23882 ;; Compatibility alias with Org versions < 7.8.03
23883 (defalias 'org-on-target-p 'org-at-target-p)
23885 (defun org-up-heading-all (arg)
23886 "Move to the heading line of which the present line is a subheading.
23887 This function considers both visible and invisible heading lines.
23888 With argument, move up ARG levels."
23889 (outline-up-heading arg t))
23891 (defun org-up-heading-safe ()
23892 "Move to the heading line of which the present line is a subheading.
23893 This version will not throw an error. It will return the level of the
23894 headline found, or nil if no higher level is found.
23896 Also, this function will be a lot faster than `outline-up-heading',
23897 because it relies on stars being the outline starters. This can really
23898 make a significant difference in outlines with very many siblings."
23899 (when (ignore-errors (org-back-to-heading t))
23900 (let ((level-up (1- (funcall outline-level))))
23901 (and (> level-up 0)
23902 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23903 (funcall outline-level)))))
23905 (defun org-first-sibling-p ()
23906 "Is this heading the first child of its parents?"
23907 (interactive)
23908 (let ((re org-outline-regexp-bol)
23909 level l)
23910 (unless (org-at-heading-p t)
23911 (user-error "Not at a heading"))
23912 (setq level (funcall outline-level))
23913 (save-excursion
23914 (if (not (re-search-backward re nil t))
23916 (setq l (funcall outline-level))
23917 (< l level)))))
23919 (defun org-goto-sibling (&optional previous)
23920 "Goto the next sibling, even if it is invisible.
23921 When PREVIOUS is set, go to the previous sibling instead. Returns t
23922 when a sibling was found. When none is found, return nil and don't
23923 move point."
23924 (let ((fun (if previous 're-search-backward 're-search-forward))
23925 (pos (point))
23926 (re org-outline-regexp-bol)
23927 level l)
23928 (when (ignore-errors (org-back-to-heading t))
23929 (setq level (funcall outline-level))
23930 (catch 'exit
23931 (or previous (forward-char 1))
23932 (while (funcall fun re nil t)
23933 (setq l (funcall outline-level))
23934 (when (< l level) (goto-char pos) (throw 'exit nil))
23935 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23936 (goto-char pos)
23937 nil))))
23939 (defun org-show-siblings ()
23940 "Show all siblings of the current headline."
23941 (save-excursion
23942 (while (org-goto-sibling) (org-flag-heading nil)))
23943 (save-excursion
23944 (while (org-goto-sibling 'previous)
23945 (org-flag-heading nil))))
23947 (defun org-goto-first-child ()
23948 "Goto the first child, even if it is invisible.
23949 Return t when a child was found. Otherwise don't move point and
23950 return nil."
23951 (let (level (pos (point)) (re org-outline-regexp-bol))
23952 (when (ignore-errors (org-back-to-heading t))
23953 (setq level (outline-level))
23954 (forward-char 1)
23955 (if (and (re-search-forward re nil t) (> (outline-level) level))
23956 (progn (goto-char (match-beginning 0)) t)
23957 (goto-char pos) nil))))
23959 (defun org-show-hidden-entry ()
23960 "Show an entry where even the heading is hidden."
23961 (save-excursion
23962 (org-show-entry)))
23964 (defun org-flag-heading (flag &optional entry)
23965 "Flag the current heading. FLAG non-nil means make invisible.
23966 When ENTRY is non-nil, show the entire entry."
23967 (save-excursion
23968 (org-back-to-heading t)
23969 ;; Check if we should show the entire entry
23970 (if entry
23971 (progn
23972 (org-show-entry)
23973 (save-excursion
23974 (and (outline-next-heading)
23975 (org-flag-heading nil))))
23976 (outline-flag-region (max (point-min) (1- (point)))
23977 (save-excursion (outline-end-of-heading) (point))
23978 flag))))
23980 (defun org-get-next-sibling ()
23981 "Move to next heading of the same level, and return point.
23982 If there is no such heading, return nil.
23983 This is like outline-next-sibling, but invisible headings are ok."
23984 (let ((level (funcall outline-level)))
23985 (outline-next-heading)
23986 (while (and (not (eobp)) (> (funcall outline-level) level))
23987 (outline-next-heading))
23988 (unless (or (eobp) (< (funcall outline-level) level))
23989 (point))))
23991 (defun org-get-last-sibling ()
23992 "Move to previous heading of the same level, and return point.
23993 If there is no such heading, return nil."
23994 (let ((opoint (point))
23995 (level (funcall outline-level)))
23996 (outline-previous-heading)
23997 (when (and (/= (point) opoint) (outline-on-heading-p t))
23998 (while (and (> (funcall outline-level) level)
23999 (not (bobp)))
24000 (outline-previous-heading))
24001 (unless (< (funcall outline-level) level)
24002 (point)))))
24004 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24005 "Goto to the end of a subtree."
24006 ;; This contains an exact copy of the original function, but it uses
24007 ;; `org-back-to-heading', to make it work also in invisible
24008 ;; trees. And is uses an invisible-ok argument.
24009 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24010 ;; Furthermore, when used inside Org, finding the end of a large subtree
24011 ;; with many children and grandchildren etc, this can be much faster
24012 ;; than the outline version.
24013 (org-back-to-heading invisible-ok)
24014 (let ((first t)
24015 (level (funcall outline-level)))
24016 (if (and (derived-mode-p 'org-mode) (< level 1000))
24017 ;; A true heading (not a plain list item), in Org
24018 ;; This means we can easily find the end by looking
24019 ;; only for the right number of stars. Using a regexp to do
24020 ;; this is so much faster than using a Lisp loop.
24021 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24022 (forward-char 1)
24023 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24024 ;; something else, do it the slow way
24025 (while (and (not (eobp))
24026 (or first (> (funcall outline-level) level)))
24027 (setq first nil)
24028 (outline-next-heading)))
24029 (unless to-heading
24030 (when (memq (preceding-char) '(?\n ?\^M))
24031 ;; Go to end of line before heading
24032 (forward-char -1)
24033 (when (memq (preceding-char) '(?\n ?\^M))
24034 ;; leave blank line before heading
24035 (forward-char -1)))))
24036 (point))
24038 (defun org-end-of-meta-data (&optional full)
24039 "Skip planning line and properties drawer in current entry.
24040 When optional argument FULL is non-nil, also skip empty lines,
24041 clocking lines and regular drawers at the beginning of the
24042 entry."
24043 (org-back-to-heading t)
24044 (forward-line)
24045 (when (looking-at-p org-planning-line-re) (forward-line))
24046 (when (looking-at org-property-drawer-re)
24047 (goto-char (match-end 0))
24048 (forward-line))
24049 (when (and full (not (org-at-heading-p)))
24050 (catch 'exit
24051 (let ((end (save-excursion (outline-next-heading) (point)))
24052 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24053 (while (not (eobp))
24054 (cond ((looking-at-p org-drawer-regexp)
24055 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24056 (forward-line)
24057 (throw 'exit t)))
24058 ((looking-at-p re) (forward-line))
24059 (t (throw 'exit t))))))))
24061 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24062 "Move forward to the ARG'th subheading at same level as this one.
24063 Stop at the first and last subheadings of a superior heading.
24064 Normally this only looks at visible headings, but when INVISIBLE-OK is
24065 non-nil it will also look at invisible ones."
24066 (interactive "p")
24067 (let ((backward? (and arg (< arg 0))))
24068 (if (org-before-first-heading-p)
24069 (if backward? (goto-char (point-min)) (outline-next-heading))
24070 (org-back-to-heading invisible-ok)
24071 (unless backward? (end-of-line)) ;do not match current headline
24072 (let ((level (- (match-end 0) (match-beginning 0) 1))
24073 (f (if backward? #'re-search-backward #'re-search-forward))
24074 (count (if arg (abs arg) 1))
24075 (result (point)))
24076 (while (and (> count 0)
24077 (funcall f org-outline-regexp-bol nil 'move))
24078 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24079 (cond ((< l level) (setq count 0))
24080 ((and (= l level)
24081 (or invisible-ok
24082 (not (org-invisible-p
24083 (line-beginning-position)))))
24084 (cl-decf count)
24085 (when (= l level) (setq result (point)))))))
24086 (goto-char result))
24087 (beginning-of-line))))
24089 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24090 "Move backward to the ARG'th subheading at same level as this one.
24091 Stop at the first and last subheadings of a superior heading."
24092 (interactive "p")
24093 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24095 (defun org-next-visible-heading (arg)
24096 "Move to the next visible heading.
24098 This function wraps `outline-next-visible-heading' with
24099 `org-with-limited-levels' in order to skip over inline tasks and
24100 respect customization of `org-odd-levels-only'."
24101 (interactive "p")
24102 (org-with-limited-levels
24103 (outline-next-visible-heading arg)))
24105 (defun org-previous-visible-heading (arg)
24106 "Move to the previous visible heading.
24108 This function wraps `outline-previous-visible-heading' with
24109 `org-with-limited-levels' in order to skip over inline tasks and
24110 respect customization of `org-odd-levels-only'."
24111 (interactive "p")
24112 (org-with-limited-levels
24113 (outline-previous-visible-heading arg)))
24115 (defun org-next-block (arg &optional backward block-regexp)
24116 "Jump to the next block.
24118 With a prefix argument ARG, jump forward ARG many blocks.
24120 When BACKWARD is non-nil, jump to the previous block.
24122 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24123 Match data is set according to this regexp when the function
24124 returns.
24126 Return point at beginning of the opening line of found block.
24127 Throw an error if no block is found."
24128 (interactive "p")
24129 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24130 (case-fold-search t)
24131 (search-fn (if backward #'re-search-backward #'re-search-forward))
24132 (count (or arg 1))
24133 (origin (point))
24134 last-element)
24135 (if backward (beginning-of-line) (end-of-line))
24136 (while (and (> count 0) (funcall search-fn re nil t))
24137 (let ((element (save-excursion
24138 (goto-char (match-beginning 0))
24139 (save-match-data (org-element-at-point)))))
24140 (when (and (memq (org-element-type element)
24141 '(center-block comment-block dynamic-block
24142 example-block export-block quote-block
24143 special-block src-block verse-block))
24144 (<= (match-beginning 0)
24145 (org-element-property :post-affiliated element)))
24146 (setq last-element element)
24147 (cl-decf count))))
24148 (if (= count 0)
24149 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24150 (save-match-data (org-show-context)))
24151 (goto-char origin)
24152 (user-error "No %s code blocks" (if backward "previous" "further")))))
24154 (defun org-previous-block (arg &optional block-regexp)
24155 "Jump to the previous block.
24156 With a prefix argument ARG, jump backward ARG many source blocks.
24157 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24158 (interactive "p")
24159 (org-next-block arg t block-regexp))
24161 (defun org-forward-paragraph ()
24162 "Move forward to beginning of next paragraph or equivalent.
24164 The function moves point to the beginning of the next visible
24165 structural element, which can be a paragraph, a table, a list
24166 item, etc. It also provides some special moves for convenience:
24168 - On an affiliated keyword, jump to the beginning of the
24169 relative element.
24170 - On an item or a footnote definition, move to the second
24171 element inside, if any.
24172 - On a table or a property drawer, jump after it.
24173 - On a verse or source block, stop after blank lines."
24174 (interactive)
24175 (unless (eobp)
24176 (let* ((deactivate-mark nil)
24177 (element (org-element-at-point))
24178 (type (org-element-type element))
24179 (post-affiliated (org-element-property :post-affiliated element))
24180 (contents-begin (org-element-property :contents-begin element))
24181 (contents-end (org-element-property :contents-end element))
24182 (end (let ((end (org-element-property :end element)) (parent element))
24183 (while (and (setq parent (org-element-property :parent parent))
24184 (= (org-element-property :contents-end parent) end))
24185 (setq end (org-element-property :end parent)))
24186 end)))
24187 (cond ((not element)
24188 (skip-chars-forward " \r\t\n")
24189 (or (eobp) (beginning-of-line)))
24190 ;; On affiliated keywords, move to element's beginning.
24191 ((< (point) post-affiliated)
24192 (goto-char post-affiliated))
24193 ;; At a table row, move to the end of the table. Similarly,
24194 ;; at a node property, move to the end of the property
24195 ;; drawer.
24196 ((memq type '(node-property table-row))
24197 (goto-char (org-element-property
24198 :end (org-element-property :parent element))))
24199 ((memq type '(property-drawer table)) (goto-char end))
24200 ;; Consider blank lines as separators in verse and source
24201 ;; blocks to ease editing.
24202 ((memq type '(src-block verse-block))
24203 (when (eq type 'src-block)
24204 (setq contents-end
24205 (save-excursion (goto-char end)
24206 (skip-chars-backward " \r\t\n")
24207 (line-beginning-position))))
24208 (beginning-of-line)
24209 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24210 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24211 (goto-char end)
24212 (skip-chars-forward " \r\t\n")
24213 (if (= (point) contents-end) (goto-char end)
24214 (beginning-of-line))))
24215 ;; With no contents, just skip element.
24216 ((not contents-begin) (goto-char end))
24217 ;; If contents are invisible, skip the element altogether.
24218 ((org-invisible-p (line-end-position))
24219 (cl-case type
24220 (headline
24221 (org-with-limited-levels (outline-next-visible-heading 1)))
24222 ;; At a plain list, make sure we move to the next item
24223 ;; instead of skipping the whole list.
24224 (plain-list (forward-char)
24225 (org-forward-paragraph))
24226 (otherwise (goto-char end))))
24227 ((>= (point) contents-end) (goto-char end))
24228 ((>= (point) contents-begin)
24229 ;; This can only happen on paragraphs and plain lists.
24230 (cl-case type
24231 (paragraph (goto-char end))
24232 ;; At a plain list, try to move to second element in
24233 ;; first item, if possible.
24234 (plain-list (end-of-line)
24235 (org-forward-paragraph))))
24236 ;; When contents start on the middle of a line (e.g. in
24237 ;; items and footnote definitions), try to reach first
24238 ;; element starting after current line.
24239 ((> (line-end-position) contents-begin)
24240 (end-of-line)
24241 (org-forward-paragraph))
24242 (t (goto-char contents-begin))))))
24244 (defun org-backward-paragraph ()
24245 "Move backward to start of previous paragraph or equivalent.
24247 The function moves point to the beginning of the current
24248 structural element, which can be a paragraph, a table, a list
24249 item, etc., or to the beginning of the previous visible one if
24250 point is already there. It also provides some special moves for
24251 convenience:
24253 - On an affiliated keyword, jump to the first one.
24254 - On a table or a property drawer, move to its beginning.
24255 - On comment, example, export, src and verse blocks, stop
24256 before blank lines."
24257 (interactive)
24258 (unless (bobp)
24259 (let* ((deactivate-mark nil)
24260 (element (org-element-at-point))
24261 (type (org-element-type element))
24262 (contents-end (org-element-property :contents-end element))
24263 (post-affiliated (org-element-property :post-affiliated element))
24264 (begin (org-element-property :begin element))
24265 (special? ;blocks handled specially
24266 (memq type '(comment-block example-block export-block src-block
24267 verse-block)))
24268 (contents-begin
24269 (if special?
24270 ;; These types have no proper contents. Fake line
24271 ;; below the block opening line as contents beginning.
24272 (save-excursion (goto-char begin) (line-beginning-position 2))
24273 (org-element-property :contents-begin element))))
24274 (cond
24275 ((not element) (goto-char (point-min)))
24276 ((= (point) begin)
24277 (backward-char)
24278 (org-backward-paragraph))
24279 ((<= (point) post-affiliated) (goto-char begin))
24280 ;; Special behavior: on a table or a property drawer, move to
24281 ;; its beginning.
24282 ((memq type '(node-property table-row))
24283 (goto-char (org-element-property
24284 :post-affiliated (org-element-property :parent element))))
24285 (special?
24286 (if (<= (point) contents-begin) (goto-char post-affiliated)
24287 ;; Inside a verse block, see blank lines as paragraph
24288 ;; separators.
24289 (let ((origin (point)))
24290 (skip-chars-backward " \r\t\n" contents-begin)
24291 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24292 (skip-chars-forward " \r\t\n" origin)
24293 (if (= (point) origin) (goto-char contents-begin)
24294 (beginning-of-line))))))
24295 ((eq type 'paragraph) (goto-char contents-begin)
24296 ;; When at first paragraph in an item or a footnote definition,
24297 ;; move directly to beginning of line.
24298 (let ((parent-contents
24299 (org-element-property
24300 :contents-begin (org-element-property :parent element))))
24301 (when (and parent-contents (= parent-contents contents-begin))
24302 (beginning-of-line))))
24303 ;; At the end of a greater element, move to the beginning of
24304 ;; the last element within.
24305 ((and contents-end (>= (point) contents-end))
24306 (goto-char (1- contents-end))
24307 (org-backward-paragraph))
24308 (t (goto-char (or post-affiliated begin))))
24309 ;; Ensure we never leave point invisible.
24310 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24312 (defun org-forward-element ()
24313 "Move forward by one element.
24314 Move to the next element at the same level, when possible."
24315 (interactive)
24316 (cond ((eobp) (user-error "Cannot move further down"))
24317 ((org-with-limited-levels (org-at-heading-p))
24318 (let ((origin (point)))
24319 (goto-char (org-end-of-subtree nil t))
24320 (unless (org-with-limited-levels (org-at-heading-p))
24321 (goto-char origin)
24322 (user-error "Cannot move further down"))))
24324 (let* ((elem (org-element-at-point))
24325 (end (org-element-property :end elem))
24326 (parent (org-element-property :parent elem)))
24327 (cond ((and parent (= (org-element-property :contents-end parent) end))
24328 (goto-char (org-element-property :end parent)))
24329 ((integer-or-marker-p end) (goto-char end))
24330 (t (message "No element at point")))))))
24332 (defun org-backward-element ()
24333 "Move backward by one element.
24334 Move to the previous element at the same level, when possible."
24335 (interactive)
24336 (cond ((bobp) (user-error "Cannot move further up"))
24337 ((org-with-limited-levels (org-at-heading-p))
24338 ;; At a headline, move to the previous one, if any, or stay
24339 ;; here.
24340 (let ((origin (point)))
24341 (org-with-limited-levels (org-backward-heading-same-level 1))
24342 ;; When current headline has no sibling above, move to its
24343 ;; parent.
24344 (when (= (point) origin)
24345 (or (org-with-limited-levels (org-up-heading-safe))
24346 (progn (goto-char origin)
24347 (user-error "Cannot move further up"))))))
24349 (let* ((elem (org-element-at-point))
24350 (beg (org-element-property :begin elem)))
24351 (cond
24352 ;; Move to beginning of current element if point isn't
24353 ;; there already.
24354 ((null beg) (message "No element at point"))
24355 ((/= (point) beg) (goto-char beg))
24356 (t (goto-char beg)
24357 (skip-chars-backward " \r\t\n")
24358 (unless (bobp)
24359 (let ((prev (org-element-at-point)))
24360 (goto-char (org-element-property :begin prev))
24361 (while (and (setq prev (org-element-property :parent prev))
24362 (<= (org-element-property :end prev) beg))
24363 (goto-char (org-element-property :begin prev)))))))))))
24365 (defun org-up-element ()
24366 "Move to upper element."
24367 (interactive)
24368 (if (org-with-limited-levels (org-at-heading-p))
24369 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24370 (let* ((elem (org-element-at-point))
24371 (parent (org-element-property :parent elem)))
24372 (if parent (goto-char (org-element-property :begin parent))
24373 (if (org-with-limited-levels (org-before-first-heading-p))
24374 (user-error "No surrounding element")
24375 (org-with-limited-levels (org-back-to-heading)))))))
24377 (defun org-down-element ()
24378 "Move to inner element."
24379 (interactive)
24380 (let ((element (org-element-at-point)))
24381 (cond
24382 ((memq (org-element-type element) '(plain-list table))
24383 (goto-char (org-element-property :contents-begin element))
24384 (forward-char))
24385 ((memq (org-element-type element) org-element-greater-elements)
24386 ;; If contents are hidden, first disclose them.
24387 (when (org-invisible-p (line-end-position)) (org-cycle))
24388 (goto-char (or (org-element-property :contents-begin element)
24389 (user-error "No content for this element"))))
24390 (t (user-error "No inner element")))))
24392 (defun org-drag-element-backward ()
24393 "Move backward element at point."
24394 (interactive)
24395 (let ((elem (or (org-element-at-point)
24396 (user-error "No element at point"))))
24397 (if (eq (org-element-type elem) 'headline)
24398 ;; Preserve point when moving a whole tree, even if point was
24399 ;; on blank lines below the headline.
24400 (let ((offset (skip-chars-backward " \t\n")))
24401 (unwind-protect (org-move-subtree-up)
24402 (forward-char (- offset))))
24403 (let ((prev-elem
24404 (save-excursion
24405 (goto-char (org-element-property :begin elem))
24406 (skip-chars-backward " \r\t\n")
24407 (unless (bobp)
24408 (let* ((beg (org-element-property :begin elem))
24409 (prev (org-element-at-point))
24410 (up prev))
24411 (while (and (setq up (org-element-property :parent up))
24412 (<= (org-element-property :end up) beg))
24413 (setq prev up))
24414 prev)))))
24415 ;; Error out if no previous element or previous element is
24416 ;; a parent of the current one.
24417 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24418 (user-error "Cannot drag element backward")
24419 (let ((pos (point)))
24420 (org-element-swap-A-B prev-elem elem)
24421 (goto-char (+ (org-element-property :begin prev-elem)
24422 (- pos (org-element-property :begin elem))))))))))
24424 (defun org-drag-element-forward ()
24425 "Move forward element at point."
24426 (interactive)
24427 (let* ((pos (point))
24428 (elem (or (org-element-at-point)
24429 (user-error "No element at point"))))
24430 (when (= (point-max) (org-element-property :end elem))
24431 (user-error "Cannot drag element forward"))
24432 (goto-char (org-element-property :end elem))
24433 (let ((next-elem (org-element-at-point)))
24434 (when (or (org-element-nested-p elem next-elem)
24435 (and (eq (org-element-type next-elem) 'headline)
24436 (not (eq (org-element-type elem) 'headline))))
24437 (goto-char pos)
24438 (user-error "Cannot drag element forward"))
24439 ;; Compute new position of point: it's shifted by NEXT-ELEM
24440 ;; body's length (without final blanks) and by the length of
24441 ;; blanks between ELEM and NEXT-ELEM.
24442 (let ((size-next (- (save-excursion
24443 (goto-char (org-element-property :end next-elem))
24444 (skip-chars-backward " \r\t\n")
24445 (forward-line)
24446 ;; Small correction if buffer doesn't end
24447 ;; with a newline character.
24448 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24449 (org-element-property :begin next-elem)))
24450 (size-blank (- (org-element-property :end elem)
24451 (save-excursion
24452 (goto-char (org-element-property :end elem))
24453 (skip-chars-backward " \r\t\n")
24454 (forward-line)
24455 (point)))))
24456 (org-element-swap-A-B elem next-elem)
24457 (goto-char (+ pos size-next size-blank))))))
24459 (defun org-drag-line-forward (arg)
24460 "Drag the line at point ARG lines forward."
24461 (interactive "p")
24462 (dotimes (_ (abs arg))
24463 (let ((c (current-column)))
24464 (if (< 0 arg)
24465 (progn
24466 (beginning-of-line 2)
24467 (transpose-lines 1)
24468 (beginning-of-line 0))
24469 (transpose-lines 1)
24470 (beginning-of-line -1))
24471 (org-move-to-column c))))
24473 (defun org-drag-line-backward (arg)
24474 "Drag the line at point ARG lines backward."
24475 (interactive "p")
24476 (org-drag-line-forward (- arg)))
24478 (defun org-mark-element ()
24479 "Put point at beginning of this element, mark at end.
24481 Interactively, if this command is repeated or (in Transient Mark
24482 mode) if the mark is active, it marks the next element after the
24483 ones already marked."
24484 (interactive)
24485 (let (deactivate-mark)
24486 (if (and (called-interactively-p 'any)
24487 (or (and (eq last-command this-command) (mark t))
24488 (and transient-mark-mode mark-active)))
24489 (set-mark
24490 (save-excursion
24491 (goto-char (mark))
24492 (goto-char (org-element-property :end (org-element-at-point)))))
24493 (let ((element (org-element-at-point)))
24494 (end-of-line)
24495 (push-mark (org-element-property :end element) t t)
24496 (goto-char (org-element-property :begin element))))))
24498 (defun org-narrow-to-element ()
24499 "Narrow buffer to current element."
24500 (interactive)
24501 (let ((elem (org-element-at-point)))
24502 (cond
24503 ((eq (car elem) 'headline)
24504 (narrow-to-region
24505 (org-element-property :begin elem)
24506 (org-element-property :end elem)))
24507 ((memq (car elem) org-element-greater-elements)
24508 (narrow-to-region
24509 (org-element-property :contents-begin elem)
24510 (org-element-property :contents-end elem)))
24512 (narrow-to-region
24513 (org-element-property :begin elem)
24514 (org-element-property :end elem))))))
24516 (defun org-transpose-element ()
24517 "Transpose current and previous elements, keeping blank lines between.
24518 Point is moved after both elements."
24519 (interactive)
24520 (org-skip-whitespace)
24521 (let ((end (org-element-property :end (org-element-at-point))))
24522 (org-drag-element-backward)
24523 (goto-char end)))
24525 (defun org-unindent-buffer ()
24526 "Un-indent the visible part of the buffer.
24527 Relative indentation (between items, inside blocks, etc.) isn't
24528 modified."
24529 (interactive)
24530 (unless (eq major-mode 'org-mode)
24531 (user-error "Cannot un-indent a buffer not in Org mode"))
24532 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24533 (unindent-tree
24534 (lambda (contents)
24535 (dolist (element (reverse contents))
24536 (if (memq (org-element-type element) '(headline section))
24537 (funcall unindent-tree (org-element-contents element))
24538 (save-excursion
24539 (save-restriction
24540 (narrow-to-region
24541 (org-element-property :begin element)
24542 (org-element-property :end element))
24543 (org-do-remove-indentation))))))))
24544 (funcall unindent-tree (org-element-contents parse-tree))))
24546 (defun org-show-children (&optional level)
24547 "Show all direct subheadings of this heading.
24548 Prefix arg LEVEL is how many levels below the current level
24549 should be shown. Default is enough to cause the following
24550 heading to appear."
24551 (interactive "p")
24552 ;; If `orgstruct-mode' is active, use the slower version.
24553 (if orgstruct-mode (call-interactively #'outline-show-children)
24554 (save-excursion
24555 (org-back-to-heading t)
24556 (let* ((current-level (funcall outline-level))
24557 (max-level (org-get-valid-level
24558 current-level
24559 (if level (prefix-numeric-value level) 1)))
24560 (end (save-excursion (org-end-of-subtree t t)))
24561 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24562 (past-first-child nil)
24563 ;; Make sure to skip inlinetasks.
24564 (re (format regexp-fmt
24565 current-level
24566 (cond
24567 ((not (featurep 'org-inlinetask)) "")
24568 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24570 (t (1- org-inlinetask-min-level))))))
24571 ;; Display parent heading.
24572 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24573 (forward-line)
24574 ;; Display children. First child may be deeper than expected
24575 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24576 ;; MAX-LEVEL accordingly.
24577 (while (re-search-forward re end t)
24578 (unless past-first-child
24579 (setq re (format regexp-fmt
24580 current-level
24581 (max (funcall outline-level) max-level)))
24582 (setq past-first-child t))
24583 (outline-flag-region
24584 (line-end-position 0) (line-end-position) nil))))))
24586 (defun org-show-subtree ()
24587 "Show everything after this heading at deeper levels."
24588 (interactive)
24589 (outline-flag-region
24590 (point)
24591 (save-excursion
24592 (org-end-of-subtree t t))
24593 nil))
24595 (defun org-show-entry ()
24596 "Show the body directly following this heading.
24597 Show the heading too, if it is currently invisible."
24598 (interactive)
24599 (save-excursion
24600 (ignore-errors
24601 (org-back-to-heading t)
24602 (outline-flag-region
24603 (max (point-min) (1- (point)))
24604 (save-excursion
24605 (if (re-search-forward
24606 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24607 (match-beginning 1)
24608 (point-max)))
24609 nil)
24610 (org-cycle-hide-drawers 'children))))
24612 (defun org-make-options-regexp (kwds &optional extra)
24613 "Make a regular expression for keyword lines.
24614 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24615 when non-nil, is a regexp matching keywords names."
24616 (concat "^[ \t]*#\\+\\("
24617 (regexp-opt kwds)
24618 (and extra (concat (and kwds "\\|") extra))
24619 "\\):[ \t]*\\(.*\\)"))
24621 ;;;; Integration with and fixes for other packages
24623 ;;; Imenu support
24625 (defvar-local org-imenu-markers nil
24626 "All markers currently used by Imenu.")
24628 (defun org-imenu-new-marker (&optional pos)
24629 "Return a new marker for use by Imenu, and remember the marker."
24630 (let ((m (make-marker)))
24631 (move-marker m (or pos (point)))
24632 (push m org-imenu-markers)
24635 (defun org-imenu-get-tree ()
24636 "Produce the index for Imenu."
24637 (dolist (x org-imenu-markers) (move-marker x nil))
24638 (setq org-imenu-markers nil)
24639 (let* ((case-fold-search nil)
24640 (n org-imenu-depth)
24641 (re (concat "^" (org-get-limited-outline-regexp)))
24642 (subs (make-vector (1+ n) nil))
24643 (last-level 0)
24644 m level head0 head)
24645 (org-with-wide-buffer
24646 (goto-char (point-max))
24647 (while (re-search-backward re nil t)
24648 (setq level (org-reduced-level (funcall outline-level)))
24649 (when (and (<= level n)
24650 (looking-at org-complex-heading-regexp)
24651 (setq head0 (match-string-no-properties 4)))
24652 (setq head (org-link-display-format head0)
24653 m (org-imenu-new-marker))
24654 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24655 (if (>= level last-level)
24656 (push (cons head m) (aref subs level))
24657 (push (cons head (aref subs (1+ level))) (aref subs level))
24658 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24659 (setq last-level level))))
24660 (aref subs 1)))
24662 (eval-after-load "imenu"
24663 '(progn
24664 (add-hook 'imenu-after-jump-hook
24665 (lambda ()
24666 (when (derived-mode-p 'org-mode)
24667 (org-show-context 'org-goto))))))
24669 (defun org-link-display-format (s)
24670 "Replace links in string S with their description.
24671 If there is no description, use the link target."
24672 (save-match-data
24673 (replace-regexp-in-string
24674 org-bracket-link-analytic-regexp
24675 (lambda (m)
24676 (if (match-end 5) (match-string 5 m)
24677 (concat (match-string 1 m) (match-string 3 m))))
24678 s nil t)))
24680 (defun org-toggle-link-display ()
24681 "Toggle the literal or descriptive display of links."
24682 (interactive)
24683 (if org-descriptive-links
24684 (progn (org-remove-from-invisibility-spec '(org-link))
24685 (org-restart-font-lock)
24686 (setq org-descriptive-links nil))
24687 (progn (add-to-invisibility-spec '(org-link))
24688 (org-restart-font-lock)
24689 (setq org-descriptive-links t))))
24691 ;; Speedbar support
24693 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24694 "Overlay marking the agenda restriction line in speedbar.")
24695 (overlay-put org-speedbar-restriction-lock-overlay
24696 'face 'org-agenda-restriction-lock)
24697 (overlay-put org-speedbar-restriction-lock-overlay
24698 'help-echo "Agendas are currently limited to this item.")
24699 (delete-overlay org-speedbar-restriction-lock-overlay)
24701 (defun org-speedbar-set-agenda-restriction ()
24702 "Restrict future agenda commands to the location at point in speedbar.
24703 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24704 (interactive)
24705 (require 'org-agenda)
24706 (let (p m tp np dir txt)
24707 (cond
24708 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24709 'org-imenu t))
24710 (setq m (get-text-property p 'org-imenu-marker))
24711 (with-current-buffer (marker-buffer m)
24712 (goto-char m)
24713 (org-agenda-set-restriction-lock 'subtree)))
24714 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24715 'speedbar-function 'speedbar-find-file))
24716 (setq tp (previous-single-property-change
24717 (1+ p) 'speedbar-function)
24718 np (next-single-property-change
24719 tp 'speedbar-function)
24720 dir (speedbar-line-directory)
24721 txt (buffer-substring-no-properties (or tp (point-min))
24722 (or np (point-max))))
24723 (with-current-buffer (find-file-noselect
24724 (let ((default-directory dir))
24725 (expand-file-name txt)))
24726 (unless (derived-mode-p 'org-mode)
24727 (user-error "Cannot restrict to non-Org mode file"))
24728 (org-agenda-set-restriction-lock 'file)))
24729 (t (user-error "Don't know how to restrict Org mode agenda")))
24730 (move-overlay org-speedbar-restriction-lock-overlay
24731 (point-at-bol) (point-at-eol))
24732 (setq current-prefix-arg nil)
24733 (org-agenda-maybe-redo)))
24735 (defvar speedbar-file-key-map)
24736 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24737 (eval-after-load "speedbar"
24738 '(progn
24739 (speedbar-add-supported-extension ".org")
24740 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24741 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24742 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24743 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24744 (add-hook 'speedbar-visiting-tag-hook
24745 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24747 ;;; Fixes and Hacks for problems with other packages
24749 (defun org--flyspell-object-check-p (element)
24750 "Non-nil when Flyspell can check object at point.
24751 ELEMENT is the element at point."
24752 (let ((object (save-excursion
24753 (when (looking-at-p "\\>") (backward-char))
24754 (org-element-context element))))
24755 (cl-case (org-element-type object)
24756 ;; Prevent checks in links due to keybinding conflict with
24757 ;; Flyspell.
24758 ((code entity export-snippet inline-babel-call
24759 inline-src-block line-break latex-fragment link macro
24760 statistics-cookie target timestamp verbatim)
24761 nil)
24762 (footnote-reference
24763 ;; Only in inline footnotes, within the definition.
24764 (and (eq (org-element-property :type object) 'inline)
24765 (< (save-excursion
24766 (goto-char (org-element-property :begin object))
24767 (search-forward ":" nil t 2))
24768 (point))))
24769 (otherwise t))))
24771 (defun org-mode-flyspell-verify ()
24772 "Function used for `flyspell-generic-check-word-predicate'."
24773 (if (org-at-heading-p)
24774 ;; At a headline or an inlinetask, check title only. This is
24775 ;; faster than relying on `org-element-at-point'.
24776 (and (save-excursion (beginning-of-line)
24777 (and (let ((case-fold-search t))
24778 (not (looking-at-p "\\*+ END[ \t]*$")))
24779 (let ((case-fold-search nil))
24780 (looking-at org-complex-heading-regexp))))
24781 (match-beginning 4)
24782 (>= (point) (match-beginning 4))
24783 (or (not (match-beginning 5))
24784 (< (point) (match-beginning 5))))
24785 (let* ((element (org-element-at-point))
24786 (post-affiliated (org-element-property :post-affiliated element)))
24787 (cond
24788 ;; Ignore checks in all affiliated keywords but captions.
24789 ((< (point) post-affiliated)
24790 (and (save-excursion
24791 (beginning-of-line)
24792 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24793 (> (point) (match-end 0))
24794 (org--flyspell-object-check-p element)))
24795 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24796 ((let ((log (org-log-into-drawer)))
24797 (and log
24798 (let ((drawer (org-element-lineage element '(drawer))))
24799 (and drawer
24800 (eq (compare-strings
24801 log nil nil
24802 (org-element-property :drawer-name drawer) nil nil t)
24803 t)))))
24804 nil)
24806 (cl-case (org-element-type element)
24807 ((comment quote-section) t)
24808 (comment-block
24809 ;; Allow checks between block markers, not on them.
24810 (and (> (line-beginning-position) post-affiliated)
24811 (save-excursion
24812 (end-of-line)
24813 (skip-chars-forward " \r\t\n")
24814 (< (point) (org-element-property :end element)))))
24815 ;; Arbitrary list of keywords where checks are meaningful.
24816 ;; Make sure point is on the value part of the element.
24817 (keyword
24818 (and (member (org-element-property :key element)
24819 '("DESCRIPTION" "TITLE"))
24820 (save-excursion
24821 (search-backward ":" (line-beginning-position) t))))
24822 ;; Check is globally allowed in paragraphs verse blocks and
24823 ;; table rows (after affiliated keywords) but some objects
24824 ;; must not be affected.
24825 ((paragraph table-row verse-block)
24826 (let ((cbeg (org-element-property :contents-begin element))
24827 (cend (org-element-property :contents-end element)))
24828 (and cbeg (>= (point) cbeg) (< (point) cend)
24829 (org--flyspell-object-check-p element))))))))))
24830 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24832 (defun org-remove-flyspell-overlays-in (beg end)
24833 "Remove flyspell overlays in region."
24834 (and (bound-and-true-p flyspell-mode)
24835 (fboundp 'flyspell-delete-region-overlays)
24836 (flyspell-delete-region-overlays beg end)))
24838 (defvar flyspell-delayed-commands)
24839 (eval-after-load "flyspell"
24840 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24842 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24843 (eval-after-load "bookmark"
24844 '(if (boundp 'bookmark-after-jump-hook)
24845 ;; We can use the hook
24846 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24847 ;; Hook not available, use advice
24848 (defadvice bookmark-jump (after org-make-visible activate)
24849 "Make the position visible."
24850 (org-bookmark-jump-unhide))))
24852 ;; Make sure saveplace shows the location if it was hidden
24853 (eval-after-load "saveplace"
24854 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24855 "Make the position visible."
24856 (org-bookmark-jump-unhide)))
24858 ;; Make sure ecb shows the location if it was hidden
24859 (eval-after-load "ecb"
24860 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24861 "Make hierarchy visible when jumping into location from ECB tree buffer."
24862 (when (derived-mode-p 'org-mode)
24863 (org-show-context))))
24865 (defun org-bookmark-jump-unhide ()
24866 "Unhide the current position, to show the bookmark location."
24867 (and (derived-mode-p 'org-mode)
24868 (or (org-invisible-p)
24869 (save-excursion (goto-char (max (point-min) (1- (point))))
24870 (org-invisible-p)))
24871 (org-show-context 'bookmark-jump)))
24873 (defun org-mark-jump-unhide ()
24874 "Make the point visible with `org-show-context' after jumping to the mark."
24875 (when (and (derived-mode-p 'org-mode)
24876 (org-invisible-p))
24877 (org-show-context 'mark-goto)))
24879 (eval-after-load "simple"
24880 '(defadvice pop-to-mark-command (after org-make-visible activate)
24881 "Make the point visible with `org-show-context'."
24882 (org-mark-jump-unhide)))
24884 (eval-after-load "simple"
24885 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24886 "Make the point visible with `org-show-context'."
24887 (org-mark-jump-unhide)))
24889 (eval-after-load "simple"
24890 '(defadvice pop-global-mark (after org-make-visible activate)
24891 "Make the point visible with `org-show-context'."
24892 (org-mark-jump-unhide)))
24894 ;; Make session.el ignore our circular variable
24895 (defvar session-globals-exclude)
24896 (eval-after-load "session"
24897 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24899 ;;;; Finish up
24901 (provide 'org)
24903 (run-hooks 'org-load-hook)
24905 ;;; org.el ends here