Small fix to emphasis fontification
[org-mode/org-tableheadings.git] / lisp / org.el
blobc2e530126bb78f684a9f05da32e909ce2aa1f6dd
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-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp) ;Silence byte-compiler
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s &optional keep-lead)
196 "Remove whitespace at the beginning and the end of string S.
197 When optional argument KEEP-LEAD is non-nil, removing blank lines
198 at the beginning of the string does not affect leading indentation."
199 (replace-regexp-in-string
200 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
201 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
203 ;; load languages based on value of `org-babel-load-languages'
204 (defvar org-babel-load-languages)
206 ;;;###autoload
207 (defun org-babel-do-load-languages (sym value)
208 "Load the languages defined in `org-babel-load-languages'."
209 (set-default sym value)
210 (dolist (pair org-babel-load-languages)
211 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
212 (if active
213 (require (intern (concat "ob-" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the Org file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 ;; Tangle-file traversal returns reversed list of tangled files
239 ;; and we want to evaluate the first target.
240 (setq exported-file
241 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
242 (message "%s %s"
243 (if compile
244 (progn (byte-compile-file exported-file 'load)
245 "Compiled and loaded")
246 (progn (load-file exported-file) "Loaded"))
247 exported-file)))
249 (defcustom org-babel-load-languages '((emacs-lisp . t))
250 "Languages which can be evaluated in Org buffers.
251 This list can be used to load support for any of the languages
252 below, note that each language will depend on a different set of
253 system executables and/or Emacs modes. When a language is
254 \"loaded\", then code blocks in that language can be evaluated
255 with `org-babel-execute-src-block' bound by default to C-c
256 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
257 be set to remove code block evaluation from the C-c C-c
258 keybinding. By default only Emacs Lisp (which has no
259 requirements) is loaded."
260 :group 'org-babel
261 :set 'org-babel-do-load-languages
262 :version "24.1"
263 :type '(alist :tag "Babel Languages"
264 :key-type
265 (choice
266 (const :tag "Awk" awk)
267 (const :tag "C" C)
268 (const :tag "R" R)
269 (const :tag "Asymptote" asymptote)
270 (const :tag "Calc" calc)
271 (const :tag "Clojure" clojure)
272 (const :tag "CSS" css)
273 (const :tag "Ditaa" ditaa)
274 (const :tag "Dot" dot)
275 (const :tag "Ebnf2ps" ebnf2ps)
276 (const :tag "Emacs Lisp" emacs-lisp)
277 (const :tag "Forth" forth)
278 (const :tag "Fortran" fortran)
279 (const :tag "Gnuplot" gnuplot)
280 (const :tag "Haskell" haskell)
281 (const :tag "hledger" hledger)
282 (const :tag "IO" io)
283 (const :tag "J" J)
284 (const :tag "Java" java)
285 (const :tag "Javascript" js)
286 (const :tag "LaTeX" latex)
287 (const :tag "Ledger" ledger)
288 (const :tag "Lilypond" lilypond)
289 (const :tag "Lisp" lisp)
290 (const :tag "Makefile" makefile)
291 (const :tag "Maxima" maxima)
292 (const :tag "Matlab" matlab)
293 (const :tag "Mscgen" mscgen)
294 (const :tag "Ocaml" ocaml)
295 (const :tag "Octave" octave)
296 (const :tag "Org" org)
297 (const :tag "Perl" perl)
298 (const :tag "Pico Lisp" picolisp)
299 (const :tag "PlantUML" plantuml)
300 (const :tag "Python" python)
301 (const :tag "Ruby" ruby)
302 (const :tag "Sass" sass)
303 (const :tag "Scala" scala)
304 (const :tag "Scheme" scheme)
305 (const :tag "Screen" screen)
306 (const :tag "Shell Script" shell)
307 (const :tag "Shen" shen)
308 (const :tag "Sql" sql)
309 (const :tag "Sqlite" sqlite)
310 (const :tag "Stan" stan)
311 (const :tag "Vala" vala))
312 :value-type (boolean :tag "Activate" :value t)))
314 ;;;; Customization variables
315 (defcustom org-clone-delete-id nil
316 "Remove ID property of clones of a subtree.
317 When non-nil, clones of a subtree don't inherit the ID property.
318 Otherwise they inherit the ID property with a new unique
319 identifier."
320 :type 'boolean
321 :version "24.1"
322 :group 'org-id)
324 ;;; Version
325 (org-check-version)
327 ;;;###autoload
328 (defun org-version (&optional here full message)
329 "Show the Org version.
330 Interactively, or when MESSAGE is non-nil, show it in echo area.
331 With prefix argument, or when HERE is non-nil, insert it at point.
332 In non-interactive uses, a reduced version string is output unless
333 FULL is given."
334 (interactive (list current-prefix-arg t (not current-prefix-arg)))
335 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
336 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
337 (load-suffixes (list ".el"))
338 (org-install-dir
339 (ignore-errors (org-find-library-dir "org-loaddefs"))))
340 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
341 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
342 (let* ((load-suffixes save-load-suffixes)
343 (release (org-release))
344 (git-version (org-git-version))
345 (version (format "Org mode version %s (%s @ %s)"
346 release
347 git-version
348 (if org-install-dir
349 (if (string= org-dir org-install-dir)
350 org-install-dir
351 (concat "mixed installation! "
352 org-install-dir
353 " and "
354 org-dir))
355 "org-loaddefs.el can not be found!")))
356 (version1 (if full version release)))
357 (when here (insert version1))
358 (when message (message "%s" version1))
359 version1)))
361 (defconst org-version (org-version))
364 ;;; Syntax Constants
366 ;;;; Block
368 (defconst org-block-regexp
369 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
370 "Regular expression for hiding blocks.")
372 (defconst org-dblock-start-re
373 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
374 "Matches the start line of a dynamic block, with parameters.")
376 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
377 "Matches the end of a dynamic block.")
379 ;;;; Clock and Planning
381 (defconst org-clock-string "CLOCK:"
382 "String used as prefix for timestamps clocking work hours on an item.")
384 (defvar org-closed-string "CLOSED:"
385 "String used as the prefix for timestamps logging closing a TODO entry.")
387 (defvar org-deadline-string "DEADLINE:"
388 "String to mark deadline entries.
389 \\<org-mode-map>
390 A deadline is this string, followed by a time stamp. It must be
391 a word, terminated by a colon. You can insert a schedule keyword
392 and a timestamp with `\\[org-deadline]'.")
394 (defvar org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 \\<org-mode-map>
397 A schedule is this string, followed by a time stamp. It must be
398 a word, terminated by a colon. You can insert a schedule keyword
399 and a timestamp with `\\[org-schedule]'.")
401 (defconst org-ds-keyword-length
402 (+ 2
403 (apply #'max
404 (mapcar #'length
405 (list org-deadline-string org-scheduled-string
406 org-clock-string org-closed-string))))
407 "Maximum length of the DEADLINE and SCHEDULED keywords.")
409 (defconst org-planning-line-re
410 (concat "^[ \t]*"
411 (regexp-opt
412 (list org-closed-string org-deadline-string org-scheduled-string)
414 "Matches a line with planning info.
415 Matched keyword is in group 1.")
417 (defconst org-clock-line-re
418 (concat "^[ \t]*" org-clock-string)
419 "Matches a line with clock info.")
421 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
422 "Matches the DEADLINE keyword.")
424 (defconst org-deadline-time-regexp
425 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
426 "Matches the DEADLINE keyword together with a time stamp.")
428 (defconst org-deadline-time-hour-regexp
429 (concat "\\<" org-deadline-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
433 (defconst org-deadline-line-regexp
434 (concat "\\<\\(" org-deadline-string "\\).*")
435 "Matches the DEADLINE keyword and the rest of the line.")
437 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
438 "Matches the SCHEDULED keyword.")
440 (defconst org-scheduled-time-regexp
441 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
442 "Matches the SCHEDULED keyword together with a time stamp.")
444 (defconst org-scheduled-time-hour-regexp
445 (concat "\\<" org-scheduled-string
446 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
447 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
449 (defconst org-closed-time-regexp
450 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
451 "Matches the CLOSED keyword together with a time stamp.")
453 (defconst org-keyword-time-regexp
454 (concat "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string
457 org-clock-string)
459 " *[[<]\\([^]>]+\\)[]>]")
460 "Matches any of the 4 keywords, together with the time stamp.")
462 (defconst org-keyword-time-not-clock-regexp
463 (concat
464 "\\<"
465 (regexp-opt
466 (list org-scheduled-string org-deadline-string org-closed-string) t)
467 " *[[<]\\([^]>]+\\)[]>]")
468 "Matches any of the 3 keywords, together with the time stamp.")
470 (defconst org-maybe-keyword-time-regexp
471 (concat "\\(\\<"
472 (regexp-opt
473 (list org-scheduled-string org-deadline-string org-closed-string
474 org-clock-string)
476 "\\)?"
477 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
478 "\\|"
479 "<%%([^\r\n>]*>\\)")
480 "Matches a timestamp, possibly preceded by a keyword.")
482 (defconst org-all-time-keywords
483 (mapcar (lambda (w) (substring w 0 -1))
484 (list org-scheduled-string org-deadline-string
485 org-clock-string org-closed-string))
486 "List of time keywords.")
488 ;;;; Drawer
490 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
491 "Matches first or last line of a hidden block.
492 Group 1 contains drawer's name or \"END\".")
494 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
495 "Regular expression matching the first line of a property drawer.")
497 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
498 "Regular expression matching the last line of a property drawer.")
500 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
501 "Regular expression matching the first line of a clock drawer.")
503 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
504 "Regular expression matching the last line of a clock drawer.")
506 (defconst org-property-drawer-re
507 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
508 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
509 "[ \t]*:END:[ \t]*$")
510 "Matches an entire property drawer.")
512 (defconst org-clock-drawer-re
513 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
514 org-clock-drawer-end-re "\\)\n?")
515 "Matches an entire clock drawer.")
517 ;;;; Headline
519 (defconst org-heading-keyword-regexp-format
520 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
521 "Printf format for a regexp matching a headline with some keyword.
522 This regexp will match the headline of any node which has the
523 exact keyword that is put into the format. The keyword isn't in
524 any group by default, but the stars and the body are.")
526 (defconst org-heading-keyword-maybe-regexp-format
527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
528 "Printf format for a regexp matching a headline, possibly with some keyword.
529 This regexp can match any headline with the specified keyword, or
530 without a keyword. The keyword isn't in any group by default,
531 but the stars and the body are.")
533 (defconst org-archive-tag "ARCHIVE"
534 "The tag that marks a subtree as archived.
535 An archived subtree does not open during visibility cycling, and does
536 not contribute to the agenda listings.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "24.4"
703 :package-version '(Org . "8.0")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
724 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
725 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
726 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
727 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
728 (const :tag "C collector: Collect properties into tables" org-collector)
729 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
730 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
731 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
732 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
733 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
734 (const :tag "C eval: Include command output as text" org-eval)
735 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
736 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
737 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
738 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
739 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
740 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
741 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
742 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
743 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
744 (const :tag "C man: Support for links to manpages in Org mode" org-man)
745 (const :tag "C mew: Links to Mew folders/messages" org-mew)
746 (const :tag "C mtags: Support for muse-like tags" org-mtags)
747 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
748 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
749 (const :tag "C registry: A registry for Org links" org-registry)
750 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
751 (const :tag "C secretary: Team management with org-mode" org-secretary)
752 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
753 (const :tag "C toc: Table of contents for Org buffer" org-toc)
754 (const :tag "C track: Keep up with Org mode development" org-track)
755 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
756 (const :tag "C vm: Links to VM folders/messages" org-vm)
757 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
758 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
759 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
761 (defvar org-export-registered-backends) ; From ox.el.
762 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
763 (declare-function org-export-backend-name "ox" (backend) t)
764 (defcustom org-export-backends '(ascii html icalendar latex odt)
765 "List of export back-ends that should be always available.
767 If a description starts with <C>, the file is not part of Emacs
768 and loading it will require that you have downloaded and properly
769 installed the Org mode distribution.
771 Unlike to `org-modules', libraries in this list will not be
772 loaded along with Org, but only once the export framework is
773 needed.
775 This variable needs to be set before org.el is loaded. If you
776 need to make a change while Emacs is running, use the customize
777 interface or run the following code, where VAL stands for the new
778 value of the variable, after updating it:
780 (progn
781 (setq org-export-registered-backends
782 (cl-remove-if-not
783 (lambda (backend)
784 (let ((name (org-export-backend-name backend)))
785 (or (memq name val)
786 (catch \\='parentp
787 (dolist (b val)
788 (and (org-export-derived-backend-p b name)
789 (throw \\='parentp t)))))))
790 org-export-registered-backends))
791 (let ((new-list (mapcar #\\='org-export-backend-name
792 org-export-registered-backends)))
793 (dolist (backend val)
794 (cond
795 ((not (load (format \"ox-%s\" backend) t t))
796 (message \"Problems while trying to load export back-end \\=`%s\\='\"
797 backend))
798 ((not (memq backend new-list)) (push backend new-list))))
799 (set-default \\='org-export-backends new-list)))
801 Adding a back-end to this list will also pull the back-end it
802 depends on, if any."
803 :group 'org
804 :group 'org-export
805 :version "26.1"
806 :package-version '(Org . "9.0")
807 :initialize 'custom-initialize-set
808 :set (lambda (var val)
809 (if (not (featurep 'ox)) (set-default var val)
810 ;; Any back-end not required anymore (not present in VAL and not
811 ;; a parent of any back-end in the new value) is removed from the
812 ;; list of registered back-ends.
813 (setq org-export-registered-backends
814 (cl-remove-if-not
815 (lambda (backend)
816 (let ((name (org-export-backend-name backend)))
817 (or (memq name val)
818 (catch 'parentp
819 (dolist (b val)
820 (and (org-export-derived-backend-p b name)
821 (throw 'parentp t)))))))
822 org-export-registered-backends))
823 ;; Now build NEW-LIST of both new back-ends and required
824 ;; parents.
825 (let ((new-list (mapcar #'org-export-backend-name
826 org-export-registered-backends)))
827 (dolist (backend val)
828 (cond
829 ((not (load (format "ox-%s" backend) t t))
830 (message "Problems while trying to load export back-end `%s'"
831 backend))
832 ((not (memq backend new-list)) (push backend new-list))))
833 ;; Set VAR to that list with fixed dependencies.
834 (set-default var new-list))))
835 :type '(set :greedy t
836 (const :tag " ascii Export buffer to ASCII format" ascii)
837 (const :tag " beamer Export buffer to Beamer presentation" beamer)
838 (const :tag " html Export buffer to HTML format" html)
839 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
840 (const :tag " latex Export buffer to LaTeX format" latex)
841 (const :tag " man Export buffer to MAN format" man)
842 (const :tag " md Export buffer to Markdown format" md)
843 (const :tag " odt Export buffer to ODT format" odt)
844 (const :tag " org Export buffer to Org format" org)
845 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
846 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
847 (const :tag "C deck Export buffer to deck.js presentations" deck)
848 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
849 (const :tag "C groff Export buffer to Groff format" groff)
850 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
851 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
852 (const :tag "C s5 Export buffer to s5 presentations" s5)
853 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
855 (eval-after-load 'ox
856 '(dolist (backend org-export-backends)
857 (condition-case nil (require (intern (format "ox-%s" backend)))
858 (error (message "Problems while trying to load export back-end `%s'"
859 backend)))))
861 (defcustom org-support-shift-select nil
862 "Non-nil means make shift-cursor commands select text when possible.
863 \\<org-mode-map>\
865 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
866 start selecting a region, or enlarge regions started in this way.
867 In Org mode, in special contexts, these same keys are used for
868 other purposes, important enough to compete with shift selection.
869 Org tries to balance these needs by supporting `shift-select-mode'
870 outside these special contexts, under control of this variable.
872 The default of this variable is nil, to avoid confusing behavior. Shifted
873 cursor keys will then execute Org commands in the following contexts:
874 - on a headline, changing TODO state (left/right) and priority (up/down)
875 - on a time stamp, changing the time
876 - in a plain list item, changing the bullet type
877 - in a property definition line, switching between allowed values
878 - in the BEGIN line of a clock table (changing the time block).
879 Outside these contexts, the commands will throw an error.
881 When this variable is t and the cursor is not in a special
882 context, Org mode will support shift-selection for making and
883 enlarging regions. To make this more effective, the bullet
884 cycling will no longer happen anywhere in an item line, but only
885 if the cursor is exactly on the bullet.
887 If you set this variable to the symbol `always', then the keys
888 will not be special in headlines, property lines, and item lines,
889 to make shift selection work there as well. If this is what you
890 want, you can use the following alternative commands:
891 `\\[org-todo]' and `\\[org-priority]' \
892 to change TODO state and priority,
893 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
894 can be used to switch TODO sets,
895 `\\[org-ctrl-c-minus]' to cycle item bullet types,
896 and properties can be edited by hand or in column view.
898 However, when the cursor is on a timestamp, shift-cursor commands
899 will still edit the time stamp - this is just too good to give up."
900 :group 'org
901 :type '(choice
902 (const :tag "Never" nil)
903 (const :tag "When outside special context" t)
904 (const :tag "Everywhere except timestamps" always)))
906 (defcustom org-loop-over-headlines-in-active-region nil
907 "Shall some commands act upon headlines in the active region?
909 When set to t, some commands will be performed in all headlines
910 within the active region.
912 When set to `start-level', some commands will be performed in all
913 headlines within the active region, provided that these headlines
914 are of the same level than the first one.
916 When set to a string, those commands will be performed on the
917 matching headlines within the active region. Such string must be
918 a tags/property/todo match as it is used in the agenda tags view.
920 The list of commands is: `org-schedule', `org-deadline',
921 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
922 `org-archive-to-archive-sibling'. The archiving commands skip
923 already archived entries."
924 :type '(choice (const :tag "Don't loop" nil)
925 (const :tag "All headlines in active region" t)
926 (const :tag "In active region, headlines at the same level than the first one" start-level)
927 (string :tag "Tags/Property/Todo matcher"))
928 :version "24.1"
929 :group 'org-todo
930 :group 'org-archive)
932 (defgroup org-startup nil
933 "Options concerning startup of Org mode."
934 :tag "Org Startup"
935 :group 'org)
937 (defcustom org-startup-folded t
938 "Non-nil means entering Org mode will switch to OVERVIEW.
940 This can also be configured on a per-file basis by adding one of
941 the following lines anywhere in the buffer:
943 #+STARTUP: fold (or `overview', this is equivalent)
944 #+STARTUP: nofold (or `showall', this is equivalent)
945 #+STARTUP: content
946 #+STARTUP: showeverything
948 Set `org-agenda-inhibit-startup' to a non-nil value if you want
949 to ignore this option when Org opens agenda files for the first
950 time."
951 :group 'org-startup
952 :type '(choice
953 (const :tag "nofold: show all" nil)
954 (const :tag "fold: overview" t)
955 (const :tag "content: all headlines" content)
956 (const :tag "show everything, even drawers" showeverything)))
958 (defcustom org-startup-truncated t
959 "Non-nil means entering Org mode will set `truncate-lines'.
960 This is useful since some lines containing links can be very long and
961 uninteresting. Also tables look terrible when wrapped.
963 The variable `org-startup-truncated' allows to configure
964 truncation for Org mode different to the other modes that use the
965 variable `truncate-lines' and as a shortcut instead of putting
966 the variable `truncate-lines' into the `org-mode-hook'. If one
967 wants to configure truncation for Org mode not statically but
968 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
969 the variable `truncate-lines' has to be used because in such a
970 case it is too late to set the variable `org-startup-truncated'."
971 :group 'org-startup
972 :type 'boolean)
974 (defcustom org-startup-indented nil
975 "Non-nil means turn on `org-indent-mode' on startup.
976 This can also be configured on a per-file basis by adding one of
977 the following lines anywhere in the buffer:
979 #+STARTUP: indent
980 #+STARTUP: noindent"
981 :group 'org-structure
982 :type '(choice
983 (const :tag "Not" nil)
984 (const :tag "Globally (slow on startup in large files)" t)))
986 (defcustom org-use-sub-superscripts t
987 "Non-nil means interpret \"_\" and \"^\" for display.
989 If you want to control how Org exports those characters, see
990 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
991 used to be an alias for `org-export-with-sub-superscripts' in
992 Org <8.0, it is not anymore.
994 When this option is turned on, you can use TeX-like syntax for
995 sub- and superscripts within the buffer. Several characters after
996 \"_\" or \"^\" will be considered as a single item - so grouping
997 with {} is normally not needed. For example, the following things
998 will be parsed as single sub- or superscripts:
1000 10^24 or 10^tau several digits will be considered 1 item.
1001 10^-12 or 10^-tau a leading sign with digits or a word
1002 x^2-y^3 will be read as x^2 - y^3, because items are
1003 terminated by almost any nonword/nondigit char.
1004 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1006 Still, ambiguity is possible. So when in doubt, use {} to enclose
1007 the sub/superscript. If you set this variable to the symbol `{}',
1008 the braces are *required* in order to trigger interpretations as
1009 sub/superscript. This can be helpful in documents that need \"_\"
1010 frequently in plain text."
1011 :group 'org-startup
1012 :version "24.4"
1013 :package-version '(Org . "8.0")
1014 :type '(choice
1015 (const :tag "Always interpret" t)
1016 (const :tag "Only with braces" {})
1017 (const :tag "Never interpret" nil)))
1019 (defcustom org-startup-with-beamer-mode nil
1020 "Non-nil means turn on `org-beamer-mode' on startup.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1024 #+STARTUP: beamer"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-align-all-tables nil
1030 "Non-nil means align all tables when visiting a file.
1031 This is useful when the column width in tables is forced with <N> cookies
1032 in table fields. Such tables will look correct only after the first re-align.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: align
1036 #+STARTUP: noalign"
1037 :group 'org-startup
1038 :type 'boolean)
1040 (defcustom org-startup-with-inline-images nil
1041 "Non-nil means show inline images when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: inlineimages
1045 #+STARTUP: noinlineimages"
1046 :group 'org-startup
1047 :version "24.1"
1048 :type 'boolean)
1050 (defcustom org-startup-with-latex-preview nil
1051 "Non-nil means preview LaTeX fragments when loading a new Org file.
1053 This can also be configured on a per-file basis by adding one of
1054 the following lines anywhere in the buffer:
1055 #+STARTUP: latexpreview
1056 #+STARTUP: nolatexpreview"
1057 :group 'org-startup
1058 :version "24.4"
1059 :package-version '(Org . "8.0")
1060 :type 'boolean)
1062 (defcustom org-insert-mode-line-in-empty-file nil
1063 "Non-nil means insert the first line setting Org mode in empty files.
1064 When the function `org-mode' is called interactively in an empty file, this
1065 normally means that the file name does not automatically trigger Org mode.
1066 To ensure that the file will always be in Org mode in the future, a
1067 line enforcing Org mode will be inserted into the buffer, if this option
1068 has been set."
1069 :group 'org-startup
1070 :type 'boolean)
1072 (defcustom org-replace-disputed-keys nil
1073 "Non-nil means use alternative key bindings for some keys.
1074 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1075 These keys are also used by other packages like shift-selection-mode'
1076 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1077 If you want to use Org mode together with one of these other modes,
1078 or more generally if you would like to move some Org mode commands to
1079 other keys, set this variable and configure the keys with the variable
1080 `org-disputed-keys'.
1082 This option is only relevant at load-time of Org mode, and must be set
1083 *before* org.el is loaded. Changing it requires a restart of Emacs to
1084 become effective."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defcustom org-use-extra-keys nil
1089 "Non-nil means use extra key sequence definitions for certain commands.
1090 This happens automatically if `window-system' is nil. This
1091 variable lets you do the same manually. You must set it before
1092 loading Org."
1093 :group 'org-startup
1094 :type 'boolean)
1096 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1098 (defcustom org-disputed-keys
1099 '(([(shift up)] . [(meta p)])
1100 ([(shift down)] . [(meta n)])
1101 ([(shift left)] . [(meta -)])
1102 ([(shift right)] . [(meta +)])
1103 ([(control shift right)] . [(meta shift +)])
1104 ([(control shift left)] . [(meta shift -)]))
1105 "Keys for which Org mode and other modes compete.
1106 This is an alist, cars are the default keys, second element specifies
1107 the alternative to use when `org-replace-disputed-keys' is t.
1109 Keys can be specified in any syntax supported by `define-key'.
1110 The value of this option takes effect only at Org mode startup,
1111 therefore you'll have to restart Emacs to apply it after changing."
1112 :group 'org-startup
1113 :type 'alist)
1115 (defun org-key (key)
1116 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1117 Or return the original if not disputed."
1118 (when org-replace-disputed-keys
1119 (let* ((nkey (key-description key))
1120 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1121 org-disputed-keys)))
1122 (setq key (if x (cdr x) key))))
1123 key)
1125 (defun org-defkey (keymap key def)
1126 "Define a key, possibly translated, as returned by `org-key'."
1127 (define-key keymap (org-key key) def))
1129 (defcustom org-ellipsis nil
1130 "The ellipsis to use in the Org mode outline.
1132 When nil, just use the standard three dots. When a non-empty string,
1133 use that string instead.
1135 The change affects only Org mode (which will then use its own display table).
1136 Changing this requires executing `\\[org-mode]' in a buffer to become
1137 effective."
1138 :group 'org-startup
1139 :type '(choice (const :tag "Default" nil)
1140 (string :tag "String" :value "...#"))
1141 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1143 (defvar org-display-table nil
1144 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1146 (defgroup org-keywords nil
1147 "Keywords in Org mode."
1148 :tag "Org Keywords"
1149 :group 'org)
1151 (defcustom org-closed-keep-when-no-todo nil
1152 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1153 :group 'org-todo
1154 :group 'org-keywords
1155 :version "24.4"
1156 :package-version '(Org . "8.0")
1157 :type 'boolean)
1159 (defgroup org-structure nil
1160 "Options concerning the general structure of Org files."
1161 :tag "Org Structure"
1162 :group 'org)
1164 (defgroup org-reveal-location nil
1165 "Options about how to make context of a location visible."
1166 :tag "Org Reveal Location"
1167 :group 'org-structure)
1169 (defcustom org-show-context-detail '((agenda . local)
1170 (bookmark-jump . lineage)
1171 (isearch . lineage)
1172 (default . ancestors))
1173 "Alist between context and visibility span when revealing a location.
1175 \\<org-mode-map>Some actions may move point into invisible
1176 locations. As a consequence, Org always expose a neighborhood
1177 around point. How much is shown depends on the initial action,
1178 or context. Valid contexts are
1180 agenda when exposing an entry from the agenda
1181 org-goto when using the command `org-goto' (`\\[org-goto]')
1182 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1183 tags-tree when constructing a sparse tree based on tags matches
1184 link-search when exposing search matches associated with a link
1185 mark-goto when exposing the jump goal of a mark
1186 bookmark-jump when exposing a bookmark location
1187 isearch when exiting from an incremental search
1188 default default for all contexts not set explicitly
1190 Allowed visibility spans are
1192 minimal show current headline; if point is not on headline,
1193 also show entry
1195 local show current headline, entry and next headline
1197 ancestors show current headline and its direct ancestors; if
1198 point is not on headline, also show entry
1200 lineage show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and first child
1204 tree show current headline, its direct ancestors and all
1205 their children; if point is not on headline, also show
1206 entry and all children
1208 canonical show current headline, its direct ancestors along with
1209 their entries and children; if point is not located on
1210 the headline, also show current entry and all children
1212 As special cases, a nil or t value means show all contexts in
1213 `minimal' or `canonical' view, respectively.
1215 Some views can make displayed information very compact, but also
1216 make it harder to edit the location of the match. In such
1217 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1218 more context."
1219 :group 'org-reveal-location
1220 :version "26.1"
1221 :package-version '(Org . "9.0")
1222 :type '(choice
1223 (const :tag "Canonical" t)
1224 (const :tag "Minimal" nil)
1225 (repeat :greedy t :tag "Individual contexts"
1226 (cons
1227 (choice :tag "Context"
1228 (const agenda)
1229 (const org-goto)
1230 (const occur-tree)
1231 (const tags-tree)
1232 (const link-search)
1233 (const mark-goto)
1234 (const bookmark-jump)
1235 (const isearch)
1236 (const default))
1237 (choice :tag "Detail level"
1238 (const minimal)
1239 (const local)
1240 (const ancestors)
1241 (const lineage)
1242 (const tree)
1243 (const canonical))))))
1245 (defcustom org-indirect-buffer-display 'other-window
1246 "How should indirect tree buffers be displayed?
1248 This applies to indirect buffers created with the commands
1249 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1251 Valid values are:
1252 current-window Display in the current window
1253 other-window Just display in another window.
1254 dedicated-frame Create one new frame, and re-use it each time.
1255 new-frame Make a new frame each time. Note that in this case
1256 previously-made indirect buffers are kept, and you need to
1257 kill these buffers yourself."
1258 :group 'org-structure
1259 :group 'org-agenda-windows
1260 :type '(choice
1261 (const :tag "In current window" current-window)
1262 (const :tag "In current frame, other window" other-window)
1263 (const :tag "Each time a new frame" new-frame)
1264 (const :tag "One dedicated frame" dedicated-frame)))
1266 (defcustom org-use-speed-commands nil
1267 "Non-nil means activate single letter commands at beginning of a headline.
1268 This may also be a function to test for appropriate locations where speed
1269 commands should be active.
1271 For example, to activate speed commands when the point is on any
1272 star at the beginning of the headline, you can do this:
1274 (setq org-use-speed-commands
1275 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1276 :group 'org-structure
1277 :type '(choice
1278 (const :tag "Never" nil)
1279 (const :tag "At beginning of headline stars" t)
1280 (function)))
1282 (defcustom org-speed-commands-user nil
1283 "Alist of additional speed commands.
1284 This list will be checked before `org-speed-commands-default'
1285 when the variable `org-use-speed-commands' is non-nil
1286 and when the cursor is at the beginning of a headline.
1287 The car of each entry is a string with a single letter, which must
1288 be assigned to `self-insert-command' in the global map.
1289 The cdr is either a command to be called interactively, a function
1290 to be called, or a form to be evaluated.
1291 An entry that is just a list with a single string will be interpreted
1292 as a descriptive headline that will be added when listing the speed
1293 commands in the Help buffer using the `?' speed command."
1294 :group 'org-structure
1295 :type '(repeat :value ("k" . ignore)
1296 (choice :value ("k" . ignore)
1297 (list :tag "Descriptive Headline" (string :tag "Headline"))
1298 (cons :tag "Letter and Command"
1299 (string :tag "Command letter")
1300 (choice
1301 (function)
1302 (sexp))))))
1304 (defcustom org-bookmark-names-plist
1305 '(:last-capture "org-capture-last-stored"
1306 :last-refile "org-refile-last-stored"
1307 :last-capture-marker "org-capture-last-stored-marker")
1308 "Names for bookmarks automatically set by some Org commands.
1309 This can provide strings as names for a number of bookmarks Org sets
1310 automatically. The following keys are currently implemented:
1311 :last-capture
1312 :last-capture-marker
1313 :last-refile
1314 When a key does not show up in the property list, the corresponding bookmark
1315 is not set."
1316 :group 'org-structure
1317 :type 'plist)
1319 (defgroup org-cycle nil
1320 "Options concerning visibility cycling in Org mode."
1321 :tag "Org Cycle"
1322 :group 'org-structure)
1324 (defcustom org-cycle-skip-children-state-if-no-children t
1325 "Non-nil means skip CHILDREN state in entries that don't have any."
1326 :group 'org-cycle
1327 :type 'boolean)
1329 (defcustom org-cycle-max-level nil
1330 "Maximum level which should still be subject to visibility cycling.
1331 Levels higher than this will, for cycling, be treated as text, not a headline.
1332 When `org-odd-levels-only' is set, a value of N in this variable actually
1333 means 2N-1 stars as the limiting headline.
1334 When nil, cycle all levels.
1335 Note that the limiting level of cycling is also influenced by
1336 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1337 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1338 than its value."
1339 :group 'org-cycle
1340 :type '(choice
1341 (const :tag "No limit" nil)
1342 (integer :tag "Maximum level")))
1344 (defcustom org-hide-block-startup nil
1345 "Non-nil means entering Org mode will fold all blocks.
1346 This can also be set in on a per-file basis with
1348 #+STARTUP: hideblocks
1349 #+STARTUP: showblocks"
1350 :group 'org-startup
1351 :group 'org-cycle
1352 :type 'boolean)
1354 (defcustom org-cycle-global-at-bob nil
1355 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use `S-TAB'
1358 or `\\[universal-argument] TAB'. For this special case to work, the first \
1359 line of the buffer
1360 must not be a headline -- it may be empty or some other text.
1362 When used in this way, `org-cycle-hook' is disabled temporarily to make
1363 sure the cursor stays at the beginning of the buffer.
1365 When this option is nil, don't do anything special at the beginning of
1366 the buffer."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-level-after-item/entry-creation t
1371 "Non-nil means cycle entry level or item indentation in new empty entries.
1373 When the cursor is at the end of an empty headline, i.e., with only stars
1374 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1375 and then all possible ancestor states, before returning to the original state.
1376 This makes data entry extremely fast: M-RET to create a new headline,
1377 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1379 When the cursor is at the end of an empty plain list item, one TAB will
1380 make it a subitem, two or more tabs will back up to make this an item
1381 higher up in the item hierarchy."
1382 :group 'org-cycle
1383 :type 'boolean)
1385 (defcustom org-cycle-emulate-tab t
1386 "Where should `org-cycle' emulate TAB.
1387 nil Never
1388 white Only in completely white lines
1389 whitestart Only at the beginning of lines, before the first non-white char
1390 t Everywhere except in headlines
1391 exc-hl-bol Everywhere except at the start of a headline
1392 If TAB is used in a place where it does not emulate TAB, the current subtree
1393 visibility is cycled."
1394 :group 'org-cycle
1395 :type '(choice (const :tag "Never" nil)
1396 (const :tag "Only in completely white lines" white)
1397 (const :tag "Before first char in a line" whitestart)
1398 (const :tag "Everywhere except in headlines" t)
1399 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1401 (defcustom org-cycle-separator-lines 2
1402 "Number of empty lines needed to keep an empty line between collapsed trees.
1403 If you leave an empty line between the end of a subtree and the following
1404 headline, this empty line is hidden when the subtree is folded.
1405 Org mode will leave (exactly) one empty line visible if the number of
1406 empty lines is equal or larger to the number given in this variable.
1407 So the default 2 means at least 2 empty lines after the end of a subtree
1408 are needed to produce free space between a collapsed subtree and the
1409 following headline.
1411 If the number is negative, and the number of empty lines is at least -N,
1412 all empty lines are shown.
1414 Special case: when 0, never leave empty lines in collapsed view."
1415 :group 'org-cycle
1416 :type 'integer)
1417 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1419 (defcustom org-pre-cycle-hook nil
1420 "Hook that is run before visibility cycling is happening.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that will be set right after running this hook. The
1423 argument is a symbol. Before a global state change, it can have the values
1424 `overview', `content', or `all'. Before a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook)
1429 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1430 org-cycle-hide-drawers
1431 org-cycle-show-empty-lines
1432 org-optimize-window-after-visibility-change)
1433 "Hook that is run after `org-cycle' has changed the buffer visibility.
1434 The function(s) in this hook must accept a single argument which indicates
1435 the new state that was set by the most recent `org-cycle' command. The
1436 argument is a symbol. After a global state change, it can have the values
1437 `overview', `contents', or `all'. After a local state change, it can have
1438 the values `folded', `children', or `subtree'."
1439 :group 'org-cycle
1440 :type 'hook
1441 :version "26.1"
1442 :package-version '(Org . "8.3"))
1444 (defgroup org-edit-structure nil
1445 "Options concerning structure editing in Org mode."
1446 :tag "Org Edit Structure"
1447 :group 'org-structure)
1449 (defcustom org-odd-levels-only nil
1450 "Non-nil means skip even levels and only use odd levels for the outline.
1451 This has the effect that two stars are being added/taken away in
1452 promotion/demotion commands. It also influences how levels are
1453 handled by the exporters.
1454 Changing it requires restart of `font-lock-mode' to become effective
1455 for fontification also in regions already fontified.
1456 You may also set this on a per-file basis by adding one of the following
1457 lines to the buffer:
1459 #+STARTUP: odd
1460 #+STARTUP: oddeven"
1461 :group 'org-edit-structure
1462 :group 'org-appearance
1463 :type 'boolean)
1465 (defcustom org-adapt-indentation t
1466 "Non-nil means adapt indentation to outline node level.
1468 When this variable is set, Org assumes that you write outlines by
1469 indenting text in each node to align with the headline (after the
1470 stars). The following issues are influenced by this variable:
1472 - The indentation is increased by one space in a demotion
1473 command, and decreased by one in a promotion command. However,
1474 in the latter case, if shifting some line in the entry body
1475 would alter document structure (e.g., insert a new headline),
1476 indentation is not changed at all.
1478 - Property drawers and planning information is inserted indented
1479 when this variable is set. When nil, they will not be indented.
1481 - TAB indents a line relative to current level. The lines below
1482 a headline will be indented when this variable is set.
1484 Note that this is all about true indentation, by adding and
1485 removing space characters. See also `org-indent.el' which does
1486 level-dependent indentation in a virtual way, i.e. at display
1487 time in Emacs."
1488 :group 'org-edit-structure
1489 :type 'boolean)
1491 (defcustom org-special-ctrl-a/e nil
1492 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1494 When t, `C-a' will bring back the cursor to the beginning of the
1495 headline text, i.e. after the stars and after a possible TODO
1496 keyword. In an item, this will be the position after bullet and
1497 check-box, if any. When the cursor is already at that position,
1498 another `C-a' will bring it to the beginning of the line.
1500 `C-e' will jump to the end of the headline, ignoring the presence
1501 of tags in the headline. A second `C-e' will then jump to the
1502 true end of the line, after any tags. This also means that, when
1503 this variable is non-nil, `C-e' also will never jump beyond the
1504 end of the heading of a folded section, i.e. not after the
1505 ellipses.
1507 When set to the symbol `reversed', the first `C-a' or `C-e' works
1508 normally, going to the true line boundary first. Only a directly
1509 following, identical keypress will bring the cursor to the
1510 special positions.
1512 This may also be a cons cell where the behavior for `C-a' and
1513 `C-e' is set separately."
1514 :group 'org-edit-structure
1515 :type '(choice
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet and before tags first" t)
1518 (const :tag "reversed: true line boundary first" reversed)
1519 (cons :tag "Set C-a and C-e separately"
1520 (choice :tag "Special C-a"
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet first" t)
1523 (const :tag "reversed: before stars/bullet first" reversed))
1524 (choice :tag "Special C-e"
1525 (const :tag "off" nil)
1526 (const :tag "on: before tags first" t)
1527 (const :tag "reversed: after tags first" reversed)))))
1528 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1530 (defcustom org-special-ctrl-k nil
1531 "Non-nil means `C-k' will behave specially in headlines.
1532 When nil, `C-k' will call the default `kill-line' command.
1533 When t, the following will happen while the cursor is in the headline:
1535 - When the cursor is at the beginning of a headline, kill the entire
1536 line and possible the folded subtree below the line.
1537 - When in the middle of the headline text, kill the headline up to the tags.
1538 - When after the headline text, kill the tags."
1539 :group 'org-edit-structure
1540 :type 'boolean)
1542 (defcustom org-ctrl-k-protect-subtree nil
1543 "Non-nil means, do not delete a hidden subtree with C-k.
1544 When set to the symbol `error', simply throw an error when C-k is
1545 used to kill (part-of) a headline that has hidden text behind it.
1546 Any other non-nil value will result in a query to the user, if it is
1547 OK to kill that hidden subtree. When nil, kill without remorse."
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not protect hidden subtrees" nil)
1552 (const :tag "Protect hidden subtrees with a security query" t)
1553 (const :tag "Never kill a hidden subtree with C-k" error)))
1555 (defcustom org-special-ctrl-o t
1556 "Non-nil means, make `C-o' insert a row in tables."
1557 :group 'org-edit-structure
1558 :type 'boolean)
1560 (defcustom org-catch-invisible-edits nil
1561 "Check if in invisible region before inserting or deleting a character.
1562 Valid values are:
1564 nil Do not check, so just do invisible edits.
1565 error Throw an error and do nothing.
1566 show Make point visible, and do the requested edit.
1567 show-and-error Make point visible, then throw an error and abort the edit.
1568 smart Make point visible, and do insertion/deletion if it is
1569 adjacent to visible text and the change feels predictable.
1570 Never delete a previously invisible character or add in the
1571 middle or right after an invisible region. Basically, this
1572 allows insertion and backward-delete right before ellipses.
1573 FIXME: maybe in this case we should not even show?"
1574 :group 'org-edit-structure
1575 :version "24.1"
1576 :type '(choice
1577 (const :tag "Do not check" nil)
1578 (const :tag "Throw error when trying to edit" error)
1579 (const :tag "Unhide, but do not do the edit" show-and-error)
1580 (const :tag "Show invisible part and do the edit" show)
1581 (const :tag "Be smart and do the right thing" smart)))
1583 (defcustom org-yank-folded-subtrees t
1584 "Non-nil means when yanking subtrees, fold them.
1585 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1586 it starts with a heading and all other headings in it are either children
1587 or siblings, then fold all the subtrees. However, do this only if no
1588 text after the yank would be swallowed into a folded tree by this action."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-yank-adjusted-subtrees nil
1593 "Non-nil means when yanking subtrees, adjust the level.
1594 With this setting, `org-paste-subtree' is used to insert the subtree, see
1595 this function for details."
1596 :group 'org-edit-structure
1597 :type 'boolean)
1599 (defcustom org-M-RET-may-split-line '((default . t))
1600 "Non-nil means M-RET will split the line at the cursor position.
1601 When nil, it will go to the end of the line before making a
1602 new line.
1603 You may also set this option in a different way for different
1604 contexts. Valid contexts are:
1606 headline when creating a new headline
1607 item when creating a new item
1608 table in a table field
1609 default the value to be used for all contexts not explicitly
1610 customized"
1611 :group 'org-structure
1612 :group 'org-table
1613 :type '(choice
1614 (const :tag "Always" t)
1615 (const :tag "Never" nil)
1616 (repeat :greedy t :tag "Individual contexts"
1617 (cons
1618 (choice :tag "Context"
1619 (const headline)
1620 (const item)
1621 (const table)
1622 (const default))
1623 (boolean)))))
1626 (defcustom org-insert-heading-respect-content nil
1627 "Non-nil means insert new headings after the current subtree.
1628 \\<org-mode-map>
1629 When nil, the new heading is created directly after the current line.
1630 The commands `\\[org-insert-heading-respect-content]' and \
1631 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1632 for the duration of the command."
1633 :group 'org-structure
1634 :type 'boolean)
1636 (defcustom org-blank-before-new-entry '((heading . auto)
1637 (plain-list-item . auto))
1638 "Should `org-insert-heading' leave a blank line before new heading/item?
1639 The value is an alist, with `heading' and `plain-list-item' as CAR,
1640 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1641 which case Org will look at the surrounding headings/items and try to
1642 make an intelligent decision whether to insert a blank line or not."
1643 :group 'org-edit-structure
1644 :type '(list
1645 (cons (const heading)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))
1649 (cons (const plain-list-item)
1650 (choice (const :tag "Never" nil)
1651 (const :tag "Always" t)
1652 (const :tag "Auto" auto)))))
1654 (defcustom org-insert-heading-hook nil
1655 "Hook being run after inserting a new heading."
1656 :group 'org-edit-structure
1657 :type 'hook)
1659 (defcustom org-enable-fixed-width-editor t
1660 "Non-nil means lines starting with \":\" are treated as fixed-width.
1661 This currently only means they are never auto-wrapped.
1662 When nil, such lines will be treated like ordinary lines."
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defcustom org-goto-auto-isearch t
1667 "Non-nil means typing characters in `org-goto' starts incremental search.
1668 When nil, you can use these keybindings to navigate the buffer:
1670 q Quit the org-goto interface
1671 n Go to the next visible heading
1672 p Go to the previous visible heading
1673 f Go one heading forward on same level
1674 b Go one heading backward on same level
1675 u Go one heading up"
1676 :group 'org-edit-structure
1677 :type 'boolean)
1679 (defgroup org-sparse-trees nil
1680 "Options concerning sparse trees in Org mode."
1681 :tag "Org Sparse Trees"
1682 :group 'org-structure)
1684 (defcustom org-highlight-sparse-tree-matches t
1685 "Non-nil means highlight all matches that define a sparse tree.
1686 The highlights will automatically disappear the next time the buffer is
1687 changed by an edit command."
1688 :group 'org-sparse-trees
1689 :type 'boolean)
1691 (defcustom org-remove-highlights-with-change t
1692 "Non-nil means any change to the buffer will remove temporary highlights.
1693 \\<org-mode-map>\
1694 Such highlights are created by `org-occur' and `org-clock-display'.
1695 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1696 to get rid of the highlights.
1697 The highlights created by `org-toggle-latex-fragment' always need
1698 `\\[org-toggle-latex-fragment]' to be removed."
1699 :group 'org-sparse-trees
1700 :group 'org-time
1701 :type 'boolean)
1703 (defcustom org-occur-case-fold-search t
1704 "Non-nil means `org-occur' should be case-insensitive.
1705 If set to `smart' the search will be case-insensitive only if it
1706 doesn't specify any upper case character."
1707 :group 'org-sparse-trees
1708 :version "26.1"
1709 :type '(choice
1710 (const :tag "Case-sensitive" nil)
1711 (const :tag "Case-insensitive" t)
1712 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1714 (defcustom org-occur-hook '(org-first-headline-recenter)
1715 "Hook that is run after `org-occur' has constructed a sparse tree.
1716 This can be used to recenter the window to show as much of the structure
1717 as possible."
1718 :group 'org-sparse-trees
1719 :type 'hook)
1721 (defgroup org-imenu-and-speedbar nil
1722 "Options concerning imenu and speedbar in Org mode."
1723 :tag "Org Imenu and Speedbar"
1724 :group 'org-structure)
1726 (defcustom org-imenu-depth 2
1727 "The maximum level for Imenu access to Org headlines.
1728 This also applied for speedbar access."
1729 :group 'org-imenu-and-speedbar
1730 :type 'integer)
1732 (defgroup org-table nil
1733 "Options concerning tables in Org mode."
1734 :tag "Org Table"
1735 :group 'org)
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-parameters
1762 '(("doi" :follow org--open-doi-link)
1763 ("elisp" :follow org--open-elisp-link)
1764 ("file" :complete org-file-complete-link)
1765 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1766 ("help" :follow org--open-help-link)
1767 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1768 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1769 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1770 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1771 ("shell" :follow org--open-shell-link))
1772 "An alist of properties that defines all the links in Org mode.
1773 The key in each association is a string of the link type.
1774 Subsequent optional elements make up a p-list of link properties.
1776 :follow - A function that takes the link path as an argument.
1778 :export - A function that takes the link path, description and
1779 export-backend as arguments.
1781 :store - A function responsible for storing the link. See the
1782 function `org-store-link-functions'.
1784 :complete - A function that inserts a link with completion. The
1785 function takes one optional prefix arg.
1787 :face - A face for the link, or a function that returns a face.
1788 The function takes one argument which is the link path. The
1789 default face is `org-link'.
1791 :mouse-face - The mouse-face. The default is `highlight'.
1793 :display - `full' will not fold the link in descriptive
1794 display. Default is `org-link'.
1796 :help-echo - A string or function that takes (window object position)
1797 as arguments and returns a string.
1799 :keymap - A keymap that is active on the link. The default is
1800 `org-mouse-map'.
1802 :htmlize-link - A function for the htmlize-link. Defaults
1803 to (list :uri \"type:path\")
1805 :activate-func - A function to run at the end of font-lock
1806 activation. The function must accept (link-start link-end path bracketp)
1807 as arguments."
1808 :group 'org-link
1809 :type '(alist :tag "Link display parameters"
1810 :value-type plist)
1811 :version "26.1"
1812 :package-version '(Org . "9.1"))
1814 (defun org-link-get-parameter (type key)
1815 "Get TYPE link property for KEY.
1816 TYPE is a string and KEY is a plist keyword."
1817 (plist-get
1818 (cdr (assoc type org-link-parameters))
1819 key))
1821 (defun org-link-set-parameters (type &rest parameters)
1822 "Set link TYPE properties to PARAMETERS.
1823 PARAMETERS should be :key val pairs."
1824 (let ((data (assoc type org-link-parameters)))
1825 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1826 (push (cons type parameters) org-link-parameters)
1827 (org-make-link-regexps)
1828 (org-element-update-syntax))))
1830 (defun org-link-types ()
1831 "Return a list of known link types."
1832 (mapcar #'car org-link-parameters))
1834 (defcustom org-link-abbrev-alist nil
1835 "Alist of link abbreviations.
1836 The car of each element is a string, to be replaced at the start of a link.
1837 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1838 links in Org buffers can have an optional tag after a double colon, e.g.,
1840 [[linkkey:tag][description]]
1842 The `linkkey' must be a single word, starting with a letter, followed
1843 by letters, numbers, `-' or `_'.
1845 If REPLACE is a string, the tag will simply be appended to create the link.
1846 If the string contains \"%s\", the tag will be inserted there. If the string
1847 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1848 at that point (see the function `url-hexify-string'). If the string contains
1849 the specifier \"%(my-function)\", then the custom function `my-function' will
1850 be invoked: this function takes the tag as its only argument and must return
1851 a string.
1853 REPLACE may also be a function that will be called with the tag as the
1854 only argument to create the link, which should be returned as a string.
1856 See the manual for examples."
1857 :group 'org-link
1858 :type '(repeat
1859 (cons
1860 (string :tag "Protocol")
1861 (choice
1862 (string :tag "Format")
1863 (function)))))
1865 (defcustom org-descriptive-links t
1866 "Non-nil means Org will display descriptive links.
1867 E.g. [[http://orgmode.org][Org website]] will be displayed as
1868 \"Org Website\", hiding the link itself and just displaying its
1869 description. When set to nil, Org will display the full links
1870 literally.
1872 You can interactively set the value of this variable by calling
1873 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1874 :group 'org-link
1875 :type 'boolean)
1877 (defcustom org-link-file-path-type 'adaptive
1878 "How the path name in file links should be stored.
1879 Valid values are:
1881 relative Relative to the current directory, i.e. the directory of the file
1882 into which the link is being inserted.
1883 absolute Absolute path, if possible with ~ for home directory.
1884 noabbrev Absolute path, no abbreviation of home directory.
1885 adaptive Use relative path for files in the current directory and sub-
1886 directories of it. For other files, use an absolute path."
1887 :group 'org-link
1888 :type '(choice
1889 (const relative)
1890 (const absolute)
1891 (const noabbrev)
1892 (const adaptive)))
1894 (defvaralias 'org-activate-links 'org-highlight-links)
1895 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1896 "Types of links that should be highlighted in Org files.
1898 This is a list of symbols, each one of them leading to the
1899 highlighting of a certain link type.
1901 You can still open links that are not highlighted.
1903 In principle, it does not hurt to turn on highlighting for all
1904 link types. There may be a small gain when turning off unused
1905 link types. The types are:
1907 bracket The recommended [[link][description]] or [[link]] links with hiding.
1908 angle Links in angular brackets that may contain whitespace like
1909 <bbdb:Carsten Dominik>.
1910 plain Plain links in normal text, no whitespace, like http://google.com.
1911 radio Text that is matched by a radio target, see manual for details.
1912 tag Tag settings in a headline (link to tag search).
1913 date Time stamps (link to calendar).
1914 footnote Footnote labels.
1916 If you set this variable during an Emacs session, use `org-mode-restart'
1917 in the Org buffer so that the change takes effect."
1918 :group 'org-link
1919 :group 'org-appearance
1920 :type '(set :greedy t
1921 (const :tag "Double bracket links" bracket)
1922 (const :tag "Angular bracket links" angle)
1923 (const :tag "Plain text links" plain)
1924 (const :tag "Radio target matches" radio)
1925 (const :tag "Tags" tag)
1926 (const :tag "Timestamps" date)
1927 (const :tag "Footnotes" footnote)))
1929 (defcustom org-make-link-description-function nil
1930 "Function to use for generating link descriptions from links.
1931 This function must take two parameters: the first one is the
1932 link, the second one is the description generated by
1933 `org-insert-link'. The function should return the description to
1934 use."
1935 :group 'org-link
1936 :type '(choice (const nil) (function)))
1938 (defgroup org-link-store nil
1939 "Options concerning storing links in Org mode."
1940 :tag "Org Store Link"
1941 :group 'org-link)
1943 (defcustom org-url-hexify-p t
1944 "When non-nil, hexify URL when creating a link."
1945 :type 'boolean
1946 :version "24.3"
1947 :group 'org-link-store)
1949 (defcustom org-email-link-description-format "Email %c: %.30s"
1950 "Format of the description part of a link to an email or usenet message.
1951 The following %-escapes will be replaced by corresponding information:
1953 %F full \"From\" field
1954 %f name, taken from \"From\" field, address if no name
1955 %T full \"To\" field
1956 %t first name in \"To\" field, address if no name
1957 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1958 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1959 %s subject
1960 %d date
1961 %m message-id.
1963 You may use normal field width specification between the % and the letter.
1964 This is for example useful to limit the length of the subject.
1966 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1967 :group 'org-link-store
1968 :type 'string)
1970 (defcustom org-from-is-user-regexp
1971 (let (r1 r2)
1972 (when (and user-mail-address (not (string= user-mail-address "")))
1973 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1974 (when (and user-full-name (not (string= user-full-name "")))
1975 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1976 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1977 "Regexp matched against the \"From:\" header of an email or usenet message.
1978 It should match if the message is from the user him/herself."
1979 :group 'org-link-store
1980 :type 'regexp)
1982 (defcustom org-context-in-file-links t
1983 "Non-nil means file links from `org-store-link' contain context.
1984 \\<org-mode-map>
1985 A search string will be added to the file name with :: as separator
1986 and used to find the context when the link is activated by the command
1987 `org-open-at-point'. When this option is t, the entire active region
1988 will be placed in the search string of the file link. If set to a
1989 positive integer, only the first n lines of context will be stored.
1991 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1992 \\[org-store-link]')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
1999 \\<org-mode-map>
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links).
2005 When this option is nil, every link which has been inserted once using
2006 `\\[org-insert-link]' will be removed from the list, to make completing the \
2007 unused
2008 links more efficient."
2009 :group 'org-link-store
2010 :type 'boolean)
2012 (defgroup org-link-follow nil
2013 "Options concerning following links in Org mode."
2014 :tag "Org Follow Link"
2015 :group 'org-link)
2017 (defcustom org-link-translation-function nil
2018 "Function to translate links with different syntax to Org syntax.
2019 This can be used to translate links created for example by the Planner
2020 or emacs-wiki packages to Org syntax.
2021 The function must accept two parameters, a TYPE containing the link
2022 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2023 which is everything after the link protocol. It should return a cons
2024 with possibly modified values of type and path.
2025 Org contains a function for this, so if you set this variable to
2026 `org-translate-link-from-planner', you should be able follow many
2027 links created by planner."
2028 :group 'org-link-follow
2029 :type '(choice (const nil) (function)))
2031 (defcustom org-follow-link-hook nil
2032 "Hook that is run after a link has been followed."
2033 :group 'org-link-follow
2034 :type 'hook)
2036 (defcustom org-tab-follows-link nil
2037 "Non-nil means on links TAB will follow the link.
2038 Needs to be set before org.el is loaded.
2039 This really should not be used, it does not make sense, and the
2040 implementation is bad."
2041 :group 'org-link-follow
2042 :type 'boolean)
2044 (defcustom org-return-follows-link nil
2045 "Non-nil means on links RET will follow the link.
2046 In tables, the special behavior of RET has precedence."
2047 :group 'org-link-follow
2048 :type 'boolean)
2050 (defcustom org-mouse-1-follows-link
2051 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2052 "Non-nil means mouse-1 on a link will follow the link.
2053 A longer mouse click will still set point. Needs to be set
2054 before org.el is loaded."
2055 :group 'org-link-follow
2056 :version "26.1"
2057 :package-version '(Org . "8.3")
2058 :type '(choice
2059 (const :tag "A double click follows the link" double)
2060 (const :tag "Unconditionally follow the link with mouse-1" t)
2061 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2063 (defcustom org-mark-ring-length 4
2064 "Number of different positions to be recorded in the ring.
2065 Changing this requires a restart of Emacs to work correctly."
2066 :group 'org-link-follow
2067 :type 'integer)
2069 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2070 "Non-nil means internal fuzzy links can only match headlines.
2072 When nil, the a fuzzy link may point to a target or a named
2073 construct in the document. When set to the special value
2074 `query-to-create', offer to create a new headline when none
2075 matched.
2077 Spaces and statistics cookies are ignored during heading searches."
2078 :group 'org-link-follow
2079 :version "24.1"
2080 :type '(choice
2081 (const :tag "Use fuzzy text search" nil)
2082 (const :tag "Match only exact headline" t)
2083 (const :tag "Match exact headline or query to create it"
2084 query-to-create))
2085 :safe #'symbolp)
2087 (defcustom org-link-frame-setup
2088 '((vm . vm-visit-folder-other-frame)
2089 (vm-imap . vm-visit-imap-folder-other-frame)
2090 (gnus . org-gnus-no-new-news)
2091 (file . find-file-other-window)
2092 (wl . wl-other-frame))
2093 "Setup the frame configuration for following links.
2094 When following a link with Emacs, it may often be useful to display
2095 this link in another window or frame. This variable can be used to
2096 set this up for the different types of links.
2097 For VM, use any of
2098 `vm-visit-folder'
2099 `vm-visit-folder-other-window'
2100 `vm-visit-folder-other-frame'
2101 For Gnus, use any of
2102 `gnus'
2103 `gnus-other-frame'
2104 `org-gnus-no-new-news'
2105 For FILE, use any of
2106 `find-file'
2107 `find-file-other-window'
2108 `find-file-other-frame'
2109 For Wanderlust use any of
2110 `wl'
2111 `wl-other-frame'
2112 For the calendar, use the variable `calendar-setup'.
2113 For BBDB, it is currently only possible to display the matches in
2114 another window."
2115 :group 'org-link-follow
2116 :type '(list
2117 (cons (const vm)
2118 (choice
2119 (const vm-visit-folder)
2120 (const vm-visit-folder-other-window)
2121 (const vm-visit-folder-other-frame)))
2122 (cons (const vm-imap)
2123 (choice
2124 (const vm-visit-imap-folder)
2125 (const vm-visit-imap-folder-other-window)
2126 (const vm-visit-imap-folder-other-frame)))
2127 (cons (const gnus)
2128 (choice
2129 (const gnus)
2130 (const gnus-other-frame)
2131 (const org-gnus-no-new-news)))
2132 (cons (const file)
2133 (choice
2134 (const find-file)
2135 (const find-file-other-window)
2136 (const find-file-other-frame)))
2137 (cons (const wl)
2138 (choice
2139 (const wl)
2140 (const wl-other-frame)))))
2142 (defcustom org-display-internal-link-with-indirect-buffer nil
2143 "Non-nil means use indirect buffer to display infile links.
2144 Activating internal links (from one location in a file to another location
2145 in the same file) normally just jumps to the location. When the link is
2146 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2147 is displayed in
2148 another window. When this option is set, the other window actually displays
2149 an indirect buffer clone of the current buffer, to avoid any visibility
2150 changes to the current buffer."
2151 :group 'org-link-follow
2152 :type 'boolean)
2154 (defcustom org-open-non-existing-files nil
2155 "Non-nil means `org-open-file' will open non-existing files.
2156 When nil, an error will be generated.
2157 This variable applies only to external applications because they
2158 might choke on non-existing files. If the link is to a file that
2159 will be opened in Emacs, the variable is ignored."
2160 :group 'org-link-follow
2161 :type 'boolean)
2163 (defcustom org-open-directory-means-index-dot-org nil
2164 "Non-nil means a link to a directory really means to index.org.
2165 When nil, following a directory link will run dired or open a finder/explorer
2166 window on that directory."
2167 :group 'org-link-follow
2168 :type 'boolean)
2170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2171 "Non-nil means ask for confirmation before executing shell links.
2172 Shell links can be dangerous: just think about a link
2174 [[shell:rm -rf ~/*][Google Search]]
2176 This link would show up in your Org document as \"Google Search\",
2177 but really it would remove your entire home directory.
2178 Therefore we advise against setting this variable to nil.
2179 Just change it to `y-or-n-p' if you want to confirm with a
2180 single keystroke rather than having to type \"yes\"."
2181 :group 'org-link-follow
2182 :type '(choice
2183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2184 (const :tag "with y-or-n (faster)" y-or-n-p)
2185 (const :tag "no confirmation (dangerous)" nil)))
2186 (put 'org-confirm-shell-link-function
2187 'safe-local-variable
2188 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2190 (defcustom org-confirm-shell-link-not-regexp ""
2191 "A regexp to skip confirmation for shell links."
2192 :group 'org-link-follow
2193 :version "24.1"
2194 :type 'regexp)
2196 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2197 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2198 Elisp links can be dangerous: just think about a link
2200 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2202 This link would show up in your Org document as \"Google Search\",
2203 but really it would remove your entire home directory.
2204 Therefore we advise against setting this variable to nil.
2205 Just change it to `y-or-n-p' if you want to confirm with a
2206 single keystroke rather than having to type \"yes\"."
2207 :group 'org-link-follow
2208 :type '(choice
2209 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2210 (const :tag "with y-or-n (faster)" y-or-n-p)
2211 (const :tag "no confirmation (dangerous)" nil)))
2212 (put 'org-confirm-shell-link-function
2213 'safe-local-variable
2214 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2216 (defcustom org-confirm-elisp-link-not-regexp ""
2217 "A regexp to skip confirmation for Elisp links."
2218 :group 'org-link-follow
2219 :version "24.1"
2220 :type 'regexp)
2222 (defconst org-file-apps-defaults-gnu
2223 '((remote . emacs)
2224 (system . mailcap)
2225 (t . mailcap))
2226 "Default file applications on a UNIX or GNU/Linux system.
2227 See `org-file-apps'.")
2229 (defconst org-file-apps-defaults-macosx
2230 '((remote . emacs)
2231 (system . "open %s")
2232 ("ps.gz" . "gv %s")
2233 ("eps.gz" . "gv %s")
2234 ("dvi" . "xdvi %s")
2235 ("fig" . "xfig %s")
2236 (t . "open %s"))
2237 "Default file applications on a macOS system.
2238 The system \"open\" is known as a default, but we use X11 applications
2239 for some files for which the OS does not have a good default.
2240 See `org-file-apps'.")
2242 (defconst org-file-apps-defaults-windowsnt
2243 (list '(remote . emacs)
2244 (cons 'system (lambda (file _path)
2245 (with-no-warnings (w32-shell-execute "open" file))))
2246 (cons t (lambda (file _path)
2247 (with-no-warnings (w32-shell-execute "open" file)))))
2248 "Default file applications on a Windows NT system.
2249 The system \"open\" is used for most files.
2250 See `org-file-apps'.")
2252 (defcustom org-file-apps
2253 '((auto-mode . emacs)
2254 ("\\.mm\\'" . default)
2255 ("\\.x?html?\\'" . default)
2256 ("\\.pdf\\'" . default))
2257 "External applications for opening `file:path' items in a document.
2258 \\<org-mode-map>\
2260 Org mode uses system defaults for different file types, but
2261 you can use this variable to set the application for a given file
2262 extension. The entries in this list are cons cells where the car identifies
2263 files and the cdr the corresponding command.
2265 Possible values for the file identifier are:
2267 \"string\" A string as a file identifier can be interpreted in different
2268 ways, depending on its contents:
2270 - Alphanumeric characters only:
2271 Match links with this file extension.
2272 Example: (\"pdf\" . \"evince %s\")
2273 to open PDFs with evince.
2275 - Regular expression: Match links where the
2276 filename matches the regexp. If you want to
2277 use groups here, use shy groups.
2279 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2280 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2281 to open *.html and *.xhtml with firefox.
2283 - Regular expression which contains (non-shy) groups:
2284 Match links where the whole link, including \"::\", and
2285 anything after that, matches the regexp.
2286 In a custom command string, %1, %2, etc. are replaced with
2287 the parts of the link that were matched by the groups.
2288 For backwards compatibility, if a command string is given
2289 that does not use any of the group matches, this case is
2290 handled identically to the second one (i.e. match against
2291 file name only).
2292 In a custom function, you can access the group matches with
2293 (match-string n link).
2295 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2296 \"evince -p %1 %s\")
2297 to open [[file:document.pdf::5]] with evince at page 5.
2299 `directory' Matches a directory
2300 `remote' Matches a remote file, accessible through tramp or efs.
2301 Remote files most likely should be visited through Emacs
2302 because external applications cannot handle such paths.
2303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2304 so all files Emacs knows how to handle. Using this with
2305 command `emacs' will open most files in Emacs. Beware that this
2306 will also open html files inside Emacs, unless you add
2307 (\"html\" . default) to the list as well.
2308 `system' The system command to open files, like `open' on Windows
2309 and macOS, and mailcap under GNU/Linux. This is the command
2310 that will be selected if you call `org-open-at-point' with a
2311 double prefix argument (`\\[universal-argument] \
2312 \\[universal-argument] \\[org-open-at-point]').
2313 t Default for files not matched by any of the other options.
2315 Possible values for the command are:
2317 `emacs' The file will be visited by the current Emacs process.
2318 `default' Use the default application for this file type, which is the
2319 association for t in the list, most likely in the system-specific
2320 part. This can be used to overrule an unwanted setting in the
2321 system-specific variable.
2322 `system' Use the system command for opening files, like \"open\".
2323 This command is specified by the entry whose car is `system'.
2324 Most likely, the system-specific version of this variable
2325 does define this command, but you can overrule/replace it
2326 here.
2327 `mailcap' Use command specified in the mailcaps.
2328 string A command to be executed by a shell; %s will be replaced
2329 by the path to the file.
2330 function A Lisp function, which will be called with two arguments:
2331 the file path and the original link string, without the
2332 \"file:\" prefix.
2334 For more examples, see the system specific constants
2335 `org-file-apps-defaults-macosx'
2336 `org-file-apps-defaults-windowsnt'
2337 `org-file-apps-defaults-gnu'."
2338 :group 'org-link-follow
2339 :type '(repeat
2340 (cons (choice :value ""
2341 (string :tag "Extension")
2342 (const :tag "System command to open files" system)
2343 (const :tag "Default for unrecognized files" t)
2344 (const :tag "Remote file" remote)
2345 (const :tag "Links to a directory" directory)
2346 (const :tag "Any files that have Emacs modes"
2347 auto-mode))
2348 (choice :value ""
2349 (const :tag "Visit with Emacs" emacs)
2350 (const :tag "Use default" default)
2351 (const :tag "Use the system command" system)
2352 (string :tag "Command")
2353 (function :tag "Function")))))
2355 (defcustom org-doi-server-url "http://dx.doi.org/"
2356 "The URL of the DOI server."
2357 :type 'string
2358 :version "24.3"
2359 :group 'org-link-follow)
2361 (defgroup org-refile nil
2362 "Options concerning refiling entries in Org mode."
2363 :tag "Org Refile"
2364 :group 'org)
2366 (defcustom org-directory "~/org"
2367 "Directory with Org files.
2368 This is just a default location to look for Org files. There is no need
2369 at all to put your files into this directory. It is used in the
2370 following situations:
2372 1. When a capture template specifies a target file that is not an
2373 absolute path. The path will then be interpreted relative to
2374 `org-directory'
2375 2. When the value of variable `org-agenda-files' is a single file, any
2376 relative paths in this file will be taken as relative to
2377 `org-directory'."
2378 :group 'org-refile
2379 :group 'org-capture
2380 :type 'directory)
2382 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2383 "Default target for storing notes.
2384 Used as a fall back file for org-capture.el, for templates that
2385 do not specify a target file."
2386 :group 'org-refile
2387 :group 'org-capture
2388 :type 'file)
2390 (defcustom org-goto-interface 'outline
2391 "The default interface to be used for `org-goto'.
2392 Allowed values are:
2393 outline The interface shows an outline of the relevant file
2394 and the correct heading is found by moving through
2395 the outline or by searching with incremental search.
2396 outline-path-completion Headlines in the current buffer are offered via
2397 completion. This is the interface also used by
2398 the refile command."
2399 :group 'org-refile
2400 :type '(choice
2401 (const :tag "Outline" outline)
2402 (const :tag "Outline-path-completion" outline-path-completion)))
2404 (defcustom org-goto-max-level 5
2405 "Maximum target level when running `org-goto' with refile interface."
2406 :group 'org-refile
2407 :type 'integer)
2409 (defcustom org-reverse-note-order nil
2410 "Non-nil means store new notes at the beginning of a file or entry.
2411 When nil, new notes will be filed to the end of a file or entry.
2412 This can also be a list with cons cells of regular expressions that
2413 are matched against file names, and values."
2414 :group 'org-capture
2415 :group 'org-refile
2416 :type '(choice
2417 (const :tag "Reverse always" t)
2418 (const :tag "Reverse never" nil)
2419 (repeat :tag "By file name regexp"
2420 (cons regexp boolean))))
2422 (defcustom org-log-refile nil
2423 "Information to record when a task is refiled.
2425 Possible values are:
2427 nil Don't add anything
2428 time Add a time stamp to the task
2429 note Prompt for a note and add it with template `org-log-note-headings'
2431 This option can also be set with on a per-file-basis with
2433 #+STARTUP: nologrefile
2434 #+STARTUP: logrefile
2435 #+STARTUP: lognoterefile
2437 You can have local logging settings for a subtree by setting the LOGGING
2438 property to one or more of these keywords.
2440 When bulk-refiling from the agenda, the value `note' is forbidden and
2441 will temporarily be changed to `time'."
2442 :group 'org-refile
2443 :group 'org-progress
2444 :version "24.1"
2445 :type '(choice
2446 (const :tag "No logging" nil)
2447 (const :tag "Record timestamp" time)
2448 (const :tag "Record timestamp with note." note)))
2450 (defcustom org-refile-targets nil
2451 "Targets for refiling entries with `\\[org-refile]'.
2452 This is a list of cons cells. Each cell contains:
2453 - a specification of the files to be considered, either a list of files,
2454 or a symbol whose function or variable value will be used to retrieve
2455 a file name or a list of file names. If you use `org-agenda-files' for
2456 that, all agenda files will be scanned for targets. Nil means consider
2457 headings in the current buffer.
2458 - A specification of how to find candidate refile targets. This may be
2459 any of:
2460 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2461 This tag has to be present in all target headlines, inheritance will
2462 not be considered.
2463 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2464 todo keyword.
2465 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2466 headlines that are refiling targets.
2467 - a cons cell (:level . N). Any headline of level N is considered a target.
2468 Note that, when `org-odd-levels-only' is set, level corresponds to
2469 order in hierarchy, not to the number of stars.
2470 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2471 Note that, when `org-odd-levels-only' is set, level corresponds to
2472 order in hierarchy, not to the number of stars.
2474 Each element of this list generates a set of possible targets.
2475 The union of these sets is presented (with completion) to
2476 the user by `org-refile'.
2478 You can set the variable `org-refile-target-verify-function' to a function
2479 to verify each headline found by the simple criteria above.
2481 When this variable is nil, all top-level headlines in the current buffer
2482 are used, equivalent to the value `((nil . (:level . 1))'."
2483 :group 'org-refile
2484 :type '(repeat
2485 (cons
2486 (choice :value org-agenda-files
2487 (const :tag "All agenda files" org-agenda-files)
2488 (const :tag "Current buffer" nil)
2489 (function) (variable) (file))
2490 (choice :tag "Identify target headline by"
2491 (cons :tag "Specific tag" (const :value :tag) (string))
2492 (cons :tag "TODO keyword" (const :value :todo) (string))
2493 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2494 (cons :tag "Level number" (const :value :level) (integer))
2495 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2497 (defcustom org-refile-target-verify-function nil
2498 "Function to verify if the headline at point should be a refile target.
2499 The function will be called without arguments, with point at the
2500 beginning of the headline. It should return t and leave point
2501 where it is if the headline is a valid target for refiling.
2503 If the target should not be selected, the function must return nil.
2504 In addition to this, it may move point to a place from where the search
2505 should be continued. For example, the function may decide that the entire
2506 subtree of the current entry should be excluded and move point to the end
2507 of the subtree."
2508 :group 'org-refile
2509 :type '(choice
2510 (const nil)
2511 (function)))
2513 (defcustom org-refile-use-cache nil
2514 "Non-nil means cache refile targets to speed up the process.
2515 \\<org-mode-map>\
2516 The cache for a particular file will be updated automatically when
2517 the buffer has been killed, or when any of the marker used for flagging
2518 refile targets no longer points at a live buffer.
2519 If you have added new entries to a buffer that might themselves be targets,
2520 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2521 if you find that easier, \
2522 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2523 \\[org-refile]'."
2524 :group 'org-refile
2525 :version "24.1"
2526 :type 'boolean)
2528 (defcustom org-refile-use-outline-path nil
2529 "Non-nil means provide refile targets as paths.
2530 So a level 3 headline will be available as level1/level2/level3.
2532 When the value is `file', also include the file name (without directory)
2533 into the path. In this case, you can also stop the completion after
2534 the file name, to get entries inserted as top level in the file.
2536 When `full-file-path', include the full file path.
2538 When `buffer-name', use the buffer name."
2539 :group 'org-refile
2540 :type '(choice
2541 (const :tag "Not" nil)
2542 (const :tag "Yes" t)
2543 (const :tag "Start with file name" file)
2544 (const :tag "Start with full file path" full-file-path)
2545 (const :tag "Start with buffer name" buffer-name)))
2547 (defcustom org-outline-path-complete-in-steps t
2548 "Non-nil means complete the outline path in hierarchical steps.
2549 When Org uses the refile interface to select an outline path (see
2550 `org-refile-use-outline-path'), the completion of the path can be
2551 done in a single go, or it can be done in steps down the headline
2552 hierarchy. Going in steps is probably the best if you do not use
2553 a special completion package like `ido' or `icicles'. However,
2554 when using these packages, going in one step can be very fast,
2555 while still showing the whole path to the entry."
2556 :group 'org-refile
2557 :type 'boolean)
2559 (defcustom org-refile-allow-creating-parent-nodes nil
2560 "Non-nil means allow the creation of new nodes as refile targets.
2561 New nodes are then created by adding \"/new node name\" to the completion
2562 of an existing node. When the value of this variable is `confirm',
2563 new node creation must be confirmed by the user (recommended).
2564 When nil, the completion must match an existing entry.
2566 Note that, if the new heading is not seen by the criteria
2567 listed in `org-refile-targets', multiple instances of the same
2568 heading would be created by trying again to file under the new
2569 heading."
2570 :group 'org-refile
2571 :type '(choice
2572 (const :tag "Never" nil)
2573 (const :tag "Always" t)
2574 (const :tag "Prompt for confirmation" confirm)))
2576 (defcustom org-refile-active-region-within-subtree nil
2577 "Non-nil means also refile active region within a subtree.
2579 By default `org-refile' doesn't allow refiling regions if they
2580 don't contain a set of subtrees, but it might be convenient to
2581 do so sometimes: in that case, the first line of the region is
2582 converted to a headline before refiling."
2583 :group 'org-refile
2584 :version "24.1"
2585 :type 'boolean)
2587 (defgroup org-todo nil
2588 "Options concerning TODO items in Org mode."
2589 :tag "Org TODO"
2590 :group 'org)
2592 (defgroup org-progress nil
2593 "Options concerning Progress logging in Org mode."
2594 :tag "Org Progress"
2595 :group 'org-time)
2597 (defvar org-todo-interpretation-widgets
2598 '((:tag "Sequence (cycling hits every state)" sequence)
2599 (:tag "Type (cycling directly to DONE)" type))
2600 "The available interpretation symbols for customizing `org-todo-keywords'.
2601 Interested libraries should add to this list.")
2603 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2604 "List of TODO entry keyword sequences and their interpretation.
2605 \\<org-mode-map>This is a list of sequences.
2607 Each sequence starts with a symbol, either `sequence' or `type',
2608 indicating if the keywords should be interpreted as a sequence of
2609 action steps, or as different types of TODO items. The first
2610 keywords are states requiring action - these states will select a headline
2611 for inclusion into the global TODO list Org produces. If one of the
2612 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2613 signify that no further action is necessary. If \"|\" is not found,
2614 the last keyword is treated as the only DONE state of the sequence.
2616 The command `\\[org-todo]' cycles an entry through these states, and one
2617 additional state where no keyword is present. For details about this
2618 cycling, see the manual.
2620 TODO keywords and interpretation can also be set on a per-file basis with
2621 the special #+SEQ_TODO and #+TYP_TODO lines.
2623 Each keyword can optionally specify a character for fast state selection
2624 \(in combination with the variable `org-use-fast-todo-selection')
2625 and specifiers for state change logging, using the same syntax that
2626 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2627 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2628 indicates to record a time stamp each time this state is selected.
2630 Each keyword may also specify if a timestamp or a note should be
2631 recorded when entering or leaving the state, by adding additional
2632 characters in the parenthesis after the keyword. This looks like this:
2633 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2634 record only the time of the state change. With X and Y being either
2635 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2636 Y when leaving the state if and only if the *target* state does not
2637 define X. You may omit any of the fast-selection key or X or /Y,
2638 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2640 For backward compatibility, this variable may also be just a list
2641 of keywords. In this case the interpretation (sequence or type) will be
2642 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2643 :group 'org-todo
2644 :group 'org-keywords
2645 :type '(choice
2646 (repeat :tag "Old syntax, just keywords"
2647 (string :tag "Keyword"))
2648 (repeat :tag "New syntax"
2649 (cons
2650 (choice
2651 :tag "Interpretation"
2652 ;;Quick and dirty way to see
2653 ;;`org-todo-interpretations'. This takes the
2654 ;;place of item arguments
2655 :convert-widget
2656 (lambda (widget)
2657 (widget-put widget
2658 :args (mapcar
2659 (lambda (x)
2660 (widget-convert
2661 (cons 'const x)))
2662 org-todo-interpretation-widgets))
2663 widget))
2664 (repeat
2665 (string :tag "Keyword"))))))
2667 (defvar-local org-todo-keywords-1 nil
2668 "All TODO and DONE keywords active in a buffer.")
2669 (defvar org-todo-keywords-for-agenda nil)
2670 (defvar org-done-keywords-for-agenda nil)
2671 (defvar org-todo-keyword-alist-for-agenda nil)
2672 (defvar org-tag-alist-for-agenda nil
2673 "Alist of all tags from all agenda files.")
2674 (defvar org-tag-groups-alist-for-agenda nil
2675 "Alist of all groups tags from all current agenda files.")
2676 (defvar-local org-tag-groups-alist nil)
2677 (defvar org-agenda-contributing-files nil)
2678 (defvar-local org-current-tag-alist nil
2679 "Alist of all tag groups in current buffer.
2680 This variable takes into consideration `org-tag-alist',
2681 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2682 (defvar-local org-not-done-keywords nil)
2683 (defvar-local org-done-keywords nil)
2684 (defvar-local org-todo-heads nil)
2685 (defvar-local org-todo-sets nil)
2686 (defvar-local org-todo-log-states nil)
2687 (defvar-local org-todo-kwd-alist nil)
2688 (defvar-local org-todo-key-alist nil)
2689 (defvar-local org-todo-key-trigger nil)
2691 (defcustom org-todo-interpretation 'sequence
2692 "Controls how TODO keywords are interpreted.
2693 This variable is in principle obsolete and is only used for
2694 backward compatibility, if the interpretation of todo keywords is
2695 not given already in `org-todo-keywords'. See that variable for
2696 more information."
2697 :group 'org-todo
2698 :group 'org-keywords
2699 :type '(choice (const sequence)
2700 (const type)))
2702 (defcustom org-use-fast-todo-selection t
2703 "\\<org-mode-map>\
2704 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2705 This variable describes if and under what circumstances the cycling
2706 mechanism for TODO keywords will be replaced by a single-key, direct
2707 selection scheme.
2709 When nil, fast selection is never used.
2711 When the symbol `prefix', it will be used when `org-todo' is called
2712 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2713 in an Org buffer, and
2714 `\\[universal-argument] t' in an agenda buffer.
2716 When t, fast selection is used by default. In this case, the prefix
2717 argument forces cycling instead.
2719 In all cases, the special interface is only used if access keys have
2720 actually been assigned by the user, i.e. if keywords in the configuration
2721 are followed by a letter in parenthesis, like TODO(t)."
2722 :group 'org-todo
2723 :type '(choice
2724 (const :tag "Never" nil)
2725 (const :tag "By default" t)
2726 (const :tag "Only with C-u C-c C-t" prefix)))
2728 (defcustom org-provide-todo-statistics t
2729 "Non-nil means update todo statistics after insert and toggle.
2730 ALL-HEADLINES means update todo statistics by including headlines
2731 with no TODO keyword as well, counting them as not done.
2732 A list of TODO keywords means the same, but skip keywords that are
2733 not in this list.
2734 When set to a list of two lists, the first list contains keywords
2735 to consider as TODO keywords, the second list contains keywords
2736 to consider as DONE keywords.
2738 When this is set, todo statistics is updated in the parent of the
2739 current entry each time a todo state is changed."
2740 :group 'org-todo
2741 :type '(choice
2742 (const :tag "Yes, only for TODO entries" t)
2743 (const :tag "Yes, including all entries" all-headlines)
2744 (repeat :tag "Yes, for TODOs in this list"
2745 (string :tag "TODO keyword"))
2746 (list :tag "Yes, for TODOs and DONEs in these lists"
2747 (repeat (string :tag "TODO keyword"))
2748 (repeat (string :tag "DONE keyword")))
2749 (other :tag "No TODO statistics" nil)))
2751 (defcustom org-hierarchical-todo-statistics t
2752 "Non-nil means TODO statistics covers just direct children.
2753 When nil, all entries in the subtree are considered.
2754 This has only an effect if `org-provide-todo-statistics' is set.
2755 To set this to nil for only a single subtree, use a COOKIE_DATA
2756 property and include the word \"recursive\" into the value."
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-after-todo-state-change-hook nil
2761 "Hook which is run after the state of a TODO item was changed.
2762 The new state (a string with a TODO keyword, or nil) is available in the
2763 Lisp variable `org-state'."
2764 :group 'org-todo
2765 :type 'hook)
2767 (defvar org-blocker-hook nil
2768 "Hook for functions that are allowed to block a state change.
2770 Functions in this hook should not modify the buffer.
2771 Each function gets as its single argument a property list,
2772 see `org-trigger-hook' for more information about this list.
2774 If any of the functions in this hook returns nil, the state change
2775 is blocked.")
2777 (defvar org-trigger-hook nil
2778 "Hook for functions that are triggered by a state change.
2780 Each function gets as its single argument a property list with at
2781 least the following elements:
2783 (:type type-of-change :position pos-at-entry-start
2784 :from old-state :to new-state)
2786 Depending on the type, more properties may be present.
2788 This mechanism is currently implemented for:
2790 TODO state changes
2791 ------------------
2792 :type todo-state-change
2793 :from previous state (keyword as a string), or nil, or a symbol
2794 `todo' or `done', to indicate the general type of state.
2795 :to new state, like in :from")
2797 (defcustom org-enforce-todo-dependencies nil
2798 "Non-nil means undone TODO entries will block switching the parent to DONE.
2799 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2800 be blocked if any prior sibling is not yet done.
2801 Finally, if the parent is blocked because of ordered siblings of its own,
2802 the child will also be blocked."
2803 :set (lambda (var val)
2804 (set var val)
2805 (if val
2806 (add-hook 'org-blocker-hook
2807 'org-block-todo-from-children-or-siblings-or-parent)
2808 (remove-hook 'org-blocker-hook
2809 'org-block-todo-from-children-or-siblings-or-parent)))
2810 :group 'org-todo
2811 :type 'boolean)
2813 (defcustom org-enforce-todo-checkbox-dependencies nil
2814 "Non-nil means unchecked boxes will block switching the parent to DONE.
2815 When this is nil, checkboxes have no influence on switching TODO states.
2816 When non-nil, you first need to check off all check boxes before the TODO
2817 entry can be switched to DONE.
2818 This variable needs to be set before org.el is loaded, and you need to
2819 restart Emacs after a change to make the change effective. The only way
2820 to change is while Emacs is running is through the customize interface."
2821 :set (lambda (var val)
2822 (set var val)
2823 (if val
2824 (add-hook 'org-blocker-hook
2825 'org-block-todo-from-checkboxes)
2826 (remove-hook 'org-blocker-hook
2827 'org-block-todo-from-checkboxes)))
2828 :group 'org-todo
2829 :type 'boolean)
2831 (defcustom org-treat-insert-todo-heading-as-state-change nil
2832 "Non-nil means inserting a TODO heading is treated as state change.
2833 So when the command `\\[org-insert-todo-heading]' is used, state change
2834 logging will apply if appropriate. When nil, the new TODO item will
2835 be inserted directly, and no logging will take place."
2836 :group 'org-todo
2837 :type 'boolean)
2839 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2840 "Non-nil means switching TODO states with S-cursor counts as state change.
2841 This is the default behavior. However, setting this to nil allows a
2842 convenient way to select a TODO state and bypass any logging associated
2843 with that."
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-todo-state-tags-triggers nil
2848 "Tag changes that should be triggered by TODO state changes.
2849 This is a list. Each entry is
2851 (state-change (tag . flag) .......)
2853 State-change can be a string with a state, and empty string to indicate the
2854 state that has no TODO keyword, or it can be one of the symbols `todo'
2855 or `done', meaning any not-done or done state, respectively."
2856 :group 'org-todo
2857 :group 'org-tags
2858 :type '(repeat
2859 (cons (choice :tag "When changing to"
2860 (const :tag "Not-done state" todo)
2861 (const :tag "Done state" done)
2862 (string :tag "State"))
2863 (repeat
2864 (cons :tag "Tag action"
2865 (string :tag "Tag")
2866 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2868 (defcustom org-log-done nil
2869 "Information to record when a task moves to the DONE state.
2871 Possible values are:
2873 nil Don't add anything, just change the keyword
2874 time Add a time stamp to the task
2875 note Prompt for a note and add it with template `org-log-note-headings'
2877 This option can also be set with on a per-file-basis with
2879 #+STARTUP: nologdone
2880 #+STARTUP: logdone
2881 #+STARTUP: lognotedone
2883 You can have local logging settings for a subtree by setting the LOGGING
2884 property to one or more of these keywords."
2885 :group 'org-todo
2886 :group 'org-progress
2887 :type '(choice
2888 (const :tag "No logging" nil)
2889 (const :tag "Record CLOSED timestamp" time)
2890 (const :tag "Record CLOSED timestamp with note." note)))
2892 ;; Normalize old uses of org-log-done.
2893 (cond
2894 ((eq org-log-done t) (setq org-log-done 'time))
2895 ((and (listp org-log-done) (memq 'done org-log-done))
2896 (setq org-log-done 'note)))
2898 (defcustom org-log-reschedule nil
2899 "Information to record when the scheduling date of a tasks is modified.
2901 Possible values are:
2903 nil Don't add anything, just change the date
2904 time Add a time stamp to the task
2905 note Prompt for a note and add it with template `org-log-note-headings'
2907 This option can also be set with on a per-file-basis with
2909 #+STARTUP: nologreschedule
2910 #+STARTUP: logreschedule
2911 #+STARTUP: lognotereschedule"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type '(choice
2915 (const :tag "No logging" nil)
2916 (const :tag "Record timestamp" time)
2917 (const :tag "Record timestamp with note." note)))
2919 (defcustom org-log-redeadline nil
2920 "Information to record when the deadline date of a tasks is modified.
2922 Possible values are:
2924 nil Don't add anything, just change the date
2925 time Add a time stamp to the task
2926 note Prompt for a note and add it with template `org-log-note-headings'
2928 This option can also be set with on a per-file-basis with
2930 #+STARTUP: nologredeadline
2931 #+STARTUP: logredeadline
2932 #+STARTUP: lognoteredeadline
2934 You can have local logging settings for a subtree by setting the LOGGING
2935 property to one or more of these keywords."
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type '(choice
2939 (const :tag "No logging" nil)
2940 (const :tag "Record timestamp" time)
2941 (const :tag "Record timestamp with note." note)))
2943 (defcustom org-log-note-clock-out nil
2944 "Non-nil means record a note when clocking out of an item.
2945 This can also be configured on a per-file basis by adding one of
2946 the following lines anywhere in the buffer:
2948 #+STARTUP: lognoteclock-out
2949 #+STARTUP: nolognoteclock-out"
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type 'boolean)
2954 (defcustom org-log-done-with-time t
2955 "Non-nil means the CLOSED time stamp will contain date and time.
2956 When nil, only the date will be recorded."
2957 :group 'org-progress
2958 :type 'boolean)
2960 (defcustom org-log-note-headings
2961 '((done . "CLOSING NOTE %t")
2962 (state . "State %-12s from %-12S %t")
2963 (note . "Note taken on %t")
2964 (reschedule . "Rescheduled from %S on %t")
2965 (delschedule . "Not scheduled, was %S on %t")
2966 (redeadline . "New deadline from %S on %t")
2967 (deldeadline . "Removed deadline, was %S on %t")
2968 (refile . "Refiled on %t")
2969 (clock-out . ""))
2970 "Headings for notes added to entries.
2972 The value is an alist, with the car being a symbol indicating the
2973 note context, and the cdr is the heading to be used. The heading
2974 may also be the empty string. The following placeholders can be
2975 used:
2977 %t a time stamp.
2978 %T an active time stamp instead the default inactive one
2979 %d a short-format time stamp.
2980 %D an active short-format time stamp.
2981 %s the new TODO state or time stamp (inactive), in double quotes.
2982 %S the old TODO state or time stamp (inactive), in double quotes.
2983 %u the user name.
2984 %U full user name.
2986 In fact, it is not a good idea to change the `state' entry,
2987 because Agenda Log mode depends on the format of these entries."
2988 :group 'org-todo
2989 :group 'org-progress
2990 :type '(list :greedy t
2991 (cons (const :tag "Heading when closing an item" done) string)
2992 (cons (const :tag
2993 "Heading when changing todo state (todo sequence only)"
2994 state) string)
2995 (cons (const :tag "Heading when just taking a note" note) string)
2996 (cons (const :tag "Heading when rescheduling" reschedule) string)
2997 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2998 (cons (const :tag "Heading when changing deadline" redeadline) string)
2999 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3000 (cons (const :tag "Heading when refiling" refile) string)
3001 (cons (const :tag "Heading when clocking out" clock-out) string)))
3003 (unless (assq 'note org-log-note-headings)
3004 (push '(note . "%t") org-log-note-headings))
3006 (defcustom org-log-into-drawer nil
3007 "Non-nil means insert state change notes and time stamps into a drawer.
3008 When nil, state changes notes will be inserted after the headline and
3009 any scheduling and clock lines, but not inside a drawer.
3011 The value of this variable should be the name of the drawer to use.
3012 LOGBOOK is proposed as the default drawer for this purpose, you can
3013 also set this to a string to define the drawer of your choice.
3015 A value of t is also allowed, representing \"LOGBOOK\".
3017 A value of t or nil can also be set with on a per-file-basis with
3019 #+STARTUP: logdrawer
3020 #+STARTUP: nologdrawer
3022 If this variable is set, `org-log-state-notes-insert-after-drawers'
3023 will be ignored.
3025 You can set the property LOG_INTO_DRAWER to overrule this setting for
3026 a subtree.
3028 Do not check directly this variable in a Lisp program. Call
3029 function `org-log-into-drawer' instead."
3030 :group 'org-todo
3031 :group 'org-progress
3032 :type '(choice
3033 (const :tag "Not into a drawer" nil)
3034 (const :tag "LOGBOOK" t)
3035 (string :tag "Other")))
3037 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3039 (defun org-log-into-drawer ()
3040 "Name of the log drawer, as a string, or nil.
3041 This is the value of `org-log-into-drawer'. However, if the
3042 current entry has or inherits a LOG_INTO_DRAWER property, it will
3043 be used instead of the default value."
3044 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3045 (cond ((equal p "nil") nil)
3046 ((equal p "t") "LOGBOOK")
3047 ((stringp p) p)
3048 (p "LOGBOOK")
3049 ((stringp org-log-into-drawer) org-log-into-drawer)
3050 (org-log-into-drawer "LOGBOOK"))))
3052 (defcustom org-log-state-notes-insert-after-drawers nil
3053 "Non-nil means insert state change notes after any drawers in entry.
3054 Only the drawers that *immediately* follow the headline and the
3055 deadline/scheduled line are skipped.
3056 When nil, insert notes right after the heading and perhaps the line
3057 with deadline/scheduling if present.
3059 This variable will have no effect if `org-log-into-drawer' is
3060 set."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-log-states-order-reversed t
3066 "Non-nil means the latest state note will be directly after heading.
3067 When nil, the state change notes will be ordered according to time.
3069 This option can also be set with on a per-file-basis with
3071 #+STARTUP: logstatesreversed
3072 #+STARTUP: nologstatesreversed"
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type 'boolean)
3077 (defcustom org-todo-repeat-to-state nil
3078 "The TODO state to which a repeater should return the repeating task.
3079 By default this is the first task in a TODO sequence, or the previous state
3080 in a TODO_TYP set. But you can specify another task here.
3081 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3082 :group 'org-todo
3083 :version "24.1"
3084 :type '(choice (const :tag "Head of sequence" nil)
3085 (string :tag "Specific state")))
3087 (defcustom org-log-repeat 'time
3088 "Non-nil means record moving through the DONE state when triggering repeat.
3089 An auto-repeating task is immediately switched back to TODO when
3090 marked DONE. If you are not logging state changes (by adding \"@\"
3091 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3092 record a closing note, there will be no record of the task moving
3093 through DONE. This variable forces taking a note anyway.
3095 nil Don't force a record
3096 time Record a time stamp
3097 note Prompt for a note and add it with template `org-log-note-headings'
3099 This option can also be set with on a per-file-basis with
3101 #+STARTUP: nologrepeat
3102 #+STARTUP: logrepeat
3103 #+STARTUP: lognoterepeat
3105 You can have local logging settings for a subtree by setting the LOGGING
3106 property to one or more of these keywords."
3107 :group 'org-todo
3108 :group 'org-progress
3109 :type '(choice
3110 (const :tag "Don't force a record" nil)
3111 (const :tag "Force recording the DONE state" time)
3112 (const :tag "Force recording a note with the DONE state" note)))
3115 (defgroup org-priorities nil
3116 "Priorities in Org mode."
3117 :tag "Org Priorities"
3118 :group 'org-todo)
3120 (defcustom org-enable-priority-commands t
3121 "Non-nil means priority commands are active.
3122 When nil, these commands will be disabled, so that you never accidentally
3123 set a priority."
3124 :group 'org-priorities
3125 :type 'boolean)
3127 (defcustom org-highest-priority ?A
3128 "The highest priority of TODO items. A character like ?A, ?B etc.
3129 Must have a smaller ASCII number than `org-lowest-priority'."
3130 :group 'org-priorities
3131 :type 'character)
3133 (defcustom org-lowest-priority ?C
3134 "The lowest priority of TODO items. A character like ?A, ?B etc.
3135 Must have a larger ASCII number than `org-highest-priority'."
3136 :group 'org-priorities
3137 :type 'character)
3139 (defcustom org-default-priority ?B
3140 "The default priority of TODO items.
3141 This is the priority an item gets if no explicit priority is given.
3142 When starting to cycle on an empty priority the first step in the cycle
3143 depends on `org-priority-start-cycle-with-default'. The resulting first
3144 step priority must not exceed the range from `org-highest-priority' to
3145 `org-lowest-priority' which means that `org-default-priority' has to be
3146 in this range exclusive or inclusive the range boundaries. Else the
3147 first step refuses to set the default and the second will fall back
3148 to (depending on the command used) the highest or lowest priority."
3149 :group 'org-priorities
3150 :type 'character)
3152 (defcustom org-priority-start-cycle-with-default t
3153 "Non-nil means start with default priority when starting to cycle.
3154 When this is nil, the first step in the cycle will be (depending on the
3155 command used) one higher or lower than the default priority.
3156 See also `org-default-priority'."
3157 :group 'org-priorities
3158 :type 'boolean)
3160 (defcustom org-get-priority-function nil
3161 "Function to extract the priority from a string.
3162 The string is normally the headline. If this is nil Org computes the
3163 priority from the priority cookie like [#A] in the headline. It returns
3164 an integer, increasing by 1000 for each priority level.
3165 The user can set a different function here, which should take a string
3166 as an argument and return the numeric priority."
3167 :group 'org-priorities
3168 :version "24.1"
3169 :type '(choice
3170 (const nil)
3171 (function)))
3173 (defgroup org-time nil
3174 "Options concerning time stamps and deadlines in Org mode."
3175 :tag "Org Time"
3176 :group 'org)
3178 (defcustom org-time-stamp-rounding-minutes '(0 5)
3179 "Number of minutes to round time stamps to.
3180 \\<org-mode-map>\
3181 These are two values, the first applies when first creating a time stamp.
3182 The second applies when changing it with the commands `S-up' and `S-down'.
3183 When changing the time stamp, this means that it will change in steps
3184 of N minutes, as given by the second value.
3186 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3187 numbers should be factors of 60, so for example 5, 10, 15.
3189 When this is larger than 1, you can still force an exact time stamp by using
3190 a double prefix argument to a time stamp command like \
3191 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3192 and by using a prefix arg to `S-up/down' to specify the exact number
3193 of minutes to shift."
3194 :group 'org-time
3195 :get (lambda (var) ; Make sure both elements are there
3196 (if (integerp (default-value var))
3197 (list (default-value var) 5)
3198 (default-value var)))
3199 :type '(list
3200 (integer :tag "when inserting times")
3201 (integer :tag "when modifying times")))
3203 ;; Normalize old customizations of this variable.
3204 (when (integerp org-time-stamp-rounding-minutes)
3205 (setq org-time-stamp-rounding-minutes
3206 (list org-time-stamp-rounding-minutes
3207 org-time-stamp-rounding-minutes)))
3209 (defcustom org-display-custom-times nil
3210 "Non-nil means overlay custom formats over all time stamps.
3211 The formats are defined through the variable `org-time-stamp-custom-formats'.
3212 To turn this on on a per-file basis, insert anywhere in the file:
3213 #+STARTUP: customtime"
3214 :group 'org-time
3215 :set 'set-default
3216 :type 'sexp)
3217 (make-variable-buffer-local 'org-display-custom-times)
3219 (defcustom org-time-stamp-custom-formats
3220 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3221 "Custom formats for time stamps. See `format-time-string' for the syntax.
3222 These are overlaid over the default ISO format if the variable
3223 `org-display-custom-times' is set. Time like %H:%M should be at the
3224 end of the second format. The custom formats are also honored by export
3225 commands, if custom time display is turned on at the time of export."
3226 :group 'org-time
3227 :type 'sexp)
3229 (defun org-time-stamp-format (&optional long inactive)
3230 "Get the right format for a time string."
3231 (let ((f (if long (cdr org-time-stamp-formats)
3232 (car org-time-stamp-formats))))
3233 (if inactive
3234 (concat "[" (substring f 1 -1) "]")
3235 f)))
3237 (defcustom org-deadline-warning-days 14
3238 "Number of days before expiration during which a deadline becomes active.
3239 This variable governs the display in sparse trees and in the agenda.
3240 When 0 or negative, it means use this number (the absolute value of it)
3241 even if a deadline has a different individual lead time specified.
3243 Custom commands can set this variable in the options section."
3244 :group 'org-time
3245 :group 'org-agenda-daily/weekly
3246 :type 'integer)
3248 (defcustom org-scheduled-delay-days 0
3249 "Number of days before a scheduled item becomes active.
3250 This variable governs the display in sparse trees and in the agenda.
3251 The default value (i.e. 0) means: don't delay scheduled item.
3252 When negative, it means use this number (the absolute value of it)
3253 even if a scheduled item has a different individual delay time
3254 specified.
3256 Custom commands can set this variable in the options section."
3257 :group 'org-time
3258 :group 'org-agenda-daily/weekly
3259 :version "24.4"
3260 :package-version '(Org . "8.0")
3261 :type 'integer)
3263 (defcustom org-read-date-prefer-future t
3264 "Non-nil means assume future for incomplete date input from user.
3265 This affects the following situations:
3266 1. The user gives a month but not a year.
3267 For example, if it is April and you enter \"feb 2\", this will be read
3268 as Feb 2, *next* year. \"May 5\", however, will be this year.
3269 2. The user gives a day, but no month.
3270 For example, if today is the 15th, and you enter \"3\", Org will read
3271 this as the third of *next* month. However, if you enter \"17\",
3272 it will be considered as *this* month.
3274 If you set this variable to the symbol `time', then also the following
3275 will work:
3277 3. If the user gives a time.
3278 If the time is before now, it will be interpreted as tomorrow.
3280 Currently none of this works for ISO week specifications.
3282 When this option is nil, the current day, month and year will always be
3283 used as defaults.
3285 See also `org-agenda-jump-prefer-future'."
3286 :group 'org-time
3287 :type '(choice
3288 (const :tag "Never" nil)
3289 (const :tag "Check month and day" t)
3290 (const :tag "Check month, day, and time" time)))
3292 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3293 "Should the agenda jump command prefer the future for incomplete dates?
3294 The default is to do the same as configured in `org-read-date-prefer-future'.
3295 But you can also set a deviating value here.
3296 This may t or nil, or the symbol `org-read-date-prefer-future'."
3297 :group 'org-agenda
3298 :group 'org-time
3299 :version "24.1"
3300 :type '(choice
3301 (const :tag "Use org-read-date-prefer-future"
3302 org-read-date-prefer-future)
3303 (const :tag "Never" nil)
3304 (const :tag "Always" t)))
3306 (defcustom org-read-date-force-compatible-dates t
3307 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3309 Depending on the system Emacs is running on, certain dates cannot
3310 be represented with the type used internally to represent time.
3311 Dates between 1970-1-1 and 2038-1-1 can always be represented
3312 correctly. Some systems allow for earlier dates, some for later,
3313 some for both. One way to find out it to insert any date into an
3314 Org buffer, putting the cursor on the year and hitting S-up and
3315 S-down to test the range.
3317 When this variable is set to t, the date/time prompt will not let
3318 you specify dates outside the 1970-2037 range, so it is certain that
3319 these dates will work in whatever version of Emacs you are
3320 running, and also that you can move a file from one Emacs implementation
3321 to another. WHenever Org is forcing the year for you, it will display
3322 a message and beep.
3324 When this variable is nil, Org will check if the date is
3325 representable in the specific Emacs implementation you are using.
3326 If not, it will force a year, usually the current year, and beep
3327 to remind you. Currently this setting is not recommended because
3328 the likelihood that you will open your Org files in an Emacs that
3329 has limited date range is not negligible.
3331 A workaround for this problem is to use diary sexp dates for time
3332 stamps outside of this range."
3333 :group 'org-time
3334 :version "24.1"
3335 :type 'boolean)
3337 (defcustom org-read-date-display-live t
3338 "Non-nil means display current interpretation of date prompt live.
3339 This display will be in an overlay, in the minibuffer."
3340 :group 'org-time
3341 :type 'boolean)
3343 (defcustom org-read-date-popup-calendar t
3344 "Non-nil means pop up a calendar when prompting for a date.
3345 In the calendar, the date can be selected with mouse-1. However, the
3346 minibuffer will also be active, and you can simply enter the date as well.
3347 When nil, only the minibuffer will be available."
3348 :group 'org-time
3349 :type 'boolean)
3350 (defvaralias 'org-popup-calendar-for-date-prompt
3351 'org-read-date-popup-calendar)
3353 (defcustom org-extend-today-until 0
3354 "The hour when your day really ends. Must be an integer.
3355 This has influence for the following applications:
3356 - When switching the agenda to \"today\". It it is still earlier than
3357 the time given here, the day recognized as TODAY is actually yesterday.
3358 - When a date is read from the user and it is still before the time given
3359 here, the current date and time will be assumed to be yesterday, 23:59.
3360 Also, timestamps inserted in capture templates follow this rule.
3362 IMPORTANT: This is a feature whose implementation is and likely will
3363 remain incomplete. Really, it is only here because past midnight seems to
3364 be the favorite working time of John Wiegley :-)"
3365 :group 'org-time
3366 :type 'integer)
3368 (defcustom org-use-effective-time nil
3369 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3370 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3371 \"effective time\" of any timestamps between midnight and 8am will be
3372 23:59 of the previous day."
3373 :group 'org-time
3374 :version "24.1"
3375 :type 'boolean)
3377 (defcustom org-use-last-clock-out-time-as-effective-time nil
3378 "When non-nil, use the last clock out time for `org-todo'.
3379 Note that this option has precedence over the combined use of
3380 `org-use-effective-time' and `org-extend-today-until'."
3381 :group 'org-time
3382 :version "24.4"
3383 :package-version '(Org . "8.0")
3384 :type 'boolean)
3386 (defcustom org-edit-timestamp-down-means-later nil
3387 "Non-nil means S-down will increase the time in a time stamp.
3388 When nil, S-up will increase."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defcustom org-calendar-follow-timestamp-change t
3393 "Non-nil means make the calendar window follow timestamp changes.
3394 When a timestamp is modified and the calendar window is visible, it will be
3395 moved to the new date."
3396 :group 'org-time
3397 :type 'boolean)
3399 (defgroup org-tags nil
3400 "Options concerning tags in Org mode."
3401 :tag "Org Tags"
3402 :group 'org)
3404 (defcustom org-tag-alist nil
3405 "Default tags available in Org files.
3407 The value of this variable is an alist. Associations either:
3409 (TAG)
3410 (TAG . SELECT)
3411 (SPECIAL)
3413 where TAG is a tag as a string, SELECT is character, used to
3414 select that tag through the fast tag selection interface, and
3415 SPECIAL is one of the following keywords: `:startgroup',
3416 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3417 `:newline'. These keywords are used to define a hierarchy of
3418 tags. See manual for details.
3420 When this variable is nil, Org mode bases tag input on what is
3421 already in the buffer. The value can be overridden locally by
3422 using a TAGS keyword, e.g.,
3424 #+TAGS: tag1 tag2
3426 See also `org-tag-persistent-alist' to sidestep this behavior."
3427 :group 'org-tags
3428 :type '(repeat
3429 (choice
3430 (cons :tag "Tag with key"
3431 (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (list :tag "Tag" (string :tag "Tag name"))
3434 (const :tag "Start radio group" (:startgroup))
3435 (const :tag "Start tag group, non distinct" (:startgrouptag))
3436 (const :tag "Group tags delimiter" (:grouptags))
3437 (const :tag "End radio group" (:endgroup))
3438 (const :tag "End tag group, non distinct" (:endgrouptag))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-tag-persistent-alist nil
3442 "Tags always available in Org files.
3444 The value of this variable is an alist. Associations either:
3446 (TAG)
3447 (TAG . SELECT)
3448 (SPECIAL)
3450 where TAG is a tag as a string, SELECT is a character, used to
3451 select that tag through the fast tag selection interface, and
3452 SPECIAL is one of the following keywords: `:startgroup',
3453 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3454 `:newline'. These keywords are used to define a hierarchy of
3455 tags. See manual for details.
3457 Unlike to `org-tag-alist', tags defined in this variable do not
3458 depend on a local TAGS keyword. Instead, to disable these tags
3459 on a per-file basis, insert anywhere in the file:
3461 #+STARTUP: noptag"
3462 :group 'org-tags
3463 :type '(repeat
3464 (choice
3465 (cons :tag "Tag with key"
3466 (string :tag "Tag name")
3467 (character :tag "Access char"))
3468 (list :tag "Tag" (string :tag "Tag name"))
3469 (const :tag "Start radio group" (:startgroup))
3470 (const :tag "Start tag group, non distinct" (:startgrouptag))
3471 (const :tag "Group tags delimiter" (:grouptags))
3472 (const :tag "End radio group" (:endgroup))
3473 (const :tag "End tag group, non distinct" (:endgrouptag))
3474 (const :tag "New line" (:newline)))))
3476 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3477 "If non-nil, always offer completion for all tags of all agenda files.
3478 Instead of customizing this variable directly, you might want to
3479 set it locally for capture buffers, because there no list of
3480 tags in that file can be created dynamically (there are none).
3482 (add-hook \\='org-capture-mode-hook
3483 (lambda ()
3484 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3485 :group 'org-tags
3486 :version "24.1"
3487 :type 'boolean)
3489 (defvar org-file-tags nil
3490 "List of tags that can be inherited by all entries in the file.
3491 The tags will be inherited if the variable `org-use-tag-inheritance'
3492 says they should be.
3493 This variable is populated from #+FILETAGS lines.")
3495 (defcustom org-use-fast-tag-selection 'auto
3496 "Non-nil means use fast tag selection scheme.
3497 This is a special interface to select and deselect tags with single keys.
3498 When nil, fast selection is never used.
3499 When the symbol `auto', fast selection is used if and only if selection
3500 characters for tags have been configured, either through the variable
3501 `org-tag-alist' or through a #+TAGS line in the buffer.
3502 When t, fast selection is always used and selection keys are assigned
3503 automatically if necessary."
3504 :group 'org-tags
3505 :type '(choice
3506 (const :tag "Always" t)
3507 (const :tag "Never" nil)
3508 (const :tag "When selection characters are configured" auto)))
3510 (defcustom org-fast-tag-selection-single-key nil
3511 "Non-nil means fast tag selection exits after first change.
3512 When nil, you have to press RET to exit it.
3513 During fast tag selection, you can toggle this flag with `C-c'.
3514 This variable can also have the value `expert'. In this case, the window
3515 displaying the tags menu is not even shown, until you press C-c again."
3516 :group 'org-tags
3517 :type '(choice
3518 (const :tag "No" nil)
3519 (const :tag "Yes" t)
3520 (const :tag "Expert" expert)))
3522 (defvar org-fast-tag-selection-include-todo nil
3523 "Non-nil means fast tags selection interface will also offer TODO states.
3524 This is an undocumented feature, you should not rely on it.")
3526 (defcustom org-tags-column -77
3527 "The column to which tags should be indented in a headline.
3528 If this number is positive, it specifies the column. If it is negative,
3529 it means that the tags should be flushright to that column. For example,
3530 -80 works well for a normal 80 character screen.
3531 When 0, place tags directly after headline text, with only one space in
3532 between."
3533 :group 'org-tags
3534 :type 'integer)
3536 (defcustom org-auto-align-tags t
3537 "Non-nil keeps tags aligned when modifying headlines.
3538 Some operations (i.e. demoting) change the length of a headline and
3539 therefore shift the tags around. With this option turned on, after
3540 each such operation the tags are again aligned to `org-tags-column'."
3541 :group 'org-tags
3542 :type 'boolean)
3544 (defcustom org-use-tag-inheritance t
3545 "Non-nil means tags in levels apply also for sublevels.
3546 When nil, only the tags directly given in a specific line apply there.
3547 This may also be a list of tags that should be inherited, or a regexp that
3548 matches tags that should be inherited. Additional control is possible
3549 with the variable `org-tags-exclude-from-inheritance' which gives an
3550 explicit list of tags to be excluded from inheritance, even if the value of
3551 `org-use-tag-inheritance' would select it for inheritance.
3553 If this option is t, a match early-on in a tree can lead to a large
3554 number of matches in the subtree when constructing the agenda or creating
3555 a sparse tree. If you only want to see the first match in a tree during
3556 a search, check out the variable `org-tags-match-list-sublevels'."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "Not" nil)
3560 (const :tag "Always" t)
3561 (repeat :tag "Specific tags" (string :tag "Tag"))
3562 (regexp :tag "Tags matched by regexp")))
3564 (defcustom org-tags-exclude-from-inheritance nil
3565 "List of tags that should never be inherited.
3566 This is a way to exclude a few tags from inheritance. For way to do
3567 the opposite, to actively allow inheritance for selected tags,
3568 see the variable `org-use-tag-inheritance'."
3569 :group 'org-tags
3570 :type '(repeat (string :tag "Tag")))
3572 (defun org-tag-inherit-p (tag)
3573 "Check if TAG is one that should be inherited."
3574 (cond
3575 ((member tag org-tags-exclude-from-inheritance) nil)
3576 ((eq org-use-tag-inheritance t) t)
3577 ((not org-use-tag-inheritance) nil)
3578 ((stringp org-use-tag-inheritance)
3579 (string-match org-use-tag-inheritance tag))
3580 ((listp org-use-tag-inheritance)
3581 (member tag org-use-tag-inheritance))
3582 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3584 (defcustom org-tags-match-list-sublevels t
3585 "Non-nil means list also sublevels of headlines matching a search.
3586 This variable applies to tags/property searches, and also to stuck
3587 projects because this search is based on a tags match as well.
3589 When set to the symbol `indented', sublevels are indented with
3590 leading dots.
3592 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3593 the sublevels of a headline matching a tag search often also match
3594 the same search. Listing all of them can create very long lists.
3595 Setting this variable to nil causes subtrees of a match to be skipped.
3597 This variable is semi-obsolete and probably should always be true. It
3598 is better to limit inheritance to certain tags using the variables
3599 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3600 :group 'org-tags
3601 :type '(choice
3602 (const :tag "No, don't list them" nil)
3603 (const :tag "Yes, do list them" t)
3604 (const :tag "List them, indented with leading dots" indented)))
3606 (defcustom org-tags-sort-function nil
3607 "When set, tags are sorted using this function as a comparator."
3608 :group 'org-tags
3609 :type '(choice
3610 (const :tag "No sorting" nil)
3611 (const :tag "Alphabetical" string<)
3612 (const :tag "Reverse alphabetical" string>)
3613 (function :tag "Custom function" nil)))
3615 (defvar org-tags-history nil
3616 "History of minibuffer reads for tags.")
3617 (defvar org-last-tags-completion-table nil
3618 "The last used completion table for tags.")
3619 (defvar org-after-tags-change-hook nil
3620 "Hook that is run after the tags in a line have changed.")
3622 (defgroup org-properties nil
3623 "Options concerning properties in Org mode."
3624 :tag "Org Properties"
3625 :group 'org)
3627 (defcustom org-property-format "%-10s %s"
3628 "How property key/value pairs should be formatted by `indent-line'.
3629 When `indent-line' hits a property definition, it will format the line
3630 according to this format, mainly to make sure that the values are
3631 lined-up with respect to each other."
3632 :group 'org-properties
3633 :type 'string)
3635 (defcustom org-properties-postprocess-alist nil
3636 "Alist of properties and functions to adjust inserted values.
3637 Elements of this alist must be of the form
3639 ([string] [function])
3641 where [string] must be a property name and [function] must be a
3642 lambda expression: this lambda expression must take one argument,
3643 the value to adjust, and return the new value as a string.
3645 For example, this element will allow the property \"Remaining\"
3646 to be updated wrt the relation between the \"Effort\" property
3647 and the clock summary:
3649 ((\"Remaining\" (lambda(value)
3650 (let ((clocksum (org-clock-sum-current-item))
3651 (effort (org-duration-to-minutes
3652 (org-entry-get (point) \"Effort\"))))
3653 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3654 :group 'org-properties
3655 :version "24.1"
3656 :type '(alist :key-type (string :tag "Property")
3657 :value-type (function :tag "Function")))
3659 (defcustom org-use-property-inheritance nil
3660 "Non-nil means properties apply also for sublevels.
3662 This setting is chiefly used during property searches. Turning it on can
3663 cause significant overhead when doing a search, which is why it is not
3664 on by default.
3666 When nil, only the properties directly given in the current entry count.
3667 When t, every property is inherited. The value may also be a list of
3668 properties that should have inheritance, or a regular expression matching
3669 properties that should be inherited.
3671 However, note that some special properties use inheritance under special
3672 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3673 and the properties ending in \"_ALL\" when they are used as descriptor
3674 for valid values of a property.
3676 Note for programmers:
3677 When querying an entry with `org-entry-get', you can control if inheritance
3678 should be used. By default, `org-entry-get' looks only at the local
3679 properties. You can request inheritance by setting the inherit argument
3680 to t (to force inheritance) or to `selective' (to respect the setting
3681 in this variable)."
3682 :group 'org-properties
3683 :type '(choice
3684 (const :tag "Not" nil)
3685 (const :tag "Always" t)
3686 (repeat :tag "Specific properties" (string :tag "Property"))
3687 (regexp :tag "Properties matched by regexp")))
3689 (defun org-property-inherit-p (property)
3690 "Return a non-nil value if PROPERTY should be inherited."
3691 (cond
3692 ((eq org-use-property-inheritance t) t)
3693 ((not org-use-property-inheritance) nil)
3694 ((stringp org-use-property-inheritance)
3695 (string-match org-use-property-inheritance property))
3696 ((listp org-use-property-inheritance)
3697 (member-ignore-case property org-use-property-inheritance))
3698 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3700 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3701 "The default column format, if no other format has been defined.
3702 This variable can be set on the per-file basis by inserting a line
3704 #+COLUMNS: %25ITEM ....."
3705 :group 'org-properties
3706 :type 'string)
3708 (defcustom org-columns-ellipses ".."
3709 "The ellipses to be used when a field in column view is truncated.
3710 When this is the empty string, as many characters as possible are shown,
3711 but then there will be no visual indication that the field has been truncated.
3712 When this is a string of length N, the last N characters of a truncated
3713 field are replaced by this string. If the column is narrower than the
3714 ellipses string, only part of the ellipses string will be shown."
3715 :group 'org-properties
3716 :type 'string)
3718 (defconst org-global-properties-fixed
3719 '(("VISIBILITY_ALL" . "folded children content all")
3720 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3721 "List of property/value pairs that can be inherited by any entry.
3723 These are fixed values, for the preset properties. The user variable
3724 that can be used to add to this list is `org-global-properties'.
3726 The entries in this list are cons cells where the car is a property
3727 name and cdr is a string with the value. If the value represents
3728 multiple items like an \"_ALL\" property, separate the items by
3729 spaces.")
3731 (defcustom org-global-properties nil
3732 "List of property/value pairs that can be inherited by any entry.
3734 This list will be combined with the constant `org-global-properties-fixed'.
3736 The entries in this list are cons cells where the car is a property
3737 name and cdr is a string with the value.
3739 You can set buffer-local values for the same purpose in the variable
3740 `org-file-properties' this by adding lines like
3742 #+PROPERTY: NAME VALUE"
3743 :group 'org-properties
3744 :type '(repeat
3745 (cons (string :tag "Property")
3746 (string :tag "Value"))))
3748 (defvar-local org-file-properties nil
3749 "List of property/value pairs that can be inherited by any entry.
3750 Valid for the current buffer.
3751 This variable is populated from #+PROPERTY lines.")
3753 (defgroup org-agenda nil
3754 "Options concerning agenda views in Org mode."
3755 :tag "Org Agenda"
3756 :group 'org)
3758 (defvar-local org-category nil
3759 "Variable used by org files to set a category for agenda display.
3760 Such files should use a file variable to set it, for example
3762 # -*- mode: org; org-category: \"ELisp\"
3764 or contain a special line
3766 #+CATEGORY: ELisp
3768 If the file does not specify a category, then file's base name
3769 is used instead.")
3770 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3772 (defcustom org-agenda-files nil
3773 "The files to be used for agenda display.
3775 If an entry is a directory, all files in that directory that are matched
3776 by `org-agenda-file-regexp' will be part of the file list.
3778 If the value of the variable is not a list but a single file name, then
3779 the list of agenda files is actually stored and maintained in that file,
3780 one agenda file per line. In this file paths can be given relative to
3781 `org-directory'. Tilde expansion and environment variable substitution
3782 are also made.
3784 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3785 and removed with `\\[org-remove-file]'."
3786 :group 'org-agenda
3787 :type '(choice
3788 (repeat :tag "List of files and directories" file)
3789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3792 "Regular expression to match files for `org-agenda-files'.
3793 If any element in the list in that variable contains a directory instead
3794 of a normal file, all files in that directory that are matched by this
3795 regular expression will be included."
3796 :group 'org-agenda
3797 :type 'regexp)
3799 (defcustom org-agenda-text-search-extra-files nil
3800 "List of extra files to be searched by text search commands.
3801 These files will be searched in addition to the agenda files by the
3802 commands `org-search-view' (`\\[org-agenda] s') \
3803 and `org-occur-in-agenda-files'.
3804 Note that these files will only be searched for text search commands,
3805 not for the other agenda views like todo lists, tag searches or the weekly
3806 agenda. This variable is intended to list notes and possibly archive files
3807 that should also be searched by these two commands.
3808 In fact, if the first element in the list is the symbol `agenda-archives',
3809 then all archive files of all agenda files will be added to the search
3810 scope."
3811 :group 'org-agenda
3812 :type '(set :greedy t
3813 (const :tag "Agenda Archives" agenda-archives)
3814 (repeat :inline t (file))))
3816 (defvaralias 'org-agenda-multi-occur-extra-files
3817 'org-agenda-text-search-extra-files)
3819 (defcustom org-agenda-skip-unavailable-files nil
3820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3821 A nil value means to remove them, after a query, from the list."
3822 :group 'org-agenda
3823 :type 'boolean)
3825 (defcustom org-calendar-to-agenda-key [?c]
3826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3827 The command `org-calendar-goto-agenda' will be bound to this key. The
3828 default is the character `c' because then `c' can be used to switch back and
3829 forth between agenda and calendar."
3830 :group 'org-agenda
3831 :type 'sexp)
3833 (defcustom org-calendar-insert-diary-entry-key [?i]
3834 "The key to be installed in `calendar-mode-map' for adding diary entries.
3835 This option is irrelevant until `org-agenda-diary-file' has been configured
3836 to point to an Org file. When that is the case, the command
3837 `org-agenda-diary-entry' will be bound to the key given here, by default
3838 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3839 if you want to continue doing this, you need to change this to a different
3840 key."
3841 :group 'org-agenda
3842 :type 'sexp)
3844 (defcustom org-agenda-diary-file 'diary-file
3845 "File to which to add new entries with the `i' key in agenda and calendar.
3846 When this is the symbol `diary-file', the functionality in the Emacs
3847 calendar will be used to add entries to the `diary-file'. But when this
3848 points to a file, `org-agenda-diary-entry' will be used instead."
3849 :group 'org-agenda
3850 :type '(choice
3851 (const :tag "The standard Emacs diary file" diary-file)
3852 (file :tag "Special Org file diary entries")))
3854 (eval-after-load "calendar"
3855 '(progn
3856 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3857 'org-calendar-goto-agenda)
3858 (add-hook 'calendar-mode-hook
3859 (lambda ()
3860 (unless (eq org-agenda-diary-file 'diary-file)
3861 (define-key calendar-mode-map
3862 org-calendar-insert-diary-entry-key
3863 'org-agenda-diary-entry))))))
3865 (defgroup org-latex nil
3866 "Options for embedding LaTeX code into Org mode."
3867 :tag "Org LaTeX"
3868 :group 'org)
3870 (defcustom org-format-latex-options
3871 '(:foreground default :background default :scale 1.0
3872 :html-foreground "Black" :html-background "Transparent"
3873 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3874 "Options for creating images from LaTeX fragments.
3875 This is a property list with the following properties:
3876 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3877 `default' means use the foreground of the default face.
3878 `auto' means use the foreground from the text face.
3879 :background the background color, or \"Transparent\".
3880 `default' means use the background of the default face.
3881 `auto' means use the background from the text face.
3882 :scale a scaling factor for the size of the images, to get more pixels
3883 :html-foreground, :html-background, :html-scale
3884 the same numbers for HTML export.
3885 :matchers a list indicating which matchers should be used to
3886 find LaTeX fragments. Valid members of this list are:
3887 \"begin\" find environments
3888 \"$1\" find single characters surrounded by $.$
3889 \"$\" find math expressions surrounded by $...$
3890 \"$$\" find math expressions surrounded by $$....$$
3891 \"\\(\" find math expressions surrounded by \\(...\\)
3892 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3893 :group 'org-latex
3894 :type 'plist)
3896 (defcustom org-format-latex-signal-error t
3897 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3898 When nil, just push out a message."
3899 :group 'org-latex
3900 :version "24.1"
3901 :type 'boolean)
3903 (defcustom org-latex-to-mathml-jar-file nil
3904 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3905 Use this to specify additional executable file say a jar file.
3907 When using MathToWeb as the converter, specify the full-path to
3908 your mathtoweb.jar file."
3909 :group 'org-latex
3910 :version "24.1"
3911 :type '(choice
3912 (const :tag "None" nil)
3913 (file :tag "JAR file" :must-match t)))
3915 (defcustom org-latex-to-mathml-convert-command nil
3916 "Command to convert LaTeX fragments to MathML.
3917 Replace format-specifiers in the command as noted below and use
3918 `shell-command' to convert LaTeX to MathML.
3919 %j: Executable file in fully expanded form as specified by
3920 `org-latex-to-mathml-jar-file'.
3921 %I: Input LaTeX file in fully expanded form.
3922 %i: The latex fragment to be converted.
3923 %o: Output MathML file.
3925 This command is used by `org-create-math-formula'.
3927 When using MathToWeb as the converter, set this option to
3928 \"java -jar %j -unicode -force -df %o %I\".
3930 When using LaTeXML set this option to
3931 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3932 :group 'org-latex
3933 :version "24.1"
3934 :type '(choice
3935 (const :tag "None" nil)
3936 (string :tag "\nShell command")))
3938 (defcustom org-preview-latex-default-process 'dvipng
3939 "The default process to convert LaTeX fragments to image files.
3940 All available processes and theirs documents can be found in
3941 `org-preview-latex-process-alist', which see."
3942 :group 'org-latex
3943 :version "26.1"
3944 :package-version '(Org . "9.0")
3945 :type 'symbol)
3947 (defcustom org-preview-latex-process-alist
3948 '((dvipng
3949 :programs ("latex" "dvipng")
3950 :description "dvi > png"
3951 :message "you need to install the programs: latex and dvipng."
3952 :image-input-type "dvi"
3953 :image-output-type "png"
3954 :image-size-adjust (1.0 . 1.0)
3955 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3956 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3957 (dvisvgm
3958 :programs ("latex" "dvisvgm")
3959 :description "dvi > svg"
3960 :message "you need to install the programs: latex and dvisvgm."
3961 :use-xcolor t
3962 :image-input-type "dvi"
3963 :image-output-type "svg"
3964 :image-size-adjust (1.7 . 1.5)
3965 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3966 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3967 (imagemagick
3968 :programs ("latex" "convert")
3969 :description "pdf > png"
3970 :message "you need to install the programs: latex and imagemagick."
3971 :use-xcolor t
3972 :image-input-type "pdf"
3973 :image-output-type "png"
3974 :image-size-adjust (1.0 . 1.0)
3975 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3976 :image-converter
3977 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3978 "Definitions of external processes for LaTeX previewing.
3979 Org mode can use some external commands to generate TeX snippet's images for
3980 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3981 `org-create-formula-image' how to call them.
3983 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3984 PROPERTIES accepts the following attributes:
3986 :programs list of strings, required programs.
3987 :description string, describe the process.
3988 :message string, message it when required programs cannot be found.
3989 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3990 :image-output-type string, output file type of image converter (e.g., \"png\").
3991 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3992 deal with background and foreground color of image.
3993 Otherwise, dvipng style background and foreground color
3994 format are generated. You may then refer to them in
3995 command options with \"%F\" and \"%B\".
3996 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3997 image size showed in buffer and the cdr element is for
3998 HTML file. This option is only useful for process
3999 developers, users should use variable
4000 `org-format-latex-options' instead.
4001 :post-clean list of strings, files matched are to be cleaned up once
4002 the image is generated. When nil, the files with \".dvi\",
4003 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4004 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4005 be cleaned up.
4006 :latex-header list of strings, the LaTeX header of the snippet file.
4007 When nil, the fallback value is used instead, which is
4008 controlled by `org-format-latex-header',
4009 `org-latex-default-packages-alist' and
4010 `org-latex-packages-alist', which see.
4011 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4012 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4013 replaced with values defined below.
4014 :image-converter list of image converter commands strings. Each of them is
4015 given to the shell and supports any of the following
4016 place-holders defined below.
4018 Place-holders used by `:image-converter' and `:latex-compiler':
4020 %f input file name
4021 %b base name of input file
4022 %o base directory of input file
4023 %O absolute output file name
4025 Place-holders only used by `:image-converter':
4027 %F foreground of image
4028 %B background of image
4029 %D dpi, which is used to adjust image size by some processing commands.
4030 %S the image size scale ratio, which is used to adjust image size by some
4031 processing commands."
4032 :group 'org-latex
4033 :version "26.1"
4034 :package-version '(Org . "9.0")
4035 :type '(alist :tag "LaTeX to image backends"
4036 :value-type (plist)))
4038 (defcustom org-preview-latex-image-directory "ltximg/"
4039 "Path to store latex preview images.
4040 A relative path here creates many directories relative to the
4041 processed org files paths. An absolute path puts all preview
4042 images at the same place."
4043 :group 'org-latex
4044 :version "26.1"
4045 :package-version '(Org . "9.0")
4046 :type 'string)
4048 (defun org-format-latex-mathml-available-p ()
4049 "Return t if `org-latex-to-mathml-convert-command' is usable."
4050 (save-match-data
4051 (when (and (boundp 'org-latex-to-mathml-convert-command)
4052 org-latex-to-mathml-convert-command)
4053 (let ((executable (car (split-string
4054 org-latex-to-mathml-convert-command))))
4055 (when (executable-find executable)
4056 (if (string-match
4057 "%j" org-latex-to-mathml-convert-command)
4058 (file-readable-p org-latex-to-mathml-jar-file)
4059 t))))))
4061 (defcustom org-format-latex-header "\\documentclass{article}
4062 \\usepackage[usenames]{color}
4063 \[PACKAGES]
4064 \[DEFAULT-PACKAGES]
4065 \\pagestyle{empty} % do not remove
4066 % The settings below are copied from fullpage.sty
4067 \\setlength{\\textwidth}{\\paperwidth}
4068 \\addtolength{\\textwidth}{-3cm}
4069 \\setlength{\\oddsidemargin}{1.5cm}
4070 \\addtolength{\\oddsidemargin}{-2.54cm}
4071 \\setlength{\\evensidemargin}{\\oddsidemargin}
4072 \\setlength{\\textheight}{\\paperheight}
4073 \\addtolength{\\textheight}{-\\headheight}
4074 \\addtolength{\\textheight}{-\\headsep}
4075 \\addtolength{\\textheight}{-\\footskip}
4076 \\addtolength{\\textheight}{-3cm}
4077 \\setlength{\\topmargin}{1.5cm}
4078 \\addtolength{\\topmargin}{-2.54cm}"
4079 "The document header used for processing LaTeX fragments.
4080 It is imperative that this header make sure that no page number
4081 appears on the page. The package defined in the variables
4082 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4083 will either replace the placeholder \"[PACKAGES]\" in this
4084 header, or they will be appended."
4085 :group 'org-latex
4086 :type 'string)
4088 (defun org-set-packages-alist (var val)
4089 "Set the packages alist and make sure it has 3 elements per entry."
4090 (set var (mapcar (lambda (x)
4091 (if (and (consp x) (= (length x) 2))
4092 (list (car x) (nth 1 x) t)
4094 val)))
4096 (defun org-get-packages-alist (var)
4097 "Get the packages alist and make sure it has 3 elements per entry."
4098 (mapcar (lambda (x)
4099 (if (and (consp x) (= (length x) 2))
4100 (list (car x) (nth 1 x) t)
4102 (default-value var)))
4104 (defcustom org-latex-default-packages-alist
4105 '(("AUTO" "inputenc" t ("pdflatex"))
4106 ("T1" "fontenc" t ("pdflatex"))
4107 ("" "graphicx" t)
4108 ("" "grffile" t)
4109 ("" "longtable" nil)
4110 ("" "wrapfig" nil)
4111 ("" "rotating" nil)
4112 ("normalem" "ulem" t)
4113 ("" "amsmath" t)
4114 ("" "textcomp" t)
4115 ("" "amssymb" t)
4116 ("" "capt-of" nil)
4117 ("" "hyperref" nil))
4118 "Alist of default packages to be inserted in the header.
4120 Change this only if one of the packages here causes an
4121 incompatibility with another package you are using.
4123 The packages in this list are needed by one part or another of
4124 Org mode to function properly:
4126 - inputenc, fontenc: for basic font and character selection
4127 - graphicx: for including images
4128 - grffile: allow periods and spaces in graphics file names
4129 - longtable: For multipage tables
4130 - wrapfig: for figure placement
4131 - rotating: for sideways figures and tables
4132 - ulem: for underline and strike-through
4133 - amsmath: for subscript and superscript and math environments
4134 - textcomp, amssymb: for various symbols used
4135 for interpreting the entities in `org-entities'. You can skip
4136 some of these packages if you don't use any of their symbols.
4137 - capt-of: for captions outside of floats
4138 - hyperref: for cross references
4140 Therefore you should not modify this variable unless you know
4141 what you are doing. The one reason to change it anyway is that
4142 you might be loading some other package that conflicts with one
4143 of the default packages. Each element is either a cell or
4144 a string.
4146 A cell is of the format
4148 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4150 If SNIPPET-FLAG is non-nil, the package also needs to be included
4151 when compiling LaTeX snippets into images for inclusion into
4152 non-LaTeX output. COMPILERS is a list of compilers that should
4153 include the package, see `org-latex-compiler'. If the document
4154 compiler is not in the list, and the list is non-nil, the package
4155 will not be inserted in the final document.
4157 A string will be inserted as-is in the header of the document."
4158 :group 'org-latex
4159 :group 'org-export-latex
4160 :set 'org-set-packages-alist
4161 :get 'org-get-packages-alist
4162 :version "26.1"
4163 :package-version '(Org . "8.3")
4164 :type '(repeat
4165 (choice
4166 (list :tag "options/package pair"
4167 (string :tag "options")
4168 (string :tag "package")
4169 (boolean :tag "Snippet"))
4170 (string :tag "A line of LaTeX"))))
4172 (defcustom org-latex-packages-alist nil
4173 "Alist of packages to be inserted in every LaTeX header.
4175 These will be inserted after `org-latex-default-packages-alist'.
4176 Each element is either a cell or a string.
4178 A cell is of the format:
4180 (\"options\" \"package\" SNIPPET-FLAG)
4182 SNIPPET-FLAG, when non-nil, indicates that this package is also
4183 needed when turning LaTeX snippets into images for inclusion into
4184 non-LaTeX output.
4186 A string will be inserted as-is in the header of the document.
4188 Make sure that you only list packages here which:
4190 - you want in every file;
4191 - do not conflict with the setup in `org-format-latex-header';
4192 - do not conflict with the default packages in
4193 `org-latex-default-packages-alist'."
4194 :group 'org-latex
4195 :group 'org-export-latex
4196 :set 'org-set-packages-alist
4197 :get 'org-get-packages-alist
4198 :type '(repeat
4199 (choice
4200 (list :tag "options/package pair"
4201 (string :tag "options")
4202 (string :tag "package")
4203 (boolean :tag "Snippet"))
4204 (string :tag "A line of LaTeX"))))
4206 (defgroup org-appearance nil
4207 "Settings for Org mode appearance."
4208 :tag "Org Appearance"
4209 :group 'org)
4211 (defcustom org-level-color-stars-only nil
4212 "Non-nil means fontify only the stars in each headline.
4213 When nil, the entire headline is fontified.
4214 Changing it requires restart of `font-lock-mode' to become effective
4215 also in regions already fontified."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-hide-leading-stars nil
4220 "Non-nil means hide the first N-1 stars in a headline.
4221 This works by using the face `org-hide' for these stars. This
4222 face is white for a light background, and black for a dark
4223 background. You may have to customize the face `org-hide' to
4224 make this work.
4225 Changing it requires restart of `font-lock-mode' to become effective
4226 also in regions already fontified.
4227 You may also set this on a per-file basis by adding one of the following
4228 lines to the buffer:
4230 #+STARTUP: hidestars
4231 #+STARTUP: showstars"
4232 :group 'org-appearance
4233 :type 'boolean)
4235 (defcustom org-hidden-keywords nil
4236 "List of symbols corresponding to keywords to be hidden the org buffer.
4237 For example, a value \\='(title) for this list will make the document's title
4238 appear in the buffer without the initial #+TITLE: keyword."
4239 :group 'org-appearance
4240 :version "24.1"
4241 :type '(set (const :tag "#+AUTHOR" author)
4242 (const :tag "#+DATE" date)
4243 (const :tag "#+EMAIL" email)
4244 (const :tag "#+TITLE" title)))
4246 (defcustom org-custom-properties nil
4247 "List of properties (as strings) with a special meaning.
4248 The default use of these custom properties is to let the user
4249 hide them with `org-toggle-custom-properties-visibility'."
4250 :group 'org-properties
4251 :group 'org-appearance
4252 :version "24.3"
4253 :type '(repeat (string :tag "Property Name")))
4255 (defcustom org-fontify-done-headline nil
4256 "Non-nil means change the face of a headline if it is marked DONE.
4257 Normally, only the TODO/DONE keyword indicates the state of a headline.
4258 When this is non-nil, the headline after the keyword is set to the
4259 `org-headline-done' as an additional indication."
4260 :group 'org-appearance
4261 :type 'boolean)
4263 (defcustom org-fontify-emphasized-text t
4264 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4265 Changing this variable requires a restart of Emacs to take effect."
4266 :group 'org-appearance
4267 :type 'boolean)
4269 (defcustom org-fontify-whole-heading-line nil
4270 "Non-nil means fontify the whole line for headings.
4271 This is useful when setting a background color for the
4272 org-level-* faces."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-highlight-latex-and-related nil
4277 "Non-nil means highlight LaTeX related syntax in the buffer.
4278 When non nil, the value should be a list containing any of the
4279 following symbols:
4280 `latex' Highlight LaTeX snippets and environments.
4281 `script' Highlight subscript and superscript.
4282 `entities' Highlight entities."
4283 :group 'org-appearance
4284 :version "24.4"
4285 :package-version '(Org . "8.0")
4286 :type '(choice
4287 (const :tag "No highlighting" nil)
4288 (set :greedy t :tag "Highlight"
4289 (const :tag "LaTeX snippets and environments" latex)
4290 (const :tag "Subscript and superscript" script)
4291 (const :tag "Entities" entities))))
4293 (defcustom org-hide-emphasis-markers nil
4294 "Non-nil mean font-lock should hide the emphasis marker characters."
4295 :group 'org-appearance
4296 :type 'boolean)
4298 (defcustom org-hide-macro-markers nil
4299 "Non-nil mean font-lock should hide the brackets marking macro calls."
4300 :group 'org-appearance
4301 :type 'boolean)
4303 (defcustom org-pretty-entities nil
4304 "Non-nil means show entities as UTF8 characters.
4305 When nil, the \\name form remains in the buffer."
4306 :group 'org-appearance
4307 :version "24.1"
4308 :type 'boolean)
4310 (defcustom org-pretty-entities-include-sub-superscripts t
4311 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4312 :group 'org-appearance
4313 :version "24.1"
4314 :type 'boolean)
4316 (defvar org-emph-re nil
4317 "Regular expression for matching emphasis.
4318 After a match, the match groups contain these elements:
4319 0 The match of the full regular expression, including the characters
4320 before and after the proper match
4321 1 The character before the proper match, or empty at beginning of line
4322 2 The proper match, including the leading and trailing markers
4323 3 The leading marker like * or /, indicating the type of highlighting
4324 4 The text between the emphasis markers, not including the markers
4325 5 The character after the match, empty at the end of a line")
4327 (defvar org-verbatim-re nil
4328 "Regular expression for matching verbatim text.")
4330 (defvar org-emphasis-regexp-components) ; defined just below
4331 (defvar org-emphasis-alist) ; defined just below
4332 (defun org-set-emph-re (var val)
4333 "Set variable and compute the emphasis regular expression."
4334 (set var val)
4335 (when (and (boundp 'org-emphasis-alist)
4336 (boundp 'org-emphasis-regexp-components)
4337 org-emphasis-alist org-emphasis-regexp-components)
4338 (pcase-let*
4339 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4340 (body (if (<= nl 0) body
4341 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4342 (template
4343 (format (concat "\\([%s]\\|^\\)" ;before markers
4344 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4345 "\\([%s]\\|$\\)") ;after markers
4346 pre border border body border post)))
4347 (setq org-emph-re (format template "*/_+"))
4348 (setq org-verbatim-re (format template "=~")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after customizing this.")
4371 (defcustom org-emphasis-alist
4372 '(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" (:strike-through t)))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks '("src" "example" "export")
4398 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4399 This is needed for font-lock setup.")
4401 ;;; Functions and variables from their packages
4402 ;; Declared here to avoid compiler warnings
4403 (defvar mark-active)
4405 ;; Various packages
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 (declare-function calendar-forward-day "cal-move" (arg))
4408 (declare-function calendar-goto-date "cal-move" (date))
4409 (declare-function calendar-goto-today "cal-move" ())
4410 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4411 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4412 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4413 (declare-function cdlatex-tab "ext:cdlatex" ())
4414 (declare-function dired-get-filename
4415 "dired"
4416 (&optional localp no-error-if-not-filep))
4417 (declare-function iswitchb-read-buffer
4418 "iswitchb"
4419 (prompt &optional
4420 default require-match _predicate start matches-set))
4421 (declare-function org-agenda-change-all-lines
4422 "org-agenda"
4423 (newhead hdmarker &optional fixface just-this))
4424 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4425 "org-agenda"
4426 (&optional end))
4427 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4428 (declare-function org-agenda-format-item
4429 "org-agenda"
4430 (extra txt &optional level category tags dotime
4431 remove-re habitp))
4432 (declare-function org-agenda-maybe-redo "org-agenda" ())
4433 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4434 (declare-function org-agenda-save-markers-for-cut-and-paste
4435 "org-agenda"
4436 (beg end))
4437 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4438 (declare-function org-agenda-skip "org-agenda" ())
4439 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4440 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4441 (declare-function org-indent-mode "org-indent" (&optional arg))
4442 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4443 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4444 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4445 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4446 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4447 (declare-function parse-time-string "parse-time" (string))
4448 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4450 (defvar align-mode-rules-list)
4451 (defvar calc-embedded-close-formula)
4452 (defvar calc-embedded-open-formula)
4453 (defvar calc-embedded-open-mode)
4454 (defvar font-lock-unfontify-region-function)
4455 (defvar iswitchb-temp-buflist)
4456 (defvar org-agenda-tags-todo-honor-ignore-options)
4457 (defvar remember-data-file)
4458 (defvar texmathp-why)
4460 ;;;###autoload
4461 (defun turn-on-orgtbl ()
4462 "Unconditionally turn on `orgtbl-mode'."
4463 (require 'org-table)
4464 (orgtbl-mode 1))
4466 (defun org-at-table-p (&optional table-type)
4467 "Non-nil if the cursor is inside an Org table.
4468 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4469 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4470 (or (not (derived-mode-p 'org-mode))
4471 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4472 (and e (or table-type
4473 (eq 'org (org-element-property :type e))))))))
4475 (defun org-at-table.el-p ()
4476 "Non-nil when point is at a table.el table."
4477 (and (org-match-line "[ \t]*[|+]")
4478 (let ((element (org-element-at-point)))
4479 (and (eq (org-element-type element) 'table)
4480 (eq (org-element-property :type element) 'table.el)))))
4482 (defun org-at-table-hline-p ()
4483 "Non-nil when point is inside a hline in a table.
4484 Assume point is already in a table."
4485 (org-match-line org-table-hline-regexp))
4487 (defun org-table-map-tables (function &optional quietly)
4488 "Apply FUNCTION to the start of all tables in the buffer."
4489 (org-with-wide-buffer
4490 (goto-char (point-min))
4491 (while (re-search-forward org-table-any-line-regexp nil t)
4492 (unless quietly
4493 (message "Mapping tables: %d%%"
4494 (floor (* 100.0 (point)) (buffer-size))))
4495 (beginning-of-line 1)
4496 (when (and (looking-at org-table-line-regexp)
4497 ;; Exclude tables in src/example/verbatim/clocktable blocks
4498 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4499 (save-excursion (funcall function))
4500 (or (looking-at org-table-line-regexp)
4501 (forward-char 1)))
4502 (re-search-forward org-table-any-border-regexp nil 1)))
4503 (unless quietly (message "Mapping tables: done")))
4505 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4506 (declare-function org-clock-update-mode-line "org-clock" ())
4507 (declare-function org-resolve-clocks "org-clock"
4508 (&optional also-non-dangling-p prompt last-valid))
4510 (defun org-at-TBLFM-p (&optional pos)
4511 "Non-nil when point (or POS) is in #+TBLFM line."
4512 (save-excursion
4513 (goto-char (or pos (point)))
4514 (beginning-of-line)
4515 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4516 (eq (org-element-type (org-element-at-point)) 'table))))
4518 (defvar org-clock-start-time)
4519 (defvar org-clock-marker (make-marker)
4520 "Marker recording the last clock-in.")
4521 (defvar org-clock-hd-marker (make-marker)
4522 "Marker recording the last clock-in, but the headline position.")
4523 (defvar org-clock-heading ""
4524 "The heading of the current clock entry.")
4525 (defun org-clock-is-active ()
4526 "Return the buffer where the clock is currently running.
4527 Return nil if no clock is running."
4528 (marker-buffer org-clock-marker))
4530 (defun org-check-running-clock ()
4531 "Check if the current buffer contains the running clock.
4532 If yes, offer to stop it and to save the buffer with the changes."
4533 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4534 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4535 (buffer-name))))
4536 (org-clock-out)
4537 (when (y-or-n-p "Save changed buffer?")
4538 (save-buffer))))
4540 (defun org-clocktable-try-shift (dir n)
4541 "Check if this line starts a clock table, if yes, shift the time block."
4542 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4543 (org-clocktable-shift dir n)))
4545 ;;;###autoload
4546 (defun org-clock-persistence-insinuate ()
4547 "Set up hooks for clock persistence."
4548 (require 'org-clock)
4549 (add-hook 'org-mode-hook 'org-clock-load)
4550 (add-hook 'kill-emacs-hook 'org-clock-save))
4552 (defgroup org-archive nil
4553 "Options concerning archiving in Org mode."
4554 :tag "Org Archive"
4555 :group 'org-structure)
4557 (defcustom org-archive-location "%s_archive::"
4558 "The location where subtrees should be archived.
4560 The value of this variable is a string, consisting of two parts,
4561 separated by a double-colon. The first part is a filename and
4562 the second part is a headline.
4564 When the filename is omitted, archiving happens in the same file.
4565 %s in the filename will be replaced by the current file
4566 name (without the directory part). Archiving to a different file
4567 is useful to keep archived entries from contributing to the
4568 Org Agenda.
4570 The archived entries will be filed as subtrees of the specified
4571 headline. When the headline is omitted, the subtrees are simply
4572 filed away at the end of the file, as top-level entries. Also in
4573 the heading you can use %s to represent the file name, this can be
4574 useful when using the same archive for a number of different files.
4576 Here are a few examples:
4577 \"%s_archive::\"
4578 If the current file is Projects.org, archive in file
4579 Projects.org_archive, as top-level trees. This is the default.
4581 \"::* Archived Tasks\"
4582 Archive in the current file, under the top-level headline
4583 \"* Archived Tasks\".
4585 \"~/org/archive.org::\"
4586 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4588 \"~/org/archive.org::* From %s\"
4589 Archive in file ~/org/archive.org (absolute path), under headlines
4590 \"From FILENAME\" where file name is the current file name.
4592 \"~/org/datetree.org::datetree/* Finished Tasks\"
4593 The \"datetree/\" string is special, signifying to archive
4594 items to the datetree. Items are placed in either the CLOSED
4595 date of the item, or the current date if there is no CLOSED date.
4596 The heading will be a subentry to the current date. There doesn't
4597 need to be a heading, but there always needs to be a slash after
4598 datetree. For example, to store archived items directly in the
4599 datetree, use \"~/org/datetree.org::datetree/\".
4601 \"basement::** Finished Tasks\"
4602 Archive in file ./basement (relative path), as level 3 trees
4603 below the level 2 heading \"** Finished Tasks\".
4605 You may set this option on a per-file basis by adding to the buffer a
4606 line like
4608 #+ARCHIVE: basement::** Finished Tasks
4610 You may also define it locally for a subtree by setting an ARCHIVE property
4611 in the entry. If such a property is found in an entry, or anywhere up
4612 the hierarchy, it will be used."
4613 :group 'org-archive
4614 :type 'string)
4616 (defcustom org-agenda-skip-archived-trees t
4617 "Non-nil means the agenda will skip any items located in archived trees.
4618 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4619 variable is no longer recommended, you should leave it at the value t.
4620 Instead, use the key `v' to cycle the archives-mode in the agenda."
4621 :group 'org-archive
4622 :group 'org-agenda-skip
4623 :type 'boolean)
4625 (defcustom org-columns-skip-archived-trees t
4626 "Non-nil means ignore archived trees when creating column view."
4627 :group 'org-archive
4628 :group 'org-properties
4629 :type 'boolean)
4631 (defcustom org-cycle-open-archived-trees nil
4632 "Non-nil means `org-cycle' will open archived trees.
4633 An archived tree is a tree marked with the tag ARCHIVE.
4634 When nil, archived trees will stay folded. You can still open them with
4635 normal outline commands like `show-all', but not with the cycling commands."
4636 :group 'org-archive
4637 :group 'org-cycle
4638 :type 'boolean)
4640 (defcustom org-sparse-tree-open-archived-trees nil
4641 "Non-nil means sparse tree construction shows matches in archived trees.
4642 When nil, matches in these trees are highlighted, but the trees are kept in
4643 collapsed state."
4644 :group 'org-archive
4645 :group 'org-sparse-trees
4646 :type 'boolean)
4648 (defcustom org-sparse-tree-default-date-type nil
4649 "The default date type when building a sparse tree.
4650 When this is nil, a date is a scheduled or a deadline timestamp.
4651 Otherwise, these types are allowed:
4653 all: all timestamps
4654 active: only active timestamps (<...>)
4655 inactive: only inactive timestamps ([...])
4656 scheduled: only scheduled timestamps
4657 deadline: only deadline timestamps"
4658 :type '(choice (const :tag "Scheduled or deadline" nil)
4659 (const :tag "All timestamps" all)
4660 (const :tag "Only active timestamps" active)
4661 (const :tag "Only inactive timestamps" inactive)
4662 (const :tag "Only scheduled timestamps" scheduled)
4663 (const :tag "Only deadline timestamps" deadline)
4664 (const :tag "Only closed timestamps" closed))
4665 :version "26.1"
4666 :package-version '(Org . "8.3")
4667 :group 'org-sparse-trees)
4669 (defun org-cycle-hide-archived-subtrees (state)
4670 "Re-hide all archived subtrees after a visibility state change.
4671 STATE should be one of the symbols listed in the docstring of
4672 `org-cycle-hook'."
4673 (when (and (not org-cycle-open-archived-trees)
4674 (not (memq state '(overview folded))))
4675 (save-excursion
4676 (let* ((globalp (memq state '(contents all)))
4677 (beg (if globalp (point-min) (point)))
4678 (end (if globalp (point-max) (org-end-of-subtree t))))
4679 (org-hide-archived-subtrees beg end)
4680 (goto-char beg)
4681 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4682 (message "%s" (substitute-command-keys
4683 "Subtree is archived and stays closed. Use \
4684 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4686 (defun org-force-cycle-archived ()
4687 "Cycle subtree even if it is archived."
4688 (interactive)
4689 (setq this-command 'org-cycle)
4690 (let ((org-cycle-open-archived-trees t))
4691 (call-interactively 'org-cycle)))
4693 (defun org-hide-archived-subtrees (beg end)
4694 "Re-hide all archived subtrees after a visibility state change."
4695 (org-with-wide-buffer
4696 (let ((case-fold-search nil)
4697 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4698 (goto-char beg)
4699 ;; Include headline point is currently on.
4700 (beginning-of-line)
4701 (while (and (< (point) end) (re-search-forward re end t))
4702 (when (member org-archive-tag (org-get-tags))
4703 (org-flag-subtree t)
4704 (org-end-of-subtree t))))))
4706 (declare-function outline-end-of-heading "outline" ())
4707 (declare-function outline-flag-region "outline" (from to flag))
4708 (defun org-flag-subtree (flag)
4709 (save-excursion
4710 (org-back-to-heading t)
4711 (outline-end-of-heading)
4712 (outline-flag-region (point)
4713 (progn (org-end-of-subtree t) (point))
4714 flag)))
4716 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4718 ;; Declare Column View Code
4720 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4721 (declare-function org-columns-compute "org-colview" (property))
4723 ;; Declare ID code
4725 (declare-function org-id-store-link "org-id")
4726 (declare-function org-id-locations-load "org-id")
4727 (declare-function org-id-locations-save "org-id")
4728 (defvar org-id-track-globally)
4730 ;;; Variables for pre-computed regular expressions, all buffer local
4732 (defvar-local org-todo-regexp nil
4733 "Matches any of the TODO state keywords.
4734 Since TODO keywords are case-sensitive, `case-fold-search' is
4735 expected to be bound to nil when matching against this regexp.")
4737 (defvar-local org-not-done-regexp nil
4738 "Matches any of the TODO state keywords except the last one.
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-heading-regexp nil
4743 "Matches a TODO headline that is not done.
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-todo-line-regexp nil
4748 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4753 "Matches a headline and puts everything into groups:
4755 group 1: Stars
4756 group 2: The TODO keyword, maybe
4757 group 3: Priority cookie
4758 group 4: True headline
4759 group 5: Tags
4761 Since TODO keywords are case-sensitive, `case-fold-search' is
4762 expected to be bound to nil when matching against this regexp.")
4764 (defvar-local org-complex-heading-regexp-format nil
4765 "Printf format to make regexp to match an exact headline.
4766 This regexp will match the headline of any node which has the
4767 exact headline text that is put into the format, but may have any
4768 TODO state, priority and tags.")
4770 (defvar-local org-todo-line-tags-regexp nil
4771 "Matches a headline and puts TODO state into group 2 if present.
4772 Also put tags into group 4 if tags are present.")
4774 (defconst org-plain-time-of-day-regexp
4775 (concat
4776 "\\(\\<[012]?[0-9]"
4777 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4778 "\\(--?"
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\)?")
4782 "Regular expression to match a plain time or time range.
4783 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4784 groups carry important information:
4785 0 the full match
4786 1 the first time, range or not
4787 8 the second time, if it is a range.")
4789 (defconst org-plain-time-extension-regexp
4790 (concat
4791 "\\(\\<[012]?[0-9]"
4792 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4793 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4794 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4795 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4796 groups carry important information:
4797 0 the full match
4798 7 hours of duration
4799 9 minutes of duration")
4801 (defconst org-stamp-time-of-day-regexp
4802 (concat
4803 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4804 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4805 "\\(--?"
4806 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4807 "Regular expression to match a timestamp time or time range.
4808 After a match, the following groups carry important information:
4809 0 the full match
4810 1 date plus weekday, for back referencing to make sure both times are on the same day
4811 2 the first time, range or not
4812 4 the second time, if it is a range.")
4814 (defconst org-startup-options
4815 '(("fold" org-startup-folded t)
4816 ("overview" org-startup-folded t)
4817 ("nofold" org-startup-folded nil)
4818 ("showall" org-startup-folded nil)
4819 ("showeverything" org-startup-folded showeverything)
4820 ("content" org-startup-folded content)
4821 ("indent" org-startup-indented t)
4822 ("noindent" org-startup-indented nil)
4823 ("hidestars" org-hide-leading-stars t)
4824 ("showstars" org-hide-leading-stars nil)
4825 ("odd" org-odd-levels-only t)
4826 ("oddeven" org-odd-levels-only nil)
4827 ("align" org-startup-align-all-tables t)
4828 ("noalign" org-startup-align-all-tables nil)
4829 ("inlineimages" org-startup-with-inline-images t)
4830 ("noinlineimages" org-startup-with-inline-images nil)
4831 ("latexpreview" org-startup-with-latex-preview t)
4832 ("nolatexpreview" org-startup-with-latex-preview nil)
4833 ("customtime" org-display-custom-times t)
4834 ("logdone" org-log-done time)
4835 ("lognotedone" org-log-done note)
4836 ("nologdone" org-log-done nil)
4837 ("lognoteclock-out" org-log-note-clock-out t)
4838 ("nolognoteclock-out" org-log-note-clock-out nil)
4839 ("logrepeat" org-log-repeat state)
4840 ("lognoterepeat" org-log-repeat note)
4841 ("logdrawer" org-log-into-drawer t)
4842 ("nologdrawer" org-log-into-drawer nil)
4843 ("logstatesreversed" org-log-states-order-reversed t)
4844 ("nologstatesreversed" org-log-states-order-reversed nil)
4845 ("nologrepeat" org-log-repeat nil)
4846 ("logreschedule" org-log-reschedule time)
4847 ("lognotereschedule" org-log-reschedule note)
4848 ("nologreschedule" org-log-reschedule nil)
4849 ("logredeadline" org-log-redeadline time)
4850 ("lognoteredeadline" org-log-redeadline note)
4851 ("nologredeadline" org-log-redeadline nil)
4852 ("logrefile" org-log-refile time)
4853 ("lognoterefile" org-log-refile note)
4854 ("nologrefile" org-log-refile nil)
4855 ("fninline" org-footnote-define-inline t)
4856 ("nofninline" org-footnote-define-inline nil)
4857 ("fnlocal" org-footnote-section nil)
4858 ("fnauto" org-footnote-auto-label t)
4859 ("fnprompt" org-footnote-auto-label nil)
4860 ("fnconfirm" org-footnote-auto-label confirm)
4861 ("fnplain" org-footnote-auto-label plain)
4862 ("fnadjust" org-footnote-auto-adjust t)
4863 ("nofnadjust" org-footnote-auto-adjust nil)
4864 ("constcgs" constants-unit-system cgs)
4865 ("constSI" constants-unit-system SI)
4866 ("noptag" org-tag-persistent-alist nil)
4867 ("hideblocks" org-hide-block-startup t)
4868 ("nohideblocks" org-hide-block-startup nil)
4869 ("beamer" org-startup-with-beamer-mode t)
4870 ("entitiespretty" org-pretty-entities t)
4871 ("entitiesplain" org-pretty-entities nil))
4872 "Variable associated with STARTUP options for org-mode.
4873 Each element is a list of three items: the startup options (as written
4874 in the #+STARTUP line), the corresponding variable, and the value to set
4875 this variable to if the option is found. An optional forth element PUSH
4876 means to push this value onto the list in the variable.")
4878 (defcustom org-group-tags t
4879 "When non-nil (the default), use group tags.
4880 This can be turned on/off through `org-toggle-tags-groups'."
4881 :group 'org-tags
4882 :group 'org-startup
4883 :type 'boolean)
4885 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4887 (defun org-toggle-tags-groups ()
4888 "Toggle support for group tags.
4889 Support for group tags is controlled by the option
4890 `org-group-tags', which is non-nil by default."
4891 (interactive)
4892 (setq org-group-tags (not org-group-tags))
4893 (cond ((and (derived-mode-p 'org-agenda-mode)
4894 org-group-tags)
4895 (org-agenda-redo))
4896 ((derived-mode-p 'org-mode)
4897 (let ((org-inhibit-startup t)) (org-mode))))
4898 (message "Groups tags support has been turned %s"
4899 (if org-group-tags "on" "off")))
4901 (defun org-set-regexps-and-options (&optional tags-only)
4902 "Precompute regular expressions used in the current buffer.
4903 When optional argument TAGS-ONLY is non-nil, only compute tags
4904 related expressions."
4905 (when (derived-mode-p 'org-mode)
4906 (let ((alist (org--setup-collect-keywords
4907 (org-make-options-regexp
4908 (append '("FILETAGS" "TAGS" "SETUPFILE")
4909 (and (not tags-only)
4910 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4911 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4912 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4913 ;; Startup options. Get this early since it does change
4914 ;; behavior for other options (e.g., tags).
4915 (let ((startup (cdr (assq 'startup alist))))
4916 (dolist (option startup)
4917 (let ((entry (assoc-string option org-startup-options t)))
4918 (when entry
4919 (let ((var (nth 1 entry))
4920 (val (nth 2 entry)))
4921 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4922 (unless (listp (symbol-value var))
4923 (set (make-local-variable var) nil))
4924 (add-to-list var val)))))))
4925 (setq-local org-file-tags
4926 (mapcar #'org-add-prop-inherited
4927 (cdr (assq 'filetags alist))))
4928 (setq org-current-tag-alist
4929 (append org-tag-persistent-alist
4930 (let ((tags (cdr (assq 'tags alist))))
4931 (if tags (org-tag-string-to-alist tags)
4932 org-tag-alist))))
4933 (setq org-tag-groups-alist
4934 (org-tag-alist-to-groups org-current-tag-alist))
4935 (unless tags-only
4936 ;; File properties.
4937 (setq-local org-file-properties (cdr (assq 'property alist)))
4938 ;; Archive location.
4939 (let ((archive (cdr (assq 'archive alist))))
4940 (when archive (setq-local org-archive-location archive)))
4941 ;; Category.
4942 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4943 (when cat
4944 (setq-local org-category (intern cat))
4945 (setq-local org-file-properties
4946 (org--update-property-plist
4947 "CATEGORY" cat org-file-properties))))
4948 ;; Columns.
4949 (let ((column (cdr (assq 'columns alist))))
4950 (when column (setq-local org-columns-default-format column)))
4951 ;; Constants.
4952 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4953 ;; Link abbreviations.
4954 (let ((links (cdr (assq 'link alist))))
4955 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4956 ;; Priorities.
4957 (let ((priorities (cdr (assq 'priorities alist))))
4958 (when priorities
4959 (setq-local org-highest-priority (nth 0 priorities))
4960 (setq-local org-lowest-priority (nth 1 priorities))
4961 (setq-local org-default-priority (nth 2 priorities))))
4962 ;; Scripts.
4963 (let ((scripts (assq 'scripts alist)))
4964 (when scripts
4965 (setq-local org-use-sub-superscripts (cdr scripts))))
4966 ;; TODO keywords.
4967 (setq-local org-todo-kwd-alist nil)
4968 (setq-local org-todo-key-alist nil)
4969 (setq-local org-todo-key-trigger nil)
4970 (setq-local org-todo-keywords-1 nil)
4971 (setq-local org-done-keywords nil)
4972 (setq-local org-todo-heads nil)
4973 (setq-local org-todo-sets nil)
4974 (setq-local org-todo-log-states nil)
4975 (let ((todo-sequences
4976 (or (nreverse (cdr (assq 'todo alist)))
4977 (let ((d (default-value 'org-todo-keywords)))
4978 (if (not (stringp (car d))) d
4979 ;; XXX: Backward compatibility code.
4980 (list (cons org-todo-interpretation d)))))))
4981 (dolist (sequence todo-sequences)
4982 (let* ((sequence (or (run-hook-with-args-until-success
4983 'org-todo-setup-filter-hook sequence)
4984 sequence))
4985 (sequence-type (car sequence))
4986 (keywords (cdr sequence))
4987 (sep (member "|" keywords))
4988 names alist)
4989 (dolist (k (remove "|" keywords))
4990 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4992 (error "Invalid TODO keyword %s" k))
4993 (let ((name (match-string 1 k))
4994 (key (match-string 2 k))
4995 (log (org-extract-log-state-settings k)))
4996 (push name names)
4997 (push (cons name (and key (string-to-char key))) alist)
4998 (when log (push log org-todo-log-states))))
4999 (let* ((names (nreverse names))
5000 (done (if sep (org-remove-keyword-keys (cdr sep))
5001 (last names)))
5002 (head (car names))
5003 (tail (list sequence-type head (car done) (org-last done))))
5004 (add-to-list 'org-todo-heads head 'append)
5005 (push names org-todo-sets)
5006 (setq org-done-keywords (append org-done-keywords done nil))
5007 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5008 (setq org-todo-key-alist
5009 (append org-todo-key-alist
5010 (and alist
5011 (append '((:startgroup))
5012 (nreverse alist)
5013 '((:endgroup))))))
5014 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5015 (setq org-todo-sets (nreverse org-todo-sets)
5016 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5017 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5018 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5019 ;; Compute the regular expressions and other local variables.
5020 ;; Using `org-outline-regexp-bol' would complicate them much,
5021 ;; because of the fixed white space at the end of that string.
5022 (unless org-done-keywords
5023 (setq org-done-keywords
5024 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5025 (setq org-not-done-keywords
5026 (org-delete-all org-done-keywords
5027 (copy-sequence org-todo-keywords-1))
5028 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5029 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5030 org-not-done-heading-regexp
5031 (format org-heading-keyword-regexp-format org-not-done-regexp)
5032 org-todo-line-regexp
5033 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5034 org-complex-heading-regexp
5035 (concat "^\\(\\*+\\)"
5036 "\\(?: +" org-todo-regexp "\\)?"
5037 "\\(?: +\\(\\[#.\\]\\)\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5040 "[ \t]*$")
5041 org-complex-heading-regexp-format
5042 (concat "^\\(\\*+\\)"
5043 "\\(?: +" org-todo-regexp "\\)?"
5044 "\\(?: +\\(\\[#.\\]\\)\\)?"
5045 "\\(?: +"
5046 ;; Stats cookies can be stuck to body.
5047 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5048 "\\(%s\\)"
5049 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5050 "\\)"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-todo-line-tags-regexp
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5058 "[ \t]*$"))
5059 (org-compute-latex-and-related-regexp)))))
5061 (defun org--setup-collect-keywords (regexp &optional files alist)
5062 "Return setup keywords values as an alist.
5064 REGEXP matches a subset of setup keywords. FILES is a list of
5065 file names already visited. It is used to avoid circular setup
5066 files. ALIST, when non-nil, is the alist computed so far.
5068 Return value contains the following keys: `archive', `category',
5069 `columns', `constants', `filetags', `link', `priorities',
5070 `property', `scripts', `startup', `tags' and `todo'."
5071 (org-with-wide-buffer
5072 (goto-char (point-min))
5073 (let ((case-fold-search t))
5074 (while (re-search-forward regexp nil t)
5075 (let ((element (org-element-at-point)))
5076 (when (eq (org-element-type element) 'keyword)
5077 (let ((key (org-element-property :key element))
5078 (value (org-element-property :value element)))
5079 (cond
5080 ((equal key "ARCHIVE")
5081 (when (org-string-nw-p value)
5082 (push (cons 'archive value) alist)))
5083 ((equal key "CATEGORY") (push (cons 'category value) alist))
5084 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5085 ((equal key "CONSTANTS")
5086 (let* ((constants (assq 'constants alist))
5087 (store (cdr constants)))
5088 (dolist (pair (split-string value))
5089 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5090 pair)
5091 (let* ((name (match-string 1 pair))
5092 (value (match-string 2 pair))
5093 (old (assoc name store)))
5094 (if old (setcdr old value)
5095 (push (cons name value) store)))))
5096 (if constants (setcdr constants store)
5097 (push (cons 'constants store) alist))))
5098 ((equal key "FILETAGS")
5099 (when (org-string-nw-p value)
5100 (let ((old (assq 'filetags alist))
5101 (new (apply #'nconc
5102 (mapcar (lambda (x) (org-split-string x ":"))
5103 (split-string value)))))
5104 (if old (setcdr old (append new (cdr old)))
5105 (push (cons 'filetags new) alist)))))
5106 ((equal key "LINK")
5107 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5108 (let ((links (assq 'link alist))
5109 (pair (cons (match-string-no-properties 1 value)
5110 (match-string-no-properties 2 value))))
5111 (if links (push pair (cdr links))
5112 (push (list 'link pair) alist)))))
5113 ((equal key "OPTIONS")
5114 (when (and (org-string-nw-p value)
5115 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5116 (push (cons 'scripts (read (match-string 1 value))) alist)))
5117 ((equal key "PRIORITIES")
5118 (push (cons 'priorities
5119 (let ((prio (split-string value)))
5120 (if (< (length prio) 3) '(?A ?C ?B)
5121 (mapcar #'string-to-char prio))))
5122 alist))
5123 ((equal key "PROPERTY")
5124 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5125 (let* ((property (assq 'property alist))
5126 (value (org--update-property-plist
5127 (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value)
5129 (cdr property))))
5130 (if property (setcdr property value)
5131 (push (cons 'property value) alist)))))
5132 ((equal key "STARTUP")
5133 (let ((startup (assq 'startup alist)))
5134 (if startup
5135 (setcdr startup
5136 (append (cdr startup) (split-string value)))
5137 (push (cons 'startup (split-string value)) alist))))
5138 ((equal key "TAGS")
5139 (let ((tag-cell (assq 'tags alist)))
5140 (if tag-cell
5141 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5142 (push (cons 'tags value) alist))))
5143 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5144 (let ((todo (assq 'todo alist))
5145 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5146 (split-string value))))
5147 (if todo (push value (cdr todo))
5148 (push (list 'todo value) alist))))
5149 ((equal key "SETUPFILE")
5150 (unless buffer-read-only ; Do not check in Gnus messages.
5151 (let ((f (and (org-string-nw-p value)
5152 (expand-file-name
5153 (org-unbracket-string "\"" "\"" value)))))
5154 (when (and f (file-readable-p f) (not (member f files)))
5155 (with-temp-buffer
5156 (setq default-directory (file-name-directory f))
5157 (insert-file-contents f)
5158 (setq alist
5159 ;; Fake Org mode to benefit from cache
5160 ;; without recurring needlessly.
5161 (let ((major-mode 'org-mode))
5162 (org--setup-collect-keywords
5163 regexp (cons f files) alist)))))))))))))))
5164 alist)
5166 (defun org-tag-string-to-alist (s)
5167 "Return tag alist associated to string S.
5168 S is a value for TAGS keyword or produced with
5169 `org-tag-alist-to-string'. Return value is an alist suitable for
5170 `org-tag-alist' or `org-tag-persistent-alist'."
5171 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5172 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5173 "\\|{.+?}\\)" ; regular expression
5174 "\\(?:(\\(.\\))\\)?\\'"))
5175 alist group-flag)
5176 (dolist (tokens lines (cdr (nreverse alist)))
5177 (push '(:newline) alist)
5178 (while tokens
5179 (let ((token (pop tokens)))
5180 (pcase token
5181 ("{"
5182 (push '(:startgroup) alist)
5183 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5184 ("}"
5185 (push '(:endgroup) alist)
5186 (setq group-flag nil))
5187 ("["
5188 (push '(:startgrouptag) alist)
5189 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5190 ("]"
5191 (push '(:endgrouptag) alist)
5192 (setq group-flag nil))
5193 (":"
5194 (push '(:grouptags) alist))
5195 ((guard (string-match tag-re token))
5196 (let ((tag (match-string 1 token))
5197 (key (and (match-beginning 2)
5198 (string-to-char (match-string 2 token)))))
5199 ;; Push all tags in groups, no matter if they already
5200 ;; appear somewhere else in the list.
5201 (when (or group-flag (not (assoc tag alist)))
5202 (push (cons tag key) alist))))))))))
5204 (defun org-tag-alist-to-string (alist &optional skip-key)
5205 "Return tag string associated to ALIST.
5207 ALIST is an alist, as defined in `org-tag-alist' or
5208 `org-tag-persistent-alist', or produced with
5209 `org-tag-string-to-alist'.
5211 Return value is a string suitable as a value for \"TAGS\"
5212 keyword.
5214 When optional argument SKIP-KEY is non-nil, skip selection keys
5215 next to tags."
5216 (mapconcat (lambda (token)
5217 (pcase token
5218 (`(:startgroup) "{")
5219 (`(:endgroup) "}")
5220 (`(:startgrouptag) "[")
5221 (`(:endgrouptag) "]")
5222 (`(:grouptags) ":")
5223 (`(:newline) "\\n")
5224 ((and
5225 (guard (not skip-key))
5226 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5227 (format "%s(%c)" tag key))
5228 (`(,(and tag (pred stringp)) . ,_) tag)
5229 (_ (user-error "Invalid tag token: %S" token))))
5230 alist
5231 " "))
5233 (defun org-tag-alist-to-groups (alist)
5234 "Return group alist from tag ALIST.
5235 ALIST is an alist, as defined in `org-tag-alist' or
5236 `org-tag-persistent-alist', or produced with
5237 `org-tag-string-to-alist'. Return value is an alist following
5238 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5239 a string, summarizing TAGS, as a list of strings."
5240 (let (groups group-status current-group)
5241 (dolist (token alist (nreverse groups))
5242 (pcase token
5243 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5244 (`(,(or :endgroup :endgrouptag))
5245 (when (eq group-status 'append)
5246 (push (nreverse current-group) groups))
5247 (setq group-status nil))
5248 (`(:grouptags) (setq group-status 'append))
5249 ((and `(,tag . ,_) (guard group-status))
5250 (if (eq group-status 'append) (push tag current-group)
5251 (setq current-group (list tag))))
5252 (_ nil)))))
5254 (defvar org--file-cache (make-hash-table :test #'equal)
5255 "Hash table to store contents of files referenced via a URL.
5256 This is the cache of file URLs read using `org-file-contents'.")
5258 (defun org-reset-file-cache ()
5259 "Reset the cache of files downloaded by `org-file-contents'."
5260 (clrhash org--file-cache))
5262 (defun org-file-url-p (file)
5263 "Non-nil if FILE is a URL."
5264 (require 'ffap)
5265 (string-match-p ffap-url-regexp file))
5267 (defun org-file-contents (file &optional noerror nocache)
5268 "Return the contents of FILE, as a string.
5270 FILE can be a file name or URL.
5272 If FILE is a URL, download the contents. If the URL contents are
5273 already cached in the `org--file-cache' hash table, the download step
5274 is skipped.
5276 If NOERROR is non-nil, ignore the error when unable to read the FILE
5277 from file or URL.
5279 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5280 is available. This option applies only if FILE is a URL."
5281 (let* ((is-url (org-file-url-p file))
5282 (cache (and is-url
5283 (not nocache)
5284 (gethash file org--file-cache))))
5285 (cond
5286 (cache)
5287 (is-url
5288 (with-current-buffer (url-retrieve-synchronously file)
5289 (goto-char (point-min))
5290 ;; Move point to after the url-retrieve header.
5291 (search-forward "\n\n" nil :move)
5292 ;; Search for the success code only in the url-retrieve header.
5293 (if (save-excursion
5294 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5295 ;; Update the cache `org--file-cache' and return contents.
5296 (puthash file
5297 (buffer-substring-no-properties (point) (point-max))
5298 org--file-cache)
5299 (funcall (if noerror #'message #'user-error)
5300 "Unable to fetch file from %S"
5301 file))))
5303 (with-temp-buffer
5304 (condition-case nil
5305 (progn
5306 (insert-file-contents file)
5307 (buffer-string))
5308 (file-error
5309 (funcall (if noerror #'message #'user-error)
5310 "Unable to read file %S"
5311 file))))))))
5313 (defun org-extract-log-state-settings (x)
5314 "Extract the log state setting from a TODO keyword string.
5315 This will extract info from a string like \"WAIT(w@/!)\"."
5316 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5317 (let ((kw (match-string 1 x))
5318 (log1 (and (match-end 3) (match-string 3 x)))
5319 (log2 (and (match-end 4) (match-string 4 x))))
5320 (and (or log1 log2)
5321 (list kw
5322 (and log1 (if (equal log1 "!") 'time 'note))
5323 (and log2 (if (equal log2 "!") 'time 'note)))))))
5325 (defun org-remove-keyword-keys (list)
5326 "Remove a pair of parenthesis at the end of each string in LIST."
5327 (mapcar (lambda (x)
5328 (if (string-match "(.*)$" x)
5329 (substring x 0 (match-beginning 0))
5331 list))
5333 (defun org-assign-fast-keys (alist)
5334 "Assign fast keys to a keyword-key alist.
5335 Respect keys that are already there."
5336 (let (new e (alt ?0))
5337 (while (setq e (pop alist))
5338 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5339 (cdr e)) ;; Key already assigned.
5340 (push e new)
5341 (let ((clist (string-to-list (downcase (car e))))
5342 (used (append new alist)))
5343 (when (= (car clist) ?@)
5344 (pop clist))
5345 (while (and clist (rassoc (car clist) used))
5346 (pop clist))
5347 (unless clist
5348 (while (rassoc alt used)
5349 (cl-incf alt)))
5350 (push (cons (car e) (or (car clist) alt)) new))))
5351 (nreverse new)))
5353 ;;; Some variables used in various places
5355 (defvar org-window-configuration nil
5356 "Used in various places to store a window configuration.")
5357 (defvar org-selected-window nil
5358 "Used in various places to store a window configuration.")
5359 (defvar org-finish-function nil
5360 "Function to be called when `C-c C-c' is used.
5361 This is for getting out of special buffers like capture.")
5362 (defvar org-last-state)
5364 ;; Defined somewhere in this file, but used before definition.
5365 (defvar org-entities) ;; defined in org-entities.el
5366 (defvar org-struct-menu)
5367 (defvar org-org-menu)
5368 (defvar org-tbl-menu)
5370 ;;;; Define the Org mode
5372 ;; We use a before-change function to check if a table might need
5373 ;; an update.
5374 (defvar org-table-may-need-update t
5375 "Indicates that a table might need an update.
5376 This variable is set by `org-before-change-function'.
5377 `org-table-align' sets it back to nil.")
5378 (defun org-before-change-function (_beg _end)
5379 "Every change indicates that a table might need an update."
5380 (setq org-table-may-need-update t))
5381 (defvar org-mode-map)
5382 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5383 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5384 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5385 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5386 (defvar org-table-buffer-is-an nil)
5388 (defvar bidi-paragraph-direction)
5389 (defvar buffer-face-mode-face)
5391 (require 'outline)
5393 ;; Other stuff we need.
5394 (require 'time-date)
5395 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5396 (require 'easymenu)
5397 (autoload 'easy-menu-add "easymenu")
5398 (require 'overlay)
5400 ;; (require 'org-macs) moved higher up in the file before it is first used
5401 (require 'org-entities)
5402 ;; (require 'org-compat) moved higher up in the file before it is first used
5403 (require 'org-faces)
5404 (require 'org-list)
5405 (require 'org-pcomplete)
5406 (require 'org-src)
5407 (require 'org-footnote)
5408 (require 'org-macro)
5410 ;; babel
5411 (require 'ob)
5413 ;;;###autoload
5414 (define-derived-mode org-mode outline-mode "Org"
5415 "Outline-based notes management and organizer, alias
5416 \"Carsten's outline-mode for keeping track of everything.\"
5418 Org mode develops organizational tasks around a NOTES file which
5419 contains information about projects as plain text. Org mode is
5420 implemented on top of Outline mode, which is ideal to keep the content
5421 of large files well structured. It supports ToDo items, deadlines and
5422 time stamps, which magically appear in the diary listing of the Emacs
5423 calendar. Tables are easily created with a built-in table editor.
5424 Plain text URL-like links connect to websites, emails (VM), Usenet
5425 messages (Gnus), BBDB entries, and any files related to the project.
5426 For printing and sharing of notes, an Org file (or a part of it)
5427 can be exported as a structured ASCII or HTML file.
5429 The following commands are available:
5431 \\{org-mode-map}"
5433 ;; Get rid of Outline menus, they are not needed
5434 ;; Need to do this here because define-derived-mode sets up
5435 ;; the keymap so late. Still, it is a waste to call this each time
5436 ;; we switch another buffer into Org mode.
5437 (define-key org-mode-map [menu-bar headings] 'undefined)
5438 (define-key org-mode-map [menu-bar hide] 'undefined)
5439 (define-key org-mode-map [menu-bar show] 'undefined)
5441 (org-load-modules-maybe)
5442 (org-install-agenda-files-menu)
5443 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5444 (add-to-invisibility-spec '(org-cwidth))
5445 (add-to-invisibility-spec '(org-hide-block . t))
5446 (setq-local outline-regexp org-outline-regexp)
5447 (setq-local outline-level 'org-outline-level)
5448 (setq bidi-paragraph-direction 'left-to-right)
5449 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5450 (unless org-display-table
5451 (setq org-display-table (make-display-table)))
5452 (set-display-table-slot
5453 org-display-table 4
5454 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5455 org-ellipsis)))
5456 (setq buffer-display-table org-display-table))
5457 (org-set-regexps-and-options)
5458 (org-set-font-lock-defaults)
5459 (when (and org-tag-faces (not org-tags-special-faces-re))
5460 ;; tag faces set outside customize.... force initialization.
5461 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5462 ;; Calc embedded
5463 (setq-local calc-embedded-open-mode "# ")
5464 ;; Modify a few syntax entries
5465 (modify-syntax-entry ?@ "w")
5466 (modify-syntax-entry ?\" "\"")
5467 (modify-syntax-entry ?\\ "_")
5468 (modify-syntax-entry ?~ "_")
5469 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5470 ;; Activate before-change-function
5471 (setq-local org-table-may-need-update t)
5472 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5473 ;; Check for running clock before killing a buffer
5474 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5475 ;; Initialize macros templates.
5476 (org-macro-initialize-templates)
5477 ;; Initialize radio targets.
5478 (org-update-radio-target-regexp)
5479 ;; Indentation.
5480 (setq-local indent-line-function 'org-indent-line)
5481 (setq-local indent-region-function 'org-indent-region)
5482 ;; Filling and auto-filling.
5483 (org-setup-filling)
5484 ;; Comments.
5485 (org-setup-comments-handling)
5486 ;; Initialize cache.
5487 (org-element-cache-reset)
5488 ;; Beginning/end of defun
5489 (setq-local beginning-of-defun-function 'org-backward-element)
5490 (setq-local end-of-defun-function
5491 (lambda ()
5492 (if (not (org-at-heading-p))
5493 (org-forward-element)
5494 (org-forward-element)
5495 (forward-char -1))))
5496 ;; Next error for sparse trees
5497 (setq-local next-error-function 'org-occur-next-match)
5498 ;; Make sure dependence stuff works reliably, even for users who set it
5499 ;; too late :-(
5500 (if org-enforce-todo-dependencies
5501 (add-hook 'org-blocker-hook
5502 'org-block-todo-from-children-or-siblings-or-parent)
5503 (remove-hook 'org-blocker-hook
5504 'org-block-todo-from-children-or-siblings-or-parent))
5505 (if org-enforce-todo-checkbox-dependencies
5506 (add-hook 'org-blocker-hook
5507 'org-block-todo-from-checkboxes)
5508 (remove-hook 'org-blocker-hook
5509 'org-block-todo-from-checkboxes))
5511 ;; Align options lines
5512 (setq-local
5513 align-mode-rules-list
5514 '((org-in-buffer-settings
5515 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5516 (modes . '(org-mode)))))
5518 ;; Imenu
5519 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5521 ;; Make isearch reveal context
5522 (setq-local outline-isearch-open-invisible-function
5523 (lambda (&rest _) (org-show-context 'isearch)))
5525 ;; Setup the pcomplete hooks
5526 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5527 (setq-local pcomplete-command-name-function 'org-command-at-point)
5528 (setq-local pcomplete-default-completion-function 'ignore)
5529 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5530 (setq-local pcomplete-termination-string "")
5531 (setq-local buffer-face-mode-face 'org-default)
5533 ;; If empty file that did not turn on Org mode automatically, make
5534 ;; it to.
5535 (when (and org-insert-mode-line-in-empty-file
5536 (called-interactively-p 'any)
5537 (= (point-min) (point-max)))
5538 (insert "# -*- mode: org -*-\n\n"))
5539 (unless org-inhibit-startup
5540 (org-unmodified
5541 (when org-startup-with-beamer-mode (org-beamer-mode))
5542 (when org-startup-align-all-tables
5543 (org-table-map-tables #'org-table-align t))
5544 (when org-startup-with-inline-images (org-display-inline-images))
5545 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5546 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5547 (when org-startup-truncated (setq truncate-lines t))
5548 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5549 (org-refresh-effort-properties)))
5550 ;; Try to set `org-hide' face correctly.
5551 (let ((foreground (org-find-invisible-foreground)))
5552 (when foreground
5553 (set-face-foreground 'org-hide foreground))))
5555 ;; Update `customize-package-emacs-version-alist'
5556 (add-to-list 'customize-package-emacs-version-alist
5557 '(Org ("8.0" . "24.4")
5558 ("8.1" . "24.4")
5559 ("8.2" . "24.4")
5560 ("8.2.7" . "24.4")
5561 ("8.3" . "26.1")
5562 ("9.0" . "26.1")
5563 ("9.1" . "26.1")))
5565 (defvar org-mode-transpose-word-syntax-table
5566 (let ((st (make-syntax-table text-mode-syntax-table)))
5567 (dolist (c org-emphasis-alist st)
5568 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5570 (when (fboundp 'abbrev-table-put)
5571 (abbrev-table-put org-mode-abbrev-table
5572 :parents (list text-mode-abbrev-table)))
5574 (defun org-find-invisible-foreground ()
5575 (let ((candidates (remove
5576 "unspecified-bg"
5577 (nconc
5578 (list (face-background 'default)
5579 (face-background 'org-default))
5580 (mapcar
5581 (lambda (alist)
5582 (when (boundp alist)
5583 (cdr (assq 'background-color (symbol-value alist)))))
5584 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5585 (list (face-foreground 'org-hide))))))
5586 (car (remove nil candidates))))
5588 (defun org-current-time (&optional rounding-minutes past)
5589 "Current time, possibly rounded to ROUNDING-MINUTES.
5590 When ROUNDING-MINUTES is not an integer, fall back on the car of
5591 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5592 the rounding returns a past time."
5593 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5594 (car org-time-stamp-rounding-minutes)))
5595 (time (decode-time)) res)
5596 (if (< r 1)
5597 (current-time)
5598 (setq res
5599 (apply 'encode-time
5600 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5601 (nthcdr 2 time))))
5602 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5603 (seconds-to-time (- (float-time res) (* r 60)))
5604 res))))
5606 (defun org-today ()
5607 "Return today date, considering `org-extend-today-until'."
5608 (time-to-days
5609 (time-subtract (current-time)
5610 (list 0 (* 3600 org-extend-today-until) 0))))
5612 ;;;; Font-Lock stuff, including the activators
5614 (defvar org-mouse-map (make-sparse-keymap))
5615 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5616 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5617 (when org-mouse-1-follows-link
5618 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5619 (when org-tab-follows-link
5620 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5621 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5623 (require 'font-lock)
5625 (defconst org-non-link-chars "]\t\n\r<>")
5626 (defvar org-link-types-re nil
5627 "Matches a link that has a url-like prefix like \"http:\"")
5628 (defvar org-link-re-with-space nil
5629 "Matches a link with spaces, optional angular brackets around it.")
5630 (defvar org-link-re-with-space2 nil
5631 "Matches a link with spaces, optional angular brackets around it.")
5632 (defvar org-link-re-with-space3 nil
5633 "Matches a link with spaces, only for internal part in bracket links.")
5634 (defvar org-angle-link-re nil
5635 "Matches link with angular brackets, spaces are allowed.")
5636 (defvar org-plain-link-re nil
5637 "Matches plain link, without spaces.")
5638 (defvar org-bracket-link-regexp nil
5639 "Matches a link in double brackets.")
5640 (defvar org-bracket-link-analytic-regexp nil
5641 "Regular expression used to analyze links.
5642 Here is what the match groups contain after a match:
5643 1: http:
5644 2: http
5645 3: path
5646 4: [desc]
5647 5: desc")
5648 (defvar org-bracket-link-analytic-regexp++ nil
5649 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5650 (defvar org-any-link-re nil
5651 "Regular expression matching any link.")
5653 (defconst org-match-sexp-depth 3
5654 "Number of stacked braces for sub/superscript matching.")
5656 (defun org-create-multibrace-regexp (left right n)
5657 "Create a regular expression which will match a balanced sexp.
5658 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5659 as single character strings.
5660 The regexp returned will match the entire expression including the
5661 delimiters. It will also define a single group which contains the
5662 match except for the outermost delimiters. The maximum depth of
5663 stacked delimiters is N. Escaping delimiters is not possible."
5664 (let* ((nothing (concat "[^" left right "]*?"))
5665 (or "\\|")
5666 (re nothing)
5667 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5668 (while (> n 1)
5669 (setq n (1- n)
5670 re (concat re or next)
5671 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5672 (concat left "\\(" re "\\)" right)))
5674 (defconst org-match-substring-regexp
5675 (concat
5676 "\\(\\S-\\)\\([_^]\\)\\("
5677 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5678 "\\|"
5679 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5680 "\\|"
5681 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5682 "The regular expression matching a sub- or superscript.")
5684 (defconst org-match-substring-with-braces-regexp
5685 (concat
5686 "\\(\\S-\\)\\([_^]\\)"
5687 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5688 "The regular expression matching a sub- or superscript, forcing braces.")
5690 (defun org-make-link-regexps ()
5691 "Update the link regular expressions.
5692 This should be called after the variable `org-link-parameters' has changed."
5693 (let ((types-re (regexp-opt (org-link-types) t)))
5694 (setq org-link-types-re
5695 (concat "\\`" types-re ":")
5696 org-link-re-with-space
5697 (concat "<?" types-re ":"
5698 "\\([^" org-non-link-chars " ]"
5699 "[^" org-non-link-chars "]*"
5700 "[^" org-non-link-chars " ]\\)>?")
5701 org-link-re-with-space2
5702 (concat "<?" types-re ":"
5703 "\\([^" org-non-link-chars " ]"
5704 "[^\t\n\r]*"
5705 "[^" org-non-link-chars " ]\\)>?")
5706 org-link-re-with-space3
5707 (concat "<?" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^\t\n\r]*\\)")
5710 org-angle-link-re
5711 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5712 types-re)
5713 org-plain-link-re
5714 (concat
5715 "\\<" types-re ":"
5716 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5717 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5718 org-bracket-link-regexp
5719 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5720 org-bracket-link-analytic-regexp
5721 (concat
5722 "\\[\\["
5723 "\\(" types-re ":\\)?"
5724 "\\([^]]+\\)"
5725 "\\]"
5726 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5727 "\\]")
5728 org-bracket-link-analytic-regexp++
5729 (concat
5730 "\\[\\["
5731 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5732 "\\([^]]+\\)"
5733 "\\]"
5734 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5735 "\\]")
5736 org-any-link-re
5737 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5738 org-angle-link-re "\\)\\|\\("
5739 org-plain-link-re "\\)"))))
5741 (org-make-link-regexps)
5743 (defvar org-emph-face nil)
5745 (defun org-do-emphasis-faces (limit)
5746 "Run through the buffer and emphasize strings."
5747 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5748 (car org-emphasis-regexp-components))))
5749 (catch :exit
5750 (while (re-search-forward quick-re limit t)
5751 (let* ((marker (match-string 2))
5752 (verbatim? (member marker '("~" "="))))
5753 (when (save-excursion
5754 (goto-char (match-beginning 0))
5755 (and
5756 ;; Do not match table hlines.
5757 (not (and (equal marker "+")
5758 (org-match-line
5759 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5760 ;; Match full emphasis markup regexp.
5761 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5762 ;; Do not span over paragraph boundaries.
5763 (not (string-match-p org-element-paragraph-separate
5764 (match-string 2)))
5765 ;; Do not span over cells in table rows.
5766 (not (and (save-match-data (org-match-line "[ \t]*|"))
5767 (string-match-p "|" (match-string 4))))))
5768 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5769 (font-lock-prepend-text-property
5770 (match-beginning 2) (match-end 2) 'face face)
5771 (when verbatim?
5772 (org-remove-flyspell-overlays-in
5773 (match-beginning 0) (match-end 0)))
5774 (add-text-properties (match-beginning 2) (match-end 2)
5775 '(font-lock-multiline t org-emphasis t))
5776 (when org-hide-emphasis-markers
5777 (add-text-properties (match-end 4) (match-beginning 5)
5778 '(invisible org-link))
5779 (add-text-properties (match-beginning 3) (match-end 3)
5780 '(invisible org-link)))
5781 (throw :exit t))))))))
5783 (defun org-emphasize (&optional char)
5784 "Insert or change an emphasis, i.e. a font like bold or italic.
5785 If there is an active region, change that region to a new emphasis.
5786 If there is no region, just insert the marker characters and position
5787 the cursor between them.
5788 CHAR should be the marker character. If it is a space, it means to
5789 remove the emphasis of the selected region.
5790 If CHAR is not given (for example in an interactive call) it will be
5791 prompted for."
5792 (interactive)
5793 (let ((erc org-emphasis-regexp-components)
5794 (string "") beg end move s)
5795 (if (org-region-active-p)
5796 (setq beg (region-beginning)
5797 end (region-end)
5798 string (buffer-substring beg end))
5799 (setq move t))
5801 (unless char
5802 (message "Emphasis marker or tag: [%s]"
5803 (mapconcat #'car org-emphasis-alist ""))
5804 (setq char (read-char-exclusive)))
5805 (if (equal char ?\s)
5806 (setq s ""
5807 move nil)
5808 (unless (assoc (char-to-string char) org-emphasis-alist)
5809 (user-error "No such emphasis marker: \"%c\"" char))
5810 (setq s (char-to-string char)))
5811 (while (and (> (length string) 1)
5812 (equal (substring string 0 1) (substring string -1))
5813 (assoc (substring string 0 1) org-emphasis-alist))
5814 (setq string (substring string 1 -1)))
5815 (setq string (concat s string s))
5816 (when beg (delete-region beg end))
5817 (unless (or (bolp)
5818 (string-match (concat "[" (nth 0 erc) "\n]")
5819 (char-to-string (char-before (point)))))
5820 (insert " "))
5821 (unless (or (eobp)
5822 (string-match (concat "[" (nth 1 erc) "\n]")
5823 (char-to-string (char-after (point)))))
5824 (insert " ") (backward-char 1))
5825 (insert string)
5826 (and move (backward-char 1))))
5828 (defconst org-nonsticky-props
5829 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5831 (defsubst org-rear-nonsticky-at (pos)
5832 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5834 (defun org-activate-links (limit)
5835 "Add link properties to links.
5836 This includes angle, plain, and bracket links."
5837 (catch :exit
5838 (while (re-search-forward org-any-link-re limit t)
5839 (let* ((start (match-beginning 0))
5840 (end (match-end 0))
5841 (style (cond ((eq ?< (char-after start)) 'angle)
5842 ((eq ?\[ (char-after (1+ start))) 'bracket)
5843 (t 'plain))))
5844 (when (and (memq style org-highlight-links)
5845 ;; Do not confuse plain links with tags.
5846 (not (and (eq style 'plain)
5847 (let ((face (get-text-property
5848 (max (1- start) (point-min)) 'face)))
5849 (if (consp face) (memq 'org-tag face)
5850 (eq 'org-tag face))))))
5851 (let* ((link-object (save-excursion
5852 (goto-char start)
5853 (save-match-data (org-element-link-parser))))
5854 (link (org-element-property :raw-link link-object))
5855 (type (org-element-property :type link-object))
5856 (path (org-element-property :path link-object))
5857 (properties ;for link's visible part
5858 (list
5859 'face (pcase (org-link-get-parameter type :face)
5860 ((and (pred functionp) face) (funcall face path))
5861 ((and (pred facep) face) face)
5862 ((and (pred consp) face) face) ;anonymous
5863 (_ 'org-link))
5864 'mouse-face (or (org-link-get-parameter type :mouse-face)
5865 'highlight)
5866 'keymap (or (org-link-get-parameter type :keymap)
5867 org-mouse-map)
5868 'help-echo (pcase (org-link-get-parameter type :help-echo)
5869 ((and (pred stringp) echo) echo)
5870 ((and (pred functionp) echo) echo)
5871 (_ (concat "LINK: " link)))
5872 'htmlize-link (pcase (org-link-get-parameter type
5873 :htmlize-link)
5874 ((and (pred functionp) f) (funcall f))
5875 (_ `(:uri ,link)))
5876 'font-lock-multiline t)))
5877 (org-remove-flyspell-overlays-in start end)
5878 (org-rear-nonsticky-at end)
5879 (if (not (eq 'bracket style))
5880 (add-text-properties start end properties)
5881 ;; Handle invisible parts in bracket links.
5882 (remove-text-properties start end '(invisible nil))
5883 (let ((hidden
5884 (append `(invisible
5885 ,(or (org-link-get-parameter type :display)
5886 'org-link))
5887 properties))
5888 (visible-start (or (match-beginning 4) (match-beginning 2)))
5889 (visible-end (or (match-end 4) (match-end 2))))
5890 (add-text-properties start visible-start hidden)
5891 (add-text-properties visible-start visible-end properties)
5892 (add-text-properties visible-end end hidden)
5893 (org-rear-nonsticky-at visible-start)
5894 (org-rear-nonsticky-at visible-end)))
5895 (let ((f (org-link-get-parameter type :activate-func)))
5896 (when (functionp f)
5897 (funcall f start end path (eq style 'bracket))))
5898 (throw :exit t))))) ;signal success
5899 nil))
5901 (defun org-activate-code (limit)
5902 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5903 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5904 (remove-text-properties (match-beginning 0) (match-end 0)
5905 '(display t invisible t intangible t))
5908 (defcustom org-src-fontify-natively t
5909 "When non-nil, fontify code in code blocks.
5910 See also the `org-block' face."
5911 :type 'boolean
5912 :version "26.1"
5913 :package-version '(Org . "8.3")
5914 :group 'org-appearance
5915 :group 'org-babel)
5917 (defcustom org-allow-promoting-top-level-subtree nil
5918 "When non-nil, allow promoting a top level subtree.
5919 The leading star of the top level headline will be replaced
5920 by a #."
5921 :type 'boolean
5922 :version "24.1"
5923 :group 'org-appearance)
5925 (defun org-fontify-meta-lines-and-blocks (limit)
5926 (condition-case nil
5927 (org-fontify-meta-lines-and-blocks-1 limit)
5928 (error (message "org-mode fontification error in %S at %d"
5929 (current-buffer)
5930 (line-number-at-pos)))))
5932 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5933 "Fontify #+ lines and blocks."
5934 (let ((case-fold-search t))
5935 (when (re-search-forward
5936 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5937 limit t)
5938 (let ((beg (match-beginning 0))
5939 (block-start (match-end 0))
5940 (block-end nil)
5941 (lang (match-string 7))
5942 (beg1 (line-beginning-position 2))
5943 (dc1 (downcase (match-string 2)))
5944 (dc3 (downcase (match-string 3)))
5945 end end1 quoting block-type)
5946 (cond
5947 ((and (match-end 4) (equal dc3 "+begin"))
5948 ;; Truly a block
5949 (setq block-type (downcase (match-string 5))
5950 quoting (member block-type org-protecting-blocks))
5951 (when (re-search-forward
5952 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5953 nil t) ;; on purpose, we look further than LIMIT
5954 (setq end (min (point-max) (match-end 0))
5955 end1 (min (point-max) (1- (match-beginning 0))))
5956 (setq block-end (match-beginning 0))
5957 (when quoting
5958 (org-remove-flyspell-overlays-in beg1 end1)
5959 (remove-text-properties beg end
5960 '(display t invisible t intangible t)))
5961 (add-text-properties
5962 beg end '(font-lock-fontified t font-lock-multiline t))
5963 (add-text-properties beg beg1 '(face org-meta-line))
5964 (org-remove-flyspell-overlays-in beg beg1)
5965 (add-text-properties ; For end_src
5966 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5967 (org-remove-flyspell-overlays-in end1 end)
5968 (cond
5969 ((and lang (not (string= lang "")) org-src-fontify-natively)
5970 (org-src-font-lock-fontify-block lang block-start block-end)
5971 (add-text-properties beg1 block-end '(src-block t)))
5972 (quoting
5973 (add-text-properties beg1 (min (point-max) (1+ end1))
5974 (list 'face
5975 (list :inherit
5976 (let ((face-name
5977 (intern (format "org-block-%s" lang))))
5978 (append (and (facep face-name) (list face-name))
5979 '(org-block))))))) ; end of source block
5980 ((not org-fontify-quote-and-verse-blocks))
5981 ((string= block-type "quote")
5982 (add-face-text-property
5983 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5984 ((string= block-type "verse")
5985 (add-face-text-property
5986 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5987 (add-text-properties beg beg1 '(face org-block-begin-line))
5988 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5989 '(face org-block-end-line))
5991 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5992 (org-remove-flyspell-overlays-in
5993 (match-beginning 0)
5994 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5995 (add-text-properties
5996 beg (match-end 3)
5997 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5998 '(font-lock-fontified t invisible t)
5999 '(font-lock-fontified t face org-document-info-keyword)))
6000 (add-text-properties
6001 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6002 (if (string-equal dc1 "+title:")
6003 '(font-lock-fontified t face org-document-title)
6004 '(font-lock-fontified t face org-document-info))))
6005 ((string-prefix-p "+caption" dc1)
6006 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6007 (remove-text-properties (match-beginning 0) (match-end 0)
6008 '(display t invisible t intangible t))
6009 ;; Handle short captions.
6010 (save-excursion
6011 (beginning-of-line)
6012 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6013 (add-text-properties (line-beginning-position) (match-end 1)
6014 '(font-lock-fontified t face org-meta-line))
6015 (add-text-properties (match-end 0) (line-end-position)
6016 '(font-lock-fontified t face org-block))
6018 ((member dc3 '(" " ""))
6019 (org-remove-flyspell-overlays-in beg (match-end 0))
6020 (add-text-properties
6021 beg (match-end 0)
6022 '(font-lock-fontified t face font-lock-comment-face)))
6023 (t ;; just any other in-buffer setting, but not indented
6024 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6025 (remove-text-properties (match-beginning 0) (match-end 0)
6026 '(display t invisible t intangible t))
6027 (add-text-properties beg (match-end 0)
6028 '(font-lock-fontified t face org-meta-line))
6029 t))))))
6031 (defun org-fontify-drawers (limit)
6032 "Fontify drawers."
6033 (when (re-search-forward org-drawer-regexp limit t)
6034 (add-text-properties
6035 (match-beginning 0) (match-end 0)
6036 '(font-lock-fontified t face org-special-keyword))
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6040 (defun org-fontify-macros (limit)
6041 "Fontify macros."
6042 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6043 (add-text-properties
6044 (match-beginning 0) (match-end 0)
6045 '(font-lock-fontified t face org-macro))
6046 (when org-hide-macro-markers
6047 (add-text-properties (match-end 2) (match-beginning 2)
6048 '(invisible t))
6049 (add-text-properties (match-beginning 1) (match-end 1)
6050 '(invisible t)))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (defun org-activate-footnote-links (limit)
6055 "Add text properties for footnotes."
6056 (let ((fn (org-footnote-next-reference-or-definition limit)))
6057 (when fn
6058 (let* ((beg (nth 1 fn))
6059 (end (nth 2 fn))
6060 (label (car fn))
6061 (referencep (/= (line-beginning-position) beg)))
6062 (when (and referencep (nth 3 fn))
6063 (save-excursion
6064 (goto-char beg)
6065 (search-forward (or label "fn:"))
6066 (org-remove-flyspell-overlays-in beg (match-end 0))))
6067 (add-text-properties beg end
6068 (list 'mouse-face 'highlight
6069 'keymap org-mouse-map
6070 'help-echo
6071 (if referencep "Footnote reference"
6072 "Footnote definition")
6073 'font-lock-fontified t
6074 'font-lock-multiline t
6075 'face 'org-footnote))))))
6077 (defun org-activate-dates (limit)
6078 "Add text properties for dates."
6079 (when (and (re-search-forward org-tsr-regexp-both limit t)
6080 (not (equal (char-before (match-beginning 0)) 91)))
6081 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6082 (add-text-properties (match-beginning 0) (match-end 0)
6083 (list 'mouse-face 'highlight
6084 'keymap org-mouse-map))
6085 (org-rear-nonsticky-at (match-end 0))
6086 (when org-display-custom-times
6087 ;; If it's a date range, activate custom time for second date.
6088 (when (match-end 3)
6089 (org-display-custom-time (match-beginning 3) (match-end 3)))
6090 (org-display-custom-time (match-beginning 1) (match-end 1)))
6093 (defvar-local org-target-link-regexp nil
6094 "Regular expression matching radio targets in plain text.")
6096 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6097 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6098 border border border))
6099 "Regular expression matching a link target.")
6101 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6102 "Regular expression matching a radio target.")
6104 (defconst org-any-target-regexp
6105 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6106 "Regular expression matching any target.")
6108 (defun org-activate-target-links (limit)
6109 "Add text properties for target matches."
6110 (when org-target-link-regexp
6111 (let ((case-fold-search t))
6112 (when (re-search-forward org-target-link-regexp limit t)
6113 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'mouse-face 'highlight
6116 'keymap org-mouse-map
6117 'help-echo "Radio target link"
6118 'org-linked-text t))
6119 (org-rear-nonsticky-at (match-end 1))
6120 t))))
6122 (defun org-update-radio-target-regexp ()
6123 "Find all radio targets in this file and update the regular expression.
6124 Also refresh fontification if needed."
6125 (interactive)
6126 (let ((old-regexp org-target-link-regexp)
6127 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6128 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6129 (targets
6130 (org-with-wide-buffer
6131 (goto-char (point-min))
6132 (let (rtn)
6133 (while (re-search-forward org-radio-target-regexp nil t)
6134 ;; Make sure point is really within the object.
6135 (backward-char)
6136 (let ((obj (org-element-context)))
6137 (when (eq (org-element-type obj) 'radio-target)
6138 (cl-pushnew (org-element-property :value obj) rtn
6139 :test #'equal))))
6140 rtn))))
6141 (setq org-target-link-regexp
6142 (and targets
6143 (concat before-re
6144 (mapconcat
6145 (lambda (x)
6146 (replace-regexp-in-string
6147 " +" "\\s-+" (regexp-quote x) t t))
6148 targets
6149 "\\|")
6150 after-re)))
6151 (unless (equal old-regexp org-target-link-regexp)
6152 ;; Clean-up cache.
6153 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6154 ((not org-target-link-regexp) old-regexp)
6156 (concat before-re
6157 (mapconcat
6158 (lambda (re)
6159 (substring re (length before-re)
6160 (- (length after-re))))
6161 (list old-regexp org-target-link-regexp)
6162 "\\|")
6163 after-re)))))
6164 (org-with-wide-buffer
6165 (goto-char (point-min))
6166 (while (re-search-forward regexp nil t)
6167 (org-element-cache-refresh (match-beginning 1)))))
6168 ;; Re fontify buffer.
6169 (when (memq 'radio org-highlight-links)
6170 (org-restart-font-lock)))))
6172 (defun org-hide-wide-columns (limit)
6173 (let (s e)
6174 (setq s (text-property-any (point) (or limit (point-max))
6175 'org-cwidth t))
6176 (when s
6177 (setq e (next-single-property-change s 'org-cwidth))
6178 (add-text-properties s e '(invisible org-cwidth))
6179 (goto-char e)
6180 t)))
6182 (defvar org-latex-and-related-regexp nil
6183 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6185 (defun org-compute-latex-and-related-regexp ()
6186 "Compute regular expression for LaTeX, entities and sub/superscript.
6187 Result depends on variable `org-highlight-latex-and-related'."
6188 (setq-local
6189 org-latex-and-related-regexp
6190 (let* ((re-sub
6191 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6192 ((eq org-use-sub-superscripts '{})
6193 (list org-match-substring-with-braces-regexp))
6194 (org-use-sub-superscripts (list org-match-substring-regexp))))
6195 (re-latex
6196 (when (memq 'latex org-highlight-latex-and-related)
6197 (let ((matchers (plist-get org-format-latex-options :matchers)))
6198 (delq nil
6199 (mapcar (lambda (x)
6200 (and (member (car x) matchers) (nth 1 x)))
6201 org-latex-regexps)))))
6202 (re-entities
6203 (when (memq 'entities org-highlight-latex-and-related)
6204 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6205 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6207 (defun org-do-latex-and-related (limit)
6208 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6209 LIMIT bounds the search for syntax to highlight. Stop at first
6210 highlighted object, if any. Return t if some highlighting was
6211 done, nil otherwise."
6212 (when (org-string-nw-p org-latex-and-related-regexp)
6213 (catch 'found
6214 (while (re-search-forward org-latex-and-related-regexp limit t)
6215 (unless
6216 (cl-some
6217 (lambda (f)
6218 (memq f '(org-code org-verbatim underline org-special-keyword)))
6219 (save-excursion
6220 (goto-char (1+ (match-beginning 0)))
6221 (face-at-point nil t)))
6222 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6223 '(?_ ?^))
6225 0)))
6226 (font-lock-prepend-text-property
6227 (+ offset (match-beginning 0)) (match-end 0)
6228 'face 'org-latex-and-related)
6229 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6230 '(font-lock-multiline t)))
6231 (throw 'found t)))
6232 nil)))
6234 (defun org-restart-font-lock ()
6235 "Restart `font-lock-mode', to force refontification."
6236 (when (and (boundp 'font-lock-mode) font-lock-mode)
6237 (font-lock-mode -1)
6238 (font-lock-mode 1)))
6240 (defun org-activate-tags (limit)
6241 (when (re-search-forward
6242 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6243 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6244 (add-text-properties (match-beginning 1) (match-end 1)
6245 (list 'mouse-face 'highlight
6246 'keymap org-mouse-map))
6247 (org-rear-nonsticky-at (match-end 1))
6250 (defun org-outline-level ()
6251 "Compute the outline level of the heading at point.
6253 If this is called at a normal headline, the level is the number
6254 of stars. Use `org-reduced-level' to remove the effect of
6255 `org-odd-levels'. Unlike to `org-current-level', this function
6256 takes into consideration inlinetasks."
6257 (org-with-wide-buffer
6258 (end-of-line)
6259 (if (re-search-backward org-outline-regexp-bol nil t)
6260 (1- (- (match-end 0) (match-beginning 0)))
6261 0)))
6263 (defvar org-font-lock-keywords nil)
6265 (defsubst org-re-property (property &optional literal allow-null value)
6266 "Return a regexp matching a PROPERTY line.
6268 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6269 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6270 non-nil, match properties even without a value.
6272 Match group 3 is set to the value when it exists. If there is no
6273 value and ALLOW-NULL is non-nil, it is set to the empty string.
6275 With optional argument VALUE, match only property lines with
6276 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6277 unless LITERAL is non-nil."
6278 (concat
6279 "^\\(?4:[ \t]*\\)"
6280 (format "\\(?1::\\(?2:%s\\):\\)"
6281 (if literal property (regexp-quote property)))
6282 (cond (value
6283 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6284 (if literal value (regexp-quote value))))
6285 (allow-null
6286 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6288 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6290 (defconst org-property-re
6291 (org-re-property "\\S-+" 'literal t)
6292 "Regular expression matching a property line.
6293 There are four matching groups:
6294 1: :PROPKEY: including the leading and trailing colon,
6295 2: PROPKEY without the leading and trailing colon,
6296 3: PROPVAL without leading or trailing spaces,
6297 4: the indentation of the current line,
6298 5: trailing whitespace.")
6300 (defvar org-font-lock-hook nil
6301 "Functions to be called for special font lock stuff.")
6303 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6305 (defvar org-font-lock-set-keywords-hook nil
6306 "Functions that can manipulate `org-font-lock-extra-keywords'.
6307 This is called after `org-font-lock-extra-keywords' is defined, but before
6308 it is installed to be used by font lock. This can be useful if something
6309 needs to be inserted at a specific position in the font-lock sequence.")
6311 (defun org-font-lock-hook (limit)
6312 "Run `org-font-lock-hook' within LIMIT."
6313 (run-hook-with-args 'org-font-lock-hook limit))
6315 (defun org-set-font-lock-defaults ()
6316 "Set font lock defaults for the current buffer."
6317 (let* ((em org-fontify-emphasized-text)
6318 (lk org-highlight-links)
6319 (org-font-lock-extra-keywords
6320 (list
6321 ;; Call the hook
6322 '(org-font-lock-hook)
6323 ;; Headlines
6324 `(,(if org-fontify-whole-heading-line
6325 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6326 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6327 (1 (org-get-level-face 1))
6328 (2 (org-get-level-face 2))
6329 (3 (org-get-level-face 3)))
6330 ;; Table lines
6331 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6332 (1 'org-table t))
6333 ;; Table internals
6334 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6335 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6336 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6337 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6338 ;; Drawers
6339 '(org-fontify-drawers)
6340 ;; Properties
6341 (list org-property-re
6342 '(1 'org-special-keyword t)
6343 '(3 'org-property-value t))
6344 ;; Link related fontification.
6345 '(org-activate-links)
6346 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6347 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6348 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6349 (when (memq 'footnote lk) '(org-activate-footnote-links))
6350 ;; Targets.
6351 (list org-any-target-regexp '(0 'org-target t))
6352 ;; Diary sexps.
6353 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6354 ;; Macro
6355 '(org-fontify-macros)
6356 '(org-hide-wide-columns (0 nil append))
6357 ;; TODO keyword
6358 (list (format org-heading-keyword-regexp-format
6359 org-todo-regexp)
6360 '(2 (org-get-todo-face 2) t))
6361 ;; DONE
6362 (if org-fontify-done-headline
6363 (list (format org-heading-keyword-regexp-format
6364 (concat
6365 "\\(?:"
6366 (mapconcat 'regexp-quote org-done-keywords "\\|")
6367 "\\)"))
6368 '(2 'org-headline-done t))
6369 nil)
6370 ;; Priorities
6371 '(org-font-lock-add-priority-faces)
6372 ;; Tags
6373 '(org-font-lock-add-tag-faces)
6374 ;; Tags groups
6375 (when (and org-group-tags org-tag-groups-alist)
6376 (list (concat org-outline-regexp-bol ".+\\(:"
6377 (regexp-opt (mapcar 'car org-tag-groups-alist))
6378 ":\\).*$")
6379 '(1 'org-tag-group prepend)))
6380 ;; Special keywords
6381 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6382 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6383 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6384 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6385 ;; Emphasis
6386 (when em '(org-do-emphasis-faces))
6387 ;; Checkboxes
6388 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6389 1 'org-checkbox prepend)
6390 (when (cdr (assq 'checkbox org-list-automatic-rules))
6391 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6392 (0 (org-get-checkbox-statistics-face) t)))
6393 ;; Description list items
6394 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6395 1 'org-list-dt prepend)
6396 ;; ARCHIVEd headings
6397 (list (concat
6398 org-outline-regexp-bol
6399 "\\(.*:" org-archive-tag ":.*\\)")
6400 '(1 'org-archived prepend))
6401 ;; Specials
6402 '(org-do-latex-and-related)
6403 '(org-fontify-entities)
6404 '(org-raise-scripts)
6405 ;; Code
6406 '(org-activate-code (1 'org-code t))
6407 ;; COMMENT
6408 (list (format
6409 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6410 org-todo-regexp
6411 org-comment-string)
6412 '(9 'org-special-keyword t))
6413 ;; Blocks and meta lines
6414 '(org-fontify-meta-lines-and-blocks))))
6415 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6416 (run-hooks 'org-font-lock-set-keywords-hook)
6417 ;; Now set the full font-lock-keywords
6418 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6419 (setq-local font-lock-defaults
6420 '(org-font-lock-keywords t nil nil backward-paragraph))
6421 (kill-local-variable 'font-lock-keywords)
6422 nil))
6424 (defun org-toggle-pretty-entities ()
6425 "Toggle the composition display of entities as UTF8 characters."
6426 (interactive)
6427 (setq-local org-pretty-entities (not org-pretty-entities))
6428 (org-restart-font-lock)
6429 (if org-pretty-entities
6430 (message "Entities are now displayed as UTF8 characters")
6431 (save-restriction
6432 (widen)
6433 (decompose-region (point-min) (point-max))
6434 (message "Entities are now displayed as plain text"))))
6436 (defvar-local org-custom-properties-overlays nil
6437 "List of overlays used for custom properties.")
6439 (defun org-toggle-custom-properties-visibility ()
6440 "Display or hide properties in `org-custom-properties'."
6441 (interactive)
6442 (if org-custom-properties-overlays
6443 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6444 (setq org-custom-properties-overlays nil))
6445 (when org-custom-properties
6446 (org-with-wide-buffer
6447 (goto-char (point-min))
6448 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6449 (while (re-search-forward regexp nil t)
6450 (let ((end (cdr (save-match-data (org-get-property-block)))))
6451 (when (and end (< (point) end))
6452 ;; Hide first custom property in current drawer.
6453 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6454 (overlay-put o 'invisible t)
6455 (overlay-put o 'org-custom-property t)
6456 (push o org-custom-properties-overlays))
6457 ;; Hide additional custom properties in the same drawer.
6458 (while (re-search-forward regexp end t)
6459 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6460 (overlay-put o 'invisible t)
6461 (overlay-put o 'org-custom-property t)
6462 (push o org-custom-properties-overlays)))))
6463 ;; Each entry is limited to a single property drawer.
6464 (outline-next-heading)))))))
6466 (defun org-fontify-entities (limit)
6467 "Find an entity to fontify."
6468 (let (ee)
6469 (when org-pretty-entities
6470 (catch 'match
6471 ;; "\_ "-family is left out on purpose. Only the first one,
6472 ;; i.e., "\_ ", could be fontified anyway, and it would be
6473 ;; confusing when adding a second white space character.
6474 (while (re-search-forward
6475 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6476 limit t)
6477 (when (and (not (org-at-comment-p))
6478 (setq ee (org-entity-get (match-string 1)))
6479 (= (length (nth 6 ee)) 1))
6480 (let* ((end (if (equal (match-string 2) "{}")
6481 (match-end 2)
6482 (match-end 1))))
6483 (add-text-properties
6484 (match-beginning 0) end
6485 (list 'font-lock-fontified t))
6486 (compose-region (match-beginning 0) end
6487 (nth 6 ee) nil)
6488 (backward-char 1)
6489 (throw 'match t))))
6490 nil))))
6492 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6493 "Fontify string S like in Org mode."
6494 (with-temp-buffer
6495 (insert s)
6496 (let ((org-odd-levels-only odd-levels))
6497 (org-mode)
6498 (org-font-lock-ensure)
6499 (buffer-string))))
6501 (defvar org-m nil)
6502 (defvar org-l nil)
6503 (defvar org-f nil)
6504 (defun org-get-level-face (n)
6505 "Get the right face for match N in font-lock matching of headlines."
6506 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6507 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6508 (if org-cycle-level-faces
6509 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6510 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6511 (cond
6512 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6513 ((eq n 2) org-f)
6514 (t (unless org-level-color-stars-only org-f))))
6516 (defun org-face-from-face-or-color (context inherit face-or-color)
6517 "Create a face list that inherits INHERIT, but sets the foreground color.
6518 When FACE-OR-COLOR is not a string, just return it."
6519 (if (stringp face-or-color)
6520 (list :inherit inherit
6521 (cdr (assoc context org-faces-easy-properties))
6522 face-or-color)
6523 face-or-color))
6525 (defun org-get-todo-face (kwd)
6526 "Get the right face for a TODO keyword KWD.
6527 If KWD is a number, get the corresponding match group."
6528 (when (numberp kwd) (setq kwd (match-string kwd)))
6529 (or (org-face-from-face-or-color
6530 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6531 (and (member kwd org-done-keywords) 'org-done)
6532 'org-todo))
6534 (defun org-get-priority-face (priority)
6535 "Get the right face for PRIORITY.
6536 PRIORITY is a character."
6537 (or (org-face-from-face-or-color
6538 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6539 'org-priority))
6541 (defun org-get-tag-face (tag)
6542 "Get the right face for TAG.
6543 If TAG is a number, get the corresponding match group."
6544 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6545 (or (org-face-from-face-or-color
6546 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6547 'org-tag)))
6549 (defun org-font-lock-add-priority-faces (limit)
6550 "Add the special priority faces."
6551 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6552 (add-text-properties
6553 (match-beginning 1) (match-end 1)
6554 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6555 'font-lock-fontified t))))
6557 (defun org-font-lock-add-tag-faces (limit)
6558 "Add the special tag faces."
6559 (when (and org-tag-faces org-tags-special-faces-re)
6560 (while (re-search-forward org-tags-special-faces-re limit t)
6561 (add-text-properties (match-beginning 1) (match-end 1)
6562 (list 'face (org-get-tag-face 1)
6563 'font-lock-fontified t))
6564 (backward-char 1))))
6566 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6567 "Remove fontification and activation overlays from links."
6568 (font-lock-default-unfontify-region beg end)
6569 (let* ((buffer-undo-list t)
6570 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6571 (inhibit-modification-hooks t)
6572 deactivate-mark buffer-file-name buffer-file-truename)
6573 (decompose-region beg end)
6574 (remove-text-properties beg end
6575 '(mouse-face t keymap t org-linked-text t
6576 invisible t intangible t
6577 org-emphasis t))
6578 (org-remove-font-lock-display-properties beg end)))
6580 (defconst org-script-display '(((raise -0.3) (height 0.7))
6581 ((raise 0.3) (height 0.7))
6582 ((raise -0.5))
6583 ((raise 0.5)))
6584 "Display properties for showing superscripts and subscripts.")
6586 (defun org-remove-font-lock-display-properties (beg end)
6587 "Remove specific display properties that have been added by font lock.
6588 The will remove the raise properties that are used to show superscripts
6589 and subscripts."
6590 (let (next prop)
6591 (while (< beg end)
6592 (setq next (next-single-property-change beg 'display nil end)
6593 prop (get-text-property beg 'display))
6594 (when (member prop org-script-display)
6595 (put-text-property beg next 'display nil))
6596 (setq beg next))))
6598 (defun org-raise-scripts (limit)
6599 "Add raise properties to sub/superscripts."
6600 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6601 (re-search-forward
6602 (if (eq org-use-sub-superscripts t)
6603 org-match-substring-regexp
6604 org-match-substring-with-braces-regexp)
6605 limit t))
6606 (let* ((pos (point)) table-p comment-p
6607 (mpos (match-beginning 3))
6608 (emph-p (get-text-property mpos 'org-emphasis))
6609 (link-p (get-text-property mpos 'mouse-face))
6610 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6611 (goto-char (point-at-bol))
6612 (setq table-p (looking-at-p org-table-dataline-regexp)
6613 comment-p (looking-at-p "^[ \t]*#[ +]"))
6614 (goto-char pos)
6615 ;; Handle a_b^c
6616 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6617 (unless (or comment-p emph-p link-p keyw-p)
6618 (put-text-property (match-beginning 3) (match-end 0)
6619 'display
6620 (if (equal (char-after (match-beginning 2)) ?^)
6621 (nth (if table-p 3 1) org-script-display)
6622 (nth (if table-p 2 0) org-script-display)))
6623 (add-text-properties (match-beginning 2) (match-end 2)
6624 (list 'invisible t))
6625 (when (and (eq (char-after (match-beginning 3)) ?{)
6626 (eq (char-before (match-end 3)) ?}))
6627 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6628 (list 'invisible t))
6629 (add-text-properties (1- (match-end 3)) (match-end 3)
6630 (list 'invisible t))))
6631 t)))
6633 ;;;; Visibility cycling, including org-goto and indirect buffer
6635 ;;; Cycling
6637 (defvar-local org-cycle-global-status nil)
6638 (put 'org-cycle-global-status 'org-state t)
6639 (defvar-local org-cycle-subtree-status nil)
6640 (put 'org-cycle-subtree-status 'org-state t)
6642 (defvar org-inlinetask-min-level)
6644 (defun org-unlogged-message (&rest args)
6645 "Display a message, but avoid logging it in the *Messages* buffer."
6646 (let ((message-log-max nil))
6647 (apply 'message args)))
6649 ;;;###autoload
6650 (defun org-cycle (&optional arg)
6651 "TAB-action and visibility cycling for Org mode.
6653 This is the command invoked in Org mode by the `TAB' key. Its main
6654 purpose is outline visibility cycling, but it also invokes other actions
6655 in special contexts.
6657 When this function is called with a `\\[universal-argument]' prefix, rotate \
6658 the entire
6659 buffer through 3 states (global cycling)
6660 1. OVERVIEW: Show only top-level headlines.
6661 2. CONTENTS: Show all headlines of all levels, but no body text.
6662 3. SHOW ALL: Show everything.
6664 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6665 switch to the startup visibility,
6666 determined by the variable `org-startup-folded', and by any VISIBILITY
6667 properties in the buffer.
6669 With a `\\[universal-argument] \\[universal-argument] \
6670 \\[universal-argument]' prefix argument, show the entire buffer, including
6671 any drawers.
6673 When inside a table, re-align the table and move to the next field.
6675 When point is at the beginning of a headline, rotate the subtree started
6676 by this line through 3 different states (local cycling)
6677 1. FOLDED: Only the main headline is shown.
6678 2. CHILDREN: The main headline and the direct children are shown.
6679 From this state, you can move to one of the children
6680 and zoom in further.
6681 3. SUBTREE: Show the entire subtree, including body text.
6682 If there is no subtree, switch directly from CHILDREN to FOLDED.
6684 When point is at the beginning of an empty headline and the variable
6685 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6686 of the headline by demoting and promoting it to likely levels. This
6687 speeds up creation document structure by pressing `TAB' once or several
6688 times right after creating a new headline.
6690 When there is a numeric prefix, go up to a heading with level ARG, do
6691 a `show-subtree' and return to the previous cursor position. If ARG
6692 is negative, go up that many levels.
6694 When point is not at the beginning of a headline, execute the global
6695 binding for `TAB', which is re-indenting the line. See the option
6696 `org-cycle-emulate-tab' for details.
6698 As a special case, if point is at the beginning of the buffer and there is
6699 no headline in line 1, this function will act as if called with prefix arg
6700 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6701 prefix arg, but only
6702 if the variable `org-cycle-global-at-bob' is t."
6703 (interactive "P")
6704 (org-load-modules-maybe)
6705 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6706 (and org-cycle-level-after-item/entry-creation
6707 (or (org-cycle-level)
6708 (org-cycle-item-indentation))))
6709 (let* ((limit-level
6710 (or org-cycle-max-level
6711 (and (boundp 'org-inlinetask-min-level)
6712 org-inlinetask-min-level
6713 (1- org-inlinetask-min-level))))
6714 (nstars (and limit-level
6715 (if org-odd-levels-only
6716 (and limit-level (1- (* limit-level 2)))
6717 limit-level)))
6718 (org-outline-regexp
6719 (if (not (derived-mode-p 'org-mode))
6720 outline-regexp
6721 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6722 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6723 (not (looking-at org-outline-regexp))))
6724 (org-cycle-hook
6725 (if bob-special
6726 (delq 'org-optimize-window-after-visibility-change
6727 (copy-sequence org-cycle-hook))
6728 org-cycle-hook))
6729 (pos (point)))
6731 (cond
6733 ((equal arg '(16))
6734 (setq last-command 'dummy)
6735 (org-set-startup-visibility)
6736 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6738 ((equal arg '(64))
6739 (outline-show-all)
6740 (org-unlogged-message "Entire buffer visible, including drawers"))
6742 ((equal arg '(4)) (org-cycle-internal-global))
6744 ;; Try hiding block at point.
6745 ((org-hide-block-toggle-maybe))
6747 ;; Try cdlatex TAB completion
6748 ((org-try-cdlatex-tab))
6750 ;; Table: enter it or move to the next field.
6751 ((org-at-table-p 'any)
6752 (if (org-at-table.el-p)
6753 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6754 Use `\\[org-edit-special]' to edit table.el tables"))
6755 (if arg (org-table-edit-field t)
6756 (org-table-justify-field-maybe)
6757 (call-interactively 'org-table-next-field))))
6759 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6761 ;; Global cycling: delegate to `org-cycle-internal-global'.
6762 (bob-special (org-cycle-internal-global))
6764 ;; Drawers: delegate to `org-flag-drawer'.
6765 ((save-excursion
6766 (beginning-of-line 1)
6767 (looking-at org-drawer-regexp))
6768 (org-flag-drawer ; toggle block visibility
6769 (not (get-char-property (match-end 0) 'invisible))))
6771 ;; Show-subtree, ARG levels up from here.
6772 ((integerp arg)
6773 (save-excursion
6774 (org-back-to-heading)
6775 (outline-up-heading (if (< arg 0) (- arg)
6776 (- (funcall outline-level) arg)))
6777 (org-show-subtree)))
6779 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6780 ((and (featurep 'org-inlinetask)
6781 (org-inlinetask-at-task-p)
6782 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6783 (org-inlinetask-toggle-visibility))
6785 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6786 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6787 (save-excursion (move-beginning-of-line 1)
6788 (looking-at org-outline-regexp)))
6789 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6790 (org-cycle-internal-local))
6792 ;; From there: TAB emulation and template completion.
6793 (buffer-read-only (org-back-to-heading))
6795 ((run-hook-with-args-until-success
6796 'org-tab-after-check-for-cycling-hook))
6798 ((org-try-structure-completion))
6800 ((run-hook-with-args-until-success
6801 'org-tab-before-tab-emulation-hook))
6803 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6804 (or (not (bolp))
6805 (not (looking-at org-outline-regexp))))
6806 (call-interactively (global-key-binding "\t")))
6808 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6809 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6810 (or (and (eq org-cycle-emulate-tab 'white)
6811 (= (match-end 0) (point-at-eol)))
6812 (and (eq org-cycle-emulate-tab 'whitestart)
6813 (>= (match-end 0) pos))))
6815 (eq org-cycle-emulate-tab t))
6816 (call-interactively (global-key-binding "\t")))
6818 (t (save-excursion
6819 (org-back-to-heading)
6820 (org-cycle)))))))
6822 (defun org-cycle-internal-global ()
6823 "Do the global cycling action."
6824 ;; Hack to avoid display of messages for .org attachments in Gnus
6825 (let ((ga (string-match "\\*fontification" (buffer-name))))
6826 (cond
6827 ((and (eq last-command this-command)
6828 (eq org-cycle-global-status 'overview))
6829 ;; We just created the overview - now do table of contents
6830 ;; This can be slow in very large buffers, so indicate action
6831 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6832 (unless ga (org-unlogged-message "CONTENTS..."))
6833 (org-content)
6834 (unless ga (org-unlogged-message "CONTENTS...done"))
6835 (setq org-cycle-global-status 'contents)
6836 (run-hook-with-args 'org-cycle-hook 'contents))
6838 ((and (eq last-command this-command)
6839 (eq org-cycle-global-status 'contents))
6840 ;; We just showed the table of contents - now show everything
6841 (run-hook-with-args 'org-pre-cycle-hook 'all)
6842 (outline-show-all)
6843 (unless ga (org-unlogged-message "SHOW ALL"))
6844 (setq org-cycle-global-status 'all)
6845 (run-hook-with-args 'org-cycle-hook 'all))
6848 ;; Default action: go to overview
6849 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6850 (org-overview)
6851 (unless ga (org-unlogged-message "OVERVIEW"))
6852 (setq org-cycle-global-status 'overview)
6853 (run-hook-with-args 'org-cycle-hook 'overview)))))
6855 (defvar org-called-with-limited-levels nil
6856 "Non-nil when `org-with-limited-levels' is currently active.")
6858 (defun org-invisible-p (&optional pos)
6859 "Non-nil if the character after POS is invisible.
6860 If POS is nil, use `point' instead."
6861 (get-char-property (or pos (point)) 'invisible))
6863 (defun org-cycle-internal-local ()
6864 "Do the local cycling action."
6865 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6866 ;; First, determine end of headline (EOH), end of subtree or item
6867 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6868 (save-excursion
6869 (if (org-at-item-p)
6870 (progn
6871 (beginning-of-line)
6872 (setq struct (org-list-struct))
6873 (setq eoh (point-at-eol))
6874 (setq eos (org-list-get-item-end-before-blank (point) struct))
6875 (setq has-children (org-list-has-child-p (point) struct)))
6876 (org-back-to-heading)
6877 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6878 (setq eos (save-excursion (org-end-of-subtree t t)
6879 (when (bolp) (backward-char)) (point)))
6880 (setq has-children
6881 (or (save-excursion
6882 (let ((level (funcall outline-level)))
6883 (outline-next-heading)
6884 (and (org-at-heading-p t)
6885 (> (funcall outline-level) level))))
6886 (save-excursion
6887 (org-list-search-forward (org-item-beginning-re) eos t)))))
6888 ;; Determine end invisible part of buffer (EOL)
6889 (beginning-of-line 2)
6890 (while (and (not (eobp)) ;This is like `next-line'.
6891 (get-char-property (1- (point)) 'invisible))
6892 (goto-char (next-single-char-property-change (point) 'invisible))
6893 (and (eolp) (beginning-of-line 2)))
6894 (setq eol (point)))
6895 ;; Find out what to do next and set `this-command'
6896 (cond
6897 ((= eos eoh)
6898 ;; Nothing is hidden behind this heading
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6901 (org-unlogged-message "EMPTY ENTRY")
6902 (setq org-cycle-subtree-status nil)
6903 (save-excursion
6904 (goto-char eos)
6905 (outline-next-heading)
6906 (when (org-invisible-p) (org-flag-heading nil))))
6907 ((and (or (>= eol eos)
6908 (not (string-match "\\S-" (buffer-substring eol eos))))
6909 (or has-children
6910 (not (setq children-skipped
6911 org-cycle-skip-children-state-if-no-children))))
6912 ;; Entire subtree is hidden in one line: children view
6913 (unless (org-before-first-heading-p)
6914 (run-hook-with-args 'org-pre-cycle-hook 'children))
6915 (if (org-at-item-p)
6916 (org-list-set-item-visibility (point-at-bol) struct 'children)
6917 (org-show-entry)
6918 (org-with-limited-levels (org-show-children))
6919 ;; FIXME: This slows down the func way too much.
6920 ;; How keep drawers hidden in subtree anyway?
6921 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6922 ;; (org-cycle-hide-drawers 'subtree))
6924 ;; Fold every list in subtree to top-level items.
6925 (when (eq org-cycle-include-plain-lists 'integrate)
6926 (save-excursion
6927 (org-back-to-heading)
6928 (while (org-list-search-forward (org-item-beginning-re) eos t)
6929 (beginning-of-line 1)
6930 (let* ((struct (org-list-struct))
6931 (prevs (org-list-prevs-alist struct))
6932 (end (org-list-get-bottom-point struct)))
6933 (dolist (e (org-list-get-all-items (point) struct prevs))
6934 (org-list-set-item-visibility e struct 'folded))
6935 (goto-char (if (< end eos) end eos)))))))
6936 (org-unlogged-message "CHILDREN")
6937 (save-excursion
6938 (goto-char eos)
6939 (outline-next-heading)
6940 (when (org-invisible-p) (org-flag-heading nil)))
6941 (setq org-cycle-subtree-status 'children)
6942 (unless (org-before-first-heading-p)
6943 (run-hook-with-args 'org-cycle-hook 'children)))
6944 ((or children-skipped
6945 (and (eq last-command this-command)
6946 (eq org-cycle-subtree-status 'children)))
6947 ;; We just showed the children, or no children are there,
6948 ;; now show everything.
6949 (unless (org-before-first-heading-p)
6950 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6951 (outline-flag-region eoh eos nil)
6952 (org-unlogged-message
6953 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6954 (setq org-cycle-subtree-status 'subtree)
6955 (unless (org-before-first-heading-p)
6956 (run-hook-with-args 'org-cycle-hook 'subtree)))
6958 ;; Default action: hide the subtree.
6959 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6960 (outline-flag-region eoh eos t)
6961 (org-unlogged-message "FOLDED")
6962 (setq org-cycle-subtree-status 'folded)
6963 (unless (org-before-first-heading-p)
6964 (run-hook-with-args 'org-cycle-hook 'folded))))))
6966 ;;;###autoload
6967 (defun org-global-cycle (&optional arg)
6968 "Cycle the global visibility. For details see `org-cycle'.
6969 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6970 With a numeric prefix, show all headlines up to that level."
6971 (interactive "P")
6972 (let ((org-cycle-include-plain-lists
6973 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6974 (cond
6975 ((integerp arg)
6976 (outline-show-all)
6977 (outline-hide-sublevels arg)
6978 (setq org-cycle-global-status 'contents))
6979 ((equal arg '(4))
6980 (org-set-startup-visibility)
6981 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6983 (org-cycle '(4))))))
6985 (defun org-set-startup-visibility ()
6986 "Set the visibility required by startup options and properties."
6987 (cond
6988 ((eq org-startup-folded t)
6989 (org-overview))
6990 ((eq org-startup-folded 'content)
6991 (org-content))
6992 ((or (eq org-startup-folded 'showeverything)
6993 (eq org-startup-folded nil))
6994 (outline-show-all)))
6995 (unless (eq org-startup-folded 'showeverything)
6996 (when org-hide-block-startup (org-hide-block-all))
6997 (org-set-visibility-according-to-property 'no-cleanup)
6998 (org-cycle-hide-archived-subtrees 'all)
6999 (org-cycle-hide-drawers 'all)
7000 (org-cycle-show-empty-lines t)))
7002 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7003 "Switch subtree visibilities according to :VISIBILITY: property."
7004 (interactive)
7005 (org-with-wide-buffer
7006 (goto-char (point-min))
7007 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7008 (if (not (org-at-property-p)) (outline-next-heading)
7009 (let ((state (match-string 3)))
7010 (save-excursion
7011 (org-back-to-heading t)
7012 (outline-hide-subtree)
7013 (org-reveal)
7014 (cond
7015 ((equal state "folded")
7016 (outline-hide-subtree))
7017 ((equal state "children")
7018 (org-show-hidden-entry)
7019 (org-show-children))
7020 ((equal state "content")
7021 (save-excursion
7022 (save-restriction
7023 (org-narrow-to-subtree)
7024 (org-content))))
7025 ((member state '("all" "showall"))
7026 (outline-show-subtree)))))))
7027 (unless no-cleanup
7028 (org-cycle-hide-archived-subtrees 'all)
7029 (org-cycle-hide-drawers 'all)
7030 (org-cycle-show-empty-lines 'all))))
7032 ;; This function uses outline-regexp instead of the more fundamental
7033 ;; org-outline-regexp so that org-cycle-global works outside of Org
7034 ;; buffers, where outline-regexp is needed.
7035 (defun org-overview ()
7036 "Switch to overview mode, showing only top-level headlines.
7037 This shows all headlines with a level equal or greater than the level
7038 of the first headline in the buffer. This is important, because if the
7039 first headline is not level one, then (hide-sublevels 1) gives confusing
7040 results."
7041 (interactive)
7042 (save-excursion
7043 (let ((level
7044 (save-excursion
7045 (goto-char (point-min))
7046 (when (re-search-forward (concat "^" outline-regexp) nil t)
7047 (goto-char (match-beginning 0))
7048 (funcall outline-level)))))
7049 (and level (outline-hide-sublevels level)))))
7051 (defun org-content (&optional arg)
7052 "Show all headlines in the buffer, like a table of contents.
7053 With numerical argument N, show content up to level N."
7054 (interactive "P")
7055 (org-overview)
7056 (save-excursion
7057 ;; Visit all headings and show their offspring
7058 (and (integerp arg) (org-overview))
7059 (goto-char (point-max))
7060 (catch 'exit
7061 (while (and (progn (condition-case nil
7062 (outline-previous-visible-heading 1)
7063 (error (goto-char (point-min))))
7065 (looking-at org-outline-regexp))
7066 (if (integerp arg)
7067 (org-show-children (1- arg))
7068 (outline-show-branches))
7069 (when (bobp) (throw 'exit nil))))))
7071 (defun org-optimize-window-after-visibility-change (state)
7072 "Adjust the window after a change in outline visibility.
7073 This function is the default value of the hook `org-cycle-hook'."
7074 (when (get-buffer-window (current-buffer))
7075 (cond
7076 ((eq state 'content) nil)
7077 ((eq state 'all) nil)
7078 ((eq state 'folded) nil)
7079 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7080 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7082 (defun org-remove-empty-overlays-at (pos)
7083 "Remove outline overlays that do not contain non-white stuff."
7084 (dolist (o (overlays-at pos))
7085 (and (eq 'outline (overlay-get o 'invisible))
7086 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7087 (overlay-end o))))
7088 (delete-overlay o))))
7090 (defun org-clean-visibility-after-subtree-move ()
7091 "Fix visibility issues after moving a subtree."
7092 ;; First, find a reasonable region to look at:
7093 ;; Start two siblings above, end three below
7094 (let* ((beg (save-excursion
7095 (and (org-get-last-sibling)
7096 (org-get-last-sibling))
7097 (point)))
7098 (end (save-excursion
7099 (and (org-get-next-sibling)
7100 (org-get-next-sibling)
7101 (org-get-next-sibling))
7102 (if (org-at-heading-p)
7103 (point-at-eol)
7104 (point))))
7105 (level (looking-at "\\*+"))
7106 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7107 (save-excursion
7108 (save-restriction
7109 (narrow-to-region beg end)
7110 (when re
7111 ;; Properly fold already folded siblings
7112 (goto-char (point-min))
7113 (while (re-search-forward re nil t)
7114 (when (and (not (org-invisible-p))
7115 (save-excursion
7116 (goto-char (point-at-eol)) (org-invisible-p)))
7117 (outline-hide-entry))))
7118 (org-cycle-show-empty-lines 'overview)
7119 (org-cycle-hide-drawers 'overview)))))
7121 (defun org-cycle-show-empty-lines (state)
7122 "Show empty lines above all visible headlines.
7123 The region to be covered depends on STATE when called through
7124 `org-cycle-hook'. Lisp program can use t for STATE to get the
7125 entire buffer covered. Note that an empty line is only shown if there
7126 are at least `org-cycle-separator-lines' empty lines before the headline."
7127 (when (/= org-cycle-separator-lines 0)
7128 (save-excursion
7129 (let* ((n (abs org-cycle-separator-lines))
7130 (re (cond
7131 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7132 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7133 (t (let ((ns (number-to-string (- n 2))))
7134 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7135 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7136 beg end)
7137 (cond
7138 ((memq state '(overview contents t))
7139 (setq beg (point-min) end (point-max)))
7140 ((memq state '(children folded))
7141 (setq beg (point)
7142 end (progn (org-end-of-subtree t t)
7143 (line-beginning-position 2)))))
7144 (when beg
7145 (goto-char beg)
7146 (while (re-search-forward re end t)
7147 (unless (get-char-property (match-end 1) 'invisible)
7148 (let ((e (match-end 1))
7149 (b (if (>= org-cycle-separator-lines 0)
7150 (match-beginning 1)
7151 (save-excursion
7152 (goto-char (match-beginning 0))
7153 (skip-chars-backward " \t\n")
7154 (line-end-position)))))
7155 (outline-flag-region b e nil))))))))
7156 ;; Never hide empty lines at the end of the file.
7157 (save-excursion
7158 (goto-char (point-max))
7159 (outline-previous-heading)
7160 (outline-end-of-heading)
7161 (when (and (looking-at "[ \t\n]+")
7162 (= (match-end 0) (point-max)))
7163 (outline-flag-region (point) (match-end 0) nil))))
7165 (defun org-show-empty-lines-in-parent ()
7166 "Move to the parent and re-show empty lines before visible headlines."
7167 (save-excursion
7168 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7169 (org-cycle-show-empty-lines context))))
7171 (defun org-files-list ()
7172 "Return `org-agenda-files' list, plus all open Org files.
7173 This is useful for operations that need to scan all of a user's
7174 open and agenda-wise Org files."
7175 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7176 (dolist (buf (buffer-list))
7177 (with-current-buffer buf
7178 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7179 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7180 files))
7182 (defsubst org-entry-beginning-position ()
7183 "Return the beginning position of the current entry."
7184 (save-excursion (org-back-to-heading t) (point)))
7186 (defsubst org-entry-end-position ()
7187 "Return the end position of the current entry."
7188 (save-excursion (outline-next-heading) (point)))
7190 (defun org-cycle-hide-drawers (state &optional exceptions)
7191 "Re-hide all drawers after a visibility state change.
7192 STATE should be one of the symbols listed in the docstring of
7193 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7194 a list of strings specifying which drawers should not be hidden."
7195 (when (and (derived-mode-p 'org-mode)
7196 (not (memq state '(overview folded contents))))
7197 (save-excursion
7198 (let* ((globalp (eq state 'all))
7199 (beg (if globalp (point-min) (point)))
7200 (end (if globalp (point-max)
7201 (if (eq state 'children)
7202 (save-excursion (outline-next-heading) (point))
7203 (org-end-of-subtree t)))))
7204 (goto-char beg)
7205 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7206 (unless (member-ignore-case (match-string 1) exceptions)
7207 (let ((drawer (org-element-at-point)))
7208 (when (memq (org-element-type drawer) '(drawer property-drawer))
7209 (org-flag-drawer t drawer)
7210 ;; Make sure to skip drawer entirely or we might flag
7211 ;; it another time when matching its ending line with
7212 ;; `org-drawer-regexp'.
7213 (goto-char (org-element-property :end drawer))))))))))
7215 (defun org-flag-drawer (flag &optional element)
7216 "When FLAG is non-nil, hide the drawer we are at.
7217 Otherwise make it visible. When optional argument ELEMENT is
7218 a parsed drawer, as returned by `org-element-at-point', hide or
7219 show that drawer instead."
7220 (let ((drawer (or element
7221 (and (save-excursion
7222 (beginning-of-line)
7223 (looking-at-p org-drawer-regexp))
7224 (org-element-at-point)))))
7225 (when (memq (org-element-type drawer) '(drawer property-drawer))
7226 (let ((post (org-element-property :post-affiliated drawer)))
7227 (save-excursion
7228 (outline-flag-region
7229 (progn (goto-char post) (line-end-position))
7230 (progn (goto-char (org-element-property :end drawer))
7231 (skip-chars-backward " \r\t\n")
7232 (line-end-position))
7233 flag))
7234 ;; When the drawer is hidden away, make sure point lies in
7235 ;; a visible part of the buffer.
7236 (when (and flag (> (line-beginning-position) post))
7237 (goto-char post))))))
7239 (defun org-subtree-end-visible-p ()
7240 "Is the end of the current subtree visible?"
7241 (pos-visible-in-window-p
7242 (save-excursion (org-end-of-subtree t) (point))))
7244 (defun org-first-headline-recenter ()
7245 "Move cursor to the first headline and recenter the headline."
7246 (let ((window (get-buffer-window)))
7247 (when window
7248 (goto-char (point-min))
7249 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7250 (set-window-start window (line-beginning-position))))))
7252 ;;; Saving and restoring visibility
7254 (defun org-outline-overlay-data (&optional use-markers)
7255 "Return a list of the locations of all outline overlays.
7256 These are overlays with the `invisible' property value `outline'.
7257 The return value is a list of cons cells, with start and stop
7258 positions for each overlay.
7259 If USE-MARKERS is set, return the positions as markers."
7260 (let (beg end)
7261 (org-with-wide-buffer
7262 (delq nil
7263 (mapcar (lambda (o)
7264 (when (eq (overlay-get o 'invisible) 'outline)
7265 (setq beg (overlay-start o)
7266 end (overlay-end o))
7267 (and beg end (> end beg)
7268 (if use-markers
7269 (cons (copy-marker beg)
7270 (copy-marker end t))
7271 (cons beg end)))))
7272 (overlays-in (point-min) (point-max)))))))
7274 (defun org-set-outline-overlay-data (data)
7275 "Create visibility overlays for all positions in DATA.
7276 DATA should have been made by `org-outline-overlay-data'."
7277 (org-with-wide-buffer
7278 (outline-show-all)
7279 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7281 ;;; Folding of blocks
7283 (defvar-local org-hide-block-overlays nil
7284 "Overlays hiding blocks.")
7286 (defun org-block-map (function &optional start end)
7287 "Call FUNCTION at the head of all source blocks in the current buffer.
7288 Optional arguments START and END can be used to limit the range."
7289 (let ((start (or start (point-min)))
7290 (end (or end (point-max))))
7291 (save-excursion
7292 (goto-char start)
7293 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7294 (save-excursion
7295 (save-match-data
7296 (goto-char (match-beginning 0))
7297 (funcall function)))))))
7299 (defun org-hide-block-toggle-all ()
7300 "Toggle the visibility of all blocks in the current buffer."
7301 (org-block-map 'org-hide-block-toggle))
7303 (defun org-hide-block-all ()
7304 "Fold all blocks in the current buffer."
7305 (interactive)
7306 (org-show-block-all)
7307 (org-block-map 'org-hide-block-toggle-maybe))
7309 (defun org-show-block-all ()
7310 "Unfold all blocks in the current buffer."
7311 (interactive)
7312 (mapc #'delete-overlay org-hide-block-overlays)
7313 (setq org-hide-block-overlays nil))
7315 (defun org-hide-block-toggle-maybe ()
7316 "Toggle visibility of block at point.
7317 Unlike to `org-hide-block-toggle', this function does not throw
7318 an error. Return a non-nil value when toggling is successful."
7319 (interactive)
7320 (ignore-errors (org-hide-block-toggle)))
7322 (defun org-hide-block-toggle (&optional force)
7323 "Toggle the visibility of the current block.
7324 When optional argument FORCE is `off', make block visible. If it
7325 is non-nil, hide it unconditionally. Throw an error when not at
7326 a block. Return a non-nil value when toggling is successful."
7327 (interactive)
7328 (let ((element (org-element-at-point)))
7329 (unless (memq (org-element-type element)
7330 '(center-block comment-block dynamic-block example-block
7331 export-block quote-block special-block
7332 src-block verse-block))
7333 (user-error "Not at a block"))
7334 (let* ((start (save-excursion
7335 (goto-char (org-element-property :post-affiliated element))
7336 (line-end-position)))
7337 (end (save-excursion
7338 (goto-char (org-element-property :end element))
7339 (skip-chars-backward " \r\t\n")
7340 (line-end-position)))
7341 (overlays (overlays-at start)))
7342 (cond
7343 ;; Do nothing when not before or at the block opening line or
7344 ;; at the block closing line.
7345 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7346 ((and (not (eq force 'off))
7347 (not (memq t (mapcar
7348 (lambda (o)
7349 (eq (overlay-get o 'invisible) 'org-hide-block))
7350 overlays))))
7351 (let ((ov (make-overlay start end)))
7352 (overlay-put ov 'invisible 'org-hide-block)
7353 ;; Make the block accessible to `isearch'.
7354 (overlay-put
7355 ov 'isearch-open-invisible
7356 (lambda (ov)
7357 (when (memq ov org-hide-block-overlays)
7358 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7359 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7360 (delete-overlay ov))))
7361 (push ov org-hide-block-overlays)
7362 ;; When the block is hidden away, make sure point is left in
7363 ;; a visible part of the buffer.
7364 (when (> (line-beginning-position) start)
7365 (goto-char start)
7366 (beginning-of-line))
7367 ;; Signal successful toggling.
7369 ((or (not force) (eq force 'off))
7370 (dolist (ov overlays t)
7371 (when (memq ov org-hide-block-overlays)
7372 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7373 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7374 (delete-overlay ov))))))))
7376 ;; Remove overlays when changing major mode
7377 (add-hook 'org-mode-hook
7378 (lambda () (add-hook 'change-major-mode-hook
7379 'org-show-block-all 'append 'local)))
7381 ;;; Org-goto
7383 (defvar org-goto-window-configuration nil)
7384 (defvar org-goto-marker nil)
7385 (defvar org-goto-map)
7386 (defun org-goto-map ()
7387 "Set the keymap `org-goto'."
7388 (setq org-goto-map
7389 (let ((map (make-sparse-keymap)))
7390 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7391 mouse-drag-region universal-argument org-occur)))
7392 (dolist (cmd cmds)
7393 (substitute-key-definition cmd cmd map global-map)))
7394 (suppress-keymap map)
7395 (org-defkey map "\C-m" 'org-goto-ret)
7396 (org-defkey map [(return)] 'org-goto-ret)
7397 (org-defkey map [(left)] 'org-goto-left)
7398 (org-defkey map [(right)] 'org-goto-right)
7399 (org-defkey map [(control ?g)] 'org-goto-quit)
7400 (org-defkey map "\C-i" 'org-cycle)
7401 (org-defkey map [(tab)] 'org-cycle)
7402 (org-defkey map [(down)] 'outline-next-visible-heading)
7403 (org-defkey map [(up)] 'outline-previous-visible-heading)
7404 (if org-goto-auto-isearch
7405 (if (fboundp 'define-key-after)
7406 (define-key-after map [t] 'org-goto-local-auto-isearch)
7407 nil)
7408 (org-defkey map "q" 'org-goto-quit)
7409 (org-defkey map "n" 'outline-next-visible-heading)
7410 (org-defkey map "p" 'outline-previous-visible-heading)
7411 (org-defkey map "f" 'outline-forward-same-level)
7412 (org-defkey map "b" 'outline-backward-same-level)
7413 (org-defkey map "u" 'outline-up-heading))
7414 (org-defkey map "/" 'org-occur)
7415 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7416 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7417 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7418 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7419 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7420 map)))
7422 (defconst org-goto-help
7423 "Browse buffer copy, to find location or copy text.%s
7424 RET=jump to location C-g=quit and return to previous location
7425 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7427 (defvar org-goto-start-pos) ; dynamically scoped parameter
7429 (defun org-goto (&optional alternative-interface)
7430 "Look up a different location in the current file, keeping current visibility.
7432 When you want look-up or go to a different location in a
7433 document, the fastest way is often to fold the entire buffer and
7434 then dive into the tree. This method has the disadvantage, that
7435 the previous location will be folded, which may not be what you
7436 want.
7438 This command works around this by showing a copy of the current
7439 buffer in an indirect buffer, in overview mode. You can dive
7440 into the tree in that copy, use org-occur and incremental search
7441 to find a location. When pressing RET or `Q', the command
7442 returns to the original buffer in which the visibility is still
7443 unchanged. After RET it will also jump to the location selected
7444 in the indirect buffer and expose the headline hierarchy above.
7446 With a prefix argument, use the alternative interface: e.g., if
7447 `org-goto-interface' is `outline' use `outline-path-completion'."
7448 (interactive "P")
7449 (org-goto-map)
7450 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7451 (org-refile-use-outline-path t)
7452 (org-refile-target-verify-function nil)
7453 (interface
7454 (if (not alternative-interface)
7455 org-goto-interface
7456 (if (eq org-goto-interface 'outline)
7457 'outline-path-completion
7458 'outline)))
7459 (org-goto-start-pos (point))
7460 (selected-point
7461 (if (eq interface 'outline)
7462 (car (org-get-location (current-buffer) org-goto-help))
7463 (let ((pa (org-refile-get-location "Goto")))
7464 (org-refile-check-position pa)
7465 (nth 3 pa)))))
7466 (if selected-point
7467 (progn
7468 (org-mark-ring-push org-goto-start-pos)
7469 (goto-char selected-point)
7470 (when (or (org-invisible-p) (org-invisible-p2))
7471 (org-show-context 'org-goto)))
7472 (message "Quit"))))
7474 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7475 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7476 (defvar org-goto-local-auto-isearch-map) ; defined below
7478 (defun org-get-location (_buf help)
7479 "Let the user select a location in current buffer.
7480 This function uses a recursive edit. It returns the selected position
7481 or nil."
7482 (org-no-popups
7483 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7484 (isearch-hide-immediately nil)
7485 (isearch-search-fun-function
7486 (lambda () 'org-goto-local-search-headings))
7487 (org-goto-selected-point org-goto-exit-command))
7488 (save-excursion
7489 (save-window-excursion
7490 (delete-other-windows)
7491 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7492 (pop-to-buffer-same-window
7493 (condition-case nil
7494 (make-indirect-buffer (current-buffer) "*org-goto*")
7495 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7496 (with-output-to-temp-buffer "*Org Help*"
7497 (princ (format help (if org-goto-auto-isearch
7498 " Just type for auto-isearch."
7499 " n/p/f/b/u to navigate, q to quit."))))
7500 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7501 (setq buffer-read-only nil)
7502 (let ((org-startup-truncated t)
7503 (org-startup-folded nil)
7504 (org-startup-align-all-tables nil))
7505 (org-mode)
7506 (org-overview))
7507 (setq buffer-read-only t)
7508 (if (and (boundp 'org-goto-start-pos)
7509 (integer-or-marker-p org-goto-start-pos))
7510 (progn (goto-char org-goto-start-pos)
7511 (when (org-invisible-p)
7512 (org-show-set-visibility 'lineage)))
7513 (goto-char (point-min)))
7514 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7515 (message "Select location and press RET")
7516 (use-local-map org-goto-map)
7517 (recursive-edit)))
7518 (kill-buffer "*org-goto*")
7519 (cons org-goto-selected-point org-goto-exit-command))))
7521 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7522 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7523 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7524 (if (fboundp 'isearch-other-control-char)
7525 (progn
7526 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7527 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7528 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7529 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7530 (define-key org-goto-local-auto-isearch-map [return] nil))
7532 (defun org-goto-local-search-headings (string bound noerror)
7533 "Search and make sure that any matches are in headlines."
7534 (catch 'return
7535 (while (if isearch-forward
7536 (search-forward string bound noerror)
7537 (search-backward string bound noerror))
7538 (when (save-match-data
7539 (and (save-excursion
7540 (beginning-of-line)
7541 (looking-at org-complex-heading-regexp))
7542 (or (not (match-beginning 5))
7543 (< (point) (match-beginning 5)))))
7544 (throw 'return (point))))))
7546 (defun org-goto-local-auto-isearch ()
7547 "Start isearch."
7548 (interactive)
7549 (goto-char (point-min))
7550 (let ((keys (this-command-keys)))
7551 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7552 (isearch-mode t)
7553 (isearch-process-search-char (string-to-char keys)))))
7555 (defun org-goto-ret (&optional _arg)
7556 "Finish `org-goto' by going to the new location."
7557 (interactive "P")
7558 (setq org-goto-selected-point (point))
7559 (setq org-goto-exit-command 'return)
7560 (throw 'exit nil))
7562 (defun org-goto-left ()
7563 "Finish `org-goto' by going to the new location."
7564 (interactive)
7565 (if (org-at-heading-p)
7566 (progn
7567 (beginning-of-line 1)
7568 (setq org-goto-selected-point (point)
7569 org-goto-exit-command 'left)
7570 (throw 'exit nil))
7571 (user-error "Not on a heading")))
7573 (defun org-goto-right ()
7574 "Finish `org-goto' by going to the new location."
7575 (interactive)
7576 (if (org-at-heading-p)
7577 (progn
7578 (setq org-goto-selected-point (point)
7579 org-goto-exit-command 'right)
7580 (throw 'exit nil))
7581 (user-error "Not on a heading")))
7583 (defun org-goto-quit ()
7584 "Finish `org-goto' without cursor motion."
7585 (interactive)
7586 (setq org-goto-selected-point nil)
7587 (setq org-goto-exit-command 'quit)
7588 (throw 'exit nil))
7590 ;;; Indirect buffer display of subtrees
7592 (defvar org-indirect-dedicated-frame nil
7593 "This is the frame being used for indirect tree display.")
7594 (defvar org-last-indirect-buffer nil)
7596 (defun org-tree-to-indirect-buffer (&optional arg)
7597 "Create indirect buffer and narrow it to current subtree.
7599 With a numerical prefix ARG, go up to this level and then take that tree.
7600 If ARG is negative, go up that many levels.
7602 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7603 indirect buffer previously made with this command, to avoid proliferation of
7604 indirect buffers. However, when you call the command with a \
7605 `\\[universal-argument]' prefix, or
7606 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7607 so that you can work with several indirect buffers at the same time. If
7608 `org-indirect-buffer-display' is `dedicated-frame', the \
7609 `\\[universal-argument]' prefix also
7610 requests that a new frame be made for the new buffer, so that the dedicated
7611 frame is not changed."
7612 (interactive "P")
7613 (let ((cbuf (current-buffer))
7614 (cwin (selected-window))
7615 (pos (point))
7616 beg end level heading ibuf)
7617 (save-excursion
7618 (org-back-to-heading t)
7619 (when (numberp arg)
7620 (setq level (org-outline-level))
7621 (when (< arg 0) (setq arg (+ level arg)))
7622 (while (> (setq level (org-outline-level)) arg)
7623 (org-up-heading-safe)))
7624 (setq beg (point)
7625 heading (org-get-heading 'no-tags))
7626 (org-end-of-subtree t t)
7627 (when (org-at-heading-p) (backward-char 1))
7628 (setq end (point)))
7629 (when (and (buffer-live-p org-last-indirect-buffer)
7630 (not (eq org-indirect-buffer-display 'new-frame))
7631 (not arg))
7632 (kill-buffer org-last-indirect-buffer))
7633 (setq ibuf (org-get-indirect-buffer cbuf heading)
7634 org-last-indirect-buffer ibuf)
7635 (cond
7636 ((or (eq org-indirect-buffer-display 'new-frame)
7637 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7638 (select-frame (make-frame))
7639 (delete-other-windows)
7640 (pop-to-buffer-same-window ibuf)
7641 (org-set-frame-title heading))
7642 ((eq org-indirect-buffer-display 'dedicated-frame)
7643 (raise-frame
7644 (select-frame (or (and org-indirect-dedicated-frame
7645 (frame-live-p org-indirect-dedicated-frame)
7646 org-indirect-dedicated-frame)
7647 (setq org-indirect-dedicated-frame (make-frame)))))
7648 (delete-other-windows)
7649 (pop-to-buffer-same-window ibuf)
7650 (org-set-frame-title (concat "Indirect: " heading)))
7651 ((eq org-indirect-buffer-display 'current-window)
7652 (pop-to-buffer-same-window ibuf))
7653 ((eq org-indirect-buffer-display 'other-window)
7654 (pop-to-buffer ibuf))
7655 (t (error "Invalid value")))
7656 (narrow-to-region beg end)
7657 (outline-show-all)
7658 (goto-char pos)
7659 (run-hook-with-args 'org-cycle-hook 'all)
7660 (and (window-live-p cwin) (select-window cwin))))
7662 (defun org-get-indirect-buffer (&optional buffer heading)
7663 (setq buffer (or buffer (current-buffer)))
7664 (let ((n 1) (base (buffer-name buffer)) bname)
7665 (while (buffer-live-p
7666 (get-buffer
7667 (setq bname
7668 (concat base "-"
7669 (if heading (concat heading "-" (number-to-string n))
7670 (number-to-string n))))))
7671 (setq n (1+ n)))
7672 (condition-case nil
7673 (make-indirect-buffer buffer bname 'clone)
7674 (error (make-indirect-buffer buffer bname)))))
7676 (defun org-set-frame-title (title)
7677 "Set the title of the current frame to the string TITLE."
7678 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7680 ;;;; Structure editing
7682 ;;; Inserting headlines
7684 (defun org--line-empty-p (n)
7685 "Is the Nth next line empty?
7687 Counts the current line as N = 1 and the previous line as N = 0;
7688 see `beginning-of-line'."
7689 (save-excursion
7690 (and (not (bobp))
7691 (or (beginning-of-line n) t)
7692 (save-match-data
7693 (looking-at "[ \t]*$")))))
7695 (defun org-previous-line-empty-p ()
7696 "Is the previous line a blank line?
7697 When NEXT is non-nil, check the next line instead."
7698 (org--line-empty-p 0))
7700 (defun org-next-line-empty-p ()
7701 "Is the previous line a blank line?
7702 When NEXT is non-nil, check the next line instead."
7703 (org--line-empty-p 2))
7705 (defun org--blank-before-heading-p (&optional parent)
7706 "Non-nil when an empty line should precede a new heading here.
7707 When optional argument PARENT is non-nil, consider parent
7708 headline instead of current one."
7709 (pcase (assq 'heading org-blank-before-new-entry)
7710 (`(heading . auto)
7711 (save-excursion
7712 (org-with-limited-levels
7713 (unless (and (org-before-first-heading-p)
7714 (not (outline-next-heading)))
7715 (org-back-to-heading t)
7716 (when parent (org-up-heading-safe))
7717 (cond ((not (bobp))
7718 (org-previous-line-empty-p))
7719 ((outline-next-heading)
7720 (org-previous-line-empty-p))
7721 ;; Ignore trailing spaces on last buffer line.
7722 ((progn (skip-chars-backward " \t") (bolp))
7723 (org-previous-line-empty-p))
7724 (t nil))))))
7725 (`(heading . ,value) value)
7726 (_ nil)))
7728 (defun org-insert-heading (&optional arg invisible-ok top)
7729 "Insert a new heading or an item with the same depth at point.
7731 If point is at the beginning of a heading, insert a new heading
7732 or a new headline above the current one. When at the beginning
7733 of a regular line of text, turn it into a heading.
7735 If point is in the middle of a line, split it and create a new
7736 headline with the text in the current line after point (see
7737 `org-M-RET-may-split-line' on how to modify this behavior). As
7738 a special case, on a headline, splitting can only happen on the
7739 title itself. E.g., this excludes breaking stars or tags.
7741 With a `\\[universal-argument]' prefix, set \
7742 `org-insert-heading-respect-content' to
7743 a non-nil value for the duration of the command. This forces the
7744 insertion of a heading after the current subtree, independently
7745 on the location of point.
7747 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7748 insert the heading at the end of the tree
7749 above the current heading. For example, if point is within a
7750 2nd-level heading, then it will insert a 2nd-level heading at
7751 the end of the 1st-level parent subtree.
7753 When INVISIBLE-OK is set, stop at invisible headlines when going
7754 back. This is important for non-interactive uses of the
7755 command.
7757 When optional argument TOP is non-nil, insert a level 1 heading,
7758 unconditionally."
7759 (interactive "P")
7760 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7761 (level (org-current-level))
7762 (stars (make-string (if (and level (not top)) level 1) ?*)))
7763 (cond
7764 ((or org-insert-heading-respect-content
7765 (member arg '((4) (16)))
7766 (and (not invisible-ok)
7767 (invisible-p (max (1- (point)) (point-min)))))
7768 ;; Position point at the location of insertion.
7769 (if (not level) ;before first headline
7770 (org-with-limited-levels (outline-next-heading))
7771 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7772 ;; is nil.
7773 (org-with-limited-levels (org-back-to-heading invisible-ok))
7774 (cond ((equal arg '(16))
7775 (org-up-heading-safe)
7776 (org-end-of-subtree t t))
7778 (org-end-of-subtree t t))))
7779 (unless (bolp) (insert "\n")) ;ensure final newline
7780 (unless (and blank? (org-previous-line-empty-p))
7781 (org-N-empty-lines-before-current (if blank? 1 0)))
7782 (insert stars " \n")
7783 (forward-char -1))
7784 ;; At a headline...
7785 ((org-at-heading-p)
7786 (cond ((bolp)
7787 (when blank? (save-excursion (insert "\n")))
7788 (save-excursion (insert stars " \n"))
7789 (unless (and blank? (org-previous-line-empty-p))
7790 (org-N-empty-lines-before-current (if blank? 1 0)))
7791 (end-of-line))
7792 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7793 (org-match-line org-complex-heading-regexp)
7794 (org-pos-in-match-range (point) 4))
7795 ;; Grab the text that should moved to the new headline.
7796 ;; Preserve tags.
7797 (let ((split (delete-and-extract-region (point) (match-end 4))))
7798 (if (looking-at "[ \t]*$") (replace-match "")
7799 (org-set-tags nil t))
7800 (end-of-line)
7801 (when blank? (insert "\n"))
7802 (insert "\n" stars " ")
7803 (when (org-string-nw-p split) (insert split))
7804 (when (eobp) (save-excursion (insert "\n")))))
7806 (end-of-line)
7807 (when blank? (insert "\n"))
7808 (insert "\n" stars " ")
7809 (when (eobp) (save-excursion (insert "\n"))))))
7810 ;; On regular text, turn line into a headline or split, if
7811 ;; appropriate.
7812 ((bolp)
7813 (insert stars " ")
7814 (unless (and blank? (org-previous-line-empty-p))
7815 (org-N-empty-lines-before-current (if blank? 1 0))))
7817 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7818 (end-of-line))
7819 (insert "\n" stars " ")
7820 (unless (and blank? (org-previous-line-empty-p))
7821 (org-N-empty-lines-before-current (if blank? 1 0))))))
7822 (run-hooks 'org-insert-heading-hook))
7824 (defun org-N-empty-lines-before-current (n)
7825 "Make the number of empty lines before current exactly N.
7826 So this will delete or add empty lines."
7827 (let ((column (current-column)))
7828 (beginning-of-line)
7829 (unless (bobp)
7830 (let ((start (save-excursion
7831 (skip-chars-backward " \r\t\n")
7832 (line-end-position))))
7833 (delete-region start (line-end-position 0))))
7834 (insert (make-string n ?\n))
7835 (move-to-column column)))
7837 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7838 "Return the heading of the current entry, without the stars.
7839 When NO-TAGS is non-nil, don't include tags.
7840 When NO-TODO is non-nil, don't include TODO keywords.
7841 When NO-PRIORITY is non-nil, don't include priority cookie.
7842 When NO-COMMENT is non-nil, don't include COMMENT string."
7843 (save-excursion
7844 (org-back-to-heading t)
7845 (let ((case-fold-search nil))
7846 (looking-at org-complex-heading-regexp)
7847 (let ((todo (and (not no-todo) (match-string 2)))
7848 (priority (and (not no-priority) (match-string 3)))
7849 (headline (pcase (match-string 4)
7850 (`nil "")
7851 ((and (guard no-comment) h)
7852 (replace-regexp-in-string
7853 (eval-when-compile
7854 (format "\\`%s[ \t]+" org-comment-string))
7855 "" h))
7856 (h h)))
7857 (tags (and (not no-tags) (match-string 5))))
7858 (mapconcat #'identity
7859 (delq nil (list todo priority headline tags))
7860 " ")))))
7862 (defvar orgstruct-mode) ; defined below
7864 (defun org-heading-components ()
7865 "Return the components of the current heading.
7866 This is a list with the following elements:
7867 - the level as an integer
7868 - the reduced level, different if `org-odd-levels-only' is set.
7869 - the TODO keyword, or nil
7870 - the priority character, like ?A, or nil if no priority is given
7871 - the headline text itself, or the tags string if no headline text
7872 - the tags string, or nil."
7873 (save-excursion
7874 (org-back-to-heading t)
7875 (when (let (case-fold-search)
7876 (looking-at
7877 (if orgstruct-mode
7878 org-heading-regexp
7879 org-complex-heading-regexp)))
7880 (if orgstruct-mode
7881 (list (length (match-string 1))
7882 (org-reduced-level (length (match-string 1)))
7885 (match-string 2)
7886 nil)
7887 (list (length (match-string 1))
7888 (org-reduced-level (length (match-string 1)))
7889 (match-string-no-properties 2)
7890 (and (match-end 3) (aref (match-string 3) 2))
7891 (match-string-no-properties 4)
7892 (match-string-no-properties 5))))))
7894 (defun org-get-entry ()
7895 "Get the entry text, after heading, entire subtree."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7900 (defun org-edit-headline (&optional heading)
7901 "Edit the current headline.
7902 Set it to HEADING when provided."
7903 (interactive)
7904 (org-with-wide-buffer
7905 (org-back-to-heading t)
7906 (let ((case-fold-search nil))
7907 (when (looking-at org-complex-heading-regexp)
7908 (let* ((old (match-string-no-properties 4))
7909 (new (save-match-data
7910 (org-trim (or heading (read-string "Edit: " old))))))
7911 (unless (equal old new)
7912 (if old (replace-match new t t nil 4)
7913 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7914 (insert " " new))
7915 (org-set-tags nil t)
7916 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7918 (defun org-insert-heading-after-current ()
7919 "Insert a new heading with same level as current, after current subtree."
7920 (interactive)
7921 (org-back-to-heading)
7922 (org-insert-heading)
7923 (org-move-subtree-down)
7924 (end-of-line 1))
7926 (defun org-insert-heading-respect-content (&optional invisible-ok)
7927 "Insert heading with `org-insert-heading-respect-content' set to t."
7928 (interactive)
7929 (org-insert-heading '(4) invisible-ok))
7931 (defun org-insert-todo-heading-respect-content (&optional force-state)
7932 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7933 (interactive)
7934 (org-insert-todo-heading force-state '(4)))
7936 (defun org-insert-todo-heading (arg &optional force-heading)
7937 "Insert a new heading with the same level and TODO state as current heading.
7939 If the heading has no TODO state, or if the state is DONE, use
7940 the first state (TODO by default). Also with one prefix arg,
7941 force first state. With two prefix args, force inserting at the
7942 end of the parent subtree.
7944 When called at a plain list item, insert a new item with an
7945 unchecked check box."
7946 (interactive "P")
7947 (when (or force-heading (not (org-insert-item 'checkbox)))
7948 (org-insert-heading (or (and (equal arg '(16)) '(16))
7949 force-heading))
7950 (save-excursion
7951 (org-forward-heading-same-level -1)
7952 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7953 (let* ((new-mark-x
7954 (if (or (equal arg '(4))
7955 (not (match-beginning 2))
7956 (member (match-string 2) org-done-keywords))
7957 (car org-todo-keywords-1)
7958 (match-string 2)))
7959 (new-mark
7961 (run-hook-with-args-until-success
7962 'org-todo-get-default-hook new-mark-x nil)
7963 new-mark-x)))
7964 (beginning-of-line 1)
7965 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7966 (if org-treat-insert-todo-heading-as-state-change
7967 (org-todo new-mark)
7968 (insert new-mark " "))))
7969 (when org-provide-todo-statistics
7970 (org-update-parent-todo-statistics))))
7972 (defun org-insert-subheading (arg)
7973 "Insert a new subheading and demote it.
7974 Works for outline headings and for plain lists alike."
7975 (interactive "P")
7976 (org-insert-heading arg)
7977 (cond
7978 ((org-at-heading-p) (org-do-demote))
7979 ((org-at-item-p) (org-indent-item))))
7981 (defun org-insert-todo-subheading (arg)
7982 "Insert a new subheading with TODO keyword or checkbox and demote it.
7983 Works for outline headings and for plain lists alike."
7984 (interactive "P")
7985 (org-insert-todo-heading arg)
7986 (cond
7987 ((org-at-heading-p) (org-do-demote))
7988 ((org-at-item-p) (org-indent-item))))
7990 ;;; Promotion and Demotion
7992 (defvar org-after-demote-entry-hook nil
7993 "Hook run after an entry has been demoted.
7994 The cursor will be at the beginning of the entry.
7995 When a subtree is being demoted, the hook will be called for each node.")
7997 (defvar org-after-promote-entry-hook nil
7998 "Hook run after an entry has been promoted.
7999 The cursor will be at the beginning of the entry.
8000 When a subtree is being promoted, the hook will be called for each node.")
8002 (defun org-promote-subtree ()
8003 "Promote the entire subtree.
8004 See also `org-promote'."
8005 (interactive)
8006 (save-excursion
8007 (org-with-limited-levels (org-map-tree 'org-promote)))
8008 (org-fix-position-after-promote))
8010 (defun org-demote-subtree ()
8011 "Demote the entire subtree.
8012 See `org-demote' and `org-promote'."
8013 (interactive)
8014 (save-excursion
8015 (org-with-limited-levels (org-map-tree 'org-demote)))
8016 (org-fix-position-after-promote))
8018 (defun org-do-promote ()
8019 "Promote the current heading higher up the tree.
8020 If the region is active in `transient-mark-mode', promote all
8021 headings in the region."
8022 (interactive)
8023 (save-excursion
8024 (if (org-region-active-p)
8025 (org-map-region 'org-promote (region-beginning) (region-end))
8026 (org-promote)))
8027 (org-fix-position-after-promote))
8029 (defun org-do-demote ()
8030 "Demote the current heading lower down the tree.
8031 If the region is active in `transient-mark-mode', demote all
8032 headings in the region."
8033 (interactive)
8034 (save-excursion
8035 (if (org-region-active-p)
8036 (org-map-region 'org-demote (region-beginning) (region-end))
8037 (org-demote)))
8038 (org-fix-position-after-promote))
8040 (defun org-fix-position-after-promote ()
8041 "Fix cursor position and indentation after demoting/promoting."
8042 (let ((pos (point)))
8043 (when (save-excursion
8044 (beginning-of-line)
8045 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8046 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8047 (cond ((eobp) (insert " "))
8048 ((eolp) (insert " "))
8049 ((equal (char-after) ?\s) (forward-char 1))))))
8051 (defun org-current-level ()
8052 "Return the level of the current entry, or nil if before the first headline.
8053 The level is the number of stars at the beginning of the
8054 headline. Use `org-reduced-level' to remove the effect of
8055 `org-odd-levels'. Unlike to `org-outline-level', this function
8056 ignores inlinetasks."
8057 (let ((level (org-with-limited-levels (org-outline-level))))
8058 (and (> level 0) level)))
8060 (defun org-get-previous-line-level ()
8061 "Return the outline depth of the last headline before the current line.
8062 Returns 0 for the first headline in the buffer, and nil if before the
8063 first headline."
8064 (and (org-current-level)
8065 (or (and (/= (line-beginning-position) (point-min))
8066 (save-excursion (beginning-of-line 0) (org-current-level)))
8067 0)))
8069 (defun org-reduced-level (l)
8070 "Compute the effective level of a heading.
8071 This takes into account the setting of `org-odd-levels-only'."
8072 (cond
8073 ((zerop l) 0)
8074 (org-odd-levels-only (1+ (floor (/ l 2))))
8075 (t l)))
8077 (defun org-level-increment ()
8078 "Return the number of stars that will be added or removed at a
8079 time to headlines when structure editing, based on the value of
8080 `org-odd-levels-only'."
8081 (if org-odd-levels-only 2 1))
8083 (defun org-get-valid-level (level &optional change)
8084 "Rectify a level change under the influence of `org-odd-levels-only'.
8085 LEVEL is a current level, CHANGE is by how much the level should
8086 be modified. Even if CHANGE is nil, LEVEL may be returned
8087 modified because even level numbers will become the next higher
8088 odd number. Returns values greater than 0."
8089 (if org-odd-levels-only
8090 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8091 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8092 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8093 (max 1 (+ level (or change 0)))))
8095 (defun org-promote ()
8096 "Promote the current heading higher up the tree."
8097 (org-with-wide-buffer
8098 (org-back-to-heading t)
8099 (let* ((after-change-functions (remq 'flyspell-after-change-function
8100 after-change-functions))
8101 (level (save-match-data (funcall outline-level)))
8102 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8103 (diff (abs (- level (length up-head) -1))))
8104 (cond
8105 ((and (= level 1) org-allow-promoting-top-level-subtree)
8106 (replace-match "# " nil t))
8107 ((= level 1)
8108 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8109 (t (replace-match up-head nil t)))
8110 (unless (= level 1)
8111 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8112 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8113 (run-hooks 'org-after-promote-entry-hook))))
8115 (defun org-demote ()
8116 "Demote the current heading lower down the tree."
8117 (org-with-wide-buffer
8118 (org-back-to-heading t)
8119 (let* ((after-change-functions (remq 'flyspell-after-change-function
8120 after-change-functions))
8121 (level (save-match-data (funcall outline-level)))
8122 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8123 (diff (abs (- level (length down-head) -1))))
8124 (replace-match down-head nil t)
8125 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8126 (when org-adapt-indentation (org-fixup-indentation diff))
8127 (run-hooks 'org-after-demote-entry-hook))))
8129 (defun org-cycle-level ()
8130 "Cycle the level of an empty headline through possible states.
8131 This goes first to child, then to parent, level, then up the hierarchy.
8132 After top level, it switches back to sibling level."
8133 (interactive)
8134 (let ((org-adapt-indentation nil))
8135 (when (org-point-at-end-of-empty-headline)
8136 (setq this-command 'org-cycle-level) ; Only needed for caching
8137 (let ((cur-level (org-current-level))
8138 (prev-level (org-get-previous-line-level)))
8139 (cond
8140 ;; If first headline in file, promote to top-level.
8141 ((= prev-level 0)
8142 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8143 do (org-do-promote)))
8144 ;; If same level as prev, demote one.
8145 ((= prev-level cur-level)
8146 (org-do-demote))
8147 ;; If parent is top-level, promote to top level if not already.
8148 ((= prev-level 1)
8149 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8150 do (org-do-promote)))
8151 ;; If top-level, return to prev-level.
8152 ((= cur-level 1)
8153 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8154 do (org-do-demote)))
8155 ;; If less than prev-level, promote one.
8156 ((< cur-level prev-level)
8157 (org-do-promote))
8158 ;; If deeper than prev-level, promote until higher than
8159 ;; prev-level.
8160 ((> cur-level prev-level)
8161 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8162 do (org-do-promote))))
8163 t))))
8165 (defun org-map-tree (fun)
8166 "Call FUN for every heading underneath the current one."
8167 (org-back-to-heading t)
8168 (let ((level (funcall outline-level)))
8169 (save-excursion
8170 (funcall fun)
8171 (while (and (progn
8172 (outline-next-heading)
8173 (> (funcall outline-level) level))
8174 (not (eobp)))
8175 (funcall fun)))))
8177 (defun org-map-region (fun beg end)
8178 "Call FUN for every heading between BEG and END."
8179 (let ((org-ignore-region t))
8180 (save-excursion
8181 (setq end (copy-marker end))
8182 (goto-char beg)
8183 (when (and (re-search-forward org-outline-regexp-bol nil t)
8184 (< (point) end))
8185 (funcall fun))
8186 (while (and (progn
8187 (outline-next-heading)
8188 (< (point) end))
8189 (not (eobp)))
8190 (funcall fun)))))
8192 (defun org-fixup-indentation (diff)
8193 "Change the indentation in the current entry by DIFF.
8195 DIFF is an integer. Indentation is done according to the
8196 following rules:
8198 - Planning information and property drawers are always indented
8199 according to the new level of the headline;
8201 - Footnote definitions and their contents are ignored;
8203 - Inlinetasks' boundaries are not shifted;
8205 - Empty lines are ignored;
8207 - Other lines' indentation are shifted by DIFF columns, unless
8208 it would introduce a structural change in the document, in
8209 which case no shifting is done at all.
8211 Assume point is at a heading or an inlinetask beginning."
8212 (org-with-wide-buffer
8213 (narrow-to-region (line-beginning-position)
8214 (save-excursion
8215 (if (org-with-limited-levels (org-at-heading-p))
8216 (org-with-limited-levels (outline-next-heading))
8217 (org-inlinetask-goto-end))
8218 (point)))
8219 (forward-line)
8220 ;; Indent properly planning info and property drawer.
8221 (when (looking-at-p org-planning-line-re)
8222 (org-indent-line)
8223 (forward-line))
8224 (when (looking-at org-property-drawer-re)
8225 (goto-char (match-end 0))
8226 (forward-line)
8227 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8228 (catch 'no-shift
8229 (when (zerop diff) (throw 'no-shift nil))
8230 ;; If DIFF is negative, first check if a shift is possible at all
8231 ;; (e.g., it doesn't break structure). This can only happen if
8232 ;; some contents are not properly indented.
8233 (let ((case-fold-search t))
8234 (when (< diff 0)
8235 (let ((diff (- diff))
8236 (forbidden-re (concat org-outline-regexp
8237 "\\|"
8238 (substring org-footnote-definition-re 1))))
8239 (save-excursion
8240 (while (not (eobp))
8241 (cond
8242 ((looking-at-p "[ \t]*$") (forward-line))
8243 ((and (looking-at-p org-footnote-definition-re)
8244 (let ((e (org-element-at-point)))
8245 (and (eq (org-element-type e) 'footnote-definition)
8246 (goto-char (org-element-property :end e))))))
8247 ((looking-at-p org-outline-regexp) (forward-line))
8248 ;; Give up if shifting would move before column 0 or
8249 ;; if it would introduce a headline or a footnote
8250 ;; definition.
8252 (skip-chars-forward " \t")
8253 (let ((ind (current-column)))
8254 (when (or (< ind diff)
8255 (and (= ind diff) (looking-at-p forbidden-re)))
8256 (throw 'no-shift nil)))
8257 ;; Ignore contents of example blocks and source
8258 ;; blocks if their indentation is meant to be
8259 ;; preserved. Jump to block's closing line.
8260 (beginning-of-line)
8261 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8262 (let ((e (org-element-at-point)))
8263 (and (memq (org-element-type e)
8264 '(example-block src-block))
8265 (or org-src-preserve-indentation
8266 (org-element-property :preserve-indent e))
8267 (goto-char (org-element-property :end e))
8268 (progn (skip-chars-backward " \r\t\n")
8269 (beginning-of-line)
8270 t))))
8271 (forward-line))))))))
8272 ;; Shift lines but footnote definitions, inlinetasks boundaries
8273 ;; by DIFF. Also skip contents of source or example blocks
8274 ;; when indentation is meant to be preserved.
8275 (while (not (eobp))
8276 (cond
8277 ((and (looking-at-p org-footnote-definition-re)
8278 (let ((e (org-element-at-point)))
8279 (and (eq (org-element-type e) 'footnote-definition)
8280 (goto-char (org-element-property :end e))))))
8281 ((looking-at-p org-outline-regexp) (forward-line))
8282 ((looking-at-p "[ \t]*$") (forward-line))
8284 (indent-line-to (+ (org-get-indentation) diff))
8285 (beginning-of-line)
8286 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8287 (let ((e (org-element-at-point)))
8288 (and (memq (org-element-type e)
8289 '(example-block src-block))
8290 (or org-src-preserve-indentation
8291 (org-element-property :preserve-indent e))
8292 (goto-char (org-element-property :end e))
8293 (progn (skip-chars-backward " \r\t\n")
8294 (beginning-of-line)
8295 t))))
8296 (forward-line)))))))))
8298 (defun org-convert-to-odd-levels ()
8299 "Convert an Org file with all levels allowed to one with odd levels.
8300 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8301 level 5 etc."
8302 (interactive)
8303 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8304 (let ((outline-level 'org-outline-level)
8305 (org-odd-levels-only nil) n)
8306 (save-excursion
8307 (goto-char (point-min))
8308 (while (re-search-forward "^\\*\\*+ " nil t)
8309 (setq n (- (length (match-string 0)) 2))
8310 (while (>= (setq n (1- n)) 0)
8311 (org-demote))
8312 (end-of-line 1))))))
8314 (defun org-convert-to-oddeven-levels ()
8315 "Convert an Org file with only odd levels to one with odd/even levels.
8316 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8317 file contains a section with an even level, conversion would
8318 destroy the structure of the file. An error is signaled in this
8319 case."
8320 (interactive)
8321 (goto-char (point-min))
8322 ;; First check if there are no even levels
8323 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8324 (org-show-set-visibility 'canonical)
8325 (error "Not all levels are odd in this file. Conversion not possible"))
8326 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8327 (let ((outline-regexp org-outline-regexp)
8328 (outline-level 'org-outline-level)
8329 (org-odd-levels-only nil) n)
8330 (save-excursion
8331 (goto-char (point-min))
8332 (while (re-search-forward "^\\*\\*+ " nil t)
8333 (setq n (/ (1- (length (match-string 0))) 2))
8334 (while (>= (setq n (1- n)) 0)
8335 (org-promote))
8336 (end-of-line 1))))))
8338 (defun org-tr-level (n)
8339 "Make N odd if required."
8340 (if org-odd-levels-only (1+ (/ n 2)) n))
8342 ;;; Vertical tree motion, cutting and pasting of subtrees
8344 (defun org-move-subtree-up (&optional arg)
8345 "Move the current subtree up past ARG headlines of the same level."
8346 (interactive "p")
8347 (org-move-subtree-down (- (prefix-numeric-value arg))))
8349 (defun org-move-subtree-down (&optional arg)
8350 "Move the current subtree down past ARG headlines of the same level."
8351 (interactive "p")
8352 (setq arg (prefix-numeric-value arg))
8353 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8354 'org-get-last-sibling))
8355 (ins-point (make-marker))
8356 (cnt (abs arg))
8357 (col (current-column))
8358 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8359 ;; Select the tree
8360 (org-back-to-heading)
8361 (setq beg0 (point))
8362 (save-excursion
8363 (setq ne-beg (org-back-over-empty-lines))
8364 (setq beg (point)))
8365 (save-match-data
8366 (save-excursion (outline-end-of-heading)
8367 (setq folded (org-invisible-p)))
8368 (progn (org-end-of-subtree nil t)
8369 (unless (eobp) (backward-char))))
8370 (outline-next-heading)
8371 (setq ne-end (org-back-over-empty-lines))
8372 (setq end (point))
8373 (goto-char beg0)
8374 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8375 ;; include less whitespace
8376 (save-excursion
8377 (goto-char beg)
8378 (forward-line (- ne-beg ne-end))
8379 (setq beg (point))))
8380 ;; Find insertion point, with error handling
8381 (while (> cnt 0)
8382 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8383 (progn (goto-char beg0)
8384 (user-error "Cannot move past superior level or buffer limit")))
8385 (setq cnt (1- cnt)))
8386 (when (> arg 0)
8387 ;; Moving forward - still need to move over subtree
8388 (org-end-of-subtree t t)
8389 (save-excursion
8390 (org-back-over-empty-lines)
8391 (or (bolp) (newline))))
8392 (setq ne-ins (org-back-over-empty-lines))
8393 (move-marker ins-point (point))
8394 (setq txt (buffer-substring beg end))
8395 (org-save-markers-in-region beg end)
8396 (delete-region beg end)
8397 (org-remove-empty-overlays-at beg)
8398 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8399 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8400 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8401 (let ((bbb (point)))
8402 (insert-before-markers txt)
8403 (org-reinstall-markers-in-region bbb)
8404 (move-marker ins-point bbb))
8405 (or (bolp) (insert "\n"))
8406 (setq ins-end (point))
8407 (goto-char ins-point)
8408 (org-skip-whitespace)
8409 (when (and (< arg 0)
8410 (org-first-sibling-p)
8411 (> ne-ins ne-beg))
8412 ;; Move whitespace back to beginning
8413 (save-excursion
8414 (goto-char ins-end)
8415 (let ((kill-whole-line t))
8416 (kill-line (- ne-ins ne-beg)) (point)))
8417 (insert (make-string (- ne-ins ne-beg) ?\n)))
8418 (move-marker ins-point nil)
8419 (if folded
8420 (outline-hide-subtree)
8421 (org-show-entry)
8422 (org-show-children)
8423 (org-cycle-hide-drawers 'children))
8424 (org-clean-visibility-after-subtree-move)
8425 ;; move back to the initial column we were at
8426 (move-to-column col)))
8428 (defvar org-subtree-clip ""
8429 "Clipboard for cut and paste of subtrees.
8430 This is actually only a copy of the kill, because we use the normal kill
8431 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8433 (defvar org-subtree-clip-folded nil
8434 "Was the last copied subtree folded?
8435 This is used to fold the tree back after pasting.")
8437 (defun org-cut-subtree (&optional n)
8438 "Cut the current subtree into the clipboard.
8439 With prefix arg N, cut this many sequential subtrees.
8440 This is a short-hand for marking the subtree and then cutting it."
8441 (interactive "p")
8442 (org-copy-subtree n 'cut))
8444 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8445 "Copy the current subtree it in the clipboard.
8446 With prefix arg N, copy this many sequential subtrees.
8447 This is a short-hand for marking the subtree and then copying it.
8448 If CUT is non-nil, actually cut the subtree.
8449 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8450 of some markers in the region, even if CUT is non-nil. This is
8451 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8452 (interactive "p")
8453 (let (beg end folded (beg0 (point)))
8454 (if (called-interactively-p 'any)
8455 (org-back-to-heading nil) ; take what looks like a subtree
8456 (org-back-to-heading t)) ; take what is really there
8457 (setq beg (point))
8458 (skip-chars-forward " \t\r\n")
8459 (save-match-data
8460 (if nosubtrees
8461 (outline-next-heading)
8462 (save-excursion (outline-end-of-heading)
8463 (setq folded (org-invisible-p)))
8464 (ignore-errors (org-forward-heading-same-level (1- n) t))
8465 (org-end-of-subtree t t)))
8466 ;; Include the end of an inlinetask
8467 (when (and (featurep 'org-inlinetask)
8468 (looking-at-p (concat (org-inlinetask-outline-regexp)
8469 "END[ \t]*$")))
8470 (end-of-line))
8471 (setq end (point))
8472 (goto-char beg0)
8473 (when (> end beg)
8474 (setq org-subtree-clip-folded folded)
8475 (when (or cut force-store-markers)
8476 (org-save-markers-in-region beg end))
8477 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8478 (setq org-subtree-clip (current-kill 0))
8479 (message "%s: Subtree(s) with %d characters"
8480 (if cut "Cut" "Copied")
8481 (length org-subtree-clip)))))
8483 (defun org-paste-subtree (&optional level tree for-yank remove)
8484 "Paste the clipboard as a subtree, with modification of headline level.
8485 The entire subtree is promoted or demoted in order to match a new headline
8486 level.
8488 If the cursor is at the beginning of a headline, the same level as
8489 that headline is used to paste the tree.
8491 If not, the new level is derived from the *visible* headings
8492 before and after the insertion point, and taken to be the inferior headline
8493 level of the two. So if the previous visible heading is level 3 and the
8494 next is level 4 (or vice versa), level 4 will be used for insertion.
8495 This makes sure that the subtree remains an independent subtree and does
8496 not swallow low level entries.
8498 You can also force a different level, either by using a numeric prefix
8499 argument, or by inserting the heading marker by hand. For example, if the
8500 cursor is after \"*****\", then the tree will be shifted to level 5.
8502 If optional TREE is given, use this text instead of the kill ring.
8504 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8505 move back over whitespace before inserting, and move point to the end of
8506 the inserted text when done.
8508 When REMOVE is non-nil, remove the subtree from the clipboard."
8509 (interactive "P")
8510 (setq tree (or tree (and kill-ring (current-kill 0))))
8511 (unless (org-kill-is-subtree-p tree)
8512 (user-error "%s"
8513 (substitute-command-keys
8514 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8515 (org-with-limited-levels
8516 (let* ((visp (not (org-invisible-p)))
8517 (txt tree)
8518 (^re_ "\\(\\*+\\)[ \t]*")
8519 (old-level (if (string-match org-outline-regexp-bol txt)
8520 (- (match-end 0) (match-beginning 0) 1)
8521 -1))
8522 (force-level (cond (level (prefix-numeric-value level))
8523 ((and (looking-at "[ \t]*$")
8524 (string-match
8525 "^\\*+$" (buffer-substring
8526 (point-at-bol) (point))))
8527 (- (match-end 0) (match-beginning 0)))
8528 ((and (bolp)
8529 (looking-at org-outline-regexp))
8530 (- (match-end 0) (point) 1))))
8531 (previous-level (save-excursion
8532 (condition-case nil
8533 (progn
8534 (outline-previous-visible-heading 1)
8535 (if (looking-at ^re_)
8536 (- (match-end 0) (match-beginning 0) 1)
8538 (error 1))))
8539 (next-level (save-excursion
8540 (condition-case nil
8541 (progn
8542 (or (looking-at org-outline-regexp)
8543 (outline-next-visible-heading 1))
8544 (if (looking-at ^re_)
8545 (- (match-end 0) (match-beginning 0) 1)
8547 (error 1))))
8548 (new-level (or force-level (max previous-level next-level)))
8549 (shift (if (or (= old-level -1)
8550 (= new-level -1)
8551 (= old-level new-level))
8553 (- new-level old-level)))
8554 (delta (if (> shift 0) -1 1))
8555 (func (if (> shift 0) 'org-demote 'org-promote))
8556 (org-odd-levels-only nil)
8557 beg end newend)
8558 ;; Remove the forced level indicator
8559 (when force-level
8560 (delete-region (point-at-bol) (point)))
8561 ;; Paste
8562 (beginning-of-line (if (bolp) 1 2))
8563 (setq beg (point))
8564 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8565 (insert-before-markers txt)
8566 (unless (string-suffix-p "\n" txt) (insert "\n"))
8567 (setq newend (point))
8568 (org-reinstall-markers-in-region beg)
8569 (setq end (point))
8570 (goto-char beg)
8571 (skip-chars-forward " \t\n\r")
8572 (setq beg (point))
8573 (when (and (org-invisible-p) visp)
8574 (save-excursion (outline-show-heading)))
8575 ;; Shift if necessary
8576 (unless (= shift 0)
8577 (save-restriction
8578 (narrow-to-region beg end)
8579 (while (not (= shift 0))
8580 (org-map-region func (point-min) (point-max))
8581 (setq shift (+ delta shift)))
8582 (goto-char (point-min))
8583 (setq newend (point-max))))
8584 (when (or (called-interactively-p 'interactive) for-yank)
8585 (message "Clipboard pasted as level %d subtree" new-level))
8586 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8587 kill-ring
8588 (eq org-subtree-clip (current-kill 0))
8589 org-subtree-clip-folded)
8590 ;; The tree was folded before it was killed/copied
8591 (outline-hide-subtree))
8592 (and for-yank (goto-char newend))
8593 (and remove (setq kill-ring (cdr kill-ring))))))
8595 (defun org-kill-is-subtree-p (&optional txt)
8596 "Check if the current kill is an outline subtree, or a set of trees.
8597 Returns nil if kill does not start with a headline, or if the first
8598 headline level is not the largest headline level in the tree.
8599 So this will actually accept several entries of equal levels as well,
8600 which is OK for `org-paste-subtree'.
8601 If optional TXT is given, check this string instead of the current kill."
8602 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8603 (re (org-get-limited-outline-regexp))
8604 (^re (concat "^" re))
8605 (start-level (and kill
8606 (string-match
8607 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8608 kill)
8609 (- (match-end 2) (match-beginning 2) 1)))
8610 (start (1+ (or (match-beginning 2) -1))))
8611 (if (not start-level)
8612 (progn
8613 nil) ;; does not even start with a heading
8614 (catch 'exit
8615 (while (setq start (string-match ^re kill (1+ start)))
8616 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8617 (throw 'exit nil)))
8618 t))))
8620 (defvar org-markers-to-move nil
8621 "Markers that should be moved with a cut-and-paste operation.
8622 Those markers are stored together with their positions relative to
8623 the start of the region.")
8625 (defun org-save-markers-in-region (beg end)
8626 "Check markers in region.
8627 If these markers are between BEG and END, record their position relative
8628 to BEG, so that after moving the block of text, we can put the markers back
8629 into place.
8630 This function gets called just before an entry or tree gets cut from the
8631 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8632 called immediately, to move the markers with the entries."
8633 (setq org-markers-to-move nil)
8634 (when (featurep 'org-clock)
8635 (org-clock-save-markers-for-cut-and-paste beg end))
8636 (when (featurep 'org-agenda)
8637 (org-agenda-save-markers-for-cut-and-paste beg end)))
8639 (defun org-check-and-save-marker (marker beg end)
8640 "Check if MARKER is between BEG and END.
8641 If yes, remember the marker and the distance to BEG."
8642 (when (and (marker-buffer marker)
8643 (equal (marker-buffer marker) (current-buffer))
8644 (>= marker beg) (< marker end))
8645 (push (cons marker (- marker beg)) org-markers-to-move)))
8647 (defun org-reinstall-markers-in-region (beg)
8648 "Move all remembered markers to their position relative to BEG."
8649 (dolist (x org-markers-to-move)
8650 (move-marker (car x) (+ beg (cdr x))))
8651 (setq org-markers-to-move nil))
8653 (defun org-narrow-to-subtree ()
8654 "Narrow buffer to the current subtree."
8655 (interactive)
8656 (save-excursion
8657 (save-match-data
8658 (org-with-limited-levels
8659 (narrow-to-region
8660 (progn (org-back-to-heading t) (point))
8661 (progn (org-end-of-subtree t t)
8662 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8663 (point)))))))
8665 (defun org-narrow-to-block ()
8666 "Narrow buffer to the current block."
8667 (interactive)
8668 (let* ((case-fold-search t)
8669 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8670 "^[ \t]*#\\+end_.*")))
8671 (if blockp
8672 (narrow-to-region (car blockp) (cdr blockp))
8673 (user-error "Not in a block"))))
8675 (defun org-clone-subtree-with-time-shift (n &optional shift)
8676 "Clone the task (subtree) at point N times.
8677 The clones will be inserted as siblings.
8679 In interactive use, the user will be prompted for the number of
8680 clones to be produced. If the entry has a timestamp, the user
8681 will also be prompted for a time shift, which may be a repeater
8682 as used in time stamps, for example `+3d'. To disable this,
8683 you can call the function with a universal prefix argument.
8685 When a valid repeater is given and the entry contains any time
8686 stamps, the clones will become a sequence in time, with time
8687 stamps in the subtree shifted for each clone produced. If SHIFT
8688 is nil or the empty string, time stamps will be left alone. The
8689 ID property of the original subtree is removed.
8691 In each clone, all the CLOCK entries will be removed. This
8692 prevents Org from considering that the clocked times overlap.
8694 If the original subtree did contain time stamps with a repeater,
8695 the following will happen:
8696 - the repeater will be removed in each clone
8697 - an additional clone will be produced, with the current, unshifted
8698 date(s) in the entry.
8699 - the original entry will be placed *after* all the clones, with
8700 repeater intact.
8701 - the start days in the repeater in the original entry will be shifted
8702 to past the last clone.
8703 In this way you can spell out a number of instances of a repeating task,
8704 and still retain the repeater to cover future instances of the task.
8706 As described above, N+1 clones are produced when the original
8707 subtree has a repeater. Setting N to 0, then, can be used to
8708 remove the repeater from a subtree and create a shifted clone
8709 with the original repeater."
8710 (interactive "nNumber of clones to produce: ")
8711 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8712 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8713 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8714 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8715 (shift
8716 (or shift
8717 (if (and (not (equal current-prefix-arg '(4)))
8718 (save-excursion
8719 (goto-char beg)
8720 (re-search-forward org-ts-regexp-both end-of-tree t)))
8721 (read-from-minibuffer
8722 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8723 ""))) ;No time shift
8724 (doshift
8725 (and (org-string-nw-p shift)
8726 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8727 shift)
8728 (user-error "Invalid shift specification %s" shift)))))
8729 (goto-char end-of-tree)
8730 (unless (bolp) (insert "\n"))
8731 (let* ((end (point))
8732 (template (buffer-substring beg end))
8733 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8734 (shift-what (pcase (and doshift (match-string 2 shift))
8735 (`nil nil)
8736 ("d" 'day)
8737 ("w" (setq shift-n (* 7 shift-n)) 'day)
8738 ("m" 'month)
8739 ("y" 'year)
8740 (_ (error "Unsupported time unit"))))
8741 (nmin 1)
8742 (nmax n)
8743 (n-no-remove -1)
8744 (idprop (org-entry-get nil "ID")))
8745 (when (and doshift
8746 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8747 template))
8748 (delete-region beg end)
8749 (setq end beg)
8750 (setq nmin 0)
8751 (setq nmax (1+ nmax))
8752 (setq n-no-remove nmax))
8753 (goto-char end)
8754 (cl-loop for n from nmin to nmax do
8755 (insert
8756 ;; Prepare clone.
8757 (with-temp-buffer
8758 (insert template)
8759 (org-mode)
8760 (goto-char (point-min))
8761 (org-show-subtree)
8762 (and idprop (if org-clone-delete-id
8763 (org-entry-delete nil "ID")
8764 (org-id-get-create t)))
8765 (unless (= n 0)
8766 (while (re-search-forward org-clock-line-re nil t)
8767 (delete-region (line-beginning-position)
8768 (line-beginning-position 2)))
8769 (goto-char (point-min))
8770 (while (re-search-forward org-drawer-regexp nil t)
8771 (org-remove-empty-drawer-at (point))))
8772 (goto-char (point-min))
8773 (when doshift
8774 (while (re-search-forward org-ts-regexp-both nil t)
8775 (org-timestamp-change (* n shift-n) shift-what))
8776 (unless (= n n-no-remove)
8777 (goto-char (point-min))
8778 (while (re-search-forward org-ts-regexp nil t)
8779 (save-excursion
8780 (goto-char (match-beginning 0))
8781 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8782 (delete-region (match-beginning 1) (match-end 1)))))))
8783 (buffer-string)))))
8784 (goto-char beg)))
8786 ;;; Outline Sorting
8788 (defun org-sort (&optional with-case)
8789 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8790 Optional argument WITH-CASE means sort case-sensitively."
8791 (interactive "P")
8792 (org-call-with-arg
8793 (cond ((org-at-table-p) #'org-table-sort-lines)
8794 ((org-at-item-p) #'org-sort-list)
8795 (t #'org-sort-entries))
8796 with-case))
8798 (defun org-sort-remove-invisible (s)
8799 "Remove invisible part of links and emphasis markers from string S."
8800 (remove-text-properties 0 (length s) org-rm-props s)
8801 (replace-regexp-in-string
8802 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8803 (replace-regexp-in-string
8804 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8805 (org-link-display-format s)
8806 t t) t t))
8808 (defvar org-priority-regexp) ; defined later in the file
8810 (defvar org-after-sorting-entries-or-items-hook nil
8811 "Hook that is run after a bunch of entries or items have been sorted.
8812 When children are sorted, the cursor is in the parent line when this
8813 hook gets called. When a region or a plain list is sorted, the cursor
8814 will be in the first entry of the sorted region/list.")
8816 (defun org-sort-entries
8817 (&optional with-case sorting-type getkey-func compare-func property
8818 interactive?)
8819 "Sort entries on a certain level of an outline tree.
8820 If there is an active region, the entries in the region are sorted.
8821 Else, if the cursor is before the first entry, sort the top-level items.
8822 Else, the children of the entry at point are sorted.
8824 Sorting can be alphabetically, numerically, by date/time as given by
8825 a time stamp, by a property, by priority order, or by a custom function.
8827 The command prompts for the sorting type unless it has been given to the
8828 function through the SORTING-TYPE argument, which needs to be a character,
8829 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8830 the precise meaning of each character:
8832 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8833 c By creation time, which is assumed to be the first inactive time stamp
8834 at the beginning of a line.
8835 d By deadline date/time.
8836 k By clocking time.
8837 n Numerically, by converting the beginning of the entry/item to a number.
8838 o By order of TODO keywords.
8839 p By priority according to the cookie.
8840 r By the value of a property.
8841 s By scheduled date/time.
8842 t By date/time, either the first active time stamp in the entry, or, if
8843 none exist, by the first inactive one.
8845 Capital letters will reverse the sort order.
8847 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8848 called with point at the beginning of the record. It must return a
8849 value that is compatible with COMPARE-FUNC, the function used to
8850 compare entries.
8852 Comparing entries ignores case by default. However, with an optional argument
8853 WITH-CASE, the sorting considers case as well.
8855 Sorting is done against the visible part of the headlines, it ignores hidden
8856 links.
8858 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8860 A non-nil value for INTERACTIVE? is used to signal that this
8861 function is being called interactively."
8862 (interactive (list current-prefix-arg nil nil nil nil t))
8863 (let ((case-func (if with-case 'identity 'downcase))
8864 start beg end stars re re2
8865 txt what tmp)
8866 ;; Find beginning and end of region to sort
8867 (cond
8868 ((org-region-active-p)
8869 ;; we will sort the region
8870 (setq end (region-end)
8871 what "region")
8872 (goto-char (region-beginning))
8873 (unless (org-at-heading-p) (outline-next-heading))
8874 (setq start (point)))
8875 ((or (org-at-heading-p)
8876 (ignore-errors (progn (org-back-to-heading) t)))
8877 ;; we will sort the children of the current headline
8878 (org-back-to-heading)
8879 (setq start (point)
8880 end (progn (org-end-of-subtree t t)
8881 (or (bolp) (insert "\n"))
8882 (when (>= (org-back-over-empty-lines) 1)
8883 (forward-line 1))
8884 (point))
8885 what "children")
8886 (goto-char start)
8887 (outline-show-subtree)
8888 (outline-next-heading))
8890 ;; we will sort the top-level entries in this file
8891 (goto-char (point-min))
8892 (or (org-at-heading-p) (outline-next-heading))
8893 (setq start (point))
8894 (goto-char (point-max))
8895 (beginning-of-line 1)
8896 (when (looking-at ".*?\\S-")
8897 ;; File ends in a non-white line
8898 (end-of-line 1)
8899 (insert "\n"))
8900 (setq end (point-max))
8901 (setq what "top-level")
8902 (goto-char start)
8903 (outline-show-all)))
8905 (setq beg (point))
8906 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8908 (looking-at "\\(\\*+\\)")
8909 (setq stars (match-string 1)
8910 re (concat "^" (regexp-quote stars) " +")
8911 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8912 txt (buffer-substring beg end))
8913 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8914 (when (and (not (equal stars "*")) (string-match re2 txt))
8915 (user-error "Region to sort contains a level above the first entry"))
8917 (unless sorting-type
8918 (message
8919 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8920 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8921 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8922 what)
8923 (setq sorting-type (read-char-exclusive)))
8925 (unless getkey-func
8926 (and (= (downcase sorting-type) ?f)
8927 (setq getkey-func
8928 (or (and interactive?
8929 (org-read-function
8930 "Function for extracting keys: "))
8931 (error "Missing key extractor")))))
8933 (and (= (downcase sorting-type) ?r)
8934 (not property)
8935 (setq property
8936 (completing-read "Property: "
8937 (mapcar #'list (org-buffer-property-keys t))
8938 nil t)))
8940 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8941 (message "Sorting entries...")
8943 (save-restriction
8944 (narrow-to-region start end)
8945 (let ((restore-clock?
8946 ;; The clock marker is lost when using `sort-subr'; mark
8947 ;; the clock with temporary `:org-clock-marker-backup'
8948 ;; text property.
8949 (when (and (eq (org-clock-is-active) (current-buffer))
8950 (<= start (marker-position org-clock-marker))
8951 (>= end (marker-position org-clock-marker)))
8952 (org-with-silent-modifications
8953 (put-text-property (1- org-clock-marker) org-clock-marker
8954 :org-clock-marker-backup t))
8956 (dcst (downcase sorting-type))
8957 (case-fold-search nil)
8958 (now (current-time)))
8959 (sort-subr
8960 (/= dcst sorting-type)
8961 ;; This function moves to the beginning character of the "record" to
8962 ;; be sorted.
8963 (lambda nil
8964 (if (re-search-forward re nil t)
8965 (goto-char (match-beginning 0))
8966 (goto-char (point-max))))
8967 ;; This function moves to the last character of the "record" being
8968 ;; sorted.
8969 (lambda nil
8970 (save-match-data
8971 (condition-case nil
8972 (outline-forward-same-level 1)
8973 (error
8974 (goto-char (point-max))))))
8975 ;; This function returns the value that gets sorted against.
8976 (lambda nil
8977 (cond
8978 ((= dcst ?n)
8979 (if (looking-at org-complex-heading-regexp)
8980 (string-to-number (org-sort-remove-invisible (match-string 4)))
8981 nil))
8982 ((= dcst ?a)
8983 (if (looking-at org-complex-heading-regexp)
8984 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8985 nil))
8986 ((= dcst ?k)
8987 (or (get-text-property (point) :org-clock-minutes) 0))
8988 ((= dcst ?t)
8989 (let ((end (save-excursion (outline-next-heading) (point))))
8990 (if (or (re-search-forward org-ts-regexp end t)
8991 (re-search-forward org-ts-regexp-both end t))
8992 (org-time-string-to-seconds (match-string 0))
8993 (float-time now))))
8994 ((= dcst ?c)
8995 (let ((end (save-excursion (outline-next-heading) (point))))
8996 (if (re-search-forward
8997 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8998 end t)
8999 (org-time-string-to-seconds (match-string 0))
9000 (float-time now))))
9001 ((= dcst ?s)
9002 (let ((end (save-excursion (outline-next-heading) (point))))
9003 (if (re-search-forward org-scheduled-time-regexp end t)
9004 (org-time-string-to-seconds (match-string 1))
9005 (float-time now))))
9006 ((= dcst ?d)
9007 (let ((end (save-excursion (outline-next-heading) (point))))
9008 (if (re-search-forward org-deadline-time-regexp end t)
9009 (org-time-string-to-seconds (match-string 1))
9010 (float-time now))))
9011 ((= dcst ?p)
9012 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9013 (string-to-char (match-string 2))
9014 org-default-priority))
9015 ((= dcst ?r)
9016 (or (org-entry-get nil property) ""))
9017 ((= dcst ?o)
9018 (when (looking-at org-complex-heading-regexp)
9019 (let* ((m (match-string 2))
9020 (s (if (member m org-done-keywords) '- '+)))
9021 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9022 ((= dcst ?f)
9023 (if getkey-func
9024 (progn
9025 (setq tmp (funcall getkey-func))
9026 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9027 tmp)
9028 (error "Invalid key function `%s'" getkey-func)))
9029 (t (error "Invalid sorting type `%c'" sorting-type))))
9031 (cond
9032 ((= dcst ?a) 'string<)
9033 ((= dcst ?f)
9034 (or compare-func
9035 (and interactive?
9036 (org-read-function
9037 (concat "Function for comparing keys "
9038 "(empty for default `sort-subr' predicate): ")
9039 'allow-empty))))
9040 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9041 (when restore-clock?
9042 (move-marker org-clock-marker
9043 (1+ (next-single-property-change
9044 start :org-clock-marker-backup)))
9045 (remove-text-properties (1- org-clock-marker) org-clock-marker
9046 '(:org-clock-marker-backup t)))))
9047 (run-hooks 'org-after-sorting-entries-or-items-hook)
9048 (message "Sorting entries...done")))
9050 ;;; The orgstruct minor mode
9052 ;; Define a minor mode which can be used in other modes in order to
9053 ;; integrate the Org mode structure editing commands.
9055 ;; This is really a hack, because the Org mode structure commands use
9056 ;; keys which normally belong to the major mode. Here is how it
9057 ;; works: The minor mode defines all the keys necessary to operate the
9058 ;; structure commands, but wraps the commands into a function which
9059 ;; tests if the cursor is currently at a headline or a plain list
9060 ;; item. If that is the case, the structure command is used,
9061 ;; temporarily setting many Org mode variables like regular
9062 ;; expressions for filling etc. However, when any of those keys is
9063 ;; used at a different location, function uses `key-binding' to look
9064 ;; up if the key has an associated command in another currently active
9065 ;; keymap (minor modes, major mode, global), and executes that
9066 ;; command. There might be problems if any of the keys is otherwise
9067 ;; used as a prefix key.
9069 (defcustom orgstruct-heading-prefix-regexp ""
9070 "Regexp that matches the custom prefix of Org headlines in
9071 orgstruct(++)-mode."
9072 :group 'org
9073 :version "26.1"
9074 :package-version '(Org . "8.3")
9075 :type 'regexp)
9076 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9078 (defcustom orgstruct-setup-hook nil
9079 "Hook run after orgstruct-mode-map is filled."
9080 :group 'org
9081 :version "24.4"
9082 :package-version '(Org . "8.0")
9083 :type 'hook)
9085 (defvar orgstruct-initialized nil)
9087 (defvar org-local-vars nil
9088 "List of local variables, for use by `orgstruct-mode'.")
9090 ;;;###autoload
9091 (define-minor-mode orgstruct-mode
9092 "Toggle the minor mode `orgstruct-mode'.
9093 This mode is for using Org mode structure commands in other
9094 modes. The following keys behave as if Org mode were active, if
9095 the cursor is on a headline, or on a plain list item (both as
9096 defined by Org mode)."
9097 nil " OrgStruct" (make-sparse-keymap)
9098 (funcall (if orgstruct-mode
9099 'add-to-invisibility-spec
9100 'remove-from-invisibility-spec)
9101 '(outline . t))
9102 (when orgstruct-mode
9103 (org-load-modules-maybe)
9104 (unless orgstruct-initialized
9105 (orgstruct-setup)
9106 (setq orgstruct-initialized t))))
9108 ;;;###autoload
9109 (defun turn-on-orgstruct ()
9110 "Unconditionally turn on `orgstruct-mode'."
9111 (orgstruct-mode 1))
9113 (defvar-local orgstruct-is-++ nil
9114 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9115 (defvar-local org-fb-vars nil)
9116 (defun orgstruct++-mode (&optional arg)
9117 "Toggle `orgstruct-mode', the enhanced version of it.
9118 In addition to setting orgstruct-mode, this also exports all
9119 indentation and autofilling variables from Org mode into the
9120 buffer. It will also recognize item context in multiline items."
9121 (interactive "P")
9122 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9123 (if (< arg 1)
9124 (progn (orgstruct-mode -1)
9125 (dolist (v org-fb-vars)
9126 (set (make-local-variable (car v))
9127 (if (eq (car-safe (cadr v)) 'quote)
9128 (cl-cadadr v)
9129 (nth 1 v)))))
9130 (orgstruct-mode 1)
9131 (setq org-fb-vars nil)
9132 (unless org-local-vars
9133 (setq org-local-vars (org-get-local-variables)))
9134 (let (var val)
9135 (dolist (x org-local-vars)
9136 (when (string-match
9137 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9138 \\|fill-prefix\\|indent-\\)"
9139 (symbol-name (car x)))
9140 (setq var (car x) val (nth 1 x))
9141 (push (list var `(quote ,(eval var))) org-fb-vars)
9142 (set (make-local-variable var)
9143 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9144 (setq-local orgstruct-is-++ t))))
9146 ;;;###autoload
9147 (defun turn-on-orgstruct++ ()
9148 "Unconditionally turn on `orgstruct++-mode'."
9149 (orgstruct++-mode 1))
9151 (defun orgstruct-error ()
9152 "Error when there is no default binding for a structure key."
9153 (interactive)
9154 (funcall (if (fboundp 'user-error)
9155 'user-error
9156 'error)
9157 "This key has no function outside structure elements"))
9159 (defun orgstruct-setup ()
9160 "Setup orgstruct keymap."
9161 (dolist (cell '((org-demote . t)
9162 (org-metaleft . t)
9163 (org-metaright . t)
9164 (org-promote . t)
9165 (org-shiftmetaleft . t)
9166 (org-shiftmetaright . t)
9167 org-backward-element
9168 org-backward-heading-same-level
9169 org-ctrl-c-ret
9170 org-ctrl-c-minus
9171 org-ctrl-c-star
9172 org-cycle
9173 org-force-cycle-archived
9174 org-forward-heading-same-level
9175 org-insert-heading
9176 org-insert-heading-respect-content
9177 org-kill-note-or-show-branches
9178 org-mark-subtree
9179 org-meta-return
9180 org-metadown
9181 org-metaup
9182 org-narrow-to-subtree
9183 org-promote-subtree
9184 org-reveal
9185 org-shiftdown
9186 org-shiftleft
9187 org-shiftmetadown
9188 org-shiftmetaup
9189 org-shiftright
9190 org-shifttab
9191 org-shifttab
9192 org-shiftup
9193 org-show-children
9194 org-show-subtree
9195 org-sort
9196 org-up-element
9197 outline-demote
9198 outline-next-visible-heading
9199 outline-previous-visible-heading
9200 outline-promote
9201 outline-up-heading))
9202 (let ((f (or (car-safe cell) cell))
9203 (disable-when-heading-prefix (cdr-safe cell)))
9204 (when (fboundp f)
9205 (let ((new-bindings))
9206 (dolist (binding (nconc (where-is-internal f org-mode-map)
9207 (where-is-internal f outline-mode-map)))
9208 (push binding new-bindings)
9209 ;; TODO use local-function-key-map
9210 (dolist (rep '(("<tab>" . "TAB")
9211 ("<return>" . "RET")
9212 ("<escape>" . "ESC")
9213 ("<delete>" . "DEL")))
9214 (setq binding (read-kbd-macro
9215 (let ((case-fold-search))
9216 (replace-regexp-in-string
9217 (regexp-quote (cdr rep))
9218 (car rep)
9219 (key-description binding)))))
9220 (cl-pushnew binding new-bindings :test 'equal)))
9221 (dolist (binding new-bindings)
9222 (let ((key (lookup-key orgstruct-mode-map binding)))
9223 (when (or (not key) (numberp key))
9224 (ignore-errors
9225 (org-defkey orgstruct-mode-map
9226 binding
9227 (orgstruct-make-binding
9228 f binding disable-when-heading-prefix))))))))))
9229 (run-hooks 'orgstruct-setup-hook))
9231 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9232 "Create a function for binding in the structure minor mode.
9233 FUN is the command to call inside a table. KEY is the key that
9234 should be checked in for a command to execute outside of tables.
9235 Non-nil `disable-when-heading-prefix' means to disable the command
9236 if `orgstruct-heading-prefix-regexp' is not empty."
9237 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9238 (let ((nname name)
9239 (i 0))
9240 (while (fboundp (intern nname))
9241 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9242 (setq name (intern nname)))
9243 (eval
9244 (let ((bindings '((org-heading-regexp
9245 (concat "^"
9246 orgstruct-heading-prefix-regexp
9247 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9248 (org-outline-regexp
9249 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9250 (org-outline-regexp-bol
9251 (concat "^" org-outline-regexp))
9252 (outline-regexp org-outline-regexp)
9253 (outline-heading-end-regexp "\n")
9254 (outline-level 'org-outline-level)
9255 (outline-heading-alist))))
9256 `(defun ,name (arg)
9257 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9258 "Outside of structure, run the binding of `"
9259 (key-description key) "'."
9260 (when disable-when-heading-prefix
9261 (concat
9262 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9263 "back to the default binding due to limitations of Org's implementation of\n"
9264 "`" (symbol-name fun) "'.")))
9265 (interactive "p")
9266 (let* ((disable
9267 ,(and disable-when-heading-prefix
9268 '(not (string= orgstruct-heading-prefix-regexp ""))))
9269 (fallback
9270 (or disable
9271 (not
9272 (let* ,bindings
9273 (org-context-p 'headline 'item
9274 ,(when (memq fun
9275 '(org-insert-heading
9276 org-insert-heading-respect-content
9277 org-meta-return))
9278 '(when orgstruct-is-++
9279 'item-body))))))))
9280 (if fallback
9281 (let* ((orgstruct-mode)
9282 (binding
9283 (let ((key ,key))
9284 (catch 'exit
9285 (dolist
9286 (rep
9287 '(nil
9288 ("<\\([^>]*\\)tab>" . "\\1TAB")
9289 ("<\\([^>]*\\)return>" . "\\1RET")
9290 ("<\\([^>]*\\)escape>" . "\\1ESC")
9291 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9292 nil)
9293 (when rep
9294 (setq key (read-kbd-macro
9295 (let ((case-fold-search))
9296 (replace-regexp-in-string
9297 (car rep)
9298 (cdr rep)
9299 (key-description key))))))
9300 (when (key-binding key)
9301 (throw 'exit (key-binding key))))))))
9302 (if (keymapp binding)
9303 (org-set-transient-map binding)
9304 (let ((func (or binding
9305 (unless disable
9306 'orgstruct-error))))
9307 (when func
9308 (call-interactively func)))))
9309 (org-run-like-in-org-mode
9310 (lambda ()
9311 (interactive)
9312 (let* ,bindings
9313 (call-interactively ',fun)))))))))
9314 name))
9316 (defun org-contextualize-keys (alist contexts)
9317 "Return valid elements in ALIST depending on CONTEXTS.
9319 `org-agenda-custom-commands' or `org-capture-templates' are the
9320 values used for ALIST, and `org-agenda-custom-commands-contexts'
9321 or `org-capture-templates-contexts' are the associated contexts
9322 definitions."
9323 (let ((contexts
9324 ;; normalize contexts
9325 (mapcar
9326 (lambda(c) (cond ((listp (cadr c))
9327 (list (car c) (car c) (nth 1 c)))
9328 ((string= "" (cadr c))
9329 (list (car c) (car c) (nth 2 c)))
9330 (t c)))
9331 contexts))
9332 (a alist) r s)
9333 ;; loop over all commands or templates
9334 (dolist (c a)
9335 (let (vrules repl)
9336 (cond
9337 ((not (assoc (car c) contexts))
9338 (push c r))
9339 ((and (assoc (car c) contexts)
9340 (setq vrules (org-contextualize-validate-key
9341 (car c) contexts)))
9342 (mapc (lambda (vr)
9343 (unless (equal (car vr) (cadr vr))
9344 (setq repl vr)))
9345 vrules)
9346 (if (not repl) (push c r)
9347 (push (cadr repl) s)
9348 (push
9349 (cons (car c)
9350 (cdr (or (assoc (cadr repl) alist)
9351 (error "Undefined key `%s' as contextual replacement for `%s'"
9352 (cadr repl) (car c)))))
9353 r))))))
9354 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9355 (delq
9357 (delete-dups
9358 (mapcar (lambda (x)
9359 (let ((tpl (car x)))
9360 (unless (delq
9362 (mapcar (lambda (y)
9363 (equal y tpl))
9365 x)))
9366 (reverse r))))))
9368 (defun org-contextualize-validate-key (key contexts)
9369 "Check CONTEXTS for agenda or capture KEY."
9370 (let (res)
9371 (dolist (r contexts)
9372 (dolist (rr (car (last r)))
9373 (when
9374 (and (equal key (car r))
9375 (if (functionp rr) (funcall rr)
9376 (or (and (eq (car rr) 'in-file)
9377 (buffer-file-name)
9378 (string-match (cdr rr) (buffer-file-name)))
9379 (and (eq (car rr) 'in-mode)
9380 (string-match (cdr rr) (symbol-name major-mode)))
9381 (and (eq (car rr) 'in-buffer)
9382 (string-match (cdr rr) (buffer-name)))
9383 (when (and (eq (car rr) 'not-in-file)
9384 (buffer-file-name))
9385 (not (string-match (cdr rr) (buffer-file-name))))
9386 (when (eq (car rr) 'not-in-mode)
9387 (not (string-match (cdr rr) (symbol-name major-mode))))
9388 (when (eq (car rr) 'not-in-buffer)
9389 (not (string-match (cdr rr) (buffer-name)))))))
9390 (push r res))))
9391 (delete-dups (delq nil res))))
9393 (defun org-context-p (&rest contexts)
9394 "Check if local context is any of CONTEXTS.
9395 Possible values in the list of contexts are `table', `headline', and `item'."
9396 (let ((pos (point)))
9397 (goto-char (point-at-bol))
9398 (prog1 (or (and (memq 'table contexts)
9399 (looking-at "[ \t]*|"))
9400 (and (memq 'headline contexts)
9401 (looking-at org-outline-regexp))
9402 (and (memq 'item contexts)
9403 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9404 (and (memq 'item-body contexts)
9405 (org-in-item-p)))
9406 (goto-char pos))))
9408 ;;;###autoload
9409 (defun org-run-like-in-org-mode (cmd)
9410 "Run a command, pretending that the current buffer is in Org mode.
9411 This will temporarily bind local variables that are typically bound in
9412 Org mode to the values they have in Org mode, and then interactively
9413 call CMD."
9414 (org-load-modules-maybe)
9415 (unless org-local-vars
9416 (setq org-local-vars (org-get-local-variables)))
9417 (let (binds)
9418 (dolist (var org-local-vars)
9419 (when (or (not (boundp (car var)))
9420 (eq (symbol-value (car var))
9421 (default-value (car var))))
9422 (push (list (car var) `(quote ,(cadr var))) binds)))
9423 (eval `(let ,binds
9424 (call-interactively (quote ,cmd))))))
9426 (defun org-get-category (&optional pos force-refresh)
9427 "Get the category applying to position POS."
9428 (save-match-data
9429 (when force-refresh (org-refresh-category-properties))
9430 (let ((pos (or pos (point))))
9431 (or (get-text-property pos 'org-category)
9432 (progn (org-refresh-category-properties)
9433 (get-text-property pos 'org-category))))))
9435 ;;; Refresh properties
9437 (defun org-refresh-properties (dprop tprop)
9438 "Refresh buffer text properties.
9439 DPROP is the drawer property and TPROP is either the
9440 corresponding text property to set, or an alist with each element
9441 being a text property (as a symbol) and a function to apply to
9442 the value of the drawer property."
9443 (let* ((case-fold-search t)
9444 (inhibit-read-only t)
9445 (inherit? (org-property-inherit-p dprop))
9446 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9447 (global (and inherit? (org--property-global-value dprop nil))))
9448 (org-with-silent-modifications
9449 (org-with-point-at 1
9450 ;; Set global values (e.g., values defined through
9451 ;; "#+PROPERTY:" keywords) to the whole buffer.
9452 (when global (put-text-property (point-min) (point-max) tprop global))
9453 ;; Set local values.
9454 (while (re-search-forward property-re nil t)
9455 (when (org-at-property-p)
9456 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9457 (outline-next-heading))))))
9459 (defun org-refresh-property (tprop p &optional inherit)
9460 "Refresh the buffer text property TPROP from the drawer property P.
9461 The refresh happens only for the current headline, or the whole
9462 sub-tree if optional argument INHERIT is non-nil."
9463 (unless (org-before-first-heading-p)
9464 (save-excursion
9465 (org-back-to-heading t)
9466 (let ((start (point))
9467 (end (save-excursion
9468 (if inherit (org-end-of-subtree t t)
9469 (or (outline-next-heading) (point-max))))))
9470 (if (symbolp tprop)
9471 ;; TPROP is a text property symbol.
9472 (put-text-property start end tprop p)
9473 ;; TPROP is an alist with (property . function) elements.
9474 (pcase-dolist (`(,prop . ,f) tprop)
9475 (put-text-property start end prop (funcall f p))))))))
9477 (defun org-refresh-category-properties ()
9478 "Refresh category text properties in the buffer."
9479 (let ((case-fold-search t)
9480 (inhibit-read-only t)
9481 (default-category
9482 (cond ((null org-category)
9483 (if buffer-file-name
9484 (file-name-sans-extension
9485 (file-name-nondirectory buffer-file-name))
9486 "???"))
9487 ((symbolp org-category) (symbol-name org-category))
9488 (t org-category))))
9489 (org-with-silent-modifications
9490 (org-with-wide-buffer
9491 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9492 ;; This is the default category for the buffer. If none is
9493 ;; found, fall-back to `org-category' or buffer file name.
9494 (put-text-property
9495 (point-min) (point-max)
9496 'org-category
9497 (catch 'buffer-category
9498 (goto-char (point-max))
9499 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9500 (let ((element (org-element-at-point)))
9501 (when (eq (org-element-type element) 'keyword)
9502 (throw 'buffer-category
9503 (org-element-property :value element)))))
9504 default-category))
9505 ;; Set sub-tree specific categories.
9506 (goto-char (point-min))
9507 (let ((regexp (org-re-property "CATEGORY")))
9508 (while (re-search-forward regexp nil t)
9509 (let ((value (match-string-no-properties 3)))
9510 (when (org-at-property-p)
9511 (put-text-property
9512 (save-excursion (org-back-to-heading t) (point))
9513 (save-excursion (org-end-of-subtree t t) (point))
9514 'org-category
9515 value)))))))))
9517 (defun org-refresh-stats-properties ()
9518 "Refresh stats text properties in the buffer."
9519 (org-with-silent-modifications
9520 (org-with-point-at 1
9521 (let ((regexp (concat org-outline-regexp-bol
9522 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9523 (while (re-search-forward regexp nil t)
9524 (let* ((numerator (string-to-number (match-string 1)))
9525 (denominator (and (match-end 2)
9526 (string-to-number (match-string 2))))
9527 (stats (cond ((not denominator) numerator) ;percent
9528 ((= denominator 0) 0)
9529 (t (/ (* numerator 100) denominator)))))
9530 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9531 'org-stats stats)))))))
9533 (defun org-refresh-effort-properties ()
9534 "Refresh effort properties"
9535 (org-refresh-properties
9536 org-effort-property
9537 '((effort . identity)
9538 (effort-minutes . org-duration-to-minutes))))
9540 ;;;; Link Stuff
9542 ;;; Link abbreviations
9544 (defun org-link-expand-abbrev (link)
9545 "Apply replacements as defined in `org-link-abbrev-alist'."
9546 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9547 (let* ((key (match-string 1 link))
9548 (as (or (assoc key org-link-abbrev-alist-local)
9549 (assoc key org-link-abbrev-alist)))
9550 (tag (and (match-end 2) (match-string 3 link)))
9551 rpl)
9552 (if (not as)
9553 link
9554 (setq rpl (cdr as))
9555 (cond
9556 ((symbolp rpl) (funcall rpl tag))
9557 ((string-match "%(\\([^)]+\\))" rpl)
9558 (replace-match
9559 (save-match-data
9560 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9561 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9562 ((string-match "%h" rpl)
9563 (replace-match (url-hexify-string (or tag "")) t t rpl))
9564 (t (concat rpl tag)))))
9565 link))
9567 ;;; Storing and inserting links
9569 (defvar org-insert-link-history nil
9570 "Minibuffer history for links inserted with `org-insert-link'.")
9572 (defvar org-stored-links nil
9573 "Contains the links stored with `org-store-link'.")
9575 (defvar org-store-link-plist nil
9576 "Plist with info about the most recently link created with `org-store-link'.")
9578 (defun org-store-link-functions ()
9579 "Return a list of functions that are called to create and store a link.
9580 The functions defined in the :store property of
9581 `org-link-parameters'.
9583 Each function will be called in turn until one returns a non-nil
9584 value. Each function should check if it is responsible for
9585 creating this link (for example by looking at the major mode).
9586 If not, it must exit and return nil. If yes, it should return
9587 a non-nil value after calling `org-store-link-props' with a list
9588 of properties and values. Special properties are:
9590 :type The link prefix, like \"http\". This must be given.
9591 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9592 This is obligatory as well.
9593 :description Optional default description for the second pair
9594 of brackets in an Org mode link. The user can still change
9595 this when inserting this link into an Org mode buffer.
9597 In addition to these, any additional properties can be specified
9598 and then used in capture templates."
9599 (cl-loop for link in org-link-parameters
9600 with store-func
9601 do (setq store-func (org-link-get-parameter (car link) :store))
9602 if store-func
9603 collect store-func))
9605 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9606 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9608 ;;;###autoload
9609 (defun org-store-link (arg)
9610 "Store an org-link to the current location.
9611 \\<org-mode-map>
9612 This link is added to `org-stored-links' and can later be inserted
9613 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9615 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9616 A single
9617 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9618 `org-gnus-prefer-web-links' for links to Usenet articles.
9620 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9621 skipping storing functions that are not
9622 part of Org core.
9624 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9625 prefix ARG forces storing a link for each line in the
9626 active region."
9627 (interactive "P")
9628 (org-load-modules-maybe)
9629 (if (and (equal arg '(64)) (org-region-active-p))
9630 (save-excursion
9631 (let ((end (region-end)))
9632 (goto-char (region-beginning))
9633 (set-mark (point))
9634 (while (< (point-at-eol) end)
9635 (move-end-of-line 1) (activate-mark)
9636 (let (current-prefix-arg)
9637 (call-interactively 'org-store-link))
9638 (move-beginning-of-line 2)
9639 (set-mark (point)))))
9640 (setq org-store-link-plist nil)
9641 (let (link cpltxt desc description search
9642 txt custom-id agenda-link sfuns sfunsn)
9643 (cond
9645 ;; Store a link using an external link type
9646 ((and (not (equal arg '(16)))
9647 (setq sfuns
9648 (delq
9649 nil (mapcar (lambda (f)
9650 (let (fs) (if (funcall f) (push f fs))))
9651 (org-store-link-functions)))
9652 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9653 (or (and (cdr sfuns)
9654 (funcall (intern
9655 (completing-read
9656 "Which function for creating the link? "
9657 sfunsn nil t (car sfunsn)))))
9658 (funcall (caar sfuns)))
9659 (setq link (plist-get org-store-link-plist :link)
9660 desc (or (plist-get org-store-link-plist
9661 :description)
9662 link))))
9664 ;; Store a link from a source code buffer.
9665 ((org-src-edit-buffer-p)
9666 (let ((coderef-format (org-src-coderef-format)))
9667 (cond ((save-excursion
9668 (beginning-of-line)
9669 (looking-at (org-src-coderef-regexp coderef-format)))
9670 (setq link (format "(%s)" (match-string-no-properties 3))))
9671 ((called-interactively-p 'any)
9672 (let ((label (read-string "Code line label: ")))
9673 (end-of-line)
9674 (setq link (format coderef-format label))
9675 (let ((gc (- 79 (length link))))
9676 (if (< (current-column) gc)
9677 (org-move-to-column gc t)
9678 (insert " ")))
9679 (insert link)
9680 (setq link (concat "(" label ")"))
9681 (setq desc nil)))
9682 (t (setq link nil)))))
9684 ;; We are in the agenda, link to referenced location
9685 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9686 (let ((m (or (get-text-property (point) 'org-hd-marker)
9687 (get-text-property (point) 'org-marker))))
9688 (when m
9689 (org-with-point-at m
9690 (setq agenda-link
9691 (if (called-interactively-p 'any)
9692 (call-interactively 'org-store-link)
9693 (org-store-link nil)))))))
9695 ((eq major-mode 'calendar-mode)
9696 (let ((cd (calendar-cursor-to-date)))
9697 (setq link
9698 (format-time-string
9699 (car org-time-stamp-formats)
9700 (apply 'encode-time
9701 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9702 nil nil nil))))
9703 (org-store-link-props :type "calendar" :date cd)))
9705 ((eq major-mode 'help-mode)
9706 (setq link (concat "help:" (save-excursion
9707 (goto-char (point-min))
9708 (looking-at "^[^ ]+")
9709 (match-string 0))))
9710 (org-store-link-props :type "help"))
9712 ((eq major-mode 'w3-mode)
9713 (setq cpltxt (if (and (buffer-name)
9714 (not (string-match "Untitled" (buffer-name))))
9715 (buffer-name)
9716 (url-view-url t))
9717 link (url-view-url t))
9718 (org-store-link-props :type "w3" :url (url-view-url t)))
9720 ((eq major-mode 'image-mode)
9721 (setq cpltxt (concat "file:"
9722 (abbreviate-file-name buffer-file-name))
9723 link cpltxt)
9724 (org-store-link-props :type "image" :file buffer-file-name))
9726 ;; In dired, store a link to the file of the current line
9727 ((derived-mode-p 'dired-mode)
9728 (let ((file (dired-get-filename nil t)))
9729 (setq file (if file
9730 (abbreviate-file-name
9731 (expand-file-name (dired-get-filename nil t)))
9732 ;; otherwise, no file so use current directory.
9733 default-directory))
9734 (setq cpltxt (concat "file:" file)
9735 link cpltxt)))
9737 ((setq search (run-hook-with-args-until-success
9738 'org-create-file-search-functions))
9739 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9740 "::" search))
9741 (setq cpltxt (or description link)))
9743 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9744 (org-with-limited-levels
9745 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9746 (cond
9747 ;; Store a link using the target at point
9748 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9749 (setq cpltxt
9750 (concat "file:"
9751 (abbreviate-file-name
9752 (buffer-file-name (buffer-base-buffer)))
9753 "::" (match-string 1))
9754 link cpltxt))
9755 ((and (featurep 'org-id)
9756 (or (eq org-id-link-to-org-use-id t)
9757 (and (called-interactively-p 'any)
9758 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9759 (and (eq org-id-link-to-org-use-id
9760 'create-if-interactive-and-no-custom-id)
9761 (not custom-id))))
9762 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9763 ;; Store a link using the ID at point
9764 (setq link (condition-case nil
9765 (prog1 (org-id-store-link)
9766 (setq desc (or (plist-get org-store-link-plist
9767 :description)
9768 "")))
9769 (error
9770 ;; Probably before first headline, link only to file
9771 (concat "file:"
9772 (abbreviate-file-name
9773 (buffer-file-name (buffer-base-buffer))))))))
9775 ;; Just link to current headline
9776 (setq cpltxt (concat "file:"
9777 (abbreviate-file-name
9778 (buffer-file-name (buffer-base-buffer)))))
9779 ;; Add a context search string
9780 (when (org-xor org-context-in-file-links
9781 (equal arg '(4)))
9782 (let* ((element (org-element-at-point))
9783 (name (org-element-property :name element)))
9784 (setq txt (cond
9785 ((org-at-heading-p) nil)
9786 (name)
9787 ((org-region-active-p)
9788 (buffer-substring (region-beginning) (region-end)))))
9789 (when (or (null txt) (string-match "\\S-" txt))
9790 (setq cpltxt
9791 (concat cpltxt "::"
9792 (condition-case nil
9793 (org-make-org-heading-search-string txt)
9794 (error "")))
9795 desc (or name
9796 (nth 4 (ignore-errors (org-heading-components)))
9797 "NONE")))))
9798 (when (string-match "::\\'" cpltxt)
9799 (setq cpltxt (substring cpltxt 0 -2)))
9800 (setq link cpltxt)))))
9802 ((buffer-file-name (buffer-base-buffer))
9803 ;; Just link to this file here.
9804 (setq cpltxt (concat "file:"
9805 (abbreviate-file-name
9806 (buffer-file-name (buffer-base-buffer)))))
9807 ;; Add a context string.
9808 (when (org-xor org-context-in-file-links
9809 (equal arg '(4)))
9810 (setq txt (if (org-region-active-p)
9811 (buffer-substring (region-beginning) (region-end))
9812 (buffer-substring (point-at-bol) (point-at-eol))))
9813 ;; Only use search option if there is some text.
9814 (when (string-match "\\S-" txt)
9815 (setq cpltxt
9816 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9817 desc "NONE")))
9818 (setq link cpltxt))
9820 ((called-interactively-p 'interactive)
9821 (user-error "No method for storing a link from this buffer"))
9823 (t (setq link nil)))
9825 ;; We're done setting link and desc, clean up
9826 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9827 (setq link (or link cpltxt)
9828 desc (or desc cpltxt))
9829 (cond ((not desc))
9830 ((equal desc "NONE") (setq desc nil))
9831 (t (setq desc
9832 (replace-regexp-in-string
9833 org-bracket-link-analytic-regexp
9834 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9835 desc))))
9836 ;; Return the link
9837 (if (not (and (or (called-interactively-p 'any)
9838 executing-kbd-macro)
9839 link))
9840 (or agenda-link (and link (org-make-link-string link desc)))
9841 (push (list link desc) org-stored-links)
9842 (message "Stored: %s" (or desc link))
9843 (when custom-id
9844 (setq link (concat "file:" (abbreviate-file-name
9845 (buffer-file-name)) "::#" custom-id))
9846 (push (list link desc) org-stored-links))
9847 (car org-stored-links)))))
9849 (defun org-store-link-props (&rest plist)
9850 "Store link properties.
9851 The properties are pre-processed by extracting names, addresses
9852 and dates."
9853 (let ((x (plist-get plist :from)))
9854 (when x
9855 (let ((adr (mail-extract-address-components x)))
9856 (setq plist (plist-put plist :fromname (car adr)))
9857 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9858 (let ((x (plist-get plist :to)))
9859 (when x
9860 (let ((adr (mail-extract-address-components x)))
9861 (setq plist (plist-put plist :toname (car adr)))
9862 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9863 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9864 (when x
9865 (setq plist (plist-put plist :date-timestamp
9866 (format-time-string
9867 (org-time-stamp-format t) x)))
9868 (setq plist (plist-put plist :date-timestamp-inactive
9869 (format-time-string
9870 (org-time-stamp-format t t) x)))))
9871 (let ((from (plist-get plist :from))
9872 (to (plist-get plist :to)))
9873 (when (and from to org-from-is-user-regexp)
9874 (setq plist
9875 (plist-put plist :fromto
9876 (if (string-match org-from-is-user-regexp from)
9877 (concat "to %t")
9878 (concat "from %f"))))))
9879 (setq org-store-link-plist plist))
9881 (defun org-add-link-props (&rest plist)
9882 "Add these properties to the link property list."
9883 (let (key value)
9884 (while plist
9885 (setq key (pop plist) value (pop plist))
9886 (setq org-store-link-plist
9887 (plist-put org-store-link-plist key value)))))
9889 (defun org-email-link-description (&optional fmt)
9890 "Return the description part of an email link.
9891 This takes information from `org-store-link-plist' and formats it
9892 according to FMT (default from `org-email-link-description-format')."
9893 (setq fmt (or fmt org-email-link-description-format))
9894 (let* ((p org-store-link-plist)
9895 (to (plist-get p :toaddress))
9896 (from (plist-get p :fromaddress))
9897 (table
9898 (list
9899 (cons "%c" (plist-get p :fromto))
9900 (cons "%F" (plist-get p :from))
9901 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9902 (cons "%T" (plist-get p :to))
9903 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9904 (cons "%s" (plist-get p :subject))
9905 (cons "%d" (plist-get p :date))
9906 (cons "%m" (plist-get p :message-id)))))
9907 (when (string-match "%c" fmt)
9908 ;; Check if the user wrote this message
9909 (if (and org-from-is-user-regexp from to
9910 (save-match-data (string-match org-from-is-user-regexp from)))
9911 (setq fmt (replace-match "to %t" t t fmt))
9912 (setq fmt (replace-match "from %f" t t fmt))))
9913 (org-replace-escapes fmt table)))
9915 (defun org-make-org-heading-search-string (&optional string)
9916 "Make search string for the current headline or STRING."
9917 (let ((s (or string
9918 (and (derived-mode-p 'org-mode)
9919 (save-excursion
9920 (org-back-to-heading t)
9921 (org-element-property :raw-value (org-element-at-point))))))
9922 (lines org-context-in-file-links))
9923 (unless string (setq s (concat "*" s))) ;Add * for headlines
9924 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9925 (when (and string (integerp lines) (> lines 0))
9926 (let ((slines (org-split-string s "\n")))
9927 (when (< lines (length slines))
9928 (setq s (mapconcat
9929 'identity
9930 (reverse (nthcdr (- (length slines) lines)
9931 (reverse slines))) "\n")))))
9932 (mapconcat #'identity (split-string s) " ")))
9934 (defun org-make-link-string (link &optional description)
9935 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9936 (unless (org-string-nw-p link) (error "Empty link"))
9937 (let ((uri (cond ((string-match org-link-types-re link)
9938 (concat (match-string 1 link)
9939 (org-link-escape (substring link (match-end 1)))))
9940 ;; For readability, url-encode internal links only
9941 ;; when absolutely needed (i.e, when they contain
9942 ;; square brackets). File links however, are
9943 ;; encoded since, e.g., spaces are significant.
9944 ((or (file-name-absolute-p link)
9945 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9946 (org-link-escape link))
9947 (t link)))
9948 (description
9949 (and (org-string-nw-p description)
9950 ;; Remove brackets from description, as they are fatal.
9951 (replace-regexp-in-string
9952 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9953 (org-trim description)))))
9954 (format "[[%s]%s]"
9956 (if description (format "[%s]" description) ""))))
9958 (defconst org-link-escape-chars
9959 ;;%20 %5B %5D %25
9960 '(?\s ?\[ ?\] ?%)
9961 "List of characters that should be escaped in a link when stored to Org.
9962 This is the list that is used for internal purposes.")
9964 (defun org-link-escape (text &optional table merge)
9965 "Return percent escaped representation of TEXT.
9966 TEXT is a string with the text to escape.
9967 Optional argument TABLE is a list with characters that should be
9968 escaped. When nil, `org-link-escape-chars' is used.
9969 If optional argument MERGE is set, merge TABLE into
9970 `org-link-escape-chars'."
9971 (let ((characters-to-encode
9972 (cond ((null table) org-link-escape-chars)
9973 (merge (append org-link-escape-chars table))
9974 (t table))))
9975 (mapconcat
9976 (lambda (c)
9977 (if (or (memq c characters-to-encode)
9978 (and org-url-hexify-p (or (< c 32) (> c 126))))
9979 (mapconcat (lambda (e) (format "%%%.2X" e))
9980 (or (encode-coding-char c 'utf-8)
9981 (error "Unable to percent escape character: %c" c))
9983 (char-to-string c)))
9984 text "")))
9986 (defun org-link-unescape (str)
9987 "Unhex hexified Unicode parts in string STR.
9988 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9989 reciprocal of `org-link-escape', which see."
9990 (if (org-string-nw-p str)
9991 (replace-regexp-in-string
9992 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9993 str))
9995 (defun org-link-unescape-compound (hex)
9996 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9997 Note: this function also decodes single byte encodings like
9998 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9999 (save-match-data
10000 (let* ((bytes (cdr (split-string hex "%")))
10001 (ret "")
10002 (eat 0)
10003 (sum 0))
10004 (while bytes
10005 (let* ((val (string-to-number (pop bytes) 16))
10006 (shift-xor
10007 (if (= 0 eat)
10008 (cond
10009 ((>= val 252) (cons 6 252))
10010 ((>= val 248) (cons 5 248))
10011 ((>= val 240) (cons 4 240))
10012 ((>= val 224) (cons 3 224))
10013 ((>= val 192) (cons 2 192))
10014 (t (cons 0 0)))
10015 (cons 6 128))))
10016 (when (>= val 192) (setq eat (car shift-xor)))
10017 (setq val (logxor val (cdr shift-xor)))
10018 (setq sum (+ (lsh sum (car shift-xor)) val))
10019 (when (> eat 0) (setq eat (- eat 1)))
10020 (cond
10021 ((= 0 eat) ;multi byte
10022 (setq ret (concat ret (char-to-string sum)))
10023 (setq sum 0))
10024 ((not bytes) ; single byte(s)
10025 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10026 ret)))
10028 (defun org-link-unescape-single-byte-sequence (hex)
10029 "Unhexify hex-encoded single byte character sequences."
10030 (mapconcat (lambda (byte)
10031 (char-to-string (string-to-number byte 16)))
10032 (cdr (split-string hex "%")) ""))
10034 (defun org-xor (a b)
10035 "Exclusive or."
10036 (if a (not b) b))
10038 (defun org-fixup-message-id-for-http (s)
10039 "Replace special characters in a message id, so it can be used in an http query."
10040 (when (string-match "%" s)
10041 (setq s (mapconcat (lambda (c)
10042 (if (eq c ?%)
10043 "%25"
10044 (char-to-string c)))
10045 s "")))
10046 (while (string-match "<" s)
10047 (setq s (replace-match "%3C" t t s)))
10048 (while (string-match ">" s)
10049 (setq s (replace-match "%3E" t t s)))
10050 (while (string-match "@" s)
10051 (setq s (replace-match "%40" t t s)))
10054 (defun org-link-prettify (link)
10055 "Return a human-readable representation of LINK.
10056 The car of LINK must be a raw link.
10057 The cdr of LINK must be either a link description or nil."
10058 (let ((desc (or (cadr link) "<no description>")))
10059 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10060 "<" (car link) ">")))
10062 ;;;###autoload
10063 (defun org-insert-link-global ()
10064 "Insert a link like Org mode does.
10065 This command can be called in any mode to insert a link in Org syntax."
10066 (interactive)
10067 (org-load-modules-maybe)
10068 (org-run-like-in-org-mode 'org-insert-link))
10070 (defun org-insert-all-links (arg &optional pre post)
10071 "Insert all links in `org-stored-links'.
10072 When a universal prefix, do not delete the links from `org-stored-links'.
10073 When `ARG' is a number, insert the last N link(s).
10074 `PRE' and `POST' are optional arguments to define a string to
10075 prepend or to append."
10076 (interactive "P")
10077 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10078 (links (copy-sequence org-stored-links))
10079 (pr (or pre "- "))
10080 (po (or post "\n"))
10081 (cnt 1) l)
10082 (if (null org-stored-links)
10083 (message "No link to insert")
10084 (while (and (or (listp arg) (>= arg cnt))
10085 (setq l (if (listp arg)
10086 (pop links)
10087 (pop org-stored-links))))
10088 (setq cnt (1+ cnt))
10089 (insert pr)
10090 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10091 (insert po)))))
10093 (defun org-insert-last-stored-link (arg)
10094 "Insert the last link stored in `org-stored-links'."
10095 (interactive "p")
10096 (org-insert-all-links arg "" "\n"))
10098 (defun org-link-fontify-links-to-this-file ()
10099 "Fontify links to the current file in `org-stored-links'."
10100 (let ((f (buffer-file-name)) a b)
10101 (setq a (mapcar (lambda(l)
10102 (let ((ll (car l)))
10103 (when (and (string-match "^file:\\(.+\\)::" ll)
10104 (equal f (expand-file-name (match-string 1 ll))))
10105 ll)))
10106 org-stored-links))
10107 (when (featurep 'org-id)
10108 (setq b (mapcar (lambda(l)
10109 (let ((ll (car l)))
10110 (when (and (string-match "^id:\\(.+\\)$" ll)
10111 (equal f (expand-file-name
10112 (or (org-id-find-id-file
10113 (match-string 1 ll)) ""))))
10114 ll)))
10115 org-stored-links)))
10116 (mapcar (lambda(l)
10117 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10118 (delq nil (append a b)))))
10120 (defvar org--links-history nil)
10121 (defun org-insert-link (&optional complete-file link-location default-description)
10122 "Insert a link. At the prompt, enter the link.
10124 Completion can be used to insert any of the link protocol prefixes in use.
10126 The history can be used to select a link previously stored with
10127 `org-store-link'. When the empty string is entered (i.e. if you just
10128 press `RET' at the prompt), the link defaults to the most recently
10129 stored link. As `SPC' triggers completion in the minibuffer, you need to
10130 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10132 You will also be prompted for a description, and if one is given, it will
10133 be displayed in the buffer instead of the link.
10135 If there is already a link at point, this command will allow you to edit
10136 link and description parts.
10138 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10139 file name can be
10140 selected using completion. The path to the file will be relative to the
10141 current directory if the file is in the current directory or a subdirectory.
10142 Otherwise, the link will be the absolute path as completed in the minibuffer
10143 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10144 option `org-link-file-path-type'.
10146 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10147 absolute path even if the file is in
10148 the current directory or below.
10150 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10151 prefix negates `org-keep-stored-link-after-insertion'.
10153 If the LINK-LOCATION parameter is non-nil, this value will be used as
10154 the link location instead of reading one interactively.
10156 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10157 be used as the default description. Otherwise, if
10158 `org-make-link-description-function' is non-nil, this function
10159 will be called with the link target, and the result will be the
10160 default link description."
10161 (interactive "P")
10162 (let* ((wcf (current-window-configuration))
10163 (origbuf (current-buffer))
10164 (region (when (org-region-active-p)
10165 (buffer-substring (region-beginning) (region-end))))
10166 (remove (and region (list (region-beginning) (region-end))))
10167 (desc region)
10168 (link link-location)
10169 (abbrevs org-link-abbrev-alist-local)
10170 entry all-prefixes auto-desc)
10171 (cond
10172 (link-location) ; specified by arg, just use it.
10173 ((org-in-regexp org-bracket-link-regexp 1)
10174 ;; We do have a link at point, and we are going to edit it.
10175 (setq remove (list (match-beginning 0) (match-end 0)))
10176 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10177 (setq link (read-string "Link: "
10178 (org-link-unescape
10179 (match-string-no-properties 1)))))
10180 ((or (org-in-regexp org-angle-link-re)
10181 (org-in-regexp org-plain-link-re))
10182 ;; Convert to bracket link
10183 (setq remove (list (match-beginning 0) (match-end 0))
10184 link (read-string "Link: "
10185 (org-unbracket-string "<" ">" (match-string 0)))))
10186 ((member complete-file '((4) (16)))
10187 ;; Completing read for file names.
10188 (setq link (org-file-complete-link complete-file)))
10190 ;; Read link, with completion for stored links.
10191 (org-link-fontify-links-to-this-file)
10192 (org-switch-to-buffer-other-window "*Org Links*")
10193 (with-current-buffer "*Org Links*"
10194 (erase-buffer)
10195 (insert "Insert a link.
10196 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10197 (when org-stored-links
10198 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10199 (insert (mapconcat 'org-link-prettify
10200 (reverse org-stored-links) "\n")))
10201 (goto-char (point-min)))
10202 (let ((cw (selected-window)))
10203 (select-window (get-buffer-window "*Org Links*" 'visible))
10204 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10205 (unless (pos-visible-in-window-p (point-max))
10206 (org-fit-window-to-buffer))
10207 (and (window-live-p cw) (select-window cw)))
10208 (setq all-prefixes (append (mapcar 'car abbrevs)
10209 (mapcar 'car org-link-abbrev-alist)
10210 (org-link-types)))
10211 (unwind-protect
10212 ;; Fake a link history, containing the stored links.
10213 (let ((org--links-history
10214 (append (mapcar #'car org-stored-links)
10215 org-insert-link-history)))
10216 (setq link
10217 (org-completing-read
10218 "Link: "
10219 (append
10220 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10221 (mapcar #'car org-stored-links))
10222 nil nil nil
10223 'org--links-history
10224 (caar org-stored-links)))
10225 (unless (org-string-nw-p link) (user-error "No link selected"))
10226 (dolist (l org-stored-links)
10227 (when (equal link (cadr l))
10228 (setq link (car l))
10229 (setq auto-desc t)))
10230 (when (or (member link all-prefixes)
10231 (and (equal ":" (substring link -1))
10232 (member (substring link 0 -1) all-prefixes)
10233 (setq link (substring link 0 -1))))
10234 (setq link (with-current-buffer origbuf
10235 (org-link-try-special-completion link)))))
10236 (set-window-configuration wcf)
10237 (kill-buffer "*Org Links*"))
10238 (setq entry (assoc link org-stored-links))
10239 (or entry (push link org-insert-link-history))
10240 (setq desc (or desc (nth 1 entry)))))
10242 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10243 (not org-keep-stored-link-after-insertion))
10244 (setq org-stored-links (delq (assoc link org-stored-links)
10245 org-stored-links)))
10247 (when (and (string-match org-plain-link-re link)
10248 (not (string-match org-ts-regexp link)))
10249 ;; URL-like link, normalize the use of angular brackets.
10250 (setq link (org-unbracket-string "<" ">" link)))
10252 ;; Check if we are linking to the current file with a search
10253 ;; option If yes, simplify the link by using only the search
10254 ;; option.
10255 (when (and buffer-file-name
10256 (let ((case-fold-search nil))
10257 (string-match "\\`file:\\(.+?\\)::" link)))
10258 (let ((path (match-string-no-properties 1 link))
10259 (search (substring-no-properties link (match-end 0))))
10260 (save-match-data
10261 (when (equal (file-truename buffer-file-name) (file-truename path))
10262 ;; We are linking to this same file, with a search option
10263 (setq link search)))))
10265 ;; Check if we can/should use a relative path. If yes, simplify the link
10266 (let ((case-fold-search nil))
10267 (when (string-match "\\`\\(file\\|docview\\):" link)
10268 (let* ((type (match-string-no-properties 0 link))
10269 (path (substring-no-properties link (match-end 0)))
10270 (origpath path))
10271 (cond
10272 ((or (eq org-link-file-path-type 'absolute)
10273 (equal complete-file '(16)))
10274 (setq path (abbreviate-file-name (expand-file-name path))))
10275 ((eq org-link-file-path-type 'noabbrev)
10276 (setq path (expand-file-name path)))
10277 ((eq org-link-file-path-type 'relative)
10278 (setq path (file-relative-name path)))
10280 (save-match-data
10281 (if (string-match (concat "^" (regexp-quote
10282 (expand-file-name
10283 (file-name-as-directory
10284 default-directory))))
10285 (expand-file-name path))
10286 ;; We are linking a file with relative path name.
10287 (setq path (substring (expand-file-name path)
10288 (match-end 0)))
10289 (setq path (abbreviate-file-name (expand-file-name path)))))))
10290 (setq link (concat type path))
10291 (when (equal desc origpath)
10292 (setq desc path)))))
10294 (unless auto-desc
10295 (let ((initial-input
10296 (cond
10297 (default-description)
10298 ((not org-make-link-description-function) desc)
10299 (t (condition-case nil
10300 (funcall org-make-link-description-function link desc)
10301 (error
10302 (message "Can't get link description from `%s'"
10303 (symbol-name org-make-link-description-function))
10304 (sit-for 2)
10305 nil))))))
10306 (setq desc (read-string "Description: " initial-input))))
10308 (unless (string-match "\\S-" desc) (setq desc nil))
10309 (when remove (apply 'delete-region remove))
10310 (insert (org-make-link-string link desc))
10311 ;; Redisplay so as the new link has proper invisible characters.
10312 (sit-for 0)))
10314 (defun org-link-try-special-completion (type)
10315 "If there is completion support for link type TYPE, offer it."
10316 (let ((fun (org-link-get-parameter type :complete)))
10317 (if (functionp fun)
10318 (funcall fun)
10319 (read-string "Link (no completion support): " (concat type ":")))))
10321 (defun org-file-complete-link (&optional arg)
10322 "Create a file link using completion."
10323 (let ((file (read-file-name "File: "))
10324 (pwd (file-name-as-directory (expand-file-name ".")))
10325 (pwd1 (file-name-as-directory (abbreviate-file-name
10326 (expand-file-name ".")))))
10327 (cond ((equal arg '(16))
10328 (concat "file:"
10329 (abbreviate-file-name (expand-file-name file))))
10330 ((string-match
10331 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10332 (concat "file:" (match-string 1 file)))
10333 ((string-match
10334 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10335 (expand-file-name file))
10336 (concat "file:"
10337 (match-string 1 (expand-file-name file))))
10338 (t (concat "file:" file)))))
10340 (defun org-completing-read (&rest args)
10341 "Completing-read with SPACE being a normal character."
10342 (let ((enable-recursive-minibuffers t)
10343 (minibuffer-local-completion-map
10344 (copy-keymap minibuffer-local-completion-map)))
10345 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10346 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10347 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10348 'org-time-stamp-inactive)
10349 (apply #'completing-read args)))
10351 ;;; Opening/following a link
10353 (defvar org-link-search-failed nil)
10355 (defvar org-open-link-functions nil
10356 "Hook for functions finding a plain text link.
10357 These functions must take a single argument, the link content.
10358 They will be called for links that look like [[link text][description]]
10359 when LINK TEXT does not have a protocol like \"http:\" and does not look
10360 like a filename (e.g. \"./blue.png\").
10362 These functions will be called *before* Org attempts to resolve the
10363 link by doing text searches in the current buffer - so if you want a
10364 link \"[[target]]\" to still find \"<<target>>\", your function should
10365 handle this as a special case.
10367 When the function does handle the link, it must return a non-nil value.
10368 If it decides that it is not responsible for this link, it must return
10369 nil to indicate that that Org can continue with other options like
10370 exact and fuzzy text search.")
10372 (defun org-next-link (&optional search-backward)
10373 "Move forward to the next link.
10374 If the link is in hidden text, expose it."
10375 (interactive "P")
10376 (when (and org-link-search-failed (eq this-command last-command))
10377 (goto-char (point-min))
10378 (message "Link search wrapped back to beginning of buffer"))
10379 (setq org-link-search-failed nil)
10380 (let* ((pos (point))
10381 (ct (org-context))
10382 (a (assq :link ct))
10383 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10384 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10385 ((looking-at org-any-link-re)
10386 ;; Don't stay stuck at link without an org-link face
10387 (forward-char (if search-backward -1 1))))
10388 (if (funcall srch-fun org-any-link-re nil t)
10389 (progn
10390 (goto-char (match-beginning 0))
10391 (when (org-invisible-p) (org-show-context)))
10392 (goto-char pos)
10393 (setq org-link-search-failed t)
10394 (message "No further link found"))))
10396 (defun org-previous-link ()
10397 "Move backward to the previous link.
10398 If the link is in hidden text, expose it."
10399 (interactive)
10400 (funcall 'org-next-link t))
10402 (defun org-translate-link (s)
10403 "Translate a link string if a translation function has been defined."
10404 (with-temp-buffer
10405 (insert (org-trim s))
10406 (org-trim (org-element-interpret-data (org-element-context)))))
10408 (defun org-translate-link-from-planner (type path)
10409 "Translate a link from Emacs Planner syntax so that Org can follow it.
10410 This is still an experimental function, your mileage may vary."
10411 (cond
10412 ((member type '("http" "https" "news" "ftp"))
10413 ;; standard Internet links are the same.
10414 nil)
10415 ((and (equal type "irc") (string-match "^//" path))
10416 ;; Planner has two / at the beginning of an irc link, we have 1.
10417 ;; We should have zero, actually....
10418 (setq path (substring path 1)))
10419 ((and (equal type "lisp") (string-match "^/" path))
10420 ;; Planner has a slash, we do not.
10421 (setq type "elisp" path (substring path 1)))
10422 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10423 ;; A typical message link. Planner has the id after the final slash,
10424 ;; we separate it with a hash mark
10425 (setq path (concat (match-string 1 path) "#"
10426 (org-unbracket-string "<" ">" (match-string 2 path))))))
10427 (cons type path))
10429 (defun org-find-file-at-mouse (ev)
10430 "Open file link or URL at mouse."
10431 (interactive "e")
10432 (mouse-set-point ev)
10433 (org-open-at-point 'in-emacs))
10435 (defun org-open-at-mouse (ev)
10436 "Open file link or URL at mouse.
10437 See the docstring of `org-open-file' for details."
10438 (interactive "e")
10439 (mouse-set-point ev)
10440 (when (eq major-mode 'org-agenda-mode)
10441 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10442 (org-open-at-point))
10444 (defvar org-window-config-before-follow-link nil
10445 "The window configuration before following a link.
10446 This is saved in case the need arises to restore it.")
10448 ;;;###autoload
10449 (defun org-open-at-point-global ()
10450 "Follow a link or time-stamp like Org mode does.
10451 This command can be called in any mode to follow an external link
10452 or a time-stamp that has Org mode syntax. Its behavior is
10453 undefined when called on internal links (e.g., fuzzy links).
10454 Raise an error when there is nothing to follow. "
10455 (interactive)
10456 (cond ((org-in-regexp org-any-link-re)
10457 (org-open-link-from-string (match-string-no-properties 0)))
10458 ((or (org-in-regexp org-ts-regexp-both nil t)
10459 (org-in-regexp org-tsr-regexp-both nil t))
10460 (org-follow-timestamp-link))
10461 (t (user-error "No link found"))))
10463 ;;;###autoload
10464 (defun org-open-link-from-string (s &optional arg reference-buffer)
10465 "Open a link in the string S, as if it was in Org mode."
10466 (interactive "sLink: \nP")
10467 (let ((reference-buffer (or reference-buffer (current-buffer))))
10468 (with-temp-buffer
10469 (let ((org-inhibit-startup (not reference-buffer)))
10470 (org-mode)
10471 (insert s)
10472 (goto-char (point-min))
10473 (when reference-buffer
10474 (setq org-link-abbrev-alist-local
10475 (with-current-buffer reference-buffer
10476 org-link-abbrev-alist-local)))
10477 (org-open-at-point arg reference-buffer)))))
10479 (defvar org-open-at-point-functions nil
10480 "Hook that is run when following a link at point.
10482 Functions in this hook must return t if they identify and follow
10483 a link at point. If they don't find anything interesting at point,
10484 they must return nil.")
10486 (defvar org-link-search-inhibit-query nil)
10487 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10488 (defun org--open-doi-link (path)
10489 "Open a \"doi\" type link.
10490 PATH is a the path to search for, as a string."
10491 (browse-url (url-encode-url (concat org-doi-server-url path))))
10493 (defun org--open-elisp-link (path)
10494 "Open a \"elisp\" type link.
10495 PATH is the sexp to evaluate, as a string."
10496 (let ((cmd path))
10497 (if (or (and (org-string-nw-p
10498 org-confirm-elisp-link-not-regexp)
10499 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10500 (not org-confirm-elisp-link-function)
10501 (funcall org-confirm-elisp-link-function
10502 (format "Execute \"%s\" as elisp? "
10503 (org-add-props cmd nil 'face 'org-warning))))
10504 (message "%s => %s" cmd
10505 (if (eq (string-to-char cmd) ?\()
10506 (eval (read cmd))
10507 (call-interactively (read cmd))))
10508 (user-error "Abort"))))
10510 (defun org--open-help-link (path)
10511 "Open a \"help\" type link.
10512 PATH is a symbol name, as a string."
10513 (pcase (intern path)
10514 ((and (pred fboundp) variable) (describe-function variable))
10515 ((and (pred boundp) function) (describe-variable function))
10516 (name (user-error "Unknown function or variable: %s" name))))
10518 (defun org--open-shell-link (path)
10519 "Open a \"shell\" type link.
10520 PATH is the command to execute, as a string."
10521 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10522 (cmd path))
10523 (if (or (and (org-string-nw-p
10524 org-confirm-shell-link-not-regexp)
10525 (string-match
10526 org-confirm-shell-link-not-regexp cmd))
10527 (not org-confirm-shell-link-function)
10528 (funcall org-confirm-shell-link-function
10529 (format "Execute \"%s\" in shell? "
10530 (org-add-props cmd nil
10531 'face 'org-warning))))
10532 (progn
10533 (message "Executing %s" cmd)
10534 (shell-command cmd buf)
10535 (when (featurep 'midnight)
10536 (setq clean-buffer-list-kill-buffer-names
10537 (cons (buffer-name buf)
10538 clean-buffer-list-kill-buffer-names))))
10539 (user-error "Abort"))))
10541 (defun org-open-at-point (&optional arg reference-buffer)
10542 "Open link, timestamp, footnote or tags at point.
10544 When point is on a link, follow it. Normally, files will be
10545 opened by an appropriate application. If the optional prefix
10546 argument ARG is non-nil, Emacs will visit the file. With
10547 a double prefix argument, try to open outside of Emacs, in the
10548 application the system uses for this file type.
10550 When point is on a timestamp, open the agenda at the day
10551 specified.
10553 When point is a footnote definition, move to the first reference
10554 found. If it is on a reference, move to the associated
10555 definition.
10557 When point is on a headline, display a list of every link in the
10558 entry, so it is possible to pick one, or all, of them. If point
10559 is on a tag, call `org-tags-view' instead.
10561 When optional argument REFERENCE-BUFFER is non-nil, it should
10562 specify a buffer from where the link search should happen. This
10563 is used internally by `org-open-link-from-string'.
10565 On top of syntactically correct links, this function will also
10566 try to open links and time-stamps in comments, example
10567 blocks... i.e., whenever point is on something looking like
10568 a timestamp or a link."
10569 (interactive "P")
10570 ;; On a code block, open block's results.
10571 (unless (call-interactively 'org-babel-open-src-block-result)
10572 (org-load-modules-maybe)
10573 (setq org-window-config-before-follow-link (current-window-configuration))
10574 (org-remove-occur-highlights nil nil t)
10575 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10576 (let* ((context
10577 ;; Only consider supported types, even if they are not
10578 ;; the closest one.
10579 (org-element-lineage
10580 (org-element-context)
10581 '(clock footnote-definition footnote-reference headline
10582 inlinetask link timestamp)
10584 (type (org-element-type context))
10585 (value (org-element-property :value context)))
10586 (cond
10587 ;; On a headline or an inlinetask, but not on a timestamp,
10588 ;; a link, a footnote reference.
10589 ((memq type '(headline inlinetask))
10590 (org-match-line org-complex-heading-regexp)
10591 (if (and (match-beginning 5)
10592 (>= (point) (match-beginning 5))
10593 (< (point) (match-end 5)))
10594 ;; On tags.
10595 (org-tags-view arg (substring (match-string 5) 0 -1))
10596 ;; Not on tags.
10597 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10598 (`(nil . ,_)
10599 (require 'org-attach)
10600 (org-attach-reveal 'if-exists))
10601 (`(,links . ,links-end)
10602 (dolist (link (if (stringp links) (list links) links))
10603 (search-forward link nil links-end)
10604 (goto-char (match-beginning 0))
10605 (org-open-at-point))))))
10606 ;; On a footnote reference or at definition's label.
10607 ((or (eq type 'footnote-reference)
10608 (and (eq type 'footnote-definition)
10609 (save-excursion
10610 ;; Do not validate action when point is on the
10611 ;; spaces right after the footnote label, in
10612 ;; order to be on par with behaviour on links.
10613 (skip-chars-forward " \t")
10614 (let ((begin
10615 (org-element-property :contents-begin context)))
10616 (if begin (< (point) begin)
10617 (= (org-element-property :post-affiliated context)
10618 (line-beginning-position)))))))
10619 (org-footnote-action))
10620 ;; No valid context. Ignore catch-all types like `headline'.
10621 ;; If point is on something looking like a link or
10622 ;; a time-stamp, try opening it. It may be useful in
10623 ;; comments, example blocks...
10624 ((memq type '(footnote-definition headline inlinetask nil))
10625 (call-interactively #'org-open-at-point-global))
10626 ;; On a clock line, make sure point is on the timestamp
10627 ;; before opening it.
10628 ((and (eq type 'clock)
10629 value
10630 (>= (point) (org-element-property :begin value))
10631 (<= (point) (org-element-property :end value)))
10632 (org-follow-timestamp-link))
10633 ;; Do nothing on white spaces after an object.
10634 ((>= (point)
10635 (save-excursion
10636 (goto-char (org-element-property :end context))
10637 (skip-chars-backward " \t")
10638 (point)))
10639 (user-error "No link found"))
10640 ((eq type 'timestamp) (org-follow-timestamp-link))
10641 ((eq type 'link)
10642 (let ((type (org-element-property :type context))
10643 (path (org-link-unescape (org-element-property :path context))))
10644 ;; Switch back to REFERENCE-BUFFER needed when called in
10645 ;; a temporary buffer through `org-open-link-from-string'.
10646 (with-current-buffer (or reference-buffer (current-buffer))
10647 (cond
10648 ((equal type "file")
10649 (if (string-match "[*?{]" (file-name-nondirectory path))
10650 (dired path)
10651 ;; Look into `org-link-parameters' in order to find
10652 ;; a DEDICATED-FUNCTION to open file. The function
10653 ;; will be applied on raw link instead of parsed
10654 ;; link due to the limitation in `org-add-link-type'
10655 ;; ("open" function called with a single argument).
10656 ;; If no such function is found, fallback to
10657 ;; `org-open-file'.
10658 (let* ((option (org-element-property :search-option context))
10659 (app (org-element-property :application context))
10660 (dedicated-function
10661 (org-link-get-parameter
10662 (if app (concat type "+" app) type)
10663 :follow)))
10664 (if dedicated-function
10665 (funcall dedicated-function
10666 (concat path
10667 (and option (concat "::" option))))
10668 (apply #'org-open-file
10669 path
10670 (cond (arg)
10671 ((equal app "emacs") 'emacs)
10672 ((equal app "sys") 'system))
10673 (cond ((not option) nil)
10674 ((string-match-p "\\`[0-9]+\\'" option)
10675 (list (string-to-number option)))
10676 (t (list nil
10677 (org-link-unescape option)))))))))
10678 ((functionp (org-link-get-parameter type :follow))
10679 (funcall (org-link-get-parameter type :follow) path))
10680 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10681 (unless (run-hook-with-args-until-success
10682 'org-open-link-functions path)
10683 (if (not arg) (org-mark-ring-push)
10684 (switch-to-buffer-other-window
10685 (org-get-buffer-for-internal-link (current-buffer))))
10686 (let ((destination
10687 (org-with-wide-buffer
10688 (if (equal type "radio")
10689 (org-search-radio-target
10690 (org-element-property :path context))
10691 (org-link-search
10692 (if (member type '("custom-id" "coderef"))
10693 (org-element-property :raw-link context)
10694 path)
10695 ;; Prevent fuzzy links from matching
10696 ;; themselves.
10697 (and (equal type "fuzzy")
10698 (+ 2 (org-element-property :begin context)))))
10699 (point))))
10700 (unless (and (<= (point-min) destination)
10701 (>= (point-max) destination))
10702 (widen))
10703 (goto-char destination))))
10704 (t (browse-url-at-point))))))
10705 (t (user-error "No link found")))))
10706 (run-hook-with-args 'org-follow-link-hook)))
10708 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10709 "Offer links in the current entry and return the selected link.
10710 If there is only one link, return it.
10711 If NTH is an integer, return the NTH link found.
10712 If ZERO is a string, check also this string for a link, and if
10713 there is one, return it."
10714 (with-current-buffer buffer
10715 (org-with-wide-buffer
10716 (goto-char marker)
10717 (let ((cnt ?0)
10718 have-zero end links link c)
10719 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10720 (push (match-string 0 zero) links)
10721 (setq cnt (1- cnt) have-zero t))
10722 (save-excursion
10723 (org-back-to-heading t)
10724 (setq end (save-excursion (outline-next-heading) (point)))
10725 (while (re-search-forward org-any-link-re end t)
10726 (push (match-string 0) links))
10727 (setq links (org-uniquify (reverse links))))
10728 (cond
10729 ((null links)
10730 (message "No links"))
10731 ((equal (length links) 1)
10732 (setq link (car links)))
10733 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10734 (setq link (nth (if have-zero nth (1- nth)) links)))
10735 (t ; we have to select a link
10736 (save-excursion
10737 (save-window-excursion
10738 (delete-other-windows)
10739 (with-output-to-temp-buffer "*Select Link*"
10740 (dolist (l links)
10741 (cond
10742 ((not (string-match org-bracket-link-regexp l))
10743 (princ (format "[%c] %s\n" (cl-incf cnt)
10744 (org-unbracket-string "<" ">" l))))
10745 ((match-end 3)
10746 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10747 (match-string 3 l) (match-string 1 l))))
10748 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10749 (match-string 1 l)))))))
10750 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10751 (message "Select link to open, RET to open all:")
10752 (setq c (read-char-exclusive))
10753 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10754 (when (equal c ?q) (user-error "Abort"))
10755 (if (equal c ?\C-m)
10756 (setq link links)
10757 (setq nth (- c ?0))
10758 (when have-zero (setq nth (1+ nth)))
10759 (unless (and (integerp nth) (>= (length links) nth))
10760 (user-error "Invalid link selection"))
10761 (setq link (nth (1- nth) links)))))
10762 (cons link end)))))
10764 ;; TODO: These functions are deprecated since `org-open-at-point'
10765 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10766 (defun org-open-file-with-system (path)
10767 "Open file at PATH using the system way of opening it."
10768 (org-open-file path 'system))
10769 (defun org-open-file-with-emacs (path)
10770 "Open file at PATH in Emacs."
10771 (org-open-file path 'emacs))
10774 ;;; File search
10776 (defvar org-create-file-search-functions nil
10777 "List of functions to construct the right search string for a file link.
10778 These functions are called in turn with point at the location to
10779 which the link should point.
10781 A function in the hook should first test if it would like to
10782 handle this file type, for example by checking the `major-mode'
10783 or the file extension. If it decides not to handle this file, it
10784 should just return nil to give other functions a chance. If it
10785 does handle the file, it must return the search string to be used
10786 when following the link. The search string will be part of the
10787 file link, given after a double colon, and `org-open-at-point'
10788 will automatically search for it. If special measures must be
10789 taken to make the search successful, another function should be
10790 added to the companion hook `org-execute-file-search-functions',
10791 which see.
10793 A function in this hook may also use `setq' to set the variable
10794 `description' to provide a suggestion for the descriptive text to
10795 be used for this link when it gets inserted into an Org buffer
10796 with \\[org-insert-link].")
10798 (defvar org-execute-file-search-functions nil
10799 "List of functions to execute a file search triggered by a link.
10801 Functions added to this hook must accept a single argument, the
10802 search string that was part of the file link, the part after the
10803 double colon. The function must first check if it would like to
10804 handle this search, for example by checking the `major-mode' or
10805 the file extension. If it decides not to handle this search, it
10806 should just return nil to give other functions a chance. If it
10807 does handle the search, it must return a non-nil value to keep
10808 other functions from trying.
10810 Each function can access the current prefix argument through the
10811 variable `current-prefix-arg'. Note that a single prefix is used
10812 to force opening a link in Emacs, so it may be good to only use a
10813 numeric or double prefix to guide the search function.
10815 In case this is needed, a function in this hook can also restore
10816 the window configuration before `org-open-at-point' was called using:
10818 (set-window-configuration org-window-config-before-follow-link)")
10820 (defun org-search-radio-target (target)
10821 "Search a radio target matching TARGET in current buffer.
10822 White spaces are not significant."
10823 (let ((re (format "<<<%s>>>"
10824 (mapconcat #'regexp-quote
10825 (split-string target)
10826 "[ \t]+\\(?:\n[ \t]*\\)?")))
10827 (origin (point)))
10828 (goto-char (point-min))
10829 (catch :radio-match
10830 (while (re-search-forward re nil t)
10831 (backward-char)
10832 (let ((object (org-element-context)))
10833 (when (eq (org-element-type object) 'radio-target)
10834 (goto-char (org-element-property :begin object))
10835 (org-show-context 'link-search)
10836 (throw :radio-match nil))))
10837 (goto-char origin)
10838 (user-error "No match for radio target: %s" target))))
10840 (defun org-link-search (s &optional avoid-pos stealth)
10841 "Search for a search string S.
10843 If S starts with \"#\", it triggers a custom ID search.
10845 If S is enclosed within parenthesis, it initiates a coderef
10846 search.
10848 If S is surrounded by forward slashes, it is interpreted as
10849 a regular expression. In Org mode files, this will create an
10850 `org-occur' sparse tree. In ordinary files, `occur' will be used
10851 to list matches. If the current buffer is in `dired-mode', grep
10852 will be used to search in all files.
10854 When AVOID-POS is given, ignore matches near that position.
10856 When optional argument STEALTH is non-nil, do not modify
10857 visibility around point, thus ignoring `org-show-context-detail'
10858 variable.
10860 Search is case-insensitive and ignores white spaces. Return type
10861 of matched result, which is either `dedicated' or `fuzzy'."
10862 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10863 (let* ((case-fold-search t)
10864 (origin (point))
10865 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10866 (starred (eq (string-to-char normalized) ?*))
10867 (words (split-string (if starred (substring s 1) s)))
10868 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10869 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10870 type)
10871 (cond
10872 ;; Check if there are any special search functions.
10873 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10874 ((eq (string-to-char s) ?#)
10875 ;; Look for a custom ID S if S starts with "#".
10876 (let* ((id (substring normalized 1))
10877 (match (org-find-property "CUSTOM_ID" id)))
10878 (if match (progn (goto-char match) (setf type 'dedicated))
10879 (error "No match for custom ID: %s" id))))
10880 ((string-match "\\`(\\(.*\\))\\'" normalized)
10881 ;; Look for coderef targets if S is enclosed within parenthesis.
10882 (let ((coderef (match-string-no-properties 1 normalized))
10883 (re (substring s-single-re 1 -1)))
10884 (goto-char (point-min))
10885 (catch :coderef-match
10886 (while (re-search-forward re nil t)
10887 (let ((element (org-element-at-point)))
10888 (when (and (memq (org-element-type element)
10889 '(example-block src-block))
10890 ;; Build proper regexp according to current
10891 ;; block's label format.
10892 (let ((label-fmt
10893 (regexp-quote
10894 (or (org-element-property :label-fmt element)
10895 org-coderef-label-format))))
10896 (save-excursion
10897 (beginning-of-line)
10898 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10899 (format label-fmt coderef))))))
10900 (setq type 'dedicated)
10901 (goto-char (match-beginning 1))
10902 (throw :coderef-match nil))))
10903 (goto-char origin)
10904 (error "No match for coderef: %s" coderef))))
10905 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10906 ;; Look for a regular expression.
10907 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10908 (match-string 1 s)))
10909 ;; From here, we handle fuzzy links.
10911 ;; Look for targets, only if not in a headline search.
10912 ((and (not starred)
10913 (let ((target (format "<<%s>>" s-multi-re)))
10914 (catch :target-match
10915 (goto-char (point-min))
10916 (while (re-search-forward target nil t)
10917 (backward-char)
10918 (let ((context (org-element-context)))
10919 (when (eq (org-element-type context) 'target)
10920 (setq type 'dedicated)
10921 (goto-char (org-element-property :begin context))
10922 (throw :target-match t))))
10923 nil))))
10924 ;; Look for elements named after S, only if not in a headline
10925 ;; search.
10926 ((and (not starred)
10927 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10928 (catch :name-match
10929 (goto-char (point-min))
10930 (while (re-search-forward name nil t)
10931 (let ((element (org-element-at-point)))
10932 (when (equal words
10933 (split-string
10934 (org-element-property :name element)))
10935 (setq type 'dedicated)
10936 (beginning-of-line)
10937 (throw :name-match t))))
10938 nil))))
10939 ;; Regular text search. Prefer headlines in Org mode buffers.
10940 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10941 ;; statistics cookies and tags.
10942 ((and (derived-mode-p 'org-mode)
10943 (let ((title-re
10944 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10945 org-outline-regexp-bol
10946 org-comment-string
10947 (mapconcat #'regexp-quote words ".+")))
10948 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10949 (comment-re (eval-when-compile
10950 (format "\\`%s[ \t]+" org-comment-string))))
10951 (goto-char (point-min))
10952 (catch :found
10953 (while (re-search-forward title-re nil t)
10954 (when (equal words
10955 (split-string
10956 (replace-regexp-in-string
10957 cookie-re ""
10958 (replace-regexp-in-string
10959 comment-re "" (org-get-heading t t t)))))
10960 (throw :found t)))
10961 nil)))
10962 (beginning-of-line)
10963 (setq type 'dedicated))
10964 ;; Offer to create non-existent headline depending on
10965 ;; `org-link-search-must-match-exact-headline'.
10966 ((and (derived-mode-p 'org-mode)
10967 (not org-link-search-inhibit-query)
10968 (eq org-link-search-must-match-exact-headline 'query-to-create)
10969 (yes-or-no-p "No match - create this as a new heading? "))
10970 (goto-char (point-max))
10971 (unless (bolp) (newline))
10972 (org-insert-heading nil t t)
10973 (insert s "\n")
10974 (beginning-of-line 0))
10975 ;; Only headlines are looked after. No need to process
10976 ;; further: throw an error.
10977 ((and (derived-mode-p 'org-mode)
10978 (or starred org-link-search-must-match-exact-headline))
10979 (goto-char origin)
10980 (error "No match for fuzzy expression: %s" normalized))
10981 ;; Regular text search.
10982 ((catch :fuzzy-match
10983 (goto-char (point-min))
10984 (while (re-search-forward s-multi-re nil t)
10985 ;; Skip match if it contains AVOID-POS or it is included in
10986 ;; a link with a description but outside the description.
10987 (unless (or (and avoid-pos
10988 (<= (match-beginning 0) avoid-pos)
10989 (> (match-end 0) avoid-pos))
10990 (and (save-match-data
10991 (org-in-regexp org-bracket-link-regexp))
10992 (match-beginning 3)
10993 (or (> (match-beginning 3) (point))
10994 (<= (match-end 3) (point)))
10995 (org-element-lineage
10996 (save-match-data (org-element-context))
10997 '(link) t)))
10998 (goto-char (match-beginning 0))
10999 (setq type 'fuzzy)
11000 (throw :fuzzy-match t)))
11001 nil))
11002 ;; All failed. Throw an error.
11003 (t (goto-char origin)
11004 (error "No match for fuzzy expression: %s" normalized)))
11005 ;; Disclose surroundings of match, if appropriate.
11006 (when (and (derived-mode-p 'org-mode) (not stealth))
11007 (org-show-context 'link-search))
11008 type))
11010 (defun org-get-buffer-for-internal-link (buffer)
11011 "Return a buffer to be used for displaying the link target of internal links."
11012 (cond
11013 ((not org-display-internal-link-with-indirect-buffer)
11014 buffer)
11015 ((string-suffix-p "(Clone)" (buffer-name buffer))
11016 (message "Buffer is already a clone, not making another one")
11017 ;; we also do not modify visibility in this case
11018 buffer)
11019 (t ; make a new indirect buffer for displaying the link
11020 (let* ((bn (buffer-name buffer))
11021 (ibn (concat bn "(Clone)"))
11022 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11023 (with-current-buffer ib (org-overview))
11024 ib))))
11026 (defun org-do-occur (regexp &optional cleanup)
11027 "Call the Emacs command `occur'.
11028 If CLEANUP is non-nil, remove the printout of the regular expression
11029 in the *Occur* buffer. This is useful if the regex is long and not useful
11030 to read."
11031 (occur regexp)
11032 (when cleanup
11033 (let ((cwin (selected-window)) win beg end)
11034 (when (setq win (get-buffer-window "*Occur*"))
11035 (select-window win))
11036 (goto-char (point-min))
11037 (when (re-search-forward "match[a-z]+" nil t)
11038 (setq beg (match-end 0))
11039 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11040 (setq end (1- (match-beginning 0)))))
11041 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11042 (goto-char (point-min))
11043 (select-window cwin))))
11045 ;;; The mark ring for links jumps
11047 (defvar org-mark-ring nil
11048 "Mark ring for positions before jumps in Org mode.")
11049 (defvar org-mark-ring-last-goto nil
11050 "Last position in the mark ring used to go back.")
11051 ;; Fill and close the ring
11052 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11053 (dotimes (_ org-mark-ring-length)
11054 (push (make-marker) org-mark-ring))
11055 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11056 org-mark-ring)
11058 (defun org-mark-ring-push (&optional pos buffer)
11059 "Put the current position or POS into the mark ring and rotate it."
11060 (interactive)
11061 (setq pos (or pos (point)))
11062 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11063 (move-marker (car org-mark-ring)
11064 (or pos (point))
11065 (or buffer (current-buffer)))
11066 (message "%s"
11067 (substitute-command-keys
11068 "Position saved to mark ring, go back with \
11069 `\\[org-mark-ring-goto]'.")))
11071 (defun org-mark-ring-goto (&optional n)
11072 "Jump to the previous position in the mark ring.
11073 With prefix arg N, jump back that many stored positions. When
11074 called several times in succession, walk through the entire ring.
11075 Org mode commands jumping to a different position in the current file,
11076 or to another Org file, automatically push the old position onto the ring."
11077 (interactive "p")
11078 (let (p m)
11079 (if (eq last-command this-command)
11080 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11081 (setq p org-mark-ring))
11082 (setq org-mark-ring-last-goto p)
11083 (setq m (car p))
11084 (pop-to-buffer-same-window (marker-buffer m))
11085 (goto-char m)
11086 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11088 (defun org-add-angle-brackets (s)
11089 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11090 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11093 ;;; Following specific links
11095 (defvar org-agenda-buffer-tmp-name)
11096 (defvar org-agenda-start-on-weekday)
11097 (defun org-follow-timestamp-link ()
11098 "Open an agenda view for the time-stamp date/range at point."
11099 (cond
11100 ((org-at-date-range-p t)
11101 (let ((org-agenda-start-on-weekday)
11102 (t1 (match-string 1))
11103 (t2 (match-string 2)) tt1 tt2)
11104 (setq tt1 (time-to-days (org-time-string-to-time t1))
11105 tt2 (time-to-days (org-time-string-to-time t2)))
11106 (let ((org-agenda-buffer-tmp-name
11107 (format "*Org Agenda(a:%s)"
11108 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11109 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11110 ((org-at-timestamp-p 'lax)
11111 (let ((org-agenda-buffer-tmp-name
11112 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11113 (org-agenda-list nil (time-to-days (org-time-string-to-time
11114 (substring (match-string 1) 0 10)))
11115 1)))
11116 (t (error "This should not happen"))))
11119 ;;; Following file links
11120 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11121 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11122 (declare-function mailcap-mime-info
11123 "mailcap" (string &optional request no-decode))
11124 (defvar org-wait nil)
11125 (defun org-open-file (path &optional in-emacs line search)
11126 "Open the file at PATH.
11127 First, this expands any special file name abbreviations. Then the
11128 configuration variable `org-file-apps' is checked if it contains an
11129 entry for this file type, and if yes, the corresponding command is launched.
11131 If no application is found, Emacs simply visits the file.
11133 With optional prefix argument IN-EMACS, Emacs will visit the file.
11134 With a double \\[universal-argument] \\[universal-argument] \
11135 prefix arg, Org tries to avoid opening in Emacs
11136 and to use an external application to visit the file.
11138 Optional LINE specifies a line to go to, optional SEARCH a string
11139 to search for. If LINE or SEARCH is given, the file will be
11140 opened in Emacs, unless an entry from org-file-apps that makes
11141 use of groups in a regexp matches.
11143 If you want to change the way frames are used when following a
11144 link, please customize `org-link-frame-setup'.
11146 If the file does not exist, an error is thrown."
11147 (let* ((file (if (equal path "")
11148 buffer-file-name
11149 (substitute-in-file-name (expand-file-name path))))
11150 (file-apps (append org-file-apps (org-default-apps)))
11151 (apps (cl-remove-if
11152 'org-file-apps-entry-match-against-dlink-p file-apps))
11153 (apps-dlink (cl-remove-if-not
11154 'org-file-apps-entry-match-against-dlink-p file-apps))
11155 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11156 (dirp (unless remp (file-directory-p file)))
11157 (file (if (and dirp org-open-directory-means-index-dot-org)
11158 (concat (file-name-as-directory file) "index.org")
11159 file))
11160 (a-m-a-p (assq 'auto-mode apps))
11161 (dfile (downcase file))
11162 ;; Reconstruct the original link from the PATH, LINE and
11163 ;; SEARCH args.
11164 (link (cond (line (concat file "::" (number-to-string line)))
11165 (search (concat file "::" search))
11166 (t file)))
11167 (dlink (downcase link))
11168 (ext
11169 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11170 (match-string 1 dfile)))
11171 (save-position-maybe
11172 (let ((old-buffer (current-buffer))
11173 (old-pos (point))
11174 (old-mode major-mode))
11175 (lambda ()
11176 (and (derived-mode-p 'org-mode)
11177 (eq old-mode 'org-mode)
11178 (or (not (eq old-buffer (current-buffer)))
11179 (not (eq old-pos (point))))
11180 (org-mark-ring-push old-pos old-buffer)))))
11181 cmd link-match-data)
11182 (cond
11183 ((member in-emacs '((16) system))
11184 (setq cmd (cdr (assq 'system apps))))
11185 (in-emacs (setq cmd 'emacs))
11187 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11188 (and dirp (cdr (assq 'directory apps)))
11189 ;; First, try matching against apps-dlink if we
11190 ;; get a match here, store the match data for
11191 ;; later.
11192 (let ((match (assoc-default dlink apps-dlink
11193 'string-match)))
11194 (if match
11195 (progn (setq link-match-data (match-data))
11196 match)
11197 (progn (setq in-emacs (or in-emacs line search))
11198 nil))) ; if we have no match in apps-dlink,
11199 ; always open the file in emacs if line or search
11200 ; is given (for backwards compatibility)
11201 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11202 'string-match)
11203 (cdr (assoc ext apps))
11204 (cdr (assq t apps))))))
11205 (when (eq cmd 'system)
11206 (setq cmd (cdr (assq 'system apps))))
11207 (when (eq cmd 'default)
11208 (setq cmd (cdr (assoc t apps))))
11209 (when (eq cmd 'mailcap)
11210 (require 'mailcap)
11211 (mailcap-parse-mailcaps)
11212 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11213 (command (mailcap-mime-info mime-type)))
11214 (if (stringp command)
11215 (setq cmd command)
11216 (setq cmd 'emacs))))
11217 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11218 (not (file-exists-p file))
11219 (not org-open-non-existing-files))
11220 (user-error "No such file: %s" file))
11221 (cond
11222 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11223 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11224 (while (string-match "['\"]%s['\"]" cmd)
11225 (setq cmd (replace-match "%s" t t cmd)))
11226 (setq cmd (replace-regexp-in-string
11227 "%s"
11228 (shell-quote-argument (convert-standard-filename file))
11230 nil t))
11232 ;; Replace "%1", "%2" etc. in command with group matches from regex
11233 (save-match-data
11234 (let ((match-index 1)
11235 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11236 (set-match-data link-match-data)
11237 (while (<= match-index number-of-groups)
11238 (let ((regex (concat "%" (number-to-string match-index)))
11239 (replace-with (match-string match-index dlink)))
11240 (while (string-match regex cmd)
11241 (setq cmd (replace-match replace-with t t cmd))))
11242 (setq match-index (+ match-index 1)))))
11244 (save-window-excursion
11245 (message "Running %s...done" cmd)
11246 (start-process-shell-command cmd nil cmd)
11247 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11248 ((or (stringp cmd)
11249 (eq cmd 'emacs))
11250 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11251 (widen)
11252 (cond (line (org-goto-line line)
11253 (when (derived-mode-p 'org-mode) (org-reveal)))
11254 (search (condition-case err
11255 (org-link-search search)
11256 ;; Save position before error-ing out so user
11257 ;; can easily move back to the original buffer.
11258 (error (funcall save-position-maybe)
11259 (error (nth 1 err)))))))
11260 ((functionp cmd)
11261 (save-match-data
11262 (set-match-data link-match-data)
11263 (condition-case nil
11264 (funcall cmd file link)
11265 ;; FIXME: Remove this check when most default installations
11266 ;; of Emacs have at least Org 9.0.
11267 ((debug wrong-number-of-arguments wrong-type-argument
11268 invalid-function)
11269 (user-error "Please see Org News for version 9.0 about \
11270 `org-file-apps'--Lisp error: %S" cmd)))))
11271 ((consp cmd)
11272 ;; FIXME: Remove this check when most default installations of
11273 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11274 ;; fall back to `org-link-frame-setup' for an old usage of
11275 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11276 (user-error "Please see Org News for version 9.0 about \
11277 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11278 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11279 (funcall save-position-maybe)))
11281 (defun org-file-apps-entry-match-against-dlink-p (entry)
11282 "This function returns non-nil if `entry' uses a regular
11283 expression which should be matched against the whole link by
11284 org-open-file.
11286 It assumes that is the case when the entry uses a regular
11287 expression which has at least one grouping construct and the
11288 action is either a lisp form or a command string containing
11289 `%1', i.e. using at least one subexpression match as a
11290 parameter."
11291 (let ((selector (car entry))
11292 (action (cdr entry)))
11293 (if (stringp selector)
11294 (and (> (regexp-opt-depth selector) 0)
11295 (or (and (stringp action)
11296 (string-match "%[0-9]" action))
11297 (consp action)))
11298 nil)))
11300 (defun org-default-apps ()
11301 "Return the default applications for this operating system."
11302 (cond
11303 ((eq system-type 'darwin)
11304 org-file-apps-defaults-macosx)
11305 ((eq system-type 'windows-nt)
11306 org-file-apps-defaults-windowsnt)
11307 (t org-file-apps-defaults-gnu)))
11309 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11310 "Convert extensions to regular expressions in the cars of LIST.
11311 Also, weed out any non-string entries, because the return value is used
11312 only for regexp matching.
11313 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11314 point to the symbol `emacs', indicating that the file should
11315 be opened in Emacs."
11316 (append
11317 (delq nil
11318 (mapcar (lambda (x)
11319 (unless (not (stringp (car x)))
11320 (if (string-match "\\W" (car x))
11322 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11323 list))
11324 (when add-auto-mode
11325 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11327 (defvar ange-ftp-name-format)
11328 (defun org-file-remote-p (file)
11329 "Test whether FILE specifies a location on a remote system.
11330 Return non-nil if the location is indeed remote.
11332 For example, the filename \"/user@host:/foo\" specifies a location
11333 on the system \"/user@host:\"."
11334 (cond ((fboundp 'file-remote-p)
11335 (file-remote-p file))
11336 ((fboundp 'tramp-handle-file-remote-p)
11337 (tramp-handle-file-remote-p file))
11338 ((and (boundp 'ange-ftp-name-format)
11339 (string-match (car ange-ftp-name-format) file))
11340 t)))
11343 ;;;; Refiling
11345 (defun org-get-org-file ()
11346 "Read a filename, with default directory `org-directory'."
11347 (let ((default (or org-default-notes-file remember-data-file)))
11348 (read-file-name (format "File name [%s]: " default)
11349 (file-name-as-directory org-directory)
11350 default)))
11352 (defun org-notes-order-reversed-p ()
11353 "Check if the current file should receive notes in reversed order."
11354 (cond
11355 ((not org-reverse-note-order) nil)
11356 ((eq t org-reverse-note-order) t)
11357 ((not (listp org-reverse-note-order)) nil)
11358 (t (catch 'exit
11359 (dolist (entry org-reverse-note-order)
11360 (when (string-match (car entry) buffer-file-name)
11361 (throw 'exit (cdr entry))))))))
11363 (defvar org-refile-target-table nil
11364 "The list of refile targets, created by `org-refile'.")
11366 (defvar org-agenda-new-buffers nil
11367 "Buffers created to visit agenda files.")
11369 (defvar org-refile-cache nil
11370 "Cache for refile targets.")
11372 (defvar org-refile-markers nil
11373 "All the markers used for caching refile locations.")
11375 (defun org-refile-marker (pos)
11376 "Get a new refile marker, but only if caching is in use."
11377 (if (not org-refile-use-cache)
11379 (let ((m (make-marker)))
11380 (move-marker m pos)
11381 (push m org-refile-markers)
11382 m)))
11384 (defun org-refile-cache-clear ()
11385 "Clear the refile cache and disable all the markers."
11386 (dolist (m org-refile-markers) (move-marker m nil))
11387 (setq org-refile-markers nil)
11388 (setq org-refile-cache nil)
11389 (message "Refile cache has been cleared"))
11391 (defun org-refile-cache-check-set (set)
11392 "Check if all the markers in the cache still have live buffers."
11393 (let (marker)
11394 (catch 'exit
11395 (while (and set (setq marker (nth 3 (pop set))))
11396 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11397 (when (and marker (null (marker-buffer marker)))
11398 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11399 (sit-for 3)
11400 (throw 'exit nil)))
11401 t)))
11403 (defun org-refile-cache-put (set &rest identifiers)
11404 "Push the refile targets SET into the cache, under IDENTIFIERS."
11405 (let* ((key (sha1 (prin1-to-string identifiers)))
11406 (entry (assoc key org-refile-cache)))
11407 (if entry
11408 (setcdr entry set)
11409 (push (cons key set) org-refile-cache))))
11411 (defun org-refile-cache-get (&rest identifiers)
11412 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11413 (cond
11414 ((not org-refile-cache) nil)
11415 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11417 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11418 org-refile-cache))))
11419 (and set (org-refile-cache-check-set set) set)))))
11421 (defvar org-outline-path-cache nil
11422 "Alist between buffer positions and outline paths.
11423 It value is an alist (POSITION . PATH) where POSITION is the
11424 buffer position at the beginning of an entry and PATH is a list
11425 of strings describing the outline path for that entry, in reverse
11426 order.")
11428 (defun org-refile-get-targets (&optional default-buffer)
11429 "Produce a table with refile targets."
11430 (let ((case-fold-search nil)
11431 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11432 (entries (or org-refile-targets '((nil . (:level . 1)))))
11433 targets tgs files desc descre)
11434 (message "Getting targets...")
11435 (with-current-buffer (or default-buffer (current-buffer))
11436 (dolist (entry entries)
11437 (setq files (car entry) desc (cdr entry))
11438 (cond
11439 ((null files) (setq files (list (current-buffer))))
11440 ((eq files 'org-agenda-files)
11441 (setq files (org-agenda-files 'unrestricted)))
11442 ((and (symbolp files) (fboundp files))
11443 (setq files (funcall files)))
11444 ((and (symbolp files) (boundp files))
11445 (setq files (symbol-value files))))
11446 (when (stringp files) (setq files (list files)))
11447 (cond
11448 ((eq (car desc) :tag)
11449 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11450 ((eq (car desc) :todo)
11451 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11452 ((eq (car desc) :regexp)
11453 (setq descre (cdr desc)))
11454 ((eq (car desc) :level)
11455 (setq descre (concat "^\\*\\{" (number-to-string
11456 (if org-odd-levels-only
11457 (1- (* 2 (cdr desc)))
11458 (cdr desc)))
11459 "\\}[ \t]")))
11460 ((eq (car desc) :maxlevel)
11461 (setq descre (concat "^\\*\\{1," (number-to-string
11462 (if org-odd-levels-only
11463 (1- (* 2 (cdr desc)))
11464 (cdr desc)))
11465 "\\}[ \t]")))
11466 (t (error "Bad refiling target description %s" desc)))
11467 (dolist (f files)
11468 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11470 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11471 (progn
11472 (when (bufferp f)
11473 (setq f (buffer-file-name (buffer-base-buffer f))))
11474 (setq f (and f (expand-file-name f)))
11475 (when (eq org-refile-use-outline-path 'file)
11476 (push (list (file-name-nondirectory f) f nil nil) tgs))
11477 (when (eq org-refile-use-outline-path 'buffer-name)
11478 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11479 (when (eq org-refile-use-outline-path 'full-file-path)
11480 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11481 (org-with-wide-buffer
11482 (goto-char (point-min))
11483 (setq org-outline-path-cache nil)
11484 (while (re-search-forward descre nil t)
11485 (beginning-of-line)
11486 (let ((case-fold-search nil))
11487 (looking-at org-complex-heading-regexp))
11488 (let ((begin (point))
11489 (heading (match-string-no-properties 4)))
11490 (unless (or (and
11491 org-refile-target-verify-function
11492 (not
11493 (funcall org-refile-target-verify-function)))
11494 (not heading))
11495 (let ((re (format org-complex-heading-regexp-format
11496 (regexp-quote heading)))
11497 (target
11498 (if (not org-refile-use-outline-path) heading
11499 (mapconcat
11500 #'identity
11501 (append
11502 (pcase org-refile-use-outline-path
11503 (`file (list (file-name-nondirectory
11504 (buffer-file-name
11505 (buffer-base-buffer)))))
11506 (`full-file-path
11507 (list (buffer-file-name
11508 (buffer-base-buffer))))
11509 (`buffer-name
11510 (list (buffer-name
11511 (buffer-base-buffer))))
11512 (_ nil))
11513 (mapcar (lambda (s) (replace-regexp-in-string
11514 "/" "\\/" s nil t))
11515 (org-get-outline-path t t)))
11516 "/"))))
11517 (push (list target f re (org-refile-marker (point)))
11518 tgs)))
11519 (when (= (point) begin)
11520 ;; Verification function has not moved point.
11521 (end-of-line)))))))
11522 (when org-refile-use-cache
11523 (org-refile-cache-put tgs (buffer-file-name) descre))
11524 (setq targets (append tgs targets))))))
11525 (message "Getting targets...done")
11526 (delete-dups (nreverse targets))))
11528 (defun org--get-outline-path-1 (&optional use-cache)
11529 "Return outline path to current headline.
11531 Outline path is a list of strings, in reverse order. When
11532 optional argument USE-CACHE is non-nil, make use of a cache. See
11533 `org-get-outline-path' for details.
11535 Assume buffer is widened and point is on a headline."
11536 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11537 (let ((p (point))
11538 (heading (let ((case-fold-search nil))
11539 (looking-at org-complex-heading-regexp)
11540 (if (not (match-end 4)) ""
11541 ;; Remove statistics cookies.
11542 (org-trim
11543 (org-link-display-format
11544 (replace-regexp-in-string
11545 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11546 (match-string-no-properties 4))))))))
11547 (if (org-up-heading-safe)
11548 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11549 (when use-cache
11550 (push (cons p path) org-outline-path-cache))
11551 path)
11552 ;; This is a new root node. Since we assume we are moving
11553 ;; forward, we can drop previous cache so as to limit number
11554 ;; of associations there.
11555 (let ((path (list heading)))
11556 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11557 path)))))
11559 (defun org-get-outline-path (&optional with-self use-cache)
11560 "Return the outline path to the current entry.
11562 An outline path is a list of ancestors for current headline, as
11563 a list of strings. Statistics cookies are removed and links are
11564 replaced with their description, if any, or their path otherwise.
11566 When optional argument WITH-SELF is non-nil, the path also
11567 includes the current headline.
11569 When optional argument USE-CACHE is non-nil, cache outline paths
11570 between calls to this function so as to avoid backtracking. This
11571 argument is useful when planning to find more than one outline
11572 path in the same document. In that case, there are two
11573 conditions to satisfy:
11574 - `org-outline-path-cache' is set to nil before starting the
11575 process;
11576 - outline paths are computed by increasing buffer positions."
11577 (org-with-wide-buffer
11578 (and (or (and with-self (org-back-to-heading t))
11579 (org-up-heading-safe))
11580 (reverse (org--get-outline-path-1 use-cache)))))
11582 (defun org-format-outline-path (path &optional width prefix separator)
11583 "Format the outline path PATH for display.
11584 WIDTH is the maximum number of characters that is available.
11585 PREFIX is a prefix to be included in the returned string,
11586 such as the file name.
11587 SEPARATOR is inserted between the different parts of the path,
11588 the default is \"/\"."
11589 (setq width (or width 79))
11590 (setq path (delq nil path))
11591 (unless (> width 0)
11592 (user-error "Argument `width' must be positive"))
11593 (setq separator (or separator "/"))
11594 (let* ((org-odd-levels-only nil)
11595 (fpath (concat
11596 prefix (and prefix path separator)
11597 (mapconcat
11598 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11599 (cl-loop for head in path
11600 for n from 0
11601 collect (org-add-props
11602 head nil 'face
11603 (nth (% n org-n-level-faces) org-level-faces)))
11604 separator))))
11605 (when (> (length fpath) width)
11606 (if (< width 7)
11607 ;; It's unlikely that `width' will be this small, but don't
11608 ;; waste characters by adding ".." if it is.
11609 (setq fpath (substring fpath 0 width))
11610 (setf (substring fpath (- width 2)) "..")))
11611 fpath))
11613 (defun org-display-outline-path (&optional file current separator just-return-string)
11614 "Display the current outline path in the echo area.
11616 If FILE is non-nil, prepend the output with the file name.
11617 If CURRENT is non-nil, append the current heading to the output.
11618 SEPARATOR is passed through to `org-format-outline-path'. It separates
11619 the different parts of the path and defaults to \"/\".
11620 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11621 (interactive "P")
11622 (let* (case-fold-search
11623 (bfn (buffer-file-name (buffer-base-buffer)))
11624 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11625 res)
11626 (when current (setq path (append path
11627 (save-excursion
11628 (org-back-to-heading t)
11629 (when (looking-at org-complex-heading-regexp)
11630 (list (match-string 4)))))))
11631 (setq res
11632 (org-format-outline-path
11633 path
11634 (1- (frame-width))
11635 (and file bfn (concat (file-name-nondirectory bfn) separator))
11636 separator))
11637 (if just-return-string
11638 (org-no-properties res)
11639 (org-unlogged-message "%s" res))))
11641 (defvar org-refile-history nil
11642 "History for refiling operations.")
11644 (defvar org-after-refile-insert-hook nil
11645 "Hook run after `org-refile' has inserted its stuff at the new location.
11646 Note that this is still *before* the stuff will be removed from
11647 the *old* location.")
11649 (defvar org-capture-last-stored-marker)
11650 (defvar org-refile-keep nil
11651 "Non-nil means `org-refile' will copy instead of refile.")
11653 (defun org-copy ()
11654 "Like `org-refile', but copy."
11655 (interactive)
11656 (let ((org-refile-keep t))
11657 (funcall 'org-refile nil nil nil "Copy")))
11659 (defun org-refile (&optional arg default-buffer rfloc msg)
11660 "Move the entry or entries at point to another heading.
11662 The list of target headings is compiled using the information in
11663 `org-refile-targets', which see.
11665 At the target location, the entry is filed as a subitem of the
11666 target heading. Depending on `org-reverse-note-order', the new
11667 subitem will either be the first or the last subitem.
11669 If there is an active region, all entries in that region will be
11670 refiled. However, the region must fulfill the requirement that
11671 the first heading sets the top-level of the moved text.
11673 With a `\\[universal-argument]' ARG, the command will only visit the target \
11674 location
11675 and not actually move anything.
11677 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11678 location where the last
11679 refiling operation has put the subtree.
11681 With a numeric prefix argument of `2', refile to the running clock.
11683 With a numeric prefix argument of `3', emulate `org-refile-keep'
11684 being set to t and copy to the target location, don't move it.
11685 Beware that keeping refiled entries may result in duplicated ID
11686 properties.
11688 RFLOC can be a refile location obtained in a different way.
11690 MSG is a string to replace \"Refile\" in the default prompt with
11691 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11693 See also `org-refile-use-outline-path'.
11695 If you are using target caching (see `org-refile-use-cache'), you
11696 have to clear the target cache in order to find new targets.
11697 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11698 prefix argument (`C-u C-u C-u C-c C-w')."
11699 (interactive "P")
11700 (if (member arg '(0 (64)))
11701 (org-refile-cache-clear)
11702 (let* ((actionmsg (cond (msg msg)
11703 ((equal arg 3) "Refile (and keep)")
11704 (t "Refile")))
11705 (regionp (org-region-active-p))
11706 (region-start (and regionp (region-beginning)))
11707 (region-end (and regionp (region-end)))
11708 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11709 pos it nbuf file level reversed)
11710 (setq last-command nil)
11711 (when regionp
11712 (goto-char region-start)
11713 (or (bolp) (goto-char (point-at-bol)))
11714 (setq region-start (point))
11715 (unless (or (org-kill-is-subtree-p
11716 (buffer-substring region-start region-end))
11717 (prog1 org-refile-active-region-within-subtree
11718 (let ((s (point-at-eol)))
11719 (org-toggle-heading)
11720 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11721 (user-error "The region is not a (sequence of) subtree(s)")))
11722 (if (equal arg '(16))
11723 (org-refile-goto-last-stored)
11724 (when (or
11725 (and (equal arg 2)
11726 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11727 (prog1
11728 (setq it (list (or org-clock-heading "running clock")
11729 (buffer-file-name
11730 (marker-buffer org-clock-hd-marker))
11732 (marker-position org-clock-hd-marker)))
11733 (setq arg nil)))
11734 (setq it
11735 (or rfloc
11736 (let (heading-text)
11737 (save-excursion
11738 (unless (and arg (listp arg))
11739 (org-back-to-heading t)
11740 (setq heading-text
11741 (replace-regexp-in-string
11742 org-bracket-link-regexp
11743 "\\3"
11744 (or (nth 4 (org-heading-components))
11745 ""))))
11746 (org-refile-get-location
11747 (cond ((and arg (listp arg)) "Goto")
11748 (regionp (concat actionmsg " region to"))
11749 (t (concat actionmsg " subtree \""
11750 heading-text "\" to")))
11751 default-buffer
11752 (and (not (equal '(4) arg))
11753 org-refile-allow-creating-parent-nodes)))))))
11754 (setq file (nth 1 it)
11755 pos (nth 3 it))
11756 (when (and (not arg)
11758 (equal (buffer-file-name) file)
11759 (if regionp
11760 (and (>= pos region-start)
11761 (<= pos region-end))
11762 (and (>= pos (point))
11763 (< pos (save-excursion
11764 (org-end-of-subtree t t))))))
11765 (error "Cannot refile to position inside the tree or region"))
11766 (setq nbuf (or (find-buffer-visiting file)
11767 (find-file-noselect file)))
11768 (if (and arg (not (equal arg 3)))
11769 (progn
11770 (pop-to-buffer-same-window nbuf)
11771 (goto-char (cond (pos)
11772 ((org-notes-order-reversed-p) (point-min))
11773 (t (point-max))))
11774 (org-show-context 'org-goto))
11775 (if regionp
11776 (progn
11777 (org-kill-new (buffer-substring region-start region-end))
11778 (org-save-markers-in-region region-start region-end))
11779 (org-copy-subtree 1 nil t))
11780 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11781 (find-file-noselect file)))
11782 (setq reversed (org-notes-order-reversed-p))
11783 (org-with-wide-buffer
11784 (if pos
11785 (progn
11786 (goto-char pos)
11787 (setq level (org-get-valid-level (funcall outline-level) 1))
11788 (goto-char
11789 (if reversed
11790 (or (outline-next-heading) (point-max))
11791 (or (save-excursion (org-get-next-sibling))
11792 (org-end-of-subtree t t)
11793 (point-max)))))
11794 (setq level 1)
11795 (if (not reversed)
11796 (goto-char (point-max))
11797 (goto-char (point-min))
11798 (or (outline-next-heading) (goto-char (point-max)))))
11799 (unless (bolp) (newline))
11800 (org-paste-subtree level nil nil t)
11801 (when org-log-refile
11802 (org-add-log-setup 'refile nil nil org-log-refile)
11803 (unless (eq org-log-refile 'note)
11804 (save-excursion (org-add-log-note))))
11805 (and org-auto-align-tags
11806 (let ((org-loop-over-headlines-in-active-region nil))
11807 (org-set-tags nil t)))
11808 (let ((bookmark-name (plist-get org-bookmark-names-plist
11809 :last-refile)))
11810 (when bookmark-name
11811 (with-demoted-errors
11812 (bookmark-set bookmark-name))))
11813 ;; If we are refiling for capture, make sure that the
11814 ;; last-capture pointers point here
11815 (when (bound-and-true-p org-capture-is-refiling)
11816 (let ((bookmark-name (plist-get org-bookmark-names-plist
11817 :last-capture-marker)))
11818 (when bookmark-name
11819 (with-demoted-errors
11820 (bookmark-set bookmark-name))))
11821 (move-marker org-capture-last-stored-marker (point)))
11822 (when (fboundp 'deactivate-mark) (deactivate-mark))
11823 (run-hooks 'org-after-refile-insert-hook)))
11824 (unless org-refile-keep
11825 (if regionp
11826 (delete-region (point) (+ (point) (- region-end region-start)))
11827 (delete-region
11828 (and (org-back-to-heading t) (point))
11829 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11830 (when (featurep 'org-inlinetask)
11831 (org-inlinetask-remove-END-maybe))
11832 (setq org-markers-to-move nil)
11833 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11835 (defun org-refile-goto-last-stored ()
11836 "Go to the location where the last refile was stored."
11837 (interactive)
11838 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11839 (message "This is the location of the last refile"))
11841 (defun org-refile--get-location (refloc tbl)
11842 "When user refile to REFLOC, find the associated target in TBL.
11843 Also check `org-refile-target-table'."
11844 (car (delq
11846 (mapcar
11847 (lambda (r) (or (assoc r tbl)
11848 (assoc r org-refile-target-table)))
11849 (list (replace-regexp-in-string "/$" "" refloc)
11850 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11852 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11853 "Prompt the user for a refile location, using PROMPT.
11854 PROMPT should not be suffixed with a colon and a space, because
11855 this function appends the default value from
11856 `org-refile-history' automatically, if that is not empty."
11857 (let ((org-refile-targets org-refile-targets)
11858 (org-refile-use-outline-path org-refile-use-outline-path))
11859 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11860 (unless org-refile-target-table
11861 (user-error "No refile targets"))
11862 (let* ((cbuf (current-buffer))
11863 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11864 (cfunc (if (and org-refile-use-outline-path
11865 org-outline-path-complete-in-steps)
11866 #'org-olpath-completing-read
11867 #'completing-read))
11868 (extra (if org-refile-use-outline-path "/" ""))
11869 (cbnex (concat (buffer-name) extra))
11870 (filename (and cfn (expand-file-name cfn)))
11871 (tbl (mapcar
11872 (lambda (x)
11873 (if (and (not (member org-refile-use-outline-path
11874 '(file full-file-path)))
11875 (not (equal filename (nth 1 x))))
11876 (cons (concat (car x) extra " ("
11877 (file-name-nondirectory (nth 1 x)) ")")
11878 (cdr x))
11879 (cons (concat (car x) extra) (cdr x))))
11880 org-refile-target-table))
11881 (completion-ignore-case t)
11882 cdef
11883 (prompt (concat prompt
11884 (or (and (car org-refile-history)
11885 (concat " (default " (car org-refile-history) ")"))
11886 (and (assoc cbnex tbl) (setq cdef cbnex)
11887 (concat " (default " cbnex ")"))) ": "))
11888 pa answ parent-target child parent old-hist)
11889 (setq old-hist org-refile-history)
11890 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11891 nil 'org-refile-history (or cdef (car org-refile-history))))
11892 (if (setq pa (org-refile--get-location answ tbl))
11893 (progn
11894 (org-refile-check-position pa)
11895 (when (or (not org-refile-history)
11896 (not (eq old-hist org-refile-history))
11897 (not (equal (car pa) (car org-refile-history))))
11898 (setq org-refile-history
11899 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11900 org-refile-history
11901 (cdr org-refile-history))))
11902 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11903 (pop org-refile-history)))
11905 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11906 (progn
11907 (setq parent (match-string 1 answ)
11908 child (match-string 2 answ))
11909 (setq parent-target (org-refile--get-location parent tbl))
11910 (when (and parent-target
11911 (or (eq new-nodes t)
11912 (and (eq new-nodes 'confirm)
11913 (y-or-n-p (format "Create new node \"%s\"? "
11914 child)))))
11915 (org-refile-new-child parent-target child)))
11916 (user-error "Invalid target location")))))
11918 (declare-function org-string-nw-p "org-macs" (s))
11919 (defun org-refile-check-position (refile-pointer)
11920 "Check if the refile pointer matches the headline to which it points."
11921 (let* ((file (nth 1 refile-pointer))
11922 (re (nth 2 refile-pointer))
11923 (pos (nth 3 refile-pointer))
11924 buffer)
11925 (if (and (not (markerp pos)) (not file))
11926 (user-error "Please indicate a target file in the refile path")
11927 (when (org-string-nw-p re)
11928 (setq buffer (if (markerp pos)
11929 (marker-buffer pos)
11930 (or (find-buffer-visiting file)
11931 (find-file-noselect file))))
11932 (with-current-buffer buffer
11933 (org-with-wide-buffer
11934 (goto-char pos)
11935 (beginning-of-line 1)
11936 (unless (looking-at-p re)
11937 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11939 (defun org-refile-new-child (parent-target child)
11940 "Use refile target PARENT-TARGET to add new CHILD below it."
11941 (unless parent-target
11942 (error "Cannot find parent for new node"))
11943 (let ((file (nth 1 parent-target))
11944 (pos (nth 3 parent-target))
11945 level)
11946 (with-current-buffer (or (find-buffer-visiting file)
11947 (find-file-noselect file))
11948 (org-with-wide-buffer
11949 (if pos
11950 (goto-char pos)
11951 (goto-char (point-max))
11952 (unless (bolp) (newline)))
11953 (when (looking-at org-outline-regexp)
11954 (setq level (funcall outline-level))
11955 (org-end-of-subtree t t))
11956 (org-back-over-empty-lines)
11957 (insert "\n" (make-string
11958 (if pos (org-get-valid-level level 1) 1) ?*)
11959 " " child "\n")
11960 (beginning-of-line 0)
11961 (list (concat (car parent-target) "/" child) file "" (point))))))
11963 (defun org-olpath-completing-read (prompt collection &rest args)
11964 "Read an outline path like a file name."
11965 (let ((thetable collection))
11966 (apply #'completing-read
11967 prompt
11968 (lambda (string predicate &optional flag)
11969 (cond
11970 ((eq flag nil) (try-completion string thetable))
11971 ((eq flag t)
11972 (let ((l (length string)))
11973 (mapcar (lambda (x)
11974 (let ((r (substring x l))
11975 (f (if (string-match " ([^)]*)$" x)
11976 (match-string 0 x)
11977 "")))
11978 (if (string-match "/" r)
11979 (concat string (substring r 0 (match-end 0)) f)
11980 x)))
11981 (all-completions string thetable predicate))))
11982 ;; Exact match?
11983 ((eq flag 'lambda) (assoc string thetable))))
11984 args)))
11986 ;;;; Dynamic blocks
11988 (defun org-find-dblock (name)
11989 "Find the first dynamic block with name NAME in the buffer.
11990 If not found, stay at current position and return nil."
11991 (let ((case-fold-search t) pos)
11992 (save-excursion
11993 (goto-char (point-min))
11994 (setq pos (and (re-search-forward
11995 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11996 (match-beginning 0))))
11997 (when pos (goto-char pos))
11998 pos))
12000 (defun org-create-dblock (plist)
12001 "Create a dynamic block section, with parameters taken from PLIST.
12002 PLIST must contain a :name entry which is used as the name of the block."
12003 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12004 (end-of-line 1)
12005 (newline))
12006 (let ((col (current-column))
12007 (name (plist-get plist :name)))
12008 (insert "#+BEGIN: " name)
12009 (while plist
12010 (if (eq (car plist) :name)
12011 (setq plist (cddr plist))
12012 (insert " " (prin1-to-string (pop plist)))))
12013 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12014 (beginning-of-line -2)))
12016 (defun org-prepare-dblock ()
12017 "Prepare dynamic block for refresh.
12018 This empties the block, puts the cursor at the insert position and returns
12019 the property list including an extra property :name with the block name."
12020 (unless (looking-at org-dblock-start-re)
12021 (user-error "Not at a dynamic block"))
12022 (let* ((begdel (1+ (match-end 0)))
12023 (name (org-no-properties (match-string 1)))
12024 (params (append (list :name name)
12025 (read (concat "(" (match-string 3) ")")))))
12026 (save-excursion
12027 (beginning-of-line 1)
12028 (skip-chars-forward " \t")
12029 (setq params (plist-put params :indentation-column (current-column))))
12030 (unless (re-search-forward org-dblock-end-re nil t)
12031 (error "Dynamic block not terminated"))
12032 (setq params
12033 (append params
12034 (list :content (buffer-substring
12035 begdel (match-beginning 0)))))
12036 (delete-region begdel (match-beginning 0))
12037 (goto-char begdel)
12038 (open-line 1)
12039 params))
12041 (defun org-map-dblocks (&optional command)
12042 "Apply COMMAND to all dynamic blocks in the current buffer.
12043 If COMMAND is not given, use `org-update-dblock'."
12044 (let ((cmd (or command 'org-update-dblock)))
12045 (save-excursion
12046 (goto-char (point-min))
12047 (while (re-search-forward org-dblock-start-re nil t)
12048 (goto-char (match-beginning 0))
12049 (save-excursion
12050 (condition-case nil
12051 (funcall cmd)
12052 (error (message "Error during update of dynamic block"))))
12053 (unless (re-search-forward org-dblock-end-re nil t)
12054 (error "Dynamic block not terminated"))))))
12056 (defun org-dblock-update (&optional arg)
12057 "User command for updating dynamic blocks.
12058 Update the dynamic block at point. With prefix ARG, update all dynamic
12059 blocks in the buffer."
12060 (interactive "P")
12061 (if arg
12062 (org-update-all-dblocks)
12063 (or (looking-at org-dblock-start-re)
12064 (org-beginning-of-dblock))
12065 (org-update-dblock)))
12067 (defun org-update-dblock ()
12068 "Update the dynamic block at point.
12069 This means to empty the block, parse for parameters and then call
12070 the correct writing function."
12071 (interactive)
12072 (save-excursion
12073 (let* ((win (selected-window))
12074 (pos (point))
12075 (line (org-current-line))
12076 (params (org-prepare-dblock))
12077 (name (plist-get params :name))
12078 (indent (plist-get params :indentation-column))
12079 (cmd (intern (concat "org-dblock-write:" name))))
12080 (message "Updating dynamic block `%s' at line %d..." name line)
12081 (funcall cmd params)
12082 (message "Updating dynamic block `%s' at line %d...done" name line)
12083 (goto-char pos)
12084 (when (and indent (> indent 0))
12085 (setq indent (make-string indent ?\ ))
12086 (save-excursion
12087 (select-window win)
12088 (org-beginning-of-dblock)
12089 (forward-line 1)
12090 (while (not (looking-at org-dblock-end-re))
12091 (insert indent)
12092 (beginning-of-line 2))
12093 (when (looking-at org-dblock-end-re)
12094 (and (looking-at "[ \t]+")
12095 (replace-match ""))
12096 (insert indent)))))))
12098 (defun org-beginning-of-dblock ()
12099 "Find the beginning of the dynamic block at point.
12100 Error if there is no such block at point."
12101 (let ((pos (point))
12102 beg)
12103 (end-of-line 1)
12104 (if (and (re-search-backward org-dblock-start-re nil t)
12105 (setq beg (match-beginning 0))
12106 (re-search-forward org-dblock-end-re nil t)
12107 (> (match-end 0) pos))
12108 (goto-char beg)
12109 (goto-char pos)
12110 (error "Not in a dynamic block"))))
12112 (defun org-update-all-dblocks ()
12113 "Update all dynamic blocks in the buffer.
12114 This function can be used in a hook."
12115 (interactive)
12116 (when (derived-mode-p 'org-mode)
12117 (org-map-dblocks 'org-update-dblock)))
12120 ;;;; Completion
12122 (declare-function org-export-backend-options "ox" (cl-x) t)
12123 (defun org-get-export-keywords ()
12124 "Return a list of all currently understood export keywords.
12125 Export keywords include options, block names, attributes and
12126 keywords relative to each registered export back-end."
12127 (let (keywords)
12128 (dolist (backend
12129 (bound-and-true-p org-export-registered-backends)
12130 (delq nil keywords))
12131 ;; Back-end name (for keywords, like #+LATEX:)
12132 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12133 (dolist (option-entry (org-export-backend-options backend))
12134 ;; Back-end options.
12135 (push (nth 1 option-entry) keywords)))))
12137 (defconst org-options-keywords
12138 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12139 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12140 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12141 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12142 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12144 (defcustom org-structure-template-alist
12145 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12146 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12147 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12148 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12149 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12150 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12151 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12152 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12153 ("L" "#+LaTeX: ")
12154 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12155 ("H" "#+HTML: ")
12156 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12157 ("A" "#+ASCII: ")
12158 ("i" "#+INDEX: ?")
12159 ("I" "#+INCLUDE: %file ?"))
12160 "Structure completion elements.
12161 This is a list of abbreviation keys and values. The value gets inserted
12162 if you type `<' followed by the key and then press the completion key,
12163 usually `TAB'. %file will be replaced by a file name after prompting
12164 for the file using completion. The cursor will be placed at the position
12165 of the `?' in the template.
12166 There are two templates for each key, the first uses the original Org syntax,
12167 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12168 the default when the /org-mtags.el/ module has been loaded. See also the
12169 variable `org-mtags-prefer-muse-templates'."
12170 :group 'org-completion
12171 :type '(repeat
12172 (list
12173 (string :tag "Key")
12174 (string :tag "Template")))
12175 :version "26.1"
12176 :package-version '(Org . "8.3"))
12178 (defun org-try-structure-completion ()
12179 "Try to complete a structure template before point.
12180 This looks for strings like \"<e\" on an otherwise empty line and
12181 expands them."
12182 (let ((l (buffer-substring (point-at-bol) (point)))
12184 (when (and (looking-at "[ \t]*$")
12185 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12186 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12187 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12188 (match-beginning 1)) a)
12189 t)))
12191 (defun org-complete-expand-structure-template (start cell)
12192 "Expand a structure template."
12193 (let ((rpl (nth 1 cell))
12194 (ind ""))
12195 (delete-region start (point))
12196 (when (string-match "\\`[ \t]*#\\+" rpl)
12197 (cond
12198 ((bolp))
12199 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12200 (setq ind (buffer-substring (point-at-bol) (point))))
12201 (t (newline))))
12202 (setq start (point))
12203 (when (string-match "%file" rpl)
12204 (setq rpl (replace-match
12205 (concat
12206 "\""
12207 (save-match-data
12208 (abbreviate-file-name (read-file-name "Include file: ")))
12209 "\"")
12210 t t rpl)))
12211 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12212 (concat "\n" ind)))
12213 (insert rpl)
12214 (when (re-search-backward "\\?" start t) (delete-char 1))))
12216 ;;;; TODO, DEADLINE, Comments
12218 (defun org-toggle-comment ()
12219 "Change the COMMENT state of an entry."
12220 (interactive)
12221 (save-excursion
12222 (org-back-to-heading)
12223 (let ((case-fold-search nil))
12224 (looking-at org-complex-heading-regexp))
12225 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12226 (skip-chars-forward " \t")
12227 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12228 (if (org-in-commented-heading-p t)
12229 (delete-region (point)
12230 (progn (search-forward " " (line-end-position) 'move)
12231 (skip-chars-forward " \t")
12232 (point)))
12233 (insert org-comment-string)
12234 (unless (eolp) (insert " ")))))
12236 (defvar org-last-todo-state-is-todo nil
12237 "This is non-nil when the last TODO state change led to a TODO state.
12238 If the last change removed the TODO tag or switched to DONE, then
12239 this is nil.")
12241 (defvar org-setting-tags nil) ; dynamically skipped
12243 (defvar org-todo-setup-filter-hook nil
12244 "Hook for functions that pre-filter todo specs.
12245 Each function takes a todo spec and returns either nil or the spec
12246 transformed into canonical form." )
12248 (defvar org-todo-get-default-hook nil
12249 "Hook for functions that get a default item for todo.
12250 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12251 nil or a string to be used for the todo mark." )
12253 (defvar org-agenda-headline-snapshot-before-repeat)
12255 (defun org-current-effective-time ()
12256 "Return current time adjusted for `org-extend-today-until' variable."
12257 (let* ((ct (org-current-time))
12258 (dct (decode-time ct))
12259 (ct1
12260 (cond
12261 (org-use-last-clock-out-time-as-effective-time
12262 (or (org-clock-get-last-clock-out-time) ct))
12263 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12264 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12265 (t ct))))
12266 ct1))
12268 (defun org-todo-yesterday (&optional arg)
12269 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12270 (interactive "P")
12271 (if (eq major-mode 'org-agenda-mode)
12272 (apply 'org-agenda-todo-yesterday arg)
12273 (let* ((org-use-effective-time t)
12274 (hour (nth 2 (decode-time (org-current-time))))
12275 (org-extend-today-until (1+ hour)))
12276 (org-todo arg))))
12278 (defvar org-block-entry-blocking ""
12279 "First entry preventing the TODO state change.")
12281 (defun org-cancel-repeater ()
12282 "Cancel a repeater by setting its numeric value to zero."
12283 (interactive)
12284 (save-excursion
12285 (org-back-to-heading t)
12286 (let ((bound1 (point))
12287 (bound0 (save-excursion (outline-next-heading) (point))))
12288 (when (and (re-search-forward
12289 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12290 org-deadline-time-regexp "\\)\\|\\("
12291 org-ts-regexp "\\)")
12292 bound0 t)
12293 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12294 bound1 t))
12295 (replace-match "0" t nil nil 1)))))
12297 (defvar org-state)
12298 (defvar org-blocked-by-checkboxes)
12299 (defun org-todo (&optional arg)
12300 "Change the TODO state of an item.
12302 The state of an item is given by a keyword at the start of the heading,
12303 like
12304 *** TODO Write paper
12305 *** DONE Call mom
12307 The different keywords are specified in the variable `org-todo-keywords'.
12308 By default the available states are \"TODO\" and \"DONE\". So, for this
12309 example: when the item starts with TODO, it is changed to DONE.
12310 When it starts with DONE, the DONE is removed. And when neither TODO nor
12311 DONE are present, add TODO at the beginning of the heading.
12313 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12314 state.
12315 With numeric prefix ARG, switch to that state.
12316 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12317 next set of TODO \
12318 keywords (nextset).
12319 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12320 prefix, circumvent any state blocking.
12321 With a numeric prefix arg of 0, inhibit note taking for the change.
12322 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12324 When called through ELisp, arg is also interpreted in the following way:
12325 `none' -> empty state
12326 \"\" -> switch to empty state
12327 `done' -> switch to DONE
12328 `nextset' -> switch to the next set of keywords
12329 `previousset' -> switch to the previous set of keywords
12330 \"WAITING\" -> switch to the specified keyword, but only if it
12331 really is a member of `org-todo-keywords'."
12332 (interactive "P")
12333 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12334 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12335 'region-start-level 'region))
12336 org-loop-over-headlines-in-active-region)
12337 (org-map-entries
12338 `(org-todo ,arg)
12339 org-loop-over-headlines-in-active-region
12340 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12341 (when (equal arg '(16)) (setq arg 'nextset))
12342 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12343 (let ((org-blocker-hook org-blocker-hook)
12344 commentp
12345 case-fold-search)
12346 (when (equal arg '(64))
12347 (setq arg nil org-blocker-hook nil))
12348 (when (and org-blocker-hook
12349 (or org-inhibit-blocking
12350 (org-entry-get nil "NOBLOCKING")))
12351 (setq org-blocker-hook nil))
12352 (save-excursion
12353 (catch 'exit
12354 (org-back-to-heading t)
12355 (when (org-in-commented-heading-p t)
12356 (org-toggle-comment)
12357 (setq commentp t))
12358 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12359 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12360 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12361 (let* ((match-data (match-data))
12362 (startpos (point-at-bol))
12363 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12364 (org-log-done org-log-done)
12365 (org-log-repeat org-log-repeat)
12366 (org-todo-log-states org-todo-log-states)
12367 (org-inhibit-logging
12368 (if (equal arg 0)
12369 (progn (setq arg nil) 'note) org-inhibit-logging))
12370 (this (match-string 1))
12371 (hl-pos (match-beginning 0))
12372 (head (org-get-todo-sequence-head this))
12373 (ass (assoc head org-todo-kwd-alist))
12374 (interpret (nth 1 ass))
12375 (done-word (nth 3 ass))
12376 (final-done-word (nth 4 ass))
12377 (org-last-state (or this ""))
12378 (completion-ignore-case t)
12379 (member (member this org-todo-keywords-1))
12380 (tail (cdr member))
12381 (org-state (cond
12382 ((and org-todo-key-trigger
12383 (or (and (equal arg '(4))
12384 (eq org-use-fast-todo-selection 'prefix))
12385 (and (not arg) org-use-fast-todo-selection
12386 (not (eq org-use-fast-todo-selection
12387 'prefix)))))
12388 ;; Use fast selection.
12389 (org-fast-todo-selection))
12390 ((and (equal arg '(4))
12391 (or (not org-use-fast-todo-selection)
12392 (not org-todo-key-trigger)))
12393 ;; Read a state with completion.
12394 (completing-read
12395 "State: " (mapcar #'list org-todo-keywords-1)
12396 nil t))
12397 ((eq arg 'right)
12398 (if this
12399 (if tail (car tail) nil)
12400 (car org-todo-keywords-1)))
12401 ((eq arg 'left)
12402 (unless (equal member org-todo-keywords-1)
12403 (if this
12404 (nth (- (length org-todo-keywords-1)
12405 (length tail) 2)
12406 org-todo-keywords-1)
12407 (org-last org-todo-keywords-1))))
12408 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12409 (setq arg nil))) ;hack to fall back to cycling
12410 (arg
12411 ;; User or caller requests a specific state.
12412 (cond
12413 ((equal arg "") nil)
12414 ((eq arg 'none) nil)
12415 ((eq arg 'done) (or done-word (car org-done-keywords)))
12416 ((eq arg 'nextset)
12417 (or (car (cdr (member head org-todo-heads)))
12418 (car org-todo-heads)))
12419 ((eq arg 'previousset)
12420 (let ((org-todo-heads (reverse org-todo-heads)))
12421 (or (car (cdr (member head org-todo-heads)))
12422 (car org-todo-heads))))
12423 ((car (member arg org-todo-keywords-1)))
12424 ((stringp arg)
12425 (user-error "State `%s' not valid in this file" arg))
12426 ((nth (1- (prefix-numeric-value arg))
12427 org-todo-keywords-1))))
12428 ((null member) (or head (car org-todo-keywords-1)))
12429 ((equal this final-done-word) nil) ;-> make empty
12430 ((null tail) nil) ;-> first entry
12431 ((memq interpret '(type priority))
12432 (if (eq this-command last-command)
12433 (car tail)
12434 (if (> (length tail) 0)
12435 (or done-word (car org-done-keywords))
12436 nil)))
12438 (car tail))))
12439 (org-state (or
12440 (run-hook-with-args-until-success
12441 'org-todo-get-default-hook org-state org-last-state)
12442 org-state))
12443 (next (if org-state (concat " " org-state " ") " "))
12444 (change-plist (list :type 'todo-state-change :from this :to org-state
12445 :position startpos))
12446 dolog now-done-p)
12447 (when org-blocker-hook
12448 (let (org-blocked-by-checkboxes block-reason)
12449 (setq org-last-todo-state-is-todo
12450 (not (member this org-done-keywords)))
12451 (unless (save-excursion
12452 (save-match-data
12453 (org-with-wide-buffer
12454 (run-hook-with-args-until-failure
12455 'org-blocker-hook change-plist))))
12456 (setq block-reason (if org-blocked-by-checkboxes
12457 "contained checkboxes"
12458 (format "\"%s\"" org-block-entry-blocking)))
12459 (if (called-interactively-p 'interactive)
12460 (user-error "TODO state change from %s to %s blocked (by %s)"
12461 this org-state block-reason)
12462 ;; Fail silently.
12463 (message "TODO state change from %s to %s blocked (by %s)"
12464 this org-state block-reason)
12465 (throw 'exit nil)))))
12466 (store-match-data match-data)
12467 (replace-match next t t)
12468 (cond ((equal this org-state)
12469 (message "TODO state was already %s" (org-trim next)))
12470 ((not (pos-visible-in-window-p hl-pos))
12471 (message "TODO state changed to %s" (org-trim next))))
12472 (unless head
12473 (setq head (org-get-todo-sequence-head org-state)
12474 ass (assoc head org-todo-kwd-alist)
12475 interpret (nth 1 ass)
12476 done-word (nth 3 ass)
12477 final-done-word (nth 4 ass)))
12478 (when (memq arg '(nextset previousset))
12479 (message "Keyword-Set %d/%d: %s"
12480 (- (length org-todo-sets) -1
12481 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12482 (length org-todo-sets)
12483 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12484 (setq org-last-todo-state-is-todo
12485 (not (member org-state org-done-keywords)))
12486 (setq now-done-p (and (member org-state org-done-keywords)
12487 (not (member this org-done-keywords))))
12488 (and logging (org-local-logging logging))
12489 (when (and (or org-todo-log-states org-log-done)
12490 (not (eq org-inhibit-logging t))
12491 (not (memq arg '(nextset previousset))))
12492 ;; We need to look at recording a time and note.
12493 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12494 (nth 2 (assoc this org-todo-log-states))))
12495 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12496 (setq dolog 'time))
12497 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12498 (and org-state
12499 (member org-state org-not-done-keywords)
12500 (not (member this org-not-done-keywords))))
12501 ;; This is now a todo state and was not one before
12502 ;; If there was a CLOSED time stamp, get rid of it.
12503 (org-add-planning-info nil nil 'closed))
12504 (when (and now-done-p org-log-done)
12505 ;; It is now done, and it was not done before.
12506 (org-add-planning-info 'closed (org-current-effective-time))
12507 (when (and (not dolog) (eq 'note org-log-done))
12508 (org-add-log-setup 'done org-state this 'note)))
12509 (when (and org-state dolog)
12510 ;; This is a non-nil state, and we need to log it.
12511 (org-add-log-setup 'state org-state this dolog)))
12512 ;; Fixup tag positioning.
12513 (org-todo-trigger-tag-changes org-state)
12514 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12515 (when org-provide-todo-statistics
12516 (org-update-parent-todo-statistics))
12517 (run-hooks 'org-after-todo-state-change-hook)
12518 (when (and arg (not (member org-state org-done-keywords)))
12519 (setq head (org-get-todo-sequence-head org-state)))
12520 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12521 ;; Do we need to trigger a repeat?
12522 (when now-done-p
12523 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12524 ;; This is for the agenda, take a snapshot of the headline.
12525 (save-match-data
12526 (setq org-agenda-headline-snapshot-before-repeat
12527 (org-get-heading))))
12528 (org-auto-repeat-maybe org-state))
12529 ;; Fixup cursor location if close to the keyword.
12530 (when (and (outline-on-heading-p)
12531 (not (bolp))
12532 (save-excursion (beginning-of-line 1)
12533 (looking-at org-todo-line-regexp))
12534 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12535 (goto-char (or (match-end 2) (match-end 1)))
12536 (and (looking-at " ") (just-one-space)))
12537 (when org-trigger-hook
12538 (save-excursion
12539 (run-hook-with-args 'org-trigger-hook change-plist)))
12540 (when commentp (org-toggle-comment))))))))
12542 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12543 "Block turning an entry into a TODO, using the hierarchy.
12544 This checks whether the current task should be blocked from state
12545 changes. Such blocking occurs when:
12547 1. The task has children which are not all in a completed state.
12549 2. A task has a parent with the property :ORDERED:, and there
12550 are siblings prior to the current task with incomplete
12551 status.
12553 3. The parent of the task is blocked because it has siblings that should
12554 be done first, or is child of a block grandparent TODO entry."
12556 (if (not org-enforce-todo-dependencies)
12557 t ; if locally turned off don't block
12558 (catch 'dont-block
12559 ;; If this is not a todo state change, or if this entry is already DONE,
12560 ;; do not block
12561 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12562 (member (plist-get change-plist :from)
12563 (cons 'done org-done-keywords))
12564 (member (plist-get change-plist :to)
12565 (cons 'todo org-not-done-keywords))
12566 (not (plist-get change-plist :to)))
12567 (throw 'dont-block t))
12568 ;; If this task has children, and any are undone, it's blocked
12569 (save-excursion
12570 (org-back-to-heading t)
12571 (let ((this-level (funcall outline-level)))
12572 (outline-next-heading)
12573 (let ((child-level (funcall outline-level)))
12574 (while (and (not (eobp))
12575 (> child-level this-level))
12576 ;; this todo has children, check whether they are all
12577 ;; completed
12578 (when (and (not (org-entry-is-done-p))
12579 (org-entry-is-todo-p))
12580 (setq org-block-entry-blocking (org-get-heading))
12581 (throw 'dont-block nil))
12582 (outline-next-heading)
12583 (setq child-level (funcall outline-level))))))
12584 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12585 ;; any previous siblings are undone, it's blocked
12586 (save-excursion
12587 (org-back-to-heading t)
12588 (let* ((pos (point))
12589 (parent-pos (and (org-up-heading-safe) (point)))
12590 (case-fold-search nil))
12591 (unless parent-pos (throw 'dont-block t)) ; no parent
12592 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12593 (forward-line 1)
12594 (re-search-forward org-not-done-heading-regexp pos t))
12595 (setq org-block-entry-blocking (match-string 0))
12596 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12597 ;; Search further up the hierarchy, to see if an ancestor is blocked
12598 (while t
12599 (goto-char parent-pos)
12600 (unless (looking-at org-not-done-heading-regexp)
12601 (throw 'dont-block t)) ; do not block, parent is not a TODO
12602 (setq pos (point))
12603 (setq parent-pos (and (org-up-heading-safe) (point)))
12604 (unless parent-pos (throw 'dont-block t)) ; no parent
12605 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12606 (forward-line 1)
12607 (re-search-forward org-not-done-heading-regexp pos t)
12608 (setq org-block-entry-blocking (org-get-heading)))
12609 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12611 (defcustom org-track-ordered-property-with-tag nil
12612 "Should the ORDERED property also be shown as a tag?
12613 The ORDERED property decides if an entry should require subtasks to be
12614 completed in sequence. Since a property is not very visible, setting
12615 this option means that toggling the ORDERED property with the command
12616 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12617 not relevant for the behavior, but it makes things more visible.
12619 Note that toggling the tag with tags commands will not change the property
12620 and therefore not influence behavior!
12622 This can be t, meaning the tag ORDERED should be used, It can also be a
12623 string to select a different tag for this task."
12624 :group 'org-todo
12625 :type '(choice
12626 (const :tag "No tracking" nil)
12627 (const :tag "Track with ORDERED tag" t)
12628 (string :tag "Use other tag")))
12630 (defun org-toggle-ordered-property ()
12631 "Toggle the ORDERED property of the current entry.
12632 For better visibility, you can track the value of this property with a tag.
12633 See variable `org-track-ordered-property-with-tag'."
12634 (interactive)
12635 (let* ((t1 org-track-ordered-property-with-tag)
12636 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12637 (save-excursion
12638 (org-back-to-heading)
12639 (if (org-entry-get nil "ORDERED")
12640 (progn
12641 (org-delete-property "ORDERED")
12642 (and tag (org-toggle-tag tag 'off))
12643 (message "Subtasks can be completed in arbitrary order"))
12644 (org-entry-put nil "ORDERED" "t")
12645 (and tag (org-toggle-tag tag 'on))
12646 (message "Subtasks must be completed in sequence")))))
12648 (defun org-block-todo-from-checkboxes (change-plist)
12649 "Block turning an entry into a TODO, using checkboxes.
12650 This checks whether the current task should be blocked from state
12651 changes because there are unchecked boxes in this entry."
12652 (if (not org-enforce-todo-checkbox-dependencies)
12653 t ; if locally turned off don't block
12654 (catch 'dont-block
12655 ;; If this is not a todo state change, or if this entry is already DONE,
12656 ;; do not block
12657 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12658 (member (plist-get change-plist :from)
12659 (cons 'done org-done-keywords))
12660 (member (plist-get change-plist :to)
12661 (cons 'todo org-not-done-keywords))
12662 (not (plist-get change-plist :to)))
12663 (throw 'dont-block t))
12664 ;; If this task has checkboxes that are not checked, it's blocked
12665 (save-excursion
12666 (org-back-to-heading t)
12667 (let ((beg (point)) end)
12668 (outline-next-heading)
12669 (setq end (point))
12670 (goto-char beg)
12671 (when (org-list-search-forward
12672 (concat (org-item-beginning-re)
12673 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12674 "\\[[- ]\\]")
12675 end t)
12676 (when (boundp 'org-blocked-by-checkboxes)
12677 (setq org-blocked-by-checkboxes t))
12678 (throw 'dont-block nil))))
12679 t))) ; do not block
12681 (defun org-entry-blocked-p ()
12682 "Non-nil if entry at point is blocked."
12683 (and (not (org-entry-get nil "NOBLOCKING"))
12684 (member (org-entry-get nil "TODO") org-not-done-keywords)
12685 (not (run-hook-with-args-until-failure
12686 'org-blocker-hook
12687 (list :type 'todo-state-change
12688 :position (point)
12689 :from 'todo
12690 :to 'done)))))
12692 (defun org-update-statistics-cookies (all)
12693 "Update the statistics cookie, either from TODO or from checkboxes.
12694 This should be called with the cursor in a line with a statistics
12695 cookie. When called with a \\[universal-argument] prefix, update
12696 all statistics cookies in the buffer."
12697 (interactive "P")
12698 (if all
12699 (progn
12700 (org-update-checkbox-count 'all)
12701 (org-map-entries 'org-update-parent-todo-statistics))
12702 (if (not (org-at-heading-p))
12703 (org-update-checkbox-count)
12704 (let ((pos (point-marker))
12705 end l1 l2)
12706 (ignore-errors (org-back-to-heading t))
12707 (if (not (org-at-heading-p))
12708 (org-update-checkbox-count)
12709 (setq l1 (org-outline-level))
12710 (setq end (save-excursion
12711 (outline-next-heading)
12712 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12713 (point)))
12714 (if (and (save-excursion
12715 (re-search-forward
12716 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12717 (not (save-excursion (re-search-forward
12718 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12719 (org-update-checkbox-count)
12720 (if (and l2 (> l2 l1))
12721 (progn
12722 (goto-char end)
12723 (org-update-parent-todo-statistics))
12724 (goto-char pos)
12725 (beginning-of-line 1)
12726 (while (re-search-forward
12727 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12728 (point-at-eol) t)
12729 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12730 (goto-char pos)
12731 (move-marker pos nil)))))
12733 (defvar org-entry-property-inherited-from) ;; defined below
12734 (defun org-update-parent-todo-statistics ()
12735 "Update any statistics cookie in the parent of the current headline.
12736 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12737 the entire subtree and this will travel up the hierarchy and update
12738 statistics everywhere."
12739 (let* ((prop (save-excursion (org-up-heading-safe)
12740 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12741 (recursive (or (not org-hierarchical-todo-statistics)
12742 (and prop (string-match "\\<recursive\\>" prop))))
12743 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12745 (first t)
12746 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12747 level ltoggle l1 new ndel
12748 (cnt-all 0) (cnt-done 0) is-percent kwd
12749 checkbox-beg cookie-present)
12750 (catch 'exit
12751 (save-excursion
12752 (beginning-of-line 1)
12753 (setq ltoggle (funcall outline-level))
12754 ;; Three situations are to consider:
12756 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12757 ;; to the top-level ancestor on the headline;
12759 ;; 2. If parent has "recursive" property, repeat up to the
12760 ;; headline setting that property, taking inheritance into
12761 ;; account;
12763 ;; 3. Else, move up to direct parent and proceed only once.
12764 (while (and (setq level (org-up-heading-safe))
12765 (or recursive first)
12766 (>= (point) lim))
12767 (setq first nil cookie-present nil)
12768 (unless (and level
12769 (not (string-match
12770 "\\<checkbox\\>"
12771 (downcase (or (org-entry-get nil "COOKIE_DATA")
12772 "")))))
12773 (throw 'exit nil))
12774 (while (re-search-forward box-re (point-at-eol) t)
12775 (setq cnt-all 0 cnt-done 0 cookie-present t)
12776 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12777 (save-match-data
12778 (unless (outline-next-heading) (throw 'exit nil))
12779 (while (and (looking-at org-complex-heading-regexp)
12780 (> (setq l1 (length (match-string 1))) level))
12781 (setq kwd (and (or recursive (= l1 ltoggle))
12782 (match-string 2)))
12783 (if (or (eq org-provide-todo-statistics 'all-headlines)
12784 (and (eq org-provide-todo-statistics t)
12785 (or (member kwd org-done-keywords)))
12786 (and (listp org-provide-todo-statistics)
12787 (stringp (car org-provide-todo-statistics))
12788 (or (member kwd org-provide-todo-statistics)
12789 (member kwd org-done-keywords)))
12790 (and (listp org-provide-todo-statistics)
12791 (listp (car org-provide-todo-statistics))
12792 (or (member kwd (car org-provide-todo-statistics))
12793 (and (member kwd org-done-keywords)
12794 (member kwd (cadr org-provide-todo-statistics))))))
12795 (setq cnt-all (1+ cnt-all))
12796 (and (eq org-provide-todo-statistics t)
12798 (setq cnt-all (1+ cnt-all))))
12799 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12800 (member kwd org-done-keywords))
12801 (and (listp org-provide-todo-statistics)
12802 (listp (car org-provide-todo-statistics))
12803 (member kwd org-done-keywords)
12804 (member kwd (cadr org-provide-todo-statistics)))
12805 (and (listp org-provide-todo-statistics)
12806 (stringp (car org-provide-todo-statistics))
12807 (member kwd org-done-keywords)))
12808 (setq cnt-done (1+ cnt-done)))
12809 (outline-next-heading)))
12810 (setq new
12811 (if is-percent
12812 (format "[%d%%]" (floor (* 100.0 cnt-done)
12813 (max 1 cnt-all)))
12814 (format "[%d/%d]" cnt-done cnt-all))
12815 ndel (- (match-end 0) checkbox-beg))
12816 (goto-char checkbox-beg)
12817 (insert new)
12818 (delete-region (point) (+ (point) ndel))
12819 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12820 (when cookie-present
12821 (run-hook-with-args 'org-after-todo-statistics-hook
12822 cnt-done (- cnt-all cnt-done))))))
12823 (run-hooks 'org-todo-statistics-hook)))
12825 (defvar org-after-todo-statistics-hook nil
12826 "Hook that is called after a TODO statistics cookie has been updated.
12827 Each function is called with two arguments: the number of not-done entries
12828 and the number of done entries.
12830 For example, the following function, when added to this hook, will switch
12831 an entry to DONE when all children are done, and back to TODO when new
12832 entries are set to a TODO status. Note that this hook is only called
12833 when there is a statistics cookie in the headline!
12835 (defun org-summary-todo (n-done n-not-done)
12836 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12837 (let (org-log-done org-log-states) ; turn off logging
12838 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12841 (defvar org-todo-statistics-hook nil
12842 "Hook that is run whenever Org thinks TODO statistics should be updated.
12843 This hook runs even if there is no statistics cookie present, in which case
12844 `org-after-todo-statistics-hook' would not run.")
12846 (defun org-todo-trigger-tag-changes (state)
12847 "Apply the changes defined in `org-todo-state-tags-triggers'."
12848 (let ((l org-todo-state-tags-triggers)
12849 changes)
12850 (when (or (not state) (equal state ""))
12851 (setq changes (append changes (cdr (assoc "" l)))))
12852 (when (and (stringp state) (> (length state) 0))
12853 (setq changes (append changes (cdr (assoc state l)))))
12854 (when (member state org-not-done-keywords)
12855 (setq changes (append changes (cdr (assq 'todo l)))))
12856 (when (member state org-done-keywords)
12857 (setq changes (append changes (cdr (assq 'done l)))))
12858 (dolist (c changes)
12859 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12861 (defun org-local-logging (value)
12862 "Get logging settings from a property VALUE."
12863 ;; Directly set the variables, they are already local.
12864 (setq org-log-done nil
12865 org-log-repeat nil
12866 org-todo-log-states nil)
12867 (dolist (w (split-string value))
12868 (let (a)
12869 (cond
12870 ((setq a (assoc w org-startup-options))
12871 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12872 (set (nth 1 a) (nth 2 a))))
12873 ((setq a (org-extract-log-state-settings w))
12874 (and (member (car a) org-todo-keywords-1)
12875 (push a org-todo-log-states)))))))
12877 (defun org-get-todo-sequence-head (kwd)
12878 "Return the head of the TODO sequence to which KWD belongs.
12879 If KWD is not set, check if there is a text property remembering the
12880 right sequence."
12881 (let (p)
12882 (cond
12883 ((not kwd)
12884 (or (get-text-property (point-at-bol) 'org-todo-head)
12885 (progn
12886 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12887 nil (point-at-eol)))
12888 (get-text-property p 'org-todo-head))))
12889 ((not (member kwd org-todo-keywords-1))
12890 (car org-todo-keywords-1))
12891 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12893 (defun org-fast-todo-selection ()
12894 "Fast TODO keyword selection with single keys.
12895 Returns the new TODO keyword, or nil if no state change should occur."
12896 (let* ((fulltable org-todo-key-alist)
12897 (done-keywords org-done-keywords) ;; needed for the faces.
12898 (maxlen (apply 'max (mapcar
12899 (lambda (x)
12900 (if (stringp (car x)) (string-width (car x)) 0))
12901 fulltable)))
12902 (expert nil)
12903 (fwidth (+ maxlen 3 1 3))
12904 (ncol (/ (- (window-width) 4) fwidth))
12905 tg cnt e c tbl
12906 groups ingroup)
12907 (save-excursion
12908 (save-window-excursion
12909 (if expert
12910 (set-buffer (get-buffer-create " *Org todo*"))
12911 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12912 (erase-buffer)
12913 (setq-local org-done-keywords done-keywords)
12914 (setq tbl fulltable cnt 0)
12915 (while (setq e (pop tbl))
12916 (cond
12917 ((equal e '(:startgroup))
12918 (push '() groups) (setq ingroup t)
12919 (unless (= cnt 0)
12920 (setq cnt 0)
12921 (insert "\n"))
12922 (insert "{ "))
12923 ((equal e '(:endgroup))
12924 (setq ingroup nil cnt 0)
12925 (insert "}\n"))
12926 ((equal e '(:newline))
12927 (unless (= cnt 0)
12928 (setq cnt 0)
12929 (insert "\n")
12930 (setq e (car tbl))
12931 (while (equal (car tbl) '(:newline))
12932 (insert "\n")
12933 (setq tbl (cdr tbl)))))
12935 (setq tg (car e) c (cdr e))
12936 (when ingroup (push tg (car groups)))
12937 (setq tg (org-add-props tg nil 'face
12938 (org-get-todo-face tg)))
12939 (when (and (= cnt 0) (not ingroup)) (insert " "))
12940 (insert "[" c "] " tg (make-string
12941 (- fwidth 4 (length tg)) ?\ ))
12942 (when (= (setq cnt (1+ cnt)) ncol)
12943 (insert "\n")
12944 (when ingroup (insert " "))
12945 (setq cnt 0)))))
12946 (insert "\n")
12947 (goto-char (point-min))
12948 (unless expert (org-fit-window-to-buffer))
12949 (message "[a-z..]:Set [SPC]:clear")
12950 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12951 (cond
12952 ((or (= c ?\C-g)
12953 (and (= c ?q) (not (rassoc c fulltable))))
12954 (setq quit-flag t))
12955 ((= c ?\ ) nil)
12956 ((setq e (rassoc c fulltable) tg (car e))
12958 (t (setq quit-flag t)))))))
12960 (defun org-entry-is-todo-p ()
12961 (member (org-get-todo-state) org-not-done-keywords))
12963 (defun org-entry-is-done-p ()
12964 (member (org-get-todo-state) org-done-keywords))
12966 (defun org-get-todo-state ()
12967 "Return the TODO keyword of the current subtree."
12968 (save-excursion
12969 (org-back-to-heading t)
12970 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12971 (match-end 2)
12972 (match-string 2))))
12974 (defun org-at-date-range-p (&optional inactive-ok)
12975 "Non-nil if point is inside a date range.
12977 When optional argument INACTIVE-OK is non-nil, also consider
12978 inactive time ranges.
12980 When this function returns a non-nil value, match data is set
12981 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12982 on INACTIVE-OK."
12983 (interactive)
12984 (save-excursion
12985 (catch 'exit
12986 (let ((pos (point)))
12987 (skip-chars-backward "^[<\r\n")
12988 (skip-chars-backward "<[")
12989 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12990 (>= (match-end 0) pos)
12991 (throw 'exit t))
12992 (skip-chars-backward "^<[\r\n")
12993 (skip-chars-backward "<[")
12994 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12995 (>= (match-end 0) pos)
12996 (throw 'exit t)))
12997 nil)))
12999 (defun org-get-repeat (&optional timestamp)
13000 "Check if there is a time-stamp with repeater in this entry.
13002 Return the repeater, as a string, or nil. Also return nil when
13003 this function is called before first heading.
13005 When optional argument TIMESTAMP is a string, extract the
13006 repeater from there instead."
13007 (save-match-data
13008 (cond (timestamp
13009 (and (string-match org-repeat-re timestamp)
13010 (match-string-no-properties 1 timestamp)))
13011 ((org-before-first-heading-p) nil)
13013 (save-excursion
13014 (org-back-to-heading t)
13015 (let ((end (org-entry-end-position)))
13016 (catch :repeat
13017 (while (re-search-forward org-repeat-re end t)
13018 (when (save-match-data (org-at-timestamp-p 'agenda))
13019 (throw :repeat (match-string-no-properties 1)))))))))))
13021 (defvar org-last-changed-timestamp)
13022 (defvar org-last-inserted-timestamp)
13023 (defvar org-log-post-message)
13024 (defvar org-log-note-purpose)
13025 (defvar org-log-note-how nil)
13026 (defvar org-log-note-extra)
13027 (defun org-auto-repeat-maybe (done-word)
13028 "Check if the current headline contains a repeated time-stamp.
13030 If yes, set TODO state back to what it was and change the base date
13031 of repeating deadline/scheduled time stamps to new date.
13033 This function is run automatically after each state change to a DONE state."
13034 (let* ((repeat (org-get-repeat))
13035 (aa (assoc org-last-state org-todo-kwd-alist))
13036 (interpret (nth 1 aa))
13037 (head (nth 2 aa))
13038 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13039 (msg "Entry repeats: ")
13040 (org-log-done nil)
13041 (org-todo-log-states nil)
13042 (end (copy-marker (org-entry-end-position))))
13043 (unwind-protect
13044 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13045 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13046 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13047 org-todo-repeat-to-state)))
13048 (org-todo (cond
13049 ((and to-state (member to-state org-todo-keywords-1))
13050 to-state)
13051 ((eq interpret 'type) org-last-state)
13052 (head)
13053 (t 'none))))
13054 (org-back-to-heading t)
13055 (org-add-planning-info nil nil 'closed)
13056 ;; When `org-log-repeat' is non-nil or entry contains
13057 ;; a clock, set LAST_REPEAT property.
13058 (when (or org-log-repeat
13059 (catch :clock
13060 (save-excursion
13061 (while (re-search-forward org-clock-line-re end t)
13062 (when (org-at-clock-log-p) (throw :clock t))))))
13063 (org-entry-put nil "LAST_REPEAT" (format-time-string
13064 (org-time-stamp-format t t)
13065 (current-time))))
13066 (when org-log-repeat
13067 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13068 (memq 'org-add-log-note post-command-hook))
13069 ;; We are already setup for some record.
13070 (when (eq org-log-repeat 'note)
13071 ;; Make sure we take a note, not only a time stamp.
13072 (setq org-log-note-how 'note))
13073 ;; Set up for taking a record.
13074 (org-add-log-setup 'state
13075 (or done-word (car org-done-keywords))
13076 org-last-state
13077 org-log-repeat)))
13078 (let ((planning-re (regexp-opt
13079 (list org-scheduled-string org-deadline-string))))
13080 (while (re-search-forward org-ts-regexp end t)
13081 (let* ((ts (match-string 0))
13082 (planning? (org-at-planning-p))
13083 (type (if (not planning?) "Plain:"
13084 (save-excursion
13085 (re-search-backward
13086 planning-re (line-beginning-position) t)
13087 (match-string 0)))))
13088 (cond
13089 ;; Ignore fake time-stamps (e.g., within comments).
13090 ((not (org-at-timestamp-p 'agenda)))
13091 ;; Time-stamps without a repeater are usually
13092 ;; skipped. However, a SCHEDULED time-stamp without
13093 ;; one is removed, as they are no longer relevant.
13094 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13095 ts))
13096 (when (equal type org-scheduled-string)
13097 (org-remove-timestamp-with-keyword type)))
13099 (let ((n (string-to-number (match-string 2 ts)))
13100 (what (match-string 3 ts)))
13101 (when (equal what "w") (setq n (* n 7) what "d"))
13102 (when (and (equal what "h")
13103 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13104 ts)))
13105 (user-error
13106 "Cannot repeat in Repeat in %d hour(s) because no hour \
13107 has been set"
13109 ;; Preparation, see if we need to modify the start
13110 ;; date for the change.
13111 (when (match-end 1)
13112 (let ((time (save-match-data
13113 (org-time-string-to-time ts))))
13114 (cond
13115 ((equal (match-string 1 ts) ".")
13116 ;; Shift starting date to today
13117 (org-timestamp-change
13118 (- (org-today) (time-to-days time))
13119 'day))
13120 ((equal (match-string 1 ts) "+")
13121 (let ((nshiftmax 10)
13122 (nshift 0))
13123 (while (or (= nshift 0)
13124 (not (time-less-p (current-time) time)))
13125 (when (= (cl-incf nshift) nshiftmax)
13126 (or (y-or-n-p
13127 (format "%d repeater intervals were not \
13128 enough to shift date past today. Continue? "
13129 nshift))
13130 (user-error "Abort")))
13131 (org-timestamp-change n (cdr (assoc what whata)))
13132 (org-in-regexp org-ts-regexp3)
13133 (setq ts (match-string 1))
13134 (setq time
13135 (save-match-data
13136 (org-time-string-to-time ts)))))
13137 (org-timestamp-change (- n) (cdr (assoc what whata)))
13138 ;; Rematch, so that we have everything in place
13139 ;; for the real shift.
13140 (org-in-regexp org-ts-regexp3)
13141 (setq ts (match-string 1))
13142 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13143 ts)))))
13144 (save-excursion
13145 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13146 (setq msg
13147 (concat
13148 msg type " " org-last-changed-timestamp " "))))))))
13149 (setq org-log-post-message msg)
13150 (message "%s" msg))
13151 (set-marker end nil))))
13153 (defun org-show-todo-tree (arg)
13154 "Make a compact tree which shows all headlines marked with TODO.
13155 The tree will show the lines where the regexp matches, and all higher
13156 headlines above the match.
13157 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13158 With a numeric prefix N, construct a sparse tree for the Nth element
13159 of `org-todo-keywords-1'."
13160 (interactive "P")
13161 (let ((case-fold-search nil)
13162 (kwd-re
13163 (cond ((null arg) org-not-done-regexp)
13164 ((equal arg '(4))
13165 (let ((kwd
13166 (completing-read "Keyword (or KWD1|KWD2|...): "
13167 (mapcar #'list org-todo-keywords-1))))
13168 (concat "\\("
13169 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13170 "\\)\\>")))
13171 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13172 (regexp-quote (nth (1- (prefix-numeric-value arg))
13173 org-todo-keywords-1)))
13174 (t (user-error "Invalid prefix argument: %s" arg)))))
13175 (message "%d TODO entries found"
13176 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13178 (defun org--deadline-or-schedule (arg type time)
13179 "Insert DEADLINE or SCHEDULE information in current entry.
13180 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13181 `org-schedule' for information about ARG and TIME arguments."
13182 (let* ((deadline? (eq type 'deadline))
13183 (keyword (if deadline? org-deadline-string org-scheduled-string))
13184 (log (if deadline? org-log-redeadline org-log-reschedule))
13185 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13186 (old-date-time (and old-date (org-time-string-to-time old-date)))
13187 ;; Save repeater cookie from either TIME or current scheduled
13188 ;; time stamp. We are going to insert it back at the end of
13189 ;; the process.
13190 (repeater (or (and (org-string-nw-p time)
13191 ;; We use `org-repeat-re' because we need
13192 ;; to tell the difference between a real
13193 ;; repeater and a time delta, e.g. "+2d".
13194 (string-match org-repeat-re time)
13195 (match-string 1 time))
13196 (and (org-string-nw-p old-date)
13197 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13198 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13199 old-date)
13200 (match-string 1 old-date)))))
13201 (pcase arg
13202 (`(4)
13203 (when (and old-date log)
13204 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13205 nil old-date log))
13206 (org-remove-timestamp-with-keyword keyword)
13207 (message (if deadline? "Item no longer has a deadline."
13208 "Item is no longer scheduled.")))
13209 (`(16)
13210 (save-excursion
13211 (org-back-to-heading t)
13212 (let ((regexp (if deadline? org-deadline-time-regexp
13213 org-scheduled-time-regexp)))
13214 (if (not (re-search-forward regexp (line-end-position 2) t))
13215 (user-error (if deadline? "No deadline information to update"
13216 "No scheduled information to update"))
13217 (let* ((rpl0 (match-string 1))
13218 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13219 (msg (if deadline? "Warn starting from" "Delay until")))
13220 (replace-match
13221 (concat keyword
13222 " <" rpl
13223 (format " -%dd"
13224 (abs (- (time-to-days
13225 (save-match-data
13226 (org-read-date
13227 nil t nil msg old-date-time)))
13228 (time-to-days old-date-time))))
13229 ">") t t))))))
13231 (org-add-planning-info type time 'closed)
13232 (when (and old-date
13234 (not (equal old-date org-last-inserted-timestamp)))
13235 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13236 org-last-inserted-timestamp
13237 old-date
13238 log))
13239 (when repeater
13240 (save-excursion
13241 (org-back-to-heading t)
13242 (when (re-search-forward
13243 (concat keyword " " org-last-inserted-timestamp)
13244 (line-end-position 2)
13246 (goto-char (1- (match-end 0)))
13247 (insert " " repeater)
13248 (setq org-last-inserted-timestamp
13249 (concat (substring org-last-inserted-timestamp 0 -1)
13250 " " repeater
13251 (substring org-last-inserted-timestamp -1))))))
13252 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13253 org-last-inserted-timestamp)))))
13255 (defun org-deadline (arg &optional time)
13256 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13257 With one universal prefix argument, remove any deadline from the item.
13258 With two universal prefix arguments, prompt for a warning delay.
13259 With argument TIME, set the deadline at the corresponding date. TIME
13260 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13261 (interactive "P")
13262 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13263 (org-map-entries
13264 (lambda () (org--deadline-or-schedule arg 'deadline time))
13266 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13267 'region-start-level
13268 'region)
13269 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13270 (org--deadline-or-schedule arg 'deadline time)))
13272 (defun org-schedule (arg &optional time)
13273 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13274 With one universal prefix argument, remove any scheduling date from the item.
13275 With two universal prefix arguments, prompt for a delay cookie.
13276 With argument TIME, scheduled at the corresponding date. TIME can
13277 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13278 (interactive "P")
13279 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13280 (org-map-entries
13281 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13283 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13284 'region-start-level
13285 'region)
13286 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13287 (org--deadline-or-schedule arg 'scheduled time)))
13289 (defun org-get-scheduled-time (pom &optional inherit)
13290 "Get the scheduled time as a time tuple, of a format suitable
13291 for calling org-schedule with, or if there is no scheduling,
13292 returns nil."
13293 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13294 (when time
13295 (apply 'encode-time (org-parse-time-string time)))))
13297 (defun org-get-deadline-time (pom &optional inherit)
13298 "Get the deadline as a time tuple, of a format suitable for
13299 calling org-deadline with, or if there is no scheduling, returns
13300 nil."
13301 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13302 (when time
13303 (apply 'encode-time (org-parse-time-string time)))))
13305 (defun org-remove-timestamp-with-keyword (keyword)
13306 "Remove all time stamps with KEYWORD in the current entry."
13307 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13308 beg)
13309 (save-excursion
13310 (org-back-to-heading t)
13311 (setq beg (point))
13312 (outline-next-heading)
13313 (while (re-search-backward re beg t)
13314 (replace-match "")
13315 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13316 (equal (char-before) ?\ ))
13317 (backward-delete-char 1)
13318 (when (string-match "^[ \t]*$" (buffer-substring
13319 (point-at-bol) (point-at-eol)))
13320 (delete-region (point-at-bol)
13321 (min (point-max) (1+ (point-at-eol))))))))))
13323 (defvar org-time-was-given) ; dynamically scoped parameter
13324 (defvar org-end-time-was-given) ; dynamically scoped parameter
13326 (defun org-at-planning-p ()
13327 "Non-nil when point is on a planning info line."
13328 ;; This is as accurate and faster than `org-element-at-point' since
13329 ;; planning info location is fixed in the section.
13330 (org-with-wide-buffer
13331 (beginning-of-line)
13332 (and (looking-at-p org-planning-line-re)
13333 (eq (point)
13334 (ignore-errors
13335 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13336 (org-back-to-heading t)
13337 (org-with-limited-levels (org-back-to-heading t)))
13338 (line-beginning-position 2))))))
13340 (defun org-add-planning-info (what &optional time &rest remove)
13341 "Insert new timestamp with keyword in the planning line.
13342 WHAT indicates what kind of time stamp to add. It is a symbol
13343 among `closed', `deadline', `scheduled' and nil. TIME indicates
13344 the time to use. If none is given, the user is prompted for
13345 a date. REMOVE indicates what kind of entries to remove. An old
13346 WHAT entry will also be removed."
13347 (let (org-time-was-given org-end-time-was-given default-time default-input)
13348 (catch 'exit
13349 (when (and (memq what '(scheduled deadline))
13350 (or (not time)
13351 (and (stringp time)
13352 (string-match "^[-+]+[0-9]" time))))
13353 ;; Try to get a default date/time from existing timestamp
13354 (save-excursion
13355 (org-back-to-heading t)
13356 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13357 (when (re-search-forward (if (eq what 'scheduled)
13358 org-scheduled-time-regexp
13359 org-deadline-time-regexp)
13360 end t)
13361 (setq ts (match-string 1)
13362 default-time (apply 'encode-time (org-parse-time-string ts))
13363 default-input (and ts (org-get-compact-tod ts)))))))
13364 (when what
13365 (setq time
13366 (if (stringp time)
13367 ;; This is a string (relative or absolute), set
13368 ;; proper date.
13369 (apply #'encode-time
13370 (org-read-date-analyze
13371 time default-time (decode-time default-time)))
13372 ;; If necessary, get the time from the user
13373 (or time (org-read-date nil 'to-time nil nil
13374 default-time default-input)))))
13376 (org-with-wide-buffer
13377 (org-back-to-heading t)
13378 (forward-line)
13379 (unless (bolp) (insert "\n"))
13380 (cond ((looking-at-p org-planning-line-re)
13381 ;; Move to current indentation.
13382 (skip-chars-forward " \t")
13383 ;; Check if we have to remove something.
13384 (dolist (type (if what (cons what remove) remove))
13385 (save-excursion
13386 (when (re-search-forward
13387 (cl-case type
13388 (closed org-closed-time-regexp)
13389 (deadline org-deadline-time-regexp)
13390 (scheduled org-scheduled-time-regexp)
13391 (otherwise
13392 (error "Invalid planning type: %s" type)))
13393 (line-end-position) t)
13394 ;; Delete until next keyword or end of line.
13395 (delete-region
13396 (match-beginning 0)
13397 (if (re-search-forward org-keyword-time-not-clock-regexp
13398 (line-end-position)
13400 (match-beginning 0)
13401 (line-end-position))))))
13402 ;; If there is nothing more to add and no more keyword
13403 ;; is left, remove the line completely.
13404 (if (and (looking-at-p "[ \t]*$") (not what))
13405 (delete-region (line-beginning-position)
13406 (line-beginning-position 2))
13407 ;; If we removed last keyword, do not leave trailing
13408 ;; white space at the end of line.
13409 (let ((p (point)))
13410 (save-excursion
13411 (end-of-line)
13412 (unless (= (skip-chars-backward " \t" p) 0)
13413 (delete-region (point) (line-end-position)))))))
13414 ((not what) (throw 'exit nil)) ; Nothing to do.
13415 (t (insert-before-markers "\n")
13416 (backward-char 1)
13417 (when org-adapt-indentation
13418 (indent-to-column (1+ (org-outline-level))))))
13419 (when what
13420 ;; Insert planning keyword.
13421 (insert (cl-case what
13422 (closed org-closed-string)
13423 (deadline org-deadline-string)
13424 (scheduled org-scheduled-string)
13425 (otherwise (error "Invalid planning type: %s" what)))
13426 " ")
13427 ;; Insert associated timestamp.
13428 (let ((ts (org-insert-time-stamp
13429 time
13430 (or org-time-was-given
13431 (and (eq what 'closed) org-log-done-with-time))
13432 (eq what 'closed)
13433 nil nil (list org-end-time-was-given))))
13434 (unless (eolp) (insert " "))
13435 ts))))))
13437 (defvar org-log-note-marker (make-marker)
13438 "Marker pointing at the entry where the note is to be inserted.")
13439 (defvar org-log-note-purpose nil)
13440 (defvar org-log-note-state nil)
13441 (defvar org-log-note-previous-state nil)
13442 (defvar org-log-note-extra nil)
13443 (defvar org-log-note-window-configuration nil)
13444 (defvar org-log-note-return-to (make-marker))
13445 (defvar org-log-note-effective-time nil
13446 "Remembered current time so that dynamically scoped
13447 `org-extend-today-until' affects timestamps in state change log")
13449 (defvar org-log-post-message nil
13450 "Message to be displayed after a log note has been stored.
13451 The auto-repeater uses this.")
13453 (defun org-add-note ()
13454 "Add a note to the current entry.
13455 This is done in the same way as adding a state change note."
13456 (interactive)
13457 (org-add-log-setup 'note))
13459 (defun org-log-beginning (&optional create)
13460 "Return expected start of log notes in current entry.
13461 When optional argument CREATE is non-nil, the function creates
13462 a drawer to store notes, if necessary. Returned position ignores
13463 narrowing."
13464 (org-with-wide-buffer
13465 (let ((drawer (org-log-into-drawer)))
13466 (cond
13467 (drawer
13468 (org-end-of-meta-data)
13469 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13470 (end (if (org-at-heading-p) (point)
13471 (save-excursion (outline-next-heading) (point))))
13472 (case-fold-search t))
13473 (catch 'exit
13474 ;; Try to find existing drawer.
13475 (while (re-search-forward regexp end t)
13476 (let ((element (org-element-at-point)))
13477 (when (eq (org-element-type element) 'drawer)
13478 (let ((cend (org-element-property :contents-end element)))
13479 (when (and (not org-log-states-order-reversed) cend)
13480 (goto-char cend)))
13481 (throw 'exit nil))))
13482 ;; No drawer found. Create one, if permitted.
13483 (when create
13484 (unless (bolp) (insert "\n"))
13485 (let ((beg (point)))
13486 (insert ":" drawer ":\n:END:\n")
13487 (org-indent-region beg (point)))
13488 (end-of-line -1)))))
13490 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13491 (skip-chars-forward " \t\n")
13492 (beginning-of-line)
13493 (unless org-log-states-order-reversed
13494 (org-skip-over-state-notes)
13495 (skip-chars-backward " \t\n")
13496 (forward-line)))))
13497 (if (bolp) (point) (line-beginning-position 2))))
13499 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13500 "Set up the post command hook to take a note.
13501 If this is about to TODO state change, the new state is expected in STATE.
13502 HOW is an indicator what kind of note should be created.
13503 EXTRA is additional text that will be inserted into the notes buffer."
13504 (move-marker org-log-note-marker (point))
13505 (setq org-log-note-purpose purpose
13506 org-log-note-state state
13507 org-log-note-previous-state prev-state
13508 org-log-note-how how
13509 org-log-note-extra extra
13510 org-log-note-effective-time (org-current-effective-time))
13511 (add-hook 'post-command-hook 'org-add-log-note 'append))
13513 (defun org-skip-over-state-notes ()
13514 "Skip past the list of State notes in an entry."
13515 (when (ignore-errors (goto-char (org-in-item-p)))
13516 (let* ((struct (org-list-struct))
13517 (prevs (org-list-prevs-alist struct))
13518 (regexp
13519 (concat "[ \t]*- +"
13520 (replace-regexp-in-string
13521 " +" " +"
13522 (org-replace-escapes
13523 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13524 `(("%d" . ,org-ts-regexp-inactive)
13525 ("%D" . ,org-ts-regexp)
13526 ("%s" . "\"\\S-+\"")
13527 ("%S" . "\"\\S-+\"")
13528 ("%t" . ,org-ts-regexp-inactive)
13529 ("%T" . ,org-ts-regexp)
13530 ("%u" . ".*?")
13531 ("%U" . ".*?")))))))
13532 (while (looking-at-p regexp)
13533 (goto-char (or (org-list-get-next-item (point) struct prevs)
13534 (org-list-get-item-end (point) struct)))))))
13536 (defun org-add-log-note (&optional _purpose)
13537 "Pop up a window for taking a note, and add this note later."
13538 (remove-hook 'post-command-hook 'org-add-log-note)
13539 (setq org-log-note-window-configuration (current-window-configuration))
13540 (delete-other-windows)
13541 (move-marker org-log-note-return-to (point))
13542 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13543 (goto-char org-log-note-marker)
13544 (org-switch-to-buffer-other-window "*Org Note*")
13545 (erase-buffer)
13546 (if (memq org-log-note-how '(time state))
13547 (org-store-log-note)
13548 (let ((org-inhibit-startup t)) (org-mode))
13549 (insert (format "# Insert note for %s.
13550 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13551 (cond
13552 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13553 ((eq org-log-note-purpose 'done) "closed todo item")
13554 ((eq org-log-note-purpose 'state)
13555 (format "state change from \"%s\" to \"%s\""
13556 (or org-log-note-previous-state "")
13557 (or org-log-note-state "")))
13558 ((eq org-log-note-purpose 'reschedule)
13559 "rescheduling")
13560 ((eq org-log-note-purpose 'delschedule)
13561 "no longer scheduled")
13562 ((eq org-log-note-purpose 'redeadline)
13563 "changing deadline")
13564 ((eq org-log-note-purpose 'deldeadline)
13565 "removing deadline")
13566 ((eq org-log-note-purpose 'refile)
13567 "refiling")
13568 ((eq org-log-note-purpose 'note)
13569 "this entry")
13570 (t (error "This should not happen")))))
13571 (when org-log-note-extra (insert org-log-note-extra))
13572 (setq-local org-finish-function 'org-store-log-note)
13573 (run-hooks 'org-log-buffer-setup-hook)))
13575 (defvar org-note-abort nil) ; dynamically scoped
13576 (defun org-store-log-note ()
13577 "Finish taking a log note, and insert it to where it belongs."
13578 (let ((txt (prog1 (buffer-string)
13579 (kill-buffer)))
13580 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13581 lines)
13582 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13583 (setq txt (replace-match "" t t txt)))
13584 (when (string-match "\\s-+\\'" txt)
13585 (setq txt (replace-match "" t t txt)))
13586 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13587 (when (org-string-nw-p note)
13588 (setq note
13589 (org-replace-escapes
13590 note
13591 (list (cons "%u" (user-login-name))
13592 (cons "%U" user-full-name)
13593 (cons "%t" (format-time-string
13594 (org-time-stamp-format 'long 'inactive)
13595 org-log-note-effective-time))
13596 (cons "%T" (format-time-string
13597 (org-time-stamp-format 'long nil)
13598 org-log-note-effective-time))
13599 (cons "%d" (format-time-string
13600 (org-time-stamp-format nil 'inactive)
13601 org-log-note-effective-time))
13602 (cons "%D" (format-time-string
13603 (org-time-stamp-format nil nil)
13604 org-log-note-effective-time))
13605 (cons "%s" (cond
13606 ((not org-log-note-state) "")
13607 ((string-match-p org-ts-regexp
13608 org-log-note-state)
13609 (format "\"[%s]\""
13610 (substring org-log-note-state 1 -1)))
13611 (t (format "\"%s\"" org-log-note-state))))
13612 (cons "%S"
13613 (cond
13614 ((not org-log-note-previous-state) "")
13615 ((string-match-p org-ts-regexp
13616 org-log-note-previous-state)
13617 (format "\"[%s]\""
13618 (substring
13619 org-log-note-previous-state 1 -1)))
13620 (t (format "\"%s\""
13621 org-log-note-previous-state)))))))
13622 (when lines (setq note (concat note " \\\\")))
13623 (push note lines))
13624 (when (and lines (not org-note-abort))
13625 (with-current-buffer (marker-buffer org-log-note-marker)
13626 (org-with-wide-buffer
13627 ;; Find location for the new note.
13628 (goto-char org-log-note-marker)
13629 (set-marker org-log-note-marker nil)
13630 ;; Note associated to a clock is to be located right after
13631 ;; the clock. Do not move point.
13632 (unless (eq org-log-note-purpose 'clock-out)
13633 (goto-char (org-log-beginning t)))
13634 ;; Make sure point is at the beginning of an empty line.
13635 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13636 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13637 ;; In an existing list, add a new item at the top level.
13638 ;; Otherwise, indent line like a regular one.
13639 (let ((itemp (org-in-item-p)))
13640 (if itemp
13641 (indent-line-to
13642 (let ((struct (save-excursion
13643 (goto-char itemp) (org-list-struct))))
13644 (org-list-get-ind (org-list-get-top-point struct) struct)))
13645 (org-indent-line)))
13646 (insert (org-list-bullet-string "-") (pop lines))
13647 (let ((ind (org-list-item-body-column (line-beginning-position))))
13648 (dolist (line lines)
13649 (insert "\n")
13650 (indent-line-to ind)
13651 (insert line)))
13652 (message "Note stored")
13653 (org-back-to-heading t)
13654 (org-cycle-hide-drawers 'children))
13655 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13656 ;; from within `org-add-log-note' because `buffer-undo-list'
13657 ;; is then modified outside of `org-with-remote-undo'.
13658 (when (eq this-command 'org-agenda-todo)
13659 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13660 ;; Don't add undo information when called from `org-agenda-todo'.
13661 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13662 (set-window-configuration org-log-note-window-configuration)
13663 (with-current-buffer (marker-buffer org-log-note-return-to)
13664 (goto-char org-log-note-return-to))
13665 (move-marker org-log-note-return-to nil)
13666 (when org-log-post-message (message "%s" org-log-post-message))))
13668 (defun org-remove-empty-drawer-at (pos)
13669 "Remove an empty drawer at position POS.
13670 POS may also be a marker."
13671 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13672 (org-with-wide-buffer
13673 (goto-char pos)
13674 (let ((drawer (org-element-at-point)))
13675 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13676 (not (org-element-property :contents-begin drawer)))
13677 (delete-region (org-element-property :begin drawer)
13678 (progn (goto-char (org-element-property :end drawer))
13679 (skip-chars-backward " \r\t\n")
13680 (forward-line)
13681 (point))))))))
13683 (defvar org-ts-type nil)
13684 (defun org-sparse-tree (&optional arg type)
13685 "Create a sparse tree, prompt for the details.
13686 This command can create sparse trees. You first need to select the type
13687 of match used to create the tree:
13689 t Show all TODO entries.
13690 T Show entries with a specific TODO keyword.
13691 m Show entries selected by a tags/property match.
13692 p Enter a property name and its value (both with completion on existing
13693 names/values) and show entries with that property.
13694 r Show entries matching a regular expression (`/' can be used as well).
13695 b Show deadlines and scheduled items before a date.
13696 a Show deadlines and scheduled items after a date.
13697 d Show deadlines due within `org-deadline-warning-days'.
13698 D Show deadlines and scheduled items between a date range."
13699 (interactive "P")
13700 (setq type (or type org-sparse-tree-default-date-type))
13701 (setq org-ts-type type)
13702 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13703 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13704 \[c]ycle through date types: %s"
13705 (cl-case type
13706 (all "all timestamps")
13707 (scheduled "only scheduled")
13708 (deadline "only deadline")
13709 (active "only active timestamps")
13710 (inactive "only inactive timestamps")
13711 (closed "with a closed time-stamp")
13712 (otherwise "scheduled/deadline")))
13713 (let ((answer (read-char-exclusive)))
13714 (cl-case answer
13716 (org-sparse-tree
13718 (cadr
13719 (memq type '(nil all scheduled deadline active inactive closed)))))
13720 (?d (call-interactively 'org-check-deadlines))
13721 (?b (call-interactively 'org-check-before-date))
13722 (?a (call-interactively 'org-check-after-date))
13723 (?D (call-interactively 'org-check-dates-range))
13724 (?t (call-interactively 'org-show-todo-tree))
13725 (?T (org-show-todo-tree '(4)))
13726 (?m (call-interactively 'org-match-sparse-tree))
13727 ((?p ?P)
13728 (let* ((kwd (completing-read
13729 "Property: " (mapcar #'list (org-buffer-property-keys))))
13730 (value (completing-read
13731 "Value: " (mapcar #'list (org-property-values kwd)))))
13732 (unless (string-match "\\`{.*}\\'" value)
13733 (setq value (concat "\"" value "\"")))
13734 (org-match-sparse-tree arg (concat kwd "=" value))))
13735 ((?r ?R ?/) (call-interactively 'org-occur))
13736 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13738 (defvar-local org-occur-highlights nil
13739 "List of overlays used for occur matches.")
13740 (defvar-local org-occur-parameters nil
13741 "Parameters of the active org-occur calls.
13742 This is a list, each call to org-occur pushes as cons cell,
13743 containing the regular expression and the callback, onto the list.
13744 The list can contain several entries if `org-occur' has been called
13745 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13746 will only contain one set of parameters. When the highlights are
13747 removed (for example with `C-c C-c', or with the next edit (depending
13748 on `org-remove-highlights-with-change'), this variable is emptied
13749 as well.")
13751 (defun org-occur (regexp &optional keep-previous callback)
13752 "Make a compact tree which shows all matches of REGEXP.
13754 The tree will show the lines where the regexp matches, and any other context
13755 defined in `org-show-context-detail', which see.
13757 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13758 done by a previous call to `org-occur' will be kept, to allow stacking of
13759 calls to this command.
13761 Optional argument CALLBACK can be a function of no argument. In this case,
13762 it is called with point at the end of the match, match data being set
13763 accordingly. Current match is shown only if the return value is non-nil.
13764 The function must neither move point nor alter narrowing."
13765 (interactive "sRegexp: \nP")
13766 (when (equal regexp "")
13767 (user-error "Regexp cannot be empty"))
13768 (unless keep-previous
13769 (org-remove-occur-highlights nil nil t))
13770 (push (cons regexp callback) org-occur-parameters)
13771 (let ((cnt 0))
13772 (save-excursion
13773 (goto-char (point-min))
13774 (when (or (not keep-previous) ; do not want to keep
13775 (not org-occur-highlights)) ; no previous matches
13776 ;; hide everything
13777 (org-overview))
13778 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13779 (isearch-no-upper-case-p regexp t)
13780 org-occur-case-fold-search)))
13781 (while (re-search-forward regexp nil t)
13782 (when (or (not callback)
13783 (save-match-data (funcall callback)))
13784 (setq cnt (1+ cnt))
13785 (when org-highlight-sparse-tree-matches
13786 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13787 (org-show-context 'occur-tree)))))
13788 (when org-remove-highlights-with-change
13789 (add-hook 'before-change-functions 'org-remove-occur-highlights
13790 nil 'local))
13791 (unless org-sparse-tree-open-archived-trees
13792 (org-hide-archived-subtrees (point-min) (point-max)))
13793 (run-hooks 'org-occur-hook)
13794 (when (called-interactively-p 'interactive)
13795 (message "%d match(es) for regexp %s" cnt regexp))
13796 cnt))
13798 (defun org-occur-next-match (&optional n _reset)
13799 "Function for `next-error-function' to find sparse tree matches.
13800 N is the number of matches to move, when negative move backwards.
13801 This function always goes back to the starting point when no
13802 match is found."
13803 (let* ((limit (if (< n 0) (point-min) (point-max)))
13804 (search-func (if (< n 0)
13805 'previous-single-char-property-change
13806 'next-single-char-property-change))
13807 (n (abs n))
13808 (pos (point))
13810 (catch 'exit
13811 (while (setq p1 (funcall search-func (point) 'org-type))
13812 (when (equal p1 limit)
13813 (goto-char pos)
13814 (user-error "No more matches"))
13815 (when (equal (get-char-property p1 'org-type) 'org-occur)
13816 (setq n (1- n))
13817 (when (= n 0)
13818 (goto-char p1)
13819 (throw 'exit (point))))
13820 (goto-char p1))
13821 (goto-char p1)
13822 (user-error "No more matches"))))
13824 (defun org-show-context (&optional key)
13825 "Make sure point and context are visible.
13826 Optional argument KEY, when non-nil, is a symbol. See
13827 `org-show-context-detail' for allowed values and how much is to
13828 be shown."
13829 (org-show-set-visibility
13830 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13831 ((cdr (assq key org-show-context-detail)))
13832 (t (cdr (assq 'default org-show-context-detail))))))
13834 (defun org-show-set-visibility (detail)
13835 "Set visibility around point according to DETAIL.
13836 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13837 `tree', `canonical' or t. See `org-show-context-detail' for more
13838 information."
13839 ;; Show current heading and possibly its entry, following headline
13840 ;; or all children.
13841 (if (and (org-at-heading-p) (not (eq detail 'local)))
13842 (org-flag-heading nil)
13843 (org-show-entry)
13844 ;; If point is hidden within a drawer or a block, make sure to
13845 ;; expose it.
13846 (dolist (o (overlays-at (point)))
13847 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13848 (delete-overlay o)))
13849 (unless (org-before-first-heading-p)
13850 (org-with-limited-levels
13851 (cl-case detail
13852 ((tree canonical t) (org-show-children))
13853 ((nil minimal ancestors))
13854 (t (save-excursion
13855 (outline-next-heading)
13856 (org-flag-heading nil)))))))
13857 ;; Show all siblings.
13858 (when (eq detail 'lineage) (org-show-siblings))
13859 ;; Show ancestors, possibly with their children.
13860 (when (memq detail '(ancestors lineage tree canonical t))
13861 (save-excursion
13862 (while (org-up-heading-safe)
13863 (org-flag-heading nil)
13864 (when (memq detail '(canonical t)) (org-show-entry))
13865 (when (memq detail '(tree canonical t)) (org-show-children))))))
13867 (defvar org-reveal-start-hook nil
13868 "Hook run before revealing a location.")
13870 (defun org-reveal (&optional siblings)
13871 "Show current entry, hierarchy above it, and the following headline.
13873 This can be used to show a consistent set of context around
13874 locations exposed with `org-show-context'.
13876 With optional argument SIBLINGS, on each level of the hierarchy all
13877 siblings are shown. This repairs the tree structure to what it would
13878 look like when opened with hierarchical calls to `org-cycle'.
13880 With a \\[universal-argument] \\[universal-argument] prefix, \
13881 go to the parent and show the entire tree."
13882 (interactive "P")
13883 (run-hooks 'org-reveal-start-hook)
13884 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13885 ((equal siblings '(16))
13886 (save-excursion
13887 (when (org-up-heading-safe)
13888 (org-show-subtree)
13889 (run-hook-with-args 'org-cycle-hook 'subtree))))
13890 (t (org-show-set-visibility 'lineage))))
13892 (defun org-highlight-new-match (beg end)
13893 "Highlight from BEG to END and mark the highlight is an occur headline."
13894 (let ((ov (make-overlay beg end)))
13895 (overlay-put ov 'face 'secondary-selection)
13896 (overlay-put ov 'org-type 'org-occur)
13897 (push ov org-occur-highlights)))
13899 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13900 "Remove the occur highlights from the buffer.
13901 BEG and END are ignored. If NOREMOVE is nil, remove this function
13902 from the `before-change-functions' in the current buffer."
13903 (interactive)
13904 (unless org-inhibit-highlight-removal
13905 (mapc #'delete-overlay org-occur-highlights)
13906 (setq org-occur-highlights nil)
13907 (setq org-occur-parameters nil)
13908 (unless noremove
13909 (remove-hook 'before-change-functions
13910 'org-remove-occur-highlights 'local))))
13912 ;;;; Priorities
13914 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13915 "Regular expression matching the priority indicator.")
13917 (defvar org-remove-priority-next-time nil)
13919 (defun org-priority-up ()
13920 "Increase the priority of the current item."
13921 (interactive)
13922 (org-priority 'up))
13924 (defun org-priority-down ()
13925 "Decrease the priority of the current item."
13926 (interactive)
13927 (org-priority 'down))
13929 (defun org-priority (&optional action _show)
13930 "Change the priority of an item.
13931 ACTION can be `set', `up', `down', or a character."
13932 (interactive "P")
13933 (if (equal action '(4))
13934 (org-show-priority)
13935 (unless org-enable-priority-commands
13936 (user-error "Priority commands are disabled"))
13937 (setq action (or action 'set))
13938 (let (current new news have remove)
13939 (save-excursion
13940 (org-back-to-heading t)
13941 (when (looking-at org-priority-regexp)
13942 (setq current (string-to-char (match-string 2))
13943 have t))
13944 (cond
13945 ((eq action 'remove)
13946 (setq remove t new ?\ ))
13947 ((or (eq action 'set)
13948 (integerp action))
13949 (if (not (eq action 'set))
13950 (setq new action)
13951 (message "Priority %c-%c, SPC to remove: "
13952 org-highest-priority org-lowest-priority)
13953 (save-match-data
13954 (setq new (read-char-exclusive))))
13955 (when (and (= (upcase org-highest-priority) org-highest-priority)
13956 (= (upcase org-lowest-priority) org-lowest-priority))
13957 (setq new (upcase new)))
13958 (cond ((equal new ?\ ) (setq remove t))
13959 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13960 (user-error "Priority must be between `%c' and `%c'"
13961 org-highest-priority org-lowest-priority))))
13962 ((eq action 'up)
13963 (setq new (if have
13964 (1- current) ; normal cycling
13965 ;; last priority was empty
13966 (if (eq last-command this-command)
13967 org-lowest-priority ; wrap around empty to lowest
13968 ;; default
13969 (if org-priority-start-cycle-with-default
13970 org-default-priority
13971 (1- org-default-priority))))))
13972 ((eq action 'down)
13973 (setq new (if have
13974 (1+ current) ; normal cycling
13975 ;; last priority was empty
13976 (if (eq last-command this-command)
13977 org-highest-priority ; wrap around empty to highest
13978 ;; default
13979 (if org-priority-start-cycle-with-default
13980 org-default-priority
13981 (1+ org-default-priority))))))
13982 (t (user-error "Invalid action")))
13983 (when (or (< (upcase new) org-highest-priority)
13984 (> (upcase new) org-lowest-priority))
13985 (if (and (memq action '(up down))
13986 (not have) (not (eq last-command this-command)))
13987 ;; `new' is from default priority
13988 (error
13989 "The default can not be set, see `org-default-priority' why")
13990 ;; normal cycling: `new' is beyond highest/lowest priority
13991 ;; and is wrapped around to the empty priority
13992 (setq remove t)))
13993 (setq news (format "%c" new))
13994 (if have
13995 (if remove
13996 (replace-match "" t t nil 1)
13997 (replace-match news t t nil 2))
13998 (if remove
13999 (user-error "No priority cookie found in line")
14000 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14001 (if (match-end 2)
14002 (progn
14003 (goto-char (match-end 2))
14004 (insert " [#" news "]"))
14005 (goto-char (match-beginning 3))
14006 (insert "[#" news "] "))))
14007 (org-set-tags nil 'align))
14008 (if remove
14009 (message "Priority removed")
14010 (message "Priority of current item set to %s" news)))))
14012 (defun org-show-priority ()
14013 "Show the priority of the current item.
14014 This priority is composed of the main priority given with the [#A] cookies,
14015 and by additional input from the age of a schedules or deadline entry."
14016 (interactive)
14017 (let ((pri (if (eq major-mode 'org-agenda-mode)
14018 (org-get-at-bol 'priority)
14019 (save-excursion
14020 (save-match-data
14021 (beginning-of-line)
14022 (and (looking-at org-heading-regexp)
14023 (org-get-priority (match-string 0))))))))
14024 (message "Priority is %d" (if pri pri -1000))))
14026 (defun org-get-priority (s)
14027 "Find priority cookie and return priority."
14028 (save-match-data
14029 (if (functionp org-get-priority-function)
14030 (funcall org-get-priority-function)
14031 (if (not (string-match org-priority-regexp s))
14032 (* 1000 (- org-lowest-priority org-default-priority))
14033 (* 1000 (- org-lowest-priority
14034 (string-to-char (match-string 2 s))))))))
14036 ;;;; Tags
14038 (defvar org-agenda-archives-mode)
14039 (defvar org-map-continue-from nil
14040 "Position from where mapping should continue.
14041 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14043 (defvar org-scanner-tags nil
14044 "The current tag list while the tags scanner is running.")
14046 (defvar org-trust-scanner-tags nil
14047 "Should `org-get-tags-at' use the tags for the scanner.
14048 This is for internal dynamical scoping only.
14049 When this is non-nil, the function `org-get-tags-at' will return the value
14050 of `org-scanner-tags' instead of building the list by itself. This
14051 can lead to large speed-ups when the tags scanner is used in a file with
14052 many entries, and when the list of tags is retrieved, for example to
14053 obtain a list of properties. Building the tags list for each entry in such
14054 a file becomes an N^2 operation - but with this variable set, it scales
14055 as N.")
14057 (defvar org--matcher-tags-todo-only nil)
14059 (defun org-scan-tags (action matcher todo-only &optional start-level)
14060 "Scan headline tags with inheritance and produce output ACTION.
14062 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14063 or `agenda' to produce an entry list for an agenda view. It can also be
14064 a Lisp form or a function that should be called at each matched headline, in
14065 this case the return value is a list of all return values from these calls.
14067 MATCHER is a function accepting three arguments, returning
14068 a non-nil value whenever a given set of tags qualifies a headline
14069 for inclusion. See `org-make-tags-matcher' for more information.
14070 As a special case, it can also be set to t (respectively nil) in
14071 order to match all (respectively none) headline.
14073 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14074 included in the output.
14076 START-LEVEL can be a string with asterisks, reducing the scope to
14077 headlines matching this string."
14078 (require 'org-agenda)
14079 (let* ((re (concat "^"
14080 (if start-level
14081 ;; Get the correct level to match
14082 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14083 org-outline-regexp)
14084 " *\\(\\<\\("
14085 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14086 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14087 (props (list 'face 'default
14088 'done-face 'org-agenda-done
14089 'undone-face 'default
14090 'mouse-face 'highlight
14091 'org-not-done-regexp org-not-done-regexp
14092 'org-todo-regexp org-todo-regexp
14093 'org-complex-heading-regexp org-complex-heading-regexp
14094 'help-echo
14095 (format "mouse-2 or RET jump to org file %s"
14096 (abbreviate-file-name
14097 (or (buffer-file-name (buffer-base-buffer))
14098 (buffer-name (buffer-base-buffer)))))))
14099 (org-map-continue-from nil)
14100 lspos tags tags-list
14101 (tags-alist (list (cons 0 org-file-tags)))
14102 (llast 0) rtn rtn1 level category i txt
14103 todo marker entry priority
14104 ts-date ts-date-type ts-date-pair)
14105 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14106 (setq action (list 'lambda nil action)))
14107 (save-excursion
14108 (goto-char (point-min))
14109 (when (eq action 'sparse-tree)
14110 (org-overview)
14111 (org-remove-occur-highlights))
14112 (while (let (case-fold-search)
14113 (re-search-forward re nil t))
14114 (setq org-map-continue-from nil)
14115 (catch :skip
14116 (setq todo
14117 ;; TODO: is the 1-2 difference a bug?
14118 (when (match-end 1) (match-string-no-properties 2))
14119 tags (when (match-end 4) (match-string-no-properties 4)))
14120 (goto-char (setq lspos (match-beginning 0)))
14121 (setq level (org-reduced-level (org-outline-level))
14122 category (org-get-category))
14123 (when (eq action 'agenda)
14124 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14125 ts-date (car ts-date-pair)
14126 ts-date-type (cdr ts-date-pair)))
14127 (setq i llast llast level)
14128 ;; remove tag lists from same and sublevels
14129 (while (>= i level)
14130 (when (setq entry (assoc i tags-alist))
14131 (setq tags-alist (delete entry tags-alist)))
14132 (setq i (1- i)))
14133 ;; add the next tags
14134 (when tags
14135 (setq tags (org-split-string tags ":")
14136 tags-alist
14137 (cons (cons level tags) tags-alist)))
14138 ;; compile tags for current headline
14139 (setq tags-list
14140 (if org-use-tag-inheritance
14141 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14142 tags)
14143 org-scanner-tags tags-list)
14144 (when org-use-tag-inheritance
14145 (setcdr (car tags-alist)
14146 (mapcar (lambda (x)
14147 (setq x (copy-sequence x))
14148 (org-add-prop-inherited x))
14149 (cdar tags-alist))))
14150 (when (and tags org-use-tag-inheritance
14151 (or (not (eq t org-use-tag-inheritance))
14152 org-tags-exclude-from-inheritance))
14153 ;; Selective inheritance, remove uninherited ones.
14154 (setcdr (car tags-alist)
14155 (org-remove-uninherited-tags (cdar tags-alist))))
14156 (when (and
14158 ;; eval matcher only when the todo condition is OK
14159 (and (or (not todo-only) (member todo org-todo-keywords-1))
14160 (if (functionp matcher)
14161 (let ((case-fold-search t) (org-trust-scanner-tags t))
14162 (funcall matcher todo tags-list level))
14163 matcher))
14165 ;; Call the skipper, but return t if it does not
14166 ;; skip, so that the `and' form continues evaluating.
14167 (progn
14168 (unless (eq action 'sparse-tree) (org-agenda-skip))
14171 ;; Check if timestamps are deselecting this entry
14172 (or (not todo-only)
14173 (and (member todo org-todo-keywords-1)
14174 (or (not org-agenda-tags-todo-honor-ignore-options)
14175 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14177 ;; select this headline
14178 (cond
14179 ((eq action 'sparse-tree)
14180 (and org-highlight-sparse-tree-matches
14181 (org-get-heading) (match-end 0)
14182 (org-highlight-new-match
14183 (match-beginning 1) (match-end 1)))
14184 (org-show-context 'tags-tree))
14185 ((eq action 'agenda)
14186 (setq txt (org-agenda-format-item
14188 (concat
14189 (if (eq org-tags-match-list-sublevels 'indented)
14190 (make-string (1- level) ?.) "")
14191 (org-get-heading))
14192 (make-string level ?\s)
14193 category
14194 tags-list)
14195 priority (org-get-priority txt))
14196 (goto-char lspos)
14197 (setq marker (org-agenda-new-marker))
14198 (org-add-props txt props
14199 'org-marker marker 'org-hd-marker marker 'org-category category
14200 'todo-state todo
14201 'ts-date ts-date
14202 'priority priority
14203 'type (concat "tagsmatch" ts-date-type))
14204 (push txt rtn))
14205 ((functionp action)
14206 (setq org-map-continue-from nil)
14207 (save-excursion
14208 (setq rtn1 (funcall action))
14209 (push rtn1 rtn)))
14210 (t (user-error "Invalid action")))
14212 ;; if we are to skip sublevels, jump to end of subtree
14213 (unless org-tags-match-list-sublevels
14214 (org-end-of-subtree t)
14215 (backward-char 1))))
14216 ;; Get the correct position from where to continue
14217 (if org-map-continue-from
14218 (goto-char org-map-continue-from)
14219 (and (= (point) lspos) (end-of-line 1)))))
14220 (when (and (eq action 'sparse-tree)
14221 (not org-sparse-tree-open-archived-trees))
14222 (org-hide-archived-subtrees (point-min) (point-max)))
14223 (nreverse rtn)))
14225 (defun org-remove-uninherited-tags (tags)
14226 "Remove all tags that are not inherited from the list TAGS."
14227 (cond
14228 ((eq org-use-tag-inheritance t)
14229 (if org-tags-exclude-from-inheritance
14230 (org-delete-all org-tags-exclude-from-inheritance tags)
14231 tags))
14232 ((not org-use-tag-inheritance) nil)
14233 ((stringp org-use-tag-inheritance)
14234 (delq nil (mapcar
14235 (lambda (x)
14236 (if (and (string-match org-use-tag-inheritance x)
14237 (not (member x org-tags-exclude-from-inheritance)))
14238 x nil))
14239 tags)))
14240 ((listp org-use-tag-inheritance)
14241 (delq nil (mapcar
14242 (lambda (x)
14243 (if (member x org-use-tag-inheritance) x nil))
14244 tags)))))
14246 (defun org-match-sparse-tree (&optional todo-only match)
14247 "Create a sparse tree according to tags string MATCH.
14249 MATCH is a string with match syntax. It can contain a selection
14250 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14251 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14252 those. See the manual for details.
14254 If optional argument TODO-ONLY is non-nil, only select lines that
14255 are also TODO tasks."
14256 (interactive "P")
14257 (org-agenda-prepare-buffers (list (current-buffer)))
14258 (let ((org--matcher-tags-todo-only todo-only))
14259 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14260 org--matcher-tags-todo-only)))
14262 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14264 (defvar org-cached-props nil)
14265 (defun org-cached-entry-get (pom property)
14266 (if (or (eq t org-use-property-inheritance)
14267 (and (stringp org-use-property-inheritance)
14268 (let ((case-fold-search t))
14269 (string-match-p org-use-property-inheritance property)))
14270 (and (listp org-use-property-inheritance)
14271 (member-ignore-case property org-use-property-inheritance)))
14272 ;; Caching is not possible, check it directly.
14273 (org-entry-get pom property 'inherit)
14274 ;; Get all properties, so we can do complicated checks easily.
14275 (cdr (assoc-string property
14276 (or org-cached-props
14277 (setq org-cached-props (org-entry-properties pom)))
14278 t))))
14280 (defun org-global-tags-completion-table (&optional files)
14281 "Return the list of all tags in all agenda buffer/files.
14282 Optional FILES argument is a list of files which can be used
14283 instead of the agenda files."
14284 (save-excursion
14285 (org-uniquify
14286 (delq nil
14287 (apply #'append
14288 (mapcar
14289 (lambda (file)
14290 (set-buffer (find-file-noselect file))
14291 (mapcar (lambda (x)
14292 (and (stringp (car-safe x))
14293 (list (car-safe x))))
14294 (or org-current-tag-alist (org-get-buffer-tags))))
14295 (if (car-safe files) files
14296 (org-agenda-files))))))))
14298 (defun org-make-tags-matcher (match)
14299 "Create the TAGS/TODO matcher form for the selection string MATCH.
14301 Returns a cons of the selection string MATCH and a function
14302 implementing the matcher.
14304 The matcher is to be called at an Org entry, with point on the
14305 headline, and returns non-nil if the entry matches the selection
14306 string MATCH. It must be called with three arguments: the TODO
14307 keyword at the entry (or nil if none), the list of all tags at
14308 the entry including inherited ones and the reduced level of the
14309 headline. Additionally, the category of the entry, if any, must
14310 be specified as the text property `org-category' on the headline.
14312 This function sets the variable `org--matcher-tags-todo-only' to
14313 a non-nil value if the matcher restricts matching to TODO
14314 entries, otherwise it is not touched.
14316 See also `org-scan-tags'."
14317 (unless match
14318 ;; Get a new match request, with completion against the global
14319 ;; tags table and the local tags in current buffer.
14320 (let ((org-last-tags-completion-table
14321 (org-uniquify
14322 (delq nil (append (org-get-buffer-tags)
14323 (org-global-tags-completion-table))))))
14324 (setq match
14325 (completing-read
14326 "Match: "
14327 'org-tags-completion-function nil nil nil 'org-tags-history))))
14329 (let ((match0 match)
14330 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14331 (start 0)
14332 tagsmatch todomatch tagsmatcher todomatcher)
14334 ;; Expand group tags.
14335 (setq match (org-tags-expand match))
14337 ;; Check if there is a TODO part of this match, which would be the
14338 ;; part after a "/". To make sure that this slash is not part of
14339 ;; a property value to be matched against, we also check that
14340 ;; there is no / after that slash. First, find the last slash.
14341 (let ((s 0))
14342 (while (string-match "/+" match s)
14343 (setq start (match-beginning 0))
14344 (setq s (match-end 0))))
14345 (if (and (string-match "/+" match start)
14346 (not (string-match-p "\"" match start)))
14347 ;; Match contains also a TODO-matching request.
14348 (progn
14349 (setq tagsmatch (substring match 0 (match-beginning 0)))
14350 (setq todomatch (substring match (match-end 0)))
14351 (when (string-prefix-p "!" todomatch)
14352 (setq org--matcher-tags-todo-only t)
14353 (setq todomatch (substring todomatch 1)))
14354 (when (string-match "\\`\\s-*\\'" todomatch)
14355 (setq todomatch nil)))
14356 ;; Only matching tags.
14357 (setq tagsmatch match)
14358 (setq todomatch nil))
14360 ;; Make the tags matcher.
14361 (when (org-string-nw-p tagsmatch)
14362 (let ((orlist nil)
14363 (orterms (org-split-string tagsmatch "|"))
14364 term)
14365 (while (setq term (pop orterms))
14366 (while (and (equal (substring term -1) "\\") orterms)
14367 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14368 (while (string-match re term)
14369 (let* ((rest (substring term (match-end 0)))
14370 (minus (and (match-end 1)
14371 (equal (match-string 1 term) "-")))
14372 (tag (save-match-data
14373 (replace-regexp-in-string
14374 "\\\\-" "-" (match-string 2 term))))
14375 (regexp (eq (string-to-char tag) ?{))
14376 (levelp (match-end 4))
14377 (propp (match-end 5))
14379 (cond
14380 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14381 (levelp
14382 `(,(org-op-to-function (match-string 3 term))
14383 level
14384 ,(string-to-number (match-string 4 term))))
14385 (propp
14386 (let* ((gv (pcase (upcase (match-string 5 term))
14387 ("CATEGORY"
14388 '(get-text-property (point) 'org-category))
14389 ("TODO" 'todo)
14390 (p `(org-cached-entry-get nil ,p))))
14391 (pv (match-string 7 term))
14392 (regexp (eq (string-to-char pv) ?{))
14393 (strp (eq (string-to-char pv) ?\"))
14394 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14395 (po (org-op-to-function (match-string 6 term)
14396 (if timep 'time strp))))
14397 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14398 (when timep (setq pv (org-matcher-time pv)))
14399 (cond ((and regexp (eq po 'org<>))
14400 `(not (string-match ,pv (or ,gv ""))))
14401 (regexp `(string-match ,pv (or ,gv "")))
14402 (strp `(,po (or ,gv "") ,pv))
14404 `(,po
14405 (string-to-number (or ,gv ""))
14406 ,(string-to-number pv))))))
14407 (t `(member ,tag tags-list)))))
14408 (push (if minus `(not ,mm) mm) tagsmatcher)
14409 (setq term rest)))
14410 (push `(and ,@tagsmatcher) orlist)
14411 (setq tagsmatcher nil))
14412 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14414 ;; Make the TODO matcher.
14415 (when (org-string-nw-p todomatch)
14416 (let ((orlist nil))
14417 (dolist (term (org-split-string todomatch "|"))
14418 (while (string-match re term)
14419 (let* ((minus (and (match-end 1)
14420 (equal (match-string 1 term) "-")))
14421 (kwd (match-string 2 term))
14422 (regexp (eq (string-to-char kwd) ?{))
14423 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14424 `(equal todo ,kwd))))
14425 (push (if minus `(not ,mm) mm) todomatcher))
14426 (setq term (substring term (match-end 0))))
14427 (push (if (> (length todomatcher) 1)
14428 (cons 'and todomatcher)
14429 (car todomatcher))
14430 orlist)
14431 (setq todomatcher nil))
14432 (setq todomatcher (cons 'or orlist))))
14434 ;; Return the string and function of the matcher. If no
14435 ;; tags-specific or todo-specific matcher exists, match
14436 ;; everything.
14437 (let ((matcher (if (and tagsmatcher todomatcher)
14438 `(and ,tagsmatcher ,todomatcher)
14439 (or tagsmatcher todomatcher t))))
14440 (when org--matcher-tags-todo-only
14441 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14442 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14444 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14445 "Expand group tags in MATCH.
14447 This replaces every group tag in MATCH with a regexp tag search.
14448 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14449 will be replaced like this:
14451 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14452 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14453 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14455 Replacing by a regexp preserves the structure of the match.
14456 E.g., this expansion
14458 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14460 will match anything tagged with \"Lab\" and \"Home\", or tagged
14461 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14463 A group tag in MATCH can contain regular expressions of its own.
14464 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14465 will be replaced like this:
14467 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14469 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14470 assumed to be a single group tag, and the function will return
14471 the list of tags in this group.
14473 When DOWNCASE is non-nil, expand downcased TAGS."
14474 (if org-group-tags
14475 (let* ((case-fold-search t)
14476 (stable org-mode-syntax-table)
14477 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14478 (taggroups (if downcased
14479 (mapcar (lambda (tg) (mapcar #'downcase tg))
14480 taggroups)
14481 taggroups))
14482 (taggroups-keys (mapcar #'car taggroups))
14483 (return-match (if downcased (downcase match) match))
14484 (count 0)
14485 (work-already-expanded tags-already-expanded)
14486 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14487 ;; @ and _ are allowed as word-components in tags.
14488 (modify-syntax-entry ?@ "w" stable)
14489 (modify-syntax-entry ?_ "w" stable)
14490 ;; Temporarily replace regexp-expressions in the match-expression.
14491 (while (string-match "{.+?}" return-match)
14492 (cl-incf count)
14493 (push (match-string 0 return-match) regexps-in-match)
14494 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14495 (while (and taggroups-keys
14496 (with-syntax-table stable
14497 (string-match
14498 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14499 (regexp-opt taggroups-keys) "\\>\\)")
14500 return-match)))
14501 (let* ((dir (match-string 1 return-match))
14502 (tag (match-string 2 return-match))
14503 (tag (if downcased (downcase tag) tag)))
14504 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14505 (member tag work-already-expanded))
14506 (setq tags-in-group (assoc tag taggroups))
14507 (push tag work-already-expanded)
14508 ;; Recursively expand each tag in the group, if the tag hasn't
14509 ;; already been expanded. Restore the match-data after all recursive calls.
14510 (save-match-data
14511 (let (tags-expanded)
14512 (dolist (x (cdr tags-in-group))
14513 (if (and (member x taggroups-keys)
14514 (not (member x work-already-expanded)))
14515 (setq tags-expanded
14516 (delete-dups
14517 (append
14518 (org-tags-expand x t downcased
14519 work-already-expanded)
14520 tags-expanded)))
14521 (setq tags-expanded
14522 (append (list x) tags-expanded)))
14523 (setq work-already-expanded
14524 (delete-dups
14525 (append tags-expanded
14526 work-already-expanded))))
14527 (setq tags-in-group
14528 (delete-dups (cons (car tags-in-group)
14529 tags-expanded)))))
14530 ;; Filter tag-regexps from tags.
14531 (setq regexp-in-group-escaped
14532 (delq nil (mapcar (lambda (x)
14533 (if (stringp x)
14534 (and (equal "{" (substring x 0 1))
14535 (equal "}" (substring x -1))
14538 tags-in-group))
14539 regexp-in-group
14540 (mapcar (lambda (x)
14541 (substring x 1 -1))
14542 regexp-in-group-escaped)
14543 tags-in-group
14544 (delq nil (mapcar (lambda (x)
14545 (if (stringp x)
14546 (and (not (equal "{" (substring x 0 1)))
14547 (not (equal "}" (substring x -1)))
14550 tags-in-group)))
14551 ;; If single-as-list, do no more in the while-loop.
14552 (if (not single-as-list)
14553 (progn
14554 (when regexp-in-group
14555 (setq regexp-in-group
14556 (concat "\\|"
14557 (mapconcat 'identity regexp-in-group
14558 "\\|"))))
14559 (setq tags-in-group
14560 (concat dir
14561 "{\\<"
14562 (regexp-opt tags-in-group)
14563 "\\>"
14564 regexp-in-group
14565 "}"))
14566 (when (stringp tags-in-group)
14567 (org-add-props tags-in-group '(grouptag t)))
14568 (setq return-match
14569 (replace-match tags-in-group t t return-match)))
14570 (setq tags-in-group
14571 (append regexp-in-group-escaped tags-in-group))))
14572 (setq taggroups-keys (delete tag taggroups-keys))))
14573 ;; Add the regular expressions back into the match-expression again.
14574 (while regexps-in-match
14575 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14576 (pop regexps-in-match)
14577 return-match t t))
14578 (cl-decf count))
14579 (if single-as-list
14580 (if tags-in-group tags-in-group (list return-match))
14581 return-match))
14582 (if single-as-list
14583 (list (if downcased (downcase match) match))
14584 match)))
14586 (defun org-op-to-function (op &optional stringp)
14587 "Turn an operator into the appropriate function."
14588 (setq op
14589 (cond
14590 ((equal op "<" ) '(< string< org-time<))
14591 ((equal op ">" ) '(> org-string> org-time>))
14592 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14593 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14594 ((member op '("=" "==")) '(= string= org-time=))
14595 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14596 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14598 (defun org<> (a b) (not (= a b)))
14599 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14600 (defun org-string>= (a b) (not (string< a b)))
14601 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14602 (defun org-string<> (a b) (not (string= a b)))
14603 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14604 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14605 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14606 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14607 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14608 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14609 (defun org-2ft (s)
14610 "Convert S to a floating point time.
14611 If S is already a number, just return it. If it is a string, parse
14612 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14613 (cond
14614 ((numberp s) s)
14615 ((stringp s)
14616 (condition-case nil
14617 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14618 (error 0.)))
14619 (t 0.)))
14621 (defun org-time-today ()
14622 "Time in seconds today at 0:00.
14623 Returns the float number of seconds since the beginning of the
14624 epoch to the beginning of today (00:00)."
14625 (float-time (apply 'encode-time
14626 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14628 (defun org-matcher-time (s)
14629 "Interpret a time comparison value."
14630 (save-match-data
14631 (cond
14632 ((string= s "<now>") (float-time))
14633 ((string= s "<today>") (org-time-today))
14634 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14635 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14636 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14637 (+ (org-time-today)
14638 (* (string-to-number (match-string 1 s))
14639 (cdr (assoc (match-string 2 s)
14640 '(("d" . 86400.0) ("w" . 604800.0)
14641 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14642 (t (org-2ft s)))))
14644 (defun org-match-any-p (re list)
14645 "Does re match any element of list?"
14646 (setq list (mapcar (lambda (x) (string-match re x)) list))
14647 (delq nil list))
14649 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14650 (defvar org-tags-overlay (make-overlay 1 1))
14651 (delete-overlay org-tags-overlay)
14653 (defun org-get-local-tags-at (&optional pos)
14654 "Get a list of tags defined in the current headline."
14655 (org-get-tags-at pos 'local))
14657 (defun org-get-local-tags ()
14658 "Get a list of tags defined in the current headline."
14659 (org-get-tags-at nil 'local))
14661 (defun org-get-tags-at (&optional pos local)
14662 "Get a list of all headline tags applicable at POS.
14663 POS defaults to point. If tags are inherited, the list contains
14664 the targets in the same sequence as the headlines appear, i.e.
14665 the tags of the current headline come last.
14666 When LOCAL is non-nil, only return tags from the current headline,
14667 ignore inherited ones."
14668 (interactive)
14669 (if (and org-trust-scanner-tags
14670 (or (not pos) (equal pos (point)))
14671 (not local))
14672 org-scanner-tags
14673 (let (tags ltags lastpos parent)
14674 (save-excursion
14675 (save-restriction
14676 (widen)
14677 (goto-char (or pos (point)))
14678 (save-match-data
14679 (catch 'done
14680 (condition-case nil
14681 (progn
14682 (org-back-to-heading t)
14683 (while (not (equal lastpos (point)))
14684 (setq lastpos (point))
14685 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14686 (setq ltags (org-split-string
14687 (match-string-no-properties 1) ":"))
14688 (when parent
14689 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14690 (setq tags (append
14691 (if parent
14692 (org-remove-uninherited-tags ltags)
14693 ltags)
14694 tags)))
14695 (or org-use-tag-inheritance (throw 'done t))
14696 (when local (throw 'done t))
14697 (or (org-up-heading-safe) (error nil))
14698 (setq parent t)))
14699 (error nil)))))
14700 (if local
14701 tags
14702 (reverse (delete-dups
14703 (reverse (append
14704 (org-remove-uninherited-tags
14705 org-file-tags)
14706 tags)))))))))
14708 (defun org-add-prop-inherited (s)
14709 (add-text-properties 0 (length s) '(inherited t) s)
14712 (defun org-toggle-tag (tag &optional onoff)
14713 "Toggle the tag TAG for the current line.
14714 If ONOFF is `on' or `off', don't toggle but set to this state."
14715 (save-excursion
14716 (org-back-to-heading t)
14717 (let ((current
14718 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14719 (line-end-position) t)
14720 (let ((tags (match-string 1)))
14721 ;; Clear current tags.
14722 (replace-match "")
14723 ;; Reverse the tags list so any new tag is appended to
14724 ;; the current list of tags.
14725 (nreverse (org-split-string tags ":")))))
14726 res)
14727 (pcase onoff
14728 (`off (setq current (delete tag current)))
14729 ((or `on (guard (not (member tag current))))
14730 (setq res t)
14731 (cl-pushnew tag current :test #'equal))
14732 (_ (setq current (delete tag current))))
14733 (end-of-line)
14734 (if current
14735 (progn
14736 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14737 (org-set-tags nil t))
14738 (delete-horizontal-space))
14739 (run-hooks 'org-after-tags-change-hook)
14740 res)))
14742 (defun org--align-tags-here (to-col)
14743 "Align tags on the current headline to TO-COL.
14744 Assume point is on a headline."
14745 (let ((pos (point)))
14746 (beginning-of-line)
14747 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14748 (>= pos (match-beginning 2)))
14749 ;; No tags or point within tags: do not align.
14750 (goto-char pos)
14751 (goto-char (match-beginning 1))
14752 (let ((shift (max (- (if (>= to-col 0) to-col
14753 (- (abs to-col) (string-width (match-string 2))))
14754 (current-column))
14755 1)))
14756 (replace-match (make-string shift ?\s) nil nil nil 1)
14757 ;; Preserve initial position, if possible. In any case, stop
14758 ;; before tags.
14759 (when (< pos (point)) (goto-char pos))))))
14761 (defun org-set-tags-command (&optional arg just-align)
14762 "Call the set-tags command for the current entry."
14763 (interactive "P")
14764 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14765 (org-set-tags arg just-align)
14766 (save-excursion
14767 (unless (and (org-region-active-p)
14768 org-loop-over-headlines-in-active-region)
14769 (org-back-to-heading t))
14770 (org-set-tags arg just-align))))
14772 (defun org-set-tags-to (data)
14773 "Set the tags of the current entry to DATA, replacing the current tags.
14774 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14775 If DATA is nil or the empty string, any tags will be removed."
14776 (interactive "sTags: ")
14777 (setq data
14778 (cond
14779 ((eq data nil) "")
14780 ((equal data "") "")
14781 ((stringp data)
14782 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14783 ":"))
14784 ((listp data)
14785 (concat ":" (mapconcat 'identity data ":") ":"))))
14786 (when data
14787 (save-excursion
14788 (org-back-to-heading t)
14789 (when (let ((case-fold-search nil))
14790 (looking-at org-complex-heading-regexp))
14791 (if (match-end 5)
14792 (progn
14793 (goto-char (match-beginning 5))
14794 (insert data)
14795 (delete-region (point) (point-at-eol))
14796 (org-set-tags nil 'align))
14797 (goto-char (point-at-eol))
14798 (insert " " data)
14799 (org-set-tags nil 'align)))
14800 (beginning-of-line 1)
14801 (when (looking-at ".*?\\([ \t]+\\)$")
14802 (delete-region (match-beginning 1) (match-end 1))))))
14804 (defun org-align-all-tags ()
14805 "Align the tags in all headings."
14806 (interactive)
14807 (save-excursion
14808 (or (ignore-errors (org-back-to-heading t))
14809 (outline-next-heading))
14810 (if (org-at-heading-p)
14811 (org-set-tags t)
14812 (message "No headings"))))
14814 (defvar org-indent-indentation-per-level)
14815 (defun org-set-tags (&optional arg just-align)
14816 "Set the tags for the current headline.
14817 With prefix ARG, realign all tags in headings in the current buffer.
14818 When JUST-ALIGN is non-nil, only align tags."
14819 (interactive "P")
14820 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14821 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14822 'region-start-level
14823 'region))
14824 org-loop-over-headlines-in-active-region)
14825 (org-map-entries
14826 ;; We don't use ARG and JUST-ALIGN here because these args
14827 ;; are not useful when looping over headlines.
14828 #'org-set-tags
14829 org-loop-over-headlines-in-active-region
14831 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14832 (let ((org-setting-tags t))
14833 (if arg
14834 (save-excursion
14835 (goto-char (point-min))
14836 (while (re-search-forward org-outline-regexp-bol nil t)
14837 (org-set-tags nil t)
14838 (end-of-line))
14839 (message "All tags realigned to column %d" org-tags-column))
14840 (let* ((current (org-get-tags-string))
14841 (tags
14842 (if just-align current
14843 ;; Get a new set of tags from the user.
14844 (save-excursion
14845 (let* ((seen)
14846 (table
14847 (setq
14848 org-last-tags-completion-table
14849 ;; Uniquify tags in alists, yet preserve
14850 ;; structure (i.e., keywords).
14851 (delq nil
14852 (mapcar
14853 (lambda (pair)
14854 (let ((head (car pair)))
14855 (cond ((symbolp head) pair)
14856 ((member head seen) nil)
14857 (t (push head seen)
14858 pair))))
14859 (append
14860 (or org-current-tag-alist
14861 (org-get-buffer-tags))
14862 (and
14863 org-complete-tags-always-offer-all-agenda-tags
14864 (org-global-tags-completion-table
14865 (org-agenda-files))))))))
14866 (current-tags (org-split-string current ":"))
14867 (inherited-tags
14868 (nreverse (nthcdr (length current-tags)
14869 (nreverse (org-get-tags-at))))))
14870 (replace-regexp-in-string
14871 "\\([-+&]+\\|,\\)"
14873 (if (or (eq t org-use-fast-tag-selection)
14874 (and org-use-fast-tag-selection
14875 (delq nil (mapcar #'cdr table))))
14876 (org-fast-tag-selection
14877 current-tags inherited-tags table
14878 (and org-fast-tag-selection-include-todo
14879 org-todo-key-alist))
14880 (let ((org-add-colon-after-tag-completion
14881 (< 1 (length table))))
14882 (org-trim
14883 (completing-read
14884 "Tags: "
14885 #'org-tags-completion-function
14886 nil nil current 'org-tags-history))))))))))
14888 (when org-tags-sort-function
14889 (setq tags
14890 (mapconcat
14891 #'identity
14892 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14893 org-tags-sort-function)
14894 ":")))
14896 (if (or (string= ":" tags)
14897 (string= "::" tags))
14898 (setq tags ""))
14899 (if (not (org-string-nw-p tags)) (setq tags "")
14900 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14901 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14903 ;; Insert new tags at the correct column.
14904 (unless (equal current tags)
14905 (save-excursion
14906 (beginning-of-line)
14907 (let ((case-fold-search nil))
14908 (looking-at org-complex-heading-regexp))
14909 ;; Remove current tags, if any.
14910 (when (match-end 5) (replace-match "" nil nil nil 5))
14911 ;; Insert new tags, if any. Otherwise, remove trailing
14912 ;; white spaces.
14913 (end-of-line)
14914 (if (not (equal tags ""))
14915 ;; When text is being inserted on an invisible
14916 ;; region boundary, it can be inadvertently sucked
14917 ;; into invisibility.
14918 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14919 (skip-chars-backward " \t")
14920 (delete-region (point) (line-end-position)))))
14921 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14922 ;; is on.
14923 (unless (equal tags "")
14924 (let* ((level (save-excursion
14925 (beginning-of-line)
14926 (skip-chars-forward "\\*")))
14927 (offset (if (bound-and-true-p org-indent-mode)
14928 (* (1- org-indent-indentation-per-level)
14929 (1- level))
14931 (tags-column
14932 (+ org-tags-column
14933 (if (> org-tags-column 0) (- offset) offset))))
14934 (org--align-tags-here tags-column))))
14935 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14937 (defun org-change-tag-in-region (beg end tag off)
14938 "Add or remove TAG for each entry in the region.
14939 This works in the agenda, and also in an Org buffer."
14940 (interactive
14941 (list (region-beginning) (region-end)
14942 (let ((org-last-tags-completion-table
14943 (if (derived-mode-p 'org-mode)
14944 (org-uniquify
14945 (delq nil (append (org-get-buffer-tags)
14946 (org-global-tags-completion-table))))
14947 (org-global-tags-completion-table))))
14948 (completing-read
14949 "Tag: " 'org-tags-completion-function nil nil nil
14950 'org-tags-history))
14951 (progn
14952 (message "[s]et or [r]emove? ")
14953 (equal (read-char-exclusive) ?r))))
14954 (when (fboundp 'deactivate-mark) (deactivate-mark))
14955 (let ((agendap (equal major-mode 'org-agenda-mode))
14956 l1 l2 m buf pos newhead (cnt 0))
14957 (goto-char end)
14958 (setq l2 (1- (org-current-line)))
14959 (goto-char beg)
14960 (setq l1 (org-current-line))
14961 (cl-loop for l from l1 to l2 do
14962 (org-goto-line l)
14963 (setq m (get-text-property (point) 'org-hd-marker))
14964 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14965 (and agendap m))
14966 (setq buf (if agendap (marker-buffer m) (current-buffer))
14967 pos (if agendap m (point)))
14968 (with-current-buffer buf
14969 (save-excursion
14970 (save-restriction
14971 (goto-char pos)
14972 (setq cnt (1+ cnt))
14973 (org-toggle-tag tag (if off 'off 'on))
14974 (setq newhead (org-get-heading)))))
14975 (and agendap (org-agenda-change-all-lines newhead m))))
14976 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14978 (defun org-tags-completion-function (string _predicate &optional flag)
14979 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14980 (confirm (lambda (x) (stringp (car x)))))
14981 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14982 (setq s1 (match-string 1 string)
14983 s2 (match-string 2 string))
14984 (setq s1 "" s2 string))
14985 (cond
14986 ((eq flag nil)
14987 ;; try completion
14988 (setq rtn (try-completion s2 ctable confirm))
14989 (when (stringp rtn)
14990 (setq rtn
14991 (concat s1 s2 (substring rtn (length s2))
14992 (if (and org-add-colon-after-tag-completion
14993 (assoc rtn ctable))
14994 ":" ""))))
14995 rtn)
14996 ((eq flag t)
14997 ;; all-completions
14998 (all-completions s2 ctable confirm))
14999 ((eq flag 'lambda)
15000 ;; exact match?
15001 (assoc s2 ctable)))))
15003 (defun org-fast-tag-insert (kwd tags face &optional end)
15004 "Insert KDW, and the TAGS, the latter with face FACE.
15005 Also insert END."
15006 (insert (format "%-12s" (concat kwd ":"))
15007 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15008 (or end "")))
15010 (defun org-fast-tag-show-exit (flag)
15011 (save-excursion
15012 (org-goto-line 3)
15013 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15014 (replace-match ""))
15015 (when flag
15016 (end-of-line 1)
15017 (org-move-to-column (- (window-width) 19) t)
15018 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15020 (defun org-set-current-tags-overlay (current prefix)
15021 "Add an overlay to CURRENT tag with PREFIX."
15022 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15023 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15024 (org-overlay-display org-tags-overlay (concat prefix s))))
15026 (defvar org-last-tag-selection-key nil)
15027 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15028 "Fast tag selection with single keys.
15029 CURRENT is the current list of tags in the headline, INHERITED is the
15030 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15031 possibly with grouping information. TODO-TABLE is a similar table with
15032 TODO keywords, should these have keys assigned to them.
15033 If the keys are nil, a-z are automatically assigned.
15034 Returns the new tags string, or nil to not change the current settings."
15035 (let* ((fulltable (append table todo-table))
15036 (maxlen (apply 'max (mapcar
15037 (lambda (x)
15038 (if (stringp (car x)) (string-width (car x)) 0))
15039 fulltable)))
15040 (buf (current-buffer))
15041 (expert (eq org-fast-tag-selection-single-key 'expert))
15042 (buffer-tags nil)
15043 (fwidth (+ maxlen 3 1 3))
15044 (ncol (/ (- (window-width) 4) fwidth))
15045 (i-face 'org-done)
15046 (c-face 'org-todo)
15047 tg cnt e c char c1 c2 ntable tbl rtn
15048 ov-start ov-end ov-prefix
15049 (exit-after-next org-fast-tag-selection-single-key)
15050 (done-keywords org-done-keywords)
15051 groups ingroup intaggroup)
15052 (save-excursion
15053 (beginning-of-line 1)
15054 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15055 (setq ov-start (match-beginning 1)
15056 ov-end (match-end 1)
15057 ov-prefix "")
15058 (setq ov-start (1- (point-at-eol))
15059 ov-end (1+ ov-start))
15060 (skip-chars-forward "^\n\r")
15061 (setq ov-prefix
15062 (concat
15063 (buffer-substring (1- (point)) (point))
15064 (if (> (current-column) org-tags-column)
15066 (make-string (- org-tags-column (current-column)) ?\ ))))))
15067 (move-overlay org-tags-overlay ov-start ov-end)
15068 (save-window-excursion
15069 (if expert
15070 (set-buffer (get-buffer-create " *Org tags*"))
15071 (delete-other-windows)
15072 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15073 (org-switch-to-buffer-other-window " *Org tags*"))
15074 (erase-buffer)
15075 (setq-local org-done-keywords done-keywords)
15076 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15077 (org-fast-tag-insert "Current" current c-face "\n\n")
15078 (org-fast-tag-show-exit exit-after-next)
15079 (org-set-current-tags-overlay current ov-prefix)
15080 (setq tbl fulltable char ?a cnt 0)
15081 (while (setq e (pop tbl))
15082 (cond
15083 ((eq (car e) :startgroup)
15084 (push '() groups) (setq ingroup t)
15085 (unless (zerop cnt)
15086 (setq cnt 0)
15087 (insert "\n"))
15088 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15089 ((eq (car e) :endgroup)
15090 (setq ingroup nil cnt 0)
15091 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15092 ((eq (car e) :startgrouptag)
15093 (setq intaggroup t)
15094 (unless (zerop cnt)
15095 (setq cnt 0)
15096 (insert "\n"))
15097 (insert "[ "))
15098 ((eq (car e) :endgrouptag)
15099 (setq intaggroup nil cnt 0)
15100 (insert "]\n"))
15101 ((equal e '(:newline))
15102 (unless (zerop cnt)
15103 (setq cnt 0)
15104 (insert "\n")
15105 (setq e (car tbl))
15106 (while (equal (car tbl) '(:newline))
15107 (insert "\n")
15108 (setq tbl (cdr tbl)))))
15109 ((equal e '(:grouptags)) (insert " : "))
15111 (setq tg (copy-sequence (car e)) c2 nil)
15112 (if (cdr e)
15113 (setq c (cdr e))
15114 ;; automatically assign a character.
15115 (setq c1 (string-to-char
15116 (downcase (substring
15117 tg (if (= (string-to-char tg) ?@) 1 0)))))
15118 (if (or (rassoc c1 ntable) (rassoc c1 table))
15119 (while (or (rassoc char ntable) (rassoc char table))
15120 (setq char (1+ char)))
15121 (setq c2 c1))
15122 (setq c (or c2 char)))
15123 (when ingroup (push tg (car groups)))
15124 (setq tg (org-add-props tg nil 'face
15125 (cond
15126 ((not (assoc tg table))
15127 (org-get-todo-face tg))
15128 ((member tg current) c-face)
15129 ((member tg inherited) i-face))))
15130 (when (equal (caar tbl) :grouptags)
15131 (org-add-props tg nil 'face 'org-tag-group))
15132 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15133 (insert "[" c "] " tg (make-string
15134 (- fwidth 4 (length tg)) ?\ ))
15135 (push (cons tg c) ntable)
15136 (when (= (cl-incf cnt) ncol)
15137 (insert "\n")
15138 (when (or ingroup intaggroup) (insert " "))
15139 (setq cnt 0)))))
15140 (setq ntable (nreverse ntable))
15141 (insert "\n")
15142 (goto-char (point-min))
15143 (unless expert (org-fit-window-to-buffer))
15144 (setq rtn
15145 (catch 'exit
15146 (while t
15147 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15148 (if (not groups) "no " "")
15149 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15150 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15151 (setq org-last-tag-selection-key c)
15152 (cond
15153 ((= c ?\r) (throw 'exit t))
15154 ((= c ?!)
15155 (setq groups (not groups))
15156 (goto-char (point-min))
15157 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15158 ((= c ?\C-c)
15159 (if (not expert)
15160 (org-fast-tag-show-exit
15161 (setq exit-after-next (not exit-after-next)))
15162 (setq expert nil)
15163 (delete-other-windows)
15164 (set-window-buffer (split-window-vertically) " *Org tags*")
15165 (org-switch-to-buffer-other-window " *Org tags*")
15166 (org-fit-window-to-buffer)))
15167 ((or (= c ?\C-g)
15168 (and (= c ?q) (not (rassoc c ntable))))
15169 (delete-overlay org-tags-overlay)
15170 (setq quit-flag t))
15171 ((= c ?\ )
15172 (setq current nil)
15173 (when exit-after-next (setq exit-after-next 'now)))
15174 ((= c ?\t)
15175 (condition-case nil
15176 (setq tg (completing-read
15177 "Tag: "
15178 (or buffer-tags
15179 (with-current-buffer buf
15180 (setq buffer-tags
15181 (org-get-buffer-tags))))))
15182 (quit (setq tg "")))
15183 (when (string-match "\\S-" tg)
15184 (cl-pushnew (list tg) buffer-tags :test #'equal)
15185 (if (member tg current)
15186 (setq current (delete tg current))
15187 (push tg current)))
15188 (when exit-after-next (setq exit-after-next 'now)))
15189 ((setq e (rassoc c todo-table) tg (car e))
15190 (with-current-buffer buf
15191 (save-excursion (org-todo tg)))
15192 (when exit-after-next (setq exit-after-next 'now)))
15193 ((setq e (rassoc c ntable) tg (car e))
15194 (if (member tg current)
15195 (setq current (delete tg current))
15196 (cl-loop for g in groups do
15197 (when (member tg g)
15198 (dolist (x g) (setq current (delete x current)))))
15199 (push tg current))
15200 (when exit-after-next (setq exit-after-next 'now))))
15202 ;; Create a sorted list
15203 (setq current
15204 (sort current
15205 (lambda (a b)
15206 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15207 (when (eq exit-after-next 'now) (throw 'exit t))
15208 (goto-char (point-min))
15209 (beginning-of-line 2)
15210 (delete-region (point) (point-at-eol))
15211 (org-fast-tag-insert "Current" current c-face)
15212 (org-set-current-tags-overlay current ov-prefix)
15213 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15214 (setq tg (match-string 1))
15215 (add-text-properties
15216 (match-beginning 1) (match-end 1)
15217 (list 'face
15218 (cond
15219 ((member tg current) c-face)
15220 ((member tg inherited) i-face)
15221 (t (get-text-property (match-beginning 1) 'face))))))
15222 (goto-char (point-min)))))
15223 (delete-overlay org-tags-overlay)
15224 (if rtn
15225 (mapconcat 'identity current ":")
15226 nil))))
15228 (defun org-get-tags-string ()
15229 "Get the TAGS string in the current headline."
15230 (unless (org-at-heading-p t)
15231 (user-error "Not on a heading"))
15232 (save-excursion
15233 (beginning-of-line 1)
15234 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15235 (match-string-no-properties 1)
15236 "")))
15238 (defun org-get-tags ()
15239 "Get the list of tags specified in the current headline."
15240 (org-split-string (org-get-tags-string) ":"))
15242 (defun org-get-buffer-tags ()
15243 "Get a table of all tags used in the buffer, for completion."
15244 (org-with-wide-buffer
15245 (goto-char (point-min))
15246 (let ((tag-re (concat org-outline-regexp-bol
15247 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15248 tags)
15249 (while (re-search-forward tag-re nil t)
15250 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15251 (push tag tags)))
15252 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15254 ;;;; The mapping API
15256 (defvar org-agenda-skip-comment-trees)
15257 (defvar org-agenda-skip-function)
15258 (defun org-map-entries (func &optional match scope &rest skip)
15259 "Call FUNC at each headline selected by MATCH in SCOPE.
15261 FUNC is a function or a lisp form. The function will be called without
15262 arguments, with the cursor positioned at the beginning of the headline.
15263 The return values of all calls to the function will be collected and
15264 returned as a list.
15266 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15267 does not need to preserve point. After evaluation, the cursor will be
15268 moved to the end of the line (presumably of the headline of the
15269 processed entry) and search continues from there. Under some
15270 circumstances, this may not produce the wanted results. For example,
15271 if you have removed (e.g. archived) the current (sub)tree it could
15272 mean that the next entry will be skipped entirely. In such cases, you
15273 can specify the position from where search should continue by making
15274 FUNC set the variable `org-map-continue-from' to the desired buffer
15275 position.
15277 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15278 Only headlines that are matched by this query will be considered during
15279 the iteration. When MATCH is nil or t, all headlines will be
15280 visited by the iteration.
15282 SCOPE determines the scope of this command. It can be any of:
15284 nil The current buffer, respecting the restriction if any
15285 tree The subtree started with the entry at point
15286 region The entries within the active region, if any
15287 region-start-level
15288 The entries within the active region, but only those at
15289 the same level than the first one.
15290 file The current buffer, without restriction
15291 file-with-archives
15292 The current buffer, and any archives associated with it
15293 agenda All agenda files
15294 agenda-with-archives
15295 All agenda files with any archive files associated with them
15296 \(file1 file2 ...)
15297 If this is a list, all files in the list will be scanned
15299 The remaining args are treated as settings for the skipping facilities of
15300 the scanner. The following items can be given here:
15302 archive skip trees with the archive tag
15303 comment skip trees with the COMMENT keyword
15304 function or Emacs Lisp form:
15305 will be used as value for `org-agenda-skip-function', so
15306 whenever the function returns a position, FUNC will not be
15307 called for that entry and search will continue from the
15308 position returned
15310 If your function needs to retrieve the tags including inherited tags
15311 at the *current* entry, you can use the value of the variable
15312 `org-scanner-tags' which will be much faster than getting the value
15313 with `org-get-tags-at'. If your function gets properties with
15314 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15315 to t around the call to `org-entry-properties' to get the same speedup.
15316 Note that if your function moves around to retrieve tags and properties at
15317 a *different* entry, you cannot use these techniques."
15318 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15319 (not (org-region-active-p)))
15320 (let* ((org-agenda-archives-mode nil) ; just to make sure
15321 (org-agenda-skip-archived-trees (memq 'archive skip))
15322 (org-agenda-skip-comment-trees (memq 'comment skip))
15323 (org-agenda-skip-function
15324 (car (org-delete-all '(comment archive) skip)))
15325 (org-tags-match-list-sublevels t)
15326 (start-level (eq scope 'region-start-level))
15327 matcher res
15328 org-todo-keywords-for-agenda
15329 org-done-keywords-for-agenda
15330 org-todo-keyword-alist-for-agenda
15331 org-tag-alist-for-agenda
15332 org--matcher-tags-todo-only)
15334 (cond
15335 ((eq match t) (setq matcher t))
15336 ((eq match nil) (setq matcher t))
15337 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15339 (save-excursion
15340 (save-restriction
15341 (cond ((eq scope 'tree)
15342 (org-back-to-heading t)
15343 (org-narrow-to-subtree)
15344 (setq scope nil))
15345 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15346 (org-region-active-p))
15347 ;; If needed, set start-level to a string like "2"
15348 (when start-level
15349 (save-excursion
15350 (goto-char (region-beginning))
15351 (unless (org-at-heading-p) (outline-next-heading))
15352 (setq start-level (org-current-level))))
15353 (narrow-to-region (region-beginning)
15354 (save-excursion
15355 (goto-char (region-end))
15356 (unless (and (bolp) (org-at-heading-p))
15357 (outline-next-heading))
15358 (point)))
15359 (setq scope nil)))
15361 (if (not scope)
15362 (progn
15363 (org-agenda-prepare-buffers
15364 (and buffer-file-name (list buffer-file-name)))
15365 (setq res
15366 (org-scan-tags
15367 func matcher org--matcher-tags-todo-only start-level)))
15368 ;; Get the right scope
15369 (cond
15370 ((and scope (listp scope) (symbolp (car scope)))
15371 (setq scope (eval scope)))
15372 ((eq scope 'agenda)
15373 (setq scope (org-agenda-files t)))
15374 ((eq scope 'agenda-with-archives)
15375 (setq scope (org-agenda-files t))
15376 (setq scope (org-add-archive-files scope)))
15377 ((eq scope 'file)
15378 (setq scope (and buffer-file-name (list buffer-file-name))))
15379 ((eq scope 'file-with-archives)
15380 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15381 (org-agenda-prepare-buffers scope)
15382 (dolist (file scope)
15383 (with-current-buffer (org-find-base-buffer-visiting file)
15384 (org-with-wide-buffer
15385 (goto-char (point-min))
15386 (setq res
15387 (append
15389 (org-scan-tags
15390 func matcher org--matcher-tags-todo-only)))))))))
15391 res)))
15393 ;;; Properties API
15395 (defconst org-special-properties
15396 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15397 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15398 "The special properties valid in Org mode.
15399 These are properties that are not defined in the property drawer,
15400 but in some other way.")
15402 (defconst org-default-properties
15403 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15404 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15405 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15406 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15407 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15408 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15409 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15410 "Some properties that are used by Org mode for various purposes.
15411 Being in this list makes sure that they are offered for completion.")
15413 (defun org--valid-property-p (property)
15414 "Non nil when string PROPERTY is a valid property name."
15415 (not
15416 (or (equal property "")
15417 (string-match-p "\\s-" property))))
15419 (defun org--update-property-plist (key val props)
15420 "Associate KEY to VAL in alist PROPS.
15421 Modifications are made by side-effect. Return new alist."
15422 (let* ((appending (string= (substring key -1) "+"))
15423 (key (if appending (substring key 0 -1) key))
15424 (old (assoc-string key props t)))
15425 (if (not old) (cons (cons key val) props)
15426 (setcdr old (if appending (concat (cdr old) " " val) val))
15427 props)))
15429 (defun org-get-property-block (&optional beg force)
15430 "Return the (beg . end) range of the body of the property drawer.
15431 BEG is the beginning of the current subtree, or of the part
15432 before the first headline. If it is not given, it will be found.
15433 If the drawer does not exist, create it if FORCE is non-nil, or
15434 return nil."
15435 (org-with-wide-buffer
15436 (when beg (goto-char beg))
15437 (unless (org-before-first-heading-p)
15438 (let ((beg (cond (beg)
15439 ((or (not (featurep 'org-inlinetask))
15440 (org-inlinetask-in-task-p))
15441 (org-back-to-heading t))
15442 (t (org-with-limited-levels (org-back-to-heading t))))))
15443 (forward-line)
15444 (when (looking-at-p org-planning-line-re) (forward-line))
15445 (cond ((looking-at org-property-drawer-re)
15446 (forward-line)
15447 (cons (point) (progn (goto-char (match-end 0))
15448 (line-beginning-position))))
15449 (force
15450 (goto-char beg)
15451 (org-insert-property-drawer)
15452 (let ((pos (save-excursion (search-forward ":END:")
15453 (line-beginning-position))))
15454 (cons pos pos))))))))
15456 (defun org-at-property-p ()
15457 "Non-nil when point is inside a property drawer.
15458 See `org-property-re' for match data, if applicable."
15459 (save-excursion
15460 (beginning-of-line)
15461 (and (looking-at org-property-re)
15462 (let ((property-drawer (save-match-data (org-get-property-block))))
15463 (and property-drawer
15464 (>= (point) (car property-drawer))
15465 (< (point) (cdr property-drawer)))))))
15467 (defun org-property-action ()
15468 "Do an action on properties."
15469 (interactive)
15470 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15471 (let ((c (read-char-exclusive)))
15472 (cl-case c
15473 (?s (call-interactively #'org-set-property))
15474 (?d (call-interactively #'org-delete-property))
15475 (?D (call-interactively #'org-delete-property-globally))
15476 (?c (call-interactively #'org-compute-property-at-point))
15477 (otherwise (user-error "No such property action %c" c)))))
15479 (defun org-inc-effort ()
15480 "Increment the value of the effort property in the current entry."
15481 (interactive)
15482 (org-set-effort nil t))
15484 (defvar org-clock-effort) ; Defined in org-clock.el.
15485 (defvar org-clock-current-task) ; Defined in org-clock.el.
15486 (defun org-set-effort (&optional value increment)
15487 "Set the effort property of the current entry.
15488 With numerical prefix arg, use the nth allowed value, 0 stands for the
15489 10th allowed value.
15491 When INCREMENT is non-nil, set the property to the next allowed value."
15492 (interactive "P")
15493 (when (equal value 0) (setq value 10))
15494 (let* ((completion-ignore-case t)
15495 (prop org-effort-property)
15496 (cur (org-entry-get nil prop))
15497 (allowed (org-property-get-allowed-values nil prop 'table))
15498 (existing (mapcar 'list (org-property-values prop)))
15499 (heading (nth 4 (org-heading-components)))
15501 (val (cond
15502 ((stringp value) value)
15503 ((and allowed (integerp value))
15504 (or (car (nth (1- value) allowed))
15505 (car (org-last allowed))))
15506 ((and allowed increment)
15507 (or (cl-caadr (member (list cur) allowed))
15508 (user-error "Allowed effort values are not set")))
15509 (allowed
15510 (message "Select 1-9,0, [RET%s]: %s"
15511 (if cur (concat "=" cur) "")
15512 (mapconcat 'car allowed " "))
15513 (setq rpl (read-char-exclusive))
15514 (if (equal rpl ?\r)
15516 (setq rpl (- rpl ?0))
15517 (when (equal rpl 0) (setq rpl 10))
15518 (if (and (> rpl 0) (<= rpl (length allowed)))
15519 (car (nth (1- rpl) allowed))
15520 (org-completing-read "Effort: " allowed nil))))
15522 (org-completing-read
15523 (concat "Effort" (and cur (string-match "\\S-" cur)
15524 (concat " [" cur "]"))
15525 ": ")
15526 existing nil nil "" nil cur)))))
15527 (unless (equal (org-entry-get nil prop) val)
15528 (org-entry-put nil prop val))
15529 (org-refresh-property
15530 '((effort . identity)
15531 (effort-minutes . org-duration-to-minutes))
15532 val)
15533 (when (equal heading (bound-and-true-p org-clock-current-task))
15534 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15535 (org-clock-update-mode-line))
15536 (message "%s is now %s" prop val)))
15538 (defun org-entry-properties (&optional pom which)
15539 "Get all properties of the current entry.
15541 When POM is a buffer position, get all properties from the entry
15542 there instead.
15544 This includes the TODO keyword, the tags, time strings for
15545 deadline, scheduled, and clocking, and any additional properties
15546 defined in the entry.
15548 If WHICH is nil or `all', get all properties. If WHICH is
15549 `special' or `standard', only get that subclass. If WHICH is
15550 a string, only get that property.
15552 Return value is an alist. Keys are properties, as upcased
15553 strings."
15554 (org-with-point-at pom
15555 (when (and (derived-mode-p 'org-mode)
15556 (ignore-errors (org-back-to-heading t)))
15557 (catch 'exit
15558 (let* ((beg (point))
15559 (specific (and (stringp which) (upcase which)))
15560 (which (cond ((not specific) which)
15561 ((member specific org-special-properties) 'special)
15562 (t 'standard)))
15563 props)
15564 ;; Get the special properties, like TODO and TAGS.
15565 (when (memq which '(nil all special))
15566 (when (or (not specific) (string= specific "CLOCKSUM"))
15567 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15568 (when clocksum
15569 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15570 props)))
15571 (when specific (throw 'exit props)))
15572 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15573 (let ((clocksumt (get-text-property (point)
15574 :org-clock-minutes-today)))
15575 (when clocksumt
15576 (push (cons "CLOCKSUM_T"
15577 (org-duration-from-minutes clocksumt))
15578 props)))
15579 (when specific (throw 'exit props)))
15580 (when (or (not specific) (string= specific "ITEM"))
15581 (let ((case-fold-search nil))
15582 (when (looking-at org-complex-heading-regexp)
15583 (push (cons "ITEM"
15584 (let ((title (match-string-no-properties 4)))
15585 (if (org-string-nw-p title)
15586 (org-remove-tabs title)
15587 "")))
15588 props)))
15589 (when specific (throw 'exit props)))
15590 (when (or (not specific) (string= specific "TODO"))
15591 (let ((case-fold-search nil))
15592 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15593 (push (cons "TODO" (match-string-no-properties 2)) props)))
15594 (when specific (throw 'exit props)))
15595 (when (or (not specific) (string= specific "PRIORITY"))
15596 (push (cons "PRIORITY"
15597 (if (looking-at org-priority-regexp)
15598 (match-string-no-properties 2)
15599 (char-to-string org-default-priority)))
15600 props)
15601 (when specific (throw 'exit props)))
15602 (when (or (not specific) (string= specific "FILE"))
15603 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15604 props)
15605 (when specific (throw 'exit props)))
15606 (when (or (not specific) (string= specific "TAGS"))
15607 (let ((value (org-string-nw-p (org-get-tags-string))))
15608 (when value (push (cons "TAGS" value) props)))
15609 (when specific (throw 'exit props)))
15610 (when (or (not specific) (string= specific "ALLTAGS"))
15611 (let ((value (org-get-tags-at)))
15612 (when value
15613 (push (cons "ALLTAGS"
15614 (format ":%s:" (mapconcat #'identity value ":")))
15615 props)))
15616 (when specific (throw 'exit props)))
15617 (when (or (not specific) (string= specific "BLOCKED"))
15618 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15619 (when specific (throw 'exit props)))
15620 (when (or (not specific)
15621 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15622 (forward-line)
15623 (when (looking-at-p org-planning-line-re)
15624 (end-of-line)
15625 (let ((bol (line-beginning-position))
15626 ;; Backward compatibility: time keywords used to
15627 ;; be configurable (before 8.3). Make sure we
15628 ;; get the correct keyword.
15629 (key-assoc `(("CLOSED" . ,org-closed-string)
15630 ("DEADLINE" . ,org-deadline-string)
15631 ("SCHEDULED" . ,org-scheduled-string))))
15632 (dolist (pair (if specific (list (assoc specific key-assoc))
15633 key-assoc))
15634 (save-excursion
15635 (when (search-backward (cdr pair) bol t)
15636 (goto-char (match-end 0))
15637 (skip-chars-forward " \t")
15638 (and (looking-at org-ts-regexp-both)
15639 (push (cons (car pair)
15640 (match-string-no-properties 0))
15641 props)))))))
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific)
15644 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15645 (let ((find-ts
15646 (lambda (end ts)
15647 ;; Fix next time-stamp before END. TS is the
15648 ;; list of time-stamps found so far.
15649 (let ((ts ts)
15650 (regexp (cond
15651 ((string= specific "TIMESTAMP")
15652 org-ts-regexp)
15653 ((string= specific "TIMESTAMP_IA")
15654 org-ts-regexp-inactive)
15655 ((assoc "TIMESTAMP_IA" ts)
15656 org-ts-regexp)
15657 ((assoc "TIMESTAMP" ts)
15658 org-ts-regexp-inactive)
15659 (t org-ts-regexp-both))))
15660 (catch 'next
15661 (while (re-search-forward regexp end t)
15662 (backward-char)
15663 (let ((object (org-element-context)))
15664 ;; Accept to match timestamps in node
15665 ;; properties, too.
15666 (when (memq (org-element-type object)
15667 '(node-property timestamp))
15668 (let ((type
15669 (org-element-property :type object)))
15670 (cond
15671 ((and (memq type '(active active-range))
15672 (not (equal specific "TIMESTAMP_IA")))
15673 (unless (assoc "TIMESTAMP" ts)
15674 (push (cons "TIMESTAMP"
15675 (org-element-property
15676 :raw-value object))
15678 (when specific (throw 'exit ts))))
15679 ((and (memq type '(inactive inactive-range))
15680 (not (string= specific "TIMESTAMP")))
15681 (unless (assoc "TIMESTAMP_IA" ts)
15682 (push (cons "TIMESTAMP_IA"
15683 (org-element-property
15684 :raw-value object))
15686 (when specific (throw 'exit ts))))))
15687 ;; Both timestamp types are found,
15688 ;; move to next part.
15689 (when (= (length ts) 2) (throw 'next ts)))))
15690 ts)))))
15691 (goto-char beg)
15692 ;; First look for timestamps within headline.
15693 (let ((ts (funcall find-ts (line-end-position) nil)))
15694 (if (= (length ts) 2) (setq props (nconc ts props))
15695 ;; Then find timestamps in the section, skipping
15696 ;; planning line.
15697 (let ((end (save-excursion (outline-next-heading))))
15698 (forward-line)
15699 (when (looking-at-p org-planning-line-re) (forward-line))
15700 (setq props (nconc (funcall find-ts end ts) props))))))))
15701 ;; Get the standard properties, like :PROP:.
15702 (when (memq which '(nil all standard))
15703 ;; If we are looking after a specific property, delegate
15704 ;; to `org-entry-get', which is faster. However, make an
15705 ;; exception for "CATEGORY", since it can be also set
15706 ;; through keywords (i.e. #+CATEGORY).
15707 (if (and specific (not (equal specific "CATEGORY")))
15708 (let ((value (org-entry-get beg specific nil t)))
15709 (throw 'exit (and value (list (cons specific value)))))
15710 (let ((range (org-get-property-block beg)))
15711 (when range
15712 (let ((end (cdr range)) seen-base)
15713 (goto-char (car range))
15714 ;; Unlike to `org--update-property-plist', we
15715 ;; handle the case where base values is found
15716 ;; after its extension. We also forbid standard
15717 ;; properties to be named as special properties.
15718 (while (re-search-forward org-property-re end t)
15719 (let* ((key (upcase (match-string-no-properties 2)))
15720 (extendp (string-match-p "\\+\\'" key))
15721 (key-base (if extendp (substring key 0 -1) key))
15722 (value (match-string-no-properties 3)))
15723 (cond
15724 ((member-ignore-case key-base org-special-properties))
15725 (extendp
15726 (setq props
15727 (org--update-property-plist key value props)))
15728 ((member key seen-base))
15729 (t (push key seen-base)
15730 (let ((p (assoc-string key props t)))
15731 (if p (setcdr p (concat value " " (cdr p)))
15732 (push (cons key value) props))))))))))))
15733 (unless (assoc "CATEGORY" props)
15734 (push (cons "CATEGORY" (org-get-category beg)) props)
15735 (when (string= specific "CATEGORY") (throw 'exit props)))
15736 ;; Return value.
15737 props)))))
15739 (defun org--property-local-values (property literal-nil)
15740 "Return value for PROPERTY in current entry.
15741 Value is a list whose car is the base value for PROPERTY and cdr
15742 a list of accumulated values. Return nil if neither is found in
15743 the entry. Also return nil when PROPERTY is set to \"nil\",
15744 unless LITERAL-NIL is non-nil."
15745 (let ((range (org-get-property-block)))
15746 (when range
15747 (goto-char (car range))
15748 (let* ((case-fold-search t)
15749 (end (cdr range))
15750 (value
15751 ;; Base value.
15752 (save-excursion
15753 (let ((v (and (re-search-forward
15754 (org-re-property property nil t) end t)
15755 (match-string-no-properties 3))))
15756 (list (if literal-nil v (org-not-nil v)))))))
15757 ;; Find additional values.
15758 (let* ((property+ (org-re-property (concat property "+") nil t)))
15759 (while (re-search-forward property+ end t)
15760 (push (match-string-no-properties 3) value)))
15761 ;; Return final values.
15762 (and (not (equal value '(nil))) (nreverse value))))))
15764 (defun org--property-global-value (property literal-nil)
15765 "Return value for PROPERTY in current buffer.
15766 Return value is a string. Return nil if property is not set
15767 globally. Also return nil when PROPERTY is set to \"nil\",
15768 unless LITERAL-NIL is non-nil."
15769 (let ((global
15770 (cdr (or (assoc-string property org-file-properties t)
15771 (assoc-string property org-global-properties t)
15772 (assoc-string property org-global-properties-fixed t)))))
15773 (if literal-nil global (org-not-nil global))))
15775 (defun org-entry-get (pom property &optional inherit literal-nil)
15776 "Get value of PROPERTY for entry or content at point-or-marker POM.
15778 If INHERIT is non-nil and the entry does not have the property,
15779 then also check higher levels of the hierarchy. If INHERIT is
15780 the symbol `selective', use inheritance only if the setting in
15781 `org-use-property-inheritance' selects PROPERTY for inheritance.
15783 If the property is present but empty, the return value is the
15784 empty string. If the property is not present at all, nil is
15785 returned. In any other case, return the value as a string.
15786 Search is case-insensitive.
15788 If LITERAL-NIL is set, return the string value \"nil\" as
15789 a string, do not interpret it as the list atom nil. This is used
15790 for inheritance when a \"nil\" value can supersede a non-nil
15791 value higher up the hierarchy."
15792 (org-with-point-at pom
15793 (cond
15794 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15795 ;; We need a special property. Use `org-entry-properties' to
15796 ;; retrieve it, but specify the wanted property.
15797 (cdr (assoc-string property (org-entry-properties nil property))))
15798 ((and inherit
15799 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15800 (org-entry-get-with-inheritance property literal-nil))
15802 (let* ((local (org--property-local-values property literal-nil))
15803 (value (and local (mapconcat #'identity (delq nil local) " "))))
15804 (if literal-nil value (org-not-nil value)))))))
15806 (defun org-property-or-variable-value (var &optional inherit)
15807 "Check if there is a property fixing the value of VAR.
15808 If yes, return this value. If not, return the current value of the variable."
15809 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15810 (if (and prop (stringp prop) (string-match "\\S-" prop))
15811 (read prop)
15812 (symbol-value var))))
15814 (defun org-entry-delete (pom property)
15815 "Delete PROPERTY from entry at point-or-marker POM.
15816 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15817 non-nil when a property was removed."
15818 (org-with-point-at pom
15819 (pcase (org-get-property-block)
15820 (`(,begin . ,origin)
15821 (let* ((end (copy-marker origin))
15822 (re (org-re-property
15823 (concat (regexp-quote property) "\\+?") t t)))
15824 (goto-char begin)
15825 (while (re-search-forward re end t)
15826 (delete-region (match-beginning 0) (line-beginning-position 2)))
15827 ;; If drawer is empty, remove it altogether.
15828 (when (= begin end)
15829 (delete-region (line-beginning-position 0)
15830 (line-beginning-position 2)))
15831 ;; Return non-nil if some property was removed.
15832 (prog1 (/= end origin) (set-marker end nil))))
15833 (_ nil))))
15835 ;; Multi-values properties are properties that contain multiple values
15836 ;; These values are assumed to be single words, separated by whitespace.
15837 (defun org-entry-add-to-multivalued-property (pom property value)
15838 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15839 (let* ((old (org-entry-get pom property))
15840 (values (and old (split-string old))))
15841 (setq value (org-entry-protect-space value))
15842 (unless (member value values)
15843 (setq values (append values (list value)))
15844 (org-entry-put pom property (mapconcat #'identity values " ")))))
15846 (defun org-entry-remove-from-multivalued-property (pom property value)
15847 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15848 (let* ((old (org-entry-get pom property))
15849 (values (and old (split-string old))))
15850 (setq value (org-entry-protect-space value))
15851 (when (member value values)
15852 (setq values (delete value values))
15853 (org-entry-put pom property (mapconcat #'identity values " ")))))
15855 (defun org-entry-member-in-multivalued-property (pom property value)
15856 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15857 (let* ((old (org-entry-get pom property))
15858 (values (and old (split-string old))))
15859 (setq value (org-entry-protect-space value))
15860 (member value values)))
15862 (defun org-entry-get-multivalued-property (pom property)
15863 "Return a list of values in a multivalued property."
15864 (let* ((value (org-entry-get pom property))
15865 (values (and value (split-string value))))
15866 (mapcar #'org-entry-restore-space values)))
15868 (defun org-entry-put-multivalued-property (pom property &rest values)
15869 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15870 VALUES should be a list of strings. Spaces will be protected."
15871 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15872 (let* ((value (org-entry-get pom property))
15873 (values (and value (split-string value))))
15874 (mapcar #'org-entry-restore-space values)))
15876 (defun org-entry-protect-space (s)
15877 "Protect spaces and newline in string S."
15878 (while (string-match " " s)
15879 (setq s (replace-match "%20" t t s)))
15880 (while (string-match "\n" s)
15881 (setq s (replace-match "%0A" t t s)))
15884 (defun org-entry-restore-space (s)
15885 "Restore spaces and newline in string S."
15886 (while (string-match "%20" s)
15887 (setq s (replace-match " " t t s)))
15888 (while (string-match "%0A" s)
15889 (setq s (replace-match "\n" t t s)))
15892 (defvar org-entry-property-inherited-from (make-marker)
15893 "Marker pointing to the entry from where a property was inherited.
15894 Each call to `org-entry-get-with-inheritance' will set this marker to the
15895 location of the entry where the inheritance search matched. If there was
15896 no match, the marker will point nowhere.
15897 Note that also `org-entry-get' calls this function, if the INHERIT flag
15898 is set.")
15900 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15901 "Get PROPERTY of entry or content at point, search higher levels if needed.
15902 The search will stop at the first ancestor which has the property defined.
15903 If the value found is \"nil\", return nil to show that the property
15904 should be considered as undefined (this is the meaning of nil here).
15905 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15906 (move-marker org-entry-property-inherited-from nil)
15907 (org-with-wide-buffer
15908 (let (value)
15909 (catch 'exit
15910 (while t
15911 (let ((v (org--property-local-values property literal-nil)))
15912 (when v
15913 (setq value
15914 (concat (mapconcat #'identity (delq nil v) " ")
15915 (and value " ")
15916 value)))
15917 (cond
15918 ((car v)
15919 (org-back-to-heading t)
15920 (move-marker org-entry-property-inherited-from (point))
15921 (throw 'exit nil))
15922 ((org-up-heading-safe))
15924 (let ((global (org--property-global-value property literal-nil)))
15925 (cond ((not global))
15926 (value (setq value (concat global " " value)))
15927 (t (setq value global))))
15928 (throw 'exit nil))))))
15929 (if literal-nil value (org-not-nil value)))))
15931 (defvar org-property-changed-functions nil
15932 "Hook called when the value of a property has changed.
15933 Each hook function should accept two arguments, the name of the property
15934 and the new value.")
15936 (defun org-entry-put (pom property value)
15937 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15939 If the value is nil, it is converted to the empty string. If it
15940 is not a string, an error is raised. Also raise an error on
15941 invalid property names.
15943 PROPERTY can be any regular property (see
15944 `org-special-properties'). It can also be \"TODO\",
15945 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15947 For the last two properties, VALUE may have any of the special
15948 values \"earlier\" and \"later\". The function then increases or
15949 decreases scheduled or deadline date by one day."
15950 (cond ((null value) (setq value ""))
15951 ((not (stringp value)) (error "Properties values should be strings"))
15952 ((not (org--valid-property-p property))
15953 (user-error "Invalid property name: \"%s\"" property)))
15954 (org-with-point-at pom
15955 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15956 (org-back-to-heading t)
15957 (org-with-limited-levels (org-back-to-heading t)))
15958 (let ((beg (point)))
15959 (cond
15960 ((equal property "TODO")
15961 (cond ((not (org-string-nw-p value)) (setq value 'none))
15962 ((not (member value org-todo-keywords-1))
15963 (user-error "\"%s\" is not a valid TODO state" value)))
15964 (org-todo value)
15965 (org-set-tags nil 'align))
15966 ((equal property "PRIORITY")
15967 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15968 (org-set-tags nil 'align))
15969 ((equal property "SCHEDULED")
15970 (forward-line)
15971 (if (and (looking-at-p org-planning-line-re)
15972 (re-search-forward
15973 org-scheduled-time-regexp (line-end-position) t))
15974 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15975 ((string= value "later") (org-timestamp-change 1 'day))
15976 ((string= value "") (org-schedule '(4)))
15977 (t (org-schedule nil value)))
15978 (if (member value '("earlier" "later" ""))
15979 (call-interactively #'org-schedule)
15980 (org-schedule nil value))))
15981 ((equal property "DEADLINE")
15982 (forward-line)
15983 (if (and (looking-at-p org-planning-line-re)
15984 (re-search-forward
15985 org-deadline-time-regexp (line-end-position) t))
15986 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15987 ((string= value "later") (org-timestamp-change 1 'day))
15988 ((string= value "") (org-deadline '(4)))
15989 (t (org-deadline nil value)))
15990 (if (member value '("earlier" "later" ""))
15991 (call-interactively #'org-deadline)
15992 (org-deadline nil value))))
15993 ((member property org-special-properties)
15994 (error "The %s property cannot be set with `org-entry-put'" property))
15996 (let* ((range (org-get-property-block beg 'force))
15997 (end (cdr range))
15998 (case-fold-search t))
15999 (goto-char (car range))
16000 (if (re-search-forward (org-re-property property nil t) end t)
16001 (progn (delete-region (match-beginning 0) (match-end 0))
16002 (goto-char (match-beginning 0)))
16003 (goto-char end)
16004 (insert "\n")
16005 (backward-char))
16006 (insert ":" property ":")
16007 (when value (insert " " value))
16008 (org-indent-line)))))
16009 (run-hook-with-args 'org-property-changed-functions property value)))
16011 (defun org-buffer-property-keys
16012 (&optional specials defaults columns ignore-malformed)
16013 "Get all property keys in the current buffer.
16015 When SPECIALS is non-nil, also list the special properties that
16016 reflect things like tags and TODO state.
16018 When DEFAULTS is non-nil, also include properties that has
16019 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16020 DESCRIPTION, LOCATION, and LOGGING and others.
16022 When COLUMNS in non-nil, also include property names given in
16023 COLUMN formats in the current buffer.
16025 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16026 automatically performed, such drawers will be silently ignored."
16027 (let ((case-fold-search t)
16028 (props (append
16029 (and specials org-special-properties)
16030 (and defaults (cons org-effort-property org-default-properties))
16031 nil)))
16032 (org-with-wide-buffer
16033 (goto-char (point-min))
16034 (while (re-search-forward org-property-start-re nil t)
16035 (let ((range (org-get-property-block)))
16036 (catch 'skip
16037 (unless range
16038 (when (and (not ignore-malformed)
16039 (not (org-before-first-heading-p))
16040 (y-or-n-p (format "Malformed drawer at %d, repair?"
16041 (line-beginning-position))))
16042 (org-get-property-block nil t))
16043 (throw 'skip nil))
16044 (goto-char (car range))
16045 (let ((begin (car range))
16046 (end (cdr range)))
16047 ;; Make sure that found property block is not located
16048 ;; before current point, as it would generate an infloop.
16049 ;; It can happen, for example, in the following
16050 ;; situation:
16052 ;; * Headline
16053 ;; :PROPERTIES:
16054 ;; ...
16055 ;; :END:
16056 ;; *************** Inlinetask
16057 ;; #+BEGIN_EXAMPLE
16058 ;; :PROPERTIES:
16059 ;; #+END_EXAMPLE
16061 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16062 (while (< (point) end)
16063 (let ((p (progn (looking-at org-property-re)
16064 (match-string-no-properties 2))))
16065 ;; Only add true property name, not extension symbol.
16066 (push (if (not (string-match-p "\\+\\'" p)) p
16067 (substring p 0 -1))
16068 props))
16069 (forward-line))))
16070 (outline-next-heading)))
16071 (when columns
16072 (goto-char (point-min))
16073 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16074 (let ((element (org-element-at-point)))
16075 (when (memq (org-element-type element) '(keyword node-property))
16076 (let ((value (org-element-property :value element))
16077 (start 0))
16078 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16079 \\(?:{[^}]+}\\)?"
16080 value start)
16081 (setq start (match-end 0))
16082 (let ((p (match-string-no-properties 1 value)))
16083 (unless (member-ignore-case p org-special-properties)
16084 (push p props))))))))))
16085 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16087 (defun org-property-values (key)
16088 "List all non-nil values of property KEY in current buffer."
16089 (org-with-wide-buffer
16090 (goto-char (point-min))
16091 (let ((case-fold-search t)
16092 (re (org-re-property key))
16093 values)
16094 (while (re-search-forward re nil t)
16095 (push (org-entry-get (point) key) values))
16096 (delete-dups values))))
16098 (defun org-insert-property-drawer ()
16099 "Insert a property drawer into the current entry."
16100 (org-with-wide-buffer
16101 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16102 (org-back-to-heading t)
16103 (org-with-limited-levels (org-back-to-heading t)))
16104 (forward-line)
16105 (when (looking-at-p org-planning-line-re) (forward-line))
16106 (unless (looking-at-p org-property-drawer-re)
16107 ;; Make sure we start editing a line from current entry, not from
16108 ;; next one. It prevents extending text properties or overlays
16109 ;; belonging to the latter.
16110 (when (bolp) (backward-char))
16111 (let ((begin (1+ (point)))
16112 (inhibit-read-only t))
16113 (insert "\n:PROPERTIES:\n:END:")
16114 (when (eobp) (insert "\n"))
16115 (org-indent-region begin (point))))))
16117 (defun org-insert-drawer (&optional arg drawer)
16118 "Insert a drawer at point.
16120 When optional argument ARG is non-nil, insert a property drawer.
16122 Optional argument DRAWER, when non-nil, is a string representing
16123 drawer's name. Otherwise, the user is prompted for a name.
16125 If a region is active, insert the drawer around that region
16126 instead.
16128 Point is left between drawer's boundaries."
16129 (interactive "P")
16130 (let* ((drawer (if arg "PROPERTIES"
16131 (or drawer (read-from-minibuffer "Drawer: ")))))
16132 (cond
16133 ;; With C-u, fall back on `org-insert-property-drawer'
16134 (arg (org-insert-property-drawer))
16135 ;; Check validity of suggested drawer's name.
16136 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16137 (user-error "Invalid drawer name"))
16138 ;; With an active region, insert a drawer at point.
16139 ((not (org-region-active-p))
16140 (progn
16141 (unless (bolp) (insert "\n"))
16142 (insert (format ":%s:\n\n:END:\n" drawer))
16143 (forward-line -2)))
16144 ;; Otherwise, insert the drawer at point
16146 (let ((rbeg (region-beginning))
16147 (rend (copy-marker (region-end))))
16148 (unwind-protect
16149 (progn
16150 (goto-char rbeg)
16151 (beginning-of-line)
16152 (when (save-excursion
16153 (re-search-forward org-outline-regexp-bol rend t))
16154 (user-error "Drawers cannot contain headlines"))
16155 ;; Position point at the beginning of the first
16156 ;; non-blank line in region. Insert drawer's opening
16157 ;; there, then indent it.
16158 (org-skip-whitespace)
16159 (beginning-of-line)
16160 (insert ":" drawer ":\n")
16161 (forward-line -1)
16162 (indent-for-tab-command)
16163 ;; Move point to the beginning of the first blank line
16164 ;; after the last non-blank line in region. Insert
16165 ;; drawer's closing, then indent it.
16166 (goto-char rend)
16167 (skip-chars-backward " \r\t\n")
16168 (insert "\n:END:")
16169 (deactivate-mark t)
16170 (indent-for-tab-command)
16171 (unless (eolp) (insert "\n")))
16172 ;; Clear marker, whatever the outcome of insertion is.
16173 (set-marker rend nil)))))))
16175 (defvar org-property-set-functions-alist nil
16176 "Property set function alist.
16177 Each entry should have the following format:
16179 (PROPERTY . READ-FUNCTION)
16181 The read function will be called with the same argument as
16182 `org-completing-read'.")
16184 (defun org-set-property-function (property)
16185 "Get the function that should be used to set PROPERTY.
16186 This is computed according to `org-property-set-functions-alist'."
16187 (or (cdr (assoc property org-property-set-functions-alist))
16188 'org-completing-read))
16190 (defun org-read-property-value (property)
16191 "Read PROPERTY value from user."
16192 (let* ((completion-ignore-case t)
16193 (allowed (org-property-get-allowed-values nil property 'table))
16194 (cur (org-entry-get nil property))
16195 (prompt (concat property " value"
16196 (if (and cur (string-match "\\S-" cur))
16197 (concat " [" cur "]") "") ": "))
16198 (set-function (org-set-property-function property))
16199 (val (if allowed
16200 (funcall set-function prompt allowed nil
16201 (not (get-text-property 0 'org-unrestricted
16202 (caar allowed))))
16203 (funcall set-function prompt
16204 (mapcar 'list (org-property-values property))
16205 nil nil "" nil cur))))
16206 (org-trim val)))
16208 (defvar org-last-set-property nil)
16209 (defvar org-last-set-property-value nil)
16210 (defun org-read-property-name ()
16211 "Read a property name."
16212 (let ((completion-ignore-case t)
16213 (default-prop (or (and (org-at-property-p)
16214 (match-string-no-properties 2))
16215 org-last-set-property)))
16216 (org-completing-read
16217 (concat "Property"
16218 (if default-prop (concat " [" default-prop "]") "")
16219 ": ")
16220 (mapcar #'list (org-buffer-property-keys nil t t))
16221 nil nil nil nil default-prop)))
16223 (defun org-set-property-and-value (use-last)
16224 "Allow to set [PROPERTY]: [value] direction from prompt.
16225 When use-default, don't even ask, just use the last
16226 \"[PROPERTY]: [value]\" string from the history."
16227 (interactive "P")
16228 (let* ((completion-ignore-case t)
16229 (pv (or (and use-last org-last-set-property-value)
16230 (org-completing-read
16231 "Enter a \"[Property]: [value]\" pair: "
16232 nil nil nil nil nil
16233 org-last-set-property-value)))
16234 prop val)
16235 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16236 (setq prop (match-string 1 pv)
16237 val (match-string 2 pv))
16238 (org-set-property prop val))))
16240 (defun org-set-property (property value)
16241 "In the current entry, set PROPERTY to VALUE.
16243 When called interactively, this will prompt for a property name, offering
16244 completion on existing and default properties. And then it will prompt
16245 for a value, offering completion either on allowed values (via an inherited
16246 xxx_ALL property) or on existing values in other instances of this property
16247 in the current file.
16249 Throw an error when trying to set a property with an invalid name."
16250 (interactive (list nil nil))
16251 (let ((property (or property (org-read-property-name))))
16252 ;; `org-entry-put' also makes the following check, but this one
16253 ;; avoids polluting `org-last-set-property' and
16254 ;; `org-last-set-property-value' needlessly.
16255 (unless (org--valid-property-p property)
16256 (user-error "Invalid property name: \"%s\"" property))
16257 (let ((value (or value (org-read-property-value property)))
16258 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16259 (setq org-last-set-property property)
16260 (setq org-last-set-property-value (concat property ": " value))
16261 ;; Possibly postprocess the inserted value:
16262 (when fn (setq value (funcall fn value)))
16263 (unless (equal (org-entry-get nil property) value)
16264 (org-entry-put nil property value)))))
16266 (defun org-find-property (property &optional value)
16267 "Find first entry in buffer that sets PROPERTY.
16269 When optional argument VALUE is non-nil, only consider an entry
16270 if it contains PROPERTY set to this value. If PROPERTY should be
16271 explicitly set to nil, use string \"nil\" for VALUE.
16273 Return position where the entry begins, or nil if there is no
16274 such entry. If narrowing is in effect, only search the visible
16275 part of the buffer."
16276 (save-excursion
16277 (goto-char (point-min))
16278 (let ((case-fold-search t)
16279 (re (org-re-property property nil (not value) value)))
16280 (catch 'exit
16281 (while (re-search-forward re nil t)
16282 (when (if value (org-at-property-p)
16283 (org-entry-get (point) property nil t))
16284 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16286 (defun org-delete-property (property)
16287 "In the current entry, delete PROPERTY."
16288 (interactive
16289 (let* ((completion-ignore-case t)
16290 (cat (org-entry-get (point) "CATEGORY"))
16291 (props0 (org-entry-properties nil 'standard))
16292 (props (if cat props0
16293 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16294 (prop (if (< 1 (length props))
16295 (completing-read "Property: " props nil t)
16296 (caar props))))
16297 (list prop)))
16298 (if (not property)
16299 (message "No property to delete in this entry")
16300 (org-entry-delete nil property)
16301 (message "Property \"%s\" deleted" property)))
16303 (defun org-delete-property-globally (property)
16304 "Remove PROPERTY globally, from all entries.
16305 This function ignores narrowing, if any."
16306 (interactive
16307 (let* ((completion-ignore-case t)
16308 (prop (completing-read
16309 "Globally remove property: "
16310 (mapcar #'list (org-buffer-property-keys)))))
16311 (list prop)))
16312 (org-with-wide-buffer
16313 (goto-char (point-min))
16314 (let ((count 0)
16315 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16316 (while (re-search-forward re nil t)
16317 (when (org-entry-delete (point) property) (cl-incf count)))
16318 (message "Property \"%s\" removed from %d entries" property count))))
16320 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16322 (defun org-compute-property-at-point ()
16323 "Compute the property at point.
16324 This looks for an enclosing column format, extracts the operator and
16325 then applies it to the property in the column format's scope."
16326 (interactive)
16327 (unless (org-at-property-p)
16328 (user-error "Not at a property"))
16329 (let ((prop (match-string-no-properties 2)))
16330 (org-columns-get-format-and-top-level)
16331 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16332 (user-error "No operator defined for property %s" prop))
16333 (org-columns-compute prop)))
16335 (defvar org-property-allowed-value-functions nil
16336 "Hook for functions supplying allowed values for a specific property.
16337 The functions must take a single argument, the name of the property, and
16338 return a flat list of allowed values. If \":ETC\" is one of
16339 the values, this means that these values are intended as defaults for
16340 completion, but that other values should be allowed too.
16341 The functions must return nil if they are not responsible for this
16342 property.")
16344 (defun org-property-get-allowed-values (pom property &optional table)
16345 "Get allowed values for the property PROPERTY.
16346 When TABLE is non-nil, return an alist that can directly be used for
16347 completion."
16348 (let (vals)
16349 (cond
16350 ((equal property "TODO")
16351 (setq vals (org-with-point-at pom
16352 (append org-todo-keywords-1 '("")))))
16353 ((equal property "PRIORITY")
16354 (let ((n org-lowest-priority))
16355 (while (>= n org-highest-priority)
16356 (push (char-to-string n) vals)
16357 (setq n (1- n)))))
16358 ((equal property "CATEGORY"))
16359 ((member property org-special-properties))
16360 ((setq vals (run-hook-with-args-until-success
16361 'org-property-allowed-value-functions property)))
16363 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16364 (when (and vals (string-match "\\S-" vals))
16365 (setq vals (car (read-from-string (concat "(" vals ")"))))
16366 (setq vals (mapcar (lambda (x)
16367 (cond ((stringp x) x)
16368 ((numberp x) (number-to-string x))
16369 ((symbolp x) (symbol-name x))
16370 (t "???")))
16371 vals)))))
16372 (when (member ":ETC" vals)
16373 (setq vals (remove ":ETC" vals))
16374 (org-add-props (car vals) '(org-unrestricted t)))
16375 (if table (mapcar 'list vals) vals)))
16377 (defun org-property-previous-allowed-value (&optional _previous)
16378 "Switch to the next allowed value for this property."
16379 (interactive)
16380 (org-property-next-allowed-value t))
16382 (defun org-property-next-allowed-value (&optional previous)
16383 "Switch to the next allowed value for this property."
16384 (interactive)
16385 (unless (org-at-property-p)
16386 (user-error "Not at a property"))
16387 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16388 (key (match-string 2))
16389 (value (match-string 3))
16390 (allowed (or (org-property-get-allowed-values (point) key)
16391 (and (member value '("[ ]" "[-]" "[X]"))
16392 '("[ ]" "[X]"))))
16393 (heading (save-match-data (nth 4 (org-heading-components))))
16394 nval)
16395 (unless allowed
16396 (user-error "Allowed values for this property have not been defined"))
16397 (when previous (setq allowed (reverse allowed)))
16398 (when (member value allowed)
16399 (setq nval (car (cdr (member value allowed)))))
16400 (setq nval (or nval (car allowed)))
16401 (when (equal nval value)
16402 (user-error "Only one allowed value for this property"))
16403 (org-at-property-p)
16404 (replace-match (concat " :" key ": " nval) t t)
16405 (org-indent-line)
16406 (beginning-of-line 1)
16407 (skip-chars-forward " \t")
16408 (when (equal prop org-effort-property)
16409 (org-refresh-property
16410 '((effort . identity)
16411 (effort-minutes . org-duration-to-minutes))
16412 nval)
16413 (when (string= org-clock-current-task heading)
16414 (setq org-clock-effort nval)
16415 (org-clock-update-mode-line)))
16416 (run-hook-with-args 'org-property-changed-functions key nval)))
16418 (defun org-find-olp (path &optional this-buffer)
16419 "Return a marker pointing to the entry at outline path OLP.
16420 If anything goes wrong, throw an error.
16421 You can wrap this call to catch the error like this:
16423 (condition-case msg
16424 (org-mobile-locate-entry (match-string 4))
16425 (error (nth 1 msg)))
16427 The return value will then be either a string with the error message,
16428 or a marker if everything is OK.
16430 If THIS-BUFFER is set, the outline path does not contain a file,
16431 only headings."
16432 (let* ((file (if this-buffer buffer-file-name (pop path)))
16433 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16434 (level 1)
16435 (lmin 1)
16436 (lmax 1)
16437 end found flevel)
16438 (unless buffer (error "File not found :%s" file))
16439 (with-current-buffer buffer
16440 (unless (derived-mode-p 'org-mode)
16441 (error "Buffer %s needs to be in Org mode" buffer))
16442 (org-with-wide-buffer
16443 (goto-char (point-min))
16444 (dolist (heading path)
16445 (let ((re (format org-complex-heading-regexp-format
16446 (regexp-quote heading)))
16447 (cnt 0))
16448 (while (re-search-forward re end t)
16449 (setq level (- (match-end 1) (match-beginning 1)))
16450 (when (and (>= level lmin) (<= level lmax))
16451 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16452 (when (= cnt 0)
16453 (error "Heading not found on level %d: %s" lmax heading))
16454 (when (> cnt 1)
16455 (error "Heading not unique on level %d: %s" lmax heading))
16456 (goto-char found)
16457 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16458 (setq end (save-excursion (org-end-of-subtree t t)))))
16459 (when (org-at-heading-p)
16460 (point-marker))))))
16462 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16463 "Find node HEADING in BUFFER.
16464 Return a marker to the heading if it was found, or nil if not.
16465 If POS-ONLY is set, return just the position instead of a marker.
16467 The heading text must match exact, but it may have a TODO keyword,
16468 a priority cookie and tags in the standard locations."
16469 (with-current-buffer (or buffer (current-buffer))
16470 (org-with-wide-buffer
16471 (goto-char (point-min))
16472 (let (case-fold-search)
16473 (when (re-search-forward
16474 (format org-complex-heading-regexp-format
16475 (regexp-quote heading)) nil t)
16476 (if pos-only
16477 (match-beginning 0)
16478 (move-marker (make-marker) (match-beginning 0))))))))
16480 (defun org-find-exact-heading-in-directory (heading &optional dir)
16481 "Find Org node headline HEADING in all .org files in directory DIR.
16482 When the target headline is found, return a marker to this location."
16483 (let ((files (directory-files (or dir default-directory)
16484 t "\\`[^.#].*\\.org\\'"))
16485 visiting m buffer)
16486 (catch 'found
16487 (dolist (file files)
16488 (message "trying %s" file)
16489 (setq visiting (org-find-base-buffer-visiting file))
16490 (setq buffer (or visiting (find-file-noselect file)))
16491 (setq m (org-find-exact-headline-in-buffer
16492 heading buffer))
16493 (when (and (not m) (not visiting)) (kill-buffer buffer))
16494 (and m (throw 'found m))))))
16496 (defun org-find-entry-with-id (ident)
16497 "Locate the entry that contains the ID property with exact value IDENT.
16498 IDENT can be a string, a symbol or a number, this function will search for
16499 the string representation of it.
16500 Return the position where this entry starts, or nil if there is no such entry."
16501 (interactive "sID: ")
16502 (let ((id (cond
16503 ((stringp ident) ident)
16504 ((symbolp ident) (symbol-name ident))
16505 ((numberp ident) (number-to-string ident))
16506 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16507 (org-with-wide-buffer (org-find-property "ID" id))))
16509 ;;;; Timestamps
16511 (defvar org-last-changed-timestamp nil)
16512 (defvar org-last-inserted-timestamp nil
16513 "The last time stamp inserted with `org-insert-time-stamp'.")
16515 (defun org-time-stamp (arg &optional inactive)
16516 "Prompt for a date/time and insert a time stamp.
16518 If the user specifies a time like HH:MM or if this command is
16519 called with at least one prefix argument, the time stamp contains
16520 the date and the time. Otherwise, only the date is included.
16522 All parts of a date not specified by the user are filled in from
16523 the timestamp at point, if any, or the current date/time
16524 otherwise.
16526 If there is already a timestamp at the cursor, it is replaced.
16528 With two universal prefix arguments, insert an active timestamp
16529 with the current time without prompting the user.
16531 When called from lisp, the timestamp is inactive if INACTIVE is
16532 non-nil."
16533 (interactive "P")
16534 (let* ((ts (cond
16535 ((org-at-date-range-p t)
16536 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16537 ((org-at-timestamp-p 'lax) (match-string 0))))
16538 ;; Default time is either the timestamp at point or today.
16539 ;; When entering a range, only the range start is considered.
16540 (default-time (if (not ts) (current-time)
16541 (apply #'encode-time (org-parse-time-string ts))))
16542 (default-input (and ts (org-get-compact-tod ts)))
16543 (repeater (and ts
16544 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16545 (match-string 0 ts)))
16546 org-time-was-given
16547 org-end-time-was-given
16548 (time
16549 (and (if (equal arg '(16)) (current-time)
16550 ;; Preserve `this-command' and `last-command'.
16551 (let ((this-command this-command)
16552 (last-command last-command))
16553 (org-read-date
16554 arg 'totime nil nil default-time default-input
16555 inactive))))))
16556 (cond
16557 ((and ts
16558 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16559 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16560 (insert "--")
16561 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16563 ;; Make sure we're on a timestamp. When in the middle of a date
16564 ;; range, move arbitrarily to range end.
16565 (unless (org-at-timestamp-p 'lax)
16566 (skip-chars-forward "-")
16567 (org-at-timestamp-p 'lax))
16568 (replace-match "")
16569 (setq org-last-changed-timestamp
16570 (org-insert-time-stamp
16571 time (or org-time-was-given arg)
16572 inactive nil nil (list org-end-time-was-given)))
16573 (when repeater
16574 (backward-char)
16575 (insert " " repeater)
16576 (setq org-last-changed-timestamp
16577 (concat (substring org-last-inserted-timestamp 0 -1)
16578 " " repeater ">")))
16579 (message "Timestamp updated"))
16580 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16581 (t (org-insert-time-stamp
16582 time (or org-time-was-given arg) inactive nil nil
16583 (list org-end-time-was-given))))))
16585 ;; FIXME: can we use this for something else, like computing time differences?
16586 (defun org-get-compact-tod (s)
16587 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16588 (let* ((t1 (match-string 1 s))
16589 (h1 (string-to-number (match-string 2 s)))
16590 (m1 (string-to-number (match-string 3 s)))
16591 (t2 (and (match-end 4) (match-string 5 s)))
16592 (h2 (and t2 (string-to-number (match-string 6 s))))
16593 (m2 (and t2 (string-to-number (match-string 7 s))))
16594 dh dm)
16595 (if (not t2)
16597 (setq dh (- h2 h1) dm (- m2 m1))
16598 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16599 (concat t1 "+" (number-to-string dh)
16600 (and (/= 0 dm) (format ":%02d" dm)))))))
16602 (defun org-time-stamp-inactive (&optional arg)
16603 "Insert an inactive time stamp.
16604 An inactive time stamp is enclosed in square brackets instead of angle
16605 brackets. It is inactive in the sense that it does not trigger agenda entries,
16606 does not link to the calendar and cannot be changed with the S-cursor keys.
16607 So these are more for recording a certain time/date."
16608 (interactive "P")
16609 (org-time-stamp arg 'inactive))
16611 (defvar org-date-ovl (make-overlay 1 1))
16612 (overlay-put org-date-ovl 'face 'org-date-selected)
16613 (delete-overlay org-date-ovl)
16615 (defvar org-ans1) ; dynamically scoped parameter
16616 (defvar org-ans2) ; dynamically scoped parameter
16618 (defvar org-plain-time-of-day-regexp) ; defined below
16620 (defvar org-overriding-default-time nil) ; dynamically scoped
16621 (defvar org-read-date-overlay nil)
16622 (defvar org-dcst nil) ; dynamically scoped
16623 (defvar org-read-date-history nil)
16624 (defvar org-read-date-final-answer nil)
16625 (defvar org-read-date-analyze-futurep nil)
16626 (defvar org-read-date-analyze-forced-year nil)
16627 (defvar org-read-date-inactive)
16629 (defvar org-read-date-minibuffer-local-map
16630 (let* ((map (make-sparse-keymap)))
16631 (set-keymap-parent map minibuffer-local-map)
16632 (org-defkey map (kbd ".")
16633 (lambda () (interactive)
16634 ;; Are we at the beginning of the prompt?
16635 (if (looking-back "^[^:]+: "
16636 (let ((inhibit-field-text-motion t))
16637 (line-beginning-position)))
16638 (org-eval-in-calendar '(calendar-goto-today))
16639 (insert "."))))
16640 (org-defkey map (kbd "C-.")
16641 (lambda () (interactive)
16642 (org-eval-in-calendar '(calendar-goto-today))))
16643 (org-defkey map [(meta shift left)]
16644 (lambda () (interactive)
16645 (org-eval-in-calendar '(calendar-backward-month 1))))
16646 (org-defkey map [(meta shift right)]
16647 (lambda () (interactive)
16648 (org-eval-in-calendar '(calendar-forward-month 1))))
16649 (org-defkey map [(meta shift up)]
16650 (lambda () (interactive)
16651 (org-eval-in-calendar '(calendar-backward-year 1))))
16652 (org-defkey map [(meta shift down)]
16653 (lambda () (interactive)
16654 (org-eval-in-calendar '(calendar-forward-year 1))))
16655 (org-defkey map [?\e (shift left)]
16656 (lambda () (interactive)
16657 (org-eval-in-calendar '(calendar-backward-month 1))))
16658 (org-defkey map [?\e (shift right)]
16659 (lambda () (interactive)
16660 (org-eval-in-calendar '(calendar-forward-month 1))))
16661 (org-defkey map [?\e (shift up)]
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(calendar-backward-year 1))))
16664 (org-defkey map [?\e (shift down)]
16665 (lambda () (interactive)
16666 (org-eval-in-calendar '(calendar-forward-year 1))))
16667 (org-defkey map [(shift up)]
16668 (lambda () (interactive)
16669 (org-eval-in-calendar '(calendar-backward-week 1))))
16670 (org-defkey map [(shift down)]
16671 (lambda () (interactive)
16672 (org-eval-in-calendar '(calendar-forward-week 1))))
16673 (org-defkey map [(shift left)]
16674 (lambda () (interactive)
16675 (org-eval-in-calendar '(calendar-backward-day 1))))
16676 (org-defkey map [(shift right)]
16677 (lambda () (interactive)
16678 (org-eval-in-calendar '(calendar-forward-day 1))))
16679 (org-defkey map "!"
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(diary-view-entries))
16682 (message "")))
16683 (org-defkey map ">"
16684 (lambda () (interactive)
16685 (org-eval-in-calendar '(calendar-scroll-left 1))))
16686 (org-defkey map "<"
16687 (lambda () (interactive)
16688 (org-eval-in-calendar '(calendar-scroll-right 1))))
16689 (org-defkey map "\C-v"
16690 (lambda () (interactive)
16691 (org-eval-in-calendar
16692 '(calendar-scroll-left-three-months 1))))
16693 (org-defkey map "\M-v"
16694 (lambda () (interactive)
16695 (org-eval-in-calendar
16696 '(calendar-scroll-right-three-months 1))))
16697 map)
16698 "Keymap for minibuffer commands when using `org-read-date'.")
16700 (defvar org-def)
16701 (defvar org-defdecode)
16702 (defvar org-with-time)
16704 (defvar calendar-setup) ; Dynamically scoped.
16705 (defun org-read-date (&optional with-time to-time from-string prompt
16706 default-time default-input inactive)
16707 "Read a date, possibly a time, and make things smooth for the user.
16708 The prompt will suggest to enter an ISO date, but you can also enter anything
16709 which will at least partially be understood by `parse-time-string'.
16710 Unrecognized parts of the date will default to the current day, month, year,
16711 hour and minute. If this command is called to replace a timestamp at point,
16712 or to enter the second timestamp of a range, the default time is taken
16713 from the existing stamp. Furthermore, the command prefers the future,
16714 so if you are giving a date where the year is not given, and the day-month
16715 combination is already past in the current year, it will assume you
16716 mean next year. For details, see the manual. A few examples:
16718 3-2-5 --> 2003-02-05
16719 feb 15 --> currentyear-02-15
16720 2/15 --> currentyear-02-15
16721 sep 12 9 --> 2009-09-12
16722 12:45 --> today 12:45
16723 22 sept 0:34 --> currentyear-09-22 0:34
16724 12 --> currentyear-currentmonth-12
16725 Fri --> nearest Friday after today
16726 -Tue --> last Tuesday
16727 etc.
16729 Furthermore you can specify a relative date by giving, as the *first* thing
16730 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16731 change in days weeks, months, years.
16732 With a single plus or minus, the date is relative to today. With a double
16733 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16734 +4d --> four days from today
16735 +4 --> same as above
16736 +2w --> two weeks from today
16737 ++5 --> five days from default date
16739 The function understands only English month and weekday abbreviations.
16741 While prompting, a calendar is popped up - you can also select the
16742 date with the mouse (button 1). The calendar shows a period of three
16743 months. To scroll it to other months, use the keys `>' and `<'.
16744 If you don't like the calendar, turn it off with
16745 (setq org-read-date-popup-calendar nil)
16747 With optional argument TO-TIME, the date will immediately be converted
16748 to an internal time.
16749 With an optional argument WITH-TIME, the prompt will suggest to
16750 also insert a time. Note that when WITH-TIME is not set, you can
16751 still enter a time, and this function will inform the calling routine
16752 about this change. The calling routine may then choose to change the
16753 format used to insert the time stamp into the buffer to include the time.
16754 With optional argument FROM-STRING, read from this string instead from
16755 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16756 the time/date that is used for everything that is not specified by the
16757 user."
16758 (require 'parse-time)
16759 (let* ((org-with-time with-time)
16760 (org-time-stamp-rounding-minutes
16761 (if (equal org-with-time '(16))
16762 '(0 0)
16763 org-time-stamp-rounding-minutes))
16764 (org-dcst org-display-custom-times)
16765 (ct (org-current-time))
16766 (org-def (or org-overriding-default-time default-time ct))
16767 (org-defdecode (decode-time org-def))
16768 (cur-frame (selected-frame))
16769 (mouse-autoselect-window nil) ; Don't let the mouse jump
16770 (calendar-setup
16771 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16772 (calendar-move-hook nil)
16773 (calendar-view-diary-initially-flag nil)
16774 (calendar-view-holidays-initially-flag nil)
16775 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16776 ;; Rationalize `org-def' and `org-defdecode', if required.
16777 (when (< (nth 2 org-defdecode) org-extend-today-until)
16778 (setf (nth 2 org-defdecode) -1)
16779 (setf (nth 1 org-defdecode) 59)
16780 (setq org-def (apply #'encode-time org-defdecode))
16781 (setq org-defdecode (decode-time org-def)))
16782 (let* ((timestr (format-time-string
16783 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16784 org-def))
16785 (prompt (concat (if prompt (concat prompt " ") "")
16786 (format "Date+time [%s]: " timestr))))
16787 (cond
16788 (from-string (setq ans from-string))
16789 (org-read-date-popup-calendar
16790 (save-excursion
16791 (save-window-excursion
16792 (calendar)
16793 (when (eq calendar-setup 'calendar-only)
16794 (setq cal-frame
16795 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16796 (select-frame cal-frame))
16797 (org-eval-in-calendar '(setq cursor-type nil) t)
16798 (unwind-protect
16799 (progn
16800 (calendar-forward-day (- (time-to-days org-def)
16801 (calendar-absolute-from-gregorian
16802 (calendar-current-date))))
16803 (org-eval-in-calendar nil t)
16804 (let* ((old-map (current-local-map))
16805 (map (copy-keymap calendar-mode-map))
16806 (minibuffer-local-map
16807 (copy-keymap org-read-date-minibuffer-local-map)))
16808 (org-defkey map (kbd "RET") 'org-calendar-select)
16809 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16810 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16811 (unwind-protect
16812 (progn
16813 (use-local-map map)
16814 (setq org-read-date-inactive inactive)
16815 (add-hook 'post-command-hook 'org-read-date-display)
16816 (setq org-ans0
16817 (read-string prompt
16818 default-input
16819 'org-read-date-history
16820 nil))
16821 ;; org-ans0: from prompt
16822 ;; org-ans1: from mouse click
16823 ;; org-ans2: from calendar motion
16824 (setq ans
16825 (concat org-ans0 " " (or org-ans1 org-ans2))))
16826 (remove-hook 'post-command-hook 'org-read-date-display)
16827 (use-local-map old-map)
16828 (when org-read-date-overlay
16829 (delete-overlay org-read-date-overlay)
16830 (setq org-read-date-overlay nil)))))
16831 (bury-buffer "*Calendar*")
16832 (when cal-frame
16833 (delete-frame cal-frame)
16834 (select-frame-set-input-focus cur-frame))))))
16836 (t ; Naked prompt only
16837 (unwind-protect
16838 (setq ans (read-string prompt default-input
16839 'org-read-date-history timestr))
16840 (when org-read-date-overlay
16841 (delete-overlay org-read-date-overlay)
16842 (setq org-read-date-overlay nil))))))
16844 (setq final (org-read-date-analyze ans org-def org-defdecode))
16846 (when org-read-date-analyze-forced-year
16847 (message "Year was forced into %s"
16848 (if org-read-date-force-compatible-dates
16849 "compatible range (1970-2037)"
16850 "range representable on this machine"))
16851 (ding))
16853 ;; One round trip to get rid of 34th of August and stuff like that....
16854 (setq final (decode-time (apply 'encode-time final)))
16856 (setq org-read-date-final-answer ans)
16858 (if to-time
16859 (apply 'encode-time final)
16860 (if (and (boundp 'org-time-was-given) org-time-was-given)
16861 (format "%04d-%02d-%02d %02d:%02d"
16862 (nth 5 final) (nth 4 final) (nth 3 final)
16863 (nth 2 final) (nth 1 final))
16864 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16866 (defun org-read-date-display ()
16867 "Display the current date prompt interpretation in the minibuffer."
16868 (when org-read-date-display-live
16869 (when org-read-date-overlay
16870 (delete-overlay org-read-date-overlay))
16871 (when (minibufferp (current-buffer))
16872 (save-excursion
16873 (end-of-line 1)
16874 (while (not (equal (buffer-substring
16875 (max (point-min) (- (point) 4)) (point))
16876 " "))
16877 (insert " ")))
16878 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16879 " " (or org-ans1 org-ans2)))
16880 (org-end-time-was-given nil)
16881 (f (org-read-date-analyze ans org-def org-defdecode))
16882 (fmts (if org-dcst
16883 org-time-stamp-custom-formats
16884 org-time-stamp-formats))
16885 (fmt (if (or org-with-time
16886 (and (boundp 'org-time-was-given) org-time-was-given))
16887 (cdr fmts)
16888 (car fmts)))
16889 (txt (format-time-string fmt (apply 'encode-time f)))
16890 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16891 (txt (concat "=> " txt)))
16892 (when (and org-end-time-was-given
16893 (string-match org-plain-time-of-day-regexp txt))
16894 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16895 org-end-time-was-given
16896 (substring txt (match-end 0)))))
16897 (when org-read-date-analyze-futurep
16898 (setq txt (concat txt " (=>F)")))
16899 (setq org-read-date-overlay
16900 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16901 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16903 (defun org-read-date-analyze (ans def defdecode)
16904 "Analyze the combined answer of the date prompt."
16905 ;; FIXME: cleanup and comment
16906 ;; Pass `current-time' result to `decode-time' (instead of calling
16907 ;; without arguments) so that only `current-time' has to be
16908 ;; overridden in tests.
16909 (let ((org-def def)
16910 (org-defdecode defdecode)
16911 (nowdecode (decode-time (current-time)))
16912 delta deltan deltaw deltadef year month day
16913 hour minute second wday pm h2 m2 tl wday1
16914 iso-year iso-weekday iso-week iso-date futurep kill-year)
16915 (setq org-read-date-analyze-futurep nil
16916 org-read-date-analyze-forced-year nil)
16917 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16918 (setq ans "+0"))
16920 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16921 (setq ans (replace-match "" t t ans)
16922 deltan (car delta)
16923 deltaw (nth 1 delta)
16924 deltadef (nth 2 delta)))
16926 ;; Check if there is an iso week date in there. If yes, store the
16927 ;; info and postpone interpreting it until the rest of the parsing
16928 ;; is done.
16929 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16930 (setq iso-year (when (match-end 1)
16931 (org-small-year-to-year
16932 (string-to-number (match-string 1 ans))))
16933 iso-weekday (when (match-end 3)
16934 (string-to-number (match-string 3 ans)))
16935 iso-week (string-to-number (match-string 2 ans)))
16936 (setq ans (replace-match "" t t ans)))
16938 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16939 (when (string-match
16940 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16941 (setq year (if (match-end 2)
16942 (string-to-number (match-string 2 ans))
16943 (progn (setq kill-year t)
16944 (string-to-number (format-time-string "%Y"))))
16945 month (string-to-number (match-string 3 ans))
16946 day (string-to-number (match-string 4 ans)))
16947 (setq year (org-small-year-to-year year))
16948 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16949 t nil ans)))
16951 ;; Help matching dotted european dates
16952 (when (string-match
16953 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16954 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16955 (setq kill-year t)
16956 (string-to-number (format-time-string "%Y")))
16957 day (string-to-number (match-string 1 ans))
16958 month (string-to-number (match-string 2 ans))
16959 ans (replace-match (format "%04d-%02d-%02d" year month day)
16960 t nil ans)))
16962 ;; Help matching american dates, like 5/30 or 5/30/7
16963 (when (string-match
16964 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16965 (setq year (if (match-end 4)
16966 (string-to-number (match-string 4 ans))
16967 (progn (setq kill-year t)
16968 (string-to-number (format-time-string "%Y"))))
16969 month (string-to-number (match-string 1 ans))
16970 day (string-to-number (match-string 2 ans)))
16971 (setq year (org-small-year-to-year year))
16972 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16973 t nil ans)))
16974 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16975 ;; If there is a time with am/pm, and *no* time without it, we convert
16976 ;; so that matching will be successful.
16977 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16978 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16979 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16980 (setq hour (string-to-number (match-string 1 ans))
16981 minute (if (match-end 3)
16982 (string-to-number (match-string 3 ans))
16984 pm (equal ?p
16985 (string-to-char (downcase (match-string 4 ans)))))
16986 (if (and (= hour 12) (not pm))
16987 (setq hour 0)
16988 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16989 (setq ans (replace-match (format "%02d:%02d" hour minute)
16990 t t ans))))
16992 ;; Check if a time range is given as a duration
16993 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16994 (setq hour (string-to-number (match-string 1 ans))
16995 h2 (+ hour (string-to-number (match-string 3 ans)))
16996 minute (string-to-number (match-string 2 ans))
16997 m2 (+ minute (if (match-end 5) (string-to-number
16998 (match-string 5 ans))0)))
16999 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17000 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17001 t t ans)))
17003 ;; Check if there is a time range
17004 (when (boundp 'org-end-time-was-given)
17005 (setq org-time-was-given nil)
17006 (when (and (string-match org-plain-time-of-day-regexp ans)
17007 (match-end 8))
17008 (setq org-end-time-was-given (match-string 8 ans))
17009 (setq ans (concat (substring ans 0 (match-beginning 7))
17010 (substring ans (match-end 7))))))
17012 (setq tl (parse-time-string ans)
17013 day (or (nth 3 tl) (nth 3 org-defdecode))
17014 month
17015 (cond ((nth 4 tl))
17016 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17017 ;; Day was specified. Make sure DAY+MONTH
17018 ;; combination happens in the future.
17019 ((nth 3 tl)
17020 (setq futurep t)
17021 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17022 (nth 4 nowdecode)))
17023 (t (nth 4 org-defdecode)))
17024 year
17025 (cond ((and (not kill-year) (nth 5 tl)))
17026 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17027 ;; Month was guessed in the future and is at least
17028 ;; equal to NOWDECODE's. Fix year accordingly.
17029 (futurep
17030 (if (or (> month (nth 4 nowdecode))
17031 (>= day (nth 3 nowdecode)))
17032 (nth 5 nowdecode)
17033 (1+ (nth 5 nowdecode))))
17034 ;; Month was specified. Make sure MONTH+YEAR
17035 ;; combination happens in the future.
17036 ((nth 4 tl)
17037 (setq futurep t)
17038 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17039 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17040 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17041 (t (nth 5 nowdecode))))
17042 (t (nth 5 org-defdecode)))
17043 hour (or (nth 2 tl) (nth 2 org-defdecode))
17044 minute (or (nth 1 tl) (nth 1 org-defdecode))
17045 second (or (nth 0 tl) 0)
17046 wday (nth 6 tl))
17048 (when (and (eq org-read-date-prefer-future 'time)
17049 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17050 (equal day (nth 3 nowdecode))
17051 (equal month (nth 4 nowdecode))
17052 (equal year (nth 5 nowdecode))
17053 (nth 2 tl)
17054 (or (< (nth 2 tl) (nth 2 nowdecode))
17055 (and (= (nth 2 tl) (nth 2 nowdecode))
17056 (nth 1 tl)
17057 (< (nth 1 tl) (nth 1 nowdecode)))))
17058 (setq day (1+ day)
17059 futurep t))
17061 ;; Special date definitions below
17062 (cond
17063 (iso-week
17064 ;; There was an iso week
17065 (require 'cal-iso)
17066 (setq futurep nil)
17067 (setq year (or iso-year year)
17068 day (or iso-weekday wday 1)
17069 wday nil ; to make sure that the trigger below does not match
17070 iso-date (calendar-gregorian-from-absolute
17071 (calendar-iso-to-absolute
17072 (list iso-week day year))))
17073 ; FIXME: Should we also push ISO weeks into the future?
17074 ; (when (and org-read-date-prefer-future
17075 ; (not iso-year)
17076 ; (< (calendar-absolute-from-gregorian iso-date)
17077 ; (time-to-days (current-time))))
17078 ; (setq year (1+ year)
17079 ; iso-date (calendar-gregorian-from-absolute
17080 ; (calendar-iso-to-absolute
17081 ; (list iso-week day year)))))
17082 (setq month (car iso-date)
17083 year (nth 2 iso-date)
17084 day (nth 1 iso-date)))
17085 (deltan
17086 (setq futurep nil)
17087 (unless deltadef
17088 ;; Pass `current-time' result to `decode-time' (instead of
17089 ;; calling without arguments) so that only `current-time' has
17090 ;; to be overridden in tests.
17091 (let ((now (decode-time (current-time))))
17092 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17093 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17094 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17095 ((equal deltaw "m") (setq month (+ month deltan)))
17096 ((equal deltaw "y") (setq year (+ year deltan)))))
17097 ((and wday (not (nth 3 tl)))
17098 ;; Weekday was given, but no day, so pick that day in the week
17099 ;; on or after the derived date.
17100 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17101 (unless (equal wday wday1)
17102 (setq day (+ day (% (- wday wday1 -7) 7))))))
17103 (when (and (boundp 'org-time-was-given)
17104 (nth 2 tl))
17105 (setq org-time-was-given t))
17106 (when (< year 100) (setq year (+ 2000 year)))
17107 ;; Check of the date is representable
17108 (if org-read-date-force-compatible-dates
17109 (progn
17110 (when (< year 1970)
17111 (setq year 1970 org-read-date-analyze-forced-year t))
17112 (when (> year 2037)
17113 (setq year 2037 org-read-date-analyze-forced-year t)))
17114 (condition-case nil
17115 (ignore (encode-time second minute hour day month year))
17116 (error
17117 (setq year (nth 5 org-defdecode))
17118 (setq org-read-date-analyze-forced-year t))))
17119 (setq org-read-date-analyze-futurep futurep)
17120 (list second minute hour day month year)))
17122 (defvar parse-time-weekdays)
17123 (defun org-read-date-get-relative (s today default)
17124 "Check string S for special relative date string.
17125 TODAY and DEFAULT are internal times, for today and for a default.
17126 Return shift list (N what def-flag)
17127 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17128 N is the number of WHATs to shift.
17129 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17130 the DEFAULT date rather than TODAY."
17131 (require 'parse-time)
17132 (when (and
17133 (string-match
17134 (concat
17135 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17136 "\\([0-9]+\\)?"
17137 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17138 "\\([ \t]\\|$\\)") s)
17139 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17140 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17141 (string-to-char (substring (match-string 1 s) -1))
17142 ?+))
17143 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17144 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17145 (what (if (match-end 3) (match-string 3 s) "d"))
17146 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17147 (date (if rel default today))
17148 (wday (nth 6 (decode-time date)))
17149 delta)
17150 (if wday1
17151 (progn
17152 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17153 (when (= delta 0) (setq delta 7))
17154 (when (= dir ?-)
17155 (setq delta (- delta 7))
17156 (when (= delta 0) (setq delta -7)))
17157 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17158 (list delta "d" rel))
17159 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17161 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17162 "Turn a user-specified date into the internal representation.
17163 The internal representation needed by the calendar is (month day year).
17164 This is a wrapper to handle the brain-dead convention in calendar that
17165 user function argument order change dependent on argument order."
17166 (pcase calendar-date-style
17167 (`american (list arg1 arg2 arg3))
17168 (`european (list arg2 arg1 arg3))
17169 (`iso (list arg2 arg3 arg1))))
17171 (defun org-eval-in-calendar (form &optional keepdate)
17172 "Eval FORM in the calendar window and return to current window.
17173 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17174 (let ((sf (selected-frame))
17175 (sw (selected-window)))
17176 (select-window (get-buffer-window "*Calendar*" t))
17177 (eval form)
17178 (when (and (not keepdate) (calendar-cursor-to-date))
17179 (let* ((date (calendar-cursor-to-date))
17180 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17181 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17182 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17183 (select-window sw)
17184 (select-frame-set-input-focus sf)))
17186 (defun org-calendar-select ()
17187 "Return to `org-read-date' with the date currently selected.
17188 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17189 (interactive)
17190 (when (calendar-cursor-to-date)
17191 (let* ((date (calendar-cursor-to-date))
17192 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17193 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17194 (when (active-minibuffer-window) (exit-minibuffer))))
17196 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17197 "Insert a date stamp for the date given by the internal TIME.
17198 See `format-time-string' for the format of TIME.
17199 WITH-HM means use the stamp format that includes the time of the day.
17200 INACTIVE means use square brackets instead of angular ones, so that the
17201 stamp will not contribute to the agenda.
17202 PRE and POST are optional strings to be inserted before and after the
17203 stamp.
17204 The command returns the inserted time stamp."
17205 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17206 stamp)
17207 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17208 (insert-before-markers (or pre ""))
17209 (when (listp extra)
17210 (setq extra (car extra))
17211 (if (and (stringp extra)
17212 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17213 (setq extra (format "-%02d:%02d"
17214 (string-to-number (match-string 1 extra))
17215 (string-to-number (match-string 2 extra))))
17216 (setq extra nil)))
17217 (when extra
17218 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17219 (insert-before-markers (setq stamp (format-time-string fmt time)))
17220 (insert-before-markers (or post ""))
17221 (setq org-last-inserted-timestamp stamp)))
17223 (defun org-toggle-time-stamp-overlays ()
17224 "Toggle the use of custom time stamp formats."
17225 (interactive)
17226 (setq org-display-custom-times (not org-display-custom-times))
17227 (unless org-display-custom-times
17228 (let ((p (point-min)) (bmp (buffer-modified-p)))
17229 (while (setq p (next-single-property-change p 'display))
17230 (when (and (get-text-property p 'display)
17231 (eq (get-text-property p 'face) 'org-date))
17232 (remove-text-properties
17233 p (setq p (next-single-property-change p 'display))
17234 '(display t))))
17235 (set-buffer-modified-p bmp)))
17236 (org-restart-font-lock)
17237 (setq org-table-may-need-update t)
17238 (if org-display-custom-times
17239 (message "Time stamps are overlaid with custom format")
17240 (message "Time stamp overlays removed")))
17242 (defun org-display-custom-time (beg end)
17243 "Overlay modified time stamp format over timestamp between BEG and END."
17244 (let* ((ts (buffer-substring beg end))
17245 t1 with-hm tf time str (off 0))
17246 (save-match-data
17247 (setq t1 (org-parse-time-string ts t))
17248 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17249 (setq off (- (match-end 0) (match-beginning 0)))))
17250 (setq end (- end off))
17251 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17252 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17253 time (org-fix-decoded-time t1)
17254 str (org-add-props
17255 (format-time-string
17256 (substring tf 1 -1) (apply 'encode-time time))
17257 nil 'mouse-face 'highlight))
17258 (put-text-property beg end 'display str)))
17260 (defun org-fix-decoded-time (time)
17261 "Set 0 instead of nil for the first 6 elements of time.
17262 Don't touch the rest."
17263 (let ((n 0))
17264 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17266 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17267 "Difference between TIMESTAMP-STRING and now in days.
17268 If SECONDS is non-nil, return the difference in seconds."
17269 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17270 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17271 (funcall fdiff (current-time)))))
17273 (defun org-deadline-close-p (timestamp-string &optional ndays)
17274 "Is the time in TIMESTAMP-STRING close to the current date?"
17275 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17276 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17277 (not (org-entry-is-done-p))))
17279 (defun org-get-wdays (ts &optional delay zero-delay)
17280 "Get the deadline lead time appropriate for timestring TS.
17281 When DELAY is non-nil, get the delay time for scheduled items
17282 instead of the deadline lead time. When ZERO-DELAY is non-nil
17283 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17284 don't try to find the delay cookie in the scheduled timestamp."
17285 (let ((tv (if delay org-scheduled-delay-days
17286 org-deadline-warning-days)))
17287 (cond
17288 ((or (and delay (< tv 0))
17289 (and delay zero-delay (<= tv 0))
17290 (and (not delay) (<= tv 0)))
17291 ;; Enforce this value no matter what
17292 (- tv))
17293 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17294 ;; lead time is specified.
17295 (floor (* (string-to-number (match-string 1 ts))
17296 (cdr (assoc (match-string 2 ts)
17297 '(("d" . 1) ("w" . 7)
17298 ("m" . 30.4) ("y" . 365.25)
17299 ("h" . 0.041667)))))))
17300 ;; go for the default.
17301 (t tv))))
17303 (defun org-calendar-select-mouse (ev)
17304 "Return to `org-read-date' with the date currently selected.
17305 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17306 (interactive "e")
17307 (mouse-set-point ev)
17308 (when (calendar-cursor-to-date)
17309 (let* ((date (calendar-cursor-to-date))
17310 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17311 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17312 (when (active-minibuffer-window) (exit-minibuffer))))
17314 (defun org-check-deadlines (ndays)
17315 "Check if there are any deadlines due or past due.
17316 A deadline is considered due if it happens within `org-deadline-warning-days'
17317 days from today's date. If the deadline appears in an entry marked DONE,
17318 it is not shown. A numeric prefix argument NDAYS can be used to test that
17319 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17320 are shown."
17321 (interactive "P")
17322 (let* ((org-warn-days
17323 (cond
17324 ((equal ndays '(4)) 100000)
17325 (ndays (prefix-numeric-value ndays))
17326 (t (abs org-deadline-warning-days))))
17327 (case-fold-search nil)
17328 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17329 (callback
17330 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17331 (message "%d deadlines past-due or due within %d days"
17332 (org-occur regexp nil callback)
17333 org-warn-days)))
17335 (defsubst org-re-timestamp (type)
17336 "Return a regexp for timestamp TYPE.
17337 Allowed values for TYPE are:
17339 all: all timestamps
17340 active: only active timestamps (<...>)
17341 inactive: only inactive timestamps ([...])
17342 scheduled: only scheduled timestamps
17343 deadline: only deadline timestamps
17344 closed: only closed time-stamps
17346 When TYPE is nil, fall back on returning a regexp that matches
17347 both scheduled and deadline timestamps."
17348 (cl-case type
17349 (all org-ts-regexp-both)
17350 (active org-ts-regexp)
17351 (inactive org-ts-regexp-inactive)
17352 (scheduled org-scheduled-time-regexp)
17353 (deadline org-deadline-time-regexp)
17354 (closed org-closed-time-regexp)
17355 (otherwise
17356 (concat "\\<"
17357 (regexp-opt (list org-deadline-string org-scheduled-string))
17358 " *<\\([^>]+\\)>"))))
17360 (defun org-check-before-date (d)
17361 "Check if there are deadlines or scheduled entries before date D."
17362 (interactive (list (org-read-date)))
17363 (let* ((case-fold-search nil)
17364 (regexp (org-re-timestamp org-ts-type))
17365 (ts-type org-ts-type)
17366 (callback
17367 (lambda ()
17368 (let ((match (match-string 1)))
17369 (and (if (memq ts-type '(active inactive all))
17370 (eq (org-element-type (save-excursion
17371 (backward-char)
17372 (org-element-context)))
17373 'timestamp)
17374 (org-at-planning-p))
17375 (time-less-p
17376 (org-time-string-to-time match t)
17377 (org-time-string-to-time d t)))))))
17378 (message "%d entries before %s"
17379 (org-occur regexp nil callback)
17380 d)))
17382 (defun org-check-after-date (d)
17383 "Check if there are deadlines or scheduled entries after date D."
17384 (interactive (list (org-read-date)))
17385 (let* ((case-fold-search nil)
17386 (regexp (org-re-timestamp org-ts-type))
17387 (ts-type org-ts-type)
17388 (callback
17389 (lambda ()
17390 (let ((match (match-string 1)))
17391 (and (if (memq ts-type '(active inactive all))
17392 (eq (org-element-type (save-excursion
17393 (backward-char)
17394 (org-element-context)))
17395 'timestamp)
17396 (org-at-planning-p))
17397 (not (time-less-p
17398 (org-time-string-to-time match t)
17399 (org-time-string-to-time d t))))))))
17400 (message "%d entries after %s"
17401 (org-occur regexp nil callback)
17402 d)))
17404 (defun org-check-dates-range (start-date end-date)
17405 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17406 (interactive (list (org-read-date nil nil nil "Range starts")
17407 (org-read-date nil nil nil "Range end")))
17408 (let ((case-fold-search nil)
17409 (regexp (org-re-timestamp org-ts-type))
17410 (callback
17411 (let ((type org-ts-type))
17412 (lambda ()
17413 (let ((match (match-string 1)))
17414 (and
17415 (if (memq type '(active inactive all))
17416 (eq (org-element-type (save-excursion
17417 (backward-char)
17418 (org-element-context)))
17419 'timestamp)
17420 (org-at-planning-p))
17421 (not (time-less-p
17422 (org-time-string-to-time match t)
17423 (org-time-string-to-time start-date t)))
17424 (time-less-p
17425 (org-time-string-to-time match t)
17426 (org-time-string-to-time end-date t))))))))
17427 (message "%d entries between %s and %s"
17428 (org-occur regexp nil callback) start-date end-date)))
17430 (defun org-evaluate-time-range (&optional to-buffer)
17431 "Evaluate a time range by computing the difference between start and end.
17432 Normally the result is just printed in the echo area, but with prefix arg
17433 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17434 If the time range is actually in a table, the result is inserted into the
17435 next column.
17436 For time difference computation, a year is assumed to be exactly 365
17437 days in order to avoid rounding problems."
17438 (interactive "P")
17440 (org-clock-update-time-maybe)
17441 (save-excursion
17442 (unless (org-at-date-range-p t)
17443 (goto-char (point-at-bol))
17444 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17445 (unless (org-at-date-range-p t)
17446 (user-error "Not at a time-stamp range, and none found in current line")))
17447 (let* ((ts1 (match-string 1))
17448 (ts2 (match-string 2))
17449 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17450 (match-end (match-end 0))
17451 (time1 (org-time-string-to-time ts1))
17452 (time2 (org-time-string-to-time ts2))
17453 (t1 (float-time time1))
17454 (t2 (float-time time2))
17455 (diff (abs (- t2 t1)))
17456 (negative (< (- t2 t1) 0))
17457 ;; (ys (floor (* 365 24 60 60)))
17458 (ds (* 24 60 60))
17459 (hs (* 60 60))
17460 (fy "%dy %dd %02d:%02d")
17461 (fy1 "%dy %dd")
17462 (fd "%dd %02d:%02d")
17463 (fd1 "%dd")
17464 (fh "%02d:%02d")
17465 y d h m align)
17466 (if havetime
17467 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17469 d (floor (/ diff ds)) diff (mod diff ds)
17470 h (floor (/ diff hs)) diff (mod diff hs)
17471 m (floor (/ diff 60)))
17472 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17474 d (floor (+ (/ diff ds) 0.5))
17475 h 0 m 0))
17476 (if (not to-buffer)
17477 (message "%s" (org-make-tdiff-string y d h m))
17478 (if (org-at-table-p)
17479 (progn
17480 (goto-char match-end)
17481 (setq align t)
17482 (and (looking-at " *|") (goto-char (match-end 0))))
17483 (goto-char match-end))
17484 (when (looking-at
17485 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17486 (replace-match ""))
17487 (when negative (insert " -"))
17488 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17489 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17490 (insert " " (format fh h m))))
17491 (when align (org-table-align))
17492 (message "Time difference inserted")))))
17494 (defun org-make-tdiff-string (y d h m)
17495 (let ((fmt "")
17496 (l nil))
17497 (when (> y 0)
17498 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17499 (push y l))
17500 (when (> d 0)
17501 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17502 (push d l))
17503 (when (> h 0)
17504 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17505 (push h l))
17506 (when (> m 0)
17507 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17508 (push m l))
17509 (apply 'format fmt (nreverse l))))
17511 (defun org-time-string-to-time (s &optional zone)
17512 "Convert timestamp string S into internal time.
17513 The optional ZONE is omitted or nil for Emacs local time, t for
17514 Universal Time, ‘wall’ for system wall clock time, or a string as
17515 in the TZ environment variable."
17516 (apply #'encode-time (org-parse-time-string s nil zone)))
17518 (defun org-time-string-to-seconds (s &optional zone)
17519 "Convert a timestamp string S into a number of seconds.
17520 The optional ZONE is omitted or nil for Emacs local time, t for
17521 Universal Time, ‘wall’ for system wall clock time, or a string as
17522 in the TZ environment variable."
17523 (float-time (org-time-string-to-time s zone)))
17525 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17527 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17528 "Convert time stamp S to an absolute day number.
17530 If DAYNR in non-nil, and there is a specifier for a cyclic time
17531 stamp, get the closest date to DAYNR. If PREFER is
17532 `past' (respectively `future') return a date past (respectively
17533 after) or equal to DAYNR.
17535 POS is the location of time stamp S, as a buffer position in
17536 BUFFER.
17538 Diary sexp timestamps are matched against DAYNR, when non-nil.
17539 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17540 signaled."
17541 (cond
17542 ((string-match "\\`%%\\((.*)\\)" s)
17543 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17544 ;; only able to match individual dates. If it fails, raise an
17545 ;; error.
17546 (if (and daynr
17547 (org-diary-sexp-entry
17548 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17549 daynr
17550 (signal 'org-diary-sexp-no-match (list s))))
17551 (daynr (org-closest-date s daynr prefer))
17552 (t (time-to-days
17553 (condition-case errdata
17554 (apply #'encode-time (org-parse-time-string s))
17555 (error (error "Bad timestamp `%s'%s\nError was: %s"
17557 (if (not (and buffer pos)) ""
17558 (format-message " at %d in buffer `%s'" pos buffer))
17559 (cdr errdata))))))))
17561 (defun org-days-to-iso-week (days)
17562 "Return the iso week number."
17563 (require 'cal-iso)
17564 (car (calendar-iso-from-absolute days)))
17566 (defun org-small-year-to-year (year)
17567 "Convert 2-digit years into 4-digit years.
17568 YEAR is expanded into one of the 30 next years, if possible, or
17569 into a past one. Any year larger than 99 is returned unchanged."
17570 (if (>= year 100) year
17571 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17572 (century (/ current 100))
17573 (offset (- year (% current 100))))
17574 (cond ((> offset 30) (+ (* (1- century) 100) year))
17575 ((> offset -70) (+ (* century 100) year))
17576 (t (+ (* (1+ century) 100) year))))))
17578 (defun org-time-from-absolute (d)
17579 "Return the time corresponding to date D.
17580 D may be an absolute day number, or a calendar-type list (month day year)."
17581 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17582 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17584 (defvar org-agenda-current-date)
17585 (defun org-calendar-holiday ()
17586 "List of holidays, for Diary display in Org mode."
17587 (require 'holidays)
17588 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17589 (and hl (mapconcat #'identity hl "; "))))
17591 (defun org-diary-sexp-entry (sexp entry d)
17592 "Process a SEXP diary ENTRY for date D."
17593 (require 'diary-lib)
17594 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17595 ;; dynamically.
17596 (let* ((sexp `(let ((entry ,entry)
17597 (date ',d))
17598 ,(car (read-from-string sexp))))
17599 (result (if calendar-debug-sexp (eval sexp)
17600 (condition-case nil
17601 (eval sexp)
17602 (error
17603 (beep)
17604 (message "Bad sexp at line %d in %s: %s"
17605 (org-current-line)
17606 (buffer-file-name) sexp)
17607 (sleep-for 2))))))
17608 (cond ((stringp result) (split-string result "; "))
17609 ((and (consp result)
17610 (not (consp (cdr result)))
17611 (stringp (cdr result))) (cdr result))
17612 ((and (consp result)
17613 (stringp (car result))) result)
17614 (result entry))))
17616 (defun org-diary-to-ical-string (frombuf)
17617 "Get iCalendar entries from diary entries in buffer FROMBUF.
17618 This uses the icalendar.el library."
17619 (let* ((tmpdir temporary-file-directory)
17620 (tmpfile (make-temp-name
17621 (expand-file-name "orgics" tmpdir)))
17622 buf rtn b e)
17623 (with-current-buffer frombuf
17624 (icalendar-export-region (point-min) (point-max) tmpfile)
17625 (setq buf (find-buffer-visiting tmpfile))
17626 (set-buffer buf)
17627 (goto-char (point-min))
17628 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17629 (setq b (match-beginning 0)))
17630 (goto-char (point-max))
17631 (when (re-search-backward "^END:VEVENT" nil t)
17632 (setq e (match-end 0)))
17633 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17634 (kill-buffer buf)
17635 (delete-file tmpfile)
17636 rtn))
17638 (defun org-closest-date (start current prefer)
17639 "Return closest date to CURRENT starting from START.
17641 CURRENT and START are both time stamps.
17643 When PREFER is `past', return a date that is either CURRENT or
17644 past. When PREFER is `future', return a date that is either
17645 CURRENT or future.
17647 Only time stamps with a repeater are modified. Any other time
17648 stamp stay unchanged. In any case, return value is an absolute
17649 day number."
17650 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17651 ;; No repeater. Do not shift time stamp.
17652 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17653 (let ((value (string-to-number (match-string 1 start)))
17654 (type (match-string 2 start)))
17655 (if (= 0 value)
17656 ;; Repeater with a 0-value is considered as void.
17657 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17658 (let* ((base (org-date-to-gregorian start))
17659 (target (org-date-to-gregorian current))
17660 (sday (calendar-absolute-from-gregorian base))
17661 (cday (calendar-absolute-from-gregorian target))
17662 n1 n2)
17663 ;; If START is already past CURRENT, just return START.
17664 (if (<= cday sday) sday
17665 ;; Compute closest date before (N1) and closest date past
17666 ;; (N2) CURRENT.
17667 (pcase type
17668 ("h"
17669 (let ((missing-hours
17670 (mod (+ (- (* 24 (- cday sday))
17671 (nth 2 (org-parse-time-string start)))
17672 org-extend-today-until)
17673 value)))
17674 (setf n1 (if (= missing-hours 0) cday
17675 (- cday (1+ (/ missing-hours 24)))))
17676 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17677 ((or "d" "w")
17678 (let ((value (if (equal type "w") (* 7 value) value)))
17679 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17680 (setf n2 (+ n1 value))))
17681 ("m"
17682 (let* ((add-months
17683 (lambda (d n)
17684 ;; Add N months to gregorian date D, i.e.,
17685 ;; a list (MONTH DAY YEAR). Return a valid
17686 ;; gregorian date.
17687 (let ((m (+ (nth 0 d) n)))
17688 (list (mod m 12)
17689 (nth 1 d)
17690 (+ (/ m 12) (nth 2 d))))))
17691 (months ; Complete months to TARGET.
17692 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17693 (- (nth 0 target) (nth 0 base))
17694 ;; If START's day is greater than
17695 ;; TARGET's, remove incomplete month.
17696 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17697 value)
17698 value))
17699 (before (funcall add-months base months)))
17700 (setf n1 (calendar-absolute-from-gregorian before))
17701 (setf n2
17702 (calendar-absolute-from-gregorian
17703 (funcall add-months before value)))))
17705 (let* ((d (nth 1 base))
17706 (m (nth 0 base))
17707 (y (nth 2 base))
17708 (years ; Complete years to TARGET.
17709 (* (/ (- (nth 2 target)
17711 ;; If START's month and day are
17712 ;; greater than TARGET's, remove
17713 ;; incomplete year.
17714 (if (or (> (nth 0 target) m)
17715 (and (= (nth 0 target) m)
17716 (> (nth 1 target) d)))
17719 value)
17720 value))
17721 (before (list m d (+ y years))))
17722 (setf n1 (calendar-absolute-from-gregorian before))
17723 (setf n2 (calendar-absolute-from-gregorian
17724 (list m d (+ (nth 2 before) value)))))))
17725 ;; Handle PREFER parameter, if any.
17726 (cond
17727 ((eq prefer 'past) (if (= cday n2) n2 n1))
17728 ((eq prefer 'future) (if (= cday n1) n1 n2))
17729 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17731 (defun org-date-to-gregorian (d)
17732 "Turn any specification of date D into a Gregorian date for the calendar."
17733 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17734 ((and (listp d) (= (length d) 3)) d)
17735 ((stringp d)
17736 (let ((d (org-parse-time-string d)))
17737 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17738 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17740 (defun org-parse-time-string (s &optional nodefault zone)
17741 "Parse the standard Org time string.
17743 This should be a lot faster than the normal `parse-time-string'.
17745 If time is not given, defaults to 0:00. However, with optional
17746 NODEFAULT, hour and minute fields will be nil if not given.
17748 The optional ZONE is omitted or nil for Emacs local time, t for
17749 Universal Time, ‘wall’ for system wall clock time, or a string as
17750 in the TZ environment variable."
17751 (cond ((string-match org-ts-regexp0 s)
17752 (list 0
17753 (when (or (match-beginning 8) (not nodefault))
17754 (string-to-number (or (match-string 8 s) "0")))
17755 (when (or (match-beginning 7) (not nodefault))
17756 (string-to-number (or (match-string 7 s) "0")))
17757 (string-to-number (match-string 4 s))
17758 (string-to-number (match-string 3 s))
17759 (string-to-number (match-string 2 s))
17760 nil nil zone))
17761 ((string-match "^<[^>]+>$" s)
17762 ;; FIXME: `decode-time' needs to be called with ZONE as its
17763 ;; second argument. However, this requires at least Emacs
17764 ;; 25.1. We can do it when we switch to this version as our
17765 ;; minimal requirement.
17766 (decode-time (seconds-to-time (org-matcher-time s))))
17767 (t (error "Not a standard Org time string: %s" s))))
17769 (defun org-timestamp-up (&optional arg)
17770 "Increase the date item at the cursor by one.
17771 If the cursor is on the year, change the year. If it is on the month,
17772 the day or the time, change that.
17773 With prefix ARG, change by that many units."
17774 (interactive "p")
17775 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17777 (defun org-timestamp-down (&optional arg)
17778 "Decrease the date item at the cursor by one.
17779 If the cursor is on the year, change the year. If it is on the month,
17780 the day or the time, change that.
17781 With prefix ARG, change by that many units."
17782 (interactive "p")
17783 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17785 (defun org-timestamp-up-day (&optional arg)
17786 "Increase the date in the time stamp by one day.
17787 With prefix ARG, change that many days."
17788 (interactive "p")
17789 (if (and (not (org-at-timestamp-p 'lax))
17790 (org-at-heading-p))
17791 (org-todo 'up)
17792 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17794 (defun org-timestamp-down-day (&optional arg)
17795 "Decrease the date in the time stamp by one day.
17796 With prefix ARG, change that many days."
17797 (interactive "p")
17798 (if (and (not (org-at-timestamp-p 'lax))
17799 (org-at-heading-p))
17800 (org-todo 'down)
17801 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17803 (defun org-at-timestamp-p (&optional extended)
17804 "Non-nil if point is inside a timestamp.
17806 By default, the function only consider syntactically valid active
17807 timestamps. However, the caller may have a broader definition
17808 for timestamps. As a consequence, optional argument EXTENDED can
17809 be set to the following values
17811 `inactive'
17813 Include also syntactically valid inactive timestamps.
17815 `agenda'
17817 Include timestamps allowed in Agenda, i.e., those in
17818 properties drawers, planning lines and clock lines.
17820 `lax'
17822 Ignore context. The function matches any part of the
17823 document looking like a timestamp. This includes comments,
17824 example blocks...
17826 For backward-compatibility with Org 9.0, every other non-nil
17827 value is equivalent to `inactive'.
17829 When at a timestamp, return the position of the point as a symbol
17830 among `bracket', `after', `year', `month', `hour', `minute',
17831 `day' or a number of character from the last know part of the
17832 time stamp.
17834 When matching, the match groups are the following:
17835 group 1: year
17836 group 2: month
17837 group 3: day number
17838 group 4: day name
17839 group 5: hours, if any
17840 group 6: minutes, if any"
17841 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17842 (pos (point))
17843 (match?
17844 (let ((boundaries (org-in-regexp regexp)))
17845 (save-match-data
17846 (cond ((null boundaries) nil)
17847 ((eq extended 'lax) t)
17849 (or (and (eq extended 'agenda)
17850 (or (org-at-planning-p)
17851 (org-at-property-p)
17852 (and (bound-and-true-p
17853 org-agenda-include-inactive-timestamps)
17854 (org-at-clock-log-p))))
17855 (eq 'timestamp
17856 (save-excursion
17857 (when (= pos (cdr boundaries)) (forward-char -1))
17858 (org-element-type (org-element-context)))))))))))
17859 (cond
17860 ((not match?) nil)
17861 ((= pos (match-beginning 0)) 'bracket)
17862 ;; Distinguish location right before the closing bracket from
17863 ;; right after it.
17864 ((= pos (1- (match-end 0))) 'bracket)
17865 ((= pos (match-end 0)) 'after)
17866 ((org-pos-in-match-range pos 2) 'year)
17867 ((org-pos-in-match-range pos 3) 'month)
17868 ((org-pos-in-match-range pos 7) 'hour)
17869 ((org-pos-in-match-range pos 8) 'minute)
17870 ((or (org-pos-in-match-range pos 4)
17871 (org-pos-in-match-range pos 5)) 'day)
17872 ((and (> pos (or (match-end 8) (match-end 5)))
17873 (< pos (match-end 0)))
17874 (- pos (or (match-end 8) (match-end 5))))
17875 (t 'day))))
17877 (defun org-toggle-timestamp-type ()
17878 "Toggle the type (<active> or [inactive]) of a time stamp."
17879 (interactive)
17880 (when (org-at-timestamp-p 'lax)
17881 (let ((beg (match-beginning 0)) (end (match-end 0))
17882 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17883 (save-excursion
17884 (goto-char beg)
17885 (while (re-search-forward "[][<>]" end t)
17886 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17887 t t)))
17888 (message "Timestamp is now %sactive"
17889 (if (equal (char-after beg) ?<) "" "in")))))
17891 (defun org-at-clock-log-p ()
17892 "Non-nil if point is on a clock log line."
17893 (and (org-match-line org-clock-line-re)
17894 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17896 (defvar org-clock-history) ; defined in org-clock.el
17897 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17898 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17899 "Change the date in the time stamp at point.
17900 The date will be changed by N times WHAT. WHAT can be `day', `month',
17901 `year', `minute', `second'. If WHAT is not given, the cursor position
17902 in the timestamp determines what will be changed.
17903 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17904 (let ((origin (point))
17905 (timestamp? (org-at-timestamp-p 'lax))
17906 origin-cat
17907 with-hm inactive
17908 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17909 extra rem
17910 ts time time0 fixnext clrgx)
17911 (unless timestamp? (user-error "Not at a timestamp"))
17912 (if (and (not what) (eq timestamp? 'bracket))
17913 (org-toggle-timestamp-type)
17914 ;; Point isn't on brackets. Remember the part of the time-stamp
17915 ;; the point was in. Indeed, size of time-stamps may change,
17916 ;; but point must be kept in the same category nonetheless.
17917 (setq origin-cat timestamp?)
17918 (when (and (not what) (not (eq timestamp? 'day))
17919 org-display-custom-times
17920 (get-text-property (point) 'display)
17921 (not (get-text-property (1- (point)) 'display)))
17922 (setq timestamp? 'day))
17923 (setq timestamp? (or what timestamp?)
17924 inactive (= (char-after (match-beginning 0)) ?\[)
17925 ts (match-string 0))
17926 (replace-match "")
17927 (when (string-match
17928 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17930 (setq extra (match-string 1 ts))
17931 (when suppress-tmp-delay
17932 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17933 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17934 (setq with-hm t))
17935 (setq time0 (org-parse-time-string ts))
17936 (when (and updown
17937 (eq timestamp? 'minute)
17938 (not current-prefix-arg))
17939 ;; This looks like s-up and s-down. Change by one rounding step.
17940 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17941 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17942 (setcar (cdr time0) (+ (nth 1 time0)
17943 (if (> n 0) (- rem) (- dm rem))))))
17944 (setq time
17945 (apply #'encode-time
17946 (or (car time0) 0)
17947 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17948 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17949 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17950 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17951 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17952 (nthcdr 6 time0)))
17953 (when (and (memq timestamp? '(hour minute))
17954 extra
17955 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17956 (setq extra (org-modify-ts-extra
17957 extra
17958 (if (eq timestamp? 'hour) 2 5)
17959 n dm)))
17960 (when (integerp timestamp?)
17961 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17962 (when (eq what 'calendar)
17963 (let ((cal-date (org-get-date-from-calendar)))
17964 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17965 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17966 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17967 (setcar time0 (or (car time0) 0))
17968 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17969 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17970 (setq time (apply 'encode-time time0))))
17971 ;; Insert the new time-stamp, and ensure point stays in the same
17972 ;; category as before (i.e. not after the last position in that
17973 ;; category).
17974 (let ((pos (point)))
17975 ;; Stay before inserted string. `save-excursion' is of no use.
17976 (setq org-last-changed-timestamp
17977 (org-insert-time-stamp time with-hm inactive nil nil extra))
17978 (goto-char pos))
17979 (save-match-data
17980 (looking-at org-ts-regexp3)
17981 (goto-char
17982 (pcase origin-cat
17983 ;; `day' category ends before `hour' if any, or at the end
17984 ;; of the day name.
17985 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17986 (`hour (min (match-end 7) origin))
17987 (`minute (min (1- (match-end 8)) origin))
17988 ((pred integerp) (min (1- (match-end 0)) origin))
17989 ;; Point was right after the time-stamp. However, the
17990 ;; time-stamp length might have changed, so refer to
17991 ;; (match-end 0) instead.
17992 (`after (match-end 0))
17993 ;; `year' and `month' have both fixed size: point couldn't
17994 ;; have moved into another part.
17995 (_ origin))))
17996 ;; Update clock if on a CLOCK line.
17997 (org-clock-update-time-maybe)
17998 ;; Maybe adjust the closest clock in `org-clock-history'
17999 (when org-clock-adjust-closest
18000 (if (not (and (org-at-clock-log-p)
18001 (< 1 (length (delq nil (mapcar 'marker-position
18002 org-clock-history))))))
18003 (message "No clock to adjust")
18004 (cond ((save-excursion ; fix previous clock?
18005 (re-search-backward org-ts-regexp0 nil t)
18006 (looking-back (concat org-clock-string " \\[")
18007 (line-beginning-position)))
18008 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18009 ((save-excursion ; fix next clock?
18010 (re-search-backward org-ts-regexp0 nil t)
18011 (looking-at (concat org-ts-regexp0 "\\] =>")))
18012 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18013 (save-window-excursion
18014 ;; Find closest clock to point, adjust the previous/next one in history
18015 (let* ((p (save-excursion (org-back-to-heading t)))
18016 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18017 (clfixnth
18018 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18019 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18020 (if (not clfixpos)
18021 (message "No clock to adjust")
18022 (save-excursion
18023 (org-goto-marker-or-bmk clfixpos)
18024 (org-show-subtree)
18025 (when (re-search-forward clrgx nil t)
18026 (goto-char (match-beginning 1))
18027 (let (org-clock-adjust-closest)
18028 (org-timestamp-change n timestamp? updown))
18029 (message "Clock adjusted in %s for heading: %s"
18030 (file-name-nondirectory (buffer-file-name))
18031 (org-get-heading t t)))))))))
18032 ;; Try to recenter the calendar window, if any.
18033 (when (and org-calendar-follow-timestamp-change
18034 (get-buffer-window "*Calendar*" t)
18035 (memq timestamp? '(day month year)))
18036 (org-recenter-calendar (time-to-days time))))))
18038 (defun org-modify-ts-extra (s pos n dm)
18039 "Change the different parts of the lead-time and repeat fields in timestamp."
18040 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18041 ng h m new rem)
18042 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18043 (cond
18044 ((or (org-pos-in-match-range pos 2)
18045 (org-pos-in-match-range pos 3))
18046 (setq m (string-to-number (match-string 3 s))
18047 h (string-to-number (match-string 2 s)))
18048 (if (org-pos-in-match-range pos 2)
18049 (setq h (+ h n))
18050 (setq n (* dm (with-no-warnings (signum n))))
18051 (unless (= 0 (setq rem (% m dm)))
18052 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18053 (setq m (+ m n)))
18054 (when (< m 0) (setq m (+ m 60) h (1- h)))
18055 (when (> m 59) (setq m (- m 60) h (1+ h)))
18056 (setq h (mod h 24))
18057 (setq ng 1 new (format "-%02d:%02d" h m)))
18058 ((org-pos-in-match-range pos 6)
18059 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18060 ((org-pos-in-match-range pos 5)
18061 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18063 ((org-pos-in-match-range pos 9)
18064 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18065 ((org-pos-in-match-range pos 8)
18066 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18068 (when ng
18069 (setq s (concat
18070 (substring s 0 (match-beginning ng))
18072 (substring s (match-end ng))))))
18075 (defun org-recenter-calendar (d)
18076 "If the calendar is visible, recenter it to date D."
18077 (let ((cwin (get-buffer-window "*Calendar*" t)))
18078 (when cwin
18079 (let ((calendar-move-hook nil))
18080 (with-selected-window cwin
18081 (calendar-goto-date
18082 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18084 (defun org-goto-calendar (&optional arg)
18085 "Go to the Emacs calendar at the current date.
18086 If there is a time stamp in the current line, go to that date.
18087 A prefix ARG can be used to force the current date."
18088 (interactive "P")
18089 (let ((calendar-move-hook nil)
18090 (calendar-view-holidays-initially-flag nil)
18091 (calendar-view-diary-initially-flag nil)
18092 diff)
18093 (when (or (org-at-timestamp-p 'lax)
18094 (org-match-line (concat ".*" org-ts-regexp)))
18095 (let ((d1 (time-to-days (current-time)))
18096 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18097 (setq diff (- d2 d1))))
18098 (calendar)
18099 (calendar-goto-today)
18100 (when (and diff (not arg)) (calendar-forward-day diff))))
18102 (defun org-get-date-from-calendar ()
18103 "Return a list (month day year) of date at point in calendar."
18104 (with-current-buffer "*Calendar*"
18105 (save-match-data
18106 (calendar-cursor-to-date))))
18108 (defun org-date-from-calendar ()
18109 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18110 If there is already a time stamp at the cursor position, update it."
18111 (interactive)
18112 (if (org-at-timestamp-p 'lax)
18113 (org-timestamp-change 0 'calendar)
18114 (let ((cal-date (org-get-date-from-calendar)))
18115 (org-insert-time-stamp
18116 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18118 (defcustom org-effort-durations
18119 `(("min" . 1)
18120 ("h" . 60)
18121 ("d" . ,(* 60 8))
18122 ("w" . ,(* 60 8 5))
18123 ("m" . ,(* 60 8 5 4))
18124 ("y" . ,(* 60 8 5 40)))
18125 "Conversion factor to minutes for an effort modifier.
18127 Each entry has the form (MODIFIER . MINUTES).
18129 In an effort string, a number followed by MODIFIER is multiplied
18130 by the specified number of MINUTES to obtain an effort in
18131 minutes.
18133 For example, if the value of this variable is ((\"hours\" . 60)), then an
18134 effort string \"2hours\" is equivalent to 120 minutes."
18135 :group 'org-agenda
18136 :version "26.1"
18137 :package-version '(Org . "8.3")
18138 :type '(alist :key-type (string :tag "Modifier")
18139 :value-type (number :tag "Minutes")))
18141 (defcustom org-image-actual-width t
18142 "Should we use the actual width of images when inlining them?
18144 When set to t, always use the image width.
18146 When set to a number, use imagemagick (when available) to set
18147 the image's width to this value.
18149 When set to a number in a list, try to get the width from any
18150 #+ATTR.* keyword if it matches a width specification like
18152 #+ATTR_HTML: :width 300px
18154 and fall back on that number if none is found.
18156 When set to nil, try to get the width from an #+ATTR.* keyword
18157 and fall back on the original width if none is found.
18159 This requires Emacs >= 24.1, build with imagemagick support."
18160 :group 'org-appearance
18161 :version "24.4"
18162 :package-version '(Org . "8.0")
18163 :type '(choice
18164 (const :tag "Use the image width" t)
18165 (integer :tag "Use a number of pixels")
18166 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18167 (const :tag "Use #+ATTR* or don't resize" nil)))
18169 (defcustom org-agenda-inhibit-startup nil
18170 "Inhibit startup when preparing agenda buffers.
18171 When this variable is t, the initialization of the Org agenda
18172 buffers is inhibited: e.g. the visibility state is not set, the
18173 tables are not re-aligned, etc."
18174 :type 'boolean
18175 :version "24.3"
18176 :group 'org-agenda)
18178 (defcustom org-agenda-ignore-properties nil
18179 "Avoid updating text properties when building the agenda.
18180 Properties are used to prepare buffers for effort estimates,
18181 appointments, statistics and subtree-local categories.
18182 If you don't use these in the agenda, you can add them to this
18183 list and agenda building will be a bit faster.
18184 The value is a list, with zero or more of the symbols `effort', `appt',
18185 `stats' or `category'."
18186 :type '(set :greedy t
18187 (const effort)
18188 (const appt)
18189 (const stats)
18190 (const category))
18191 :version "26.1"
18192 :package-version '(Org . "8.3")
18193 :group 'org-agenda)
18195 ;;;; Files
18197 (defun org-save-all-org-buffers ()
18198 "Save all Org buffers without user confirmation."
18199 (interactive)
18200 (message "Saving all Org buffers...")
18201 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18202 (when (featurep 'org-id) (org-id-locations-save))
18203 (message "Saving all Org buffers... done"))
18205 (defun org-revert-all-org-buffers ()
18206 "Revert all Org buffers.
18207 Prompt for confirmation when there are unsaved changes.
18208 Be sure you know what you are doing before letting this function
18209 overwrite your changes.
18211 This function is useful in a setup where one tracks org files
18212 with a version control system, to revert on one machine after pulling
18213 changes from another. I believe the procedure must be like this:
18215 1. M-x org-save-all-org-buffers
18216 2. Pull changes from the other machine, resolve conflicts
18217 3. M-x org-revert-all-org-buffers"
18218 (interactive)
18219 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18220 (user-error "Abort"))
18221 (save-excursion
18222 (save-window-excursion
18223 (dolist (b (buffer-list))
18224 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18225 (with-current-buffer b buffer-file-name))
18226 (pop-to-buffer-same-window b)
18227 (revert-buffer t 'no-confirm)))
18228 (when (and (featurep 'org-id) org-id-track-globally)
18229 (org-id-locations-load)))))
18231 ;;;; Agenda files
18233 ;;;###autoload
18234 (defun org-switchb (&optional arg)
18235 "Switch between Org buffers.
18237 With `\\[universal-argument]' prefix, restrict available buffers to files.
18239 With `\\[universal-argument] \\[universal-argument]' \
18240 prefix, restrict available buffers to agenda files."
18241 (interactive "P")
18242 (let ((blist (org-buffer-list
18243 (cond ((equal arg '(4)) 'files)
18244 ((equal arg '(16)) 'agenda)))))
18245 (pop-to-buffer-same-window
18246 (completing-read "Org buffer: "
18247 (mapcar #'list (mapcar #'buffer-name blist))
18248 nil t))))
18250 (defun org-buffer-list (&optional predicate exclude-tmp)
18251 "Return a list of Org buffers.
18252 PREDICATE can be `export', `files' or `agenda'.
18254 export restrict the list to Export buffers.
18255 files restrict the list to buffers visiting Org files.
18256 agenda restrict the list to buffers visiting agenda files.
18258 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18259 (let* ((bfn nil)
18260 (agenda-files (and (eq predicate 'agenda)
18261 (mapcar 'file-truename (org-agenda-files t))))
18262 (filter
18263 (cond
18264 ((eq predicate 'files)
18265 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18266 ((eq predicate 'export)
18267 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18268 ((eq predicate 'agenda)
18269 (lambda (b)
18270 (with-current-buffer b
18271 (and (derived-mode-p 'org-mode)
18272 (setq bfn (buffer-file-name b))
18273 (member (file-truename bfn) agenda-files)))))
18274 (t (lambda (b) (with-current-buffer b
18275 (or (derived-mode-p 'org-mode)
18276 (string-match "\\*Org .*Export"
18277 (buffer-name b)))))))))
18278 (delq nil
18279 (mapcar
18280 (lambda(b)
18281 (if (and (funcall filter b)
18282 (or (not exclude-tmp)
18283 (not (string-match "tmp" (buffer-name b)))))
18285 nil))
18286 (buffer-list)))))
18288 (defun org-agenda-files (&optional unrestricted archives)
18289 "Get the list of agenda files.
18290 Optional UNRESTRICTED means return the full list even if a restriction
18291 is currently in place.
18292 When ARCHIVES is t, include all archive files that are really being
18293 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18294 `org-agenda-archives-mode' is t."
18295 (let ((files
18296 (cond
18297 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18298 ((stringp org-agenda-files) (org-read-agenda-file-list))
18299 ((listp org-agenda-files) org-agenda-files)
18300 (t (error "Invalid value of `org-agenda-files'")))))
18301 (setq files (apply 'append
18302 (mapcar (lambda (f)
18303 (if (file-directory-p f)
18304 (directory-files
18305 f t org-agenda-file-regexp)
18306 (list f)))
18307 files)))
18308 (when org-agenda-skip-unavailable-files
18309 (setq files (delq nil
18310 (mapcar (function
18311 (lambda (file)
18312 (and (file-readable-p file) file)))
18313 files))))
18314 (when (or (eq archives t)
18315 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18316 (setq files (org-add-archive-files files)))
18317 files))
18319 (defun org-agenda-file-p (&optional file)
18320 "Return non-nil, if FILE is an agenda file.
18321 If FILE is omitted, use the file associated with the current
18322 buffer."
18323 (let ((fname (or file (buffer-file-name))))
18324 (and fname
18325 (member (file-truename fname)
18326 (mapcar #'file-truename (org-agenda-files t))))))
18328 (defun org-edit-agenda-file-list ()
18329 "Edit the list of agenda files.
18330 Depending on setup, this either uses customize to edit the variable
18331 `org-agenda-files', or it visits the file that is holding the list. In the
18332 latter case, the buffer is set up in a way that saving it automatically kills
18333 the buffer and restores the previous window configuration."
18334 (interactive)
18335 (if (stringp org-agenda-files)
18336 (let ((cw (current-window-configuration)))
18337 (find-file org-agenda-files)
18338 (setq-local org-window-configuration cw)
18339 (add-hook 'after-save-hook
18340 (lambda ()
18341 (set-window-configuration
18342 (prog1 org-window-configuration
18343 (kill-buffer (current-buffer))))
18344 (org-install-agenda-files-menu)
18345 (message "New agenda file list installed"))
18346 nil 'local)
18347 (message "%s" (substitute-command-keys
18348 "Edit list and finish with \\[save-buffer]")))
18349 (customize-variable 'org-agenda-files)))
18351 (defun org-store-new-agenda-file-list (list)
18352 "Set new value for the agenda file list and save it correctly."
18353 (if (stringp org-agenda-files)
18354 (let ((fe (org-read-agenda-file-list t)) b u)
18355 (while (setq b (find-buffer-visiting org-agenda-files))
18356 (kill-buffer b))
18357 (with-temp-file org-agenda-files
18358 (insert
18359 (mapconcat
18360 (lambda (f) ;; Keep un-expanded entries.
18361 (if (setq u (assoc f fe))
18362 (cdr u)
18364 list "\n")
18365 "\n")))
18366 (let ((org-mode-hook nil) (org-inhibit-startup t)
18367 (org-insert-mode-line-in-empty-file nil))
18368 (setq org-agenda-files list)
18369 (customize-save-variable 'org-agenda-files org-agenda-files))))
18371 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18372 "Read the list of agenda files from a file.
18373 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18374 filenames, used by `org-store-new-agenda-file-list' to write back
18375 un-expanded file names."
18376 (when (file-directory-p org-agenda-files)
18377 (error "`org-agenda-files' cannot be a single directory"))
18378 (when (stringp org-agenda-files)
18379 (with-temp-buffer
18380 (insert-file-contents org-agenda-files)
18381 (mapcar
18382 (lambda (f)
18383 (let ((e (expand-file-name (substitute-in-file-name f)
18384 org-directory)))
18385 (if pair-with-expansion
18386 (cons e f)
18387 e)))
18388 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18390 ;;;###autoload
18391 (defun org-cycle-agenda-files ()
18392 "Cycle through the files in `org-agenda-files'.
18393 If the current buffer visits an agenda file, find the next one in the list.
18394 If the current buffer does not, find the first agenda file."
18395 (interactive)
18396 (let* ((fs (or (org-agenda-files t)
18397 (user-error "No agenda files")))
18398 (files (copy-sequence fs))
18399 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18400 file)
18401 (when tcf
18402 (while (and (setq file (pop files))
18403 (not (equal (file-truename file) tcf)))))
18404 (find-file (car (or files fs)))
18405 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18407 (defun org-agenda-file-to-front (&optional to-end)
18408 "Move/add the current file to the top of the agenda file list.
18409 If the file is not present in the list, it is added to the front. If it is
18410 present, it is moved there. With optional argument TO-END, add/move to the
18411 end of the list."
18412 (interactive "P")
18413 (let ((org-agenda-skip-unavailable-files nil)
18414 (file-alist (mapcar (lambda (x)
18415 (cons (file-truename x) x))
18416 (org-agenda-files t)))
18417 (ctf (file-truename
18418 (or buffer-file-name
18419 (user-error "Please save the current buffer to a file"))))
18420 x had)
18421 (setq x (assoc ctf file-alist) had x)
18423 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18424 (if to-end
18425 (setq file-alist (append (delq x file-alist) (list x)))
18426 (setq file-alist (cons x (delq x file-alist))))
18427 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18428 (org-install-agenda-files-menu)
18429 (message "File %s to %s of agenda file list"
18430 (if had "moved" "added") (if to-end "end" "front"))))
18432 (defun org-remove-file (&optional file)
18433 "Remove current file from the list of files in variable `org-agenda-files'.
18434 These are the files which are being checked for agenda entries.
18435 Optional argument FILE means use this file instead of the current."
18436 (interactive)
18437 (let* ((org-agenda-skip-unavailable-files nil)
18438 (file (or file buffer-file-name
18439 (user-error "Current buffer does not visit a file")))
18440 (true-file (file-truename file))
18441 (afile (abbreviate-file-name file))
18442 (files (delq nil (mapcar
18443 (lambda (x)
18444 (unless (equal true-file
18445 (file-truename x))
18447 (org-agenda-files t)))))
18448 (if (not (= (length files) (length (org-agenda-files t))))
18449 (progn
18450 (org-store-new-agenda-file-list files)
18451 (org-install-agenda-files-menu)
18452 (message "Removed from Org Agenda list: %s" afile))
18453 (message "File was not in list: %s (not removed)" afile))))
18455 (defun org-file-menu-entry (file)
18456 (vector file (list 'find-file file) t))
18458 (defun org-check-agenda-file (file)
18459 "Make sure FILE exists. If not, ask user what to do."
18460 (unless (file-exists-p file)
18461 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18462 (abbreviate-file-name file))
18463 (let ((r (downcase (read-char-exclusive))))
18464 (cond
18465 ((equal r ?r)
18466 (org-remove-file file)
18467 (throw 'nextfile t))
18468 (t (user-error "Abort"))))))
18470 (defun org-get-agenda-file-buffer (file)
18471 "Get an agenda buffer visiting FILE.
18472 If the buffer needs to be created, add it to the list of buffers
18473 which might be released later."
18474 (let ((buf (org-find-base-buffer-visiting file)))
18475 (if buf
18476 buf ; just return it
18477 ;; Make a new buffer and remember it
18478 (setq buf (find-file-noselect file))
18479 (when buf (push buf org-agenda-new-buffers))
18480 buf)))
18482 (defun org-release-buffers (blist)
18483 "Release all buffers in list, asking the user for confirmation when needed.
18484 When a buffer is unmodified, it is just killed. When modified, it is saved
18485 \(if the user agrees) and then killed."
18486 (let (file)
18487 (dolist (buf blist)
18488 (setq file (buffer-file-name buf))
18489 (when (and (buffer-modified-p buf)
18490 file
18491 (y-or-n-p (format "Save file %s? " file)))
18492 (with-current-buffer buf (save-buffer)))
18493 (kill-buffer buf))))
18495 (defun org-agenda-prepare-buffers (files)
18496 "Create buffers for all agenda files, protect archived trees and comments."
18497 (interactive)
18498 (let ((pa '(:org-archived t))
18499 (pc '(:org-comment t))
18500 (pall '(:org-archived t :org-comment t))
18501 (inhibit-read-only t)
18502 (org-inhibit-startup org-agenda-inhibit-startup)
18503 (rea (concat ":" org-archive-tag ":"))
18504 re pos)
18505 (setq org-tag-alist-for-agenda nil
18506 org-tag-groups-alist-for-agenda nil)
18507 (save-excursion
18508 (save-restriction
18509 (dolist (file files)
18510 (catch 'nextfile
18511 (if (bufferp file)
18512 (set-buffer file)
18513 (org-check-agenda-file file)
18514 (set-buffer (org-get-agenda-file-buffer file)))
18515 (widen)
18516 (org-set-regexps-and-options 'tags-only)
18517 (setq pos (point))
18518 (or (memq 'category org-agenda-ignore-properties)
18519 (org-refresh-category-properties))
18520 (or (memq 'stats org-agenda-ignore-properties)
18521 (org-refresh-stats-properties))
18522 (or (memq 'effort org-agenda-ignore-properties)
18523 (org-refresh-effort-properties))
18524 (or (memq 'appt org-agenda-ignore-properties)
18525 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18526 (setq org-todo-keywords-for-agenda
18527 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18528 (setq org-done-keywords-for-agenda
18529 (append org-done-keywords-for-agenda org-done-keywords))
18530 (setq org-todo-keyword-alist-for-agenda
18531 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18532 (setq org-tag-alist-for-agenda
18533 (org-uniquify
18534 (append org-tag-alist-for-agenda
18535 org-current-tag-alist)))
18536 ;; Merge current file's tag groups into global
18537 ;; `org-tag-groups-alist-for-agenda'.
18538 (when org-group-tags
18539 (dolist (alist org-tag-groups-alist)
18540 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18541 (if old
18542 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18543 (push alist org-tag-groups-alist-for-agenda)))))
18544 (org-with-silent-modifications
18545 (save-excursion
18546 (remove-text-properties (point-min) (point-max) pall)
18547 (when org-agenda-skip-archived-trees
18548 (goto-char (point-min))
18549 (while (re-search-forward rea nil t)
18550 (when (org-at-heading-p t)
18551 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18552 (goto-char (point-min))
18553 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18554 (while (re-search-forward re nil t)
18555 (when (save-match-data (org-in-commented-heading-p t))
18556 (add-text-properties
18557 (match-beginning 0) (org-end-of-subtree t) pc)))))
18558 (goto-char pos)))))
18559 (setq org-todo-keywords-for-agenda
18560 (org-uniquify org-todo-keywords-for-agenda))
18561 (setq org-todo-keyword-alist-for-agenda
18562 (org-uniquify org-todo-keyword-alist-for-agenda))))
18565 ;;;; CDLaTeX minor mode
18567 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18568 "Keymap for the minor `org-cdlatex-mode'.")
18570 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18571 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18572 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18573 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18574 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18576 (defvar org-cdlatex-texmathp-advice-is-done nil
18577 "Flag remembering if we have applied the advice to texmathp already.")
18579 (define-minor-mode org-cdlatex-mode
18580 "Toggle the minor `org-cdlatex-mode'.
18581 This mode supports entering LaTeX environment and math in LaTeX fragments
18582 in Org mode.
18583 \\{org-cdlatex-mode-map}"
18584 nil " OCDL" nil
18585 (when org-cdlatex-mode
18586 (require 'cdlatex)
18587 (run-hooks 'cdlatex-mode-hook)
18588 (cdlatex-compute-tables))
18589 (unless org-cdlatex-texmathp-advice-is-done
18590 (setq org-cdlatex-texmathp-advice-is-done t)
18591 (defadvice texmathp (around org-math-always-on activate)
18592 "Always return t in Org buffers.
18593 This is because we want to insert math symbols without dollars even outside
18594 the LaTeX math segments. If Org mode thinks that point is actually inside
18595 an embedded LaTeX fragment, let `texmathp' do its job.
18596 `\\[org-cdlatex-mode-map]'"
18597 (interactive)
18598 (let (p)
18599 (cond
18600 ((not (derived-mode-p 'org-mode)) ad-do-it)
18601 ((eq this-command 'cdlatex-math-symbol)
18602 (setq ad-return-value t
18603 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18605 (let ((p (org-inside-LaTeX-fragment-p)))
18606 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18607 (setq ad-return-value t
18608 texmathp-why '("Org mode embedded math" . 0))
18609 (when p ad-do-it)))))))))
18611 (defun turn-on-org-cdlatex ()
18612 "Unconditionally turn on `org-cdlatex-mode'."
18613 (org-cdlatex-mode 1))
18615 (defun org-try-cdlatex-tab ()
18616 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18617 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18618 - inside a LaTeX fragment, or
18619 - after the first word in a line, where an abbreviation expansion could
18620 insert a LaTeX environment."
18621 (when org-cdlatex-mode
18622 (cond
18623 ;; Before any word on the line: No expansion possible.
18624 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18625 ;; Just after first word on the line: Expand it. Make sure it
18626 ;; cannot happen on headlines, though.
18627 ((save-excursion
18628 (skip-chars-backward "a-zA-Z0-9*")
18629 (skip-chars-backward " \t")
18630 (and (bolp) (not (org-at-heading-p))))
18631 (cdlatex-tab) t)
18632 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18634 (defun org-cdlatex-underscore-caret (&optional _arg)
18635 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18636 Revert to the normal definition outside of these fragments."
18637 (interactive "P")
18638 (if (org-inside-LaTeX-fragment-p)
18639 (call-interactively 'cdlatex-sub-superscript)
18640 (let (org-cdlatex-mode)
18641 (call-interactively (key-binding (vector last-input-event))))))
18643 (defun org-cdlatex-math-modify (&optional _arg)
18644 "Execute `cdlatex-math-modify' in LaTeX fragments.
18645 Revert to the normal definition outside of these fragments."
18646 (interactive "P")
18647 (if (org-inside-LaTeX-fragment-p)
18648 (call-interactively 'cdlatex-math-modify)
18649 (let (org-cdlatex-mode)
18650 (call-interactively (key-binding (vector last-input-event))))))
18652 (defun org-cdlatex-environment-indent (&optional environment item)
18653 "Execute `cdlatex-environment' and indent the inserted environment.
18655 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18657 The inserted environment is indented to current indentation
18658 unless point is at the beginning of the line, in which the
18659 environment remains unintended."
18660 (interactive)
18661 ;; cdlatex-environment always return nil. Therefore, capture output
18662 ;; first and determine if an environment was selected.
18663 (let* ((beg (point-marker))
18664 (end (copy-marker (point) t))
18665 (inserted (progn
18666 (ignore-errors (cdlatex-environment environment item))
18667 (< beg end)))
18668 ;; Figure out how many lines to move forward after the
18669 ;; environment has been inserted.
18670 (lines (when inserted
18671 (save-excursion
18672 (- (cl-loop while (< beg (point))
18673 with x = 0
18674 do (forward-line -1)
18675 (cl-incf x)
18676 finally return x)
18677 (if (progn (goto-char beg)
18678 (and (progn (skip-chars-forward " \t") (eolp))
18679 (progn (skip-chars-backward " \t") (bolp))))
18680 1 0)))))
18681 (env (org-trim (delete-and-extract-region beg end))))
18682 (when inserted
18683 ;; Get indentation of next line unless at column 0.
18684 (let ((ind (if (bolp) 0
18685 (save-excursion
18686 (org-return-indent)
18687 (prog1 (org-get-indentation)
18688 (when (progn (skip-chars-forward " \t") (eolp))
18689 (delete-region beg (point)))))))
18690 (bol (progn (skip-chars-backward " \t") (bolp))))
18691 ;; Insert a newline before environment unless at column zero
18692 ;; to "escape" the current line. Insert a newline if
18693 ;; something is one the same line as \end{ENVIRONMENT}.
18694 (insert
18695 (concat (unless bol "\n") env
18696 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18697 (unless (zerop ind)
18698 (save-excursion
18699 (goto-char beg)
18700 (while (< (point) end)
18701 (unless (eolp) (indent-line-to ind))
18702 (forward-line))))
18703 (goto-char beg)
18704 (forward-line lines)
18705 (indent-line-to ind)))
18706 (set-marker beg nil)
18707 (set-marker end nil)))
18710 ;;;; LaTeX fragments
18712 (defun org-inside-LaTeX-fragment-p ()
18713 "Test if point is inside a LaTeX fragment.
18714 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18715 sequence appearing also before point.
18716 Even though the matchers for math are configurable, this function assumes
18717 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18718 delimiters are skipped when they have been removed by customization.
18719 The return value is nil, or a cons cell with the delimiter and the
18720 position of this delimiter.
18722 This function does a reasonably good job, but can locally be fooled by
18723 for example currency specifications. For example it will assume being in
18724 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18725 fragments that are properly closed, but during editing, we have to live
18726 with the uncertainty caused by missing closing delimiters. This function
18727 looks only before point, not after."
18728 (catch 'exit
18729 (let ((pos (point))
18730 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18731 (lim (save-excursion (org-backward-paragraph) (point)))
18732 dd-on str (start 0) m re)
18733 (goto-char pos)
18734 (when dodollar
18735 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18736 re (nth 1 (assoc "$" org-latex-regexps)))
18737 (while (string-match re str start)
18738 (cond
18739 ((= (match-end 0) (length str))
18740 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18741 ((= (match-end 0) (- (length str) 5))
18742 (throw 'exit nil))
18743 (t (setq start (match-end 0))))))
18744 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18745 (goto-char pos)
18746 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18747 (and (match-beginning 2) (throw 'exit nil))
18748 ;; count $$
18749 (while (re-search-backward "\\$\\$" lim t)
18750 (setq dd-on (not dd-on)))
18751 (goto-char pos)
18752 (when dd-on (cons "$$" m))))))
18754 (defun org-inside-latex-macro-p ()
18755 "Is point inside a LaTeX macro or its arguments?"
18756 (save-match-data
18757 (org-in-regexp
18758 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18760 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18761 "Build an overlay between BEG and END using IMAGE file.
18762 Argument IMAGETYPE is the extension of the displayed image,
18763 as a string. It defaults to \"png\"."
18764 (let ((ov (make-overlay beg end))
18765 (imagetype (or (intern imagetype) 'png)))
18766 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18767 (overlay-put ov 'evaporate t)
18768 (overlay-put ov
18769 'modification-hooks
18770 (list (lambda (o _flag _beg _end &optional _l)
18771 (delete-overlay o))))
18772 (overlay-put ov
18773 'display
18774 (list 'image :type imagetype :file image :ascent 'center))))
18776 (defun org--list-latex-overlays (&optional beg end)
18777 "List all Org LaTeX overlays in current buffer.
18778 Limit to overlays between BEG and END when those are provided."
18779 (cl-remove-if-not
18780 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18781 (overlays-in (or beg (point-min)) (or end (point-max)))))
18783 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18784 "Remove all overlays with LaTeX fragment images in current buffer.
18785 When optional arguments BEG and END are non-nil, remove all
18786 overlays between them instead. Return a non-nil value when some
18787 overlays were removed, nil otherwise."
18788 (let ((overlays (org--list-latex-overlays beg end)))
18789 (mapc #'delete-overlay overlays)
18790 overlays))
18792 (defun org-toggle-latex-fragment (&optional arg)
18793 "Preview the LaTeX fragment at point, or all locally or globally.
18795 If the cursor is on a LaTeX fragment, create the image and overlay
18796 it over the source code, if there is none. Remove it otherwise.
18797 If there is no fragment at point, display all fragments in the
18798 current section.
18800 With prefix ARG, preview or clear image for all fragments in the
18801 current subtree or in the whole buffer when used before the first
18802 headline. With a prefix ARG `\\[universal-argument] \
18803 \\[universal-argument]' preview or clear images
18804 for all fragments in the buffer."
18805 (interactive "P")
18806 (when (display-graphic-p)
18807 (catch 'exit
18808 (save-excursion
18809 (let (beg end msg)
18810 (cond
18811 ((or (equal arg '(16))
18812 (and (equal arg '(4))
18813 (org-with-limited-levels (org-before-first-heading-p))))
18814 (if (org-remove-latex-fragment-image-overlays)
18815 (progn (message "LaTeX fragments images removed from buffer")
18816 (throw 'exit nil))
18817 (setq msg "Creating images for buffer...")))
18818 ((equal arg '(4))
18819 (org-with-limited-levels (org-back-to-heading t))
18820 (setq beg (point))
18821 (setq end (progn (org-end-of-subtree t) (point)))
18822 (if (org-remove-latex-fragment-image-overlays beg end)
18823 (progn
18824 (message "LaTeX fragment images removed from subtree")
18825 (throw 'exit nil))
18826 (setq msg "Creating images for subtree...")))
18827 ((let ((datum (org-element-context)))
18828 (when (memq (org-element-type datum)
18829 '(latex-environment latex-fragment))
18830 (setq beg (org-element-property :begin datum))
18831 (setq end (org-element-property :end datum))
18832 (if (org-remove-latex-fragment-image-overlays beg end)
18833 (progn (message "LaTeX fragment image removed")
18834 (throw 'exit nil))
18835 (setq msg "Creating image...")))))
18837 (org-with-limited-levels
18838 (setq beg (if (org-at-heading-p) (line-beginning-position)
18839 (outline-previous-heading)
18840 (point)))
18841 (setq end (progn (outline-next-heading) (point)))
18842 (if (org-remove-latex-fragment-image-overlays beg end)
18843 (progn
18844 (message "LaTeX fragment images removed from section")
18845 (throw 'exit nil))
18846 (setq msg "Creating images for section...")))))
18847 (let ((file (buffer-file-name (buffer-base-buffer))))
18848 (org-format-latex
18849 (concat org-preview-latex-image-directory "org-ltximg")
18850 beg end
18851 ;; Emacs cannot overlay images from remote hosts. Create
18852 ;; it in `temporary-file-directory' instead.
18853 (if (or (not file) (file-remote-p file))
18854 temporary-file-directory
18855 default-directory)
18856 'overlays msg 'forbuffer org-preview-latex-default-process))
18857 (message (concat msg "done")))))))
18859 (defun org-format-latex
18860 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18861 "Replace LaTeX fragments with links to an image.
18863 The function takes care of creating the replacement image.
18865 Only consider fragments between BEG and END when those are
18866 provided.
18868 When optional argument OVERLAYS is non-nil, display the image on
18869 top of the fragment instead of replacing it.
18871 PROCESSING-TYPE is the conversion method to use, as a symbol.
18873 Some of the options can be changed using the variable
18874 `org-format-latex-options', which see."
18875 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18876 (unless (eq processing-type 'verbatim)
18877 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18878 (cnt 0)
18879 checkdir-flag)
18880 (goto-char (or beg (point-min)))
18881 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18882 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18883 (overlay-recenter (or end (point-max))))
18884 (while (re-search-forward math-regexp end t)
18885 (unless (and overlays
18886 (eq (get-char-property (point) 'org-overlay-type)
18887 'org-latex-overlay))
18888 (let* ((context (org-element-context))
18889 (type (org-element-type context)))
18890 (when (memq type '(latex-environment latex-fragment))
18891 (let ((block-type (eq type 'latex-environment))
18892 (value (org-element-property :value context))
18893 (beg (org-element-property :begin context))
18894 (end (save-excursion
18895 (goto-char (org-element-property :end context))
18896 (skip-chars-backward " \r\t\n")
18897 (point))))
18898 (cond
18899 ((eq processing-type 'mathjax)
18900 ;; Prepare for MathJax processing.
18901 (if (not (string-match "\\`\\$\\$?" value))
18902 (goto-char end)
18903 (delete-region beg end)
18904 (if (string= (match-string 0 value) "$$")
18905 (insert "\\[" (substring value 2 -2) "\\]")
18906 (insert "\\(" (substring value 1 -1) "\\)"))))
18907 ((assq processing-type org-preview-latex-process-alist)
18908 ;; Process to an image.
18909 (cl-incf cnt)
18910 (goto-char beg)
18911 (let* ((processing-info
18912 (cdr (assq processing-type org-preview-latex-process-alist)))
18913 (face (face-at-point))
18914 ;; Get the colors from the face at point.
18916 (let ((color (plist-get org-format-latex-options
18917 :foreground)))
18918 (if (and forbuffer (eq color 'auto))
18919 (face-attribute face :foreground nil 'default)
18920 color)))
18922 (let ((color (plist-get org-format-latex-options
18923 :background)))
18924 (if (and forbuffer (eq color 'auto))
18925 (face-attribute face :background nil 'default)
18926 color)))
18927 (hash (sha1 (prin1-to-string
18928 (list org-format-latex-header
18929 org-latex-default-packages-alist
18930 org-latex-packages-alist
18931 org-format-latex-options
18932 forbuffer value fg bg))))
18933 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18934 (absprefix (expand-file-name prefix dir))
18935 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18936 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18937 (sep (and block-type "\n\n"))
18938 (link (concat sep "[[file:" linkfile "]]" sep))
18939 (options
18940 (org-combine-plists
18941 org-format-latex-options
18942 `(:foreground ,fg :background ,bg))))
18943 (when msg (message msg cnt))
18944 (unless checkdir-flag ; Ensure the directory exists.
18945 (setq checkdir-flag t)
18946 (let ((todir (file-name-directory absprefix)))
18947 (unless (file-directory-p todir)
18948 (make-directory todir t))))
18949 (unless (file-exists-p movefile)
18950 (org-create-formula-image
18951 value movefile options forbuffer processing-type))
18952 (if overlays
18953 (progn
18954 (dolist (o (overlays-in beg end))
18955 (when (eq (overlay-get o 'org-overlay-type)
18956 'org-latex-overlay)
18957 (delete-overlay o)))
18958 (org--format-latex-make-overlay beg end movefile imagetype)
18959 (goto-char end))
18960 (delete-region beg end)
18961 (insert
18962 (org-add-props link
18963 (list 'org-latex-src
18964 (replace-regexp-in-string "\"" "" value)
18965 'org-latex-src-embed-type
18966 (if block-type 'paragraph 'character)))))))
18967 ((eq processing-type 'mathml)
18968 ;; Process to MathML.
18969 (unless (org-format-latex-mathml-available-p)
18970 (user-error "LaTeX to MathML converter not configured"))
18971 (cl-incf cnt)
18972 (when msg (message msg cnt))
18973 (goto-char beg)
18974 (delete-region beg end)
18975 (insert (org-format-latex-as-mathml
18976 value block-type prefix dir)))
18978 (error "Unknown conversion process %s for LaTeX fragments"
18979 processing-type)))))))))))
18981 (defun org-create-math-formula (latex-frag &optional mathml-file)
18982 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18983 Use `org-latex-to-mathml-convert-command'. If the conversion is
18984 sucessful, return the portion between \"<math...> </math>\"
18985 elements otherwise return nil. When MATHML-FILE is specified,
18986 write the results in to that file. When invoked as an
18987 interactive command, prompt for LATEX-FRAG, with initial value
18988 set to the current active region and echo the results for user
18989 inspection."
18990 (interactive (list (let ((frag (when (org-region-active-p)
18991 (buffer-substring-no-properties
18992 (region-beginning) (region-end)))))
18993 (read-string "LaTeX Fragment: " frag nil frag))))
18994 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18995 (let* ((tmp-in-file
18996 (let ((file (file-relative-name
18997 (make-temp-name (expand-file-name "ltxmathml-in")))))
18998 (write-region latex-frag nil file)
18999 file))
19000 (tmp-out-file (file-relative-name
19001 (make-temp-name (expand-file-name "ltxmathml-out"))))
19002 (cmd (format-spec
19003 org-latex-to-mathml-convert-command
19004 `((?j . ,(and org-latex-to-mathml-jar-file
19005 (shell-quote-argument
19006 (expand-file-name
19007 org-latex-to-mathml-jar-file))))
19008 (?I . ,(shell-quote-argument tmp-in-file))
19009 (?i . ,latex-frag)
19010 (?o . ,(shell-quote-argument tmp-out-file)))))
19011 mathml shell-command-output)
19012 (when (called-interactively-p 'any)
19013 (unless (org-format-latex-mathml-available-p)
19014 (user-error "LaTeX to MathML converter not configured")))
19015 (message "Running %s" cmd)
19016 (setq shell-command-output (shell-command-to-string cmd))
19017 (setq mathml
19018 (when (file-readable-p tmp-out-file)
19019 (with-current-buffer (find-file-noselect tmp-out-file t)
19020 (goto-char (point-min))
19021 (when (re-search-forward
19022 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19023 (regexp-quote
19024 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19025 nil t)
19026 (prog1 (match-string 0) (kill-buffer))))))
19027 (cond
19028 (mathml
19029 (setq mathml
19030 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19031 (when mathml-file
19032 (write-region mathml nil mathml-file))
19033 (when (called-interactively-p 'any)
19034 (message mathml)))
19035 ((message "LaTeX to MathML conversion failed")
19036 (message shell-command-output)))
19037 (delete-file tmp-in-file)
19038 (when (file-exists-p tmp-out-file)
19039 (delete-file tmp-out-file))
19040 mathml))
19042 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19043 prefix &optional dir)
19044 "Use `org-create-math-formula' but check local cache first."
19045 (let* ((absprefix (expand-file-name prefix dir))
19046 (print-length nil) (print-level nil)
19047 (formula-id (concat
19048 "formula-"
19049 (sha1
19050 (prin1-to-string
19051 (list latex-frag
19052 org-latex-to-mathml-convert-command)))))
19053 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19054 (formula-cache-dir (file-name-directory formula-cache)))
19056 (unless (file-directory-p formula-cache-dir)
19057 (make-directory formula-cache-dir t))
19059 (unless (file-exists-p formula-cache)
19060 (org-create-math-formula latex-frag formula-cache))
19062 (if (file-exists-p formula-cache)
19063 ;; Successful conversion. Return the link to MathML file.
19064 (org-add-props
19065 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19066 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19067 'org-latex-src-embed-type (if latex-frag-type
19068 'paragraph 'character)))
19069 ;; Failed conversion. Return the LaTeX fragment verbatim
19070 latex-frag)))
19072 (defun org--get-display-dpi ()
19073 "Get the DPI of the display.
19074 The function assumes that the display has the same pixel width in
19075 the horizontal and vertical directions."
19076 (if (display-graphic-p)
19077 (round (/ (display-pixel-height)
19078 (/ (display-mm-height) 25.4)))
19079 (error "Attempt to calculate the dpi of a non-graphic display")))
19081 (defun org-create-formula-image
19082 (string tofile options buffer &optional processing-type)
19083 "Create an image from LaTeX source using external processes.
19085 The LaTeX STRING is saved to a temporary LaTeX file, then
19086 converted to an image file by process PROCESSING-TYPE defined in
19087 `org-preview-latex-process-alist'. A nil value defaults to
19088 `org-preview-latex-default-process'.
19090 The generated image file is eventually moved to TOFILE.
19092 The OPTIONS argument controls the size, foreground color and
19093 background color of the generated image.
19095 When BUFFER non-nil, this function is used for LaTeX previewing.
19096 Otherwise, it is used to deal with LaTeX snippets showed in
19097 a HTML file."
19098 (let* ((processing-type (or processing-type
19099 org-preview-latex-default-process))
19100 (processing-info
19101 (cdr (assq processing-type org-preview-latex-process-alist)))
19102 (programs (plist-get processing-info :programs))
19103 (error-message (or (plist-get processing-info :message) ""))
19104 (use-xcolor (plist-get processing-info :use-xcolor))
19105 (image-input-type (plist-get processing-info :image-input-type))
19106 (image-output-type (plist-get processing-info :image-output-type))
19107 (post-clean (or (plist-get processing-info :post-clean)
19108 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19109 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19110 (latex-header
19111 (or (plist-get processing-info :latex-header)
19112 (org-latex-make-preamble
19113 (org-export-get-environment (org-export-get-backend 'latex))
19114 org-format-latex-header
19115 'snippet)))
19116 (latex-compiler (plist-get processing-info :latex-compiler))
19117 (image-converter (plist-get processing-info :image-converter))
19118 (tmpdir temporary-file-directory)
19119 (texfilebase (make-temp-name
19120 (expand-file-name "orgtex" tmpdir)))
19121 (texfile (concat texfilebase ".tex"))
19122 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19123 '(1.0 . 1.0)))
19124 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19125 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19126 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19127 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19128 "Black"))
19129 (bg (or (plist-get options (if buffer :background :html-background))
19130 "Transparent"))
19131 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19132 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19133 (dolist (program programs)
19134 (org-check-external-command program error-message))
19135 (if use-xcolor
19136 (progn (if (eq fg 'default)
19137 (setq fg (org-latex-color :foreground))
19138 (setq fg (org-latex-color-format fg)))
19139 (if (eq bg 'default)
19140 (setq bg (org-latex-color :background))
19141 (setq bg (org-latex-color-format
19142 (if (string= bg "Transparent") "white" bg))))
19143 (with-temp-file texfile
19144 (insert latex-header)
19145 (insert "\n\\begin{document}\n"
19146 "\\definecolor{fg}{rgb}{" fg "}\n"
19147 "\\definecolor{bg}{rgb}{" bg "}\n"
19148 "\n\\pagecolor{bg}\n"
19149 "\n{\\color{fg}\n"
19150 string
19151 "\n}\n"
19152 "\n\\end{document}\n")))
19153 (if (eq fg 'default)
19154 (setq fg (org-dvipng-color :foreground))
19155 (unless (string= fg "Transparent")
19156 (setq fg (org-dvipng-color-format fg))))
19157 (if (eq bg 'default)
19158 (setq bg (org-dvipng-color :background))
19159 (unless (string= bg "Transparent")
19160 (setq bg (org-dvipng-color-format bg))))
19161 (with-temp-file texfile
19162 (insert latex-header)
19163 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19165 (let* ((err-msg (format "Please adjust `%s' part of \
19166 `org-preview-latex-process-alist'."
19167 processing-type))
19168 (image-input-file
19169 (org-compile-file
19170 texfile latex-compiler image-input-type err-msg log-buf))
19171 (image-output-file
19172 (org-compile-file
19173 image-input-file image-converter image-output-type err-msg log-buf
19174 `((?F . ,(shell-quote-argument fg))
19175 (?B . ,(shell-quote-argument bg))
19176 (?D . ,(shell-quote-argument (format "%s" dpi)))
19177 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19178 (copy-file image-output-file tofile 'replace)
19179 (dolist (e post-clean)
19180 (when (file-exists-p (concat texfilebase e))
19181 (delete-file (concat texfilebase e))))
19182 image-output-file)))
19184 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19185 "Fill a LaTeX header template TPL.
19186 In the template, the following place holders will be recognized:
19188 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19189 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19190 [PACKAGES] \\usepackage statements for PKG
19191 [NO-PACKAGES] do not include PKG
19192 [EXTRA] the string EXTRA
19193 [NO-EXTRA] do not include EXTRA
19195 For backward compatibility, if both the positive and the negative place
19196 holder is missing, the positive one (without the \"NO-\") will be
19197 assumed to be present at the end of the template.
19198 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19199 EXTRA is a string.
19200 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19201 (let (rpl (end ""))
19202 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19203 (setq rpl (if (or (match-end 1) (not def-pkg))
19204 "" (org-latex-packages-to-string def-pkg snippets-p t))
19205 tpl (replace-match rpl t t tpl))
19206 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19208 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19209 (setq rpl (if (or (match-end 1) (not pkg))
19210 "" (org-latex-packages-to-string pkg snippets-p t))
19211 tpl (replace-match rpl t t tpl))
19212 (when pkg (setq end
19213 (concat end "\n"
19214 (org-latex-packages-to-string pkg snippets-p)))))
19216 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19217 (setq rpl (if (or (match-end 1) (not extra))
19218 "" (concat extra "\n"))
19219 tpl (replace-match rpl t t tpl))
19220 (when (and extra (string-match "\\S-" extra))
19221 (setq end (concat end "\n" extra))))
19223 (if (string-match "\\S-" end)
19224 (concat tpl "\n" end)
19225 tpl)))
19227 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19228 "Turn an alist of packages into a string with the \\usepackage macros."
19229 (setq pkg (mapconcat (lambda(p)
19230 (cond
19231 ((stringp p) p)
19232 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19233 (format "%% Package %s omitted" (cadr p)))
19234 ((equal "" (car p))
19235 (format "\\usepackage{%s}" (cadr p)))
19237 (format "\\usepackage[%s]{%s}"
19238 (car p) (cadr p)))))
19240 "\n"))
19241 (if newline (concat pkg "\n") pkg))
19243 (defun org-dvipng-color (attr)
19244 "Return a RGB color specification for dvipng."
19245 (org-dvipng-color-format (face-attribute 'default attr nil)))
19247 (defun org-dvipng-color-format (color-name)
19248 "Convert COLOR-NAME to a RGB color value for dvipng."
19249 (apply #'format "rgb %s %s %s"
19250 (mapcar 'org-normalize-color
19251 (color-values color-name))))
19253 (defun org-latex-color (attr)
19254 "Return a RGB color for the LaTeX color package."
19255 (org-latex-color-format (face-attribute 'default attr nil)))
19257 (defun org-latex-color-format (color-name)
19258 "Convert COLOR-NAME to a RGB color value."
19259 (apply #'format "%s,%s,%s"
19260 (mapcar 'org-normalize-color
19261 (color-values color-name))))
19263 (defun org-normalize-color (value)
19264 "Return string to be used as color value for an RGB component."
19265 (format "%g" (/ value 65535.0)))
19269 ;; Image display
19271 (defvar-local org-inline-image-overlays nil)
19273 (defun org-toggle-inline-images (&optional include-linked)
19274 "Toggle the display of inline images.
19275 INCLUDE-LINKED is passed to `org-display-inline-images'."
19276 (interactive "P")
19277 (if org-inline-image-overlays
19278 (progn
19279 (org-remove-inline-images)
19280 (when (called-interactively-p 'interactive)
19281 (message "Inline image display turned off")))
19282 (org-display-inline-images include-linked)
19283 (when (called-interactively-p 'interactive)
19284 (message (if org-inline-image-overlays
19285 (format "%d images displayed inline"
19286 (length org-inline-image-overlays))
19287 "No images to display inline")))))
19289 (defun org-redisplay-inline-images ()
19290 "Refresh the display of inline images."
19291 (interactive)
19292 (if (not org-inline-image-overlays)
19293 (org-toggle-inline-images)
19294 (org-toggle-inline-images)
19295 (org-toggle-inline-images)))
19297 (defun org-display-inline-images (&optional include-linked refresh beg end)
19298 "Display inline images.
19300 An inline image is a link which follows either of these
19301 conventions:
19303 1. Its path is a file with an extension matching return value
19304 from `image-file-name-regexp' and it has no contents.
19306 2. Its description consists in a single link of the previous
19307 type.
19309 When optional argument INCLUDE-LINKED is non-nil, also links with
19310 a text description part will be inlined. This can be nice for
19311 a quick look at those images, but it does not reflect what
19312 exported files will look like.
19314 When optional argument REFRESH is non-nil, refresh existing
19315 images between BEG and END. This will create new image displays
19316 only if necessary. BEG and END default to the buffer
19317 boundaries."
19318 (interactive "P")
19319 (when (display-graphic-p)
19320 (unless refresh
19321 (org-remove-inline-images)
19322 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19323 (org-with-wide-buffer
19324 (goto-char (or beg (point-min)))
19325 (let* ((case-fold-search t)
19326 (file-extension-re (image-file-name-regexp))
19327 (link-abbrevs (mapcar #'car
19328 (append org-link-abbrev-alist-local
19329 org-link-abbrev-alist)))
19330 ;; Check absolute, relative file names and explicit
19331 ;; "file:" links. Also check link abbreviations since
19332 ;; some might expand to "file" links.
19333 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19334 (if (not link-abbrevs) ""
19335 (format "\\|\\(?:%s:\\)"
19336 (regexp-opt link-abbrevs))))))
19337 (while (re-search-forward file-types-re end t)
19338 (let ((link (save-match-data (org-element-context))))
19339 ;; Check if we're at an inline image, i.e., an image file
19340 ;; link without a description (unless INCLUDE-LINKED is
19341 ;; non-nil).
19342 (when (and (equal "file" (org-element-property :type link))
19343 (or include-linked
19344 (null (org-element-contents link)))
19345 (string-match-p file-extension-re
19346 (org-element-property :path link)))
19347 (let ((file (expand-file-name
19348 (org-link-unescape
19349 (org-element-property :path link)))))
19350 (when (file-exists-p file)
19351 (let ((width
19352 ;; Apply `org-image-actual-width' specifications.
19353 (cond
19354 ((not (image-type-available-p 'imagemagick)) nil)
19355 ((eq org-image-actual-width t) nil)
19356 ((listp org-image-actual-width)
19358 ;; First try to find a width among
19359 ;; attributes associated to the paragraph
19360 ;; containing link.
19361 (let ((paragraph
19362 (let ((e link))
19363 (while (and (setq e (org-element-property
19364 :parent e))
19365 (not (eq (org-element-type e)
19366 'paragraph))))
19367 e)))
19368 (when paragraph
19369 (save-excursion
19370 (goto-char (org-element-property :begin paragraph))
19371 (when
19372 (re-search-forward
19373 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19374 (org-element-property
19375 :post-affiliated paragraph)
19377 (string-to-number (match-string 1))))))
19378 ;; Otherwise, fall-back to provided number.
19379 (car org-image-actual-width)))
19380 ((numberp org-image-actual-width)
19381 org-image-actual-width)))
19382 (old (get-char-property-and-overlay
19383 (org-element-property :begin link)
19384 'org-image-overlay)))
19385 (if (and (car-safe old) refresh)
19386 (image-refresh (overlay-get (cdr old) 'display))
19387 (let ((image (create-image file
19388 (and width 'imagemagick)
19390 :width width)))
19391 (when image
19392 (let ((ov (make-overlay
19393 (org-element-property :begin link)
19394 (progn
19395 (goto-char
19396 (org-element-property :end link))
19397 (skip-chars-backward " \t")
19398 (point)))))
19399 (overlay-put ov 'display image)
19400 (overlay-put ov 'face 'default)
19401 (overlay-put ov 'org-image-overlay t)
19402 (overlay-put
19403 ov 'modification-hooks
19404 (list 'org-display-inline-remove-overlay))
19405 (push ov org-inline-image-overlays)))))))))))))))
19407 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19408 "Remove inline-display overlay if a corresponding region is modified."
19409 (let ((inhibit-modification-hooks t))
19410 (when (and ov after)
19411 (delete ov org-inline-image-overlays)
19412 (delete-overlay ov))))
19414 (defun org-remove-inline-images ()
19415 "Remove inline display of images."
19416 (interactive)
19417 (mapc #'delete-overlay org-inline-image-overlays)
19418 (setq org-inline-image-overlays nil))
19420 ;;;; Key bindings
19422 (defun org-remap (map &rest commands)
19423 "In MAP, remap the functions given in COMMANDS.
19424 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19425 (let (new old)
19426 (while commands
19427 (setq old (pop commands) new (pop commands))
19428 (org-defkey map (vector 'remap old) new))))
19430 ;; Outline functions from `outline-mode-prefix-map'
19431 ;; that can be remapped in Org:
19432 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19433 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19434 (define-key org-mode-map [remap outline-forward-same-level]
19435 'org-forward-heading-same-level)
19436 (define-key org-mode-map [remap outline-backward-same-level]
19437 'org-backward-heading-same-level)
19438 (define-key org-mode-map [remap outline-show-branches]
19439 'org-kill-note-or-show-branches)
19440 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19441 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19442 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19443 (define-key org-mode-map [remap outline-next-visible-heading]
19444 'org-next-visible-heading)
19445 (define-key org-mode-map [remap outline-previous-visible-heading]
19446 'org-previous-visible-heading)
19447 (define-key org-mode-map [remap show-children] 'org-show-children)
19449 ;; Outline functions from `outline-mode-prefix-map' that can not
19450 ;; be remapped in Org:
19452 ;; - the column "key binding" shows whether the Outline function is still
19453 ;; available in Org mode on the same key that it has been bound to in
19454 ;; Outline mode:
19455 ;; - "overridden": key used for a different functionality in Org mode
19456 ;; - else: key still bound to the same Outline function in Org mode
19458 ;; | Outline function | key binding | Org replacement |
19459 ;; |------------------------------------+-------------+--------------------------|
19460 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19461 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19462 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19463 ;; | `show-entry' | overridden | no replacement |
19464 ;; | `show-branches' | `C-c C-k' | still same function |
19465 ;; | `show-subtree' | overridden | visibility cycling |
19466 ;; | `show-all' | overridden | no replacement |
19467 ;; | `hide-subtree' | overridden | visibility cycling |
19468 ;; | `hide-body' | overridden | no replacement |
19469 ;; | `hide-entry' | overridden | visibility cycling |
19470 ;; | `hide-leaves' | overridden | no replacement |
19471 ;; | `hide-sublevels' | overridden | no replacement |
19472 ;; | `hide-other' | overridden | no replacement |
19474 ;; Make `C-c C-x' a prefix key
19475 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19477 ;; TAB key with modifiers
19478 (org-defkey org-mode-map "\C-i" 'org-cycle)
19479 (org-defkey org-mode-map [(tab)] 'org-cycle)
19480 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19481 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19483 ;; The following line is necessary under Suse GNU/Linux
19484 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19485 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19486 (define-key org-mode-map [backtab] 'org-shifttab)
19488 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19489 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19490 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19492 ;; Cursor keys with modifiers
19493 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19494 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19495 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19496 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19498 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19499 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19500 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19501 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19502 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19503 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19505 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19506 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19507 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19508 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19510 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19511 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19512 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19513 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19515 ;; Babel keys
19516 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19517 (dolist (pair org-babel-key-bindings)
19518 (define-key org-babel-map (car pair) (cdr pair)))
19520 ;;; Extra keys for tty access.
19521 ;; We only set them when really needed because otherwise the
19522 ;; menus don't show the simple keys
19524 (when (or org-use-extra-keys (not window-system))
19525 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19526 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19527 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19528 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19529 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19530 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19531 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19532 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19533 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19534 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19535 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19536 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19537 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19538 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19539 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19540 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19541 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19542 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19543 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19544 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19545 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19546 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19547 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19548 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19549 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19550 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19551 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19552 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19554 ;; All the other keys
19555 (org-remap org-mode-map
19556 'self-insert-command 'org-self-insert-command
19557 'delete-char 'org-delete-char
19558 'delete-backward-char 'org-delete-backward-char)
19559 (org-defkey org-mode-map "|" 'org-force-self-insert)
19561 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19562 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19563 (if (boundp 'narrow-map)
19564 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19565 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19566 (if (boundp 'narrow-map)
19567 (org-defkey narrow-map "b" 'org-narrow-to-block)
19568 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19569 (if (boundp 'narrow-map)
19570 (org-defkey narrow-map "e" 'org-narrow-to-element)
19571 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19572 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19573 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19574 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19575 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19576 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19577 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19578 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19579 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19580 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19581 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19582 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19583 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19584 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19585 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19586 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19587 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19588 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19589 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19590 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19591 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19592 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19593 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19594 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19595 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19596 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19597 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19598 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19599 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19600 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19601 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19602 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19603 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19604 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19605 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19606 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19607 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19608 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19609 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19610 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19611 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19612 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19613 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19614 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19615 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19616 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19617 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19618 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19619 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19620 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19621 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19622 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19623 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19624 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19625 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19626 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19627 (org-defkey org-mode-map "\C-c^" 'org-sort)
19628 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19629 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19630 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19631 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19632 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19633 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19634 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19635 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19636 (org-defkey org-mode-map "\C-m" 'org-return)
19637 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19638 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19639 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19640 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19641 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19642 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19643 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19644 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19645 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19646 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19647 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19648 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19649 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19650 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19651 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19652 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19653 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19654 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19655 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19656 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19657 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19658 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19659 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19660 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19661 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19663 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19664 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19665 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19667 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19668 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19669 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19670 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19671 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19672 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19673 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19674 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19675 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19676 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19677 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19678 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19679 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19680 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19681 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19682 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19683 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19684 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19685 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19686 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19687 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19688 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19690 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19691 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19692 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19693 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19694 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19696 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19698 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19700 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19701 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19703 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19706 (defconst org-speed-commands-default
19708 ("Outline Navigation")
19709 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19710 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19711 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19712 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19713 ("F" . org-next-block)
19714 ("B" . org-previous-block)
19715 ("u" . (org-speed-move-safe 'outline-up-heading))
19716 ("j" . org-goto)
19717 ("g" . (org-refile t))
19718 ("Outline Visibility")
19719 ("c" . org-cycle)
19720 ("C" . org-shifttab)
19721 (" " . org-display-outline-path)
19722 ("s" . org-narrow-to-subtree)
19723 ("=" . org-columns)
19724 ("Outline Structure Editing")
19725 ("U" . org-metaup)
19726 ("D" . org-metadown)
19727 ("r" . org-metaright)
19728 ("l" . org-metaleft)
19729 ("R" . org-shiftmetaright)
19730 ("L" . org-shiftmetaleft)
19731 ("i" . (progn (forward-char 1) (call-interactively
19732 'org-insert-heading-respect-content)))
19733 ("^" . org-sort)
19734 ("w" . org-refile)
19735 ("a" . org-archive-subtree-default-with-confirmation)
19736 ("@" . org-mark-subtree)
19737 ("#" . org-toggle-comment)
19738 ("Clock Commands")
19739 ("I" . org-clock-in)
19740 ("O" . org-clock-out)
19741 ("Meta Data Editing")
19742 ("t" . org-todo)
19743 ("," . (org-priority))
19744 ("0" . (org-priority ?\ ))
19745 ("1" . (org-priority ?A))
19746 ("2" . (org-priority ?B))
19747 ("3" . (org-priority ?C))
19748 (":" . org-set-tags-command)
19749 ("e" . org-set-effort)
19750 ("E" . org-inc-effort)
19751 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19752 (org-entry-put (point) "APPT_WARNTIME" m)))
19753 ("Agenda Views etc")
19754 ("v" . org-agenda)
19755 ("/" . org-sparse-tree)
19756 ("Misc")
19757 ("o" . org-open-at-point)
19758 ("?" . org-speed-command-help)
19759 ("<" . (org-agenda-set-restriction-lock 'subtree))
19760 (">" . (org-agenda-remove-restriction-lock))
19762 "The default speed commands.")
19764 (defun org-print-speed-command (e)
19765 (if (> (length (car e)) 1)
19766 (progn
19767 (princ "\n")
19768 (princ (car e))
19769 (princ "\n")
19770 (princ (make-string (length (car e)) ?-))
19771 (princ "\n"))
19772 (princ (car e))
19773 (princ " ")
19774 (if (symbolp (cdr e))
19775 (princ (symbol-name (cdr e)))
19776 (prin1 (cdr e)))
19777 (princ "\n")))
19779 (defun org-speed-command-help ()
19780 "Show the available speed commands."
19781 (interactive)
19782 (if (not org-use-speed-commands)
19783 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19784 (with-output-to-temp-buffer "*Help*"
19785 (princ "User-defined Speed commands\n===========================\n")
19786 (mapc #'org-print-speed-command org-speed-commands-user)
19787 (princ "\n")
19788 (princ "Built-in Speed commands\n=======================\n")
19789 (mapc #'org-print-speed-command org-speed-commands-default))
19790 (with-current-buffer "*Help*"
19791 (setq truncate-lines t))))
19793 (defun org-speed-move-safe (cmd)
19794 "Execute CMD, but make sure that the cursor always ends up in a headline.
19795 If not, return to the original position and throw an error."
19796 (interactive)
19797 (let ((pos (point)))
19798 (call-interactively cmd)
19799 (unless (and (bolp) (org-at-heading-p))
19800 (goto-char pos)
19801 (error "Boundary reached while executing %s" cmd))))
19803 (defvar org-self-insert-command-undo-counter 0)
19805 (defvar org-table-auto-blank-field) ; defined in org-table.el
19806 (defvar org-speed-command nil)
19808 (defun org-speed-command-activate (keys)
19809 "Hook for activating single-letter speed commands.
19810 `org-speed-commands-default' specifies a minimal command set.
19811 Use `org-speed-commands-user' for further customization."
19812 (when (or (and (bolp) (looking-at org-outline-regexp))
19813 (and (functionp org-use-speed-commands)
19814 (funcall org-use-speed-commands)))
19815 (cdr (assoc keys (append org-speed-commands-user
19816 org-speed-commands-default)))))
19818 (defun org-babel-speed-command-activate (keys)
19819 "Hook for activating single-letter code block commands."
19820 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19821 (cdr (assoc keys org-babel-key-bindings))))
19823 (defcustom org-speed-command-hook
19824 '(org-speed-command-activate org-babel-speed-command-activate)
19825 "Hook for activating speed commands at strategic locations.
19826 Hook functions are called in sequence until a valid handler is
19827 found.
19829 Each hook takes a single argument, a user-pressed command key
19830 which is also a `self-insert-command' from the global map.
19832 Within the hook, examine the cursor position and the command key
19833 and return nil or a valid handler as appropriate. Handler could
19834 be one of an interactive command, a function, or a form.
19836 Set `org-use-speed-commands' to non-nil value to enable this
19837 hook. The default setting is `org-speed-command-activate'."
19838 :group 'org-structure
19839 :version "24.1"
19840 :type 'hook)
19842 (defun org-self-insert-command (N)
19843 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19844 If the cursor is in a table looking at whitespace, the whitespace is
19845 overwritten, and the table is not marked as requiring realignment."
19846 (interactive "p")
19847 (org-check-before-invisible-edit 'insert)
19848 (cond
19849 ((and org-use-speed-commands
19850 (let ((kv (this-command-keys-vector)))
19851 (setq org-speed-command
19852 (run-hook-with-args-until-success
19853 'org-speed-command-hook
19854 (make-string 1 (aref kv (1- (length kv))))))))
19855 (cond
19856 ((commandp org-speed-command)
19857 (setq this-command org-speed-command)
19858 (call-interactively org-speed-command))
19859 ((functionp org-speed-command)
19860 (funcall org-speed-command))
19861 ((and org-speed-command (listp org-speed-command))
19862 (eval org-speed-command))
19863 (t (let (org-use-speed-commands)
19864 (call-interactively 'org-self-insert-command)))))
19865 ((and
19866 (org-at-table-p)
19867 (eq N 1)
19868 (not (org-region-active-p))
19869 (progn
19870 ;; Check if we blank the field, and if that triggers align.
19871 (and (featurep 'org-table) org-table-auto-blank-field
19872 (memq last-command
19873 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19874 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19875 ;; Got extra space, this field does not determine
19876 ;; column width.
19877 (let (org-table-may-need-update) (org-table-blank-field))
19878 ;; No extra space, this field may determine column
19879 ;; width.
19880 (org-table-blank-field)))
19882 (looking-at "[^|\n]* \\( \\)|"))
19883 ;; There is room for insertion without re-aligning the table.
19884 (delete-region (match-beginning 1) (match-end 1))
19885 (self-insert-command N))
19887 (setq org-table-may-need-update t)
19888 (self-insert-command N)
19889 (org-fix-tags-on-the-fly)
19890 (when org-self-insert-cluster-for-undo
19891 (if (not (eq last-command 'org-self-insert-command))
19892 (setq org-self-insert-command-undo-counter 1)
19893 (if (>= org-self-insert-command-undo-counter 20)
19894 (setq org-self-insert-command-undo-counter 1)
19895 (and (> org-self-insert-command-undo-counter 0)
19896 buffer-undo-list (listp buffer-undo-list)
19897 (not (cadr buffer-undo-list)) ; remove nil entry
19898 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19899 (setq org-self-insert-command-undo-counter
19900 (1+ org-self-insert-command-undo-counter))))))))
19902 (defun org-check-before-invisible-edit (kind)
19903 "Check is editing if kind KIND would be dangerous with invisible text around.
19904 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19905 ;; First, try to get out of here as quickly as possible, to reduce overhead
19906 (when (and org-catch-invisible-edits
19907 (or (not (boundp 'visible-mode)) (not visible-mode))
19908 (or (get-char-property (point) 'invisible)
19909 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19910 ;; OK, we need to take a closer look. Do not consider
19911 ;; invisibility obtained through text properties (e.g., link
19912 ;; fontification), as it cannot be toggled.
19913 (let* ((invisible-at-point
19914 (pcase (get-char-property-and-overlay (point) 'invisible)
19915 (`(,_ . ,(and (pred overlayp) o)) o)))
19916 ;; Assume that point cannot land in the middle of an
19917 ;; overlay, or between two overlays.
19918 (invisible-before-point
19919 (and (not invisible-at-point)
19920 (not (bobp))
19921 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19922 (`(,_ . ,(and (pred overlayp) o)) o))))
19923 (border-and-ok-direction
19925 ;; Check if we are acting predictably before invisible
19926 ;; text.
19927 (and invisible-at-point
19928 (memq kind '(insert delete-backward)))
19929 ;; Check if we are acting predictably after invisible text
19930 ;; This works not well, and I have turned it off. It seems
19931 ;; better to always show and stop after invisible text.
19932 ;; (and (not invisible-at-point) invisible-before-point
19933 ;; (memq kind '(insert delete)))
19935 (when (or invisible-at-point invisible-before-point)
19936 (when (eq org-catch-invisible-edits 'error)
19937 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19938 (if (and org-custom-properties-overlays
19939 (y-or-n-p "Display invisible properties in this buffer? "))
19940 (org-toggle-custom-properties-visibility)
19941 ;; Make the area visible
19942 (save-excursion
19943 (when invisible-before-point
19944 (goto-char
19945 (previous-single-char-property-change (point) 'invisible)))
19946 ;; Remove whatever overlay is currently making yet-to-be
19947 ;; edited text invisible. Also remove nested invisibility
19948 ;; related overlays.
19949 (delete-overlay (or invisible-at-point invisible-before-point))
19950 (let ((origin (if invisible-at-point (point) (1- (point)))))
19951 (while (pcase (get-char-property-and-overlay origin 'invisible)
19952 (`(,_ . ,(and (pred overlayp) o))
19953 (delete-overlay o)
19954 t)))))
19955 (cond
19956 ((eq org-catch-invisible-edits 'show)
19957 ;; That's it, we do the edit after showing
19958 (message
19959 "Unfolding invisible region around point before editing")
19960 (sit-for 1))
19961 ((and (eq org-catch-invisible-edits 'smart)
19962 border-and-ok-direction)
19963 (message "Unfolding invisible region around point before editing"))
19965 ;; Don't do the edit, make the user repeat it in full visibility
19966 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19968 (defun org-fix-tags-on-the-fly ()
19969 "Align tags in headline at point.
19970 Unlike to `org-set-tags', it ignores region and sorting."
19971 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19972 (org-at-heading-p))
19973 (let ((org-ignore-region t)
19974 (org-tags-sort-function nil))
19975 (org-set-tags nil t))))
19977 (defun org-delete-backward-char (N)
19978 "Like `delete-backward-char', insert whitespace at field end in tables.
19979 When deleting backwards, in tables this function will insert whitespace in
19980 front of the next \"|\" separator, to keep the table aligned. The table will
19981 still be marked for re-alignment if the field did fill the entire column,
19982 because, in this case the deletion might narrow the column."
19983 (interactive "p")
19984 (save-match-data
19985 (org-check-before-invisible-edit 'delete-backward)
19986 (if (and (org-at-table-p)
19987 (eq N 1)
19988 (not (org-region-active-p))
19989 (string-match "|" (buffer-substring (point-at-bol) (point)))
19990 (looking-at ".*?|"))
19991 (let ((pos (point))
19992 (noalign (looking-at "[^|\n\r]* |"))
19993 (c org-table-may-need-update))
19994 (backward-delete-char N)
19995 (unless overwrite-mode
19996 (skip-chars-forward "^|")
19997 (insert " ")
19998 (goto-char (1- pos)))
19999 ;; noalign: if there were two spaces at the end, this field
20000 ;; does not determine the width of the column.
20001 (when noalign (setq org-table-may-need-update c)))
20002 (backward-delete-char N)
20003 (org-fix-tags-on-the-fly))))
20005 (defun org-delete-char (N)
20006 "Like `delete-char', but insert whitespace at field end in tables.
20007 When deleting characters, in tables this function will insert whitespace in
20008 front of the next \"|\" separator, to keep the table aligned. The table will
20009 still be marked for re-alignment if the field did fill the entire column,
20010 because, in this case the deletion might narrow the column."
20011 (interactive "p")
20012 (save-match-data
20013 (org-check-before-invisible-edit 'delete)
20014 (if (and (org-at-table-p)
20015 (not (bolp))
20016 (not (= (char-after) ?|))
20017 (eq N 1))
20018 (if (looking-at ".*?|")
20019 (let ((pos (point))
20020 (noalign (looking-at "[^|\n\r]* |"))
20021 (c org-table-may-need-update))
20022 (replace-match
20023 (concat (substring (match-string 0) 1 -1) " |") nil t)
20024 (goto-char 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 (delete-char N))
20029 (delete-char N)
20030 (org-fix-tags-on-the-fly))))
20032 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20033 (put 'org-self-insert-command 'delete-selection
20034 (lambda ()
20035 (not (run-hook-with-args-until-success
20036 'self-insert-uses-region-functions))))
20037 (put 'orgtbl-self-insert-command 'delete-selection
20038 (lambda ()
20039 (not (run-hook-with-args-until-success
20040 'self-insert-uses-region-functions))))
20041 (put 'org-delete-char 'delete-selection 'supersede)
20042 (put 'org-delete-backward-char 'delete-selection 'supersede)
20043 (put 'org-yank 'delete-selection 'yank)
20045 ;; Make `flyspell-mode' delay after some commands
20046 (put 'org-self-insert-command 'flyspell-delayed t)
20047 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20048 (put 'org-delete-char 'flyspell-delayed t)
20049 (put 'org-delete-backward-char 'flyspell-delayed t)
20051 ;; Make pabbrev-mode expand after Org mode commands
20052 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20053 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20055 (defun org-transpose-words ()
20056 "Transpose words for Org.
20057 This uses the `org-mode-transpose-word-syntax-table' syntax
20058 table, which interprets characters in `org-emphasis-alist' as
20059 word constituents."
20060 (interactive)
20061 (with-syntax-table org-mode-transpose-word-syntax-table
20062 (call-interactively 'transpose-words)))
20063 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20065 (defvar org-ctrl-c-ctrl-c-hook nil
20066 "Hook for functions attaching themselves to `C-c C-c'.
20068 This can be used to add additional functionality to the C-c C-c
20069 key which executes context-dependent commands. This hook is run
20070 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20071 run after the last test.
20073 Each function will be called with no arguments. The function
20074 must check if the context is appropriate for it to act. If yes,
20075 it should do its thing and then return a non-nil value. If the
20076 context is wrong, just do nothing and return nil.")
20078 (defvar org-ctrl-c-ctrl-c-final-hook nil
20079 "Hook for functions attaching themselves to `C-c C-c'.
20081 This can be used to add additional functionality to the C-c C-c
20082 key which executes context-dependent commands. This hook is run
20083 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20084 before the first test.
20086 Each function will be called with no arguments. The function
20087 must check if the context is appropriate for it to act. If yes,
20088 it should do its thing and then return a non-nil value. If the
20089 context is wrong, just do nothing and return nil.")
20091 (defvar org-tab-first-hook nil
20092 "Hook for functions to attach themselves to TAB.
20093 See `org-ctrl-c-ctrl-c-hook' for more information.
20094 This hook runs as the first action when TAB is pressed, even before
20095 `org-cycle' messes around with the `outline-regexp' to cater for
20096 inline tasks and plain list item folding.
20097 If any function in this hook returns t, any other actions that
20098 would have been caused by TAB (such as table field motion or visibility
20099 cycling) will not occur.")
20101 (defvar org-tab-after-check-for-table-hook nil
20102 "Hook for functions to attach themselves to TAB.
20103 See `org-ctrl-c-ctrl-c-hook' for more information.
20104 This hook runs after it has been established that the cursor is not in a
20105 table, but before checking if the cursor is in a headline or if global cycling
20106 should be done.
20107 If any function in this hook returns t, not other actions like visibility
20108 cycling will be done.")
20110 (defvar org-tab-after-check-for-cycling-hook nil
20111 "Hook for functions to attach themselves to TAB.
20112 See `org-ctrl-c-ctrl-c-hook' for more information.
20113 This hook runs after it has been established that not table field motion and
20114 not visibility should be done because of current context. This is probably
20115 the place where a package like yasnippets can hook in.")
20117 (defvar org-tab-before-tab-emulation-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 after every other options for TAB have been exhausted, but
20121 before indentation and \t insertion takes place.")
20123 (defvar org-metaleft-hook nil
20124 "Hook for functions attaching themselves to `M-left'.
20125 See `org-ctrl-c-ctrl-c-hook' for more information.")
20126 (defvar org-metaright-hook nil
20127 "Hook for functions attaching themselves to `M-right'.
20128 See `org-ctrl-c-ctrl-c-hook' for more information.")
20129 (defvar org-metaup-hook nil
20130 "Hook for functions attaching themselves to `M-up'.
20131 See `org-ctrl-c-ctrl-c-hook' for more information.")
20132 (defvar org-metadown-hook nil
20133 "Hook for functions attaching themselves to `M-down'.
20134 See `org-ctrl-c-ctrl-c-hook' for more information.")
20135 (defvar org-shiftmetaleft-hook nil
20136 "Hook for functions attaching themselves to `M-S-left'.
20137 See `org-ctrl-c-ctrl-c-hook' for more information.")
20138 (defvar org-shiftmetaright-hook nil
20139 "Hook for functions attaching themselves to `M-S-right'.
20140 See `org-ctrl-c-ctrl-c-hook' for more information.")
20141 (defvar org-shiftmetaup-hook nil
20142 "Hook for functions attaching themselves to `M-S-up'.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-shiftmetadown-hook nil
20145 "Hook for functions attaching themselves to `M-S-down'.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.")
20147 (defvar org-metareturn-hook nil
20148 "Hook for functions attaching themselves to `M-RET'.
20149 See `org-ctrl-c-ctrl-c-hook' for more information.")
20150 (defvar org-shiftup-hook nil
20151 "Hook for functions attaching themselves to `S-up'.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.")
20153 (defvar org-shiftup-final-hook nil
20154 "Hook for functions attaching themselves to `S-up'.
20155 This one runs after all other options except shift-select have been excluded.
20156 See `org-ctrl-c-ctrl-c-hook' for more information.")
20157 (defvar org-shiftdown-hook nil
20158 "Hook for functions attaching themselves to `S-down'.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-shiftdown-final-hook nil
20161 "Hook for functions attaching themselves to `S-down'.
20162 This one runs after all other options except shift-select have been excluded.
20163 See `org-ctrl-c-ctrl-c-hook' for more information.")
20164 (defvar org-shiftleft-hook nil
20165 "Hook for functions attaching themselves to `S-left'.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.")
20167 (defvar org-shiftleft-final-hook nil
20168 "Hook for functions attaching themselves to `S-left'.
20169 This one runs after all other options except shift-select have been excluded.
20170 See `org-ctrl-c-ctrl-c-hook' for more information.")
20171 (defvar org-shiftright-hook nil
20172 "Hook for functions attaching themselves to `S-right'.
20173 See `org-ctrl-c-ctrl-c-hook' for more information.")
20174 (defvar org-shiftright-final-hook nil
20175 "Hook for functions attaching themselves to `S-right'.
20176 This one runs after all other options except shift-select have been excluded.
20177 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defun org-modifier-cursor-error ()
20180 "Throw an error, a modified cursor command was applied in wrong context."
20181 (user-error "This command is active in special context like tables, headlines or items"))
20183 (defun org-shiftselect-error ()
20184 "Throw an error because Shift-Cursor command was applied in wrong context."
20185 (if (and (boundp 'shift-select-mode) shift-select-mode)
20186 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20187 (user-error "This command works only in special context like headlines or timestamps")))
20189 (defun org-call-for-shift-select (cmd)
20190 (let ((this-command-keys-shift-translated t))
20191 (call-interactively cmd)))
20193 (defun org-shifttab (&optional arg)
20194 "Global visibility cycling or move to previous table field.
20195 Call `org-table-previous-field' within a table.
20196 When ARG is nil, cycle globally through visibility states.
20197 When ARG is a numeric prefix, show contents of this level."
20198 (interactive "P")
20199 (cond
20200 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20201 ((integerp arg)
20202 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20203 (message "Content view to level: %d" arg)
20204 (org-content (prefix-numeric-value arg2))
20205 (org-cycle-show-empty-lines t)
20206 (setq org-cycle-global-status 'overview)))
20207 (t (call-interactively 'org-global-cycle))))
20209 (defun org-shiftmetaleft ()
20210 "Promote subtree or delete table column.
20211 Calls `org-promote-subtree', `org-outdent-item-tree', or
20212 `org-table-delete-column', depending on context. See the
20213 individual commands for more information."
20214 (interactive)
20215 (cond
20216 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20217 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20218 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20219 ((if (not (org-region-active-p)) (org-at-item-p)
20220 (save-excursion (goto-char (region-beginning))
20221 (org-at-item-p)))
20222 (call-interactively 'org-outdent-item-tree))
20223 (t (org-modifier-cursor-error))))
20225 (defun org-shiftmetaright ()
20226 "Demote subtree or insert table column.
20227 Calls `org-demote-subtree', `org-indent-item-tree', or
20228 `org-table-insert-column', depending on context. See the
20229 individual commands for more information."
20230 (interactive)
20231 (cond
20232 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20233 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20234 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20235 ((if (not (org-region-active-p)) (org-at-item-p)
20236 (save-excursion (goto-char (region-beginning))
20237 (org-at-item-p)))
20238 (call-interactively 'org-indent-item-tree))
20239 (t (org-modifier-cursor-error))))
20241 (defun org-shiftmetaup (&optional _arg)
20242 "Drag the line at point up.
20243 In a table, kill the current row.
20244 On a clock timestamp, update the value of the timestamp like `S-<up>'
20245 but also adjust the previous clocked item in the clock history.
20246 Everywhere else, drag the line at point up."
20247 (interactive "P")
20248 (cond
20249 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20250 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20251 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20252 (call-interactively 'org-timestamp-up)))
20253 (t (call-interactively 'org-drag-line-backward))))
20255 (defun org-shiftmetadown (&optional _arg)
20256 "Drag the line at point down.
20257 In a table, insert an empty row at the current line.
20258 On a clock timestamp, update the value of the timestamp like `S-<down>'
20259 but also adjust the previous clocked item in the clock history.
20260 Everywhere else, drag the line at point down."
20261 (interactive "P")
20262 (cond
20263 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20264 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20265 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20266 (call-interactively 'org-timestamp-down)))
20267 (t (call-interactively 'org-drag-line-forward))))
20269 (defsubst org-hidden-tree-error ()
20270 (user-error
20271 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20273 (defun org-metaleft (&optional _arg)
20274 "Promote heading, list item at point or move table column left.
20276 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20277 depending on context. With no specific context, calls the Emacs
20278 default `backward-word'. See the individual commands for more
20279 information.
20281 This function runs the hook `org-metaleft-hook' as a first step,
20282 and returns at first non-nil value."
20283 (interactive "P")
20284 (cond
20285 ((run-hook-with-args-until-success 'org-metaleft-hook))
20286 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20287 ((org-with-limited-levels
20288 (or (org-at-heading-p)
20289 (and (org-region-active-p)
20290 (save-excursion
20291 (goto-char (region-beginning))
20292 (org-at-heading-p)))))
20293 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20294 (call-interactively 'org-do-promote))
20295 ;; At an inline task.
20296 ((org-at-heading-p)
20297 (call-interactively 'org-inlinetask-promote))
20298 ((or (org-at-item-p)
20299 (and (org-region-active-p)
20300 (save-excursion
20301 (goto-char (region-beginning))
20302 (org-at-item-p))))
20303 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20304 (call-interactively 'org-outdent-item))
20305 (t (call-interactively 'backward-word))))
20307 (defun org-metaright (&optional _arg)
20308 "Demote heading, list item at point or move table column right.
20310 In front of a drawer or a block keyword, indent it correctly.
20312 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20313 `org-indent-drawer' or `org-indent-block' depending on context.
20314 With no specific context, calls the Emacs default `forward-word'.
20315 See the individual commands for more information.
20317 This function runs the hook `org-metaright-hook' as a first step,
20318 and returns at first non-nil value."
20319 (interactive "P")
20320 (cond
20321 ((run-hook-with-args-until-success 'org-metaright-hook))
20322 ((org-at-table-p) (call-interactively 'org-table-move-column))
20323 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20324 ((org-at-block-p) (call-interactively 'org-indent-block))
20325 ((org-with-limited-levels
20326 (or (org-at-heading-p)
20327 (and (org-region-active-p)
20328 (save-excursion
20329 (goto-char (region-beginning))
20330 (org-at-heading-p)))))
20331 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20332 (call-interactively 'org-do-demote))
20333 ;; At an inline task.
20334 ((org-at-heading-p)
20335 (call-interactively 'org-inlinetask-demote))
20336 ((or (org-at-item-p)
20337 (and (org-region-active-p)
20338 (save-excursion
20339 (goto-char (region-beginning))
20340 (org-at-item-p))))
20341 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20342 (call-interactively 'org-indent-item))
20343 (t (call-interactively 'forward-word))))
20345 (defun org-check-for-hidden (what)
20346 "Check if there are hidden headlines/items in the current visual line.
20347 WHAT can be either `headlines' or `items'. If the current line is
20348 an outline or item heading and it has a folded subtree below it,
20349 this function returns t, nil otherwise."
20350 (let ((re (cond
20351 ((eq what 'headlines) org-outline-regexp-bol)
20352 ((eq what 'items) (org-item-beginning-re))
20353 (t (error "This should not happen"))))
20354 beg end)
20355 (save-excursion
20356 (catch 'exit
20357 (unless (org-region-active-p)
20358 (setq beg (point-at-bol))
20359 (beginning-of-line 2)
20360 (while (and (not (eobp)) ;; this is like `next-line'
20361 (get-char-property (1- (point)) 'invisible))
20362 (beginning-of-line 2))
20363 (setq end (point))
20364 (goto-char beg)
20365 (goto-char (point-at-eol))
20366 (setq end (max end (point)))
20367 (while (re-search-forward re end t)
20368 (when (get-char-property (match-beginning 0) 'invisible)
20369 (throw 'exit t))))
20370 nil))))
20372 (defun org-metaup (&optional _arg)
20373 "Move subtree up or move table row up.
20374 Calls `org-move-subtree-up' or `org-table-move-row' or
20375 `org-move-item-up', depending on context. See the individual commands
20376 for more information."
20377 (interactive "P")
20378 (cond
20379 ((run-hook-with-args-until-success 'org-metaup-hook))
20380 ((org-region-active-p)
20381 (let* ((a (min (region-beginning) (region-end)))
20382 (b (1- (max (region-beginning) (region-end))))
20383 (c (save-excursion (goto-char a)
20384 (move-beginning-of-line 0)))
20385 (d (save-excursion (goto-char a)
20386 (move-end-of-line 0) (point))))
20387 (transpose-regions a b c d)
20388 (goto-char c)))
20389 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20390 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20391 ((org-at-item-p) (call-interactively 'org-move-item-up))
20392 (t (org-drag-element-backward))))
20394 (defun org-metadown (&optional _arg)
20395 "Move subtree down or move table row down.
20396 Calls `org-move-subtree-down' or `org-table-move-row' or
20397 `org-move-item-down', depending on context. See the individual
20398 commands for more information."
20399 (interactive "P")
20400 (cond
20401 ((run-hook-with-args-until-success 'org-metadown-hook))
20402 ((org-region-active-p)
20403 (let* ((a (min (region-beginning) (region-end)))
20404 (b (max (region-beginning) (region-end)))
20405 (c (save-excursion (goto-char b)
20406 (move-beginning-of-line 1)))
20407 (d (save-excursion (goto-char b)
20408 (move-end-of-line 1) (1+ (point)))))
20409 (transpose-regions a b c d)
20410 (goto-char d)))
20411 ((org-at-table-p) (call-interactively 'org-table-move-row))
20412 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20413 ((org-at-item-p) (call-interactively 'org-move-item-down))
20414 (t (org-drag-element-forward))))
20416 (defun org-shiftup (&optional arg)
20417 "Increase item in timestamp or increase priority of current headline.
20418 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20419 depending on context. See the individual commands for more information."
20420 (interactive "P")
20421 (cond
20422 ((run-hook-with-args-until-success 'org-shiftup-hook))
20423 ((and org-support-shift-select (org-region-active-p))
20424 (org-call-for-shift-select 'previous-line))
20425 ((org-at-timestamp-p 'lax)
20426 (call-interactively (if org-edit-timestamp-down-means-later
20427 'org-timestamp-down 'org-timestamp-up)))
20428 ((and (not (eq org-support-shift-select 'always))
20429 org-enable-priority-commands
20430 (org-at-heading-p))
20431 (call-interactively 'org-priority-up))
20432 ((and (not org-support-shift-select) (org-at-item-p))
20433 (call-interactively 'org-previous-item))
20434 ((org-clocktable-try-shift 'up arg))
20435 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20436 (org-support-shift-select
20437 (org-call-for-shift-select 'previous-line))
20438 (t (org-shiftselect-error))))
20440 (defun org-shiftdown (&optional arg)
20441 "Decrease item in timestamp or decrease priority of current headline.
20442 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20443 depending on context. See the individual commands for more information."
20444 (interactive "P")
20445 (cond
20446 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20447 ((and org-support-shift-select (org-region-active-p))
20448 (org-call-for-shift-select 'next-line))
20449 ((org-at-timestamp-p 'lax)
20450 (call-interactively (if org-edit-timestamp-down-means-later
20451 'org-timestamp-up 'org-timestamp-down)))
20452 ((and (not (eq org-support-shift-select 'always))
20453 org-enable-priority-commands
20454 (org-at-heading-p))
20455 (call-interactively 'org-priority-down))
20456 ((and (not org-support-shift-select) (org-at-item-p))
20457 (call-interactively 'org-next-item))
20458 ((org-clocktable-try-shift 'down arg))
20459 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20460 (org-support-shift-select
20461 (org-call-for-shift-select 'next-line))
20462 (t (org-shiftselect-error))))
20464 (defun org-shiftright (&optional arg)
20465 "Cycle the thing at point or in the current line, depending on context.
20466 Depending on context, this does one of the following:
20468 - switch a timestamp at point one day into the future
20469 - on a headline, switch to the next TODO keyword.
20470 - on an item, switch entire list to the next bullet type
20471 - on a property line, switch to the next allowed value
20472 - on a clocktable definition line, move time block into the future"
20473 (interactive "P")
20474 (cond
20475 ((run-hook-with-args-until-success 'org-shiftright-hook))
20476 ((and org-support-shift-select (org-region-active-p))
20477 (org-call-for-shift-select 'forward-char))
20478 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20479 ((and (not (eq org-support-shift-select 'always))
20480 (org-at-heading-p))
20481 (let ((org-inhibit-logging
20482 (not org-treat-S-cursor-todo-selection-as-state-change))
20483 (org-inhibit-blocking
20484 (not org-treat-S-cursor-todo-selection-as-state-change)))
20485 (org-call-with-arg 'org-todo 'right)))
20486 ((or (and org-support-shift-select
20487 (not (eq org-support-shift-select 'always))
20488 (org-at-item-bullet-p))
20489 (and (not org-support-shift-select) (org-at-item-p)))
20490 (org-call-with-arg 'org-cycle-list-bullet nil))
20491 ((and (not (eq org-support-shift-select 'always))
20492 (org-at-property-p))
20493 (call-interactively 'org-property-next-allowed-value))
20494 ((org-clocktable-try-shift 'right arg))
20495 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20496 (org-support-shift-select
20497 (org-call-for-shift-select 'forward-char))
20498 (t (org-shiftselect-error))))
20500 (defun org-shiftleft (&optional arg)
20501 "Cycle the thing at point or in the current line, depending on context.
20502 Depending on context, this does one of the following:
20504 - switch a timestamp at point one day into the past
20505 - on a headline, switch to the previous TODO keyword.
20506 - on an item, switch entire list to the previous bullet type
20507 - on a property line, switch to the previous allowed value
20508 - on a clocktable definition line, move time block into the past"
20509 (interactive "P")
20510 (cond
20511 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20512 ((and org-support-shift-select (org-region-active-p))
20513 (org-call-for-shift-select 'backward-char))
20514 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20515 ((and (not (eq org-support-shift-select 'always))
20516 (org-at-heading-p))
20517 (let ((org-inhibit-logging
20518 (not org-treat-S-cursor-todo-selection-as-state-change))
20519 (org-inhibit-blocking
20520 (not org-treat-S-cursor-todo-selection-as-state-change)))
20521 (org-call-with-arg 'org-todo 'left)))
20522 ((or (and org-support-shift-select
20523 (not (eq org-support-shift-select 'always))
20524 (org-at-item-bullet-p))
20525 (and (not org-support-shift-select) (org-at-item-p)))
20526 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20527 ((and (not (eq org-support-shift-select 'always))
20528 (org-at-property-p))
20529 (call-interactively 'org-property-previous-allowed-value))
20530 ((org-clocktable-try-shift 'left arg))
20531 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20532 (org-support-shift-select
20533 (org-call-for-shift-select 'backward-char))
20534 (t (org-shiftselect-error))))
20536 (defun org-shiftcontrolright ()
20537 "Switch to next TODO set."
20538 (interactive)
20539 (cond
20540 ((and org-support-shift-select (org-region-active-p))
20541 (org-call-for-shift-select 'forward-word))
20542 ((and (not (eq org-support-shift-select 'always))
20543 (org-at-heading-p))
20544 (org-call-with-arg 'org-todo 'nextset))
20545 (org-support-shift-select
20546 (org-call-for-shift-select 'forward-word))
20547 (t (org-shiftselect-error))))
20549 (defun org-shiftcontrolleft ()
20550 "Switch to previous TODO set."
20551 (interactive)
20552 (cond
20553 ((and org-support-shift-select (org-region-active-p))
20554 (org-call-for-shift-select 'backward-word))
20555 ((and (not (eq org-support-shift-select 'always))
20556 (org-at-heading-p))
20557 (org-call-with-arg 'org-todo 'previousset))
20558 (org-support-shift-select
20559 (org-call-for-shift-select 'backward-word))
20560 (t (org-shiftselect-error))))
20562 (defun org-shiftcontrolup (&optional n)
20563 "Change timestamps synchronously up in CLOCK log lines.
20564 Optional argument N tells to change by that many units."
20565 (interactive "P")
20566 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20567 (let (org-support-shift-select)
20568 (org-clock-timestamps-up n))
20569 (user-error "Not at a clock log")))
20571 (defun org-shiftcontroldown (&optional n)
20572 "Change timestamps synchronously down in CLOCK log lines.
20573 Optional argument N tells to change by that many units."
20574 (interactive "P")
20575 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20576 (let (org-support-shift-select)
20577 (org-clock-timestamps-down n))
20578 (user-error "Not at a clock log")))
20580 (defun org-increase-number-at-point (&optional inc)
20581 "Increment the number at point.
20582 With an optional prefix numeric argument INC, increment using
20583 this numeric value."
20584 (interactive "p")
20585 (if (not (number-at-point))
20586 (user-error "Not on a number")
20587 (unless inc (setq inc 1))
20588 (let ((pos (point))
20589 (beg (skip-chars-backward "-+^/*0-9eE."))
20590 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20591 (setq nap (buffer-substring-no-properties
20592 (+ pos beg) (+ pos beg end)))
20593 (delete-region (+ pos beg) (+ pos beg end))
20594 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20595 (when (org-at-table-p)
20596 (org-table-align)
20597 (org-table-end-of-field 1))))
20599 (defun org-decrease-number-at-point (&optional inc)
20600 "Decrement the number at point.
20601 With an optional prefix numeric argument INC, decrement using
20602 this numeric value."
20603 (interactive "p")
20604 (org-increase-number-at-point (- (or inc 1))))
20606 (defun org-ctrl-c-ret ()
20607 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20608 (interactive)
20609 (cond
20610 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20611 (t (call-interactively 'org-insert-heading))))
20613 (defun org-find-visible ()
20614 (let ((s (point)))
20615 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20616 (get-char-property s 'invisible)))
20618 (defun org-find-invisible ()
20619 (let ((s (point)))
20620 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20621 (not (get-char-property s 'invisible))))
20624 (defun org-copy-visible (beg end)
20625 "Copy the visible parts of the region."
20626 (interactive "r")
20627 (let ((result ""))
20628 (while (/= beg end)
20629 (when (get-char-property beg 'invisible)
20630 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20631 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20632 (setq result (concat result (buffer-substring beg next)))
20633 (setq beg next)))
20634 (kill-new result)))
20636 (defun org-copy-special ()
20637 "Copy region in table or copy current subtree.
20638 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20639 context. See the individual commands for more information."
20640 (interactive)
20641 (call-interactively
20642 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20644 (defun org-cut-special ()
20645 "Cut region in table or cut current subtree.
20646 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20647 context. See the individual commands for more information."
20648 (interactive)
20649 (call-interactively
20650 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20652 (defun org-paste-special (arg)
20653 "Paste rectangular region into table, or past subtree relative to level.
20654 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20655 See the individual commands for more information."
20656 (interactive "P")
20657 (if (org-at-table-p)
20658 (org-table-paste-rectangle)
20659 (org-paste-subtree arg)))
20661 (defun org-edit-special (&optional arg)
20662 "Call a special editor for the element at point.
20663 When at a table, call the formula editor with `org-table-edit-formulas'.
20664 When in a source code block, call `org-edit-src-code'.
20665 When in a fixed-width region, call `org-edit-fixed-width-region'.
20666 When in an export block, call `org-edit-export-block'.
20667 When in a LaTeX environment, call `org-edit-latex-environment'.
20668 When at an #+INCLUDE keyword, visit the included file.
20669 When at a footnote reference, call `org-edit-footnote-reference'
20670 On a link, call `ffap' to visit the link at point.
20671 Otherwise, return a user error."
20672 (interactive "P")
20673 (let ((element (org-element-at-point)))
20674 (barf-if-buffer-read-only)
20675 (pcase (org-element-type element)
20676 (`src-block
20677 (if (not arg) (org-edit-src-code)
20678 (let* ((info (org-babel-get-src-block-info))
20679 (lang (nth 0 info))
20680 (params (nth 2 info))
20681 (session (cdr (assq :session params))))
20682 (if (not session) (org-edit-src-code)
20683 ;; At a src-block with a session and function called with
20684 ;; an ARG: switch to the buffer related to the inferior
20685 ;; process.
20686 (switch-to-buffer
20687 (funcall (intern (concat "org-babel-prep-session:" lang))
20688 session params))))))
20689 (`keyword
20690 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20691 (org-open-link-from-string
20692 (format "[[%s]]"
20693 (expand-file-name
20694 (let ((value (org-element-property :value element)))
20695 (cond ((org-file-url-p value)
20696 (user-error "The file is specified as a URL, cannot be edited"))
20697 ((not (org-string-nw-p value))
20698 (user-error "No file to edit"))
20699 ((string-match "\\`\"\\(.*?\\)\"" value)
20700 (match-string 1 value))
20701 ((string-match "\\`[^ \t\"]\\S-*" value)
20702 (match-string 0 value))
20703 (t (user-error "No valid file specified")))))))
20704 (user-error "No special environment to edit here")))
20705 (`table
20706 (if (eq (org-element-property :type element) 'table.el)
20707 (org-edit-table.el)
20708 (call-interactively 'org-table-edit-formulas)))
20709 ;; Only Org tables contain `table-row' type elements.
20710 (`table-row (call-interactively 'org-table-edit-formulas))
20711 (`example-block (org-edit-src-code))
20712 (`export-block (org-edit-export-block))
20713 (`fixed-width (org-edit-fixed-width-region))
20714 (`latex-environment (org-edit-latex-environment))
20716 ;; No notable element at point. Though, we may be at a link or
20717 ;; a footnote reference, which are objects. Thus, scan deeper.
20718 (let ((context (org-element-context element)))
20719 (pcase (org-element-type context)
20720 (`footnote-reference (org-edit-footnote-reference))
20721 (`inline-src-block (org-edit-inline-src-code))
20722 (`link (call-interactively #'ffap))
20723 (_ (user-error "No special environment to edit here"))))))))
20725 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20726 (defun org-ctrl-c-ctrl-c (&optional arg)
20727 "Set tags in headline, or update according to changed information at point.
20729 This command does many different things, depending on context:
20731 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20732 this is what we do.
20734 - If the cursor is on a statistics cookie, update it.
20736 - If the cursor is in a headline, prompt for tags and insert them
20737 into the current line, aligned to `org-tags-column'. When called
20738 with prefix arg, realign all tags in the current buffer.
20740 - If the cursor is in one of the special #+KEYWORD lines, this
20741 triggers scanning the buffer for these lines and updating the
20742 information.
20744 - If the cursor is inside a table, realign the table. This command
20745 works even if the automatic table editor has been turned off.
20747 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20748 the entire table.
20750 - If the cursor is at a footnote reference or definition, jump to
20751 the corresponding definition or references, respectively.
20753 - If the cursor is a the beginning of a dynamic block, update it.
20755 - If the current buffer is a capture buffer, close note and file it.
20757 - If the cursor is on a <<<target>>>, update radio targets and
20758 corresponding links in this buffer.
20760 - If the cursor is on a numbered item in a plain list, renumber the
20761 ordered list.
20763 - If the cursor is on a checkbox, toggle it.
20765 - If the cursor is on a code block, evaluate it. The variable
20766 `org-confirm-babel-evaluate' can be used to control prompting
20767 before code block evaluation, by default every code block
20768 evaluation requires confirmation. Code block evaluation can be
20769 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20770 (interactive "P")
20771 (cond
20772 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20773 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20774 (org-remove-occur-highlights)
20775 (message "Temporary highlights/overlays removed from current buffer"))
20776 ((and (local-variable-p 'org-finish-function)
20777 (fboundp org-finish-function))
20778 (funcall org-finish-function))
20779 ((org-babel-hash-at-point))
20780 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20782 (let* ((context
20783 (org-element-lineage
20784 (org-element-context)
20785 ;; Limit to supported contexts.
20786 '(babel-call clock dynamic-block footnote-definition
20787 footnote-reference inline-babel-call inline-src-block
20788 inlinetask item keyword node-property paragraph
20789 plain-list planning property-drawer radio-target
20790 src-block statistics-cookie table table-cell table-row
20791 timestamp)
20793 (type (org-element-type context)))
20794 ;; For convenience: at the first line of a paragraph on the same
20795 ;; line as an item, apply function on that item instead.
20796 (when (eq type 'paragraph)
20797 (let ((parent (org-element-property :parent context)))
20798 (when (and (eq (org-element-type parent) 'item)
20799 (= (line-beginning-position)
20800 (org-element-property :begin parent)))
20801 (setq context parent)
20802 (setq type 'item))))
20803 ;; Act according to type of element or object at point.
20805 ;; Do nothing on a blank line, except if it is contained in
20806 ;; a src block. Hence, we first check if point is in such
20807 ;; a block and then if it is at a blank line.
20808 (pcase type
20809 ((or `inline-src-block `src-block)
20810 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20811 (org-babel-eval-wipe-error-buffer)
20812 (org-babel-execute-src-block
20813 current-prefix-arg (org-babel-get-src-block-info nil context))))
20814 ((guard (org-match-line "[ \t]*$"))
20815 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20816 (user-error
20817 (substitute-command-keys
20818 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20819 ((or `babel-call `inline-babel-call)
20820 (let ((info (org-babel-lob-get-info context)))
20821 (when info (org-babel-execute-src-block nil info))))
20822 (`clock (org-clock-update-time-maybe))
20823 (`dynamic-block
20824 (save-excursion
20825 (goto-char (org-element-property :post-affiliated context))
20826 (org-update-dblock)))
20827 (`footnote-definition
20828 (goto-char (org-element-property :post-affiliated context))
20829 (call-interactively 'org-footnote-action))
20830 (`footnote-reference (call-interactively #'org-footnote-action))
20831 ((or `headline `inlinetask)
20832 (save-excursion (goto-char (org-element-property :begin context))
20833 (call-interactively #'org-set-tags)))
20834 (`item
20835 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20836 ;; unconditionally, whereas `C-u' will toggle its presence.
20837 ;; Without a universal argument, if the item has a checkbox,
20838 ;; toggle it. Otherwise repair the list.
20839 (let* ((box (org-element-property :checkbox context))
20840 (struct (org-element-property :structure context))
20841 (old-struct (copy-tree struct))
20842 (parents (org-list-parents-alist struct))
20843 (prevs (org-list-prevs-alist struct))
20844 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20845 (org-list-set-checkbox
20846 (org-element-property :begin context) struct
20847 (cond ((equal arg '(16)) "[-]")
20848 ((and (not box) (equal arg '(4))) "[ ]")
20849 ((or (not box) (equal arg '(4))) nil)
20850 ((eq box 'on) "[ ]")
20851 (t "[X]")))
20852 ;; Mimic `org-list-write-struct' but with grabbing a return
20853 ;; value from `org-list-struct-fix-box'.
20854 (org-list-struct-fix-ind struct parents 2)
20855 (org-list-struct-fix-item-end struct)
20856 (org-list-struct-fix-bul struct prevs)
20857 (org-list-struct-fix-ind struct parents)
20858 (let ((block-item
20859 (org-list-struct-fix-box struct parents prevs orderedp)))
20860 (if (and box (equal struct old-struct))
20861 (if (equal arg '(16))
20862 (message "Checkboxes already reset")
20863 (user-error "Cannot toggle this checkbox: %s"
20864 (if (eq box 'on)
20865 "all subitems checked"
20866 "unchecked subitems")))
20867 (org-list-struct-apply-struct struct old-struct)
20868 (org-update-checkbox-count-maybe))
20869 (when block-item
20870 (message "Checkboxes were removed due to empty box at line %d"
20871 (org-current-line block-item))))))
20872 (`keyword
20873 (let ((org-inhibit-startup-visibility-stuff t)
20874 (org-startup-align-all-tables nil))
20875 (when (boundp 'org-table-coordinate-overlays)
20876 (mapc #'delete-overlay org-table-coordinate-overlays)
20877 (setq org-table-coordinate-overlays nil))
20878 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20879 (message "Local setup has been refreshed"))
20880 (`plain-list
20881 ;; At a plain list, with a double C-u argument, set
20882 ;; checkboxes of each item to "[-]", whereas a single one
20883 ;; will toggle their presence according to the state of the
20884 ;; first item in the list. Without an argument, repair the
20885 ;; list.
20886 (let* ((begin (org-element-property :contents-begin context))
20887 (beginm (move-marker (make-marker) begin))
20888 (struct (org-element-property :structure context))
20889 (old-struct (copy-tree struct))
20890 (first-box (save-excursion
20891 (goto-char begin)
20892 (looking-at org-list-full-item-re)
20893 (match-string-no-properties 3)))
20894 (new-box (cond ((equal arg '(16)) "[-]")
20895 ((equal arg '(4)) (unless first-box "[ ]"))
20896 ((equal first-box "[X]") "[ ]")
20897 (t "[X]"))))
20898 (cond
20899 (arg
20900 (dolist (pos
20901 (org-list-get-all-items
20902 begin struct (org-list-prevs-alist struct)))
20903 (org-list-set-checkbox pos struct new-box)))
20904 ((and first-box (eq (point) begin))
20905 ;; For convenience, when point is at bol on the first
20906 ;; item of the list and no argument is provided, simply
20907 ;; toggle checkbox of that item, if any.
20908 (org-list-set-checkbox begin struct new-box)))
20909 (org-list-write-struct
20910 struct (org-list-parents-alist struct) old-struct)
20911 (org-update-checkbox-count-maybe)
20912 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20913 ((or `property-drawer `node-property)
20914 (call-interactively #'org-property-action))
20915 (`radio-target
20916 (call-interactively #'org-update-radio-target-regexp))
20917 (`statistics-cookie
20918 (call-interactively #'org-update-statistics-cookies))
20919 ((or `table `table-cell `table-row)
20920 ;; At a table, recalculate every field and align it. Also
20921 ;; send the table if necessary. If the table has
20922 ;; a `table.el' type, just give up. At a table row or cell,
20923 ;; maybe recalculate line but always align table.
20924 (if (eq (org-element-property :type context) 'table.el)
20925 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20926 Use `\\[org-edit-special]' to edit table.el tables"))
20927 (if (or (eq type 'table)
20928 ;; Check if point is at a TBLFM line.
20929 (and (eq type 'table-row)
20930 (= (point) (org-element-property :end context))))
20931 (save-excursion
20932 (if (org-at-TBLFM-p)
20933 (progn (require 'org-table)
20934 (org-table-calc-current-TBLFM))
20935 (goto-char (org-element-property :contents-begin context))
20936 (org-call-with-arg 'org-table-recalculate (or arg t))
20937 (orgtbl-send-table 'maybe)))
20938 (org-table-maybe-eval-formula)
20939 (cond (arg (call-interactively #'org-table-recalculate))
20940 ((org-table-maybe-recalculate-line))
20941 (t (org-table-align))))))
20942 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20943 (org-timestamp-change 0 'day))
20944 ((and `nil (guard (org-at-heading-p)))
20945 ;; When point is on an unsupported object type, we can miss
20946 ;; the fact that it also is at a heading. Handle it here.
20947 (call-interactively #'org-set-tags))
20948 ((guard
20949 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20951 (user-error
20952 (substitute-command-keys
20953 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20955 (defun org-mode-restart ()
20956 (interactive)
20957 (let ((indent-status (bound-and-true-p org-indent-mode)))
20958 (funcall major-mode)
20959 (hack-local-variables)
20960 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20961 (org-indent-mode -1))
20962 (org-reset-file-cache))
20963 (message "%s restarted" major-mode))
20965 (defun org-kill-note-or-show-branches ()
20966 "Abort storing current note, or call `outline-show-branches'."
20967 (interactive)
20968 (if (not org-finish-function)
20969 (progn
20970 (outline-hide-subtree)
20971 (call-interactively 'outline-show-branches))
20972 (let ((org-note-abort t))
20973 (funcall org-finish-function))))
20975 (defun org-delete-indentation (&optional arg)
20976 "Join current line to previous and fix whitespace at join.
20978 If previous line is a headline add to headline title. Otherwise
20979 the function calls `delete-indentation'.
20981 With a non-nil optional argument, join it to the following one."
20982 (interactive "*P")
20983 (if (save-excursion
20984 (beginning-of-line (if arg 1 0))
20985 (let ((case-fold-search nil))
20986 (looking-at org-complex-heading-regexp)))
20987 ;; At headline.
20988 (let ((tags-column (when (match-beginning 5)
20989 (save-excursion (goto-char (match-beginning 5))
20990 (current-column))))
20991 (string (concat " " (progn (when arg (forward-line 1))
20992 (org-trim (delete-and-extract-region
20993 (line-beginning-position)
20994 (line-end-position)))))))
20995 (unless (bobp) (delete-region (point) (1- (point))))
20996 (goto-char (or (match-end 4)
20997 (match-beginning 5)
20998 (match-end 0)))
20999 (skip-chars-backward " \t")
21000 (save-excursion (insert string))
21001 ;; Adjust alignment of tags.
21002 (cond
21003 ((not tags-column)) ;no tags
21004 (org-auto-align-tags (org-set-tags nil t))
21005 (t (org--align-tags-here tags-column)))) ;preserve tags column
21006 (delete-indentation arg)))
21008 (defun org-open-line (n)
21009 "Insert a new row in tables, call `open-line' elsewhere.
21010 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21011 As a special case, when a document starts with a table, allow to
21012 call `open-line' on the very first character."
21013 (interactive "*p")
21014 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21015 (org-table-insert-row)
21016 (open-line n)))
21018 (defun org-return (&optional indent)
21019 "Goto next table row or insert a newline.
21021 Calls `org-table-next-row' or `newline', depending on context.
21023 When optional INDENT argument is non-nil, call
21024 `newline-and-indent' instead of `newline'.
21026 When `org-return-follows-link' is non-nil and point is on
21027 a timestamp or a link, call `org-open-at-point'. However, it
21028 will not happen if point is in a table or on a \"dead\"
21029 object (e.g., within a comment). In these case, you need to use
21030 `org-open-at-point' directly."
21031 (interactive)
21032 (let ((context (if org-return-follows-link (org-element-context)
21033 (org-element-at-point))))
21034 (cond
21035 ;; In a table, call `org-table-next-row'.
21036 ((or (and (eq (org-element-type context) 'table)
21037 (>= (point) (org-element-property :contents-begin context))
21038 (< (point) (org-element-property :contents-end context)))
21039 (org-element-lineage context '(table-row table-cell) t))
21040 (org-table-justify-field-maybe)
21041 (call-interactively #'org-table-next-row))
21042 ;; On a link or a timestamp, call `org-open-at-point' if
21043 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21044 ;; locations, e.g., in a comment, as `org-open-at-point'.
21045 ((and org-return-follows-link
21046 (or (org-in-regexp org-ts-regexp-both nil t)
21047 (org-in-regexp org-tsr-regexp-both nil t)
21048 (org-in-regexp org-any-link-re nil t)))
21049 (call-interactively #'org-open-at-point))
21050 ;; Insert newline in heading, but preserve tags.
21051 ((and (not (bolp))
21052 (save-excursion (beginning-of-line)
21053 (let ((case-fold-search nil))
21054 (looking-at org-complex-heading-regexp))))
21055 ;; At headline. Split line. However, if point is on keyword,
21056 ;; priority cookie or tags, do not break any of them: add
21057 ;; a newline after the headline instead.
21058 (let ((tags-column (and (match-beginning 5)
21059 (save-excursion (goto-char (match-beginning 5))
21060 (current-column))))
21061 (string
21062 (when (and (match-end 4) (org-point-in-group (point) 4))
21063 (delete-and-extract-region (point) (match-end 4)))))
21064 ;; Adjust tag alignment.
21065 (cond
21066 ((not (and tags-column string)))
21067 (org-auto-align-tags (org-set-tags nil t))
21068 (t (org--align-tags-here tags-column))) ;preserve tags column
21069 (end-of-line)
21070 (org-show-entry)
21071 (if indent (newline-and-indent) (newline))
21072 (when string (save-excursion (insert (org-trim string))))))
21073 ;; In a list, make sure indenting keeps trailing text within.
21074 ((and indent
21075 (not (eolp))
21076 (org-element-lineage context '(item)))
21077 (let ((trailing-data
21078 (delete-and-extract-region (point) (line-end-position))))
21079 (newline-and-indent)
21080 (save-excursion (insert trailing-data))))
21081 (t (if indent (newline-and-indent) (newline))))))
21083 (defun org-return-indent ()
21084 "Goto next table row or insert a newline and indent.
21085 Calls `org-table-next-row' or `newline-and-indent', depending on
21086 context. See the individual commands for more information."
21087 (interactive)
21088 (org-return t))
21090 (defun org-ctrl-c-star ()
21091 "Compute table, or change heading status of lines.
21092 Calls `org-table-recalculate' or `org-toggle-heading',
21093 depending on context."
21094 (interactive)
21095 (cond
21096 ((org-at-table-p)
21097 (call-interactively 'org-table-recalculate))
21099 ;; Convert all lines in region to list items
21100 (call-interactively 'org-toggle-heading))))
21102 (defun org-ctrl-c-minus ()
21103 "Insert separator line in table or modify bullet status of line.
21104 Also turns a plain line or a region of lines into list items.
21105 Calls `org-table-insert-hline', `org-toggle-item', or
21106 `org-cycle-list-bullet', depending on context."
21107 (interactive)
21108 (cond
21109 ((org-at-table-p)
21110 (call-interactively 'org-table-insert-hline))
21111 ((org-region-active-p)
21112 (call-interactively 'org-toggle-item))
21113 ((org-in-item-p)
21114 (call-interactively 'org-cycle-list-bullet))
21116 (call-interactively 'org-toggle-item))))
21118 (defun org-toggle-heading (&optional nstars)
21119 "Convert headings to normal text, or items or text to headings.
21120 If there is no active region, only convert the current line.
21122 With a `\\[universal-argument]' prefix, convert the whole list at
21123 point into heading.
21125 In a region:
21127 - If the first non blank line is a headline, remove the stars
21128 from all headlines in the region.
21130 - If it is a normal line, turn each and every normal line (i.e.,
21131 not an heading or an item) in the region into headings. If you
21132 want to convert only the first line of this region, use one
21133 universal prefix argument.
21135 - If it is a plain list item, turn all plain list items into headings.
21137 When converting a line into a heading, the number of stars is chosen
21138 such that the lines become children of the current entry. However,
21139 when a numeric prefix argument is given, its value determines the
21140 number of stars to add."
21141 (interactive "P")
21142 (let ((skip-blanks
21143 (function
21144 ;; Return beginning of first non-blank line, starting from
21145 ;; line at POS.
21146 (lambda (pos)
21147 (save-excursion
21148 (goto-char pos)
21149 (while (org-at-comment-p) (forward-line))
21150 (skip-chars-forward " \r\t\n")
21151 (point-at-bol)))))
21152 beg end toggled)
21153 ;; Determine boundaries of changes. If a universal prefix has
21154 ;; been given, put the list in a region. If region ends at a bol,
21155 ;; do not consider the last line to be in the region.
21157 (when (and current-prefix-arg (org-at-item-p))
21158 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21159 (org-mark-element))
21161 (if (org-region-active-p)
21162 (setq beg (funcall skip-blanks (region-beginning))
21163 end (copy-marker (save-excursion
21164 (goto-char (region-end))
21165 (if (bolp) (point) (point-at-eol)))))
21166 (setq beg (funcall skip-blanks (point-at-bol))
21167 end (copy-marker (point-at-eol))))
21168 ;; Ensure inline tasks don't count as headings.
21169 (org-with-limited-levels
21170 (save-excursion
21171 (goto-char beg)
21172 (cond
21173 ;; Case 1. Started at an heading: de-star headings.
21174 ((org-at-heading-p)
21175 (while (< (point) end)
21176 (when (org-at-heading-p t)
21177 (looking-at org-outline-regexp) (replace-match "")
21178 (setq toggled t))
21179 (forward-line)))
21180 ;; Case 2. Started at an item: change items into headlines.
21181 ;; One star will be added by `org-list-to-subtree'.
21182 ((org-at-item-p)
21183 (while (< (point) end)
21184 (when (org-at-item-p)
21185 ;; Pay attention to cases when region ends before list.
21186 (let* ((struct (org-list-struct))
21187 (list-end
21188 (min (org-list-get-bottom-point struct) (1+ end))))
21189 (save-restriction
21190 (narrow-to-region (point) list-end)
21191 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21192 (setq toggled t))
21193 (forward-line)))
21194 ;; Case 3. Started at normal text: make every line an heading,
21195 ;; skipping headlines and items.
21196 (t (let* ((stars
21197 (make-string
21198 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21199 (add-stars
21200 (cond (nstars "") ; stars from prefix only
21201 ((equal stars "") "*") ; before first heading
21202 (org-odd-levels-only "**") ; inside heading, odd
21203 (t "*"))) ; inside heading, oddeven
21204 (rpl (concat stars add-stars " "))
21205 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21206 (while (< (point) (if (equal nstars '(4)) lend end))
21207 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21208 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21209 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21210 (forward-line)))))))
21211 (unless toggled (message "Cannot toggle heading from here"))))
21213 (defun org-meta-return (&optional arg)
21214 "Insert a new heading or wrap a region in a table.
21215 Calls `org-insert-heading', `org-insert-item' or
21216 `org-table-wrap-region', depending on context. When called with
21217 an argument, unconditionally call `org-insert-heading'."
21218 (interactive "P")
21219 (org-check-before-invisible-edit 'insert)
21220 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21221 (call-interactively (cond (arg #'org-insert-heading)
21222 ((org-at-table-p) #'org-table-wrap-region)
21223 ((org-in-item-p) #'org-insert-item)
21224 (t #'org-insert-heading)))))
21226 ;;; Menu entries
21228 (defsubst org-in-subtree-not-table-p ()
21229 "Are we in a subtree and not in a table?"
21230 (and (not (org-before-first-heading-p))
21231 (not (org-at-table-p))))
21233 ;; Define the Org mode menus
21234 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21235 '("Tbl"
21236 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21237 ["Next Field" org-cycle (org-at-table-p)]
21238 ["Previous Field" org-shifttab (org-at-table-p)]
21239 ["Next Row" org-return (org-at-table-p)]
21240 "--"
21241 ["Blank Field" org-table-blank-field (org-at-table-p)]
21242 ["Edit Field" org-table-edit-field (org-at-table-p)]
21243 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21244 "--"
21245 ("Column"
21246 ["Move Column Left" org-metaleft (org-at-table-p)]
21247 ["Move Column Right" org-metaright (org-at-table-p)]
21248 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21249 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21250 ("Row"
21251 ["Move Row Up" org-metaup (org-at-table-p)]
21252 ["Move Row Down" org-metadown (org-at-table-p)]
21253 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21254 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21255 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21256 "--"
21257 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21258 ("Rectangle"
21259 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21260 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21261 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21262 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21263 "--"
21264 ("Calculate"
21265 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21266 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21267 ["Edit Formulas" org-edit-special (org-at-table-p)]
21268 "--"
21269 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21270 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21271 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21272 "--"
21273 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21274 "--"
21275 ["Sum Column/Rectangle" org-table-sum
21276 (or (org-at-table-p) (org-region-active-p))]
21277 ["Which Column?" org-table-current-column (org-at-table-p)])
21278 ["Debug Formulas"
21279 org-table-toggle-formula-debugger
21280 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21281 ["Show Col/Row Numbers"
21282 org-table-toggle-coordinate-overlays
21283 :style toggle
21284 :selected (bound-and-true-p org-table-overlay-coordinates)]
21285 "--"
21286 ["Create" org-table-create (not (org-at-table-p))]
21287 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21288 ["Import from File" org-table-import (not (org-at-table-p))]
21289 ["Export to File" org-table-export (org-at-table-p)]
21290 "--"
21291 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21292 "--"
21293 ("Plot"
21294 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21295 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21297 (easy-menu-define org-org-menu org-mode-map "Org menu"
21298 '("Org"
21299 ("Show/Hide"
21300 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21301 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21302 ["Sparse Tree..." org-sparse-tree t]
21303 ["Reveal Context" org-reveal t]
21304 ["Show All" outline-show-all t]
21305 "--"
21306 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21307 "--"
21308 ["New Heading" org-insert-heading t]
21309 ("Navigate Headings"
21310 ["Up" outline-up-heading t]
21311 ["Next" outline-next-visible-heading t]
21312 ["Previous" outline-previous-visible-heading t]
21313 ["Next Same Level" outline-forward-same-level t]
21314 ["Previous Same Level" outline-backward-same-level t]
21315 "--"
21316 ["Jump" org-goto t])
21317 ("Edit Structure"
21318 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21319 "--"
21320 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21321 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21322 "--"
21323 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21324 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21325 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21326 "--"
21327 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21328 "--"
21329 ["Copy visible text" org-copy-visible t]
21330 "--"
21331 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21332 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21333 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21334 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21335 "--"
21336 ["Sort Region/Children" org-sort t]
21337 "--"
21338 ["Convert to odd levels" org-convert-to-odd-levels t]
21339 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21340 ("Editing"
21341 ["Emphasis..." org-emphasize t]
21342 ["Edit Source Example" org-edit-special t]
21343 "--"
21344 ["Footnote new/jump" org-footnote-action t]
21345 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21346 ("Archive"
21347 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21348 "--"
21349 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21350 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21351 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21353 "--"
21354 ("Hyperlinks"
21355 ["Store Link (Global)" org-store-link t]
21356 ["Find existing link to here" org-occur-link-in-agenda-files t]
21357 ["Insert Link" org-insert-link t]
21358 ["Follow Link" org-open-at-point t]
21359 "--"
21360 ["Next link" org-next-link t]
21361 ["Previous link" org-previous-link t]
21362 "--"
21363 ["Descriptive Links"
21364 org-toggle-link-display
21365 :style radio
21366 :selected org-descriptive-links
21368 ["Literal Links"
21369 org-toggle-link-display
21370 :style radio
21371 :selected (not org-descriptive-links)])
21372 "--"
21373 ("TODO Lists"
21374 ["TODO/DONE/-" org-todo t]
21375 ("Select keyword"
21376 ["Next keyword" org-shiftright (org-at-heading-p)]
21377 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21378 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21379 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21380 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21381 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21382 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21383 "--"
21384 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21385 :selected org-enforce-todo-dependencies :style toggle :active t]
21386 "Settings for tree at point"
21387 ["Do Children sequentially" org-toggle-ordered-property :style radio
21388 :selected (org-entry-get nil "ORDERED")
21389 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21390 ["Do Children parallel" org-toggle-ordered-property :style radio
21391 :selected (not (org-entry-get nil "ORDERED"))
21392 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21393 "--"
21394 ["Set Priority" org-priority t]
21395 ["Priority Up" org-shiftup t]
21396 ["Priority Down" org-shiftdown t]
21397 "--"
21398 ["Get news from all feeds" org-feed-update-all t]
21399 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21400 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21401 ("TAGS and Properties"
21402 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21403 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21404 "--"
21405 ["Set property" org-set-property (not (org-before-first-heading-p))]
21406 ["Column view of properties" org-columns t]
21407 ["Insert Column View DBlock" org-columns-insert-dblock t])
21408 ("Dates and Scheduling"
21409 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21410 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21411 ("Change Date"
21412 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21413 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21414 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21415 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21416 ["Compute Time Range" org-evaluate-time-range t]
21417 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21418 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21419 "--"
21420 ["Custom time format" org-toggle-time-stamp-overlays
21421 :style radio :selected org-display-custom-times]
21422 "--"
21423 ["Goto Calendar" org-goto-calendar t]
21424 ["Date from Calendar" org-date-from-calendar t]
21425 "--"
21426 ["Start/Restart Timer" org-timer-start t]
21427 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21428 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21429 ["Insert Timer String" org-timer t]
21430 ["Insert Timer Item" org-timer-item t])
21431 ("Logging work"
21432 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21433 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21434 ["Clock out" org-clock-out t]
21435 ["Clock cancel" org-clock-cancel t]
21436 "--"
21437 ["Mark as default task" org-clock-mark-default-task t]
21438 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21439 ["Goto running clock" org-clock-goto t]
21440 "--"
21441 ["Display times" org-clock-display t]
21442 ["Create clock table" org-clock-report t]
21443 "--"
21444 ["Record DONE time"
21445 (progn (setq org-log-done (not org-log-done))
21446 (message "Switching to %s will %s record a timestamp"
21447 (car org-done-keywords)
21448 (if org-log-done "automatically" "not")))
21449 :style toggle :selected org-log-done])
21450 "--"
21451 ["Agenda Command..." org-agenda t]
21452 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21453 ("File List for Agenda")
21454 ("Special views current file"
21455 ["TODO Tree" org-show-todo-tree t]
21456 ["Check Deadlines" org-check-deadlines t]
21457 ["Tags/Property tree" org-match-sparse-tree t])
21458 "--"
21459 ["Export/Publish..." org-export-dispatch t]
21460 ("LaTeX"
21461 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21462 :selected org-cdlatex-mode]
21463 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21464 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21465 ["Modify math symbol" org-cdlatex-math-modify
21466 (org-inside-LaTeX-fragment-p)]
21467 ["Insert citation" org-reftex-citation t])
21468 "--"
21469 ("MobileOrg"
21470 ["Push Files and Views" org-mobile-push t]
21471 ["Get Captured and Flagged" org-mobile-pull t]
21472 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21473 "--"
21474 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21475 "--"
21476 ("Documentation"
21477 ["Show Version" org-version t]
21478 ["Info Documentation" org-info t])
21479 ("Customize"
21480 ["Browse Org Group" org-customize t]
21481 "--"
21482 ["Expand This Menu" org-create-customize-menu
21483 (fboundp 'customize-menu-create)])
21484 ["Send bug report" org-submit-bug-report t]
21485 "--"
21486 ("Refresh/Reload"
21487 ["Refresh setup current buffer" org-mode-restart t]
21488 ["Reload Org (after update)" org-reload t]
21489 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21492 (defun org-info (&optional node)
21493 "Read documentation for Org in the info system.
21494 With optional NODE, go directly to that node."
21495 (interactive)
21496 (info (format "(org)%s" (or node ""))))
21498 ;;;###autoload
21499 (defun org-submit-bug-report ()
21500 "Submit a bug report on Org via mail.
21502 Don't hesitate to report any problems or inaccurate documentation.
21504 If you don't have setup sending mail from (X)Emacs, please copy the
21505 output buffer into your mail program, as it gives us important
21506 information about your Org version and configuration."
21507 (interactive)
21508 (require 'reporter)
21509 (defvar reporter-prompt-for-summary-p)
21510 (org-load-modules-maybe)
21511 (org-require-autoloaded-modules)
21512 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21513 (reporter-submit-bug-report
21514 "emacs-orgmode@gnu.org"
21515 (org-version nil 'full)
21516 (let (list)
21517 (save-window-excursion
21518 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21519 (delete-other-windows)
21520 (erase-buffer)
21521 (insert "You are about to submit a bug report to the Org mailing list.
21523 We would like to add your full Org and Outline configuration to the
21524 bug report. This greatly simplifies the work of the maintainer and
21525 other experts on the mailing list.
21527 HOWEVER, some variables you have customized may contain private
21528 information. The names of customers, colleagues, or friends, might
21529 appear in the form of file names, tags, todo states, or search strings.
21530 If you answer yes to the prompt, you might want to check and remove
21531 such private information before sending the email.")
21532 (add-text-properties (point-min) (point-max) '(face org-warning))
21533 (when (yes-or-no-p "Include your Org configuration ")
21534 (mapatoms
21535 (lambda (v)
21536 (and (boundp v)
21537 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21538 (or (and (symbol-value v)
21539 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21540 (and
21541 (get v 'custom-type) (get v 'standard-value)
21542 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21543 (push v list)))))
21544 (kill-buffer (get-buffer "*Warn about privacy*"))
21545 list))
21546 nil nil
21547 "Remember to cover the basics, that is, what you expected to happen and
21548 what in fact did happen. You don't know how to make a good report? See
21550 http://orgmode.org/manual/Feedback.html#Feedback
21552 Your bug report will be posted to the Org mailing list.
21553 ------------------------------------------------------------------------")
21554 (save-excursion
21555 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21556 (replace-match "\\1Bug: \\3 [\\2]")))))
21559 (defun org-install-agenda-files-menu ()
21560 (let ((bl (buffer-list)))
21561 (save-excursion
21562 (while bl
21563 (set-buffer (pop bl))
21564 (when (derived-mode-p 'org-mode) (setq bl nil)))
21565 (when (derived-mode-p 'org-mode)
21566 (easy-menu-change
21567 '("Org") "File List for Agenda"
21568 (append
21569 (list
21570 ["Edit File List" (org-edit-agenda-file-list) t]
21571 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21572 ["Remove Current File from List" org-remove-file t]
21573 ["Cycle through agenda files" org-cycle-agenda-files t]
21574 ["Occur in all agenda files" org-occur-in-agenda-files t]
21575 "--")
21576 (mapcar 'org-file-menu-entry
21577 ;; Prevent initialization from failing.
21578 (ignore-errors (org-agenda-files t)))))))))
21580 ;;;; Documentation
21582 (defun org-require-autoloaded-modules ()
21583 (interactive)
21584 (mapc #'require
21585 '(org-agenda org-archive org-attach org-clock org-colview org-id
21586 org-table org-timer)))
21588 ;;;###autoload
21589 (defun org-reload (&optional uncompiled)
21590 "Reload all org lisp files.
21591 With prefix arg UNCOMPILED, load the uncompiled versions."
21592 (interactive "P")
21593 (require 'loadhist)
21594 (let* ((org-dir (org-find-library-dir "org"))
21595 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21596 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21597 (remove-re (format "\\`%s\\'"
21598 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21599 (feats (delete-dups
21600 (mapcar 'file-name-sans-extension
21601 (mapcar 'file-name-nondirectory
21602 (delq nil
21603 (mapcar 'feature-file
21604 features))))))
21605 (lfeat (append
21606 (sort
21607 (setq feats
21608 (delq nil (mapcar
21609 (lambda (f)
21610 (if (and (string-match feature-re f)
21611 (not (string-match remove-re f)))
21612 f nil))
21613 feats)))
21614 'string-lessp)
21615 (list "org-version" "org")))
21616 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21617 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21618 load-uncore load-misses)
21619 (setq load-misses
21620 (delq 't
21621 (mapcar (lambda (f)
21622 (or (org-load-noerror-mustsuffix (concat org-dir f))
21623 (and (string= org-dir contrib-dir)
21624 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21625 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21626 (add-to-list 'load-uncore f 'append)
21629 lfeat)))
21630 (when load-uncore
21631 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21632 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21633 (if load-misses
21634 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21635 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21636 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21638 ;;;###autoload
21639 (defun org-customize ()
21640 "Call the customize function with org as argument."
21641 (interactive)
21642 (org-load-modules-maybe)
21643 (org-require-autoloaded-modules)
21644 (customize-browse 'org))
21646 (defun org-create-customize-menu ()
21647 "Create a full customization menu for Org mode, insert it into the menu."
21648 (interactive)
21649 (org-load-modules-maybe)
21650 (org-require-autoloaded-modules)
21651 (if (fboundp 'customize-menu-create)
21652 (progn
21653 (easy-menu-change
21654 '("Org") "Customize"
21655 `(["Browse Org group" org-customize t]
21656 "--"
21657 ,(customize-menu-create 'org)
21658 ["Set" Custom-set t]
21659 ["Save" Custom-save t]
21660 ["Reset to Current" Custom-reset-current t]
21661 ["Reset to Saved" Custom-reset-saved t]
21662 ["Reset to Standard Settings" Custom-reset-standard t]))
21663 (message "\"Org\"-menu now contains full customization menu"))
21664 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21666 ;;;; Miscellaneous stuff
21668 ;;; Generally useful functions
21670 (defun org-get-at-eol (property n)
21671 "Get text property PROPERTY at the end of line less N characters."
21672 (get-text-property (- (point-at-eol) n) property))
21674 (defun org-find-text-property-in-string (prop s)
21675 "Return the first non-nil value of property PROP in string S."
21676 (or (get-text-property 0 prop s)
21677 (get-text-property (or (next-single-property-change 0 prop s) 0)
21678 prop s)))
21680 (defun org-display-warning (message)
21681 "Display the given MESSAGE as a warning."
21682 (display-warning 'org message :warning))
21684 (defun org-eval (form)
21685 "Eval FORM and return result."
21686 (condition-case error
21687 (eval form)
21688 (error (format "%%![Error: %s]" error))))
21690 (defun org-in-clocktable-p ()
21691 "Check if the cursor is in a clocktable."
21692 (let ((pos (point)) start)
21693 (save-excursion
21694 (end-of-line 1)
21695 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21696 (setq start (match-beginning 0))
21697 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21698 (>= (match-end 0) pos)
21699 start))))
21701 (defun org-in-verbatim-emphasis ()
21702 (save-match-data
21703 (and (org-in-regexp org-verbatim-re 2)
21704 (>= (point) (match-beginning 3))
21705 (<= (point) (match-end 4)))))
21707 (defun org-overlay-display (ovl text &optional face evap)
21708 "Make overlay OVL display TEXT with face FACE."
21709 (overlay-put ovl 'display text)
21710 (if face (overlay-put ovl 'face face))
21711 (if evap (overlay-put ovl 'evaporate t)))
21713 (defun org-overlay-before-string (ovl text &optional face evap)
21714 "Make overlay OVL display TEXT with face FACE."
21715 (if face (org-add-props text nil 'face face))
21716 (overlay-put ovl 'before-string text)
21717 (if evap (overlay-put ovl 'evaporate t)))
21719 (defun org-find-overlays (prop &optional pos delete)
21720 "Find all overlays specifying PROP at POS or point.
21721 If DELETE is non-nil, delete all those overlays."
21722 (let (found)
21723 (dolist (ov (overlays-at (or pos (point))) found)
21724 (cond ((not (overlay-get ov prop)))
21725 (delete (delete-overlay ov))
21726 (t (push ov found))))))
21728 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21729 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21730 (if (and marker (marker-buffer marker)
21731 (buffer-live-p (marker-buffer marker)))
21732 (progn
21733 (pop-to-buffer-same-window (marker-buffer marker))
21734 (when (or (> marker (point-max)) (< marker (point-min)))
21735 (widen))
21736 (goto-char marker)
21737 (org-show-context 'org-goto))
21738 (if bookmark
21739 (bookmark-jump bookmark)
21740 (error "Cannot find location"))))
21742 (defun org-quote-csv-field (s)
21743 "Quote field for inclusion in CSV material."
21744 (if (string-match "[\",]" s)
21745 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21748 (defun org-force-self-insert (N)
21749 "Needed to enforce self-insert under remapping."
21750 (interactive "p")
21751 (self-insert-command N))
21753 (defun org-shorten-string (s maxlength)
21754 "Shorten string S so that it is no longer than MAXLENGTH characters.
21755 If the string is shorter or has length MAXLENGTH, just return the
21756 original string. If it is longer, the functions finds a space in the
21757 string, breaks this string off at that locations and adds three dots
21758 as ellipsis. Including the ellipsis, the string will not be longer
21759 than MAXLENGTH. If finding a good breaking point in the string does
21760 not work, the string is just chopped off in the middle of a word
21761 if necessary."
21762 (if (<= (length s) maxlength)
21764 (let* ((n (max (- maxlength 4) 1))
21765 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21766 (if (string-match re s)
21767 (concat (match-string 1 s) "...")
21768 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21770 (defun org-get-indentation (&optional line)
21771 "Get the indentation of the current line, interpreting tabs.
21772 When LINE is given, assume it represents a line and compute its indentation."
21773 (if line
21774 (when (string-match "^ *" (org-remove-tabs line))
21775 (match-end 0))
21776 (save-excursion
21777 (beginning-of-line 1)
21778 (skip-chars-forward " \t")
21779 (current-column))))
21781 (defun org-get-string-indentation (s)
21782 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21783 (let ((n -1) (i 0) (w tab-width) c)
21784 (catch 'exit
21785 (while (< (setq n (1+ n)) (length s))
21786 (setq c (aref s n))
21787 (cond ((= c ?\ ) (setq i (1+ i)))
21788 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21789 (t (throw 'exit t)))))
21792 (defun org-remove-tabs (s &optional width)
21793 "Replace tabulators in S with spaces.
21794 Assumes that s is a single line, starting in column 0."
21795 (setq width (or width tab-width))
21796 (while (string-match "\t" s)
21797 (setq s (replace-match
21798 (make-string
21799 (- (* width (/ (+ (match-beginning 0) width) width))
21800 (match-beginning 0)) ?\ )
21801 t t s)))
21804 (defun org-fix-indentation (line ind)
21805 "Fix indentation in LINE.
21806 IND is a cons cell with target and minimum indentation.
21807 If the current indentation in LINE is smaller than the minimum,
21808 leave it alone. If it is larger than ind, set it to the target."
21809 (let* ((l (org-remove-tabs line))
21810 (i (org-get-indentation l))
21811 (i1 (car ind)) (i2 (cdr ind)))
21812 (when (>= i i2) (setq l (substring line i2)))
21813 (if (> i1 0)
21814 (concat (make-string i1 ?\ ) l)
21815 l)))
21817 (defun org-remove-indentation (code &optional n)
21818 "Remove maximum common indentation in string CODE and return it.
21819 N may optionally be the number of columns to remove. Return CODE
21820 as-is if removal failed."
21821 (with-temp-buffer
21822 (insert code)
21823 (if (org-do-remove-indentation n) (buffer-string) code)))
21825 (defun org-do-remove-indentation (&optional n)
21826 "Remove the maximum common indentation from the buffer.
21827 When optional argument N is a positive integer, remove exactly
21828 that much characters from indentation, if possible. Return nil
21829 if it fails."
21830 (catch :exit
21831 (goto-char (point-min))
21832 ;; Find maximum common indentation, if not specified.
21833 (let ((n (or n
21834 (let ((min-ind (point-max)))
21835 (save-excursion
21836 (while (re-search-forward "^[ \t]*\\S-" nil t)
21837 (let ((ind (1- (current-column))))
21838 (if (zerop ind) (throw :exit nil)
21839 (setq min-ind (min min-ind ind))))))
21840 min-ind))))
21841 (if (zerop n) (throw :exit nil)
21842 ;; Remove exactly N indentation, but give up if not possible.
21843 (while (not (eobp))
21844 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21845 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21846 ((< ind n) (throw :exit nil))
21847 (t (indent-line-to (- ind n))))
21848 (forward-line)))
21849 ;; Signal success.
21850 t))))
21852 (defun org-fill-template (template alist)
21853 "Find each %key of ALIST in TEMPLATE and replace it."
21854 (let ((case-fold-search nil))
21855 (dolist (entry (sort (copy-sequence alist)
21856 (lambda (a b) (< (length (car a)) (length (car b))))))
21857 (setq template
21858 (replace-regexp-in-string
21859 (concat "%" (regexp-quote (car entry)))
21860 (or (cdr entry) "") template t t)))
21861 template))
21863 (defun org-base-buffer (buffer)
21864 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21865 (if (not buffer)
21866 buffer
21867 (or (buffer-base-buffer buffer)
21868 buffer)))
21870 (defun org-wrap (string &optional width lines)
21871 "Wrap string to either a number of lines, or a width in characters.
21872 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21873 that costs. If there is a word longer than WIDTH, the text is actually
21874 wrapped to the length of that word.
21875 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21876 many lines, whatever width that takes.
21877 The return value is a list of lines, without newlines at the end."
21878 (let* ((words (split-string string))
21879 (maxword (apply 'max (mapcar 'org-string-width words)))
21880 w ll)
21881 (cond (width
21882 (org-do-wrap words (max maxword width)))
21883 (lines
21884 (setq w maxword)
21885 (setq ll (org-do-wrap words maxword))
21886 (if (<= (length ll) lines)
21888 (setq ll words)
21889 (while (> (length ll) lines)
21890 (setq w (1+ w))
21891 (setq ll (org-do-wrap words w)))
21892 ll))
21893 (t (error "Cannot wrap this")))))
21895 (defun org-do-wrap (words width)
21896 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21897 (let (lines line)
21898 (while words
21899 (setq line (pop words))
21900 (while (and words (< (+ (length line) (length (car words))) width))
21901 (setq line (concat line " " (pop words))))
21902 (setq lines (push line lines)))
21903 (nreverse lines)))
21905 (defun org-quote-vert (s)
21906 "Replace \"|\" with \"\\vert\"."
21907 (while (string-match "|" s)
21908 (setq s (replace-match "\\vert" t t s)))
21911 (defun org-uuidgen-p (s)
21912 "Is S an ID created by UUIDGEN?"
21913 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21915 (defun org-in-src-block-p (&optional inside)
21916 "Whether point is in a code source block.
21917 When INSIDE is non-nil, don't consider we are within a src block
21918 when point is at #+BEGIN_SRC or #+END_SRC."
21919 (let ((case-fold-search t))
21920 (or (and (eq (get-char-property (point) 'src-block) t))
21921 (and (not inside)
21922 (save-match-data
21923 (save-excursion
21924 (beginning-of-line)
21925 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21927 (defun org-context ()
21928 "Return a list of contexts of the current cursor position.
21929 If several contexts apply, all are returned.
21930 Each context entry is a list with a symbol naming the context, and
21931 two positions indicating start and end of the context. Possible
21932 contexts are:
21934 :headline anywhere in a headline
21935 :headline-stars on the leading stars in a headline
21936 :todo-keyword on a TODO keyword (including DONE) in a headline
21937 :tags on the TAGS in a headline
21938 :priority on the priority cookie in a headline
21939 :item on the first line of a plain list item
21940 :item-bullet on the bullet/number of a plain list item
21941 :checkbox on the checkbox in a plain list item
21942 :table in an Org table
21943 :table-special on a special filed in a table
21944 :table-table in a table.el table
21945 :clocktable in a clocktable
21946 :src-block in a source block
21947 :link on a hyperlink
21948 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21949 :target on a <<target>>
21950 :radio-target on a <<<radio-target>>>
21951 :latex-fragment on a LaTeX fragment
21952 :latex-preview on a LaTeX fragment with overlaid preview image
21954 This function expects the position to be visible because it uses font-lock
21955 faces as a help to recognize the following contexts: :table-special, :link,
21956 and :keyword."
21957 (let* ((f (get-text-property (point) 'face))
21958 (faces (if (listp f) f (list f)))
21959 (case-fold-search t)
21960 (p (point)) clist o)
21961 ;; First the large context
21962 (cond
21963 ((org-at-heading-p t)
21964 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21965 (when (progn
21966 (beginning-of-line 1)
21967 (looking-at org-todo-line-tags-regexp))
21968 (push (org-point-in-group p 1 :headline-stars) clist)
21969 (push (org-point-in-group p 2 :todo-keyword) clist)
21970 (push (org-point-in-group p 4 :tags) clist))
21971 (goto-char p)
21972 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21973 (when (looking-at "\\[#[A-Z0-9]\\]")
21974 (push (org-point-in-group p 0 :priority) clist)))
21976 ((org-at-item-p)
21977 (push (org-point-in-group p 2 :item-bullet) clist)
21978 (push (list :item (point-at-bol)
21979 (save-excursion (org-end-of-item) (point)))
21980 clist)
21981 (and (org-at-item-checkbox-p)
21982 (push (org-point-in-group p 0 :checkbox) clist)))
21984 ((org-at-table-p)
21985 (push (list :table (org-table-begin) (org-table-end)) clist)
21986 (when (memq 'org-formula faces)
21987 (push (list :table-special
21988 (previous-single-property-change p 'face)
21989 (next-single-property-change p 'face)) clist)))
21990 ((org-at-table-p 'any)
21991 (push (list :table-table) clist)))
21992 (goto-char p)
21994 (let ((case-fold-search t))
21995 ;; New the "medium" contexts: clocktables, source blocks
21996 (cond ((org-in-clocktable-p)
21997 (push (list :clocktable
21998 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21999 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22000 (match-beginning 1))
22001 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22002 (match-end 0))) clist))
22003 ((org-in-src-block-p)
22004 (push (list :src-block
22005 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22006 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22007 (match-beginning 1))
22008 (and (search-forward "#+END_SRC" nil t)
22009 (match-beginning 0))) clist))))
22010 (goto-char p)
22012 ;; Now the small context
22013 (cond
22014 ((org-at-timestamp-p)
22015 (push (org-point-in-group p 0 :timestamp) clist))
22016 ((memq 'org-link faces)
22017 (push (list :link
22018 (previous-single-property-change p 'face)
22019 (next-single-property-change p 'face)) clist))
22020 ((memq 'org-special-keyword faces)
22021 (push (list :keyword
22022 (previous-single-property-change p 'face)
22023 (next-single-property-change p 'face)) clist))
22024 ((org-at-target-p)
22025 (push (org-point-in-group p 0 :target) clist)
22026 (goto-char (1- (match-beginning 0)))
22027 (when (looking-at org-radio-target-regexp)
22028 (push (org-point-in-group p 0 :radio-target) clist))
22029 (goto-char p))
22030 ((setq o (cl-some
22031 (lambda (o)
22032 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22034 (overlays-at (point))))
22035 (push (list :latex-fragment
22036 (overlay-start o) (overlay-end o)) clist)
22037 (push (list :latex-preview
22038 (overlay-start o) (overlay-end o)) clist))
22039 ((org-inside-LaTeX-fragment-p)
22040 ;; FIXME: positions wrong.
22041 (push (list :latex-fragment (point) (point)) clist)))
22043 (setq clist (nreverse (delq nil clist)))
22044 clist))
22046 (defun org-in-regexp (regexp &optional nlines visually)
22047 "Check if point is inside a match of REGEXP.
22049 Normally only the current line is checked, but you can include
22050 NLINES extra lines around point into the search. If VISUALLY is
22051 set, require that the cursor is not after the match but really
22052 on, so that the block visually is on the match.
22054 Return nil or a cons cell (BEG . END) where BEG and END are,
22055 respectively, the positions at the beginning and the end of the
22056 match."
22057 (catch :exit
22058 (let ((pos (point))
22059 (eol (line-end-position (if nlines (1+ nlines) 1))))
22060 (save-excursion
22061 (beginning-of-line (- 1 (or nlines 0)))
22062 (while (and (re-search-forward regexp eol t)
22063 (<= (match-beginning 0) pos))
22064 (let ((end (match-end 0)))
22065 (when (or (> end pos) (and (= end pos) (not visually)))
22066 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22068 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22069 "Non-nil when point is between matches of START-RE and END-RE.
22071 Also return a non-nil value when point is on one of the matches.
22073 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22074 buffer positions. Default values are the positions of headlines
22075 surrounding the point.
22077 The functions returns a cons cell whose car (resp. cdr) is the
22078 position before START-RE (resp. after END-RE)."
22079 (save-match-data
22080 (let ((pos (point))
22081 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22082 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22083 beg end)
22084 (save-excursion
22085 ;; Point is on a block when on START-RE or if START-RE can be
22086 ;; found before it...
22087 (and (or (org-in-regexp start-re)
22088 (re-search-backward start-re limit-up t))
22089 (setq beg (match-beginning 0))
22090 ;; ... and END-RE after it...
22091 (goto-char (match-end 0))
22092 (re-search-forward end-re limit-down t)
22093 (> (setq end (match-end 0)) pos)
22094 ;; ... without another START-RE in-between.
22095 (goto-char (match-beginning 0))
22096 (not (re-search-backward start-re (1+ beg) t))
22097 ;; Return value.
22098 (cons beg end))))))
22100 (defun org-in-block-p (names)
22101 "Non-nil when point belongs to a block whose name belongs to NAMES.
22103 NAMES is a list of strings containing names of blocks.
22105 Return first block name matched, or nil. Beware that in case of
22106 nested blocks, the returned name may not belong to the closest
22107 block from point."
22108 (save-match-data
22109 (catch 'exit
22110 (let ((case-fold-search t)
22111 (lim-up (save-excursion (outline-previous-heading)))
22112 (lim-down (save-excursion (outline-next-heading))))
22113 (dolist (name names)
22114 (let ((n (regexp-quote name)))
22115 (when (org-between-regexps-p
22116 (concat "^[ \t]*#\\+begin_" n)
22117 (concat "^[ \t]*#\\+end_" n)
22118 lim-up lim-down)
22119 (throw 'exit n)))))
22120 nil)))
22122 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22123 "Call `multi-occur' with buffers for all agenda files."
22124 (interactive "sOrg-files matching: ")
22125 (let* ((files (org-agenda-files))
22126 (tnames (mapcar #'file-truename files))
22127 (extra org-agenda-text-search-extra-files))
22128 (when (eq (car extra) 'agenda-archives)
22129 (setq extra (cdr extra))
22130 (setq files (org-add-archive-files files)))
22131 (dolist (f extra)
22132 (unless (member (file-truename f) tnames)
22133 (unless (member f files) (setq files (append files (list f))))
22134 (setq tnames (append tnames (list (file-truename f))))))
22135 (multi-occur
22136 (mapcar (lambda (x)
22137 (with-current-buffer
22138 ;; FIXME: Why not just (find-file-noselect x)?
22139 ;; Is it to avoid the "revert buffer" prompt?
22140 (or (get-file-buffer x) (find-file-noselect x))
22141 (widen)
22142 (current-buffer)))
22143 files)
22144 regexp)))
22146 (add-hook 'occur-mode-find-occurrence-hook
22147 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22149 (defun org-occur-link-in-agenda-files ()
22150 "Create a link and search for it in the agendas.
22151 The link is not stored in `org-stored-links', it is just created
22152 for the search purpose."
22153 (interactive)
22154 (let ((link (condition-case nil
22155 (org-store-link nil)
22156 (error "Unable to create a link to here"))))
22157 (org-occur-in-agenda-files (regexp-quote link))))
22159 (defun org-reverse-string (string)
22160 "Return the reverse of STRING."
22161 (apply 'string (reverse (string-to-list string))))
22163 ;; defsubst org-uniquify must be defined before first use
22165 (defun org-uniquify-alist (alist)
22166 "Merge elements of ALIST with the same key.
22168 For example, in this alist:
22170 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22171 => \\='((a 1 3) (b 2))
22173 merge (a 1) and (a 3) into (a 1 3).
22175 The function returns the new ALIST."
22176 (let (rtn)
22177 (dolist (e alist rtn)
22178 (let (n)
22179 (if (not (assoc (car e) rtn))
22180 (push e rtn)
22181 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22182 (setq rtn (assq-delete-all (car e) rtn))
22183 (push n rtn))))))
22185 (defun org-delete-all (elts list)
22186 "Remove all elements in ELTS from LIST.
22187 Comparison is done with `equal'. It is a destructive operation
22188 that may remove elements by altering the list structure."
22189 (while elts
22190 (setq list (delete (pop elts) list)))
22191 list)
22193 (defun org-back-over-empty-lines ()
22194 "Move backwards over whitespace, to the beginning of the first empty line.
22195 Returns the number of empty lines passed."
22196 (let ((pos (point)))
22197 (if (cdr (assq 'heading org-blank-before-new-entry))
22198 (skip-chars-backward " \t\n\r")
22199 (unless (eobp)
22200 (forward-line -1)))
22201 (beginning-of-line 2)
22202 (goto-char (min (point) pos))
22203 (count-lines (point) pos)))
22205 (defun org-skip-whitespace ()
22206 (skip-chars-forward " \t\n\r"))
22208 (defun org-point-in-group (point group &optional context)
22209 "Check if POINT is in match-group GROUP.
22210 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22211 match. If the match group does not exist or point is not inside it,
22212 return nil."
22213 (and (match-beginning group)
22214 (>= point (match-beginning group))
22215 (<= point (match-end group))
22216 (if context
22217 (list context (match-beginning group) (match-end group))
22218 t)))
22220 (defun org-switch-to-buffer-other-window (&rest args)
22221 "Switch to buffer in a second window on the current frame.
22222 In particular, do not allow pop-up frames.
22223 Returns the newly created buffer."
22224 (org-no-popups
22225 (apply 'switch-to-buffer-other-window args)))
22227 (defun org-combine-plists (&rest plists)
22228 "Create a single property list from all plists in PLISTS.
22229 The process starts by copying the first list, and then setting properties
22230 from the other lists. Settings in the last list are the most significant
22231 ones and overrule settings in the other lists."
22232 (let ((rtn (copy-sequence (pop plists)))
22233 p v ls)
22234 (while plists
22235 (setq ls (pop plists))
22236 (while ls
22237 (setq p (pop ls) v (pop ls))
22238 (setq rtn (plist-put rtn p v))))
22239 rtn))
22241 (defun org-replace-escapes (string table)
22242 "Replace %-escapes in STRING with values in TABLE.
22243 TABLE is an association list with keys like \"%a\" and string values.
22244 The sequences in STRING may contain normal field width and padding information,
22245 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22246 so values can contain further %-escapes if they are define later in TABLE."
22247 (let ((tbl (copy-alist table))
22248 (case-fold-search nil)
22249 (pchg 0)
22250 re rpl)
22251 (dolist (e tbl)
22252 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22253 (when (and (cdr e) (string-match re (cdr e)))
22254 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22255 (safe "SREF"))
22256 (add-text-properties 0 3 (list 'sref sref) safe)
22257 (setcdr e (replace-match safe t t (cdr e)))))
22258 (while (string-match re string)
22259 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22260 (cdr e)))
22261 (setq string (replace-match rpl t t string))))
22262 (while (setq pchg (next-property-change pchg string))
22263 (let ((sref (get-text-property pchg 'sref string)))
22264 (when (and sref (string-match "SREF" string pchg))
22265 (setq string (replace-match sref t t string)))))
22266 string))
22268 (defun org-find-base-buffer-visiting (file)
22269 "Like `find-buffer-visiting' but always return the base buffer and
22270 not an indirect buffer."
22271 (let ((buf (or (get-file-buffer file)
22272 (find-buffer-visiting file))))
22273 (if buf
22274 (or (buffer-base-buffer buf) buf)
22275 nil)))
22277 ;;; TODO: Only called once, from ox-odt which should probably use
22278 ;;; org-export-inline-image-p or something.
22279 (defun org-file-image-p (file)
22280 "Return non-nil if FILE is an image."
22281 (save-match-data
22282 (string-match (image-file-name-regexp) file)))
22284 (defun org-get-cursor-date (&optional with-time)
22285 "Return the date at cursor in as a time.
22286 This works in the calendar and in the agenda, anywhere else it just
22287 returns the current time.
22288 If WITH-TIME is non-nil, returns the time of the event at point (in
22289 the agenda) or the current time of the day."
22290 (let (date day defd tp hod mod)
22291 (when with-time
22292 (setq tp (get-text-property (point) 'time))
22293 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22294 (setq hod (string-to-number (match-string 1 tp))
22295 mod (string-to-number (match-string 2 tp))))
22296 (or tp (let ((now (decode-time)))
22297 (setq hod (nth 2 now)
22298 mod (nth 1 now)))))
22299 (cond
22300 ((eq major-mode 'calendar-mode)
22301 (setq date (calendar-cursor-to-date)
22302 defd (encode-time 0 (or mod 0) (or hod 0)
22303 (nth 1 date) (nth 0 date) (nth 2 date))))
22304 ((eq major-mode 'org-agenda-mode)
22305 (setq day (get-text-property (point) 'day))
22306 (when day
22307 (setq date (calendar-gregorian-from-absolute day)
22308 defd (encode-time 0 (or mod 0) (or hod 0)
22309 (nth 1 date) (nth 0 date) (nth 2 date))))))
22310 (or defd (current-time))))
22312 (defun org-mark-subtree (&optional up)
22313 "Mark the current subtree.
22314 This puts point at the start of the current subtree, and mark at
22315 the end. If a numeric prefix UP is given, move up into the
22316 hierarchy of headlines by UP levels before marking the subtree."
22317 (interactive "P")
22318 (org-with-limited-levels
22319 (cond ((org-at-heading-p) (beginning-of-line))
22320 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22321 (t (outline-previous-visible-heading 1))))
22322 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22323 (if (called-interactively-p 'any)
22324 (call-interactively 'org-mark-element)
22325 (org-mark-element)))
22327 (defun org-file-newer-than-p (file time)
22328 "Non-nil if FILE is newer than TIME.
22329 FILE is a filename, as a string, TIME is a list of integers, as
22330 returned by, e.g., `current-time'."
22331 (and (file-exists-p file)
22332 ;; Only compare times up to whole seconds as some file-systems
22333 ;; (e.g. HFS+) do not retain any finer granularity. As
22334 ;; a consequence, make sure we return non-nil when the two
22335 ;; times are equal.
22336 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22337 (cl-subseq time 0 2)))))
22339 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22340 "Compile a SOURCE file using PROCESS.
22342 PROCESS is either a function or a list of shell commands, as
22343 strings. EXT is a file extension, without the leading dot, as
22344 a string. It is used to check if the process actually succeeded.
22346 PROCESS must create a file with the same base name and directory
22347 as SOURCE, but ending with EXT. The function then returns its
22348 filename. Otherwise, it raises an error. The error message can
22349 then be refined by providing string ERR-MSG, which is appended to
22350 the standard message.
22352 If PROCESS is a function, it is called with a single argument:
22353 the SOURCE file.
22355 If it is a list of commands, each of them is called using
22356 `shell-command'. By default, in each command, %b, %f, %F, %o and
22357 %O are replaced with, respectively, SOURCE base name, name, full
22358 name, directory and absolute output file name. It is possible,
22359 however, to use more place-holders by specifying them in optional
22360 argument SPEC, as an alist following the pattern
22362 (CHARACTER . REPLACEMENT-STRING).
22364 When PROCESS is a list of commands, optional argument LOG-BUF can
22365 be set to a buffer or a buffer name. `shell-command' then uses
22366 it for output."
22367 (let* ((base-name (file-name-base source))
22368 (full-name (file-truename source))
22369 (out-dir (or (file-name-directory source) "./"))
22370 (output (expand-file-name (concat base-name "." ext) out-dir))
22371 (time (current-time))
22372 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22373 (save-window-excursion
22374 (pcase process
22375 ((pred functionp) (funcall process (shell-quote-argument source)))
22376 ((pred consp)
22377 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22378 (spec (append spec
22379 `((?b . ,(shell-quote-argument base-name))
22380 (?f . ,(shell-quote-argument source))
22381 (?F . ,(shell-quote-argument full-name))
22382 (?o . ,(shell-quote-argument out-dir))
22383 (?O . ,(shell-quote-argument output))))))
22384 (dolist (command process)
22385 (shell-command (format-spec command spec) log-buf))
22386 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22387 (_ (error "No valid command to process %S%s" source err-msg))))
22388 ;; Check for process failure. Output file is expected to be
22389 ;; located in the same directory as SOURCE.
22390 (unless (org-file-newer-than-p output time)
22391 (error (format "File %S wasn't produced%s" output err-msg)))
22392 output))
22394 ;;; Indentation
22396 (defvar org-element-greater-elements)
22397 (defun org--get-expected-indentation (element contentsp)
22398 "Expected indentation column for current line, according to ELEMENT.
22399 ELEMENT is an element containing point. CONTENTSP is non-nil
22400 when indentation is to be computed according to contents of
22401 ELEMENT."
22402 (let ((type (org-element-type element))
22403 (start (org-element-property :begin element))
22404 (post-affiliated (org-element-property :post-affiliated element)))
22405 (org-with-wide-buffer
22406 (cond
22407 (contentsp
22408 (cl-case type
22409 ((diary-sexp footnote-definition) 0)
22410 ((headline inlinetask nil)
22411 (if (not org-adapt-indentation) 0
22412 (let ((level (org-current-level)))
22413 (if level (1+ level) 0))))
22414 ((item plain-list) (org-list-item-body-column post-affiliated))
22416 (goto-char start)
22417 (org-get-indentation))))
22418 ((memq type '(headline inlinetask nil))
22419 (if (org-match-line "[ \t]*$")
22420 (org--get-expected-indentation element t)
22422 ((memq type '(diary-sexp footnote-definition)) 0)
22423 ;; First paragraph of a footnote definition or an item.
22424 ;; Indent like parent.
22425 ((< (line-beginning-position) start)
22426 (org--get-expected-indentation
22427 (org-element-property :parent element) t))
22428 ;; At first line: indent according to previous sibling, if any,
22429 ;; ignoring footnote definitions and inline tasks, or parent's
22430 ;; contents.
22431 ((= (line-beginning-position) start)
22432 (catch 'exit
22433 (while t
22434 (if (= (point-min) start) (throw 'exit 0)
22435 (goto-char (1- start))
22436 (let* ((previous (org-element-at-point))
22437 (parent previous))
22438 (while (and parent (<= (org-element-property :end parent) start))
22439 (setq previous parent
22440 parent (org-element-property :parent parent)))
22441 (cond
22442 ((not previous) (throw 'exit 0))
22443 ((> (org-element-property :end previous) start)
22444 (throw 'exit (org--get-expected-indentation previous t)))
22445 ((memq (org-element-type previous)
22446 '(footnote-definition inlinetask))
22447 (setq start (org-element-property :begin previous)))
22448 (t (goto-char (org-element-property :begin previous))
22449 (throw 'exit
22450 (if (bolp) (org-get-indentation)
22451 ;; At first paragraph in an item or
22452 ;; a footnote definition.
22453 (org--get-expected-indentation
22454 (org-element-property :parent previous) t))))))))))
22455 ;; Otherwise, move to the first non-blank line above.
22457 (beginning-of-line)
22458 (let ((pos (point)))
22459 (skip-chars-backward " \r\t\n")
22460 (cond
22461 ;; Two blank lines end a footnote definition or a plain
22462 ;; list. When we indent an empty line after them, the
22463 ;; containing list or footnote definition is over, so it
22464 ;; qualifies as a previous sibling. Therefore, we indent
22465 ;; like its first line.
22466 ((and (memq type '(footnote-definition plain-list))
22467 (> (count-lines (point) pos) 2))
22468 (goto-char start)
22469 (org-get-indentation))
22470 ;; Line above is the first one of a paragraph at the
22471 ;; beginning of an item or a footnote definition. Indent
22472 ;; like parent.
22473 ((< (line-beginning-position) start)
22474 (org--get-expected-indentation
22475 (org-element-property :parent element) t))
22476 ;; Line above is the beginning of an element, i.e., point
22477 ;; was originally on the blank lines between element's start
22478 ;; and contents.
22479 ((= (line-beginning-position) post-affiliated)
22480 (org--get-expected-indentation element t))
22481 ;; POS is after contents in a greater element. Indent like
22482 ;; the beginning of the element.
22483 ((and (memq type org-element-greater-elements)
22484 (let ((cend (org-element-property :contents-end element)))
22485 (and cend (<= cend pos))))
22486 ;; As a special case, if point is at the end of a footnote
22487 ;; definition or an item, indent like the very last element
22488 ;; within. If that last element is an item, indent like
22489 ;; its contents.
22490 (if (memq type '(footnote-definition item plain-list))
22491 (let ((last (org-element-at-point)))
22492 (goto-char pos)
22493 (org--get-expected-indentation
22494 last (eq (org-element-type last) 'item)))
22495 (goto-char start)
22496 (org-get-indentation)))
22497 ;; In any other case, indent like the current line.
22498 (t (org-get-indentation)))))))))
22500 (defun org--align-node-property ()
22501 "Align node property at point.
22502 Alignment is done according to `org-property-format', which see."
22503 (when (save-excursion
22504 (beginning-of-line)
22505 (looking-at org-property-re))
22506 (replace-match
22507 (concat (match-string 4)
22508 (org-trim
22509 (format org-property-format (match-string 1) (match-string 3))))
22510 t t)))
22512 (defun org-indent-line ()
22513 "Indent line depending on context.
22515 Indentation is done according to the following rules:
22517 - Footnote definitions, diary sexps, headlines and inline tasks
22518 have to start at column 0.
22520 - On the very first line of an element, consider, in order, the
22521 next rules until one matches:
22523 1. If there's a sibling element before, ignoring footnote
22524 definitions and inline tasks, indent like its first line.
22526 2. If element has a parent, indent like its contents. More
22527 precisely, if parent is an item, indent after the
22528 description part, if any, or the bullet (see
22529 `org-list-description-max-indent'). Else, indent like
22530 parent's first line.
22532 3. Otherwise, indent relatively to current level, if
22533 `org-adapt-indentation' is non-nil, or to left margin.
22535 - On a blank line at the end of an element, indent according to
22536 the type of the element. More precisely
22538 1. If element is a plain list, an item, or a footnote
22539 definition, indent like the very last element within.
22541 2. If element is a paragraph, indent like its last non blank
22542 line.
22544 3. Otherwise, indent like its very first line.
22546 - In the code part of a source block, use language major mode
22547 to indent current line if `org-src-tab-acts-natively' is
22548 non-nil. If it is nil, do nothing.
22550 - Otherwise, indent like the first non-blank line above.
22552 The function doesn't indent an item as it could break the whole
22553 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22554 `\\[org-shiftmetaright]'.
22556 Also align node properties according to `org-property-format'."
22557 (interactive)
22558 (cond
22559 (orgstruct-is-++
22560 (let ((indent-line-function
22561 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22562 (indent-according-to-mode)))
22563 ((org-at-heading-p) 'noindent)
22565 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22566 (type (org-element-type element)))
22567 (cond ((and (memq type '(plain-list item))
22568 (= (line-beginning-position)
22569 (org-element-property :post-affiliated element)))
22570 'noindent)
22571 ((and (eq type 'latex-environment)
22572 (>= (point) (org-element-property :post-affiliated element))
22573 (< (point) (org-with-wide-buffer
22574 (goto-char (org-element-property :end element))
22575 (skip-chars-backward " \r\t\n")
22576 (line-beginning-position 2))))
22577 'noindent)
22578 ((and (eq type 'src-block)
22579 org-src-tab-acts-natively
22580 (> (line-beginning-position)
22581 (org-element-property :post-affiliated element))
22582 (< (line-beginning-position)
22583 (org-with-wide-buffer
22584 (goto-char (org-element-property :end element))
22585 (skip-chars-backward " \r\t\n")
22586 (line-beginning-position))))
22587 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22589 (let ((column (org--get-expected-indentation element nil)))
22590 ;; Preserve current column.
22591 (if (<= (current-column) (current-indentation))
22592 (indent-line-to column)
22593 (save-excursion (indent-line-to column))))
22594 ;; Align node property. Also preserve current column.
22595 (when (eq type 'node-property)
22596 (let ((column (current-column)))
22597 (org--align-node-property)
22598 (org-move-to-column column)))))))))
22600 (defun org-indent-region (start end)
22601 "Indent each non-blank line in the region.
22602 Called from a program, START and END specify the region to
22603 indent. The function will not indent contents of example blocks,
22604 verse blocks and export blocks as leading white spaces are
22605 assumed to be significant there."
22606 (interactive "r")
22607 (save-excursion
22608 (goto-char start)
22609 (skip-chars-forward " \r\t\n")
22610 (unless (eobp) (beginning-of-line))
22611 (let ((indent-to
22612 (lambda (ind pos)
22613 ;; Set IND as indentation for all lines between point and
22614 ;; POS. Blank lines are ignored. Leave point after POS
22615 ;; once done.
22616 (let ((limit (copy-marker pos)))
22617 (while (< (point) limit)
22618 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22619 (forward-line))
22620 (set-marker limit nil))))
22621 (end (copy-marker end)))
22622 (while (< (point) end)
22623 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22624 (let* ((element (org-element-at-point))
22625 (type (org-element-type element))
22626 (element-end (copy-marker (org-element-property :end element)))
22627 (ind (org--get-expected-indentation element nil)))
22628 (cond
22629 ;; Element indented as a single block. Example blocks
22630 ;; preserving indentation are a special case since the
22631 ;; "contents" must not be indented whereas the block
22632 ;; boundaries can.
22633 ((or (memq type '(export-block latex-environment))
22634 (and (eq type 'example-block)
22635 (not
22636 (or org-src-preserve-indentation
22637 (org-element-property :preserve-indent element)))))
22638 (let ((offset (- ind (org-get-indentation))))
22639 (unless (zerop offset)
22640 (indent-rigidly (org-element-property :begin element)
22641 (org-element-property :end element)
22642 offset)))
22643 (goto-char element-end))
22644 ;; Elements indented line wise. Be sure to exclude
22645 ;; example blocks (preserving indentation) and source
22646 ;; blocks from this category as they are treated
22647 ;; specially later.
22648 ((or (memq type '(paragraph table table-row))
22649 (not (or (org-element-property :contents-begin element)
22650 (memq type '(example-block src-block)))))
22651 (when (eq type 'node-property)
22652 (org--align-node-property)
22653 (beginning-of-line))
22654 (funcall indent-to ind (min element-end end)))
22655 ;; Elements consisting of three parts: before the
22656 ;; contents, the contents, and after the contents. The
22657 ;; contents are treated specially, according to the
22658 ;; element type, or not indented at all. Other parts are
22659 ;; indented as a single block.
22661 (let* ((post (copy-marker
22662 (org-element-property :post-affiliated element)))
22663 (cbeg
22664 (copy-marker
22665 (cond
22666 ((not (org-element-property :contents-begin element))
22667 ;; Fake contents for source blocks.
22668 (org-with-wide-buffer
22669 (goto-char post)
22670 (line-beginning-position 2)))
22671 ((memq type '(footnote-definition item plain-list))
22672 ;; Contents in these elements could start on
22673 ;; the same line as the beginning of the
22674 ;; element. Make sure we start indenting
22675 ;; from the second line.
22676 (org-with-wide-buffer
22677 (goto-char post)
22678 (end-of-line)
22679 (skip-chars-forward " \r\t\n")
22680 (if (eobp) (point) (line-beginning-position))))
22681 (t (org-element-property :contents-begin element)))))
22682 (cend (copy-marker
22683 (or (org-element-property :contents-end element)
22684 ;; Fake contents for source blocks.
22685 (org-with-wide-buffer
22686 (goto-char element-end)
22687 (skip-chars-backward " \r\t\n")
22688 (line-beginning-position)))
22689 t)))
22690 ;; Do not change items indentation individually as it
22691 ;; might break the list as a whole. On the other
22692 ;; hand, when at a plain list, indent it as a whole.
22693 (cond ((eq type 'plain-list)
22694 (let ((offset (- ind (org-get-indentation))))
22695 (unless (zerop offset)
22696 (indent-rigidly (org-element-property :begin element)
22697 (org-element-property :end element)
22698 offset))
22699 (goto-char cbeg)))
22700 ((eq type 'item) (goto-char cbeg))
22701 (t (funcall indent-to ind (min cbeg end))))
22702 (when (< (point) end)
22703 (cl-case type
22704 ((example-block verse-block))
22705 (src-block
22706 ;; In a source block, indent source code
22707 ;; according to language major mode, but only if
22708 ;; `org-src-tab-acts-natively' is non-nil.
22709 (when (and (< (point) end) org-src-tab-acts-natively)
22710 (ignore-errors
22711 (org-babel-do-in-edit-buffer
22712 (indent-region (point-min) (point-max))))))
22713 (t (org-indent-region (point) (min cend end))))
22714 (goto-char (min cend end))
22715 (when (< (point) end)
22716 (funcall indent-to ind (min element-end end))))
22717 (set-marker post nil)
22718 (set-marker cbeg nil)
22719 (set-marker cend nil))))
22720 (set-marker element-end nil))))
22721 (set-marker end nil))))
22723 (defun org-indent-drawer ()
22724 "Indent the drawer at point."
22725 (interactive)
22726 (unless (save-excursion
22727 (beginning-of-line)
22728 (looking-at-p org-drawer-regexp))
22729 (user-error "Not at a drawer"))
22730 (let ((element (org-element-at-point)))
22731 (unless (memq (org-element-type element) '(drawer property-drawer))
22732 (user-error "Not at a drawer"))
22733 (org-with-wide-buffer
22734 (org-indent-region (org-element-property :begin element)
22735 (org-element-property :end element))))
22736 (message "Drawer at point indented"))
22738 (defun org-indent-block ()
22739 "Indent the block at point."
22740 (interactive)
22741 (unless (save-excursion
22742 (beginning-of-line)
22743 (let ((case-fold-search t))
22744 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22745 (user-error "Not at a block"))
22746 (let ((element (org-element-at-point)))
22747 (unless (memq (org-element-type element)
22748 '(comment-block center-block dynamic-block example-block
22749 export-block quote-block special-block
22750 src-block verse-block))
22751 (user-error "Not at a block"))
22752 (org-with-wide-buffer
22753 (org-indent-region (org-element-property :begin element)
22754 (org-element-property :end element))))
22755 (message "Block at point indented"))
22758 ;;; Filling
22760 ;; We use our own fill-paragraph and auto-fill functions.
22762 ;; `org-fill-paragraph' relies on adaptive filling and context
22763 ;; checking. Appropriate `fill-prefix' is computed with
22764 ;; `org-adaptive-fill-function'.
22766 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22767 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22768 ;; `org-adaptive-fill-function' value. Internally,
22769 ;; `org-comment-line-break-function' breaks the line.
22771 ;; `org-setup-filling' installs filling and auto-filling related
22772 ;; variables during `org-mode' initialization.
22774 (defvar org-element-paragraph-separate) ; org-element.el
22775 (defun org-setup-filling ()
22776 (require 'org-element)
22777 ;; Prevent auto-fill from inserting unwanted new items.
22778 (when (boundp 'fill-nobreak-predicate)
22779 (setq-local
22780 fill-nobreak-predicate
22781 (org-uniquify
22782 (append fill-nobreak-predicate
22783 '(org-fill-line-break-nobreak-p
22784 org-fill-n-macro-as-item-nobreak-p
22785 org-fill-paragraph-with-timestamp-nobreak-p)))))
22786 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22787 (setq-local paragraph-start paragraph-ending)
22788 (setq-local paragraph-separate paragraph-ending))
22789 (setq-local fill-paragraph-function 'org-fill-paragraph)
22790 (setq-local auto-fill-inhibit-regexp nil)
22791 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22792 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22793 (setq-local comment-line-break-function 'org-comment-line-break-function))
22795 (defun org-fill-line-break-nobreak-p ()
22796 "Non-nil when a new line at point would create an Org line break."
22797 (save-excursion
22798 (skip-chars-backward "[ \t]")
22799 (skip-chars-backward "\\\\")
22800 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22802 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22803 "Non-nil when a new line at point would split a timestamp."
22804 (and (org-at-timestamp-p 'lax)
22805 (not (looking-at org-ts-regexp-both))))
22807 (defun org-fill-n-macro-as-item-nobreak-p ()
22808 "Non-nil when a new line at point would create a new list."
22809 ;; During export, a "n" macro followed by a dot or a closing
22810 ;; parenthesis can end up being parsed as a new list item.
22811 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22813 (declare-function message-in-body-p "message" ())
22814 (defvar orgtbl-line-start-regexp) ; From org-table.el
22815 (defun org-adaptive-fill-function ()
22816 "Compute a fill prefix for the current line.
22817 Return fill prefix, as a string, or nil if current line isn't
22818 meant to be filled. For convenience, if `adaptive-fill-regexp'
22819 matches in paragraphs or comments, use it."
22820 (catch 'exit
22821 (when (derived-mode-p 'message-mode)
22822 (save-excursion
22823 (beginning-of-line)
22824 (cond ((not (message-in-body-p)) (throw 'exit nil))
22825 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22826 ((looking-at message-cite-prefix-regexp)
22827 (throw 'exit (match-string-no-properties 0)))
22828 ((looking-at org-outline-regexp)
22829 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22830 (org-with-wide-buffer
22831 (unless (org-at-heading-p)
22832 (let* ((p (line-beginning-position))
22833 (element (save-excursion
22834 (beginning-of-line)
22835 (org-element-at-point)))
22836 (type (org-element-type element))
22837 (post-affiliated (org-element-property :post-affiliated element)))
22838 (unless (< p post-affiliated)
22839 (cl-case type
22840 (comment
22841 (save-excursion
22842 (beginning-of-line)
22843 (looking-at "[ \t]*")
22844 (concat (match-string 0) "# ")))
22845 (footnote-definition "")
22846 ((item plain-list)
22847 (make-string (org-list-item-body-column post-affiliated) ?\s))
22848 (paragraph
22849 ;; Fill prefix is usually the same as the current line,
22850 ;; unless the paragraph is at the beginning of an item.
22851 (let ((parent (org-element-property :parent element)))
22852 (save-excursion
22853 (beginning-of-line)
22854 (cond ((eq (org-element-type parent) 'item)
22855 (make-string (org-list-item-body-column
22856 (org-element-property :begin parent))
22857 ?\s))
22858 ((and adaptive-fill-regexp
22859 ;; Locally disable
22860 ;; `adaptive-fill-function' to let
22861 ;; `fill-context-prefix' handle
22862 ;; `adaptive-fill-regexp' variable.
22863 (let (adaptive-fill-function)
22864 (fill-context-prefix
22865 post-affiliated
22866 (org-element-property :end element)))))
22867 ((looking-at "[ \t]+") (match-string 0))
22868 (t "")))))
22869 (comment-block
22870 ;; Only fill contents if P is within block boundaries.
22871 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22872 (forward-line)
22873 (point)))
22874 (cend (save-excursion
22875 (goto-char (org-element-property :end element))
22876 (skip-chars-backward " \r\t\n")
22877 (line-beginning-position))))
22878 (when (and (>= p cbeg) (< p cend))
22879 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22880 (match-string 0)
22881 "")))))))))))
22883 (declare-function message-goto-body "message" ())
22884 (defvar message-cite-prefix-regexp) ; From message.el
22886 (defun org-fill-element (&optional justify)
22887 "Fill element at point, when applicable.
22889 This function only applies to comment blocks, comments, example
22890 blocks and paragraphs. Also, as a special case, re-align table
22891 when point is at one.
22893 If JUSTIFY is non-nil (interactively, with prefix argument),
22894 justify as well. If `sentence-end-double-space' is non-nil, then
22895 period followed by one space does not end a sentence, so don't
22896 break a line there. The variable `fill-column' controls the
22897 width for filling.
22899 For convenience, when point is at a plain list, an item or
22900 a footnote definition, try to fill the first paragraph within."
22901 (with-syntax-table org-mode-transpose-word-syntax-table
22902 ;; Move to end of line in order to get the first paragraph within
22903 ;; a plain list or a footnote definition.
22904 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22905 ;; First check if point is in a blank line at the beginning of
22906 ;; the buffer. In that case, ignore filling.
22907 (cl-case (org-element-type element)
22908 ;; Use major mode filling function is src blocks.
22909 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22910 ;; Align Org tables, leave table.el tables as-is.
22911 (table-row (org-table-align) t)
22912 (table
22913 (when (eq (org-element-property :type element) 'org)
22914 (save-excursion
22915 (goto-char (org-element-property :post-affiliated element))
22916 (org-table-align)))
22918 (paragraph
22919 ;; Paragraphs may contain `line-break' type objects.
22920 (let ((beg (max (point-min)
22921 (org-element-property :contents-begin element)))
22922 (end (min (point-max)
22923 (org-element-property :contents-end element))))
22924 ;; Do nothing if point is at an affiliated keyword.
22925 (if (< (line-end-position) beg) t
22926 (when (derived-mode-p 'message-mode)
22927 ;; In `message-mode', do not fill following citation
22928 ;; in current paragraph nor text before message body.
22929 (let ((body-start (save-excursion (message-goto-body))))
22930 (when body-start (setq beg (max body-start beg))))
22931 (when (save-excursion
22932 (re-search-forward
22933 (concat "^" message-cite-prefix-regexp) end t))
22934 (setq end (match-beginning 0))))
22935 ;; Fill paragraph, taking line breaks into account.
22936 (save-excursion
22937 (goto-char beg)
22938 (let ((cuts (list beg)))
22939 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22940 (when (eq 'line-break
22941 (org-element-type
22942 (save-excursion (backward-char)
22943 (org-element-context))))
22944 (push (point) cuts)))
22945 (dolist (c (delq end cuts))
22946 (fill-region-as-paragraph c end justify)
22947 (setq end c))))
22948 t)))
22949 ;; Contents of `comment-block' type elements should be
22950 ;; filled as plain text, but only if point is within block
22951 ;; markers.
22952 (comment-block
22953 (let* ((case-fold-search t)
22954 (beg (save-excursion
22955 (goto-char (org-element-property :begin element))
22956 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22957 (forward-line)
22958 (point)))
22959 (end (save-excursion
22960 (goto-char (org-element-property :end element))
22961 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22962 (line-beginning-position))))
22963 (if (or (< (point) beg) (> (point) end)) t
22964 (fill-region-as-paragraph
22965 (save-excursion (end-of-line)
22966 (re-search-backward "^[ \t]*$" beg 'move)
22967 (line-beginning-position))
22968 (save-excursion (beginning-of-line)
22969 (re-search-forward "^[ \t]*$" end 'move)
22970 (line-beginning-position))
22971 justify))))
22972 ;; Fill comments.
22973 (comment
22974 (let ((begin (org-element-property :post-affiliated element))
22975 (end (org-element-property :end element)))
22976 (when (and (>= (point) begin) (<= (point) end))
22977 (let ((begin (save-excursion
22978 (end-of-line)
22979 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22980 (progn (forward-line) (point))
22981 begin)))
22982 (end (save-excursion
22983 (end-of-line)
22984 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22985 (1- (line-beginning-position))
22986 (skip-chars-backward " \r\t\n")
22987 (line-end-position)))))
22988 ;; Do not fill comments when at a blank line.
22989 (when (> end begin)
22990 (let ((fill-prefix
22991 (save-excursion
22992 (beginning-of-line)
22993 (looking-at "[ \t]*#")
22994 (let ((comment-prefix (match-string 0)))
22995 (goto-char (match-end 0))
22996 (if (looking-at adaptive-fill-regexp)
22997 (concat comment-prefix (match-string 0))
22998 (concat comment-prefix " "))))))
22999 (save-excursion
23000 (fill-region-as-paragraph begin end justify))))))
23002 ;; Ignore every other element.
23003 (otherwise t)))))
23005 (defun org-fill-paragraph (&optional justify region)
23006 "Fill element at point, when applicable.
23008 This function only applies to comment blocks, comments, example
23009 blocks and paragraphs. Also, as a special case, re-align table
23010 when point is at one.
23012 For convenience, when point is at a plain list, an item or
23013 a footnote definition, try to fill the first paragraph within.
23015 If JUSTIFY is non-nil (interactively, with prefix argument),
23016 justify as well. If `sentence-end-double-space' is non-nil, then
23017 period followed by one space does not end a sentence, so don't
23018 break a line there. The variable `fill-column' controls the
23019 width for filling.
23021 The REGION argument is non-nil if called interactively; in that
23022 case, if Transient Mark mode is enabled and the mark is active,
23023 fill each of the elements in the active region, instead of just
23024 filling the current element."
23025 (interactive (progn
23026 (barf-if-buffer-read-only)
23027 (list (if current-prefix-arg 'full) t)))
23028 (cond
23029 ((and (derived-mode-p 'message-mode)
23030 (or (not (message-in-body-p))
23031 (save-excursion (move-beginning-of-line 1)
23032 (looking-at message-cite-prefix-regexp))))
23033 ;; First ensure filling is correct in message-mode.
23034 (let ((fill-paragraph-function
23035 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23036 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23037 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23038 (paragraph-separate
23039 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23040 (fill-paragraph nil)))
23041 ((and region transient-mark-mode mark-active
23042 (not (eq (region-beginning) (region-end))))
23043 (let ((origin (point-marker))
23044 (start (region-beginning)))
23045 (unwind-protect
23046 (progn
23047 (goto-char (region-end))
23048 (while (> (point) start)
23049 (org-backward-paragraph)
23050 (org-fill-element justify)))
23051 (goto-char origin)
23052 (set-marker origin nil))))
23053 (t (org-fill-element justify))))
23054 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23056 (defun org-auto-fill-function ()
23057 "Auto-fill function."
23058 ;; Check if auto-filling is meaningful.
23059 (let ((fc (current-fill-column)))
23060 (when (and fc (> (current-column) fc))
23061 (let* ((fill-prefix (org-adaptive-fill-function))
23062 ;; Enforce empty fill prefix, if required. Otherwise, it
23063 ;; will be computed again.
23064 (adaptive-fill-mode (not (equal fill-prefix ""))))
23065 (when fill-prefix (do-auto-fill))))))
23067 (defun org-comment-line-break-function (&optional soft)
23068 "Break line at point and indent, continuing comment if within one.
23069 The inserted newline is marked hard if variable
23070 `use-hard-newlines' is true, unless optional argument SOFT is
23071 non-nil."
23072 (if soft (insert-and-inherit ?\n) (newline 1))
23073 (save-excursion (forward-char -1) (delete-horizontal-space))
23074 (delete-horizontal-space)
23075 (indent-to-left-margin)
23076 (insert-before-markers-and-inherit fill-prefix))
23079 ;;; Fixed Width Areas
23081 (defun org-toggle-fixed-width ()
23082 "Toggle fixed-width markup.
23084 Add or remove fixed-width markup on current line, whenever it
23085 makes sense. Return an error otherwise.
23087 If a region is active and if it contains only fixed-width areas
23088 or blank lines, remove all fixed-width markup in it. If the
23089 region contains anything else, convert all non-fixed-width lines
23090 to fixed-width ones.
23092 Blank lines at the end of the region are ignored unless the
23093 region only contains such lines."
23094 (interactive)
23095 (if (not (org-region-active-p))
23096 ;; No region:
23098 ;; Remove fixed width marker only in a fixed-with element.
23100 ;; Add fixed width maker in paragraphs, in blank lines after
23101 ;; elements or at the beginning of a headline or an inlinetask,
23102 ;; and before any one-line elements (e.g., a clock).
23103 (progn
23104 (beginning-of-line)
23105 (let* ((element (org-element-at-point))
23106 (type (org-element-type element)))
23107 (cond
23108 ((and (eq type 'fixed-width)
23109 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23110 (replace-match
23111 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23112 ((and (memq type '(babel-call clock comment diary-sexp headline
23113 horizontal-rule keyword paragraph
23114 planning))
23115 (<= (org-element-property :post-affiliated element) (point)))
23116 (skip-chars-forward " \t")
23117 (insert ": "))
23118 ((and (looking-at-p "[ \t]*$")
23119 (or (eq type 'inlinetask)
23120 (save-excursion
23121 (skip-chars-forward " \r\t\n")
23122 (<= (org-element-property :end element) (point)))))
23123 (delete-region (point) (line-end-position))
23124 (org-indent-line)
23125 (insert ": "))
23126 (t (user-error "Cannot insert a fixed-width line here")))))
23127 ;; Region active.
23128 (let* ((begin (save-excursion
23129 (goto-char (region-beginning))
23130 (line-beginning-position)))
23131 (end (copy-marker
23132 (save-excursion
23133 (goto-char (region-end))
23134 (unless (eolp) (beginning-of-line))
23135 (if (save-excursion (re-search-backward "\\S-" begin t))
23136 (progn (skip-chars-backward " \r\t\n") (point))
23137 (point)))))
23138 (all-fixed-width-p
23139 (catch 'not-all-p
23140 (save-excursion
23141 (goto-char begin)
23142 (skip-chars-forward " \r\t\n")
23143 (when (eobp) (throw 'not-all-p nil))
23144 (while (< (point) end)
23145 (let ((element (org-element-at-point)))
23146 (if (eq (org-element-type element) 'fixed-width)
23147 (goto-char (org-element-property :end element))
23148 (throw 'not-all-p nil))))
23149 t))))
23150 (if all-fixed-width-p
23151 (save-excursion
23152 (goto-char begin)
23153 (while (< (point) end)
23154 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23155 (replace-match
23156 "" nil nil nil
23157 (if (= (line-end-position) (match-end 0)) 0 1)))
23158 (forward-line)))
23159 (let ((min-ind (point-max)))
23160 ;; Find minimum indentation across all lines.
23161 (save-excursion
23162 (goto-char begin)
23163 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23164 (setq min-ind 0)
23165 (catch 'zerop
23166 (while (< (point) end)
23167 (unless (looking-at-p "[ \t]*$")
23168 (let ((ind (org-get-indentation)))
23169 (setq min-ind (min min-ind ind))
23170 (when (zerop ind) (throw 'zerop t))))
23171 (forward-line)))))
23172 ;; Loop over all lines and add fixed-width markup everywhere
23173 ;; but in fixed-width lines.
23174 (save-excursion
23175 (goto-char begin)
23176 (while (< (point) end)
23177 (cond
23178 ((org-at-heading-p)
23179 (insert ": ")
23180 (forward-line)
23181 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23182 (insert ":")
23183 (forward-line)))
23184 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23185 (let* ((element (org-element-at-point))
23186 (element-end (org-element-property :end element)))
23187 (if (eq (org-element-type element) 'fixed-width)
23188 (progn (goto-char element-end)
23189 (skip-chars-backward " \r\t\n")
23190 (forward-line))
23191 (let ((limit (min end element-end)))
23192 (while (< (point) limit)
23193 (org-move-to-column min-ind t)
23194 (insert ": ")
23195 (forward-line))))))
23197 (org-move-to-column min-ind t)
23198 (insert ": ")
23199 (forward-line)))))))
23200 (set-marker end nil))))
23203 ;;; Comments
23205 ;; Org comments syntax is quite complex. It requires the entire line
23206 ;; to be just a comment. Also, even with the right syntax at the
23207 ;; beginning of line, some elements (e.g., verse-block or
23208 ;; example-block) don't accept comments. Usual Emacs comment commands
23209 ;; cannot cope with those requirements. Therefore, Org replaces them.
23211 ;; Org still relies on `comment-dwim', but cannot trust
23212 ;; `comment-only-p'. So, `comment-region-function' and
23213 ;; `uncomment-region-function' both point
23214 ;; to`org-comment-or-uncomment-region'. Eventually,
23215 ;; `org-insert-comment' takes care of insertion of comments at the
23216 ;; beginning of line.
23218 ;; `org-setup-comments-handling' install comments related variables
23219 ;; during `org-mode' initialization.
23221 (defun org-setup-comments-handling ()
23222 (interactive)
23223 (setq-local comment-use-syntax nil)
23224 (setq-local comment-start "# ")
23225 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23226 (setq-local comment-insert-comment-function 'org-insert-comment)
23227 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23228 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23230 (defun org-insert-comment ()
23231 "Insert an empty comment above current line.
23232 If the line is empty, insert comment at its beginning. When
23233 point is within a source block, comment according to the related
23234 major mode."
23235 (if (let ((element (org-element-at-point)))
23236 (and (eq (org-element-type element) 'src-block)
23237 (< (save-excursion
23238 (goto-char (org-element-property :post-affiliated element))
23239 (line-end-position))
23240 (point))
23241 (> (save-excursion
23242 (goto-char (org-element-property :end element))
23243 (skip-chars-backward " \r\t\n")
23244 (line-beginning-position))
23245 (point))))
23246 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23247 (beginning-of-line)
23248 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23249 (open-line 1))
23250 (org-indent-line)
23251 (insert "# ")))
23253 (defvar comment-empty-lines) ; From newcomment.el.
23254 (defun org-comment-or-uncomment-region (beg end &rest _)
23255 "Comment or uncomment each non-blank line in the region.
23256 Uncomment each non-blank line between BEG and END if it only
23257 contains commented lines. Otherwise, comment them. If region is
23258 strictly within a source block, use appropriate comment syntax."
23259 (if (let ((element (org-element-at-point)))
23260 (and (eq (org-element-type element) 'src-block)
23261 (< (save-excursion
23262 (goto-char (org-element-property :post-affiliated element))
23263 (line-end-position))
23264 beg)
23265 (>= (save-excursion
23266 (goto-char (org-element-property :end element))
23267 (skip-chars-backward " \r\t\n")
23268 (line-beginning-position))
23269 end)))
23270 ;; Translate region boundaries for the Org buffer to the source
23271 ;; buffer.
23272 (let ((offset (- end beg)))
23273 (save-excursion
23274 (goto-char beg)
23275 (org-babel-do-in-edit-buffer
23276 (comment-or-uncomment-region (point) (+ offset (point))))))
23277 (save-restriction
23278 ;; Restrict region
23279 (narrow-to-region (save-excursion (goto-char beg)
23280 (skip-chars-forward " \r\t\n" end)
23281 (line-beginning-position))
23282 (save-excursion (goto-char end)
23283 (skip-chars-backward " \r\t\n" beg)
23284 (line-end-position)))
23285 (let ((uncommentp
23286 ;; UNCOMMENTP is non-nil when every non blank line between
23287 ;; BEG and END is a comment.
23288 (save-excursion
23289 (goto-char (point-min))
23290 (while (and (not (eobp))
23291 (let ((element (org-element-at-point)))
23292 (and (eq (org-element-type element) 'comment)
23293 (goto-char (min (point-max)
23294 (org-element-property
23295 :end element)))))))
23296 (eobp))))
23297 (if uncommentp
23298 ;; Only blank lines and comments in region: uncomment it.
23299 (save-excursion
23300 (goto-char (point-min))
23301 (while (not (eobp))
23302 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23303 (replace-match "" nil nil nil 1))
23304 (forward-line)))
23305 ;; Comment each line in region.
23306 (let ((min-indent (point-max)))
23307 ;; First find the minimum indentation across all lines.
23308 (save-excursion
23309 (goto-char (point-min))
23310 (while (and (not (eobp)) (not (zerop min-indent)))
23311 (unless (looking-at "[ \t]*$")
23312 (setq min-indent (min min-indent (current-indentation))))
23313 (forward-line)))
23314 ;; Then loop over all lines.
23315 (save-excursion
23316 (goto-char (point-min))
23317 (while (not (eobp))
23318 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23319 ;; Don't get fooled by invisible text (e.g. link path)
23320 ;; when moving to column MIN-INDENT.
23321 (let ((buffer-invisibility-spec nil))
23322 (org-move-to-column min-indent t))
23323 (insert comment-start))
23324 (forward-line)))))))))
23326 (defun org-comment-dwim (_arg)
23327 "Call `comment-dwim' within a source edit buffer if needed."
23328 (interactive "*P")
23329 (if (org-in-src-block-p)
23330 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23331 (call-interactively 'comment-dwim)))
23334 ;;; Timestamps API
23336 ;; This section contains tools to operate on timestamp objects, as
23337 ;; returned by, e.g. `org-element-context'.
23339 (defun org-timestamp--to-internal-time (timestamp &optional end)
23340 "Encode TIMESTAMP object into Emacs internal time.
23341 Use end of date range or time range when END is non-nil."
23342 (apply #'encode-time
23343 (cons 0
23344 (mapcar
23345 (lambda (prop) (or (org-element-property prop timestamp) 0))
23346 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23347 '(:minute-start :hour-start :day-start :month-start
23348 :year-start))))))
23350 (defun org-timestamp-has-time-p (timestamp)
23351 "Non-nil when TIMESTAMP has a time specified."
23352 (org-element-property :hour-start timestamp))
23354 (defun org-timestamp-format (timestamp format &optional end utc)
23355 "Format a TIMESTAMP object into a string.
23357 FORMAT is a format specifier to be passed to
23358 `format-time-string'.
23360 When optional argument END is non-nil, use end of date-range or
23361 time-range, if possible.
23363 When optional argument UTC is non-nil, time will be expressed as
23364 Universal Time."
23365 (format-time-string
23366 format (org-timestamp--to-internal-time timestamp end)
23367 (and utc t)))
23369 (defun org-timestamp-split-range (timestamp &optional end)
23370 "Extract a TIMESTAMP object from a date or time range.
23372 END, when non-nil, means extract the end of the range.
23373 Otherwise, extract its start.
23375 Return a new timestamp object."
23376 (let ((type (org-element-property :type timestamp)))
23377 (if (memq type '(active inactive diary)) timestamp
23378 (let ((split-ts (org-element-copy timestamp)))
23379 ;; Set new type.
23380 (org-element-put-property
23381 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23382 ;; Copy start properties over end properties if END is
23383 ;; non-nil. Otherwise, copy end properties over `start' ones.
23384 (let ((p-alist '((:minute-start . :minute-end)
23385 (:hour-start . :hour-end)
23386 (:day-start . :day-end)
23387 (:month-start . :month-end)
23388 (:year-start . :year-end))))
23389 (dolist (p-cell p-alist)
23390 (org-element-put-property
23391 split-ts
23392 (funcall (if end #'car #'cdr) p-cell)
23393 (org-element-property
23394 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23395 ;; Eventually refresh `:raw-value'.
23396 (org-element-put-property split-ts :raw-value nil)
23397 (org-element-put-property
23398 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23400 (defun org-timestamp-translate (timestamp &optional boundary)
23401 "Translate TIMESTAMP object to custom format.
23403 Format string is defined in `org-time-stamp-custom-formats',
23404 which see.
23406 When optional argument BOUNDARY is non-nil, it is either the
23407 symbol `start' or `end'. In this case, only translate the
23408 starting or ending part of TIMESTAMP if it is a date or time
23409 range. Otherwise, translate both parts.
23411 Return timestamp as-is if `org-display-custom-times' is nil or if
23412 it has a `diary' type."
23413 (let ((type (org-element-property :type timestamp)))
23414 (if (or (not org-display-custom-times) (eq type 'diary))
23415 (org-element-interpret-data timestamp)
23416 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23417 org-time-stamp-custom-formats)))
23418 (if (and (not boundary) (memq type '(active-range inactive-range)))
23419 (concat (org-timestamp-format timestamp fmt)
23420 "--"
23421 (org-timestamp-format timestamp fmt t))
23422 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23426 ;;; Other stuff.
23428 (defvar reftex-docstruct-symbol)
23429 (defvar org--rds)
23431 (defun org-reftex-citation ()
23432 "Use reftex-citation to insert a citation into the buffer.
23433 This looks for a line like
23435 #+BIBLIOGRAPHY: foo plain option:-d
23437 and derives from it that foo.bib is the bibliography file relevant
23438 for this document. It then installs the necessary environment for RefTeX
23439 to work in this buffer and calls `reftex-citation' to insert a citation
23440 into the buffer.
23442 Export of such citations to both LaTeX and HTML is handled by the contributed
23443 package ox-bibtex by Taru Karttunen."
23444 (interactive)
23445 (let ((reftex-docstruct-symbol 'org--rds)
23446 org--rds bib)
23447 (org-with-wide-buffer
23448 (let ((case-fold-search t)
23449 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23450 (if (not (save-excursion
23451 (or (re-search-forward re nil t)
23452 (re-search-backward re nil t))))
23453 (user-error "No bibliography defined in file")
23454 (setq bib (concat (match-string 1) ".bib")
23455 org--rds (list (list 'bib bib))))))
23456 (call-interactively 'reftex-citation)))
23458 ;;;; Functions extending outline functionality
23460 (defun org-beginning-of-line (&optional n)
23461 "Go to the beginning of the current visible line.
23463 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23464 tags on the first attempt, and only move to after the tags when
23465 the cursor is already beyond the end of the headline.
23467 With argument N not nil or 1, move forward N - 1 lines first."
23468 (interactive "^p")
23469 (let ((origin (point))
23470 (special (pcase org-special-ctrl-a/e
23471 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23472 deactivate-mark)
23473 ;; First move to a visible line.
23474 (if (bound-and-true-p visual-line-mode)
23475 (beginning-of-visual-line n)
23476 (move-beginning-of-line n)
23477 ;; `move-beginning-of-line' may leave point after invisible
23478 ;; characters if line starts with such of these (e.g., with
23479 ;; a link at column 0). Really move to the beginning of the
23480 ;; current visible line.
23481 (beginning-of-line))
23482 (cond
23483 ;; No special behavior. Point is already at the beginning of
23484 ;; a line, logical or visual.
23485 ((not special))
23486 ;; `beginning-of-visual-line' left point before logical beginning
23487 ;; of line: point is at the beginning of a visual line. Bail
23488 ;; out.
23489 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23490 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23491 ;; At a headline, special position is before the title, but
23492 ;; after any TODO keyword or priority cookie.
23493 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23494 (line-end-position)))
23495 (bol (point)))
23496 (if (eq special 'reversed)
23497 (when (and (= origin bol) (eq last-command this-command))
23498 (goto-char refpos))
23499 (when (or (> origin refpos) (= origin bol))
23500 (goto-char refpos)))))
23501 ((and (looking-at org-list-full-item-re)
23502 (memq (org-element-type (save-match-data (org-element-at-point)))
23503 '(item plain-list)))
23504 ;; Set special position at first white space character after
23505 ;; bullet, and check-box, if any.
23506 (let ((after-bullet
23507 (let ((box (match-end 3)))
23508 (cond ((not box) (match-end 1))
23509 ((eq (char-after box) ?\s) (1+ box))
23510 (t box)))))
23511 (if (eq special 'reversed)
23512 (when (and (= (point) origin) (eq last-command this-command))
23513 (goto-char after-bullet))
23514 (when (or (> origin after-bullet) (= (point) origin))
23515 (goto-char after-bullet)))))
23516 ;; No special context. Point is already at beginning of line.
23517 (t nil))))
23519 (defun org-end-of-line (&optional n)
23520 "Go to the end of the line, but before ellipsis, if any.
23522 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23523 tags on the first attempt, and only move to after the tags when
23524 the cursor is already beyond the end of the headline.
23526 With argument N not nil or 1, move forward N - 1 lines first."
23527 (interactive "^p")
23528 (let ((origin (point))
23529 (special (pcase org-special-ctrl-a/e
23530 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23531 deactivate-mark)
23532 ;; First move to a visible line.
23533 (if (bound-and-true-p visual-line-mode)
23534 (beginning-of-visual-line n)
23535 (move-beginning-of-line n))
23536 (cond
23537 ;; At a headline, with tags.
23538 ((and special
23539 (save-excursion
23540 (beginning-of-line)
23541 (let ((case-fold-search nil))
23542 (looking-at org-complex-heading-regexp)))
23543 (match-end 5))
23544 (let ((tags (save-excursion
23545 (goto-char (match-beginning 5))
23546 (skip-chars-backward " \t")
23547 (point)))
23548 (visual-end (and (bound-and-true-p visual-line-mode)
23549 (save-excursion
23550 (end-of-visual-line)
23551 (point)))))
23552 ;; If `end-of-visual-line' brings us before end of line or
23553 ;; even tags, i.e., the headline spans over multiple visual
23554 ;; lines, move there.
23555 (cond ((and visual-end
23556 (< visual-end tags)
23557 (<= origin visual-end))
23558 (goto-char visual-end))
23559 ((eq special 'reversed)
23560 (if (and (= origin (line-end-position))
23561 (eq this-command last-command))
23562 (goto-char tags)
23563 (end-of-line)))
23565 (if (or (< origin tags) (= origin (line-end-position)))
23566 (goto-char tags)
23567 (end-of-line))))))
23568 ((bound-and-true-p visual-line-mode)
23569 (let ((bol (line-beginning-position)))
23570 (end-of-visual-line)
23571 ;; If `end-of-visual-line' gets us past the ellipsis at the
23572 ;; end of a line, backtrack and use `end-of-line' instead.
23573 (when (/= bol (line-beginning-position))
23574 (goto-char bol)
23575 (end-of-line))))
23576 (t (end-of-line)))))
23578 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23579 (define-key org-mode-map "\C-e" 'org-end-of-line)
23581 (defun org-backward-sentence (&optional _arg)
23582 "Go to beginning of sentence, or beginning of table field.
23583 This will call `backward-sentence' or `org-table-beginning-of-field',
23584 depending on context."
23585 (interactive)
23586 (let* ((element (org-element-at-point))
23587 (contents-begin (org-element-property :contents-begin element))
23588 (table (org-element-lineage element '(table) t)))
23589 (if (and table
23590 (> (point) contents-begin)
23591 (<= (point) (org-element-property :contents-end table)))
23592 (call-interactively #'org-table-beginning-of-field)
23593 (save-restriction
23594 (when (and contents-begin
23595 (< (point-min) contents-begin)
23596 (> (point) contents-begin))
23597 (narrow-to-region contents-begin
23598 (org-element-property :contents-end element)))
23599 (call-interactively #'backward-sentence)))))
23601 (defun org-forward-sentence (&optional _arg)
23602 "Go to end of sentence, or end of table field.
23603 This will call `forward-sentence' or `org-table-end-of-field',
23604 depending on context."
23605 (interactive)
23606 (if (and (org-at-heading-p)
23607 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23608 (save-restriction
23609 (narrow-to-region (line-beginning-position) (line-end-position))
23610 (call-interactively #'forward-sentence))
23611 (let* ((element (org-element-at-point))
23612 (contents-end (org-element-property :contents-end element))
23613 (table (org-element-lineage element '(table) t)))
23614 (if (and table
23615 (>= (point) (org-element-property :contents-begin table))
23616 (< (point) contents-end))
23617 (call-interactively #'org-table-end-of-field)
23618 (save-restriction
23619 (when (and contents-end
23620 (> (point-max) contents-end)
23621 ;; Skip blank lines between elements.
23622 (< (org-element-property :end element)
23623 (save-excursion (goto-char contents-end)
23624 (skip-chars-forward " \r\t\n"))))
23625 (narrow-to-region (org-element-property :contents-begin element)
23626 contents-end))
23627 ;; End of heading is considered as the end of a sentence.
23628 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23629 (call-interactively #'forward-sentence)))))))
23631 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23632 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23634 (defun org-kill-line (&optional _arg)
23635 "Kill line, to tags or end of line."
23636 (interactive)
23637 (cond
23638 ((or (not org-special-ctrl-k)
23639 (bolp)
23640 (not (org-at-heading-p)))
23641 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23642 org-ctrl-k-protect-subtree
23643 (or (eq org-ctrl-k-protect-subtree 'error)
23644 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23645 (user-error "C-k aborted as it would kill a hidden subtree"))
23646 (call-interactively
23647 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23648 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23649 (kill-region (point) (match-beginning 1))
23650 (org-set-tags nil t))
23651 (t (kill-region (point) (point-at-eol)))))
23653 (define-key org-mode-map "\C-k" 'org-kill-line)
23655 (defun org-yank (&optional arg)
23656 "Yank. If the kill is a subtree, treat it specially.
23657 This command will look at the current kill and check if is a single
23658 subtree, or a series of subtrees[1]. If it passes the test, and if the
23659 cursor is at the beginning of a line or after the stars of a currently
23660 empty headline, then the yank is handled specially. How exactly depends
23661 on the value of the following variables.
23663 `org-yank-folded-subtrees'
23664 By default, this variable is non-nil, which results in
23665 subtree(s) being folded after insertion, except if doing so
23666 would swallow text after the yanked text.
23668 `org-yank-adjusted-subtrees'
23669 When non-nil (the default value is nil), the subtree will be
23670 promoted or demoted in order to fit into the local outline tree
23671 structure, which means that the level will be adjusted so that it
23672 becomes the smaller one of the two *visible* surrounding headings.
23674 Any prefix to this command will cause `yank' to be called directly with
23675 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23676 will just
23677 plainly yank the text as it is.
23679 \[1] The test checks if the first non-white line is a heading
23680 and if there are no other headings with fewer stars."
23681 (interactive "P")
23682 (org-yank-generic 'yank arg))
23684 (defun org-yank-generic (command arg)
23685 "Perform some yank-like command.
23687 This function implements the behavior described in the `org-yank'
23688 documentation. However, it has been generalized to work for any
23689 interactive command with similar behavior."
23691 ;; pretend to be command COMMAND
23692 (setq this-command command)
23694 (if arg
23695 (call-interactively command)
23697 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23698 (and (org-kill-is-subtree-p)
23699 (or (bolp)
23700 (and (looking-at "[ \t]*$")
23701 (string-match
23702 "\\`\\*+\\'"
23703 (buffer-substring (point-at-bol) (point)))))))
23704 swallowp)
23705 (cond
23706 ((and subtreep org-yank-folded-subtrees)
23707 (let ((beg (point))
23708 end)
23709 (if (and subtreep org-yank-adjusted-subtrees)
23710 (org-paste-subtree nil nil 'for-yank)
23711 (call-interactively command))
23713 (setq end (point))
23714 (goto-char beg)
23715 (when (and (bolp) subtreep
23716 (not (setq swallowp
23717 (org-yank-folding-would-swallow-text beg end))))
23718 (org-with-limited-levels
23719 (or (looking-at org-outline-regexp)
23720 (re-search-forward org-outline-regexp-bol end t))
23721 (while (and (< (point) end) (looking-at org-outline-regexp))
23722 (outline-hide-subtree)
23723 (org-cycle-show-empty-lines 'folded)
23724 (condition-case nil
23725 (outline-forward-same-level 1)
23726 (error (goto-char end))))))
23727 (when swallowp
23728 (message
23729 "Inserted text not folded because that would swallow text"))
23731 (goto-char end)
23732 (skip-chars-forward " \t\n\r")
23733 (beginning-of-line 1)
23734 (push-mark beg 'nomsg)))
23735 ((and subtreep org-yank-adjusted-subtrees)
23736 (let ((beg (point-at-bol)))
23737 (org-paste-subtree nil nil 'for-yank)
23738 (push-mark beg 'nomsg)))
23740 (call-interactively command))))))
23742 (defun org-yank-folding-would-swallow-text (beg end)
23743 "Would hide-subtree at BEG swallow any text after END?"
23744 (let (level)
23745 (org-with-limited-levels
23746 (save-excursion
23747 (goto-char beg)
23748 (when (or (looking-at org-outline-regexp)
23749 (re-search-forward org-outline-regexp-bol end t))
23750 (setq level (org-outline-level)))
23751 (goto-char end)
23752 (skip-chars-forward " \t\r\n\v\f")
23753 (not (or (eobp)
23754 (and (bolp) (looking-at-p org-outline-regexp)
23755 (<= (org-outline-level) level))))))))
23757 (define-key org-mode-map "\C-y" 'org-yank)
23759 (defun org-truely-invisible-p ()
23760 "Check if point is at a character currently not visible.
23761 This version does not only check the character property, but also
23762 `visible-mode'."
23763 (unless (bound-and-true-p visible-mode)
23764 (org-invisible-p)))
23766 (defun org-invisible-p2 ()
23767 "Check if point is at a character currently not visible.
23769 If the point is at EOL (and not at the beginning of a buffer too),
23770 move it back by one char before doing this check."
23771 (save-excursion
23772 (when (and (eolp) (not (bobp)))
23773 (backward-char 1))
23774 (org-invisible-p)))
23776 (defun org-back-to-heading (&optional invisible-ok)
23777 "Call `outline-back-to-heading', but provide a better error message."
23778 (condition-case nil
23779 (outline-back-to-heading invisible-ok)
23780 (error (error "Before first headline at position %d in buffer %s"
23781 (point) (current-buffer)))))
23783 (defun org-before-first-heading-p ()
23784 "Before first heading?"
23785 (save-excursion
23786 (end-of-line)
23787 (null (re-search-backward org-outline-regexp-bol nil t))))
23789 (defun org-at-heading-p (&optional ignored)
23790 (outline-on-heading-p t))
23792 (defun org-in-commented-heading-p (&optional no-inheritance)
23793 "Non-nil if point is under a commented heading.
23794 This function also checks ancestors of the current headline,
23795 unless optional argument NO-INHERITANCE is non-nil."
23796 (cond
23797 ((org-before-first-heading-p) nil)
23798 ((let ((headline (nth 4 (org-heading-components))))
23799 (and headline
23800 (let ((case-fold-search nil))
23801 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23802 headline)))))
23803 (no-inheritance nil)
23805 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23807 (defun org-at-comment-p nil
23808 "Is cursor in a commented line?"
23809 (save-excursion
23810 (save-match-data
23811 (beginning-of-line)
23812 (looking-at "^[ \t]*# "))))
23814 (defun org-at-drawer-p nil
23815 "Is cursor at a drawer keyword?"
23816 (save-excursion
23817 (move-beginning-of-line 1)
23818 (looking-at org-drawer-regexp)))
23820 (defun org-at-block-p nil
23821 "Is cursor at a block keyword?"
23822 (save-excursion
23823 (move-beginning-of-line 1)
23824 (looking-at org-block-regexp)))
23826 (defun org-point-at-end-of-empty-headline ()
23827 "If point is at the end of an empty headline, return t, else nil.
23828 If the heading only contains a TODO keyword, it is still still considered
23829 empty."
23830 (let ((case-fold-search nil))
23831 (and (looking-at "[ \t]*$")
23832 org-todo-line-regexp
23833 (save-excursion
23834 (beginning-of-line)
23835 (looking-at org-todo-line-regexp)
23836 (string= (match-string 3) "")))))
23838 (defun org-at-heading-or-item-p ()
23839 (or (org-at-heading-p) (org-at-item-p)))
23841 (defun org-at-target-p ()
23842 (or (org-in-regexp org-radio-target-regexp)
23843 (org-in-regexp org-target-regexp)))
23844 ;; Compatibility alias with Org versions < 7.8.03
23845 (defalias 'org-on-target-p 'org-at-target-p)
23847 (defun org-up-heading-all (arg)
23848 "Move to the heading line of which the present line is a subheading.
23849 This function considers both visible and invisible heading lines.
23850 With argument, move up ARG levels."
23851 (outline-up-heading arg t))
23853 (defun org-up-heading-safe ()
23854 "Move to the heading line of which the present line is a subheading.
23855 This version will not throw an error. It will return the level of the
23856 headline found, or nil if no higher level is found.
23858 Also, this function will be a lot faster than `outline-up-heading',
23859 because it relies on stars being the outline starters. This can really
23860 make a significant difference in outlines with very many siblings."
23861 (when (ignore-errors (org-back-to-heading t))
23862 (let ((level-up (1- (funcall outline-level))))
23863 (and (> level-up 0)
23864 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23865 (funcall outline-level)))))
23867 (defun org-first-sibling-p ()
23868 "Is this heading the first child of its parents?"
23869 (interactive)
23870 (let ((re org-outline-regexp-bol)
23871 level l)
23872 (unless (org-at-heading-p t)
23873 (user-error "Not at a heading"))
23874 (setq level (funcall outline-level))
23875 (save-excursion
23876 (if (not (re-search-backward re nil t))
23878 (setq l (funcall outline-level))
23879 (< l level)))))
23881 (defun org-goto-sibling (&optional previous)
23882 "Goto the next sibling, even if it is invisible.
23883 When PREVIOUS is set, go to the previous sibling instead. Returns t
23884 when a sibling was found. When none is found, return nil and don't
23885 move point."
23886 (let ((fun (if previous 're-search-backward 're-search-forward))
23887 (pos (point))
23888 (re org-outline-regexp-bol)
23889 level l)
23890 (when (ignore-errors (org-back-to-heading t))
23891 (setq level (funcall outline-level))
23892 (catch 'exit
23893 (or previous (forward-char 1))
23894 (while (funcall fun re nil t)
23895 (setq l (funcall outline-level))
23896 (when (< l level) (goto-char pos) (throw 'exit nil))
23897 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23898 (goto-char pos)
23899 nil))))
23901 (defun org-show-siblings ()
23902 "Show all siblings of the current headline."
23903 (save-excursion
23904 (while (org-goto-sibling) (org-flag-heading nil)))
23905 (save-excursion
23906 (while (org-goto-sibling 'previous)
23907 (org-flag-heading nil))))
23909 (defun org-goto-first-child ()
23910 "Goto the first child, even if it is invisible.
23911 Return t when a child was found. Otherwise don't move point and
23912 return nil."
23913 (let (level (pos (point)) (re org-outline-regexp-bol))
23914 (when (ignore-errors (org-back-to-heading t))
23915 (setq level (outline-level))
23916 (forward-char 1)
23917 (if (and (re-search-forward re nil t) (> (outline-level) level))
23918 (progn (goto-char (match-beginning 0)) t)
23919 (goto-char pos) nil))))
23921 (defun org-show-hidden-entry ()
23922 "Show an entry where even the heading is hidden."
23923 (save-excursion
23924 (org-show-entry)))
23926 (defun org-flag-heading (flag &optional entry)
23927 "Flag the current heading. FLAG non-nil means make invisible.
23928 When ENTRY is non-nil, show the entire entry."
23929 (save-excursion
23930 (org-back-to-heading t)
23931 ;; Check if we should show the entire entry
23932 (if entry
23933 (progn
23934 (org-show-entry)
23935 (save-excursion
23936 (and (outline-next-heading)
23937 (org-flag-heading nil))))
23938 (outline-flag-region (max (point-min) (1- (point)))
23939 (save-excursion (outline-end-of-heading) (point))
23940 flag))))
23942 (defun org-get-next-sibling ()
23943 "Move to next heading of the same level, and return point.
23944 If there is no such heading, return nil.
23945 This is like outline-next-sibling, but invisible headings are ok."
23946 (let ((level (funcall outline-level)))
23947 (outline-next-heading)
23948 (while (and (not (eobp)) (> (funcall outline-level) level))
23949 (outline-next-heading))
23950 (unless (or (eobp) (< (funcall outline-level) level))
23951 (point))))
23953 (defun org-get-last-sibling ()
23954 "Move to previous heading of the same level, and return point.
23955 If there is no such heading, return nil."
23956 (let ((opoint (point))
23957 (level (funcall outline-level)))
23958 (outline-previous-heading)
23959 (when (and (/= (point) opoint) (outline-on-heading-p t))
23960 (while (and (> (funcall outline-level) level)
23961 (not (bobp)))
23962 (outline-previous-heading))
23963 (unless (< (funcall outline-level) level)
23964 (point)))))
23966 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23967 "Goto to the end of a subtree."
23968 ;; This contains an exact copy of the original function, but it uses
23969 ;; `org-back-to-heading', to make it work also in invisible
23970 ;; trees. And is uses an invisible-ok argument.
23971 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23972 ;; Furthermore, when used inside Org, finding the end of a large subtree
23973 ;; with many children and grandchildren etc, this can be much faster
23974 ;; than the outline version.
23975 (org-back-to-heading invisible-ok)
23976 (let ((first t)
23977 (level (funcall outline-level)))
23978 (if (and (derived-mode-p 'org-mode) (< level 1000))
23979 ;; A true heading (not a plain list item), in Org
23980 ;; This means we can easily find the end by looking
23981 ;; only for the right number of stars. Using a regexp to do
23982 ;; this is so much faster than using a Lisp loop.
23983 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23984 (forward-char 1)
23985 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23986 ;; something else, do it the slow way
23987 (while (and (not (eobp))
23988 (or first (> (funcall outline-level) level)))
23989 (setq first nil)
23990 (outline-next-heading)))
23991 (unless to-heading
23992 (when (memq (preceding-char) '(?\n ?\^M))
23993 ;; Go to end of line before heading
23994 (forward-char -1)
23995 (when (memq (preceding-char) '(?\n ?\^M))
23996 ;; leave blank line before heading
23997 (forward-char -1)))))
23998 (point))
24000 (defun org-end-of-meta-data (&optional full)
24001 "Skip planning line and properties drawer in current entry.
24002 When optional argument FULL is non-nil, also skip empty lines,
24003 clocking lines and regular drawers at the beginning of the
24004 entry."
24005 (org-back-to-heading t)
24006 (forward-line)
24007 (when (looking-at-p org-planning-line-re) (forward-line))
24008 (when (looking-at org-property-drawer-re)
24009 (goto-char (match-end 0))
24010 (forward-line))
24011 (when (and full (not (org-at-heading-p)))
24012 (catch 'exit
24013 (let ((end (save-excursion (outline-next-heading) (point)))
24014 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24015 (while (not (eobp))
24016 (cond ((looking-at-p org-drawer-regexp)
24017 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24018 (forward-line)
24019 (throw 'exit t)))
24020 ((looking-at-p re) (forward-line))
24021 (t (throw 'exit t))))))))
24023 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24024 "Move forward to the ARG'th subheading at same level as this one.
24025 Stop at the first and last subheadings of a superior heading.
24026 Normally this only looks at visible headings, but when INVISIBLE-OK is
24027 non-nil it will also look at invisible ones."
24028 (interactive "p")
24029 (let ((backward? (and arg (< arg 0))))
24030 (if (org-before-first-heading-p)
24031 (if backward? (goto-char (point-min)) (outline-next-heading))
24032 (org-back-to-heading invisible-ok)
24033 (unless backward? (end-of-line)) ;do not match current headline
24034 (let ((level (- (match-end 0) (match-beginning 0) 1))
24035 (f (if backward? #'re-search-backward #'re-search-forward))
24036 (count (if arg (abs arg) 1))
24037 (result (point)))
24038 (while (and (> count 0)
24039 (funcall f org-outline-regexp-bol nil 'move))
24040 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24041 (cond ((< l level) (setq count 0))
24042 ((and (= l level)
24043 (or invisible-ok
24044 (not (org-invisible-p
24045 (line-beginning-position)))))
24046 (cl-decf count)
24047 (when (= l level) (setq result (point)))))))
24048 (goto-char result))
24049 (beginning-of-line))))
24051 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24052 "Move backward to the ARG'th subheading at same level as this one.
24053 Stop at the first and last subheadings of a superior heading."
24054 (interactive "p")
24055 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24057 (defun org-next-visible-heading (arg)
24058 "Move to the next visible heading.
24060 This function wraps `outline-next-visible-heading' with
24061 `org-with-limited-levels' in order to skip over inline tasks and
24062 respect customization of `org-odd-levels-only'."
24063 (interactive "p")
24064 (org-with-limited-levels
24065 (outline-next-visible-heading arg)))
24067 (defun org-previous-visible-heading (arg)
24068 "Move to the previous visible heading.
24070 This function wraps `outline-previous-visible-heading' with
24071 `org-with-limited-levels' in order to skip over inline tasks and
24072 respect customization of `org-odd-levels-only'."
24073 (interactive "p")
24074 (org-with-limited-levels
24075 (outline-previous-visible-heading arg)))
24077 (defun org-next-block (arg &optional backward block-regexp)
24078 "Jump to the next block.
24080 With a prefix argument ARG, jump forward ARG many blocks.
24082 When BACKWARD is non-nil, jump to the previous block.
24084 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24085 Match data is set according to this regexp when the function
24086 returns.
24088 Return point at beginning of the opening line of found block.
24089 Throw an error if no block is found."
24090 (interactive "p")
24091 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24092 (case-fold-search t)
24093 (search-fn (if backward #'re-search-backward #'re-search-forward))
24094 (count (or arg 1))
24095 (origin (point))
24096 last-element)
24097 (if backward (beginning-of-line) (end-of-line))
24098 (while (and (> count 0) (funcall search-fn re nil t))
24099 (let ((element (save-excursion
24100 (goto-char (match-beginning 0))
24101 (save-match-data (org-element-at-point)))))
24102 (when (and (memq (org-element-type element)
24103 '(center-block comment-block dynamic-block
24104 example-block export-block quote-block
24105 special-block src-block verse-block))
24106 (<= (match-beginning 0)
24107 (org-element-property :post-affiliated element)))
24108 (setq last-element element)
24109 (cl-decf count))))
24110 (if (= count 0)
24111 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24112 (save-match-data (org-show-context)))
24113 (goto-char origin)
24114 (user-error "No %s code blocks" (if backward "previous" "further")))))
24116 (defun org-previous-block (arg &optional block-regexp)
24117 "Jump to the previous block.
24118 With a prefix argument ARG, jump backward ARG many source blocks.
24119 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24120 (interactive "p")
24121 (org-next-block arg t block-regexp))
24123 (defun org-forward-paragraph ()
24124 "Move forward to beginning of next paragraph or equivalent.
24126 The function moves point to the beginning of the next visible
24127 structural element, which can be a paragraph, a table, a list
24128 item, etc. It also provides some special moves for convenience:
24130 - On an affiliated keyword, jump to the beginning of the
24131 relative element.
24132 - On an item or a footnote definition, move to the second
24133 element inside, if any.
24134 - On a table or a property drawer, jump after it.
24135 - On a verse or source block, stop after blank lines."
24136 (interactive)
24137 (unless (eobp)
24138 (let* ((deactivate-mark nil)
24139 (element (org-element-at-point))
24140 (type (org-element-type element))
24141 (post-affiliated (org-element-property :post-affiliated element))
24142 (contents-begin (org-element-property :contents-begin element))
24143 (contents-end (org-element-property :contents-end element))
24144 (end (let ((end (org-element-property :end element)) (parent element))
24145 (while (and (setq parent (org-element-property :parent parent))
24146 (= (org-element-property :contents-end parent) end))
24147 (setq end (org-element-property :end parent)))
24148 end)))
24149 (cond ((not element)
24150 (skip-chars-forward " \r\t\n")
24151 (or (eobp) (beginning-of-line)))
24152 ;; On affiliated keywords, move to element's beginning.
24153 ((< (point) post-affiliated)
24154 (goto-char post-affiliated))
24155 ;; At a table row, move to the end of the table. Similarly,
24156 ;; at a node property, move to the end of the property
24157 ;; drawer.
24158 ((memq type '(node-property table-row))
24159 (goto-char (org-element-property
24160 :end (org-element-property :parent element))))
24161 ((memq type '(property-drawer table)) (goto-char end))
24162 ;; Consider blank lines as separators in verse and source
24163 ;; blocks to ease editing.
24164 ((memq type '(src-block verse-block))
24165 (when (eq type 'src-block)
24166 (setq contents-end
24167 (save-excursion (goto-char end)
24168 (skip-chars-backward " \r\t\n")
24169 (line-beginning-position))))
24170 (beginning-of-line)
24171 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24172 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24173 (goto-char end)
24174 (skip-chars-forward " \r\t\n")
24175 (if (= (point) contents-end) (goto-char end)
24176 (beginning-of-line))))
24177 ;; With no contents, just skip element.
24178 ((not contents-begin) (goto-char end))
24179 ;; If contents are invisible, skip the element altogether.
24180 ((org-invisible-p (line-end-position))
24181 (cl-case type
24182 (headline
24183 (org-with-limited-levels (outline-next-visible-heading 1)))
24184 ;; At a plain list, make sure we move to the next item
24185 ;; instead of skipping the whole list.
24186 (plain-list (forward-char)
24187 (org-forward-paragraph))
24188 (otherwise (goto-char end))))
24189 ((>= (point) contents-end) (goto-char end))
24190 ((>= (point) contents-begin)
24191 ;; This can only happen on paragraphs and plain lists.
24192 (cl-case type
24193 (paragraph (goto-char end))
24194 ;; At a plain list, try to move to second element in
24195 ;; first item, if possible.
24196 (plain-list (end-of-line)
24197 (org-forward-paragraph))))
24198 ;; When contents start on the middle of a line (e.g. in
24199 ;; items and footnote definitions), try to reach first
24200 ;; element starting after current line.
24201 ((> (line-end-position) contents-begin)
24202 (end-of-line)
24203 (org-forward-paragraph))
24204 (t (goto-char contents-begin))))))
24206 (defun org-backward-paragraph ()
24207 "Move backward to start of previous paragraph or equivalent.
24209 The function moves point to the beginning of the current
24210 structural element, which can be a paragraph, a table, a list
24211 item, etc., or to the beginning of the previous visible one if
24212 point is already there. It also provides some special moves for
24213 convenience:
24215 - On an affiliated keyword, jump to the first one.
24216 - On a table or a property drawer, move to its beginning.
24217 - On comment, example, export, src and verse blocks, stop
24218 before blank lines."
24219 (interactive)
24220 (unless (bobp)
24221 (let* ((deactivate-mark nil)
24222 (element (org-element-at-point))
24223 (type (org-element-type element))
24224 (contents-end (org-element-property :contents-end element))
24225 (post-affiliated (org-element-property :post-affiliated element))
24226 (begin (org-element-property :begin element))
24227 (special? ;blocks handled specially
24228 (memq type '(comment-block example-block export-block src-block
24229 verse-block)))
24230 (contents-begin
24231 (if special?
24232 ;; These types have no proper contents. Fake line
24233 ;; below the block opening line as contents beginning.
24234 (save-excursion (goto-char begin) (line-beginning-position 2))
24235 (org-element-property :contents-begin element))))
24236 (cond
24237 ((not element) (goto-char (point-min)))
24238 ((= (point) begin)
24239 (backward-char)
24240 (org-backward-paragraph))
24241 ((<= (point) post-affiliated) (goto-char begin))
24242 ;; Special behavior: on a table or a property drawer, move to
24243 ;; its beginning.
24244 ((memq type '(node-property table-row))
24245 (goto-char (org-element-property
24246 :post-affiliated (org-element-property :parent element))))
24247 (special?
24248 (if (<= (point) contents-begin) (goto-char post-affiliated)
24249 ;; Inside a verse block, see blank lines as paragraph
24250 ;; separators.
24251 (let ((origin (point)))
24252 (skip-chars-backward " \r\t\n" contents-begin)
24253 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24254 (skip-chars-forward " \r\t\n" origin)
24255 (if (= (point) origin) (goto-char contents-begin)
24256 (beginning-of-line))))))
24257 ((eq type 'paragraph) (goto-char contents-begin)
24258 ;; When at first paragraph in an item or a footnote definition,
24259 ;; move directly to beginning of line.
24260 (let ((parent-contents
24261 (org-element-property
24262 :contents-begin (org-element-property :parent element))))
24263 (when (and parent-contents (= parent-contents contents-begin))
24264 (beginning-of-line))))
24265 ;; At the end of a greater element, move to the beginning of
24266 ;; the last element within.
24267 ((and contents-end (>= (point) contents-end))
24268 (goto-char (1- contents-end))
24269 (org-backward-paragraph))
24270 (t (goto-char (or post-affiliated begin))))
24271 ;; Ensure we never leave point invisible.
24272 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24274 (defun org-forward-element ()
24275 "Move forward by one element.
24276 Move to the next element at the same level, when possible."
24277 (interactive)
24278 (cond ((eobp) (user-error "Cannot move further down"))
24279 ((org-with-limited-levels (org-at-heading-p))
24280 (let ((origin (point)))
24281 (goto-char (org-end-of-subtree nil t))
24282 (unless (org-with-limited-levels (org-at-heading-p))
24283 (goto-char origin)
24284 (user-error "Cannot move further down"))))
24286 (let* ((elem (org-element-at-point))
24287 (end (org-element-property :end elem))
24288 (parent (org-element-property :parent elem)))
24289 (cond ((and parent (= (org-element-property :contents-end parent) end))
24290 (goto-char (org-element-property :end parent)))
24291 ((integer-or-marker-p end) (goto-char end))
24292 (t (message "No element at point")))))))
24294 (defun org-backward-element ()
24295 "Move backward by one element.
24296 Move to the previous element at the same level, when possible."
24297 (interactive)
24298 (cond ((bobp) (user-error "Cannot move further up"))
24299 ((org-with-limited-levels (org-at-heading-p))
24300 ;; At a headline, move to the previous one, if any, or stay
24301 ;; here.
24302 (let ((origin (point)))
24303 (org-with-limited-levels (org-backward-heading-same-level 1))
24304 ;; When current headline has no sibling above, move to its
24305 ;; parent.
24306 (when (= (point) origin)
24307 (or (org-with-limited-levels (org-up-heading-safe))
24308 (progn (goto-char origin)
24309 (user-error "Cannot move further up"))))))
24311 (let* ((elem (org-element-at-point))
24312 (beg (org-element-property :begin elem)))
24313 (cond
24314 ;; Move to beginning of current element if point isn't
24315 ;; there already.
24316 ((null beg) (message "No element at point"))
24317 ((/= (point) beg) (goto-char beg))
24318 (t (goto-char beg)
24319 (skip-chars-backward " \r\t\n")
24320 (unless (bobp)
24321 (let ((prev (org-element-at-point)))
24322 (goto-char (org-element-property :begin prev))
24323 (while (and (setq prev (org-element-property :parent prev))
24324 (<= (org-element-property :end prev) beg))
24325 (goto-char (org-element-property :begin prev)))))))))))
24327 (defun org-up-element ()
24328 "Move to upper element."
24329 (interactive)
24330 (if (org-with-limited-levels (org-at-heading-p))
24331 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24332 (let* ((elem (org-element-at-point))
24333 (parent (org-element-property :parent elem)))
24334 (if parent (goto-char (org-element-property :begin parent))
24335 (if (org-with-limited-levels (org-before-first-heading-p))
24336 (user-error "No surrounding element")
24337 (org-with-limited-levels (org-back-to-heading)))))))
24339 (defun org-down-element ()
24340 "Move to inner element."
24341 (interactive)
24342 (let ((element (org-element-at-point)))
24343 (cond
24344 ((memq (org-element-type element) '(plain-list table))
24345 (goto-char (org-element-property :contents-begin element))
24346 (forward-char))
24347 ((memq (org-element-type element) org-element-greater-elements)
24348 ;; If contents are hidden, first disclose them.
24349 (when (org-invisible-p (line-end-position)) (org-cycle))
24350 (goto-char (or (org-element-property :contents-begin element)
24351 (user-error "No content for this element"))))
24352 (t (user-error "No inner element")))))
24354 (defun org-drag-element-backward ()
24355 "Move backward element at point."
24356 (interactive)
24357 (let ((elem (or (org-element-at-point)
24358 (user-error "No element at point"))))
24359 (if (eq (org-element-type elem) 'headline)
24360 ;; Preserve point when moving a whole tree, even if point was
24361 ;; on blank lines below the headline.
24362 (let ((offset (skip-chars-backward " \t\n")))
24363 (unwind-protect (org-move-subtree-up)
24364 (forward-char (- offset))))
24365 (let ((prev-elem
24366 (save-excursion
24367 (goto-char (org-element-property :begin elem))
24368 (skip-chars-backward " \r\t\n")
24369 (unless (bobp)
24370 (let* ((beg (org-element-property :begin elem))
24371 (prev (org-element-at-point))
24372 (up prev))
24373 (while (and (setq up (org-element-property :parent up))
24374 (<= (org-element-property :end up) beg))
24375 (setq prev up))
24376 prev)))))
24377 ;; Error out if no previous element or previous element is
24378 ;; a parent of the current one.
24379 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24380 (user-error "Cannot drag element backward")
24381 (let ((pos (point)))
24382 (org-element-swap-A-B prev-elem elem)
24383 (goto-char (+ (org-element-property :begin prev-elem)
24384 (- pos (org-element-property :begin elem))))))))))
24386 (defun org-drag-element-forward ()
24387 "Move forward element at point."
24388 (interactive)
24389 (let* ((pos (point))
24390 (elem (or (org-element-at-point)
24391 (user-error "No element at point"))))
24392 (when (= (point-max) (org-element-property :end elem))
24393 (user-error "Cannot drag element forward"))
24394 (goto-char (org-element-property :end elem))
24395 (let ((next-elem (org-element-at-point)))
24396 (when (or (org-element-nested-p elem next-elem)
24397 (and (eq (org-element-type next-elem) 'headline)
24398 (not (eq (org-element-type elem) 'headline))))
24399 (goto-char pos)
24400 (user-error "Cannot drag element forward"))
24401 ;; Compute new position of point: it's shifted by NEXT-ELEM
24402 ;; body's length (without final blanks) and by the length of
24403 ;; blanks between ELEM and NEXT-ELEM.
24404 (let ((size-next (- (save-excursion
24405 (goto-char (org-element-property :end next-elem))
24406 (skip-chars-backward " \r\t\n")
24407 (forward-line)
24408 ;; Small correction if buffer doesn't end
24409 ;; with a newline character.
24410 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24411 (org-element-property :begin next-elem)))
24412 (size-blank (- (org-element-property :end elem)
24413 (save-excursion
24414 (goto-char (org-element-property :end elem))
24415 (skip-chars-backward " \r\t\n")
24416 (forward-line)
24417 (point)))))
24418 (org-element-swap-A-B elem next-elem)
24419 (goto-char (+ pos size-next size-blank))))))
24421 (defun org-drag-line-forward (arg)
24422 "Drag the line at point ARG lines forward."
24423 (interactive "p")
24424 (dotimes (_ (abs arg))
24425 (let ((c (current-column)))
24426 (if (< 0 arg)
24427 (progn
24428 (beginning-of-line 2)
24429 (transpose-lines 1)
24430 (beginning-of-line 0))
24431 (transpose-lines 1)
24432 (beginning-of-line -1))
24433 (org-move-to-column c))))
24435 (defun org-drag-line-backward (arg)
24436 "Drag the line at point ARG lines backward."
24437 (interactive "p")
24438 (org-drag-line-forward (- arg)))
24440 (defun org-mark-element ()
24441 "Put point at beginning of this element, mark at end.
24443 Interactively, if this command is repeated or (in Transient Mark
24444 mode) if the mark is active, it marks the next element after the
24445 ones already marked."
24446 (interactive)
24447 (let (deactivate-mark)
24448 (if (and (called-interactively-p 'any)
24449 (or (and (eq last-command this-command) (mark t))
24450 (and transient-mark-mode mark-active)))
24451 (set-mark
24452 (save-excursion
24453 (goto-char (mark))
24454 (goto-char (org-element-property :end (org-element-at-point)))))
24455 (let ((element (org-element-at-point)))
24456 (end-of-line)
24457 (push-mark (org-element-property :end element) t t)
24458 (goto-char (org-element-property :begin element))))))
24460 (defun org-narrow-to-element ()
24461 "Narrow buffer to current element."
24462 (interactive)
24463 (let ((elem (org-element-at-point)))
24464 (cond
24465 ((eq (car elem) 'headline)
24466 (narrow-to-region
24467 (org-element-property :begin elem)
24468 (org-element-property :end elem)))
24469 ((memq (car elem) org-element-greater-elements)
24470 (narrow-to-region
24471 (org-element-property :contents-begin elem)
24472 (org-element-property :contents-end elem)))
24474 (narrow-to-region
24475 (org-element-property :begin elem)
24476 (org-element-property :end elem))))))
24478 (defun org-transpose-element ()
24479 "Transpose current and previous elements, keeping blank lines between.
24480 Point is moved after both elements."
24481 (interactive)
24482 (org-skip-whitespace)
24483 (let ((end (org-element-property :end (org-element-at-point))))
24484 (org-drag-element-backward)
24485 (goto-char end)))
24487 (defun org-unindent-buffer ()
24488 "Un-indent the visible part of the buffer.
24489 Relative indentation (between items, inside blocks, etc.) isn't
24490 modified."
24491 (interactive)
24492 (unless (eq major-mode 'org-mode)
24493 (user-error "Cannot un-indent a buffer not in Org mode"))
24494 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24495 (unindent-tree
24496 (lambda (contents)
24497 (dolist (element (reverse contents))
24498 (if (memq (org-element-type element) '(headline section))
24499 (funcall unindent-tree (org-element-contents element))
24500 (save-excursion
24501 (save-restriction
24502 (narrow-to-region
24503 (org-element-property :begin element)
24504 (org-element-property :end element))
24505 (org-do-remove-indentation))))))))
24506 (funcall unindent-tree (org-element-contents parse-tree))))
24508 (defun org-show-children (&optional level)
24509 "Show all direct subheadings of this heading.
24510 Prefix arg LEVEL is how many levels below the current level
24511 should be shown. Default is enough to cause the following
24512 heading to appear."
24513 (interactive "p")
24514 ;; If `orgstruct-mode' is active, use the slower version.
24515 (if orgstruct-mode (call-interactively #'outline-show-children)
24516 (save-excursion
24517 (org-back-to-heading t)
24518 (let* ((current-level (funcall outline-level))
24519 (max-level (org-get-valid-level
24520 current-level
24521 (if level (prefix-numeric-value level) 1)))
24522 (end (save-excursion (org-end-of-subtree t t)))
24523 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24524 (past-first-child nil)
24525 ;; Make sure to skip inlinetasks.
24526 (re (format regexp-fmt
24527 current-level
24528 (cond
24529 ((not (featurep 'org-inlinetask)) "")
24530 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24532 (t (1- org-inlinetask-min-level))))))
24533 ;; Display parent heading.
24534 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24535 (forward-line)
24536 ;; Display children. First child may be deeper than expected
24537 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24538 ;; MAX-LEVEL accordingly.
24539 (while (re-search-forward re end t)
24540 (unless past-first-child
24541 (setq re (format regexp-fmt
24542 current-level
24543 (max (funcall outline-level) max-level)))
24544 (setq past-first-child t))
24545 (outline-flag-region
24546 (line-end-position 0) (line-end-position) nil))))))
24548 (defun org-show-subtree ()
24549 "Show everything after this heading at deeper levels."
24550 (interactive)
24551 (outline-flag-region
24552 (point)
24553 (save-excursion
24554 (org-end-of-subtree t t))
24555 nil))
24557 (defun org-show-entry ()
24558 "Show the body directly following this heading.
24559 Show the heading too, if it is currently invisible."
24560 (interactive)
24561 (save-excursion
24562 (ignore-errors
24563 (org-back-to-heading t)
24564 (outline-flag-region
24565 (max (point-min) (1- (point)))
24566 (save-excursion
24567 (if (re-search-forward
24568 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24569 (match-beginning 1)
24570 (point-max)))
24571 nil)
24572 (org-cycle-hide-drawers 'children))))
24574 (defun org-make-options-regexp (kwds &optional extra)
24575 "Make a regular expression for keyword lines.
24576 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24577 when non-nil, is a regexp matching keywords names."
24578 (concat "^[ \t]*#\\+\\("
24579 (regexp-opt kwds)
24580 (and extra (concat (and kwds "\\|") extra))
24581 "\\):[ \t]*\\(.*\\)"))
24583 ;;;; Integration with and fixes for other packages
24585 ;;; Imenu support
24587 (defvar-local org-imenu-markers nil
24588 "All markers currently used by Imenu.")
24590 (defun org-imenu-new-marker (&optional pos)
24591 "Return a new marker for use by Imenu, and remember the marker."
24592 (let ((m (make-marker)))
24593 (move-marker m (or pos (point)))
24594 (push m org-imenu-markers)
24597 (defun org-imenu-get-tree ()
24598 "Produce the index for Imenu."
24599 (dolist (x org-imenu-markers) (move-marker x nil))
24600 (setq org-imenu-markers nil)
24601 (let* ((case-fold-search nil)
24602 (n org-imenu-depth)
24603 (re (concat "^" (org-get-limited-outline-regexp)))
24604 (subs (make-vector (1+ n) nil))
24605 (last-level 0)
24606 m level head0 head)
24607 (org-with-wide-buffer
24608 (goto-char (point-max))
24609 (while (re-search-backward re nil t)
24610 (setq level (org-reduced-level (funcall outline-level)))
24611 (when (and (<= level n)
24612 (looking-at org-complex-heading-regexp)
24613 (setq head0 (match-string-no-properties 4)))
24614 (setq head (org-link-display-format head0)
24615 m (org-imenu-new-marker))
24616 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24617 (if (>= level last-level)
24618 (push (cons head m) (aref subs level))
24619 (push (cons head (aref subs (1+ level))) (aref subs level))
24620 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24621 (setq last-level level))))
24622 (aref subs 1)))
24624 (eval-after-load "imenu"
24625 '(progn
24626 (add-hook 'imenu-after-jump-hook
24627 (lambda ()
24628 (when (derived-mode-p 'org-mode)
24629 (org-show-context 'org-goto))))))
24631 (defun org-link-display-format (s)
24632 "Replace links in string S with their description.
24633 If there is no description, use the link target."
24634 (save-match-data
24635 (replace-regexp-in-string
24636 org-bracket-link-analytic-regexp
24637 (lambda (m)
24638 (if (match-end 5) (match-string 5 m)
24639 (concat (match-string 1 m) (match-string 3 m))))
24640 s nil t)))
24642 (defun org-toggle-link-display ()
24643 "Toggle the literal or descriptive display of links."
24644 (interactive)
24645 (if org-descriptive-links
24646 (progn (org-remove-from-invisibility-spec '(org-link))
24647 (org-restart-font-lock)
24648 (setq org-descriptive-links nil))
24649 (progn (add-to-invisibility-spec '(org-link))
24650 (org-restart-font-lock)
24651 (setq org-descriptive-links t))))
24653 ;; Speedbar support
24655 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24656 "Overlay marking the agenda restriction line in speedbar.")
24657 (overlay-put org-speedbar-restriction-lock-overlay
24658 'face 'org-agenda-restriction-lock)
24659 (overlay-put org-speedbar-restriction-lock-overlay
24660 'help-echo "Agendas are currently limited to this item.")
24661 (delete-overlay org-speedbar-restriction-lock-overlay)
24663 (defun org-speedbar-set-agenda-restriction ()
24664 "Restrict future agenda commands to the location at point in speedbar.
24665 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24666 (interactive)
24667 (require 'org-agenda)
24668 (let (p m tp np dir txt)
24669 (cond
24670 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24671 'org-imenu t))
24672 (setq m (get-text-property p 'org-imenu-marker))
24673 (with-current-buffer (marker-buffer m)
24674 (goto-char m)
24675 (org-agenda-set-restriction-lock 'subtree)))
24676 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24677 'speedbar-function 'speedbar-find-file))
24678 (setq tp (previous-single-property-change
24679 (1+ p) 'speedbar-function)
24680 np (next-single-property-change
24681 tp 'speedbar-function)
24682 dir (speedbar-line-directory)
24683 txt (buffer-substring-no-properties (or tp (point-min))
24684 (or np (point-max))))
24685 (with-current-buffer (find-file-noselect
24686 (let ((default-directory dir))
24687 (expand-file-name txt)))
24688 (unless (derived-mode-p 'org-mode)
24689 (user-error "Cannot restrict to non-Org mode file"))
24690 (org-agenda-set-restriction-lock 'file)))
24691 (t (user-error "Don't know how to restrict Org mode agenda")))
24692 (move-overlay org-speedbar-restriction-lock-overlay
24693 (point-at-bol) (point-at-eol))
24694 (setq current-prefix-arg nil)
24695 (org-agenda-maybe-redo)))
24697 (defvar speedbar-file-key-map)
24698 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24699 (eval-after-load "speedbar"
24700 '(progn
24701 (speedbar-add-supported-extension ".org")
24702 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24703 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24704 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24705 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24706 (add-hook 'speedbar-visiting-tag-hook
24707 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24709 ;;; Fixes and Hacks for problems with other packages
24711 (defun org--flyspell-object-check-p (element)
24712 "Non-nil when Flyspell can check object at point.
24713 ELEMENT is the element at point."
24714 (let ((object (save-excursion
24715 (when (looking-at-p "\\>") (backward-char))
24716 (org-element-context element))))
24717 (cl-case (org-element-type object)
24718 ;; Prevent checks in links due to keybinding conflict with
24719 ;; Flyspell.
24720 ((code entity export-snippet inline-babel-call
24721 inline-src-block line-break latex-fragment link macro
24722 statistics-cookie target timestamp verbatim)
24723 nil)
24724 (footnote-reference
24725 ;; Only in inline footnotes, within the definition.
24726 (and (eq (org-element-property :type object) 'inline)
24727 (< (save-excursion
24728 (goto-char (org-element-property :begin object))
24729 (search-forward ":" nil t 2))
24730 (point))))
24731 (otherwise t))))
24733 (defun org-mode-flyspell-verify ()
24734 "Function used for `flyspell-generic-check-word-predicate'."
24735 (if (org-at-heading-p)
24736 ;; At a headline or an inlinetask, check title only. This is
24737 ;; faster than relying on `org-element-at-point'.
24738 (and (save-excursion (beginning-of-line)
24739 (and (let ((case-fold-search t))
24740 (not (looking-at-p "\\*+ END[ \t]*$")))
24741 (let ((case-fold-search nil))
24742 (looking-at org-complex-heading-regexp))))
24743 (match-beginning 4)
24744 (>= (point) (match-beginning 4))
24745 (or (not (match-beginning 5))
24746 (< (point) (match-beginning 5))))
24747 (let* ((element (org-element-at-point))
24748 (post-affiliated (org-element-property :post-affiliated element)))
24749 (cond
24750 ;; Ignore checks in all affiliated keywords but captions.
24751 ((< (point) post-affiliated)
24752 (and (save-excursion
24753 (beginning-of-line)
24754 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24755 (> (point) (match-end 0))
24756 (org--flyspell-object-check-p element)))
24757 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24758 ((let ((log (org-log-into-drawer)))
24759 (and log
24760 (let ((drawer (org-element-lineage element '(drawer))))
24761 (and drawer
24762 (eq (compare-strings
24763 log nil nil
24764 (org-element-property :drawer-name drawer) nil nil t)
24765 t)))))
24766 nil)
24768 (cl-case (org-element-type element)
24769 ((comment quote-section) t)
24770 (comment-block
24771 ;; Allow checks between block markers, not on them.
24772 (and (> (line-beginning-position) post-affiliated)
24773 (save-excursion
24774 (end-of-line)
24775 (skip-chars-forward " \r\t\n")
24776 (< (point) (org-element-property :end element)))))
24777 ;; Arbitrary list of keywords where checks are meaningful.
24778 ;; Make sure point is on the value part of the element.
24779 (keyword
24780 (and (member (org-element-property :key element)
24781 '("DESCRIPTION" "TITLE"))
24782 (save-excursion
24783 (search-backward ":" (line-beginning-position) t))))
24784 ;; Check is globally allowed in paragraphs verse blocks and
24785 ;; table rows (after affiliated keywords) but some objects
24786 ;; must not be affected.
24787 ((paragraph table-row verse-block)
24788 (let ((cbeg (org-element-property :contents-begin element))
24789 (cend (org-element-property :contents-end element)))
24790 (and cbeg (>= (point) cbeg) (< (point) cend)
24791 (org--flyspell-object-check-p element))))))))))
24792 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24794 (defun org-remove-flyspell-overlays-in (beg end)
24795 "Remove flyspell overlays in region."
24796 (and (bound-and-true-p flyspell-mode)
24797 (fboundp 'flyspell-delete-region-overlays)
24798 (flyspell-delete-region-overlays beg end)))
24800 (defvar flyspell-delayed-commands)
24801 (eval-after-load "flyspell"
24802 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24804 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24805 (eval-after-load "bookmark"
24806 '(if (boundp 'bookmark-after-jump-hook)
24807 ;; We can use the hook
24808 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24809 ;; Hook not available, use advice
24810 (defadvice bookmark-jump (after org-make-visible activate)
24811 "Make the position visible."
24812 (org-bookmark-jump-unhide))))
24814 ;; Make sure saveplace shows the location if it was hidden
24815 (eval-after-load "saveplace"
24816 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24817 "Make the position visible."
24818 (org-bookmark-jump-unhide)))
24820 ;; Make sure ecb shows the location if it was hidden
24821 (eval-after-load "ecb"
24822 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24823 "Make hierarchy visible when jumping into location from ECB tree buffer."
24824 (when (derived-mode-p 'org-mode)
24825 (org-show-context))))
24827 (defun org-bookmark-jump-unhide ()
24828 "Unhide the current position, to show the bookmark location."
24829 (and (derived-mode-p 'org-mode)
24830 (or (org-invisible-p)
24831 (save-excursion (goto-char (max (point-min) (1- (point))))
24832 (org-invisible-p)))
24833 (org-show-context 'bookmark-jump)))
24835 (defun org-mark-jump-unhide ()
24836 "Make the point visible with `org-show-context' after jumping to the mark."
24837 (when (and (derived-mode-p 'org-mode)
24838 (org-invisible-p))
24839 (org-show-context 'mark-goto)))
24841 (eval-after-load "simple"
24842 '(defadvice pop-to-mark-command (after org-make-visible activate)
24843 "Make the point visible with `org-show-context'."
24844 (org-mark-jump-unhide)))
24846 (eval-after-load "simple"
24847 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24848 "Make the point visible with `org-show-context'."
24849 (org-mark-jump-unhide)))
24851 (eval-after-load "simple"
24852 '(defadvice pop-global-mark (after org-make-visible activate)
24853 "Make the point visible with `org-show-context'."
24854 (org-mark-jump-unhide)))
24856 ;; Make session.el ignore our circular variable
24857 (defvar session-globals-exclude)
24858 (eval-after-load "session"
24859 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24861 ;;;; Finish up
24863 (provide 'org)
24865 (run-hooks 'org-load-hook)
24867 ;;; org.el ends here